#!/bin/tcsh -f
# samseg

set VERSION = 'samseg dev';

set outdir = ();
set subject = ();
set usebin = 0;
set exvivo = 0;
set monly = 0;
set MLF = ();
set threads = 1;
set parallel = 0;
set DoValGrind = 0
set vg = (valgrind --error-limit=no --leak-check=yes --tool=memcheck --track-origins=yes)
set tmpdir = ();
set cleanup = 1;
set LF = ();
set regmat = ()
set initlta = ()
set inputlist = ()
set regonly = 0;
set computedice = 0;
set diceseg = none
set DoRecon = 0;
set DoFill = 0; # Create filled.mgz in samseg2recon
set DoNormalization2 = 0; # Do Normalization2 in samseg2recon
set DoHiRes = 0;
set DoLesion = 0;
set DoImport = 0
set HaveT1w = 0;
set HaveT2w = 0;
set HaveFLAIR = 0;
set UseT2w = 0;
set UseFLAIR = 0;
set modenamelist = ()
set refmodename = ();
set SaveMesh = 0
set basedir = ()
set max_iters = ()
set SavePosteriors = 0
set SaveProbabilities = 0
set SaveWarp = 1;
set DoMRF = 0;
#set mrfgca = $FREESURFER_HOME/average/samseg/samseg.talairach.lta.mrf.gca
set mrfgca = $FREESURFER_HOME/average/samseg/samseg.talairach.m3z.mrf.gca
set DoRefine = 0
set ForceUpdate = 0
set PallidumSeparate = 0;
set OptionsFile = ()
set SaveHistory = 0
set LesionMaskPattern = ()
set GMM = ()
set ShowFigs = 0
set ShowMovie = 0;
set IgnoreUnkown = 0;

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
  set tmpdir = `fs_temp_dir --scratch --base $outdir`
endif
mkdir -p $tmpdir

