#!/bin/tcsh -f
# fsr-mergexopts - sources
if(-e $FREESURFER_HOME/sources.csh) then
  source $FREESURFER_HOME/sources.csh
endif

set VERSION = '$Id$';
set scriptname = `basename $0`

set outxopts = ();
set xoptslist = ();
set ForceUpdate = 0

set tmpdir = ();
set cleanup = 1;
set LF = ();

set inputargs = ($argv);
set PrintHelp = 0;
if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;
  goto usage_exit;
endif
set n = `echo $argv | grep -e -version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif
goto parse_args;
parse_args_return:
goto check_params;
check_params_return:

set StartTime = `date`;
set tSecStart = `date '+%s'`;
set year  = `date +%Y`
set month = `date +%m`
set day   = `date +%d`
set hour   = `date +%H`
set min    = `date +%M`

set outdir = `dirname $outxopts`
mkdir -p $outdir/log
pushd $outdir > /dev/null
set outdir = `pwd`;
popd > /dev/null

if($#tmpdir == 0) then
  if(-dw /scratch)   set tmpdir = /scratch/tmpdir.fsr-mergexopts.$$
  if(! -dw /scratch) set tmpdir = $outdir/tmpdir.fsr-mergexopts.$$
endif
#mkdir -p $tmpdir

# Set up log file
set LF = /dev/null
if($#LF == 0) set LF = $outdir/log/fsr-mergexopts.Y$year.M$month.D$day.H$hour.M$min.log
if($LF != /dev/null) rm -f $LF
echo "Log file for fsr-mergexopts" >> $LF
date  | tee -a $LF
echo "" | tee -a $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" | tee -a $LF
echo "cd `pwd`"  | tee -a $LF
echo $0 $inputargs | tee -a $LF
ls -l $0  | tee -a $LF
echo "" | tee -a $LF
cat $FREESURFER_HOME/build-stamp.txt | tee -a $LF
echo $VERSION | tee -a $LF
uname -a  | tee -a $LF
echo "pid $$" | tee -a $LF
if($?PBS_JOBID) then
  echo "pbsjob $PBS_JOBID"  >> $LF
endif
if($?SLURM_JOB_ID) then
  echo SLURM_JOB_ID $SLURM_JOB_ID >> $LF
endif

#========================================================

rm -f $outxopts

# Get a unique list of commands across all xopts
set cmdlist = (`cat $xoptslist | grep -v \# | awk '{print $1}' | sort | uniq`)

# If recon-all exists as a command, do that first
foreach cmd ($cmdlist)
  if($cmd != recon-all) continue
  set opts = ()
  # Go through each xopts file and append the options in the order 
  # that the xopt files were given on the command line
  foreach xopts ($xoptslist)
    set tmp = `cat $xopts | grep recon-all | awk '{print $0}'`
    if($#tmp < 2) continue
    set opts = ($opts $tmp[2-$#tmp])
  end
  echo $cmd $opts | tee -a $outxopts
end

# Now do the non-recon-all commands
foreach cmd ($cmdlist)
  if($cmd == recon-all) continue
  set opts = ()
  # Go through each xopts file and append the options in the order 
  # that the xopt files were given on the command line
  foreach xopts ($xoptslist)
    set tmp = `cat $xopts | grep recon-all | awk '{print $0}'`
    if($#tmp < 2) continue
    set opts = ($opts $tmp[2-$#tmp])
  end
  echo $cmd $opts | tee -a $outxopts
end

# One final check. If the individual xopts check out ok, then this one
# should too.
fsr-checkxopts $outxopts
if($status) then
  cat $outxopts
  rm -f $outxopts
  exit 1
endif


#========================================================

# Cleanup
# if($cleanup) rm -rf $tmpdir

# Done
echo " " |& tee -a $LF
set tSecEnd = `date '+%s'`;
@ tSecRun = $tSecEnd - $tSecStart;
set tRunMin = `echo $tSecRun/60|bc -l`
set tRunMin = `printf %5.2f $tRunMin`
set tRunHours = `echo $tSecRun/3600|bc -l`
set tRunHours = `printf %5.2f $tRunHours`
echo "Started at $StartTime " |& tee -a $LF
echo "Ended   at `date`" |& tee -a $LF
echo "Fsr-Mergexopts-Run-Time-Sec $tSecRun" |& tee -a $LF
echo "Fsr-Mergexopts-Run-Time-Min $tRunMin" |& tee -a $LF
echo "Fsr-Mergexopts-Run-Time-Hours $tRunHours" |& tee -a $LF
echo " " |& tee -a $LF
echo "fsr-mergexopts Done" |& tee -a $LF
exit 0

###############################################

############--------------##################
error_exit:
echo "ERROR:"

exit 1;
###############################################

############--------------##################
parse_args:
set cmdline = ($argv);
while( $#argv != 0 )

  set flag = $argv[1]; shift;
  
  switch($flag)

    case "--x":
      if($#argv < 1) goto arg1err;
      set xopts = $argv[1]; shift;
      if(! -e $xopts) then
        echo "ERROR: cannot find $xopts"
        exit 1
      endif
      set xoptslist = ($xoptslist $xopts)
      breaksw

    case "--o":
      if($#argv < 1) goto arg1err;
      set outxopts = $argv[1]; shift;
      breaksw

    case "--force":
     set ForceUpdate = 1
     breaksw
    case "--no-force":
     set ForceUpdate = 0
     breaksw

    case "--log":
      if($#argv < 1) goto arg1err;
      set LF = $argv[1]; shift;
      breaksw

    case "--nolog":
    case "--no-log":
      set LF = /dev/null
      breaksw

    case "--tmp":
    case "--tmpdir":
      if($#argv < 1) goto arg1err;
      set tmpdir = $argv[1]; shift;
      set cleanup = 0;
      breaksw

    case "--nocleanup":
      set cleanup = 0;
      breaksw

    case "--cleanup":
      set cleanup = 1;
      breaksw

    case "--debug":
      set verbose = 1;
      set echo = 1;
      breaksw

    default:
      echo ERROR: Flag $flag unrecognized. 
      echo $cmdline
      exit 1
      breaksw
  endsw

end

goto parse_args_return;
############--------------##################

############--------------##################
check_params:

if($#outxopts == 0) then
  echo "ERROR: must spec output expert file"
  exit 1;
endif
if($#xoptslist == 0) then
  echo "ERROR: must spec input expert file"
  exit 1;
endif

foreach xopts ($xoptslist)
  fsr-checkxopts $xopts
  if($status) exit 1
end

set ud = `UpdateNeeded $outxopts $xoptslist`
if(! $ud && ! $ForceUpdate) then
  echo "$outxopts does not need to be updated"
  echo "If you want to force an update, then add --force"
  exit 0
endif

goto check_params_return;
############--------------##################

############--------------##################
arg1err:
  echo "ERROR: flag $flag requires one argument"
  exit 1
############--------------##################
arg2err:
  echo "ERROR: flag $flag requires two arguments"
  exit 1
############--------------##################

############--------------##################
usage_exit:
  echo ""
  echo "fsr-mergexopts"
  echo "  --x xopts1 --x xopts2 ... <--x xoptsN>"
  echo "  --o mergedxopts"
  echo ""

  if(! $PrintHelp) exit 1;
  echo $VERSION
  cat $0 | awk 'BEGIN{prt=0}{if(prt) print $0; if($1 == "BEGINHELP") prt = 1 }'
exit 1;

#---- Everything below here is printed out as part of help -----#
BEGINHELP
