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

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

set outdir = ();
set subject = ();
set ForceUpdate = 0
set threads = 1
setenv OMP_NUM_THREADS $threads
setenv FS_OMP_NUM_THREADS $OMP_NUM_THREADS
set RunIt = 1
set XOptsFile = ()
set invol = ()
set fs_time = "";

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`

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.rca-talairach.$$
  if(! -dw /scratch) set tmpdir = $outdir/tmpdir.rca-talairach.$$
endif
#mkdir -p $tmpdir

# Set up log file
if($#LF == 0) set LF = $outdir/log/rca-talairach.Y$year.M$month.D$day.H$hour.M$min.log
if($LF != /dev/null) rm -f $LF
echo "Log file for rca-talairach" >> $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

#========================================================
set mni305stripped = $FREESURFER/average/mni305.cor.stripped.mgz
set mni305lta = $sm_mni305dir/aff.lta
set cmd = (fs-synthmorph-reg --i $invol --t $mni305stripped --affine-only \
  --o $sm_mni305dir --threads $OMP_NUM_THREADS)
if($ForceUpdate) set cmd = ($cmd --force)
echo $cmd |& tee -a $LF
if($RunIt) then
  $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  if($#subject) then
    set xfmlta = $mdir/transforms/talairach.xfm.lta
    set xfm    = $mdir/transforms/talairach.xfm
  else
    set xfmlta = $outdir/talairach.xfm.lta
    set xfm    = $outdir/transforms/talairach.xfm
  endif
  set ud = `UpdateNeeded $xfmlta $mni305lta`
  if($ud || $ForceUpdate) then
    set cmd = (lta_convert --ltavox2vox --inlta $mni305lta --outlta $xfmlta) # convert to VOX2VOX
    $cmd |& tee -a $LF
    if($status) goto error_exit;
    set cmd = (lta_convert --inlta $xfmlta --outmni $xfm)
    $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
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 "Rca-Talairach-Run-Time-Sec $tSecRun" |& tee -a $LF
echo "Rca-Talairach-Run-Time-Min $tRunMin" |& tee -a $LF
echo "Rca-Talairach-Run-Time-Hours $tRunHours" |& tee -a $LF
echo " " |& tee -a $LF
echo "rca-talairach 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 "--s":
    case "-s":
      if($#argv < 1) goto arg1err;
      set subject = $argv[1]; shift;
      breaksw

   case "-sd":
   case "--sd":
   case "--sdir":
      if($#argv < 1) goto arg1err;
      setenv SUBJECTS_DIR $argv[1]; shift;
      breaksw

    case "--threads":
    case "-threads":
      if($#argv < 1) goto arg1err;
      set threads = $argv[1]; shift;
      setenv OMP_NUM_THREADS $threads
      setenv FS_OMP_NUM_THREADS $OMP_NUM_THREADS
      breaksw

    case "-dontrun":
    case "--dontrun":
      set RunIt = 0;
      breaksw

    case "-expert":
      if( $#argv < 1) goto arg1err;
      set XOptsFile = $argv[1]; shift;
      fsr-checkxopts $XOptsFile
      if($status) goto error_exit;
      set XOptsFile = `getfullpath $XOptsFile`
      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 "--o":
      if($#argv < 1) goto arg1err;
      set outdir = $argv[1]; shift;
      # Not used
      breaksw

    case "--i":
      if($#argv < 1) goto arg1err;
      set invol = $argv[1]; shift;
      # Not used
      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($#subject == 0) then
  echo "ERROR: must spec subject"
  exit 1;
endif
if(! -e $SUBJECTS_DIR/$subject) then
  echo "ERROR: cannot find $subject"
  exit 1;
endif
set mdir = $SUBJECTS_DIR/$subject/mri
set invol = $mdir/synthstrip.mgz

if($#outdir == 0) then
  set sm_mni305dir = $mdir/transforms/synthmorph.mni305
  set outdir = $sm_mni305dir 
  set logdir = $SUBJECTS_DIR/$subject/scripts
else
  set sm_mni305dir = $outdir
  set logdir = $outdir/log
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 "rca-talairach -  affine registration talairch.xfm to the mni305 with synthmorph"
  echo " --s subject"
  echo " --threads threads"
  echo " --sdir SUBJECTS_DIR "
  echo " --force : force update"
  echo " --dontrun"

  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