# Set up log file
if($#LF == 0) then
  if($#subject == 0) then
    set LF = $outdir/log/samseg.Y$year.M$month.D$day.H$hour.M$min.log
    pushd $outdir 
    ln -sf log/samseg.Y$year.M$month.D$day.H$hour.M$min.log samseg.log
    popd
  endif
  if($#subject != 0) then
    mkdir -p $SUBJECTS_DIR/$subject/scripts/log
    set LF = $SUBJECTS_DIR/$subject/scripts/log/samseg.Y$year.M$month.D$day.H$hour.M$min.log
    pushd $SUBJECTS_DIR/$subject/scripts
    ln -sf log/samseg.Y$year.M$month.D$day.H$hour.M$min.log samseg.log
    popd
  endif
endif
if($LF != /dev/null) rm -f $LF
echo "Log file for samseg" >> $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
echo "" | tee -a $LF
cat $FREESURFER_HOME/build-stamp.txt | tee -a $LF
echo $VERSION | tee -a $LF
uname -a  | tee -a $LF
if($?PBS_JOBID) then
  echo "pbsjob $PBS_JOBID"  >> $LF
endif

if($#GMM) cp $GMM $outdir/log/gmm.txt

if($DoImport) then
  # Import the data
  set cmd = (fsr-import $inputargs --o $importdir)
  if($DoHiRes) set cmd = ($cmd --hires) # prevents conforming
  if($ForceUpdate) set cmd = ($cmd --force-update)
  echo $cmd | tee -a $LF
  fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  # Coregister within and between modes, resample to reference mode
  set cmd = (fsr-coreg --i $importdir --ref $refmodename --threads $threads --o $coregdir)
  if($ForceUpdate) set cmd = ($cmd --force-update)
  echo $cmd | tee -a $LF
  fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  # Create input list, make sure refmodename is first
  set outvol = $coregdir/$refmodename/$refmodename.mgz
  set inputlist = ($outvol)
  set modenamelist = (`cat $importdir/modenames.txt`)
  foreach modename ($modenamelist)
    if($modename == $refmodename) continue;
    set outvol = $coregdir/$modename/$modename.mgz
    set inputlist = ($inputlist $outvol)
  end
endif

#========================================================
set cmd0 = (run_samseg -o $outdir --threads $threads)
if($SaveMesh) set cmd0 = ($cmd0 --save-mesh)
if($#regmat)  set cmd0 = ($cmd0 --reg $regmat)
if($#initlta) set cmd0 = ($cmd0 --init-reg $initlta)
if($regonly) set cmd0 = ($cmd0 --reg-only);
if($#max_iters) set cmd0 = ($cmd0 --max-iters $max_iters);
if($SavePosteriors) set cmd0 = ($cmd0 --save-posteriors)
if($SaveProbabilities) set cmd0 = ($cmd0 --save-probabilities)
if($SaveWarp) set cmd0 = ($cmd0 --save-warp)
if($PallidumSeparate) set cmd0 = ($cmd0 --pallidum-separate)
if($#OptionsFile)  set cmd0 = ($cmd0 --options $OptionsFile)
if($SaveHistory)  set cmd0 = ($cmd0 --history)
if($DoLesion) set cmd0 = ($cmd0 --lesion)  # TODO: if T2/flair is provided, --lesion-mask-pattern must be set
if($#LesionMaskPattern) set cmd0 = ($cmd0 --lesion-mask-pattern $LesionMaskPattern)
if($#GMM) set cmd0 = ($cmd0 --gmm $GMM)
if($ShowFigs) set cmd0 = ($cmd0 --showfigs)
if($ShowMovie) set cmd0 = ($cmd0 --movie)
if($IgnoreUnkown) set cmd0 = ($cmd0 --ignore-unknown)

# specify input list
foreach input ($inputlist)
  set cmd0 = ($cmd0 -i $input)
end
if($DoValGrind == 0) then
  set cmd = (fs_time $cmd0)
else
  set cmd = ($vg $cmd0)
endif
echo $cmd | tee -a $LF
$cmd |& tee -a $LF
if($status) goto error_exit;
echo "run_samseg complete" | tee -a $LF

date | tee -a $LF

# Should probably convert segmentation to INT (now saves as float)

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

# Create an xfm as well
set lta = $outdir/samseg.talairach.lta
set xfm = $outdir/samseg.talairach.xfm
set cmd = (lta_convert --inlta $lta --outmni $xfm)
echo $cmd | tee -a $LF
$cmd | tee -a $LF
if($status) goto error_exit;

if(! $regonly) then

  set seg = "$outdir/seg.mgz"

  if($DoRefine) then
    set cmd = (mri_refine_seg --debug -i $seg -o $seg)
    echo $cmd | tee -a $LF
    $cmd | tee -a $LF
    if($status) goto error_exit;
  endif

  # Compute segstats
  set sumfile = $outdir/seg.stats 
  set cmd = (mri_segstats --ctab-default --seg $seg --sum $sumfile)
  echo $cmd | tee -a $LF
  $cmd | tee -a $LF
  if($status) goto error_exit;

  if($DoMRF) then
    set inputbase = `basename $inputlist[1]` 
    set inputbase = `fname2stem $inputbase`
    set bc = "$outdir/modality01_bias_corrected.mgz"
    if(! -e $bc) then
      echo "ERROR: cannot find $bc" | tee -a $LF
      goto error_exit;
    endif
    set mrf = "$outdir/seg.mrf.mgz"
    #set reg = $outdir/samseg.talairach.lta
    set reg = $outdir/template.m3z
    set cmd = (mri_ca_label -r $seg -relabel_unlikely 9 .3 \
       -prior 0.5 -align $bc $reg $mrfgca $mrf)
    echo $cmd | tee -a $LF
    fs_time $cmd | tee -a $LF
    if($status) goto error_exit;
    # Compute segstats of the mrf'ed seg
    set sumfile = $outdir/seg.mrf.stats 
    set cmd = (mri_segstats --ctab-default --seg $mrf --sum $sumfile)
    echo $cmd | tee -a $LF
    $cmd | tee -a $LF
    if($status) goto error_exit;
  endif #MRF

  if($computedice) then
    set logfile = $outdir/dice.log
    set tablefile = $outdir/dice.table.dat
    rm -f $logfile # need to rm because it just appends
    set cmd = (mri_compute_seg_overlap -table $tablefile -log $logfile $diceseg $seg)
    echo $cmd | tee -a $LF
    $cmd | tee -a $LF
    if($status) then
      echo "error: could not compute seg overlap";
      goto error_exit;
    endif
  endif

endif # not regonly

# Prep for recon
if($#subject != 0) then
  set cmd = (samseg2recon --s $subject) # --i $input 
  set cmd = ($cmd --tmpdir $tmpdir/tmp.mergeseg)
  if($cleanup) set cmd = ($cmd --cleanup)
  if($DoFill) set cmd = ($cmd --fill)
  if($DoNormalization2) set cmd = ($cmd --normalization2)
  echo $cmd | tee -a $LF
  $cmd | tee -a $LF
  if($status) goto error_exit;
  if($DoRecon) then
    echo "" | tee -a $LF
    echo "" | tee -a $LF
    echo "Starting recon-all `date`" | tee -a $LF
    set cmd = (recon-all)
    if($parallel) then
      set cmd = ($cmd -parallel)
    endif
    set cmd = ($cmd -s $subject -autorecon2-samseg -autorecon3 -threads $threads)
    if($DoFill) set cmd = ($cmd -nosegmentation -nofill)
    if($DoNormalization2) set cmd = ($cmd -nonormalization2)
    if($UseT2w)   set cmd = ($cmd -T2pial)
    if($UseFLAIR) set cmd = ($cmd -FLAIRpial)
    if($DoHiRes) set cmd = ($cmd -hires)
    echo $cmd | tee -a $LF
    $cmd | tee -a $LF
    if($status) goto error_exit;
    echo "recon-all done `date`" | tee -a $LF
    echo "" | tee -a $LF
    echo "" | tee -a $LF
  endif
endif

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

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

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

############--------------##################
error_exit:
echo "ERROR: $cmd"
exit 1;
###############################################

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

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

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

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

    case "--recon":
      set DoRecon = 1
      breaksw

    case "--lesion":
      set DoLesion = 1
      breaksw

    case "--lesion-mask-pattern":
      if($#argv < 2) goto arg1err;
      set LesionMaskPattern = ($argv[1] $argv[2]); shift;shift;
      breaksw

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

    case "--mrf":
      set DoMRF = 1
      breaksw
    case "--no-mrf":
      set DoMRF = 0
      breaksw

    case "--reg":
    case "--regmat":
      # this can be a .mat file like that created by samseg or an LUT
      if($#argv < 1) goto arg1err;
      set regmat = $argv[1]; shift;
      if(! -e $regmat) then
        echo "ERROR: cannot find $regmat"
        exit 1
      endif
      breaksw

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

    case "--i":
      if($#argv < 1) goto arg1err;
      set inputlist = ($inputlist $argv[1]); shift;
      # assumes multiple inputs are already in alignment
      breaksw

    # These are inputs to fsr-import or fsr-coreg. The actual values
    # are not directly important for samseg. The only thing is that
    # there must be a t1w if a recon will be done.
    case "--t1w":
      if($#argv < 1) goto arg1err;
      shift; 
      set HaveT1w = 1;
      set DoImport = 1
      breaksw
    case "--t2w":
      if($#argv < 1) goto arg1err;
      shift; 
      set HaveT2w = 1;
      set DoImport = 1
      breaksw
    case "--flair":
      if($#argv < 1) goto arg1err;
      shift;
      set HaveFLAIR = 1;
      set DoImport = 1
      breaksw
    case "--mode":
      if($#argv < 2) goto arg2err;
      set modename = $argv[1]; shift
      shift;
      if($modename == t1w) set HaveT1w = 1;
      set DoImport = 1
      breaksw
    case "--refmode":
      if($#argv < 1) goto arg1err;
      set refmodename = $argv[1]; shift;
      set DoImport = 1
      breaksw
    # When doing a recon with T2 and/or FLAIR available, one can
    # include the T2 or the FLAIR in the recon (but not both).
    case "--use-t2w":
      set UseT2w = 1;
      set DoImport = 1
      breaksw
    case "--use-flair":
      set UseFLAIR = 1;
      set DoImport = 1
      breaksw

    case "--pallidum-separate":
      set PallidumSeparate = 1;
      breaksw

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

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

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

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

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

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

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

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

    case "--regonly":
    case "--reg-only":
      set regonly = 1;
      breaksw

    case "--save-mesh":
      set SaveMesh = 1;
      breaksw
    case "--no-save-mesh":
      set SaveMesh = 0;
      breaksw

    case "--monly":
    case "-monly":
      if( $#argv < 1) goto arg1err;
      set MLF =  $1; shift;
      set monly = 1;
      breaksw
    
    case "--threads":
      if( $#argv < 1) goto arg1err;
      set threads =  $1; shift;
      breaksw

    case "--ssdd":
      if( $#argv < 1) goto arg1err;
      setenv SAMSEG_DATA_DIR $1; shift;
      breaksw

    case "--parallel":
      set parallel = 1
      breaksw

    case "--fill":
      # Do fill in samseg2recon, not recon-all
      set DoFill = 1;
      breaksw
    case "--no-fill":
      set DoFill = 0;
      breaksw

    case "--normalization2":
      # Do norm2 in samseg2recon, not recon-all
      set DoNormalization2 = 1;
      breaksw
    case "--no-normalization2":
    case "--nonormalization2":
      set DoNormalization2 = 0;
      breaksw

    case "--valgrind":
      set DoValGrind = 1;
      breaksw

    case "--bin":
      set usebin = 1;
      set monly = 0;
      breaksw

    case "--no-bin":
      set usebin = 0;
      breaksw

    case "--hires":
    case "-hires":
      set DoHiRes = 1; # for recon-all
      breaksw
    case "--no-hires":
      set DoHiRes = 0; # for recon-all
      breaksw

    case "--history":
      set SaveHistory = 1
      breaksw
    case "--no-history":
      set SaveHistory = 0
      breaksw

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

    case "--save-posteriors":
      set SavePosteriors = 1;
      breaksw

    case "--save-probabilities":
      set SaveProbabilities = 1;
      breaksw

    case "--save-warp":
      set SaveWarp = 1;
      breaksw
    case "--no-save-warp":
      set SaveWarp = 0;
      breaksw

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

    case "--ignore-unknown":
      set IgnoreUnkown = 1
      breaksw   

    case "--showfigs":
      set ShowFigs = 1;
      breaksw   

    case "--movie":
      set ShowMovie = 1;
      breaksw   

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

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

    case "--atlas":
      if($#argv < 1) goto arg1err;
      setenv SAMSEG_DATA_DIR $argv[1]; shift;
      if(! -e $SAMSEG_DATA_DIR) then
        echo "ERROR: cannot find $SAMSEG_DATA_DIR"
        exit 1
      endif
      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 "--exvivo":
      set exvivo = 1;
      set GMM = $FREESURFER/average/samseg/20Subjects_smoothing2_down2_smoothingForAffine2/exvivo.sharedGMMParameters.txt
      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($#inputlist == 0 && $DoImport == 0) then
  echo "ERROR: must supply at least one input"
  exit 1
endif
if($#inputlist != 0 && $DoImport != 0) then
  echo "ERROR: cannot spec both --i and --mode/--t1w/--t2w/--flair"
  exit 1
endif
if($DoImport == 0) then
  foreach f ($inputlist)
    if($f != none && ! -e $f) then
      echo "ERROR: cannot find $f"
      exit 1;
    endif
  end
endif
if($DoRecon && $DoImport == 0) then
  echo "ERROR: with --recon, must spec input with --mode/--t1w/--t2w/--flair "
  exit 1
endif
if($#subject && $DoImport == 0) then
  echo "ERROR: with --s, must spec input with --mode/--t1w/--t2w/--flair "
  exit 1
endif
if($#subject == 0 && $DoRecon) then
  echo "ERROR: Cannot use --recon without --s"
  exit 1;
endif

if($DoImport) then
  if($#refmodename == 0) then
    echo "ERROR: must specify --refmode with --mode/--t1w/--t2w/--flair"
    exit 1;
  endif
  if(! $HaveT1w) then
    echo "ERROR: if performing a recon and import, then must have a T1w mode"
    exit 1;
  endif
  if($HaveT2w && $HaveFLAIR) then
    if($UseT2w == 1 && $UseFLAIR == 1) then
      echo "ERROR: you cannot specify to use both T2w and FLAIR in the recon"
      exit 1
    endif
  endif
endif

if($#regmat && $#initlta) then
  echo "ERROR: cannot specify both --regmat and --initlta"
  exit 1
endif

if($#outdir == 0 && $#subject == 0) then
  echo "ERROR: must spec outdir or --s"
  exit 1;
endif

if($#subject) then
  if(-e $SUBJECTS_DIR/$subject) then
    echo "ERROR: $subject already exists"
    #exit 1;
  endif
  if($#outdir != 0) then
    echo "ERROR: cannot spec --o with --s"
    exit 1;
  endif
  set outdir = $SUBJECTS_DIR/$subject/mri/samseg
  set importdir = $SUBJECTS_DIR/$subject/input
  set coregdir  = $SUBJECTS_DIR/$subject/coreg
  # --conformed-to-min in new version of mri_info
  #set cmd = (mri_info --conformed-to-min $inputlist[1])
  #set isconformed = `$cmd | head -n 1`
  #if(0 && "$isconformed" != "yes") then
  #  echo "$isconformed"
  #  echo "ERROR: must use conformed volume with --s"
  #  exit 1;
  #endif
  mkdir -p $outdir 
  mkdir -p $SUBJECTS_DIR/$subject/scripts 
  mkdir -p $SUBJECTS_DIR/$subject/mri/transforms
else
  set importdir = $outdir/input
  set coregdir  = $outdir/coreg
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 "samseg"
  echo "  --i file.mgz <--i file2.mgz> <--i file3.mgz>... <--i>"
  echo "  --t1w t1file.mgz <--t1w t2file2.mgz> <--t2w t2file.mgz> <--flair flairfile.mgz> <--mode modename modefile.mgz>  "
  echo "     Note: using the t1w/t2w/flair/modename will cause input to be conformed unless --hires"
  echo "      --refmode modename (t1w/t2w/flair/modename)  "
  echo "  --o outdir "
  echo "  --options OptionsFile : json file for advanced"
  echo "  --history : Turns on save history"
  echo "  --s subject : create subject, sets outdir to subject/mri/samseg"
  echo "                the first input must be the conformed T1 weighted input"
  echo "  --save-posteriors : save posterior probs"
  echo "  --save-probabilities : save post, prior, and likelihood as 3-frame vol foreach tissue type" 
  echo "  --no-save-warp : do not save m3z-style warp"
  echo "  --mrf/--no-mrf : do or do not do MRF (default is $DoMRF)"
  echo "  --threads nthreads : set the number of CPUs to use"
  echo "  --atlas SAMSEG_DATA_DIR"
  echo "  --gmm gmmfile"
  echo ""
  echo "  --recon : run recon-all "
  echo "  --fill : use samseg to create filled.mgz instead of recon-all"
  echo "  --normalization2 : use samseg to create brain.mgz instead of recon-all (with --recon) "
  echo "  --use-t2w : use the t2-weighted input when running recon-all"
  echo "  --use-flair : use the FLAIR-weighted input when running recon-all"
  echo "  --hires  : use -hires when running recon-all"
  echo "  --sd SUBJECTS_DIR"
  echo ""
  echo " --pallidum-separate : Move pallidum outside of global white matter class. Use this flag when"
  echo "   analyzing T2 or FLAIR"
  echo " --lesion : Turn on lesion segmentation"
  echo " --lesion-mask-pattern A B : Needed when using T2 (eg, 0 1)"
  echo " --reg reg.{lta,mat} : registration file (LTA or  as output by samseg)"
  echo "    allows using the reg from one run with another run"
  echo " --regmat reg.{lta.mat} same as --reg"
  echo " --initlta init.lta : initial registration"
  echo " --reg-only : only perform registration"
  echo " --ssdd SAMSEG_DATA_DIR : where the atlas is located"
  echo " --save-mesh : save the mesh (probably for longitudinal analysis)"
  echo " --options optionsfile : to pass to run_samseg"
  echo " --max-iters iters"
  echo " --dice seg.mgz"
  echo " --ignore-unknown"
  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

Inputs can be specified in two ways. One way is simply with --i
input1.mgz <--i input2.mgz>. In this case, each input will be a
separate input to samseg; all the inputs must be in registration with
each other. The alternative is with the "fsr-import" options:
--t1w/--t2w/--flair/--mode. If multiple acquisitions within modality
are specified, they will be registered and averaged together. If
multiple modalities are specified, then they will be registered
together for input to samseg. The registration is performed with
fsr-coreg. Within modality, the volumes must be the same dimension,
voxel size, etc.  The inputs can differ in dimension, etc, between
modality. When using the fsr-import option, one must supply a
--refmode to indicate which mode the other modes should be registered
to.

When running with --recon, the input must be specified with the
fsr-input options. One of the modes must be t1w. The --refmode should
probably be t1w. If the input includes a t2-weighted and/or a FLAIR image, 
the user can supply a --use-t2w or --use-flair to indicate that the recon
should be done with T2/FLAIR pial refinement. 

You can change the atlas dir with either
  setenv SAMSEG_DATA_DIR /path/to/atlas
or
  --atlas /path/to/atlas



Example,
samseg --t1w run1.T1.slice0.dicom  --t1w run2.T1.slice0.dicom \
  --t2w T2.nii.gz  --mode pd myPDimage.mgz --flair FLAIR-weighted.dcm ...

To use the --inilta, the LTA should map from the input volume to the
atlas (eg, $FREESURFER_HOME/average/samseg/20Subjects_smoothing2_down2_smoothingForAffine2/template.nii)

eg, 
mri_coreg --mov $atlas --targ orig.mgz --dof 12 --reg coreg.lta 

Example 

recon samseg --t1w 001.mgz --t2w T2raw.mgz --s subject --recon --use-t2w --refmode t1w 

This will do a whole-brain multimodal segmentation using the
T1-weighted 001.mgz and the T2-weighted T2raw.mgz. The output will go
into $SUBJECTS_DIR/$subject/samseg.  recon-all will be run using the
SAMSEG segmentation and the bias corrected t1w and t2w. The pial
surface will be refined with the T2 because --use-t2w was specified.




