#!/usr/bin/tcsh -f

#
# recon-all
#
# Script to run the entire reconstruction pipline.
# Original Author: Doug Greve
#
# Copyright © 2021 The General Hospital Corporation (Boston, MA) "MGH"
#

umask 002;

setenv FS_RECON_VERSION 'mockbuild-local (freesurfer-local-build-20260505)'

# This turns on the V8 options
if($?FS_V8_XOPTS == 0) setenv FS_V8_XOPTS 1
set UseV8 = $FS_V8_XOPTS;

set ProgName = `basename $0`;
set inputargs = ($argv);
set subjid = ();
set hemilist = (lh rh);
set mailuser = ();
set WaitForFile = ();
set nWaitsMax  = 1000;
set WaitSleep =  1m;
set NotifyFile = ();
set PrintHelp = 0;
set LF = ();
set LF_DEFAULT_NAME = recon-all.log;
set SF = ();
set SF_DEFAULT_NAME = recon-all-status.log;
set CF = ();
set CF_DEFAULT_NAME = recon-all.cmd;
set AppendLog    = 1;
set AppendStatus = 1;
set DoTime = 1;
if($?SET_FS_CMD_TIMING) set DoTime = 1;
set fs_time = "";
set ErrorFile = /dev/null
set cmd = ();
setenv FS_LOAD_DWI 0 # turn off trying to load DWI
if($?FS_GII == 0) setenv FS_GII ""
set IntensityBFS = 255

# commands to only process single hemispheres (e.g. for ex vivo)
set LHonly = 0 ;
set RHonly = 0 ;
set nocerebellum = () ;  # will be set to -nocerebellum

set tcsh61706 = (`tcsh --version | grep "6\.17\.06"`)
if ("$tcsh61706" != "") then
    echo ""
    echo "WARNING: tcsh v6.17.06 has an exit code bug! Please update tcsh!"
    echo ""
    # workaround to force expected behavior:
    set anyerror
endif

set Force = 0;
set DoCleanCSDF  = 0;
set DoCleanCW256 = 0;
set DoCleanTal   = 0;
set DoCleanLta   = 0;
set DoCleanCP    = 0;
set DoCleanTWM   = 0;
set DoCleanSeed  = 0;
set DoCleanPFH   = 0;
set DoCleanBM    = 0;
set DoCleanBFSE  = 0;
set DoCleanASeg  = 0;
set DoCleanWM    = 0;
set DoCleanFilled = 0;
set DoCleanXopts = 0;
set DoCleanT2    = 0;
set DoCleanFLAIR = 0;
set DoSuperClean = 0;

set DoShowEdits  = 0;

set InputList = ();

# parameter defaults (most can be overriden with flags)
set XOptsFile = ();
set GlobXOptsFile = ()
set XOptsClean = 0; # Delete a pre-existing xopts file
set XOptsUse   = 1; # Use a pre-existing xopts file (default '1': always use)
set XOptsOverwrite = 0; # Overwrite a pre-existing xopts file
set TermScriptList = ();
set ControlPointsFile = ();
set TWMControlPointsFile = ();
set PonsSeedCRS = (); # SeedCRS center of pons for mri_fill #
set CCSeedCRS = ();   # SeedCRS center of corpus callosum for mri_fill #
set RHSeedCRS = ();   # SeedCRS point in the right hemi wm for mri_fill #
set LHSeedCRS = ();   # SeedCRS point in the left  hemi wm for mri_fill #

set CustomMaskInput = (); # custom brain mask to replace mri_watershed
set UseMincMritotal = 0; # if 1, then use the BIC-MNI mritotal tal reg tools
set DoSamsegReg = 0; # if 1, then uses samseg for talairach registration
set DoTalairachUseNu = 0; # if 1, use nu.mgz as input to talairach stage
set UseYa3tTalAtlas = 0; # if 1, use 3T18yoSchwartz young-adult 3T atlas
                         # for tal_avi (recommended as 3T default by Avi S.)
set CustomTalAtlas = ""; # -custom-tal-atlas <name of atlas in average dir>
set EMRegStrip = 1; # Run mri_em_register for skullstrip (otherwise use tal.xfm)
set EMRegAseg = 1; # Run mri_em_register for GCA (otherwise use tal.xfm converted to lta)

set DoNuMakeUchar = 1; # if 1, then run mri_nu_correct.mni using talairach.xfm
                       # to run mri_make_uchar to correct histogram problem
# Neither of these are used right now
set UseMaskNuCorrect = 0; # if 1, nu_correct runs with -mask brainmask.mgz
set DilateMaskNuCorrect = (); # grow nu_correct mask by this amount

set WaterShed = 1;      # 0=no WS, 1= WS normal, 2 = WS only, 3 = WS+1st
set WSLess    = 0;      # Shrinks skull surface
set WSMore    = 0;      # Expands skull surface
set WSPctPreFlood = (); # Pre-flooding height
set WSSeedPoint = ();   # C R S
set WSAtlas     = 0;    # 0=don't use atlas, 1=use atlas (for skull strip)
set WSGcaAtlas  = 1;    # 1=use GCA atlas and registration to do skull strip
set WSUseTalXfm = 0;    # 1=use talairach.xfm instead of talairach_with_skull
                        # to do atlas alignment during mri_watershed
set WSCopy = 0;         # Simply copy input to output ignoring other opts, 
                        # for when brain is already stripped
set DoGcut = 0;         # 1=run mri_gcut after mri_watershed
set NuIterations = 2;   # Number of iterations for nu intensity correction
set ConformMin = 0;     # 1=conformed to min dimension
set ConformKeepDC = 0;  # Keep volume direction cosines when conforming
set HiRes = 0;          # 1=hires option (conformed to min dimension)
set DoConf2Hires = 0;
set Norm3dIters = ();   # passed as -n to *both* mri_normalize runs
set NormMaxGrad = 1;    # passed as -g to *both* mri_normalize runs
set Norm1_b = ();       # passed as -b to the *first* mri_normalize only
set Norm1_n = ();       # passed as -n to the *first* mri_normalize only
set Norm2_b = ();       # passed as -b to the *second* mri_normalize only
set Norm2_n = ();       # passed as -n to the *second* mri_normalize only
set WMSegFromASeg = 0; # use aseg WM instead of mri_segment
#set DoAntsDenoising = 0; # Do not use ANTS denoising prior to mri_segment # see recon-conf.yaml
set NoThicken = 0 # if 1, add '-thicken 0' to mri_segment
set MriSegWsizemm = 13  # Sets search region for mri_segment
set WMSeg_wlo = ();  # from -seg-ghi and -seg-wlo, passed to mri_segment
set WMSeg_ghi = ();  #                             and mris_make_surfaces
set FixWithGA = 1;   # for topology fixer
set FixDiagOnly = 0; # for topology fixer
set RmNeckRadius = 25;  # used by mri_remove_neck
set UseCAAlign = (-align); # flag added to mri_ca_label
set UseCAAlignAfter = (-align-after); # flag added to mri_ca_register
set UseAseg  = 1 # when set to 0 (using -noaseg),then aseg.presurf.mgz not used
                 # nor is ?h.cortex.label (which originates through the aseg)
set NoAsegInorm2 = 0 # when set to 1 (using -noaseg-inorm2), then aseg.presurf
                     # is not used during the 2nd mri_normalize step
set UseNoNeg = 0 # if 1, add '-remove_negative 1' to mris_sphere,mris_register
set UnCompress = 0    # if 1, add '-uncompress' to mri_ca_reg
set BigVentricles = 0 # if 1, add '-bigventricles' to mri_ca_reg.
                      # else, add '-nobigventricles'
set DoSecondPassRenorm = 0 # if 1, add -secondpassrenorm to mri_ca_register
set UseOldTopoFix = 1 # if 1, use mris_fix_topology instead of mris_topo_fixer
set UseNewTopoFix = 0 # if 1, use mris_topo_fixer instead of mris_fix_topology
#set DoRemesh = 1; # remesh ?h.orig to improve triangle quality# see recon-conf.yaml
set NoRandomness = 1 # if 1, seed critical binaries with identical seeds, to
                     # ensure consistency in surface creation. otherwise, the
                     # default is to seed with current time and date,
                     # resulting in slightly different surfaces each run.
                     # affects: mris_smooth, mris_sphere, mris_topology_fixer,
                     # mris_topo_fixer, mris_ca_label,
                     # mri_robust_template (1st-base-call-only)
set RngSeed = 1234   # seed for random number generator, used only when
                     # -norandomness flag is used, and can be overriden by
                     # the flag -rng-seed <seed>
set DoMultiStrip = 0 # if 1, then multiple instances of mri_watershed and
                     # mri_em_register are run in order to determine the best
                     # skull-strip
set IsMPRAGE = 1     # if 1, then -mprage added to mri_normalize/segment, turn off with -no-mprage
set IsWashuMPRAGE = 0 # if 1, then -washu_mprage added to mri_normalize/segment
set DoConformWidth256 = 0 # if 1, then conform to 256^3 during
                          # the mri_convert -conform step
set NoNormMGZ = 0; # set to 1 when -nosubcortseg or -noaseg flag is used,
                   # which causes norm.mgz not to used during inorm2 step
set NoWMSA = 0;      # if 1, then -nowmsa flag is added to mri_ca_label
set TH3Flag = 0; # turn off now because TH3 hard-coded in vertexvol
set DoQdecCache = 0; # if 1, then create smoothed fsaverage surface files
set measurelist = ( thickness area area.pial volume curv sulc \
                    white.K white.H jacobian_white w-g.pct.mgh )
                     # ^ these are the files smoothed by DoQdecCache (-qcache)
set UserMeasureList = 0; # if 1, then 'measurelist' gets -measure args
set measuredir = (); # for specifying an alternate path to measure files
set fwhmlist = ( 0 5 10 15 20 25 ) # see DoQdecCache
set target = fsaverage # see DoQdecCache
set SmoothCortexOnly = 1; # For -qcache. smooths only within ?h.cortex.label
set mps_n_averages = () # n_averages for mris_place_surfaces
set UseHighMyelin = 0; # Allows using diff thresholds when placing white in high-myelin cortex
set HighMyelinFactor = (); # Value between 0 (closer to white) and 1 (closer to cortical gm)

set DoMakefile = 0; # if 1, run make -f recon-all.makefile $(MakefileTarget)
set MakefileTarget = () # argument to recon-all -make
set DoLabelV1 = 0; # if 1, create V1 label from O.Hinds V1 prediction atlas
set DoRobustMotionCor = 1; # if 1, then use mri_robust_template for motion cor
set mc_robust_template_avg_arg = 1; # when using mri_robust_template for motion
                     # correction, construct template from: 0 Mean, 1 Median
set PialNoAparc = 0; # if 1 (-pial-noaparc), then add -noaparc flag to
                     # mris_make_surfaces to bypass usage of parcellation
set UseCPsWithCaNorm = 0 # -canorm-usecps enable control points with ca_norm
set DoT2pial = 0; # if 1, mris_make_surfaces refines pial using T2
set T2_max_inside = ();
set T2_min_inside = ();
set T2_min_outside = ();
set T2_max_outside = ();
set nsigma_above = 2;
set nsigma_below = 5;

set DoFLAIRpial = 0; # if 1, mris_make_surfaces refines pial using FLAIR
set EMRegMaskArg = () ; # MOD: HCP: mask passed when running mri_em_reg, default is 
set EMRegMask = brainmask.mgz ; # MOD: HCP: mask when running mri_em_reg, default is 
set xhemi = 0


# Desired average face area of orig.nofix after decimation. This is
# set to 0.5 by default because this is the value for the orig.nofix
# 0.5 when the voxel size is 1mm3.  Only applies if DoDecimation = 1
# or for high res data. Decimation will have no effect if the average
# face area is already => DecimationFaceArea.
#set DecimationFaceArea = 0.5; # see recon-conf.yaml
#set DoDecimation = 0;

# set multi-threaded stuff to single-threaded/cpu for cluster politeness.
# various binaries (em_reg, ca_reg, mris_sphere) have OpenMP enabled code.
# -openmp <num_threads> allows specifying more threads.
# to support -make, where recon-all is re-entrant, look for FS_OMP_NUM_THREADS
if ($?FS_OMP_NUM_THREADS) then
  setenv OMP_NUM_THREADS $FS_OMP_NUM_THREADS # var declared in -openmp
else
  setenv OMP_NUM_THREADS 1 # default is one thread, -openmp will override
endif
set OMP_NUM_SET = 0 # set to 1 if -openmp <num> is used

# subfields processing uses ITK threading
setenv ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS 1 # -itkthreads <num_threads>
set DoSubfields = 0;

set DoParallel = 0; # if 1, then run with -openmp 4 and -itkthreads 4, 
                    # and run rh/lh stages in parallel

# Longitudinal processing:
set longitudinal = 0;    # if 1, will run the longitudinal scheme
set longbaseid = ();
set tpNid = ();
set LongSamseg = 0
set UseConcatLtaTal = 0; # if 1, use mri_concatenate_lta during tal creation
set UseLongbaseCtrlVol = 0;   # if 1, use ctrl volume of longbase in norm step
set UseLongbaseWMedits = 0;   # if 1, xfer wm edits from base (default is cross)
set UseAsegFusion = 1; # if 0, dont create 'fused' asegs from timepoints
set UseAsegBase = 0; # -asegbase if 1, init TP with base aseg instead of fusion
set DoCreateBaseSubj = 0; # if 1, create the 'base' subject used in longitud
set BaseSubjInvol = (orig.mgz); # -base-invol allows using some other file
set BaseSubjsList = (); # subject set grabbed from -base-tp args
set BaseSubjsListFname = (base-tps); # file containing BaseSubjsList
set robust_template_avg_arg = 1; # construct template from: 0 Mean, 1 Median
set DoNuIntensityCor3T = 0; # if 1, use Zheng, Chee, Zagorodnov params for 3T
set DoAddTp = 0; # if 1, then 'fake'-add this timepoint to long subj set
set DoAffineBase = 0; # if 1, allow affine when creating base (fix calibration)

set UseCubic = 0; # if 1, use cubic spline when mri_convert does conform step
set UseFixMtl = 0; # if 1, add -fix_mtl flag to make_surfaces

# Brainstem substructures
set DoBSsubst = 0;

# For defacing, as found in:
# $FREESURFER_HOME/average/
set brain_template = talairach_mixed_with_skull.gca
set face_template  = face.gca

# For subcortical segmentation
set GCADIR   = "${FREESURFER_HOME}/average"
set GCAOutputName = ();
set GCARegIterations = ();
set GCARegTol  = ();

# For cortical registration, as found in $AvgCurvTifPath/$hemi.$AvgCurvTif
set AvgCurvTifPath = "${FREESURFER_HOME}/average"
#set AvgCurvTif = average.curvature.filled.buckner40.tif
#set AvgCurvTif = curvature.buckner40.2016-03-20.tif
set AvgCurvTif = folding.atlas.acfb40.noaparc.i12.2016-08-02.tif

# Desikan-Killiany cortical parcellation atlas (-cortparc), as found in:
# $FREESURFER_HOME/average/$hemi.$GCS
# The 2009-03-04 atlas contains the insula label.
# The 2010-03-25 atlas has a different color for temporalpole (the old
# color was gray, which looked like the default tksurfer surface color).
set OLD_OLD_GCS = curvature.buckner40.filled.desikan_killiany.2007-06-20.gcs
set OLD_GCS = curvature.buckner40.filled.desikan_killiany.2009-03-04.gcs
set NEW_OLD_GCS = curvature.buckner40.filled.desikan_killiany.2010-03-25.gcs
# The GCSs must have been created with the matching folding atlas
set GCS = DKaparc.atlas.acfb40.noaparc.i12.2016-08-02.gcs
set GCSDIR = "${FREESURFER_HOME}/average"

# Christophe Destrieux cortical parcellation atlas (-cortparc2):
set OLD_OLD_DESTRIEUX_GCS = atlas2002_simple.gcs
set OLD_OLD_DESTRIEUX_NAME = a2002s
set OLD_DESTRIEUX_GCS = atlas2005_simple.gcs
set OLD_DESTRIEUX_NAME = a2005s
set NEW_OLD_DESTRIEUX_GCS = destrieux.simple.2009-07-29.gcs
set DESTRIEUX_GCS = CDaparc.atlas.acfb40.noaparc.i12.2016-08-02.gcs
set DESTRIEUX_NAME = a2009s

# Mindboggle cortical parcellation atlas (-cortparc3):
set DKTATLAS_GCS = DKTaparc.atlas.acfb40.noaparc.i12.2016-08-02.gcs
set DKTATLAS_NAME = DKTatlas

# Initialization method for BBR
set BBRInit = coreg; # others are spm, header, rr, best

# Set this to 0 to do everything but run the command.
# This is good for debugging.
set RunIt = 1;

set PatchDir = ();

# print versions and exit
set DoVersionsOnly = 0;

#----- Volume -----------#
set DoConvertInput   = 0;
set DoConvertT2Input = 0;
set DoConvertFlairInput = 0;
set DoCreateBaseInput = 0;
set DoMotionCor      = 0;
set DoDeface         = 0;
set DoNuIntensityCor = 0;
set DoTalairach      = 0;
set DoTalCheck       = 0;
set DoNormalization  = 0;
set DoNormalization2 = 0;
set DoMaskBFS        = 0;
set UseControlPoints = 0;
set UseTWMControlPoints = 0;
set DoSkullStrip     = 0;
set DoSegmentation   = 0;
set DoGCAReg         = 0;
set DoCANormalize    = 0;
set DoCAReg          = 0;
set DoRemoveNeck     = 0;
set DoSkullLTA       = 0;
set DoCALabel        = 0;
set DoCCSeg          = 0;
set DoASegMerge      = 0;
set DoFill           = 0;
#----- Surface -----------#
set DoTessellate     = 0;
set SvInitOrigSurf   = 0;
set DoSmooth1        = 0;
set DoInflate1       = 0;
set DoQSphere        = 0;
set DoFix            = 0;
set DoSmooth2        = 0;
set DoInflate2       = 0;
set DoCurvHK         = 0;
set DoCurvStats      = 0;
set DoSphere         = 0;
set DoSurfReg        = 0;
set DoJacobianWhite  = 0;
set DoJacobianDist0  = 0;
set DoAvgCurv        = 0;
set DoMorphRGB       = 0;
set DoAutoDetGWStats = 0;
set DoWhitePreAparc  = 0;
set DoCortexLabel    = 0;
set DoWhiteSurfs     = 0;
set DoCortParc       = 0;
set DoCortParc2      = 0;
set DoCortParc3      = 0;
set DoPialSurfs      = 0;
set DoPctSurfCon     = 0;
set DoSurfVolume     = 0;
set DoParcStats      = 0;
set DoParcStats2     = 0;
set DoParcStats3     = 0;
set DoLocalGyriIndex = 0;
set DoBaLabels       = 0;
set DoLabelExvivoEC  = 0;
# ----------- Surface and Volume -----------#
set DoCortRibbonVolMask = 0;
set DoRelabelHypos   = 0;
set DoAParc2ASeg     = 0;
set DoAPas2ASeg      = 0;
set DoSegStats       = 0;
set DoWMParc         = 0;
set DoAParcASegStats = 0;
set DoVnoMatchCheck  = 0;

set ForceUpdate = 0
set DoSBatch = 0;
set SBjobname = ()
set DoIsRunning  = 1;
set IsRunningFile  = ();
set DoneFile = ();

setenv LANG C # Required by MNI tool

# -------------------------------------------------- #
set PWD = pwd;
# better yet, make sure the real pwd is used:
if ( -e /bin/pwd ) set PWD = /bin/pwd

set argv0 = ($argv); # make a copy

if($#argv == 0) goto usage_exit;
set n = `echo $argv | egrep -e -help | wc -l`
if($n != 0) then
  set PrintHelp = 1;
  goto usage_exit;
endif
set n = `echo $argv | egrep -e -version | wc -l`
if($n != 0) then
  cat $FREESURFER_HOME/build-stamp.txt
  exit 0;
endif

source $FREESURFER_HOME/sources.csh

# See whether v8 was passed on the command line
foreach arg ($argv)
  switch($arg)
    case "-v8": 
    case "--v8": 
      set UseV8 = 1
      setenv FS_V8_XOPTS 1
      breaksw;
    case "-no-v8": 
    case "--no-v8": 
      set UseV8 = 0
      setenv FS_V8_XOPTS 0
      breaksw;
  endsw
end        
set V8XoptsFile = ()
set rcav8xopts = ()
if($UseV8) then
  set V8XoptsFile = $FREESURFER/etc/global-expert-options.v8.txt
  set rcav8xopts = `fsr-getxopts recon-all $V8XoptsFile`;
endif
set xopts = ()
if(-e $SUBJECTS_DIR/global-expert-options.txt) then
  set xopts = `fsr-getxopts recon-all $SUBJECTS_DIR/global-expert-options.txt`;
endif
set argv = ($rcav8xopts $xopts $argv);
if($#rcav8xopts || $#xopts) echo "Adding options $rcav8xopts $xopts"

# Forward the command line arguments to recon-config, which
# will parse out any recognized flags and update a recon-specific
# configuration file. Unrecognized arguments will be relayed to
# tmp_unknown_args, which will be parsed in this script
set tmp_config = `mktemp`
set tmp_unknown_args = `mktemp`
rca-config $FREESURFER_HOME/etc/recon-config.yaml $tmp_config $tmp_unknown_args $argv:q
if($status) then
  echo "ERROR: could not configure recon-all parameters"
  exit 1;
endif

# Set global parameters defined by the config file. rca-config2csh
# will print out a bunch of "set" statements to set local
# variables. This call assumes that there will be no superfluous
# terminal output, but this is not necessarily the case, so grep with set
eval "`rca-config2csh $tmp_config | grep set`"
if($NoFixACJ) set FixACJ = 0

# Overwrite argv with all the arguments that were not recognized in the config
set argv = ( "`cat $tmp_unknown_args`" )

goto parse_args;
parse_args_return:

if($DoSBatch) then
  if($?FS_SBATCH_ACCOUNT == 0) then
    echo "ERROR: no sbatch account name. set environment variable FS_SBATCH_ACCOUNT to accountname"
    echo "       or specify with -sbatch-account accountname"
    exit 1;
  endif
  if($#SBjobname == 0) set SBjobname = $subjid
  mkdir -p $SUBJECTS_DIR/sbatch
  set dt = `date +%Y.%m.%H.%M`
  set SBlogFile  = $SUBJECTS_DIR/sbatch/sbatch.$SBjobname.$dt
  set cmd = ($0 $inputargs -no-sbatch)
  set sbatch = (sbatch --partition=$SBpartition --nodes=1 --time=2-0 \
    --ntasks-per-node=1 --cpus-per-task=$OMP_NUM_THREADS \
    --account=$FS_SBATCH_ACCOUNT )
  set cmd = ($sbatch --job-name=$SBjobname --output=$SBlogFile $cmd)
  echo $cmd
  $cmd
  exit $status
endif

# Allow editing of filled.mgz
if(! $?FS_ALLOW_FILLED_EDIT) setenv FS_ALLOW_FILLED_EDIT 1

# Error file. This is created when error_exit is run.
set ErrorFile = $SUBJECTS_DIR/$subjid/scripts/recon-all.error
# Done file. This is created when recon-all exits normally
if($#DoneFile == 0) set DoneFile = $SUBJECTS_DIR/$subjid/scripts/recon-all.done
if($SkipDone && -e $DoneFile && ! -e $ErrorFile) then
  echo "Skipping $subjid because --skip-done specified and done file exists and error file does not exist"  
  exit 0
endif

goto check_params;
check_params_return:

set StartTime = `date`;
set tSecStart = `date '+%s'`;

# This is to revert the T2 masking to that done in 7.1X to make it
# consistent. The 71X reversion means that the T2 is not actually
# masked (which is a bug). 
if($?FS_RCA_T2_MASK_71 == 0) setenv FS_RCA_T2_MASK_71 1

set bstampfile0 = $FREESURFER_HOME/build-stamp.txt
cp $bstampfile0 $SUBJECTS_DIR/$subjid/scripts/lastcall.build-stamp.txt

rm -f $SUBJECTS_DIR/$subjid/scripts/patchdir.txt
if($?PatchDir) then
  echo "$PatchDir" > $SUBJECTS_DIR/$subjid/scripts/patchdir.txt
endif

if ($DoMakefile) then
  setenv RECONALL_MAKE_SUBJECT $subjid
  set make_flags=( $MakefileTarget )
  if ( ! $RunIt) set make_flags=( -n $make_flags )
  echo "Subject '$subjid': make $make_flags"
  make -f $FREESURFER_HOME/bin/recon-all.makefile ${make_flags}
  set makestatus=($status)
  unsetenv RECONALL_MAKE_SUBJECT
  exit ($makestatus)
endif

if ($DoTime) then
  fs_time ls >& /dev/null
  if ( ! $status) set fs_time=(fs_time)
endif

echo "INFO: SUBJECTS_DIR is $SUBJECTS_DIR"

# Get "True" FS HOME
pushd $FREESURFER_HOME > /dev/null
set freesurfer_home_true = `pwd`;
popd > /dev/null
echo "Actual FREESURFER_HOME $freesurfer_home_true"

set DateString = "`date '+%y%m%d%H%M'`"

# -superclean deletes everything except contents of mri/orig
if($DoSuperClean) then
  echo "super-cleaning..."
  set cmd = (rm -Rfv \
    $subjdir/label \
    $subjdir/scripts \
    $subjdir/stats \
    $subjdir/surf \
    $subjdir/tmp \
    $subjdir/touch \
    $subjdir/trash \
    $subjdir/mri/transforms)
  echo "$cmd"
  if($RunIt) $cmd
  set cmd = (rm -v $subjdir/mri/* $subjdir/mri/.xdebug*)
  echo "$cmd"
  if($RunIt) $cmd
endif

cd $subjdir # This variable is set in check_params
mkdir -p mri scripts surf tmp label touch stats touch trash
mkdir -p mri/transforms mri/transforms/bak mri/orig
set touchdir = $subjdir/touch

# Move the subject-specific config files from their temporary locations. I know redirecting cat to
# copy these files to the scripts dir seems unnecessary, but often times tmp files have strict
# permissions, and there's no easy, non-buggy way to copy files while ignoring perms on OSX (on
# GNU it's pretty straightforward). This method is the best portable option I can think of.
rm -f scripts/recon-config.yaml scripts/unknown-args.txt
cat $tmp_config > scripts/recon-config.yaml
cat $tmp_unknown_args > scripts/unknown-args.txt
rm -f $tmp_config $tmp_unknown_args

# Create cmd and env files from scratch
if(! $DoVersionsOnly) then
  set CF = ($subjdir/scripts/$CF_DEFAULT_NAME)
  # rm -f $CF, let it accumulate commands
  echo "\n\n#---------------------------------" >> $CF
  echo "# New invocation of recon-all `date` " >> $CF
  # Create a separate file for the env
  set ENVF = $subjdir/scripts/recon-all.env
  if(-e $ENVF) mv -f $ENVF $ENVF.bak
  date                                     >> $ENVF
  echo "FREESURFER_HOME $FREESURFER_HOME"  >> $ENVF
  echo "Actual FREESURFER_HOME $freesurfer_home_true"  >> $ENVF
  pwd                                      >> $ENVF
  echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" >> $ENVF
  echo $inputargs                          >> $ENVF
  uname -a                                 >> $ENVF
  echo ""                                  >> $ENVF
  if(-e /etc/os-release) cat /etc/os-release >> $ENVF
  echo ""                                  >> $ENVF
  limit                                    >> $ENVF
  echo ""                                  >> $ENVF
  printenv                                 >> $ENVF
endif

if($DoVersionsOnly) then
  if (-e /dev/stdout) then
    set LF = /dev/stdout
    set SF = /dev/stdout
  else
    set LF = /dev/null
    set SF = /dev/null
  endif
endif

# ------------ Create the log file --------------- #
if($#LF == 0) then
  set LF = ($subjdir/scripts/$LF_DEFAULT_NAME)
  if(-e $LF) then
    ls -l $LF
    if(! $AppendLog) then
      mv -f $LF $LF.old
    else
      # if running using -make, then dont bother with repeated info dumps
      if ($?RECONALL_MAKE_SUBJECT) goto skip_new_invo
      echo "\n\n"  >> $LF
      echo "#New# invocation of recon-all "  >> $LF
      echo "\n\n"  >> $LF
    endif
  endif
else
  if(-e $LF) then
    if ($?RECONALL_MAKE_SUBJECT) goto skip_new_invo
    echo "\n\n"  >> $LF
    echo "#New# invocation of recon-all "  >> $LF
    echo "\n\n"  >> $LF
  endif
endif
skip_new_invo:

echo "" >> $LF
date >> $LF
echo "cd `$PWD`" >> $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" >> $LF
echo $0 $inputargs >> $LF
echo "" >> $LF

# if running using -make, then dont bother with repeated info dumps
if ($?RECONALL_MAKE_SUBJECT) goto skip_all_info
echo "subjid $subjid" >> $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" >> $LF
echo "FREESURFER_HOME $FREESURFER_HOME" >> $LF
echo "Actual FREESURFER_HOME $freesurfer_home_true" >> $LF
if (-e $FREESURFER_HOME/build-stamp.txt) then
  echo "build-stamp.txt: `cat $FREESURFER_HOME/build-stamp.txt`" >> $LF
endif
uname -a | tee -a $LF
if(-e /etc/os-release) cat /etc/os-release | tee -a $LF
limit >> $LF
if (-e /usr/bin/free) then
  echo "" >> $LF
  /usr/bin/free --human >> $LF
  echo "" >> $LF
endif
if ("`uname -s`" == "Darwin") then
  echo "" >> $LF
  /usr/bin/top -l 1 | grep PhysMem >> $LF
  echo "" >> $LF
endif
if($?PBS_JOBID) then
  # If the job has been submitted to launchpad, get jobid
  echo "pbsjob $PBS_JOBID"  >> $LF
endif
if($?SLURM_JOB_ID) then
  echo SLURM_JOB_ID $SLURM_JOB_ID >> $LF
endif

# check for existence of bc (binary calculator)
# some minimal installs of centos do not have it
set cmd = (which bc)
$cmd >& /dev/null
if($status) then
  echo "ERROR: OS is missing bc (binary calculator) utility" |& tee -a $LF
  exit 1;
endif

## gather all versions here
echo "########################################" >> $LF
echo "program versions used" >> $LF
echo $FS_RECON_VERSION       >> $LF
set allinfocmds = (\
	lta_convert \
	mri_and \
	mri_annotation2label \
	mri_aparc2aseg \
	mri_surf2volseg \
	mri_binarize \
	mri_ca_label \
	mri_ca_normalize \
	mri_ca_register \
	mri_cc \
	mri_compute_overlap \
	mri_compute_seg_overlap \
	mri_concat \
	mri_concatenate_lta \
	mri_convert \
	mri_diff \
	mri_edit_wm_with_aseg \
	mri_em_register \
	mri_fill \
	mri_fuse_segmentations \
	mri_fwhm \
	mri_gcut \
	mri_info \
	mri_label2label \
	mri_label2vol \
	mri_log_likelihood \
	mri_mask \
	mri_matrix_multiply \
	mri_normalize \
	mri_normalize_tp2 \
        mri_or \
	mri_relabel_hypointensities \
	mri_relabel_nonwm_hypos \
	mri_remove_neck \
	mri_robust_register \
	mri_robust_template \
	mris_anatomical_stats \
	mris_ca_label \
	mris_calc \
	mris_convert \
	mris_curvature \
	mris_curvature_stats \
	mris_diff \
	mris_divide_parcellation \
	mri_segment \
	mri_segstats \
	mris_euler_number \
	mris_fix_topology \
	mris_topo_fixer \
	mris_jacobian \
	mris_label2annot \
	mris_left_right_register \
	mris_place_surface \
	mrisp_paint \
	mris_register \
	mris_smooth \
	mris_sphere \
	mris_surface_stats \
	mri_stats2seg \
	mris_thickness \
	mris_thickness_diff \
	mris_topo_fixer \
	mri_surf2surf \
	mri_surf2vol \
	mri_surfcluster \
	mris_volmask \
	mri_tessellate \
	mri_vol2surf \
	mri_vol2vol \
	mri_voldiff \
	mri_watershed \
        tkregister2_cmdl \
)
# Note: these commands do not properly support -all-info and should be fixed:
# 	mri_add_xform_to_header mri_mc 	mri_deface mris_inflate 	talairach_afd
# 	mris_info 	talairach_avi
foreach cmd ($allinfocmds)
  $cmd -all-info >> $LF
  if($status) then
    echo "ERROR: Executable '${cmd} -all-info failed! Is it missing from the distribution?'" |& tee -a $LF
    exit 1;
  endif
end
mri_motion_correct.fsl -version >> $LF
#if (-e $FREESURFER_HOME/bin/flirt.fsl) flirt.fsl -version >> $LF
if(! $DoAntsN3 && ! $DoAntsN4) nu_correct -version >> $LF

# clean-up droppings
if(-e .xdebug_mris_curvature_stats) rm -f .xdebug_mris_curvature_stats
if(-e .xdebug_mris_calc) rm -f .xdebug_mris_calc


echo "#######################################" >> $LF
echo "GCADIR $GCADIR" >> $LF
echo "GCA $GCA" >> $LF
echo "GCASkull $GCASkull" >> $LF
echo "AvgCurvTif $AvgCurvTif" >> $LF
echo "GCSDIR $GCSDIR" >> $LF
echo "GCS $GCS" >> $LF
echo "#######################################" >> $LF
skip_all_info:

if($DoVersionsOnly) exit 0;

# Delete the error and done files
rm -f $DoneFile
rm -f $ErrorFile

# ------------ Create the IsRunning File --------- #
if($DoIsRunning) then
  set IsRunningLH   = $subjdir/scripts/IsRunning.lh
  set IsRunningRH   = $subjdir/scripts/IsRunning.rh
  set IsRunningLHRH = $subjdir/scripts/IsRunning.lh+rh
  set bailfile = ();
  if($#hemilist == 1) then
    set hemi = $hemilist;
    set IsRunningFile = $subjdir/scripts/IsRunning.$hemi
    if(-e $IsRunningLHRH) set bailfile = $IsRunningLHRH
  else
    set IsRunningFile = $subjdir/scripts/IsRunning.lh+rh
    if(-e $IsRunningLH)   set bailfile = $IsRunningLH
    if(-e $IsRunningRH)   set bailfile = $IsRunningRH
  endif
  if(-e $IsRunningFile) set bailfile = $IsRunningFile
  if($#bailfile) then
    echo ""
    echo "ERROR: it appears that recon-all is already running"
    echo "for $subjid based on the presence of $bailfile. It could"
    echo "also be that recon-all was running at one point but"
    echo "died in an unexpected way. If it is the case that there"
    echo "is a process running, you can kill it and start over or"
    echo "just let it run. If the process has died, you should type:"
    echo ""
    echo " rm $bailfile"
    echo ""
    echo "and re-run. Or you can add -no-isrunning to the recon-all"
    echo "command-line. The contents of this file are:"
    echo "----------------------------------------------------------"
    cat  $bailfile
    echo "----------------------------------------------------------"
    exit 1;
  endif
  echo "------------------------------" > $IsRunningFile
  echo "SUBJECT $subjid" >> $IsRunningFile
  echo "HEMI    $hemilist"  >> $IsRunningFile
  echo "DATE `date`"     >> $IsRunningFile
  echo "USER $user"      >> $IsRunningFile
  echo "HOST `hostname`" >> $IsRunningFile
  echo "PROCESSID $$ "   >> $IsRunningFile
  echo "PROCESSOR `uname -m`" >> $IsRunningFile
  echo "OS `uname -s`"       >> $IsRunningFile
  uname -a         >> $IsRunningFile
  echo $FS_RECON_VERSION    >> $IsRunningFile
  if($?PBS_JOBID) then
    echo "pbsjob $PBS_JOBID"  >> $IsRunningFile
  endif
endif

# ------- Check FREESURFER_HOME consistency --------------#
set CSDF = $subjdir/scripts/csurfdir
if($DoCleanCSDF) rm -vf $CSDF
if(-e $CSDF) then
  set tmp = `cat $CSDF`;
  if($tmp != $FREESURFER_HOME) then
   echo "INFO: current FREESURFER_HOME does not match that of previous processing." \
     | tee -a $LF
   echo "    Current: $FREESURFER_HOME" | tee -a $LF
   echo "    Previous: $tmp" | tee -a $LF
   sleep 1;
  endif
endif

# --------------- Create the status file ---------------- #
if($#SF == 0) then
  set SF = ($subjdir/scripts/$SF_DEFAULT_NAME)
  if(-e $SF) then
    if(! $AppendStatus) then
       mv -f $SF $SF.old
    else
      echo "\n\n"  >> $SF
      echo "#New# invocation of recon-all "  >> $SF
      echo "\n\n"  >> $SF
    endif
  endif
else
  if(-e $SF) then
    echo "\n\n"  >> $SF
    echo "#New# invocation of recon-all "  >> $SF
    echo "\n\n"  >> $SF
  endif
endif
echo "status file for recon-all" >> $SF
date >> $SF

# Put a copy of myself (this script) in the scripts dir
if ("`uname -s`" == "Linux") then
  set FullProgName = `readlink -f $0`; 
  cp $FullProgName $subjdir/scripts/recon-all.local-copy
endif

# Wait for a file to appear #
if($#WaitForFile != 0) then
  echo "Waiting for $WaitForFile" |& tee -a $SF |& tee -a $LF
  echo "  WaitSleep $WaitSleep" |& tee -a $SF |& tee -a $LF
  echo "  nWaitsMax $nWaitsMax" |& tee -a $SF |& tee -a $LF
  @ nWaits = 1;
  while(! -e $WaitForFile && $nWaits < $nWaitsMax)
    sleep $WaitSleep;
    @ nWaits = $nWaits + 1;
  end
  if(! -e $WaitForFile ) then
    echo "ERROR: timed out waiting for $WaitForFile"
    goto error_exit;
  endif
  echo "Finished Waiting `date`" |& tee -a $SF |& tee -a $LF
endif

if( ! $RunIt) then
  echo "INFO: -dontrun flag is in effect, so subsequent commands" |& tee -a $LF
  echo "may not have accurate arguments!" |& tee -a $LF
endif

if ( $DoRestart) then
    if( -e $RestartFile) then
        echo "Restart file $RestartFile exists <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
        goto Restart
    endif
endif

#------------         --------------#
##-----------  -clean --------------#
#------------         --------------#
if($DoCleanSeed) then
  set cmd = ("mv -f $subjdir/scripts/seed-*.crs.man.dat $subjdir/trash");
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanCW256) then
  set cmd = (mv -f $subjdir/tmp/cw256 $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanTal) then
  set cmd = (mv -f $subjdir/mri/transforms/talairach.xfm $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
  set cmd = (mv -f $subjdir/mri/orig_nu.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanLta) then
  set cmd = ("mv -f $subjdir/mri/transforms/*.lta $subjdir/trash")
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanPFH) then
  set cmd = (mv -f $subjdir/mri/optimal_preflood_height $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
  set cmd = (mv -f $subjdir/mri/optimal_skullstrip_invol $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanBM) then
  set cmd = (mv -f $subjdir/mri/brainmask.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanASeg) then
  set cmd = (mv -f $subjdir/mri/aseg.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
  set cmd = (mv -f $subjdir/mri/aseg.presurf.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
  set cmd = (mv -f $subjdir/mri/aseg.manedit.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanWM) then
  set cmd = (mv -f $subjdir/mri/wm.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
  set cmd = (mv -f $subjdir/mri/wm.seg.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanFilled) then
  set cmd = (mv -f $subjdir/mri/filled.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanCP) then
  set cmd = (mv -f $subjdir/tmp/control.dat $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanTWM) then
  set cmd = (mv -f $subjdir/tmp/twm.dat $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanBFSE) then
  set cmd = (mv -f $subjdir/mri/brain.finalsurfs.manedit.mgz $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanXopts) then
  set cmd = (mv -f $subjdir/scripts/expert-options $subjdir/trash)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd  |& tee -a $LF
endif
if($DoCleanT2) then
  set flist = ($mdir/T2.mgz $mdir/transforms/T2raw.lta $mdir/transforms/T2raw.auto.lta)
  foreach f ($flist)
    if(-e $f) then
      set cmd = (mv -f $f $subjdir/trash)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $cmd  |& tee -a $LF
    endif
  end
endif
if($DoCleanFLAIR) then
  set flist = ($mdir/FLAIR.mgz $mdir/transforms/FLAIRraw.lta $mdir/transforms/FLAIRraw.auto.lta)
  foreach f ($flist)
    if(-e $f) then
      set cmd = (mv -f $f $subjdir/trash)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $cmd  |& tee -a $LF
    endif
  end
endif


#------------ Handle Seed Points for Fill/Cut, and Watershed ---------------#
set seedfile = $subjdir/scripts/seed-pons.crs.man.dat
if($#PonsSeedCRS) then
  echo "# Manually specified seed CRS for Pons" > $seedfile
  echo $PonsSeedCRS >>  $seedfile
endif
if(-e $seedfile) set PonsSeedCRS = `cat $seedfile | grep -v \#`
set seedfile = $subjdir/scripts/seed-cc.crs.man.dat
if($#CCSeedCRS) then
  echo "# Manually specified seed CRS for CC" > $seedfile
  echo $CCSeedCRS >>  $seedfile
endif
if(-e $seedfile) set CCSeedCRS = `cat $seedfile | grep -v \#`
set seedfile = $subjdir/scripts/seed-lh.crs.man.dat
if($#LHSeedCRS) then
  echo "# Manually specified seed CRS for LH" > $seedfile
  echo $LHSeedCRS >>  $seedfile
endif
if(-e $seedfile) set LHSeedCRS = `cat $seedfile | grep -v \#`
set seedfile = $subjdir/scripts/seed-rh.crs.man.dat
if($#RHSeedCRS) then
  echo "# Manually specified seed CRS for RH" > $seedfile
  echo $RHSeedCRS >>  $seedfile
endif
if(-e $seedfile) set RHSeedCRS = `cat $seedfile | grep -v \#`

set seedfile = $subjdir/scripts/seed-ws.crs.man.dat
if($#WSSeedPoint) then
  echo "# Manually specified seed CRS for watershed" > $seedfile
  echo $WSSeedPoint >>  $seedfile
endif
if(-e $seedfile) set WSSeedPoint = `cat $seedfile | grep -v \#`

#------------ Control Points for Intensity Normalization -----------#
set ControlPointsFile = $subjdir/tmp/control.dat
if(-e $ControlPointsFile) then
  set UseControlPoints = 1;
endif

#------------ Control Points for Registration -----------#
set DefaultTWMControlPointsFile = $subjdir/tmp/twm.dat
if( $UseTWMControlPoints ) then
  #copy twmfile to $subjdir/tmp/twm.dat:
  set cmd = (mkdir -p ${subjdir}/tmp)
  echo "\n $cmd"|& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd |& tee -a $LF
  set cmd = (cp -vf ${TWMControlPointsFile} $DefaultTWMControlPointsFile)
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) $cmd |& tee -a $LF
  if($status) goto error_exit;
  set TWMControlPointsFile = $DefaultTWMControlPointsFile
else
  if (-e $DefaultTWMControlPointsFile) then
    set UseControlPoints = 1;
    set TWMControlPointsFile = $DefaultTWMControlPointsFile
  endif
endif

#----                      ----#
#---- Conform Width to 256 ----#
##---         -cw256       ----#
if( $DoConformWidth256) then
  echo "-cw256 option is now persistent (remove with -clean-cw256)" \
    |& tee -a $LF
  touch $subjdir/tmp/cw256
endif

#-----------              -----------#
##----------  -show-edits -----------#
#-----------              -----------#
# discover which edits a user has made, list them, and if volume edits were
# made, create a file which shows them (using mri_compile_edits)
if($DoShowEdits) then
  @ edit_count = 0;
  echo "-----------------------------------------------" |& tee -a $LF
  echo "Subject $subjid has the following edits..." |& tee -a $LF

  # control points
  if(-e $ControlPointsFile) then
    @ edit_count = $edit_count + 1;
    set num_cps = (`grep numpoints $ControlPointsFile | awk '{print $2}'`)
    echo "$num_cps control points declared in file $ControlPointsFile" |& tee -a $LF
  endif

  # seeds
  set seedfile = $subjdir/scripts/seed-pons.crs.man.dat
  if(-e $seedfile) then
    @ edit_count = $edit_count + 1;
    echo "Manually specified seed CRS for Pons in file $seedfile" |& tee -a $LF
  endif
  set seedfile = $subjdir/scripts/seed-cc.crs.man.dat
  if($#CCSeedCRS) then
    @ edit_count = $edit_count + 1;
    echo "Manually specified seed CRS for CC in file $seedfile" |& tee -a $LF
  endif
  set seedfile = $subjdir/scripts/seed-lh.crs.man.dat
  if($#LHSeedCRS) then
    @ edit_count = $edit_count + 1;
    echo "Manually specified seed CRS for LH in file $seedfile" |& tee -a $LF
  endif
  set seedfile = $subjdir/scripts/seed-rh.crs.man.dat
  if($#RHSeedCRS) then
    @ edit_count = $edit_count + 1;
    echo "Manually specified seed CRS for RH in file $seedfile" |& tee -a $LF
  endif

  set seedfile = $subjdir/scripts/seed-ws.crs.man.dat
  if($#WSSeedPoint) then
    @ edit_count = $edit_count + 1;
    echo "Manually specified seed CRS for watershed in file $seedfile" \
        |& tee -a $LF
  endif

  # expert opts
  if($#XOptsFile != 0) then
    if (-e $XOptsFile) then
      @ edit_count = $edit_count + 1;
      echo "Expert options declared in file $XOptsFile" |& tee -a $LF
    endif
  endif
  if($#GlobXOptsFile != 0) then
    if (-e $GlobXOptsFile) then
      @ edit_count = $edit_count + 1;
      echo "Global expert options declared in file $GlobXOptsFile" |& tee -a $LF
    endif
  endif

  # talairach.xfm
  set xfm = $subjdir/mri/transforms/talairach.xfm
  set xfma = $subjdir/mri/transforms/talairach.auto.xfm
  if(-e $xfm && -e $xfma) then
    diff $xfm $xfma >& /dev/null
    if($status) then
      @ edit_count = $edit_count + 1;
      echo "The talairach.xfm file appears to have been edited" |& tee -a $LF
   endif
  endif

  # cw256
  if(-e $subjdir/tmp/cw256) then
    @ edit_count = $edit_count + 1;
    echo "Conform-width (reduce FOV) to 256 is enabled" |& tee -a $LF
  endif

  # volume edits, as determined by mri_compile_edits:
  # brainmask.mgz, aseg.presurf.mgz, brain.finalsurfs.mgz, wm.mgz, brain.mgz
  set compile_edits=($subjdir/tmp/compile_edits)
  set cmd = (mri_compile_edits ${subjid} $subjdir/mri/edits.mgz)
  if($RunIt) then
    if ( -e $compile_edits) rm -f $compile_edits
    $cmd |& tee -a $LF |& tee -a $compile_edits
    set vol_edits=(`grep mri_compile_edits_found $compile_edits | awk '{print $1}'`)
    if($#vol_edits != 0) then
      @ edit_count = $edit_count + $vol_edits;
    endif
  endif

  # summarize
  echo "$edit_count edits were found for subject $subjid" |& tee -a $LF

endif


#-----------               -----------#
#-----------  Longitudinal -----------#
##---------- -long and -tp ----------#
#-----------               -----------#
if($longitudinal && ! $LongSamseg) then
  # if adding a new timepoint was requested by -addtp flag
  if($DoAddTp) then
    echo "Adding $tpNid as timepoint to base $longbaseid" |& tee -a $LF
    set cmd = (mri_add_new_tp $longbaseid $tpNid)
    if($RunIt) $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif

  set cmd = (rca-long-tp-init -long $tpNid $longbaseid -s $subjid -log $LF -cf $CF -sf $SF)
  if($UseLongbaseCtrlVol) set cmd = ($cmd -uselongbasectrlvol)
  if($#hemilist == 1) set cmd = ($cmd -hemi $hemilist)
  set xopts = `fsr-getxopts rca-base-init $V8XoptsFile $GlobXOptsFile $XOptsFile`;
  set cmd = ($cmd $xopts)
  if($RunIt == 0) set cmd = ($cmd -dontrun)
  echo $cmd
  $cmd 
  if($status) goto error_exit

  # init regfile variable with map cross_tp to base:
  # used later in many places
  set tpNtobase_regfile = ${longbasedir}/mri/transforms/${tpNid}_to_${longbaseid}.lta

  # map control.dat file from the cross-sectional data for this subj
  if ( -e ${SUBJECTS_DIR}/${tpNid}/tmp/control.dat && ! $UseLongbaseCtrlVol ) then
    # only if it does not already exist:
    if ( ! -e ${subjdir}/tmp/control.dat ) then
      # The code that was here now in rca-long-tp-init
      set UseControlPoints = 1;
    endif
  endif
endif
if($longitudinal && $LongSamseg) then
  set cmd = (rca-long-tp-init -long-samseg $longbaseid $subjid -log $LF -cf $CF -sf $SF)
  echo $cmd 
  $cmd 
  if($status) goto error_exit
endif

#-----------                  -----------#
#----------- Convert T1 Input -----------#
##----------    -i <file>     -----------#
#-----------                  -----------#
if($#InputList != 0) then
  @ nth = 1;
  foreach InputVol ($InputList:q)
    set nthid = `printf %03d.mgz $nth`
    set cmd = (mri_convert "$InputVol" $subjdir/mri/orig/$nthid)
    $PWD |& tee -a $LF
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd:q |& tee -a $LF
      if($status) goto error_exit;
    endif
    # sanity-check: make sure each input has the same dimensions
    if ($nth == 1) then
      # assume first input has 'correct' dimensions
      set firstInput = $subjdir/mri/orig/$nthid
      set rows = `mri_info --nrows $firstInput |& tail -n 1`
      set cols = `mri_info --ncols $firstInput |& tail -n 1`
      set slices = `mri_info --nslices $firstInput |& tail -n 1`
    else
      # check subsequent against the first input
      set nextInput = $subjdir/mri/orig/$nthid
      set nrows = `mri_info --nrows $nextInput |& tail -n 1`
      set ncols = `mri_info --ncols $nextInput |& tail -n 1`
      set nslices = `mri_info --nslices $nextInput |& tail -n 1`
      if (($nrows != $rows) || ($ncols != $cols) || ($nslices != $slices)) then
        echo "ERROR: inputs have mismatched dimensions!" |& tee -a $LF
        echo "$firstInput is" |& tee -a $LF
        echo "$rows x $cols x $slices while" |& tee -a $LF
        echo "$InputVol is" |& tee -a $LF
        echo "$nrows x $ncols x $nslices" |& tee -a $LF
        goto error_exit;
      endif
    endif
    @ nth = $nth + 1;
  end # loop over input list
endif

#-----------                          -----------#
#----------- Input T2 or FLAIR images -----------#
##---------- -T2 <file> -FLAIR <file> -----------#
#-----------                          -----------#
if ($DoConvertT2Input || $DoConvertFlairInput) then

  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# T2/FLAIR Input `date`" \
    |& tee -a $SF |& tee -a $LF |& tee -a $CF

  if ($DoConvertT2Input) then
    set cmd = (mri_convert \
        --no_scale 1 \
        $InputT2Vol \
        $subjdir/mri/orig/T2raw.mgz)
    $PWD |& tee -a $LF
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

  if ($DoConvertFlairInput) then
    set cmd = (mri_convert \
        --no_scale 1 \
        $InputFlairVol \
        $subjdir/mri/orig/FLAIRraw.mgz)
    $PWD |& tee -a $LF
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

endif

#-----------                         -----------#
#----------- Input custom brain mask -----------#
#-----------      -xmask <file>       -----------#
#-----------                         -----------#

if ($#CustomMaskInput) then

  echo "#--------------------------------------------" |& tee -a $LF |& tee -a $CF
  echo "#@# Brain Mask Input `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF

  set cmd = (mri_convert --no_scale 1 $CustomMaskInput $subjdir/mri/orig/rawmask.mgz)
  $PWD |& tee -a $LF
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) then
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif

endif

#-------------                                                 ------------#
#------------- Longitudinal 'base' subject input file creation ------------#
##------------                   -base                         ------------#
#-------------                                                 ------------#
# #DNG MoveToBaseScript
if ($DoCreateBaseInput && $DoCreateBaseSubj) then
  echo "#--------------------------------------------" |& tee -a $LF |& tee -a $CF
  echo "#@# Longitudinal Base Subject Creation `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir > /dev/null
  $PWD |& tee -a $LF
  set cmd = (rca-base-init -base $subjid)
  foreach s ($BaseSubjsList)
    set cmd = ($cmd -tp $s)
  end
  set cmd = ($cmd -log $LF -cf $CF -sf $SF)
  set xopts = `fsr-getxopts rca-base-init $V8XoptsFile $GlobXOptsFile $XOptsFile`;
  set cmd = ($cmd $xopts)
  if($RunIt) then
    # Don't use fs_time or capture output because it will be captured by rca-base-init
    echo $cmd
    $cmd 
    if($status) goto error_exit
  endif
endif
#-----------             -------------#
##---------- AUTORECON 1 -------------#
#-----------             -------------#

set origvol = $subjdir/mri/orig.mgz
set rawavg  = $subjdir/mri/rawavg.mgz

#-----------                            -----------#
#----------- Motion Correct and Average -----------#
##----------        -motioncor          -----------#
#-----------                            -----------#
if($DoMotionCor) then
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# MotionCor `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF

  set origvol = $subjdir/mri/orig.mgz

  if($longitudinal) then
    # Code that was here  now in rca-long-tp-init
    goto motioncor_post_process
  endif 

  # base processing (we do not need to do anything,
  #   as orig should be there, rawavg is not there, due to difficulties of
  #   averaging different image geometries across time)
  if($DoCreateBaseSubj) then
    goto motioncor_post_process
  endif

  # default processing:
  set cmd = ();

  # Get list of input run directories #
  set RunList = ();
  ls $subjdir/mri/orig/[0-9][0-9][0-9].mgz >& /dev/null
  if(! $status) then
    set RunList = `ls $subjdir/mri/orig/[0-9][0-9][0-9].mgz`;
  else
    # No runs found
    ls $subjdir/mri//[0-9][0-9][0-9].mgz >& /dev/null
    if(! $status) then
      set RunList = `ls $subjdir/mri//[0-9][0-9][0-9].mgz`;
    endif
  endif
  if($#RunList == 0 && $RunIt) then
    echo "ERROR: no run data found in $subjdir/mri. Make sure to" \
      |& tee -a $LF
    echo "have a volume called 001.mgz in  $subjdir/mri/orig." |& tee -a $LF
    echo "If you have a second run of data call it 002.mgz, etc." \
      |& tee -a $LF
    echo "See also: http://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/Conversion" \
      |& tee -a $LF
    goto error_exit;
  else
    if ($RunIt) then
      echo "Found $#RunList runs" |& tee -a $LF
      foreach run ($RunList)
        echo $run |& tee -a $LF
      end
    endif
  endif

  # sanity-check: check if the input contains multiple frames, which would
  # be the case if a multi-echo frame mprage was accidently used as input.
  # without this check, andre is unhappy
  foreach RunVol ($RunList)
    echo "Checking for (invalid) multi-frame inputs..." |& tee -a $LF
    set nframes = `mri_info --nframes $RunVol |& tail -n 1`
    if ($nframes != 1) then
      echo "ERROR: input(s) cannot have multiple frames!" |& tee -a $LF
      echo "$RunVol has $nframes frames" |& tee -a $LF
      if ($nframes == 4) then
        echo "If this is a multi-frame MEMPRAGE image," |& tee -a $LF
        echo "use mri_concat --rms to combine echo frames." |& tee -a $LF
      endif
      goto error_exit;
    endif
  end

  # Only one run, copy to rawavg
  if($#RunList == 1) then
    set ud = `UpdateNeeded $rawavg $RunList`
    if($ud || $ForceUpdate) then
      echo "Only one run found so motion"|& tee -a $LF
      echo "correction will not be performed. I'll"|& tee -a $LF
      echo "copy the run to rawavg and continue."|& tee -a $LF
      sleep 2s;
      set cmd = (cp $RunList $rawavg)
      echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
      if($RunIt) then
        sleep 1; # Sleep here to assure that they have diff time stamps
        $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    else
      echo "INFO: $rawavg does not need updating" | tee -a $LF
    endif
  endif

  # Actually perform the motion correction -- creates rawavg
  if($#RunList > 1) then
    # set names for ltas
    set RunLtas = ""
    set RunIscales = ""
    foreach nthid ($RunList)
      set nthname=`basename $nthid .mgz`
      set nthdir=`dirname $nthid`
      set nthlta=${nthdir}/${nthname}.lta
      set RunLtas=($RunLtas $nthlta)
      set RunIscales=($RunIscales ${nthdir}/${nthname}-iscale.txt)
    end

    set ud = `UpdateNeeded $rawavg $RunList`
    if($ud || $ForceUpdate) then
      if($DoRobustMotionCor) then
        set cmd = (mri_robust_template)
        set cmd = ($cmd --mov ${RunList})
        set cmd = ($cmd --average 1)
        set cmd = ($cmd --template ${rawavg})
        set cmd = ($cmd --satit)
        set cmd = ($cmd --inittp 1)
        set cmd = ($cmd --fixtp)
        set cmd = ($cmd --noit)
        set cmd = ($cmd --iscale)
        set cmd = ($cmd --iscaleout $RunIscales)
        set cmd = ($cmd --subsample 200)
        set cmd = ($cmd --lta $RunLtas)
      else
        # use FSL's flirt to do motion correction (averaging of runs)
        set cmd = (mri_motion_correct.fsl -o $rawavg -wild $RunList)
      endif
      echo "#-----------------------------------------------"
      $PWD |& tee -a $LF
      echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
        echo $cmd > $touchdir/motion_correct.touch
      endif
    else
      echo "INFO: $rawavg does not need updating" | tee -a $LF
    endif
  endif

  # output some basic info about rawavg
  set cmd = (mri_info $rawavg)
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) then
    echo "rawavg.mgz ========================================" | tee -a $LF
    $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif

  set synthsr = $subjdir/mri/rawavg.synthsr.mgz
  if($DoSynthSR) then
    set ud = `UpdateNeeded $synthsr $rawavg`
    if($ud || $ForceUpdate) then
      set cmd = (mri_synthsr --threads $OMP_NUM_THREADS --i $rawavg --o $synthsr)
      echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
      if($RunIt) then
        $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    endif
  endif
  if(-e $synthsr) then
    echo "Found synthsr, so using that" | tee -a $LF
    set rawavg = $synthsr
  endif

  # At this point, rawavg.mgz exists. Use it to create orig.mgz,
  # conform to COR FOV but keep mgz format. Also add tal.xfm to header
  # eventhough it does not exist yet. 
  set ud = (`UpdateNeeded $origvol $rawavg`)
  if($ud || $ForceUpdate) then
    set cmd = (mri_convert $rawavg $origvol)
    if($UseCubic) set cmd = ($cmd -rt cubic)
    if($ConformKeepDC) set cmd = ($cmd --conform-dc)
    if($ConformMin) then
      set cmd = ($cmd --conform_min)
    else
      set cmd = ($cmd --conform)
      if($DoConformWidth256 || -e $subjdir/tmp/cw256) then
        # force conform width to 256
        set cmd = ($cmd --cw256)
        # see note just below on when -cw256 is necessary (ie, when FOV > 256)
      endif
    endif
    $PWD |& tee -a $LF
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      echo $cmd > $touchdir/conform.touch
    endif
    # Add xfm to orig, even though it does not exist yet. This is a
    # compromise to keep from having to change the time stamp of the
    # orig volume after talairaching. DNG moved this here on 5/18/22.
    set cmd = (mri_add_xform_to_header -c \
               $subjdir/mri/transforms/talairach.xfm \
               $origvol $origvol)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  else
    echo "INFO: $origvol does not need updating"  | tee -a $LF
  endif

  # output some basic info about orig.mgz
  set cmd = (mri_info $origvol)
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) then
    echo "orig.mgz ========================================" | tee -a $LF
    $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif

  # this is the goto target for longitudinal processing (from above):
  motioncor_post_process:

  # check if FOV > 256 and error exit if so
  set FOV=`mri_info ${origvol} | grep fov: | awk '{print $2}'`
  set FOV_gt_256=`echo "${FOV} > 256" | bc`
  if ($FOV_gt_256) then
    echo "\n****************************************" |& tee -a $LF
    echo "ERROR! FOV=${FOV} > 256" |& tee -a $LF
    echo "Include the flag -cw256 with recon-all!" |& tee -a $LF
    echo "Inspect orig.mgz to ensure the head is fully visible." |& tee -a $LF
    echo "****************************************\n" |& tee -a $LF
    goto error_exit;
  endif

endif # Motion Correction

# Explicitly create an LTA to go from rawavg/native space to orig
if(-e $rawavg) then
  set lta = $mdir/rawavg2orig.lta 
  set ud = `UpdateNeeded $lta $origvol $rawavg`
  if($ud || $ForceUpdate) then
    set cmd = (lta_convert --inlta identity.nofile --src $rawavg \
      --trg $origvol --outlta $lta --subject $subjid)
    echo $cmd | tee -a $LF
    if($RunIt) then
      fs_time $cmd |& tee -a $LF
      if($status) goto error_exit
    endif
  endif
endif

# Should vsinus and mca be masked out here?
set synthstrip = $mdir/synthstrip.mgz
if($SynthStrip) then
  set ud = `UpdateNeeded $synthstrip $origvol`
  if($ud || $ForceUpdate) then
    set xopts = `fsr-getxopts synthstrip $V8XoptsFile $GlobXOptsFile $XOptsFile`;
    set cmd = (mri_synthstrip --threads $OMP_NUM_THREADS -i $origvol -o $synthstrip)
    if($UseGPU) set cmd = ($cmd --gpu)
    set cmd = ($cmd $xopts)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif
endif

set synthseg = $subjdir/mri/synthseg.rca.mgz
set synthsegcsv = $subjdir/stats/synthseg.vol.csv
if($UseSynthSeg || $CblumFromSynthSeg || $SynthSegForSurf || $FixVSinus) then
  # Note: no m3z will be produced.
  set origvol  = $subjdir/mri/orig.mgz
  set ud = `UpdateNeeded $synthseg $origvol`
  if($ud || $ForceUpdate) then
    set xopts = `fsr-getxopts synthseg $V8XoptsFile $GlobXOptsFile $XOptsFile`;
    set cmd = (mri_synthseg --i $origvol --o $synthseg --threads $OMP_NUM_THREADS \
       --vol $synthsegcsv --keepgeom --addctab $xopts)
    if(! $UseGPU)  set cmd = ($cmd --cpu)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      if(! $CblumFromSynthSeg && ! $SynthSegForSurf) then
        pushd $subjdir/mri 
        rm -f aseg.auto_noCCseg.mgz
        ln -sf synthseg.rca.mgz aseg.auto_noCCseg.mgz
        popd
      endif
    endif
  endif
  if(0 && ! $CblumFromSynthSeg  && ! $SynthSegForSurf) then
    set xopts = `fsr-getxopts seg2recon $V8XoptsFile $GlobXOptsFile $XOptsFile`;
    set cmd = (seg2recon --s $subjid --seg $synthseg --i $origvol --threads $OMP_NUM_THREADS)
    if(-e $synthstrip) set cmd = ($cmd --m $synthstrip)
    set cmd = ($cmd $xopts)
    if($#XOptsFile) set cmd = ($cmd --expert $XOptsFile)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    # seg2recon will create a brainmask.mgz. Below, synthstrip will re-create it,
    # but it should be identical.
  endif
endif


set synthsegtiv = $subjdir/stats/synthseg.tiv.dat
if(-e $synthsegcsv) then
  set ud = `UpdateNeeded $synthsegtiv $synthsegcsv`
  csvprint --csv $synthsegcsv --f "total intracranial" > $synthsegtiv
endif

if($UseSamseg) then
  # what to do if have T2, FLAIR, long, etc?
  set origvol = $subjdir/mri/orig.mgz
  set samsegdir = $subjdir/mri/samseg.rca
  set ud = `UpdateNeeded $samsegdir/seg.mgz $origvol`
  if($ud || $ForceUpdate) then
    set xopts = `fsr-getxopts samseg $V8XoptsFile $GlobXOptsFile $XOptsFile`;
    set cmd = (samseg --t1w $origvol --refmode t1w --o $samsegdir \
      --threads $OMP_NUM_THREADS --hires $xopts)
    # --save-probabilities -- this probably not needed now
    # always use hires here to prevent conforming as input will be desired 
    # shape regardless
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif
  # Need to add fix for hypos and vents
  set cmd = (samseg2recon --s $subjid --samseg $samsegdir --from-recon-all) 
  if($ForceUpdate) set cmd = ($cmd force-update)
  set xopts = `fsr-getxopts samseg2recon $V8XoptsFile $GlobXOptsFile $XOptsFile`;
  if(-e $synthstrip) set cmd = ($cmd --m $synthstrip)
  set cmd = ($cmd $xopts)
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) then
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

# MOD: this takes the externally supplied mask and resamples it into the
# orig space so that it can be used with mri_em_register
if($#EMRegMaskArg != 0) then
  set cmd = (mri_vol2vol --mov $EMRegMaskArg --targ ${subjdir}/mri/orig.mgz\
    --regheader --interp nearest --o ${subjdir}/mri/extern.emreg.mask.mgz)
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) then
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
  set EMRegMask = extern.emreg.mask.mgz
endif

#-----------          -----------#
##----------  -deface -----------#
#-----------          -----------#
if($DoDeface) then
  echo "#--------------------------------------------" |& tee -a $LF |& tee -a $CF
  echo "#@# Deface `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  set cmd = (mri_deface orig.mgz \
     $FREESURFER_HOME/average/$brain_template \
     $FREESURFER_HOME/average/$face_template \
     orig_defaced.mgz)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  touch $touchdir/deface.touch
endif

#-----------             -----------#
##----------  -talairach -----------#
#-----------             -----------#
if($DoTalairach) then
talairach:
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# Talairach `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF
  set xfma = transforms/talairach.auto.xfm
  set xfm = transforms/talairach.xfm
  if ($longitudinal) then
    # longitudinal processing:
    if( -e $longbasedir/mri/$xfm) then
      set tal_xfm = $xfm
    else
      set tal_xfm = $xfma
    endif
    # copy from the base (as we are now in same space)
    # if edits were made to base, they will be also in long
    set cmd = (cp $longbasedir/mri/$tal_xfm $subjdir/mri/$xfma)

  else if ($DoSamsegReg) then

    # Use samseg talairach registration
    set cmd = (run_samseg -i orig.mgz -o samseg --reg-only)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    # Convert lta to talairach.xfm
    set cmd = (lta_convert --inlta samseg/samseg.talairach.lta --outmni $xfma)

  else
    # default processing:
    # first run bias correction...
    if ($DoTalairachUseNu) then
      # note that this only works if nu exists
      # this is used as an alternative if tal is giving bad results
      set tal_input = nu.mgz
    else
      # default: run one pass of nu_correct, as its been found that scans
      # with strong bias fields can cause talairach_avi to fail.  note that
      # this orig_nu.mgz uses the full head, whereas nu.mgz is created using
      # the brainmask, and talairach.xfm used to find the white matter ball.
      set tal_input = orig_nu.mgz
      set cmd = (mri_nu_correct.mni --no-rescale --i orig.mgz --o $tal_input)
      if($DoAntsN3) set cmd = ($cmd --ants-n3)
      if($DoAntsN4) set cmd = ($cmd --ants-n4)
      # -3T flag support:
      if ($DoNuIntensityCor3T) then
        # 3T params from Zheng, Chee, Zagorodnov 2009 NeuroImage paper
        # "Improvement of brain segmentation accuracy by optimizing
        # non-uniformity correction using N3"
        # namely specifying iterations, proto-iters and distance: 
        set cmd = ($cmd --n 1 --proto-iters 1000 --distance 50)
      else
        # 1.5T default: 
        # DNG: changed distance from 200 to 50 to match 5.3 
        set cmd = ($cmd --n 1 --proto-iters 1000 --distance 50)
      endif
      # allow expert-options override
      set xopts = `fsr-getxopts mri_nu_correct.mni $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = ($cmd $xopts)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    # now run the talairach registration...
    if ($UseMincMritotal) then
      # use the MINC mritotal utility
      set xopts = `fsr-getxopts talairach $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (talairach --i $tal_input --xfm $xfma $xopts)
    else
      # Avi Snyder's registration tools
      set xopts = `fsr-getxopts talairach_avi $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (talairach_avi --i $tal_input --xfm $xfma)
      if($?CustomTalAtlas && "$CustomTalAtlas" != "") then
        # use user-specified atlas found in average dir
        set cmd = ($cmd --atlas "$CustomTalAtlas")
      else
        if($UseYa3tTalAtlas) then
          # special atlas composed of young adults scanned at 3T
          set cmd = ($cmd --atlas 3T18yoSchwartzReactN32_as_orig)
        endif
      endif
      set cmd = ($cmd $xopts)
    endif
  endif
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if ( ! $UseMincMritotal && ! $DoSamsegReg ) then
    echo "talairach_avi log file is transforms/talairach_avi.log..." \
        |& tee -a $LF |& tee -a $CF
  endif
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;

  if( -e $xfm && ! $DoCleanTal) then
    echo "\nINFO: $xfm already exists!" \
        |& tee -a $LF |& tee -a $CF
    echo "The new $xfma will not be copied to $xfm" \
        |& tee -a $LF |& tee -a $CF
    echo "This is done to retain any edits made to $xfm" \
        |& tee -a $LF |& tee -a $CF
    echo "Add the -clean-tal flag to recon-all to overwrite $xfm\n" \
        |& tee -a $LF |& tee -a $CF
  endif

  if($DoCleanTal || ! -e $xfm) then
    if(-e $xfm) cp $xfm transforms/bak/talairach.xfm.$DateString
    set cmd = (cp $xfma $xfm)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) then
      sleep 2; # Sleep here to assure that they have diff time stamps
      $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

  echo $cmd > $touchdir/talairach.touch
endif

if($DoTalairach && ! $UseSynthMorph) then 
  # Always convert the talairach.xfm into an LTA
  cd $subjdir/mri > /dev/null
  set xfm = transforms/talairach.xfm 
  set lta = transforms/talairach.xfm.lta
  set ud = `UpdateNeeded $lta $xfm`
  if($ud) then
    set mni305 = $FREESURFER_HOME/average/mni305.cor.mgz
    set cmd = (lta_convert --src orig.mgz --trg $mni305 --inxfm $xfm \
        --outlta $lta --subject fsaverage --ltavox2vox)
    echo $cmd |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $cmd |& tee -a $LF
      if($status) then
        goto error_exit
      endif
    endif
  endif
endif

# If not using mri_em_register, then make simlinks to the ltas
pushd $SUBJECTS_DIR/$subjid/mri/transforms
if($EMRegStrip == 0) then
  set cmd = (ln -sf talairach.xfm.lta talairach_with_skull.lta)
  echo "$cmd" | tee -a $LF | tee -a $CF
  if($RunIt) $cmd |& tee -a $LF
endif
if($EMRegAseg == 0) then
  set cmd = (ln -sf talairach.xfm.lta talairach.lta)
  echo "$cmd" | tee -a $LF | tee -a $CF
  if($RunIt) $cmd |& tee -a $LF
endif
popd

# perform the failure detection scheme
if($DoTalCheck) then
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# Talairach Failure Detection `date`" \
    |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  # first run Laurence's AFD tool:
  set xopts = `fsr-getxopts talairach_afd $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set xfm = transforms/talairach.xfm
  set cmd = (talairach_afd -T 0.005 -xfm $xfm $xopts)
  set afdTestFailed = 0;
  $PWD |& tee -a $LF
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) then
    $fs_time $cmd |& tee -a $LF
    if($status) then
      set handleTalErrors = 1;
      goto handle_tal_error;
    endif
  endif
  # now run Avi's QA check on the results found in talairach_avi.log
  # see document RLB700_preprocessing_statistics.pdf for details
  set avilog = ($subjdir/mri/transforms/talairach_avi.log)
  if ( ! $UseMincMritotal && -e $avilog) then
    set cmd = (awk -f $FREESURFER_HOME/bin/extract_talairach_avi_QA.awk)
    set cmd = ($cmd $avilog)
    set qalog = ($subjdir/mri/transforms/talairach_avi_QA.log)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    set cmd2 = (tal_QC_AZS $avilog)
    set qalog2 = ($subjdir/mri/transforms/talairach_avi_QA2.log)
    echo "\n $cmd2 \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) then
      rm -f $qalog $qalog2
      $cmd >& $qalog
      if($status) then
        echo "ERROR: ${cmd} failed!  See logfile ${qalog}" |& tee -a $LF
        goto error_exit;
      endif
# tal_QC_AZS disabled:
# failing in weird ways. getting caught in infinite 'test' loops.
if (0) then
      $fs_time $cmd2 >& $qalog2
      set tal_QC_AZS_status = $status
      if($tal_QC_AZS_status) then
        echo "INFO: ${cmd2} failed!  See logfile ${qalog2}" |& tee -a $LF
        echo "      skipping tal_QC_AZS test" |& tee -a $LF
        #NJS: skip instead of exit because tal_QC_AZS doesnt work on centos5.4
        #goto error_exit;
      endif
endif
      # first set of QA data:
      set talAviQA=`grep "TalAviQA" ${qalog} | awk '{print $2}'`
      echo "TalAviQA: ${talAviQA}" |& tee -a $LF
      set mean=(0.9781) # buckner40 mean TalAviQA
      set std=(0.0044)  # buckner40 std TalAviQA
      set zscore=`echo "scale=0;(${talAviQA} - ${mean}) / ${std}" | bc`
      echo "z-score: ${zscore}" |& tee -a $LF
      set zscoreThreshold=(-9) # conservative value, but catches M.Harms subjs.
# tal_QC_AZS disabled:
if (0) then
      # second set:
      if ( ! $tal_QC_AZS_status ) then
        set talAviQA2=`grep "atlas_transform_error" ${qalog2} | awk '{print $6}'`
        echo "TalAviQA2: ${talAviQA2}" |& tee -a $LF
        set atlaserrhi=`echo "${talAviQA2} > 24" | bc`
        set atlaserrlo=`echo "${talAviQA2} < -60" | bc`
      else
        set talAviQA2=0
        set atlaserrhi=0
        set atlaserrlo=0
      endif
else
      set talAviQA2=0
      set atlaserrhi=0
      set atlaserrlo=0
endif
      # check scores:
      set handleTalErrors = 0;
      if (($zscore < $zscoreThreshold) || $atlaserrhi || $atlaserrlo) then
        echo "WARNING: Talairach QA check failed!" |& tee -a $LF
        echo "z-score of ${zscore} is <= threshold of ${zscoreThreshold}\n" \
             |& tee -a $LF
# tal_QC_AZS disabled:
if (0) then
        echo "or the atlas xform error of $talAviQA2 is < -60 | > 24" \
             |& tee -a $LF
endif
        set handleTalErrors = 1;
      endif

handle_tal_error:
      if ($handleTalErrors) then
        echo "\nManual Talairach alignment may be necessary, or" |& tee -a $LF
        echo "include the -notal-check flag to skip this test," |& tee -a $LF
        echo "making sure the -notal-check flag follows -all" |& tee -a $LF
        echo "or -autorecon1 in the command string." |& tee -a $LF
        echo "See:\n" |& tee -a $LF
        echo "http://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/Talairach" \
            |& tee -a $LF
        echo "" |& tee -a $LF
        # IF Talairach alignment was run
        # AND it was using the default (711-2C) atlas
        # AND a check failed,
        # THEN first retry avi method using newer 3T Schwartz atlas 
        # THEN (if that fails) try Talairach alignment using MINC mritotal tool
        # ELSE error exit
        if($DoTalairach && ! $UseMincMritotal && ! $longitudinal && \
           ! $UseYa3tTalAtlas ) then
          echo "INFO: Retrying Talairach align using 3T-based atlas...\n" \
            |& tee -a $LF
          set UseYa3tTalAtlas = 1; # try 3T-based atlas
          set UseMincMritotal = 0;
          set DoCleanTal = 1;
          goto talairach;
        else if($DoTalairach && ! $UseMincMritotal && ! $longitudinal) then
          echo "INFO: Trying MINC mritotal to perform Talairach align...\n" \
            |& tee -a $LF
          set UseMincMritotal = 1;
          set DoCleanTal = 1;
          goto talairach;
        else
          echo "\nERROR: Talairach failed!\n" |& tee -a $LF
          goto error_exit;
        endif
      endif
    endif
  endif
endif

set synthmorphdir = ()
if($UseSynthMorph) then
  # Affine registration to the mni305 to create talairach.xfm
  set cmd = (rca-talairach --s $subjid --threads $OMP_NUM_THREADS)
  if($ForceUpdate) set cmd = ($cmd --force)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) then
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
  set synthmorphdir = $mdir/transforms/synthmorph.1.0mm.1.0mm
  # Nonlinear reg to 152. This will use nu by default so spec orig
  set xopts = `fsr-getxopts fs-synthmorph-reg $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (fs-synthmorph-reg --s $subjid --threads $OMP_NUM_THREADS \
    --i $subjdir/mri/orig.mgz --test)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) then
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#-----------                         -----------#
#----------- Nu Intensity Correction -----------#
##----------     -nuintensitycor  (see also -skip-nu-intensity-cor) -----------#
#----------- Creates nu.mgz          -----------#
if($DoNuIntensityCor) then
  echo "#--------------------------------------------"  |& tee -a $LF |& tee -a $CF
  echo "#@# Nu Intensity Correction `date`"  |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri 
  set ud = `UpdateNeeded nu.mgz orig.mgz`
  if($ud || $ForceUpdate) then
    set xopts = `fsr-getxopts mri_nu_correct.mni $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mri_nu_correct.mni --i orig.mgz --o nu.mgz)
    # to fix a problem with mri_nu_correct.mni messing with the histogramming
    # in some odd subjects (due to voxels outside the brain, which has the
    # effect of altering white matter intensity interpretation downstream),
    # the inclusion of talairach.xfm with mri_nu_correct.mni causes
    # mri_make_uchar to run, which uses the Tal xform to find a ball of voxels
    # that are mostly brain. The top of the intensity histogram in this ball
    # will then be white matter, which allows us to center it at the desired
    # value, approximately (110).
    if ($DoNuMakeUchar) then
      if ( ! -e transforms/talairach.xfm && $RunIt) then
        echo "WARNING: transforms/talairach.xfm does not exist!" \
          |& tee -a $LF
        echo "It will not be used by mri_nu_correct.mni." \
          |& tee -a $LF
      else
        set cmd = ($cmd --uchar transforms/talairach.xfm)
      endif
    endif
    # --cm for hi-res support:
    if ($ConformMin) set cmd = ($cmd --cm)
    # -3T flag support:
    if ($DoNuIntensityCor3T) then
      # 3T params from Zheng, Chee, Zagorodnov 2009 NeuroImage paper
      # "Improvement of brain segmentation accuracy by optimizing
      # non-uniformity correction using N3"
      # namely specifying iterations, proto-iters and distance: 
      set NuIterations = 1;
      set cmd = ($cmd --proto-iters 1000 --distance 50)
    endif
    # add user-specified option (from an 'experts file')
    set cmd = ($cmd --n $NuIterations)
    if($DoAntsN3) set cmd = ($cmd --ants-n3)  # ignores other options
    if($DoAntsN4) set cmd = ($cmd --ants-n4)  # ignores other options
    set cmd = ($cmd $xopts)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    # Add xfm to nu
    set cmd = (mri_add_xform_to_header -c \
               $subjdir/mri/transforms/talairach.xfm \
               nu.mgz nu.mgz)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif
  # done:
  date > $touchdir/nu.touch
endif

if($SkipNuIntensityCor) then
  # -skip-nu-intensity-cor. If this is set, then DoNuIntensityCor is
  # going to be set to 0
  # Create a link nu.mgz to orig.mgz
  pushd $subjdir/mri 
  rm -f nu.mgz
  ln -sf orig.mgz nu.mgz
  popd
endif

#-----------                          -----------#
#----------- Intensity Normalization1 -----------#
##----------      -normalization      -----------#
#-----------  Creates T1.mgz          -----------#
if($DoNormalization) then
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# Intensity Normalization `date`" \
    |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF
  set xopts = `fsr-getxopts mri_normalize $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  if ( $longitudinal && $UseLongbaseCtrlVol) then
    # longitudinal processing stream AND using ctrl_vol.mgz from base:
    if( ! -e $longbasedir/mri/ctrl_vol.mgz || \
        ! -e $longbasedir/mri/bias_vol.mgz ) then
      echo "Recompute intensity norm to create $longbaseid ctrl_vol.mgz" \
        |& tee -a $LF
      set cmd = (mri_normalize)
      if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
      if($#Norm3dIters)  set cmd = ($cmd -n $Norm3dIters)
      if($#Norm1_b)      set cmd = ($cmd -b $Norm1_b)
      if($#Norm1_n)      set cmd = ($cmd -n $Norm1_n)
      if($IsMPRAGE)      set cmd = ($cmd -mprage)
      if($IsWashuMPRAGE) set cmd = ($cmd -washu_mprage)
      set cmd = ($cmd \
        -mask $longbasedir/mri/brain.mgz \
        -W $longbasedir/mri/ctrl_vol.mgz $longbasedir/mri/bias_vol.mgz \
        $longbasedir/mri/nu.mgz \
        $longbasedir/mri/T1_tmp.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      if( ! -e $longbasedir/mri/ctrl_vol.mgz ) then
        echo "ERROR: unable to generate cntl-point volume for longbase" \
          |& tee -a $LF
        goto error_exit;
      endif
      rm -f $longbasedir/mri/T1_tmp.mgz
    endif
    # use ctrl_vol.mgz from base for normalization:
    set cmd = (mri_normalize)
    if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd \
      -w $subjdir/mri/ctrl_vol.mgz $subjdir/mri/bias_vol.mgz \
      -l $longbasedir/mri/ctrl_vol.mgz $longbasedir/mri/bias_vol.mgz \
      $subjdir/mri/nu.mgz \
      $subjdir/mri/T1.mgz)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  else
    if ( $longitudinal ) then
      # the longitudinal stream skips the talairach step, so orig_nu does not
      # get created, so create it now...
      set cmd = (mri_nu_correct.mni --no-rescale --i orig.mgz --o orig_nu.mgz)
      # -3T flag support:
      if ($DoNuIntensityCor3T) then
        # 3T params from Zheng, Chee, Zagorodnov 2009 NeuroImage paper
        # "Improvement of brain segmentation accuracy by optimizing
        # non-uniformity correction using N3"
        # namely specifying iterations, proto-iters and distance: 
        set cmd = ($cmd --n 1 --proto-iters 1000 --distance 50)
      else
      # 1.5T default:
        set cmd = ($cmd --n 1 --proto-iters 1000 --distance 200)
      endif
      # allow expert-options override
      set xopts = `fsr-getxopts mri_nu_correct.mni $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      if($DoAntsN3) set cmd = ($cmd --ants-n3)  # ignores other options
      if($DoAntsN4) set cmd = ($cmd --ants-n4)  # ignores other options
      set cmd = ($cmd $xopts)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd >& orig_nu.log
      if($status) goto error_exit;
    endif
    # for cross, base (and long if not useLongBaseCtrlVol) processing streams:
    set cmd = (mri_normalize -g $NormMaxGrad);
    if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    if($UseControlPoints) set cmd = ($cmd -f $ControlPointsFile)
    if($#Norm3dIters)     set cmd = ($cmd -n $Norm3dIters)
    if($#Norm1_b)         set cmd = ($cmd -b $Norm1_b)
    if($#Norm1_n)         set cmd = ($cmd -n $Norm1_n)
    if($IsMPRAGE)         set cmd = ($cmd -mprage)
    if($IsWashuMPRAGE)    set cmd = ($cmd -washu_mprage)
    if($ConformMin)       set cmd = ($cmd -noconform)
    # in base create the ctrl_vol.mgz for init longs later:
    if($DoCreateBaseSubj) set cmd = ($cmd -W ctrl_vol.mgz bias_vol.mgz)
    set cmd = ($cmd $xopts nu.mgz T1.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
  echo $cmd > $touchdir/inorm1.touch
endif

# Segment MCA/dura here to be able to pass it to mri_watershed
set mcadura = $mdir/mca-dura.mgz
if($FixMCADura) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "\n#@# MCADura Segmentation `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  set nu = $mdir/nu.mgz
  set ud = `UpdateNeeded $mcadura $nu`
  if($ud || $ForceUpdate) then
    set cmd = (mri_mcadura_seg --i $nu --o $mcadura --threads $OMP_NUM_THREADS)
    if($#synthmorphdir) set cmd = ($cmd --synthmorphdir $synthmorphdir);
    set xopts = `fsr-getxopts mri_mcadura_seg $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd  $xopts)
    echo $cmd | tee -a $LF
    if($RunIt) $cmd | tee -a $LF
    if($status) goto error_exit;
  else
    echo "MCADura Segmentation does not need to be updated" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  endif
endif

# Segment venous sinuses here to be able to pass it to mri_watershed
# Could get synthmorph dir from above (just affine so not big deal)
set vsinus = $mdir/vsinus.mgz
if($FixVSinus) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "\n#@# VSinus Segmentation `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  set nu = $mdir/nu.mgz
  set ud = `UpdateNeeded $vsinus $nu`
  if($ud || $ForceUpdate) then
    set cmd = (mri_vsinus_seg --s $subjid --rca-synthseg --threads $OMP_NUM_THREADS $xopts)
    if($#synthmorphdir) set cmd = ($cmd --synthmorphdir $synthmorphdir);
    set xopts = `fsr-getxopts mri_vsinus_seg $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd  $xopts)
    echo $cmd | tee -a $LF
    if($RunIt) $cmd | tee -a $LF
    if($status) goto error_exit;
  else
    echo "VSinus Segmentation does not need to be updated" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  endif
endif

if($DoSkullStrip && $SynthStrip) then
  # This will be redundant with seg2recon above (but identical)
  set T1 = $mdir/T1.mgz
  set BM = $mdir/brainmask.mgz
  set ud = `UpdateNeeded $BM $T1 $synthstrip`
  if($ud || $ForceUpdate) then
    set cmd = (mri_mask $T1 $synthstrip $BM)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    # Moved mcadura and vsinus masking to brain.finalsurfs
    if(0 && $FixMCADura) then
      set cmd = (mri_mask -invert $BM $mdir/mca-dura.mgz $BM)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) then
        $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    endif
    if(0 && $FixVSinus) then
      set cmd = (mri_mask -invert $BM $mdir/vsinus.mgz $BM)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) then
        $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    endif
  endif
endif

#-----------                 -----------#
#----------- Skull Stripping -----------#
##----------   -skullstrip   -----------#
#-----------                 -----------#
if($DoSkullStrip && ! $SynthStrip) then
skullstrip:
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# Skull Stripping `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF

  set BM  = brainmask.mgz

  if ($longitudinal) then
    # longitudinal processing stream (copy from base):
    # Code that copied brainmask now in rca-long-tp-init
    set bmbase = brainmask_${longbaseid}.mgz
    set BMA = brainmask.auto.mgz
    set BM  = brainmask.mgz

    # first apply mask and keep deletion edits (1)
    set cmd = (mri_mask -keep_mask_deletion_edits)
    set cmd = ($cmd T1.mgz ${bmbase} ${BMA})
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    # then transfer the 255 edits (still keep deletions)
    set cmd = (mri_mask -transfer 255)
    set cmd = ($cmd -keep_mask_deletion_edits)
    set cmd = ($cmd $BMA ${bmbase} $BMA)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    goto skipped_skullstrip;
  endif

  # base subject stream:
  if($DoCreateBaseSubj) then
    set BMA = brainmask.auto.mgz
    set BM  = brainmask.mgz  #used later 
    # Cannot move below to rca-base-init because of T1.mgz
    # Create brainmask.auto by applying brainmask_template to T1
    # first apply mask and keep deletion edits (1)
    set cmd = (mri_mask -keep_mask_deletion_edits)
    set cmd = ($cmd T1.mgz brainmask_template.mgz $BMA)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    # then copy over the 255 (edits) and still keep deletions (1)
    set cmd = (mri_mask -transfer 255)
    set cmd = ($cmd -keep_mask_deletion_edits)
    set cmd = ($cmd $BMA brainmask_template.mgz $BMA)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    goto skipped_skullstrip; 
  endif 

  # If custom mask was provided, skip automated skull stripping
  if ( -e $subjdir/mri/orig/rawmask.mgz ) then
    goto skipped_skullstrip;
  endif

  # default stream...
  set xopts = `fsr-getxopts mri_watershed $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set opts = ();
  if($WaterShed == 0) set opts = ($opts -n);
  if($WaterShed == 2) set opts = ($opts -wat);
  if($WaterShed == 3) set opts = ($opts -wat+temp);
  if($WaterShed == 4) set opts = ($opts -atlas);
  if($WSLess) set opts = ($opts -less);
  if($WSMore) set opts = ($opts -more);
  if($WSAtlas) set opts = ($opts -atlas);
  if($WSCopy) set opts = ($opts -copy);
  if($#WSSeedPoint != 0) set opts = ($opts -s $WSSeedPoint);
  if($#WSPctPreFlood != 0) then
    set opts = ($opts -h $WSPctPreFlood);
    set DoMultiStrip = 0
  else if( -e optimal_preflood_height) then
    set WSPctPreFlood = `cat optimal_preflood_height`
    set opts = ($opts -h $WSPctPreFlood);
    set DoMultiStrip = 0
    echo "Using optimal preflood height of $WSPctPreFlood" |& tee -a $LF
  endif

  # Originally, I had set this up to mask the mcadura and vsinus from
  # mask from the get-go. But the inorm is so sensitive that this
  # masking ends up having downsteram repurcusions. So masking has
  # been moved to the creation of the brain.finalsurfs where it will
  # only affect the surfaces.
  #if($FixMCADura) set opts = ($opts -xmask $mcadura)
  #if($FixVSinus)  set opts = ($opts -xmask $vsinus)

  set cmd = (mri_watershed)
  set BM  = brainmask.mgz

  if ($WSGcaAtlas || $DoMultiStrip) then
    if ( ! $WSUseTalXfm) then # dont bother if using talairach.xfm
      # if using the GCA atlas to help with the skull-strip, then run the
      # GCA registration (mri_em_register) to align to an atlas with a skull,
      # unless that file already exists
      if ( ! -e transforms/talairach_with_skull.lta || $DoCleanLta ) then
        if($EMRegStrip) then
          set xopts2 = `fsr-getxopts mri_em_register $V8XoptsFile $GlobXOptsFile $XOptsFile `;
          set cmd2 = (mri_em_register)
	  set cmd2 = ($cmd2 $nocerebellum )
	  if ($LHonly) set cmd2 = ($cmd2 -lh )
	  if ($RHonly) set cmd2 = ($cmd2 -rh )
          set cmd2 = ($cmd2 -skull)
          set cmd2 = ($cmd2 $xopts2 nu.mgz ${GCADIR}/$GCASkull)
          set cmd2 = ($cmd2 transforms/talairach_with_skull.lta)
          echo "\n $cmd2 \n"|& tee -a $LF |& tee -a $CF
          if($RunIt) $fs_time $cmd2 |& tee -a $LF
          if($status) goto error_exit;
          echo $cmd2 > $touchdir/skull.lta.touch
        endif
        # else just use talairach.xfm.lta 
      endif
    endif

    if ($WSGcaAtlas) then
      # if just using -brain_atlas flag, then include necessary options
      if ($WSUseTalXfm) then
        set opts = (-brain_atlas ${GCADIR}/$GCASkull \
                    transforms/talairach.xfm $opts)
      else
        set opts = (-brain_atlas ${GCADIR}/$GCASkull \
                    transforms/talairach_with_skull.lta $opts)
      endif
    endif
  endif

  if($DoMultiStrip) then

    # when DoMultiStrip is enabled, multiple instances of mri_watershed are
    # run each using the following preflood height parameters
    if ( $?WATERSHED_PREFLOOD_HEIGHTS ) then
      # externally specified in the environment
      set PREFLOOD_HEIGHTS = ( $WATERSHED_PREFLOOD_HEIGHTS )
    else
      # defaults:
      set PREFLOOD_HEIGHTS = ( 5 10 20 30 )
    endif
    set SS_VOLUMES = ( orig orig_nu T1 )
    if ( $?GOTO_LL_CALC ) goto ll_calc

    # create command files, one job for each volume type and preflood height...
    set CMDFS = ()
    foreach vol ( $SS_VOLUMES )
      foreach pfh ( $PREFLOOD_HEIGHTS )
        set cmd = (mri_watershed)
        set BMA_OLD = brainmask.auto.mgz
        set BMA = brainmask_${vol}_PFH${pfh}.auto.mgz
        if(-e $BMA_OLD && -e $BM && ! $DoCleanBM) then
          set cmd = ($cmd -keep $BMA_OLD $BM $BMA)
        endif
        set cmd = ($cmd $opts -h ${pfh} $xopts ${vol}.mgz $BMA)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        set CMDF = mri_watershed_${vol}_PFH${pfh}.cmd
        echo "$cmd" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      end
    end

    # and launch parallel jobs and wait for completion.
    # the reconbatchjobs script will append each job output to $LF
    if($RunIt) then
      reconbatchjobs $LF $CMDFS
      if($status) then
        # don't exit, since some may encounter 'preflood height' failures
        echo "WARNING: Some multi-skullstrip operations may have failed!" \
            |& tee -a $LF |& tee -a $CF
        echo "         Continuing multi-skullstrip with the others..." \
            |& tee -a $LF |& tee -a $CF
      endif
    endif

    # brainmask volumes actually need to be T1 volumes, because while
    # mri_watershed may run best in some cases using orig.mgz as input,
    # we really want the brainmask to be from T1.mgz (post normalization)
    set CMDFS = ()
    foreach pfh ( $PREFLOOD_HEIGHTS )
      set BMA_ORIG = brainmask_orig_PFH${pfh}.auto.mgz
      if ( -e $BMA_ORIG ) then
        set cmd = (mri_mask T1.mgz $BMA_ORIG $BMA_ORIG)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        set CMDF = mri_mask_PFH${pfh}.cmd
        echo "$cmd" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      endif
    end

    # and launch parallel jobs and wait for completion.
    # the reconbatchjobs script will append each job output to $LF
    if($RunIt) then
      if($#CMDFS != 0) then
        reconbatchjobs $LF $CMDFS
        if($status) goto error_exit;
      endif
    endif
    echo $cmd > $touchdir/skull_strip.touch

    # calculate a measure of skull-strip performance (mri_log_likelihood):
    ll_calc:
    set max_ll = -9999999999;
    set best_pfh = 0;
    set best_vol = ();
    set xopts = `fsr-getxopts mri_log_likelihood $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    foreach vol ( $SS_VOLUMES )
      foreach pfh ( $PREFLOOD_HEIGHTS )
        set BMA = brainmask_${vol}_PFH${pfh}.auto.mgz
        if ( ! -e $BMA) continue;
        set LTA = transforms/talairach_with_skull.lta
        set cmd = (mri_log_likelihood -orig T1.mgz $BMA)
        set cmd = ($cmd $xopts ${GCADIR}/$GCA $LTA)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($RunIt) then
          $cmd |& tee -a $LF |& tee -a ll_tmp
          # extract the last line of output, containing the result
          set ll = `tail -n 1 ll_tmp`
          rm -f ll_tmp
        endif
        if($status) goto error_exit;
        # and make the best result the brainmask.auto.mgz
        if($RunIt) then
          echo "$BMA log_likelihood= $ll" |& tee -a $LF
          if ("$ll" == "nan") continue
          if ($ll > $max_ll) then
            set max_ll = $ll;
            set best_pfh = $pfh;
            set best_vol = $vol;
            rm -f brainmask.auto.mgz
            cp $BMA brainmask.auto.mgz
            if($status) goto error_exit;
          endif
        endif
      end
    end
    if($RunIt) then
      if ($best_pfh == 0) then
        echo "ERROR: failure in calculating best preflood height param." \
          |& tee -a $LF
        goto error_exit;
      endif
      echo ""
      echo "Optimal input vol: $best_vol, pre-flood height= $best_pfh, results in log_likelihood= $max_ll" \
        |& tee -a $LF
      #rm -f *_PFH*.auto.*
      #rm -f *_PFH*.*
      # save this result, so that it is used next time, negating the need
      # to run mulitstrip (parallel jobs) again
      echo "$best_vol" > optimal_skullstrip_invol
      echo "$best_pfh" > optimal_preflood_height
    endif
    echo $cmd > $touchdir/log_likelihood.touch
    # make sure this is set properly:
    set BMA = brainmask.auto.mgz

  else

    # single-job skull-strip (default)

    set BMA = brainmask.auto.mgz
    if(-e $BMA && -e $BM && ! $DoCleanBM) set cmd = ($cmd -keep $BMA $BM $BM)
    set INVOL = T1
    if( -e optimal_skullstrip_invol) set INVOL = `cat optimal_skullstrip_invol`
    if("$INVOL" == "T1") set opts = ( -T1 $opts )
    set cmd = ($cmd $opts $xopts $INVOL.mgz $BMA)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    if("$INVOL" == "orig") then
      # while mri_watershed may run best in some cases using orig.mgz as input,
      # we really want the brainmask to be from T1.mgz (post normalization)
      set cmd = (mri_mask T1.mgz $BMA $BMA)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/skull_strip.touch

  endif

  # Gcut:
  # Nanyang Technological University's skull-stripper, which is intended to
  # work best running after watershed.  it further removes dura.  see:
  # 'Skull Stripping Using Graph Cuts', Neuroimage, 2009
  # brainmask.gcuts.mgz is a debug file showing voxels that were cut.
  if($DoGcut) then
    set BMA = brainmask.auto.mgz
    set BGC = brainmask.gcuts.mgz
    set cmd = (rm -f $BGC)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $cmd |& tee -a $LF
    set xopts = `fsr-getxopts mri_gcut $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mri_gcut $xopts -110 -mult $BMA T1.mgz $BMA $BGC)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    echo "" |& tee -a $LF
    echo "INFO: Care must be taken to thoroughly inspect your data" \
        |& tee -a $LF
    echo "      when using mri_gcut. In particular, inspect the edges of" \
        |& tee -a $LF
    echo "      gm and cerebellum for over-aggressive cutting." |& tee -a $LF
    echo "      Add -segmentation brainmask.gcuts.mgz to the tkmedit" |& tee -a $LF
    echo "      command string to view the voxels which gcut has removed." |& tee -a $LF
    echo "" |& tee -a $LF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    # binarize the gcuts file, setting vals to label 999 which appears as red
    # when loaded as a segmentation
    if ( -e $BGC) then
      set cmd = (mri_binarize --i $BGC --o $BGC --binval 999 --min 1)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

  skipped_skullstrip:

  if( -e $BM && ! $DoCleanBM) then
    echo "\nINFO: brainmask.mgz already exists!" \
        |& tee -a $LF |& tee -a $CF
    echo "It will not be overwritten." \
        |& tee -a $LF |& tee -a $CF
    echo "This is done to retain any edits made to brainmask.mgz." \
        |& tee -a $LF |& tee -a $CF
    echo "Add the -clean-bm flag to recon-all to overwrite brainmask.mgz.\n" \
        |& tee -a $LF |& tee -a $CF
  endif

  if(! -e $BM || $DoCleanBM) then
    if( -e orig/rawmask.mgz ) then
      # Use custom mask if provided
      echo "Masking T1 with external brain mask" |& tee -a $LF
    
      # First resample mask to match orig.mgz
      set cmd = (mri_vol2vol --mov orig/rawmask.mgz --targ orig.mgz --regheader --o mask.mgz --nearest)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) then
        $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    
      # Now mask
      set cmd = (mri_mask T1.mgz mask.mgz $BM)
    else
      # Otherwise just copy auto brainmask
      set cmd = (cp $BMA $BM)
    endif
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) then
      sleep 1; # Sleep here to assure that they have diff time stamps
      $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

endif # Brainmask

#-----------             -------------#
##---------- AUTORECON 2 -------------#
#-----------             -------------#

#--------------                   ---------------#
#-------------- GCA Registration  ---------------#
##-------------      -gcareg      ---------------#
#-------------- Runs mri_em_register, creates talairach.lta ---------------#
if($DoGCAReg) then
  echo "#-------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# EM Registration `date`" |& tee -a $SF |& tee -a $LF  |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF
  set xopts = `fsr-getxopts mri_em_register $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  if(! $longitudinal) then
    # Note: longitudinal copy of talairach.lta now done in rca-long-tp-init
    # cross processing
    if($EMRegAseg) then
      set cmd = (mri_em_register)
      set cmd = ($cmd $nocerebellum )
      if ($LHonly) set cmd = ($cmd -lh  -spacing 4 -s 7)
      if ($RHonly) set cmd = ($cmd -rh  -spacing 4 -s 7)
      set lta = transforms/talairach.lta
      if($DoCreateBaseSubj) then
        # base subj processing (norm_template instead of nu, and no mask needed):
        set cmd = ($cmd -mask brainmask.mgz $xopts  norm_template.mgz ${GCADIR}/$GCA $lta)
      else
        # default processing:
        if($#GCAOutputName) set lta = transforms/talairach.$GCAOutputName.lta
        set cmd = ($cmd -uns 3 -mask $EMRegMask $xopts nu.mgz ${GCADIR}/$GCA $lta)
      endif
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      echo $cmd > $touchdir/em_register.touch
    else
      # Just use talairach.xfm.lta 
      if($RunIt) then
        pushd transforms
        set lta = talairach.lta
        if($#GCAOutputName) set lta = talairach.$GCAOutputName.lta
        ln -sf talairach.xfm.lta $lta
        popd
      endif
      touch $touchdir/em_register.touch
    endif
  endif
endif

#------------                         --------------#
#----------- Canonical Intensity Normalization -----#
##-----------         -canorm         --------------#
#------------ Creates norm.mgz        --------------#
if($DoCANormalize) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# CA Normalize `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF

  set lta = transforms/talairach.lta
  set norm = norm.mgz
  set ctrl_pts = ctrl_pts.mgz
  if($#GCAOutputName) then
    set lta = transforms/talairach.$GCAOutputName.lta
    set norm = norm.$GCAOutputName.mgz
    set ctrl_pts = ctrl_pts.$GCAOutputName.mgz
  endif

  # longitudinal copy of aseg now done in rca-long-tp-init

  set xopts = `fsr-getxopts mri_ca_normalize $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (mri_ca_normalize)
  if($UseCPsWithCaNorm)  set cmd = ($cmd -f $ControlPointsFile)
  set cmd = ($cmd $nocerebellum )
  if ($LHonly) set cmd = ($cmd -lh )
  if ($RHonly) set cmd = ($cmd -rh )
    
  if ($longitudinal) then
    # longitudinal processing:
    # use the aseg_base (just created) as initialization of the current TP:
    set cmd = ($cmd -long aseg_${longbaseid}.mgz)
  else
    # default stream
    set cmd = ($cmd -c $ctrl_pts)
  endif
  set cmd = ($cmd -mask brainmask.mgz $xopts)
  if($DoCreateBaseSubj) then
    # base subject stream
    # (use norm vol created during -base-init, no mask needed)
    set cmd = ($cmd norm_template.mgz)
  else
    # default stream
    set cmd = ($cmd nu.mgz)
  endif

  set cmd = ($cmd ${GCADIR}/$GCA $lta $norm)

  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/ca_normalize.touch

endif # DoCANormalize

#------------                        --------------#
#------------ Canonical Registration --------------#
##-----------        -careg          --------------#
#------------ mri_ca_register talairach.xfm --------------#
# This is what takes a long time
if($DoCAReg && ! ($UseSynthSeg && ! $UseSynthMorph)) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# CA Reg `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF

  set xopts = `fsr-getxopts mri_ca_register $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (mri_ca_register)
  set cmd = ($cmd $nocerebellum )
  if ($LHonly) set cmd = ($cmd -lh)
  if ($RHonly) set cmd = ($cmd -rh)
  if($#GCARegIterations) set cmd = ($cmd -n $GCARegIterations)
  if($#GCARegTol) set cmd = ($cmd -tol $GCARegTol)
  set lta = transforms/talairach.lta
  set m3z = transforms/talairach.m3z
  set norm = norm.mgz
  if($#GCAOutputName) then
    set lta = transforms/talairach.$GCAOutputName.lta
    set m3z = transforms/talairach.$GCAOutputName.m3z
    set norm = norm.$GCAOutputName.mgz
  endif
  if($UnCompress) set cmd = ($cmd -uncompress)
  if($BigVentricles) set cmd = ($cmd -bigventricles -smoothness 0.5)
  if( ! $BigVentricles) set cmd = ($cmd -nobigventricles)
  if($DoSecondPassRenorm) set cmd = ($cmd -secondpassrenorm)
  if( ! $longitudinal) set cmd = ($cmd -T $lta)
  if($UseTWMControlPoints) set cmd = ($cmd -twm $TWMControlPointsFile)
  if ( $longitudinal ) then
    # here is tpN's longitudinal command
    # init with warp (m3z) from base
    # no need to concatenate, as we are in same space now
    set cmd = ($cmd -levels 2 -A 1 \
                -l $longbasedir/mri/transforms/talairach.m3z \
                identity.nofile)
  endif

  set cmd = ($cmd $UseCAAlignAfter)
  set cmd = ($cmd -mask brainmask.mgz)
  set cmd = ($cmd $xopts $norm ${GCADIR}/$GCA $m3z)
  set deps = ($norm)
  if(! $longitudinal) set deps = ($deps $lta)
  if(  $longitudinal) set deps = ($deps $longbasedir/mri/transforms/talairach.m3z)
  set ud = `UpdateNeeded $m3z $deps`
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  set st = $status
  if($st) then
    echo "ERROR: mri_ca_register with non-zero status $st" |& tee -a $LF
    #echo "but continuing despite the error" |& tee -a $LF
    goto error_exit;
  endif

  echo $cmd > $touchdir/ca_register.touch
endif

#------------                                    --------------#
#------------ Removes neck and part of the face  --------------#
##----------- -rmneck, needed if doing SkullLTA  --------------#
#------------                                    --------------#
if($DoRemoveNeck) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# Remove Neck `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  set xopts = `fsr-getxopts mri_remove_neck $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set xform = (transforms/talairach.m3z)
  if ( ! -e $xform) then
    echo "INFO: $xform not found, using talairach.lta instead" \
      |& tee -a $LF |& tee -a $CF
    set xform = (transforms/talairach.lta)
  endif
  set cmd = (mri_remove_neck -radius $RmNeckRadius $xopts \
             nu.mgz $xform \
             ${GCADIR}/$GCA nu_noneck.mgz)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/mri_remove_neck.touch
endif

#------------                                       --------------#
#------------ Recompute lta with skull but no neck  --------------#
##-----------              -skull-lta               --------------#
#------------                                       --------------#
if($DoSkullLTA) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# SkullLTA `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  set xopts = `fsr-getxopts mri_em_register $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (mri_em_register)
  set cmd = ($cmd $nocerebellum )
  if ($LHonly) set cmd = ($cmd -lh )
  if ($RHonly) set cmd = ($cmd -rh )
  set cmd = ($cmd -skull -t transforms/talairach.lta \
     $xopts nu_noneck.mgz ${GCADIR}/$GCASkull \
     transforms/talairach_with_skull_2.lta)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/skull_2.lta.touch
endif

if($FixEntoWM) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "\n#@# EntoWM Segmentation `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  set nu = $mdir/nu.mgz
  set entowm = $mdir/entowm.mgz  
  set entowmstats = $SUBJECTS_DIR/$subjid/stats/entowm.stats
  set ud = `UpdateNeeded $entowm $nu`
  if($ud || $ForceUpdate) then
    set xopts = `fsr-getxopts mri_entowm_seg $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    # --s uses nu and also outputs a .stats file
    set cmd = (mri_entowm_seg --s $subjid --conform --threads $OMP_NUM_THREADS $xopts)
    echo $cmd | tee -a $LF
    if($RunIt) $cmd | tee -a $LF
    if($status) goto error_exit;
  else
    echo "EntoWM Segmentation does not need to be updated" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  endif
  # Check for seg failure by checking whether the entowm volume is
  # less than 200 or the gyrus ambiens volume is less than 50. In the
  # manual data set the min entowm was 751 and the min GA was 217. A
  # "failure" could cause fix-ga in label-cortex to fail outright, but
  # also raises the question about whether this should be manually
  # edited if FixEntoWM or FixGA are to be used for any subject in the
  # study. Eg, if it is going to fail, it is likely to fail in cases
  # where there is a lot of atrophy. For studies with good data with
  # subjects without a ton of atrophy, the failure rates are low. In
  # FHS (N=6000) was less than 1%. FC1K (N=499) was less than 1%. In
  # IXI (N=526), none failed.  Buckner40 (N=40) was about 5%. But in
  # ADNI3 (N=2142), failure rate was about 4%, with CN at about 1%,
  # MCI at about 5-8%, and AD at about 30%. For ADNI1 (N=100), CN was
  # less than 1% and AD was 25%.
  grep -v \# $entowmstats | tee -a $LF
  set gaok = 1;
  foreach hemi ($hemilist)
    set vols = (`grep wm-$hemi $entowmstats | awk '{print $3}'`)
    if($vols[1] < 200 || $vols[2] < 50) set gaok = 0;
  end
  if(! $gaok) then
    echo "WARNING: entowm has very low volumes so not using it to edit GA of cortex label" | tee -a $LF
    set FixGA = 0
  endif
endif

#--------------                      --------------#
#-------------- SubCort Segmentation --------------#
##-------------        -calabel      --------------#
#--------------                      --------------#
if($DoCALabel  && ! $UseSynthSeg) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# SubCort Seg `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  set DoCCSeg = 1; # Force

  if($DoCleanASeg) then
    set cmd = (rm -f aseg.presurf.mgz aseg.manedit.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $cmd |& tee -a $LF
      if($status) goto error_exit;
  endif

  # ----------- Prior to changing aseg.auto.mgz ------------#
  if( -e aseg.presurf.mgz && -e aseg.auto.mgz ) then
    # aseg.presurf.mgz and aseg.auto.mgz DO exist (at least 2nd pass)
    if( ! -e aseg.manedit.mgz) then
      # aseg.manedit.mgz does NOT exist
      # Check for diffs between aseg.auto and aseg.presurf
      # Note: if there are no diffs, then aseg.manedit.mgz is not created
      set cmd = (mri_seg_diff --seg1 aseg.auto.mgz \
        --seg2 aseg.presurf.mgz --diff aseg.manedit.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if( ! $RunIt) then
        echo "INFO: mri_seg_diff was not actually executed," |& tee -a $LF
        echo "so subsequent commands (shown with -dontrun)" |& tee -a $LF
        echo "may not have accurate arguments!" |& tee -a $LF
      endif
      if($RunIt) $cmd |& tee -a $LF
      if($status) goto error_exit;
    else
      # aseg.manedit.mgz DOES exist
      # This has to be handled in two stages in case manedit itself has
      # been edited.
      # 1. Check for diffs between aseg.auto and aseg.presurf (new & old edits)
      set cmd = (mri_seg_diff --seg1 aseg.auto.mgz \
        --seg2 aseg.presurf.mgz --diff aseg.manedit.tmp.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if( ! $RunIt) then
        echo "INFO: mri_seg_diff was not actually executed," |& tee -a $LF
        echo "so subsequent commands (shown with -dontrun)" |& tee -a $LF
        echo "may not have accurate arguments!" |& tee -a $LF
      endif
      if($RunIt) $cmd |& tee -a $LF
      if($status) goto error_exit;
      # 2. Merge new and old edits with manedit. If manedit has not
      # been edited, then there will be no change.
      if(-e aseg.manedit.tmp.mgz) then
        set cmd = (mri_seg_diff --seg aseg.manedit.mgz \
          --diff-in aseg.manedit.tmp.mgz --merged aseg.manedit.mgz)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($RunIt) $cmd |& tee -a $LF
        if($status) goto error_exit;
        rm aseg.manedit.tmp.mgz
      endif
    endif
  endif

  # ------------ longitudinal (pre)processing ----------------#
  # fuse segmentations of subjects composing the 'longbase' subject
  # This cannot be moved to rca-long-tp-init because it needs norm.mgz
  if ($longitudinal && $UseAsegFusion) then
    cd $subjdir/mri > /dev/null
    $PWD |& tee -a $LF
    set BaseSubjsList = (`cat ${longbasedir}/${BaseSubjsListFname}`)
    set asegprecount = 0
    set aseg = ()
    set alt = ()
    set nocc = ()
    set norm = ()
    set trx = () # Cross to base.
    foreach s (${BaseSubjsList})
      set aseg = ($aseg ${SUBJECTS_DIR}/${s}/mri/aseg.presurf.mgz)
      set alt = ($alt ${SUBJECTS_DIR}/${s}/mri/aseg.mgz)
      set nocc = ($nocc ${SUBJECTS_DIR}/${s}/mri/aseg.auto_noCCseg.mgz)
      set norm = ($norm ${SUBJECTS_DIR}/${s}/mri/norm.mgz)
      set trx = ($trx ${longbasedir}/mri/transforms/${s}_to_${longbaseid}.lta)
      # check if all cross dirs have aseg.presurf 
      if ( -e $aseg[$#aseg] ) then
        @ asegprecount++
      endif
    end
    # if we are missing aseg.presurf, assume that cross is 5.3 or older
    # and use aseg.mgz for fusion
    if ( $#BaseSubjsList > $asegprecount ) then
      set aseg = ($alt)
    endif
    # now create the fused aseg
    set cmd = (mri_fuse_segmentations -a $aseg -c $nocc -n $norm -t $trx)
    set cmd = ($cmd norm.mgz aseg.fused.mgz)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

  #------------------- mri_ca_label ------------------------#
  # Run mri_ca_label to create aseg.auto_noCCseg.mgz
  set xopts = `fsr-getxopts mri_ca_label $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (mri_ca_label -relabel_unlikely 9 .3 -prior 0.5)
  set cmd = ($cmd $UseCAAlign)
  set cmd = ($cmd $nocerebellum )
  if ($LHonly) set cmd = ($cmd -lh )
  if ($RHonly) set cmd = ($cmd -rh )
  if($NoWMSA) set cmd = ($cmd -nowmsa)
  if($CblumFromSynthSeg) set cmd = ($cmd -cblum-from-seg $synthseg)
  set asegbasename=(aseg.auto_noCCseg)
  if($longitudinal) then
    # Initizlize long TP using ...
    if($UseAsegFusion) then
      # fused' aseg just created above
      set cmd = ($cmd -r $subjdir/mri/aseg.fused.mgz)
    endif
    if($UseAsegBase) then
      # aseg from base
      set cmd = ($cmd -r $longbasedir/mri/${asegbasename}.mgz)
    endif
    set cmd = ($cmd -ri $longbasedir/mri/${asegbasename}.label_intensities.txt)
  endif
  set cmd = ($cmd $xopts norm.mgz)
  set cmd = ($cmd transforms/talairach.m3z)
  set cmd = ($cmd ${GCADIR}/$GCA)
  set cmd = ($cmd ${asegbasename}.mgz)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) then
    $fs_time $cmd |& tee -a $LF
    # Create/delete a file to indicate whether Cblum is from SynthSeg
    set cblumfile = $subjdir/scripts/CblumFromSynthSeg.txt
    if($CblumFromSynthSeg) then
      touch $cblumfile
    else
      rm -f $cblumfile
    endif
  endif
  if($status) goto error_exit;
endif

Restart:

if ( $DoRestart) then
    if( ! -e $RestartFile) then
    else
        if($DoCALabel) then
            set DoCCSeg = 1; # Force
        endif
        mkdir -p mri
        cd mri
    endif
    echo "Restart: Label " `pwd` "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
    if( ! -e $RestartFile) then
        echo "Create Restart File $RestartFile <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
        tar cvf $RestartFile .
    else
        echo "Restart using $RestartFile  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
        tar xvf $RestartFile .
    endif
    printenv 
    set
endif


#--- Corpus Callosum Segmentation ---#
# Run mri_cc to create aseg.auto.mgz. Note that DoCCSeg
# will be 1 if CALabel is run. This just allows the recon-all -make
# to start from here if aseg.auto_noCCseg.mgz was modified
if($DoCCSeg) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# CC Seg `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  set DoASegMerge = 1; # Force
  set cmd = (seg2cc --s $subjid)
  if ($LHonly) set cmd = ($cmd -lh )
  if ($RHonly) set cmd = ($cmd -rh )
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
endif

# --------- Incorporate Manual ASeg Changes ----------------------
# Allow it to be done outside of CALabel. Note that DoASegMerge
# will be 1 if CCSeg (or CALabel) is run. This just allows the user to
# merge with Man Edits even if CALabel was not run, which will
# only have an effect if the user has actually changed aseg.manedit
if($DoASegMerge) then
  echo "#--------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# Merge ASeg `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  if(-e aseg.manedit.mgz ) then
    set cmd = (mri_seg_diff --seg aseg.auto.mgz \
      --diff-in aseg.manedit.mgz --merged aseg.presurf.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if( ! $RunIt) then
      echo "INFO: mri_seg_diff was not actually executed," |& tee -a $LF
      echo "so subsequent commands (shown with -dontrun)" |& tee -a $LF
      echo "may not have accurate arguments!" |& tee -a $LF
    endif
    if($RunIt) $cmd |& tee -a $LF
    if($status) goto error_exit;
  else
    set ud = `UpdateNeeded aseg.presurf.mgz aseg.auto.mgz`
    if($ud || $ForceUpdate) then
      set cmd = (cp aseg.auto.mgz aseg.presurf.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

  echo $cmd > $touchdir/asegmerge.touch
endif

#-----------                          -----------------#
#----------- Intensity Normalization2 -----------------#
##----------     -normalization2      -----------------#
#-----------                          -----------------#
if($DoNormalization2) then
  echo "#--------------------------------------------" \
    |& tee -a $LF  |& tee -a $CF
  echo "#@# Intensity Normalization2 `date`" \
    |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri 
  set deps = (aseg.presurf.mgz brainmask.mgz)
  if($UseControlPoints) set deps = ($deps $ControlPointsFile)
  if(! $NoNormMGZ) set deps = ($deps norm.mgz)
  set ud = `UpdateNeeded brain.mgz $deps`
  if($ud || $ForceUpdate) then
    set xopts = `fsr-getxopts mri_normalize $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mri_normalize);
    if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    if($UseControlPoints)   set cmd = ($cmd -f $ControlPointsFile)
    if($#Norm3dIters)       set cmd = ($cmd -n $Norm3dIters)
    if($#Norm2_b)           set cmd = ($cmd -b $Norm2_b)
    if($#Norm2_n)           set cmd = ($cmd -n $Norm2_n)
    if($IsMPRAGE)           set cmd = ($cmd -mprage)
    if($IsWashuMPRAGE)      set cmd = ($cmd -washu_mprage)
    if($ConformMin)         set cmd = ($cmd -noconform)
    if($UseAseg && ! $NoAsegInorm2) set cmd = ($cmd -aseg aseg.presurf.mgz)
    if($NoNormMGZ) then
      # norm.mgz doesnt exist with -noaseg or -nosubcortseg, so use brainmask.mgz
      set cmd = ($cmd $xopts brainmask.mgz brain.mgz)
    else
      set cmd = ($cmd -mask brainmask.mgz $xopts norm.mgz brain.mgz)
    endif
    $PWD |& tee -a $LF
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    echo $cmd > $touchdir/inorm2.touch
  endif
endif

#--------------                        ---------------#
#-------------- Create BrainFinalSurfs ---------------#
##-------------         -maskbfs       ---------------#
#--------------                        ---------------#
if($DoMaskBFS) then
  # This logic has become a mess
  echo "#--------------------------------------------" |& tee -a $LF  |& tee -a $CF
  echo "#@# Mask BFS `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  set xopts = `fsr-getxopts mri_mask $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  # Set threshold to WM_MIN_VAL=5
  set cmd = (mri_mask -T 5 $xopts brain.mgz brainmask.mgz brain.finalsurfs.mgz)
  $PWD |& tee -a $LF
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) then
    # Remove MCA/Dura/Vsinus here instead of at skull strip. See note above.
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    if($FixMCADura) then
      set cmd = (mri_mask -oval 1 -invert brain.finalsurfs.mgz $mcadura brain.finalsurfs.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    if($FixVSinus) then
      set cmd = (mri_mask -oval 1 -invert brain.finalsurfs.mgz $vsinus brain.finalsurfs.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif
  # If edits exist in local folder, transfer finalsurfs edits (voxels=255 and voxels=1).
  # Note that if cross or base edits exist, they should be transferred on the first 
  # round. If a manedit in long is created later, that will be incorporated on top
  # of the existing man edits from cross/base; the manedit from cross/base will no
  # longer be consdidered (but that's ok because the edits were already incorporated;
  # in theory, one should not change the manedit from cross or base once the long
  # is created).
  if( -e brain.finalsurfs.manedit.mgz ) then
    set cmd = (mri_mask -transfer 255)
    set cmd = ($cmd -keep_mask_deletion_edits)
    set cmd = ($cmd brain.finalsurfs.mgz brain.finalsurfs.manedit.mgz brain.finalsurfs.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  else 
    # Manedit does NOT exist in current folder
    # With the change below, both cross and base will have manedits. If no edits have been
    # made, then no change will be made to long bfs
    # If base manedit exists, copy edits to this. If not and cross manedit exists, use those
    set bfmanedit = ${SUBJECTS_DIR}/${tpNid}/mri/brain.finalsurfs.manedit.mgz # cross
    if($longitudinal && $LongTransferBaseBFS) then
      set bfmanedit = ${SUBJECTS_DIR}/${longbaseid}/mri/brain.finalsurfs.manedit.mgz # base
    endif
    if($longitudinal && -e $bfmanedit && ! $LongSamseg) then
      # Transfer any edits from cross or base to long. If no edits, then this has no effect
      set cmd = (mri_mask -transfer 255)
      set cmd = ($cmd -keep_mask_deletion_edits)
      if(! $LongTransferBaseBFS) set cmd = ($cmd -xform $tpNtobase_regfile)
      set cmd = ($cmd brain.finalsurfs.mgz)
      set cmd = ($cmd $bfmanedit)
      set cmd = ($cmd brain.finalsurfs.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    if($FixEntoWM) then
      # There is a question as to whether to do this in long because
      # ento was probably fixed in cross; this would add to that
      # fix. Probably not a big deal.
      # Level is hardcoded at 2. To change to 3 put 
      # "bfsfixentowm -sa-fix-ento-wm entowm.mgz 3 255 255" in the xopts
      set xopts = `fsr-getxopts bfsfixentowm $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (mri_edit_wm_with_aseg -sa-fix-ento-wm entowm.mgz 2 $IntensityBFS $IntensityBFS \
        $xopts brain.finalsurfs.mgz brain.finalsurfs.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    if($FixACJ) then
      set xopts = `fsr-getxopts bfsfixacj $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (mri_edit_wm_with_aseg -sa-fix-acj aseg.presurf.mgz $IntensityBFS $IntensityBFS \
        $xopts brain.finalsurfs.mgz brain.finalsurfs.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    # Copy brain.finalsurfs to manedit (applies to cross, base, and long)
    set cmd = (cp brain.finalsurfs.mgz brain.finalsurfs.manedit.mgz)
    echo $cmd | tee -a $LF
    if($RunIt) $cmd | tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------                 -------------------#
#---------------- WM Segmentation -------------------#
##---------------  -segmentation  -------------------#
#----------------                 -------------------#
if($DoSegmentation) then
  # It would be nice not to do this for longitudinal, but wm.mgz is
  # used in autodet gw stats and in mris_place_surfce to clip bright
  # values in the T1
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# WM Segmentation `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null

  set AllowLongWMtransfers = "1"
  if(! $DoCleanWM && -e wm.mgz) then
    # test if edits were made
    # count 255 edits:
    set cmd = (mri_binarize --i wm.mgz --min 255 --max 255 \
        --o wm255.mgz --count wm255.txt)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $cmd |& tee -a $LF
    if($status) goto error_exit;
    # count 1 edits:
    set cmd = (mri_binarize --i wm.mgz --min 1 --max 1 \
        --o wm1.mgz --count wm1.txt)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $cmd |& tee -a $LF
    if($status) goto error_exit;
    # remove unnecessary mgz's
    set cmd = (rm wm1.mgz wm255.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $cmd |& tee -a $LF
    if($status) goto error_exit;
    # get number of edits:
    set wm255=""
    if ( -e wm255.txt )  then
      set wm255 = `cat wm255.txt | awk ' { print $1 } '`
    endif
    set wm1=""
    if ( -e wm1.txt ) then
      set wm1 = `cat wm1.txt | awk ' { print $1 } '`
    endif

    # if edits exist:
    if ( "$wm1" != "0" || "$wm255" != "0" ) then
      echo "Found wm edits: $wm1 deletes, $wm255 fills" |& tee -a $LF
      set cmd = (cp wm.mgz wm.seg.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $cmd |& tee -a $LF
      if($status) goto error_exit;
      # wm.mgz was available (probably edited):
      # don't allow transfers in long below
      set AllowLongWMtransfers = "0"
    endif
  endif
  # ----------- Segment -------------------------
  if(! $WMSegFromASeg) then
    # Use the traditional mri_segment to generate the wm.seg.mgz
    set mrisegment_input = brain.mgz
    if($DoAntsDenoising) then
      set ud = `UpdateNeeded antsdn.brain.mgz brain.mgz`
      if($ud || $ForceUpdate) then
        set cmd = (AntsDenoiseImageFs -i brain.mgz -o antsdn.brain.mgz)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
      set mrisegment_input = antsdn.brain.mgz
    endif
    set ud = `UpdateNeeded wm.seg.mgz $mrisegment_input`
    if($ud || $ForceUpdate) then
      set xopts = `fsr-getxopts mri_segment $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (mri_segment -wsizemm $MriSegWsizemm);
      if ($NoThicken) set cmd = ($cmd -thicken 0)
      # note: check for wm.mgz happens so that -dontrun output is correct
      if(! $DoCleanWM && -e wm.mgz && -e wm.seg.mgz) set cmd = ($cmd -keep)
      if($IsMPRAGE)         set cmd = ($cmd -mprage)
      if($IsWashuMPRAGE)    set cmd = ($cmd -washu_mprage)
      set cmd = ($cmd $WMSeg_wlo $WMSeg_ghi $xopts $mrisegment_input wm.seg.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      rm -f $SUBJECTS_DIR/$subjid/scripts/wmseg-from-aseg
    endif
  else
    # Use the aseg to generate the wm.seg.mgz
    set cmd = (mri_binarize --i aseg.presurf.mgz --match 2 41 --o wm.mask-from-aseg.presurf.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    set cmd = (mri_mask brain.mgz  wm.mask-from-aseg.presurf.mgz wm.seg.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    # Force to uchar or else mri_edit_wm_with_aseg gets upset
    set cmd = (mri_convert wm.seg.mgz -odt uchar --no_scale 1 wm.seg.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    # Silly way to keep track of whether this was run or not
    touch $SUBJECTS_DIR/$subjid/scripts/wmseg-from-aseg
  endif
  # ----------- Edit with ASeg -------------------------
  if($UseAseg) then
    # Not sure update will work here since wm.mgz can be edited
    set xopts = `fsr-getxopts mri_edit_wm_with_aseg $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mri_edit_wm_with_aseg)
    if(! $DoCleanWM) set cmd = ($cmd -keep-in)
    if($FixEntoWM) set cmd = ($cmd -fix-ento-wm entowm.mgz 3 255 255)
    if($FixACJ)    set cmd = ($cmd -fix-acj $AsegForSurf 255 255)
    if($SynthSegForSurf) set cmd = ($cmd -wmsa aseg.presurf.mgz) # could use -fill-seg-wm
    if($UseSynthSeg) set cmd = ($cmd -fill-seg-wm) # no aseg to fill wmsas
    set cmd = ($cmd $xopts wm.seg.mgz brain.mgz $AsegForSurf wm.asegedit.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
  # ----------- PreTess -------------------------
  set xopts = `fsr-getxopts mri_pretess $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set wmlabelstring = "wm"
  if($UseAseg) then
    set WM_vol = wm.asegedit.mgz
  else
    set WM_vol = wm.seg.mgz
  endif
  if($NoNormMGZ) then
    set norm_vol = brain.mgz
  else
    set norm_vol = norm.mgz
  endif
  set cmd = (mri_pretess )
  if(! $DoCleanWM && -e wm.mgz) set cmd = ($cmd -keep)
  set cmd = ($cmd $xopts $WM_vol $wmlabelstring $norm_vol wm.mgz)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  if($FixEntoWM) then
    echo "Fixing entowm in wm.mgz"|& tee -a $LF |& tee -a $CF # because mri_pretess will alter it
    set cmd = (mri_edit_wm_with_aseg -sa-fix-ento-wm entowm.mgz 3 255 255 wm.mgz wm.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
  if($FixACJ) then
    echo "Fixing ACJ in wm.mgz"|& tee -a $LF |& tee -a $CF # because mri_pretess will alter it
    set cmd = (mri_edit_wm_with_aseg -sa-fix-acj $AsegForSurf 255 255 wm.mgz wm.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
  if($longitudinal && $AllowLongWMtransfers && ! $LongSamseg) then
    if ($UseLongbaseWMedits) then
      # transfer wm edits (voxels=255) from longbase wm.mgz to long tpN wm.mgz
      # and -keep_mask_deletion_edits transfers voxel-deletion (voxels=1) edits
      set cmd = (mri_mask -transfer 255)
      set cmd = ($cmd -keep_mask_deletion_edits)
      set cmd = ($cmd wm.mgz $longbasedir/mri/wm.mgz wm.mgz)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    else #default in -long:
      if(-e  ${SUBJECTS_DIR}/${tpNid}/mri/wm.mgz) then
        # transfer wm matter edits (voxels=255) from cross wm.mgz to long tpN wm.mgz
        # and -keep_mask_deletion_edits transfers voxel-deletion (voxels=1) edits
        set cmd = (mri_mask -transfer 255)
        set cmd = ($cmd -keep_mask_deletion_edits)
        set cmd = ($cmd -xform $tpNtobase_regfile)
        set cmd = ($cmd wm.mgz ${SUBJECTS_DIR}/${tpNid}/mri/wm.mgz wm.mgz)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    endif
  endif

  echo $cmd > $touchdir/wmsegment.touch
endif

#----------------        -------------------#
##---------------  -fill -------------------#
#----------------        -------------------#
if($DoFill && ! $longitudinal) then
  # Dont do this if long
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# Fill `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  set xopts = `fsr-getxopts mri_fill $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set seedopts = ();
  if($#PonsSeedCRS) set seedopts = ($seedopts -Pv  $PonsSeedCRS);
  if($#CCSeedCRS)   set seedopts = ($seedopts -Cv  $CCSeedCRS);
  if($#LHSeedCRS)   set seedopts = ($seedopts -lhv $LHSeedCRS);
  if($#RHSeedCRS)   set seedopts = ($seedopts -rhv $RHSeedCRS);
  set cmd = (mri_fill -a ../scripts/ponscc.cut.log $seedopts)
  if(-e transforms/talairach.lta) then
    set cmd = ($cmd  -xform transforms/talairach.lta)
  endif
  if ($LHonly) set cmd = ($cmd -lhonly )
  if ($RHonly) set cmd = ($cmd -rhonly )
  if($UseAseg) set cmd = ($cmd -segmentation $AsegForSurf);
  if(! $UseOldTopoFix && ! $NoNormMGZ) set cmd = ($cmd -topofix norm.mgz);
  set filledman = filled.mgz
  set filledauto = filled.auto.mgz
  if($FS_ALLOW_FILLED_EDIT) then
    set cmd = ($cmd -ctab $FREESURFER_HOME/SubCorticalMassLUT.txt)
    if(-e $filledauto && -e $filledman) then
      set fillededits = ../tmp/filled.edits.txt
      set cmd = ($cmd -auto-man $filledauto $filledman $fillededits)
    endif
  endif
  set cmd = ($cmd $xopts wm.mgz filled.mgz)
  $PWD |& tee -a $LF
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) then 
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    if(! -e $filledauto && $FS_ALLOW_FILLED_EDIT) then
      set cmd = (cp $filledman $filledauto)
      echo " $cmd" |& tee -a $LF |& tee -a $CF
      $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif

  echo $cmd > $touchdir/fill.touch
endif

if($longitudinal) then
  # This is a bit of a hack to transfer filled edits from base to
  # long. In the long, the filled is not actually used for creating
  # the orig surface in the way that it is in cross or base; the orig
  # surface comes from the base. However, the filled may be edited in
  # the base to create a better orig AND to create a stopmask. The
  # long may still need the stopmask, so need to copy over the the
  # filled. Comparison of the filled with the base filled.auto
  # indicates which voxels were edited (at either the base or long
  # stage) allowing creation and (implicit) editing of the stopmask at
  # the long stage. Could have just copied over the stopmask, but then
  # would have to have edited the stopmask rather than the more
  # familiar filled. It is all very confusing.
  set lfilled = $mdir/filled.mgz
  if(! -e $lfilled) then
    set bfilled = $SUBJECTS_DIR/$longbaseid/mri/filled.mgz
    set cmd = "cp -p $bfilled $lfilled"
    if($RunIt) then 
      echo $cmd |& tee -a $LF
      $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif
  #set bfilledauto = $longbaseid/mri/filled.auto.mgz
endif

#########################################################
#                  Per-Hemisphere                       #
#########################################################

#
# Notes on -parallel ($DoParallel) implementation:
# - clear the var CMDFS that stores command-files to run in parallel
# - start for loop on each hemi
# - print start-up log message, and build the 'cmd' var as usual
# - if DoParallel:
#     write 'cmd' to a file and put that filename in CMDFS
#     don't run the command just yet
# - else if not DoParallel (the traditional usage)
#     run the command
#     check error status
# - end for loop
# - if DoParallel:
#     run 'reconbatchjobs', which does the following grunt work:
#       - calls 'exec' on each command in the command file
#       - directs stdout/stderr to a temporary log file
#       - waits for each command to complete
#       - appends each temp log into recon-all.log
#       - check command return status and error-exit if error
#     check error status of reconbatchjobs
#

if($TopoFitLevel > 0) then
  # Uses brain.finalsurfs.manedit as input
  set cmd = (topofit --s $subjid --threads $OMP_NUM_THREADS --ico7)
  if($#hemilist == 1)    set cmd = ($cmd --$hemilist)
  if($TopoFitLevel == 2) set cmd = ($cmd --sphere)
  if($UseGPU)            set cmd = ($cmd --gpu)
  if($ForceUpdate)       set cmd = ($cmd --force)
  #set cmd = ($cmd --ico7)
  set xopts = `fsr-getxopts rca-topofit $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = ($cmd $xopts)
  echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
endif

#----------------              -------------------#
##---------------  -tessellate -------------------#
#----------------              -------------------#
if($DoTessellate && ( ! $longitudinal )) then
  # no need to run hemis in parallel, as this already runs in seconds
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Tessellate $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF

    if($hemi == "lh") then
      set hemivalue = 255;
    else
      set hemivalue = 127;
    endif

    # necessary second pretess, per f.segonne
    set xopts = `fsr-getxopts mri_pretess $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    if($NoNormMGZ) then
      set norm_vol = brain.mgz
    else
      set norm_vol = norm.mgz
    endif
    set cmd = (mri_pretess $xopts ../mri/filled.mgz $hemivalue \
                ../mri/$norm_vol ../mri/filled-pretess$hemivalue.mgz)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    set outfile = ../surf/$hemi.orig.nofix
    if($DoDecimation) set outfile = ../surf/$hemi.orig.nofix.predec

    set xopts = `fsr-getxopts mri_tessellate $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mri_tessellate $xopts ../mri/filled-pretess$hemivalue.mgz $hemivalue $outfile)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    set cmd = (rm -f ../mri/filled-pretess$hemivalue.mgz)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $cmd |& tee -a $LF

    # remove possible extra components, per f.segonne
    set xopts = `fsr-getxopts mris_extract_main_component $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_extract_main_component $xopts $outfile $outfile)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    if($DoDecimation) then
      # Reduce the number of faces such that the average face area is
      # DecimationFaceArea.  If the average face area is already more
      # than DecimationFaceArea, then the surface is not changed.
      # set cmd = (mris_decimate -a $DecimationFaceArea ../surf/$hemi.orig.nofix.predec ../surf/$hemi.orig.nofix)
      set cmd = (mris_remesh --desired-face-area $DecimationFaceArea --input ../surf/$hemi.orig.nofix.predec \
        --output ../surf/$hemi.orig.nofix)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif

    echo $cmd > $touchdir/$hemi.tessellate.touch
  end # Loop over hemilist
endif

#----------------           -------------------#
##---------------  -smooth1 -------------------#
#----------------           -------------------#
if($DoSmooth1 && ( ! $longitudinal )) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Smooth1 $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_smooth $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    # -nw prevents it from writing curv and area
    set cmd = (mris_smooth -nw)
    if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set outfile = ../surf/$hemi.smoothwm.nofix
    set cmd = ($cmd $xopts ../surf/$hemi.orig.nofix $outfile)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_smooth_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.smoothwm1.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------            -------------------#
##---------------  -inflate1 -------------------#
#----------------            -------------------#
if($DoInflate1 && ( ! $longitudinal )) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Inflation1 $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_inflate $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_inflate)
    set cmd = ($cmd  -no-save-sulc $xopts \
      ../surf/$hemi.smoothwm.nofix ../surf/$hemi.inflated.nofix)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_inflate_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.inflate1.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------           -------------------#
##---------------  -qsphere -------------------#
#----------------           -------------------#
if($DoQSphere && ( ! $longitudinal ) ) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# QSphere $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_sphere $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_sphere -q  -p 6 -a 128 )
    if($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd $xopts)
    set cmd = ($cmd ../surf/$hemi.inflated.nofix ../surf/$hemi.qsphere.nofix)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_sphere_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.qsphere.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------              -------------------#
#---------------- Fix Topology -------------------#
##---------------     -fix     -------------------#
#----------------              -------------------#
if($DoFix && ( ! $longitudinal )) then
  cd $subjdir/scripts
  set origsurf = orig
  if($DoRemesh) set origsurf = orig.premesh
  set NewTopoFixHemiList = (); # to handle Old/NewTopoFix use cases
  # Removed copying of orig.nofix and inflated.nofix to orig and inflated
  # because they can be specified directly as input.

  if($UseOldTopoFix) then
    set CMDFS = () # see earlier notes on -parallel implementation
    foreach hemi ($hemilist)
      echo "#@# Fix Topology $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
      set xopts = `fsr-getxopts mris_fix_topology $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      # At some point, mris_fix_topology became nondeterministic with
      # multiple threads so force it to use a single thread. The
      # non-deterministicness only happens on 3 of the buckner 40, so
      # not every time, and not most of the time.
      set cmd = (mris_fix_topology -threads 1 -mgz -sphere qsphere.nofix$FS_GII \
        -inflated inflated.nofix$FS_GII -orig orig.nofix$FS_GII -out $origsurf)
      if($FixWithGA) set cmd = ($cmd -ga)
      if($FixDiagOnly) set cmd = ($cmd -diagonly)
      if($NoRandomness) set cmd = ($cmd -seed $RngSeed)
      set cmd = ($cmd $xopts $subjid $hemi)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($DoParallel) then
        set CMDF = mris_fix_topology_${hemi}.cmd
        echo "$cmd" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      else
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    end # hemi loop
    if($RunIt && $DoParallel) then # if -parallel flag is used
      reconbatchjobs $LF $CMDFS |& tee -a $LF
      if($status) goto error_exit;
    endif

    foreach hemi ($hemilist)
      # check if total defect index != 0, meaning, euler # != 2 (surface bad)
      set cmd = (mris_euler_number ../surf/$hemi.$origsurf$FS_GII)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) then
        $cmd >& mris_euler_number.${hemi}.log
        if($status) then
          # have to run it again or else wont get info about why it failed
          $cmd |& tee -a $LF |& tee -a $CF
          goto error_exit;
        endif
        set defect_idx=`grep "total defect index" mris_euler_number.${hemi}.log | awk '{print $5}'`
        if("$defect_idx" != "0") then
          echo "mris_fix_topology failed on ${hemi}! (euler number != 2)" |& tee -a $LF
          echo "Trying new mris_topo_fixer on ${hemi}..." |& tee -a $LF
          set UseNewTopoFix = 1
          set NewTopoFixHemiList = ($NewTopoFixHemiList $hemi)
          set UseOldTopoFix = 0
          # cannot use the failed ?h.orig surface, must revert to ?.orig.nofix
          set cmd = (cp ../surf/$hemi.orig.nofix$FS_GII ../surf/$hemi.$origsurf$FS_GII)
          echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
          if($RunIt) $cmd |& tee -a $LF
          if($status) goto error_exit;
        endif
        cat mris_euler_number.${hemi}.log |& tee -a $LF
        rm -f mris_euler_number.${hemi}.log
      endif
    end # hemi loop

    # Convert the defects into a segmentation
    set cmd = (defect2seg --s $subjid) # This needs to be updated for remeshing
    if($#hemilist == 1) set cmd = ($cmd --$hemilist-only)
    if($DefectsCortex) set cmd = ($cmd --cortex)
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

  endif # UseOldTopoFix

  # the 'new' topology fixer is run if either the 'old' one failed,
  # or if usage is flagged on the recon-all command-string (-use-new_fixer)
  if($UseNewTopoFix) then
    if($#NewTopoFixHemiList == 0) then
      set NewTopoFixHemiList = ($hemilist) # use command-line default
      # else use the bad hemi(s) found in prior euler-number check
    endif
    set CMDFS = () # see earlier notes on -parallel implementation
    foreach hemi ($NewTopoFixHemiList)
      set cmd = (cp ../surf/$hemi.qsphere.nofix ../surf/$hemi.qsphere)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $cmd |& tee -a $LF
      if($status) goto error_exit;
      set cmd = (cp ../surf/$hemi.smoothwm.nofix ../surf/$hemi.smoothwm)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $cmd |& tee -a $LF
      if($status) goto error_exit;
      set xopts = `fsr-getxopts mris_topo_fixer $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (mris_topo_fixer -orig_name orig.nofix -out_name $origsurf -mgz -warnings)
      if($NoRandomness) set cmd = ($cmd -seed $RngSeed)
      # Need to update for remesh
      set cmd = ($cmd $xopts $subjid $hemi)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($DoParallel) then
        set CMDF = mris_topo_fixer_${hemi}.cmd
        echo "$cmd" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      else
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    end # hemi loop
    if($RunIt && $DoParallel) then # if -parallel flag is used
      reconbatchjobs $LF $CMDFS |& tee -a $LF
      if($status) goto error_exit;
    endif
  endif # UseNewTopoFix

  # This improves the triangle quality (changes topology)
  # Could do this as part of topo fix
  if($DoRemesh) then
    set RemeshIterations = 3; # Does not change much after 3
    foreach hemi ($hemilist)
      set origsurfpath = $SUBJECTS_DIR/$subjid/surf/$hemi.$origsurf
      set remeshpath   = $SUBJECTS_DIR/$subjid/surf/$hemi.orig
      set xopts = `fsr-getxopts mris_remesh-quality $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (mris_remesh --remesh --iters $RemeshIterations \
        --input $origsurfpath --output $remeshpath $xopts)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    end
  endif

  # run surface intersection checker/fixer
  foreach hemi ($hemilist)
    set xopts = `fsr-getxopts mris_remove_intersection $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_remove_intersection)
    set cmd = ($cmd $xopts ../surf/$hemi.orig ../surf/$hemi.orig)
    $PWD |& tee -a $LF
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    # Remove hemi.inflated, real one created after mris_make_surfaces
    #   Note sure this is needed anymore
    set cmd = (rm -f ../surf/$hemi.inflated)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $cmd |& tee -a $LF
    echo $cmd > $touchdir/$hemi.topofix.touch
  end # Loop over hemilist
endif

# Smooth2 and Inflate2 stages run after make white surfs

if($DoAutoDetGWStats) then
  cd $mdir
  set bfs  = brain.finalsurfs.mgz 
  set wm   = wm.mgz
  set aseg = $AsegForSurf
  foreach hemi ($hemilist)
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
    echo "#@# AutoDetGWStats $hemi `date`" |& tee -a $LF |& tee -a $CF
    set ads  = ../surf/autodet.gw.stats.$hemi.dat
    set orig = ../surf/$hemi.orig
    # Using the premesh makes a difference
    if($DoRemesh && ! $longitudinal) set orig = ../surf/$hemi.orig.premesh
    set cmd = (mris_autodet_gwstats --o $ads  --i $bfs --wm $wm --surf $orig)
    set xopts = `fsr-getxopts mris_autodet_gwstats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $WMSeg_wlo $WMSeg_ghi $xopts)
    echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
    echo $cmd        |& tee -a $LF |& tee -a $CF
    set ud = `UpdateNeeded $ads $bfs $wm $orig`
    if($ud || $ForceUpdate) then
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
        echo $cmd > $touchdir/$hemi.autodet.gw.stats.touch
      endif
    else
      echo "  Update not needed" | tee -a $LF |& tee -a $CF
    endif
  end # hemi
endif

set stopmaskscm = ()
if($UseStopMaskSCM && ($DoWhitePreAparc || $DoWhiteSurfs) ) then
  set stopmaskscm = $mdir/stopmask.scm.mgz
  echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
  echo "#@# StopMaskSCM `date`" |& tee -a $LF |& tee -a $CF
  if(! $longitudinal) then
    set filledauto = $mdir/filled.auto.mgz
  else
    set filledauto = $SUBJECTS_DIR/$longbaseid/mri/filled.auto.mgz
  endif
  set filled = $mdir/filled.mgz
  set wmpath = $mdir/wm.mgz
  set bfspath = $mdir/brain.finalsurfs.mgz
  set asegpspath = $mdir/$AsegForSurf
  set ud = (`UpdateNeeded $stopmaskscm $filledauto $filled $wmpath $bfspath $asegpspath`)
  if($ud || $ForceUpdate) then
    set xopts = `fsr-getxopts StopMaskSCM $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mri_stopmask --o $stopmaskscm --aseg $asegpspath \
      --filled $filledauto $filled --wm $wmpath --bfs $bfspath \
      --lv --wmsa 1 $xopts)
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      echo $cmd > $touchdir/stopmask.scm.txt
      endif
    endif
    echo "  StopMaskSCM update not needed" | tee -a $LF |& tee -a $CF
  endif
endif

if($DoWhitePreAparc) then
  cd $mdir
  set bfs  = brain.finalsurfs.mgz 
  set wm   = wm.mgz
  set aseg = $AsegForSurf
  if(! $UseAseg) set aseg = ()
  foreach hemi ($hemilist)
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
    echo "#@# WhitePreAparc $hemi `date`" |& tee -a $LF |& tee -a $CF
    set ads  = ../surf/autodet.gw.stats.$hemi.dat
    set orig = ../surf/$hemi.orig
    set whitepreaparc = ../surf/$hemi.white.preaparc
    set cmd = (mris_place_surface --adgws-in $ads --wm $wm --threads $OMP_NUM_THREADS\
     --invol $bfs --$hemi  --i $orig --o $whitepreaparc --white)
    if($UseAseg) set cmd = ($cmd --seg $aseg) # probably should always use
    if($FixEntoWM || $FixACJ) set cmd = ($cmd --restore-255) 
    #if($CBVfindFirstPeakD1) set cmd = ($cmd --first-peak-d1) # errors near Put/Insula
    if($longitudinal == 0) set cmd = ($cmd --nsmooth 5) # good idea?
    if($longitudinal == 1) set cmd = ($cmd --max-cbv-dist 3.5) 
    if($#mps_n_averages) set cmd = ($cmd --n_averages $mps_n_averages)
    if($UseStopMaskSCM) set cmd = ($cmd --stopmask $stopmaskscm)
    set xopts = `fsr-getxopts WhitePreAparc $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $xopts)
    echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
    echo $cmd        |& tee -a $LF |& tee -a $CF
    set tmp = ()
    if($UseAseg) set tmp = ($aseg)
    set ud = `UpdateNeeded $whitepreaparc $ads $bfs $wm $orig $tmp $stopmaskscm`
    if($ud || $ForceUpdate) then
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
        echo $cmd > $touchdir/$hemi.white.preaparc.touch
      endif
    else
      echo "   Update not needed" |& tee -a $LF |& tee -a $CF
    endif
  end # hemi
endif

if($DoCortexLabel) then
  cd $mdir
  set aseg = $AsegForSurf
  foreach hemi ($hemilist)
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
    echo "#@# CortexLabel $hemi `date`" |& tee -a $LF |& tee -a $CF
    set whitepreaparc = ../surf/$hemi.white.preaparc
    set cmd = (label-cortex --s $subjid --$hemi)
    if($FixGA) set cmd = ($cmd --fix-ga)
    if($UseGifti) set cmd = ($cmd --gii)
    if($ForceUpdate) set cmd = ($cmd --force-update)
    set xopts = `fsr-getxopts CortexLabel $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $xopts)
    if($RunIt) then
      $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      echo $cmd > $touchdir/$hemi.cortex.touch
    else
      echo "   Update not needed" |& tee -a $LF |& tee -a $CF
    endif
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
    echo "#@# CortexLabel+HipAmyg $hemi `date`" |& tee -a $LF |& tee -a $CF
    set cortexha = ../label/$hemi.cortex+hipamyg.label # Must have a "/" or LabelRead() fails below
    set cmd = (mri_label2label --label-cortex $whitepreaparc $aseg 1 $cortexha)
    set xopts = `fsr-getxopts CortexLabelHA $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $xopts)
    echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
    echo $cmd        |& tee -a $LF |& tee -a $CF
    set ud = `UpdateNeeded $cortexha $whitepreaparc $aseg`
    if($ud || $ForceUpdate) then
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
        echo $cmd > $touchdir/$hemi.cortex+hipamyg.touch
      endif
    else
      echo "   Update not needed" |& tee -a $LF |& tee -a $CF
    endif
  end # hemi
endif

#----------------           -------------------#
##---------------  -smooth2 -------------------#
#----------------           -------------------#
if($DoSmooth2) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Smooth2 $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_smooth $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    # Use -nw to keep from writing out curv and area
    # Default number of iterations is 10, but use 3 here
    set cmd = (mris_smooth -n 3 -nw)
    if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd $xopts)
    set cmd = ($cmd ../surf/$hemi.white.preaparc ../surf/$hemi.smoothwm)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_smooth_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.smoothwm2.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------            -------------------#
##---------------  -inflate2 -------------------#
#----------------            -------------------#
if($DoInflate2) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Inflation2 $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_inflate $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_inflate)
    set cmd = ($cmd $xopts ../surf/$hemi.smoothwm ../surf/$hemi.inflated)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_inflate_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.inflate2.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------                     -----------#
#---------- Curvature .H and .K -----------#
##---------       -curvHK       -----------#
#----------                     -----------#
if($DoCurvHK) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Curv .H and .K $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/surf > /dev/null
    $PWD |& tee -a $LF
    # create curvature files ?h.white.H and ?h.white.K
    set xopts = `fsr-getxopts mris_curvature $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_curvature -w)
    if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd $xopts $hemi.white.preaparc)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_curvature_white_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    # This is a bit of a hack to account for the change in the name of the input white
    # surface. There needs to be a file called ?h.white.{H,K} but mris_curvature creates
    # ?h.white.preaparc.{H,K}. This just creates a symlink 
    foreach suffix (H K)
      set cmd1 = (rm -f $hemi.white.$suffix$FS_GII)
      set cmd2 = (ln -s $hemi.white.preaparc.$suffix$FS_GII $hemi.white.$suffix$FS_GII)
      echo $cmd1 | tee -a $LF
      echo $cmd2 | tee -a $LF
      if($DoParallel) then
        set CMDF = rm_curvature_white_${hemi}.$suffix.cmd
        echo "$cmd1" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
        set CMDF = ln_curvature_white_${hemi}.$suffix.cmd
        echo "$cmd2" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      else
        if($RunIt) then
          $cmd1 | tee -a $LF
          if($status) goto error_exit
          $cmd2 | tee -a $LF
          if($status) goto error_exit
        endif
      endif
    end
    echo $cmd > $touchdir/$hemi.white.H.K.touch

    # create curvature files ?h.inflated.H and ?h.inflated.K
    set xopts = `fsr-getxopts mris_curvature $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_curvature )
    if ($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd -thresh .999 -n -a 5 -w -distances 10 10)
    set cmd = ($cmd $xopts $hemi.inflated)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_curvature_inflated_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.inflate.H.K.touch
  end # Loop over hemilist

  if($RunIt && $DoParallel) then
    set cmd = (reconbatchjobs $LF $CMDFS)
    echo "cd `pwd`" | tee -a $LF
    echo $cmd | tee -a $LF
    $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
  foreach hemi ($hemilist)
    if($RunIt &&  ! -e ${hemi}.white.H$FS_GII) then
      pwd  | tee -a $LF
      echo "Cannot find ${hemi}.white.H$FS_GII" | tee -a $LF
      goto error_exit;
    endif
    if($RunIt &&  ! -e ${hemi}.inflated.H$FS_GII) then
      pwd  | tee -a $LF
      echo "Cannot find ${hemi}.inflated.H$FS_GII" | tee -a $LF
      goto error_exit;
    endif
  end
endif

#-----------             -------------#
##---------- AUTORECON 3 -------------#
#-----------             -------------#

#----------------          ----------------#
##---------------  -sphere ----------------#
#----------------          ----------------#
if($DoSphere) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Sphere $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    # longitudinal copying of sphere now done in rca-long-tp-init
    if(! $longitudinal) then
      # default stream:
      set xopts = `fsr-getxopts mris_sphere $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (mris_sphere -threads $OMP_NUM_THREADS)
      if($NoRandomness) set cmd = ($cmd -seed $RngSeed)
      if($UseNoNeg) set cmd = ($cmd -remove_negative 1)
      set cmd = ($cmd $xopts)
      set cmd = ($cmd ../surf/$hemi.inflated ../surf/$hemi.sphere)
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($DoParallel) then
        set CMDF = mris_sphere_${hemi}.cmd
        echo "$cmd" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      else
        echo $cmd |& tee -a $LF
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
      echo $cmd > $touchdir/$hemi.sphmorph.touch
    endif
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------                      -------------------#
#---------------- Surface Registration -------------------#
##---------------       -surfreg       -------------------#
#----------------                      -------------------#
if($DoSurfReg) then
  set cmd = (rca-surfreg --s $subjid --threads $OMP_NUM_THREADS \
   --tif-path $AvgCurvTifPath --tif-name $AvgCurvTif)
  if($#hemilist == 1) set cmd = ($cmd --$hemilist)
  if($longitudinal) set cmd = ($cmd --long $longbaseid)
  if($UseNoNeg) set cmd = ($cmd --usenoneg)
  if($JosaReg) set cmd = ($cmd --josa)
  if($ForceUpdate) set cmd = ($cmd --force)
  if($XOptsFile) set cmd = ($cmd --expert $XOptsFile)
  echo "#@# Surf Reg  `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  if($RunIt) then
    echo $cmd |& tee -a $LF
    $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------                  -------------------#
##---------------  -jacobian_white -------------------#
#----------------                  -------------------#
if($DoJacobianWhite) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Jacobian white $hemi `date`" \
        |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    # produce the jacobian, from the white surface to the sphere
    set cmd = (mris_jacobian \
                ../surf/$hemi.white.preaparc \
                ../surf/$hemi.sphere.reg \
                ../surf/$hemi.jacobian_white)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_jacobian_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.jacobian_white.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#---                                                                  ---#
#--- Surface Registration, allow maximal distortion, produce Jacobian ---#
##--                        -jacobian_dist0                           ---#
#---                                                                  ---#
if($DoJacobianDist0) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Jacobian dist0 $hemi `date`" \
        |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set AvgTif = ${AvgCurvTifPath}/$hemi.${AvgCurvTif}
    set xopts = `fsr-getxopts mris_register $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_register -curv -norot -jacobian \
        ../surf/$hemi.jacobian_dist0 -dist 0)
    set cmd = ($cmd $xopts)
    set cmd = ($cmd ../surf/$hemi.sphere.reg $AvgTif \
        ../surf/$hemi.sphere.dist0.jacobian.reg)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_register_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.jacobian_dist0.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#---------------                          ---------------#
#--------------- Average Curv for Display ---------------#
##--------------         -avgcurv         ---------------#
#---------------                          ---------------#
if($DoAvgCurv) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# AvgCurv $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set AvgTif = ${AvgCurvTifPath}/$hemi.${AvgCurvTif}
    set xopts = `fsr-getxopts mrisp_paint $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    # -a 5 means to smooth 5 iterations
    set cmd = (mrisp_paint -a 5 $xopts "$AvgTif#6" \
      ../surf/$hemi.sphere.reg ../surf/$hemi.avg_curv)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mrisp_paint_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.avgcurv.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------                       -----------------#
#---------------- Cortical Parcellation -----------------#
##---------------       -cortparc       -----------------#
#----------------                       -----------------#
if($DoCortParc) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Cortical Parc $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_ca_label $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set CPAtlas = ${GCSDIR}/$hemi.$GCS
    set annot = ../label/$hemi.aparc.annot
    set cmd = (mris_ca_label)
    if($UseAseg) set cmd = ($cmd -l ../label/$hemi.cortex.label)
    if($UseAseg) set cmd = ($cmd -aseg ../mri/$AsegForSurf)
    if($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd $xopts)
    if($longitudinal) then
      # longitudinal:
      set cmd = ($cmd -long -R $longbasedir/label/${hemi}.aparc.annot)
    endif
    set cmd = ($cmd $subjid $hemi ../surf/$hemi.sphere.reg $CPAtlas $annot)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_ca_label_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.aparc.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

if($UseHighMyelin) then
  foreach hemi ($hemilist)
    echo "#@# HighMyelinLabel $hemi `date`" |& tee -a $LF |& tee -a $CF
    set hml = $ldir/$hemi.high-myelin.label
    set sphreg = $sdir/$hemi.sphere.reg
    set fsahml = $FREESURFER_HOME/subjects/fsaverage/label/$hemi.high-myelin.label
    set fsareg = $FREESURFER_HOME/subjects/fsaverage/surf/$hemi.sphere.reg
    set ud = (`UpdateNeeded $hml $fsareg $fsahml $sphreg`)
    if($ud || $ForceUpdate) then
      set cmd = (mris_apply_reg --src-label $fsahml --streg $fsareg $sphreg --trg $hml)
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    else
      echo "   $hemi.high-myelin.label update not needed" |& tee -a $LF |& tee -a $CF
    endif
  end
endif

if($DoConf2Hires && ! $LongSamseg) then
  # This places the surfaces on the highres T1 (and T2)
  set cmd = (conf2hires --threads $OMP_NUM_THREADS)
  if($DoT2pial == 1)    set cmd = ($cmd --T2)
  if($DoFLAIRpial == 1) set cmd = ($cmd --FLAIR)
  if($CBVfindFirstPeakD1) set cmd = ($cmd --first-peak-d1)
  if($UseHighMyelin)      set cmd = ($cmd --high-myelin $HighMyelinFactor)
  if($UseStopMaskSCM) set cmd = ($cmd --stopmask $stopmaskscm)
  if($longitudinal) then
    set cmd = ($cmd --longitudinal $tpNid $longbaseid)
  else
    set cmd = ($cmd --s $subjid)
  endif
  if($UseCubic == 1) set cmd = ($cmd --cubic)
  if($UseCubic == 0) set cmd = ($cmd --trilin)
  if($ForceUpdate)   set cmd = ($cmd --force-update)
  set xopts = `fsr-getxopts conf2hires $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = ($cmd $xopts)
  echo $cmd | tee -a $LF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/conf2hires
endif

if($DoWhiteSurfs && ! $DoConf2Hires) then
  cd $mdir
  set bfs  = brain.finalsurfs.mgz 
  set wm   = wm.mgz
  set aseg = $AsegForSurf
  foreach hemi ($hemilist)
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
    echo "#@# WhiteSurfs $hemi `date`" |& tee -a $LF |& tee -a $CF
    set ads  = ../surf/autodet.gw.stats.$hemi.dat
    set inputsurf = ../surf/$hemi.white.preaparc
    if($longitudinal) set inputsurf = ../surf/$hemi.orig_white # seems like white.preparc better
    set aparc  = ../label/$hemi.aparc.annot  
    set cortex = ../label/$hemi.cortex.label
    set white = ../surf/$hemi.white
    set cmd = (mris_place_surface --adgws-in $ads --seg $aseg --threads $OMP_NUM_THREADS\
      --wm $wm --invol $bfs --$hemi  --i $inputsurf --o $white \
      --white --nsmooth 0 --rip-label $cortex --rip-bg \
      --rip-surf $inputsurf --aparc $aparc)
    if($RipWMSA)   set cmd = ($cmd --rip-wmsa)
    if($RipLesion) set cmd = ($cmd --rip-lesion)
    if($CBVfindFirstPeakD1) set cmd = ($cmd --first-peak-d1)
    if($longitudinal) set cmd = ($cmd --max-cbv-dist 3.5) 
    if($#mps_n_averages) set cmd = ($cmd --n_averages $mps_n_averages)
    if($UseStopMaskSCM) set cmd = ($cmd --stopmask $stopmaskscm)
    if($FixEntoWM || $FixACJ) set cmd = ($cmd --restore-255) 
    if($UseHighMyelin) then
      # The factor is a value between 0 and 1 that changes how far
      # into GM the white surface will go. 1 is the same as not using
      # highmy. Towards 0 will make the surface pull back away from
      # cortex.  Try 0.3. This will only apply to vertices in the
      # high-myelin mask. Cortex is bright in himy areas and sometimes
      # the white extends too far. This was added to better process
      # the HCP data, but I did not find it helped much.
      set hml = $ldir/$hemi.high-myelin.label
      set cmd = ($cmd --alt-border-low $hml $HighMyelinFactor)
    else
      set hml = ()
    endif
    set xopts = `fsr-getxopts PlaceWhiteSurf $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $xopts)
    echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
    echo $cmd        |& tee -a $LF |& tee -a $CF
    set repos = $sdir/repos.$hemi.white.json
    if(! -e $repos) set repos = ()
    set ud = `UpdateNeeded $white $inputsurf $ads $bfs $wm $inputsurf $cortex $hml $repos $aseg $stopmaskscm`
    if($ud || $ForceUpdate) then
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
        echo $cmd > $touchdir/$hemi.white.touch
        if(-e "$repos") then
          # Use json point set to reposition surface. This is a little bit of a hack
          # in that the placement above is rerun even if it is not needed in order
          # to run the repositioning. This is not done for preaparc because this
          # is only fine tuning
          set cmd = (mris_reposition_surface -s $white -v $bfs -p $repos -o $white)
          set xopts = `fsr-getxopts ReposWhiteSurf $V8XoptsFile $GlobXOptsFile $XOptsFile `;
          set cmd = ($cmd $xopts)
          echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
          echo $cmd        |& tee -a $LF |& tee -a $CF
          $fs_time $cmd |& tee -a $LF
          if($status) goto error_exit;
          echo $cmd > $touchdir/repos.$hemi.white.touch
        endif
      endif
    else
      echo "   Update not needed" |& tee -a $LF |& tee -a $CF
    endif
  end # hemi
endif

#---------------- Make T1-based Pial Surfaces -pial -------------------#
if($DoPialSurfs && ! $DoConf2Hires) then
  cd $mdir
  set bfs  = brain.finalsurfs.mgz 
  set wm   = wm.mgz
  set aseg = $AsegForSurf
  foreach hemi ($hemilist)
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
    echo "#@# T1PialSurf $hemi `date`" |& tee -a $LF |& tee -a $CF
    set ads  = ../surf/autodet.gw.stats.$hemi.dat
    set inputsurf = ../surf/$hemi.white
    if($longitudinal) set inputsurf = ../surf/$hemi.orig_pial
    set aparc  = ../label/$hemi.aparc.annot  
    set cortex   = ../label/$hemi.cortex.label
    set cortexha = ../label/$hemi.cortex+hipamyg.label 
    set white = ../surf/$hemi.white
    set pial = ../surf/$hemi.pial.T1
    set cmd = (mris_place_surface --adgws-in $ads --seg $aseg --threads $OMP_NUM_THREADS\
      --wm $wm --invol $bfs --$hemi  --i $inputsurf --o $pial \
      --pial --nsmooth 0 --rip-label $cortexha --pin-medial-wall $cortex \
      --aparc $aparc --repulse-surf $white  --white-surf $white)
    if($CBVfindFirstPeakD1) set cmd = ($cmd --first-peak-d1)
    if($FixEntoWM || $FixACJ) set cmd = ($cmd --restore-255) 
    if($longitudinal) then
      set cmd = ($cmd --max-cbv-dist 3.5) # --long not used anymore
      set cmd = ($cmd --blend-surf .25 $white)
    endif
    if($#mps_n_averages) set cmd = ($cmd --n_averages $mps_n_averages)
    # Things might need to add: noaseg, noaparc, UseFixMtl
    set xopts = `fsr-getxopts PlaceT1PialSurf $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $xopts)
    echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
    echo $cmd        |& tee -a $LF |& tee -a $CF
    set repos = $sdir/repos.$hemi.pial.json
    if(! -e $repos || $DoT2pial || $DoFLAIRpial) set repos = ()
    set ud = `UpdateNeeded $pial $inputsurf $ads $bfs $wm $cortex $cortexha $repos $aseg`
    if($ud || $ForceUpdate) then
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
        echo $cmd > $touchdir/$hemi.pial.touch
        if($DoT2pial == 0 &&  $DoFLAIRpial == 0)  then
          cd ../surf; ln -sf $hemi.pial.T1$FS_GII $hemi.pial$FS_GII; cd ../mri
          if(-e "$repos") then
            # Use json point set to reposition surface. See notes above for white.
            # This is run in the T2/FLAIR stage, but it will either be done here
            # or it will be done there, but not both.
            set cmd = (mris_reposition_surface -s $pial -v $bfs -p $repos -o $pial)
            set xopts = `fsr-getxopts ReposPialSurf $V8XoptsFile $GlobXOptsFile $XOptsFile `;
            set cmd = ($cmd $xopts)
            echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
            echo $cmd        |& tee -a $LF |& tee -a $CF
            $fs_time $cmd |& tee -a $LF
            if($status) goto error_exit;
            echo $cmd > $touchdir/repos.$hemi.pial.touch
          endif
        endif
      endif
    else
      echo "   Update not needed" |& tee -a $LF |& tee -a $CF
    endif
    # Make curvature file after any T2 refinement
  end # hemi
endif

#----------------                                     ----------------#
#---------------- Refine Pial Surfaces Using T2/FLAIR ----------------#
##---------------     -T2pial  and  -FLAIRpial        ----------------#
#----------------                                     ----------------#
# note: the registration portion requires existence of both surfaces
if(($DoT2pial || $DoFLAIRpial) && ! $DoConf2Hires) then
  echo "#--------------------------------------------" |& tee -a $LF |& tee -a $CF
  echo "#@# Refine Pial Surfs w/ T2/FLAIR `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/scripts > /dev/null

  # should be one or the other.  'check_params' section checks for this.
  if($DoT2pial)    set t2flair=(T2)
  if($DoFLAIRpial) set t2flair=(FLAIR)

  set t2flairraw = $mdir/orig/${t2flair}raw.mgz

  if (! -e $mdir/${t2flair}.mgz) then

    # Longitudinal processing
    if ($longitudinal) then

      # use T2/FLAIR raw from cross if missing in long
      if (! -e $t2flairraw) then
        set t2flairraw = ${SUBJECTS_DIR}/${tpNid}/mri/orig/${t2flair}raw.mgz
      endif
      if (! -e $t2flairraw) then
        echo "ERROR: mri/orig/${t2flair}raw.mgz missing in long and cross." \
          |& tee -a $LF
        goto error_exit;
      endif

      # concatenate lta if created in cross (T2cross->T1cross->longspace)
      # this avoids registering again if already done in cross
      if ( -e ${SUBJECTS_DIR}/${tpNid}/mri/transforms/${t2flair}raw.lta ) then
        set cmd = (mri_concatenate_lta )
        set cmd = ($cmd ${SUBJECTS_DIR}/${tpNid}/mri/transforms/${t2flair}raw.lta )
        set cmd = ($cmd $tpNtobase_regfile $mdir/transforms/${t2flair}raw.lta)
        echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      else
        # if t2flairraw.lta does not exist in cross, register T2raw to longspace
        set xopts = `fsr-getxopts bbregister $V8XoptsFile $GlobXOptsFile $XOptsFile `;
	if ($LHonly) set xopts = ($xopts --lh-only )
	if ($RHonly) set xopts = ($xopts --rh-only )
        set bbcmd = (bbregister --s $subjid  --mov $t2flairraw --lta $mdir/transforms/${t2flair}raw.lta \
            --init-$BBRInit --T2 --gm-proj-abs 2 --wm-proj-abs 1 $xopts)
        set bbcmd = ($bbcmd --no-coreg-ref-mask) # otherwise can become non-determin if aparc+aseg is there
        echo "\n $bbcmd \n"|& tee -a $LF |& tee -a $CF
        if($RunIt) $fs_time $bbcmd |& tee -a $LF
        if($status) goto error_exit;
      endif

    else #regular processing, register T2flairraw to T1 and create lta

      set LTAAuto = $mdir/transforms/${t2flair}raw.auto.lta 
      set LTAMan = $mdir/transforms/${t2flair}raw.lta 
      set DontCopy = 0
      if(-e $LTAAuto && -e $LTAMan) then
        set DontCopy = `diff $LTAAuto $LTAMan | grep -v \# | grep -v filename | wc -l`
      endif

      # first create a T2/FLAIR that is registered to the T1s
      set xopts = `fsr-getxopts bbregister $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      if ($LHonly) set xopts = ($xopts --lh-only )
      if ($RHonly) set xopts = ($xopts --rh-only )
      set bbcmd = (bbregister --s $subjid  --mov $t2flairraw   --lta $LTAAuto \
          --init-$BBRInit  --T2 --gm-proj-abs 2 --wm-proj-abs 1 $xopts)
      set bbcmd = ($bbcmd --no-coreg-ref-mask) # otherwise can become non-determin if aparc+aseg is there
      echo "\n $bbcmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $bbcmd |& tee -a $LF
      if($status) goto error_exit;

      if($DontCopy == 0) then
        set cmd = (cp $LTAAuto $LTAMan)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif

    endif

    # both regular and long processing:

    # actually map the input (and make conform as the T1 target)
    # this creates the ${t2flair}.prenorm.mgz
    # MOD: is it possible to pass the T2 surface placement
    # a non-resampled image and a registration matrix (???)
    # Before: used mri_vol2vol for highres
    set mapcmd = (mri_convert -odt float -at $mdir/transforms/${t2flair}raw.lta)
    # MOD: should we always use cubic here?
    if($UseCubic) set mapcmd = ($mapcmd -rt cubic -ns 1)
    set mapcmd = ($mapcmd -rl $mdir/orig.mgz )
    set mapcmd = ($mapcmd $t2flairraw )
    set mapcmd = ($mapcmd $mdir/${t2flair}.prenorm.mgz )
    if($RunIt) $fs_time $mapcmd |& tee -a $LF
    if($status) goto error_exit;

    # Then give the T2/FLAIR a little normalizing note: pre-normalized
    # file remains for debug, with .prenorm in name this creates
    # ${t2flair}.norm.mgz. MOD: may want to simply globaly rescale instead
    set surfaces = ()
    foreach hemi ($hemilist)
        set surfaces = ($surfaces -surface $sdir/$hemi.white identity.nofile)
    end
    set normcmd = (mri_normalize)
    if ($NoRandomness) set normcmd = ($normcmd -seed $RngSeed)
    set normcmd = ($normcmd \
        -sigma 0.5 -nonmax_suppress 0 -min_dist 1 \
        -aseg $mdir/aseg.presurf.mgz \
	$surfaces  \
        $mdir/${t2flair}.prenorm.mgz \
        $mdir/${t2flair}.norm.mgz)
    echo "\n $normcmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $normcmd |& tee -a $LF
    if($status) goto error_exit;
    
  endif

  # then mask the T2/FLAIR 
  # note: post-normalized file remains for debug, with .norm in name
  # this creates ${t2flair}.mgz
  if($FS_RCA_T2_MASK_71) then
    set fs_rca_t2_mask_args = (-transfer 255 -keep_mask_deletion_edits)
  else
    set fs_rca_t2_mask_args = (-T 1)
  endif
  set maskcmd = (mri_mask $fs_rca_t2_mask_args  \
      $mdir/${t2flair}.norm.mgz  $mdir/brain.finalsurfs.mgz  $mdir/${t2flair}.mgz)
  echo "\n $maskcmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $maskcmd |& tee -a $LF
  if($status) goto error_exit;

  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    cd $mdir
    set bfs  = brain.finalsurfs.mgz 
    set wm   = wm.mgz
    set aseg = $AsegForSurf
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF
    echo "#@# MMPialSurf $hemi `date`" |& tee -a $LF |& tee -a $CF
    set ads  = ../surf/autodet.gw.stats.$hemi.dat
    set aparc  = ../label/$hemi.aparc.annot  
    set cortex   = ../label/$hemi.cortex.label
    set cortexha = ../label/$hemi.cortex+hipamyg.label 
    set white = ../surf/$hemi.white
    set pialt1 = ../surf/$hemi.pial.T1
    if($DoT2pial)    set MultiModal = T2
    if($DoFLAIRpial) set MultiModal = FLAIR
    set pialmm = ../surf/$hemi.pial.$MultiModal
    set mmvol = $MultiModal.mgz
    set cmd = (mris_place_surface --adgws-in $ads --seg $aseg  --wm $wm --threads $OMP_NUM_THREADS\
      --invol $bfs --$hemi  --i $pialt1 --o $pialmm --pial --nsmooth 0 \
      --rip-label $cortexha --pin-medial-wall $cortex --white-surf $white \
      --aparc $aparc --repulse-surf $white --mmvol $mmvol $MultiModal)
    if($#mps_n_averages) set cmd = ($cmd --n_averages $mps_n_averages)
    # Things might need to add: noaseg, noaparc, UseFixMtl
    set xopts = `fsr-getxopts PlaceMMPialSurf $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $xopts)
    echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
    echo $cmd        |& tee -a $LF |& tee -a $CF
    set repos = $sdir/repos.$hemi.pial.json
    if(! -e $repos) set repos = ()
    set ud = `UpdateNeeded $pialmm $pialt1 $bfs $cortex $cortexha $white $ads $wm $repos $mmvol`
    if($ud || $ForceUpdate) then
      if($RunIt) then
        $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
        cd ../surf; ln -sf $hemi.pial.$MultiModal$FS_GII $hemi.pial$FS_GII; cd ../mri
        if(-e "$repos") then
          # Use json point set to reposition surface. See notes above for white and pial.
          set cmd = (mris_reposition_surface -s $pialmm -v $bfs -p $repos -o $pialmm)
          set xopts = `fsr-getxopts ReposPialSurf $V8XoptsFile $GlobXOptsFile $XOptsFile `;
          set cmd = ($cmd $xopts)
          echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
          echo $cmd        |& tee -a $LF |& tee -a $CF
          $fs_time $cmd |& tee -a $LF
          if($status) goto error_exit;
          echo $cmd > $touchdir/repos.$hemi.pial.touch
        endif
      endif
    else
      echo "   Update not needed" |& tee -a $LF |& tee -a $CF
    endif
  end # hemi

endif # if revine pial with T2/FLAIR

############################################################
###### Surface placement is done ###########################
############################################################

if(1) then
  cd $mdir
  foreach hemi ($hemilist)

    foreach surftype (white pial)
      set surf = ../surf/$hemi.$surftype$FS_GII
      if(! -e $surf) continue
      foreach meas (curv area)
        echo "#@# $surftype $meas $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
        set measfile = ../surf/$hemi.$meas$FS_GII
        if($surftype == pial) set measfile = ../surf/$hemi.$meas.pial$FS_GII
        set cmd = (mris_place_surface --$meas-map $surf)
        if($meas == curv) set cmd = ($cmd 2 10)
        set cmd = ($cmd $measfile)
        set xopts = `fsr-getxopts $surftype$meas $V8XoptsFile $GlobXOptsFile $XOptsFile `;
        set cmd = ($cmd $xopts)
        echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
        echo $cmd        |& tee -a $LF |& tee -a $CF
        set ud = `UpdateNeeded $measfile $surf`
        if($ud || $ForceUpdate) then
          if($RunIt) then
            $fs_time $cmd |& tee -a $LF
            if($status) goto error_exit;
        endif
        else
          echo "   Update not needed" |& tee -a $LF |& tee -a $CF
        endif
      end # meas
    end # surftype

    set white = ../surf/$hemi.white$FS_GII
    set pial  = ../surf/$hemi.pial$FS_GII
    if(-e $white && -e $pial) then
      # Should add a check here to make sure that pial is up-to-date (needs autorecon3)
      echo "#@# thickness $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
      set thickness = ../surf/$hemi.thickness$FS_GII
      set cmd = (mris_place_surface --thickness $white $pial 20 5 $thickness)
      echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
      echo $cmd        |& tee -a $LF |& tee -a $CF
      set ud = `UpdateNeeded $thickness $pial $white`
      if($ud || $ForceUpdate) then
        if($RunIt) then
          $fs_time $cmd |& tee -a $LF
          if($status) goto error_exit;
        endif
      else
        echo "   Update not needed" |& tee -a $LF |& tee -a $CF
      endif
      #-----------------------------------
      echo "#@# area and vertex vol $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
      set areamid = ../surf/$hemi.area.mid$FS_GII
      set areawhite = ../surf/$hemi.area$FS_GII
      set areapial = ../surf/$hemi.area.pial$FS_GII
      set vtxvol   = ../surf/$hemi.volume$FS_GII
      echo "cd `$PWD`" |& tee -a $LF |& tee -a $CF
      set ud1 = `UpdateNeeded $areamid $areawhite $areapial`
      set ud2 = `UpdateNeeded $vtxvol $pial $white`
      set xopts = `fsr-getxopts vertexvol $V8XoptsFile $GlobXOptsFile $XOptsFile `;
      set cmd = (vertexvol --s $subjid --$hemi --th3 $xopts) # hard-code th3 now
      if($ud1 || $ud2 || $ForceUpdate) then
        if($RunIt) then
          $fs_time $cmd |& tee -a $LF
          if($status) goto error_exit;
        endif
      else
        echo "   Update not needed" |& tee -a $LF |& tee -a $CF
      endif
    endif
  end #hemi
endif

# stats and GWcontrast must run here, after T2 pial refinement

#----------                            -----------#
#---------- Curvature Anatomical Stats -----------#
##---------        -curvstats          -----------#
#----------                            -----------#
if($DoCurvStats) then
  foreach hemi ($hemilist)
    echo "\n#-----------------------------------------" |& tee -a $LF |& tee -a $CF
    echo "#@# Curvature Stats $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/surf > /dev/null
    $PWD |& tee -a $LF
    set stats = ../stats/$hemi.curv.stats
    set xopts = `fsr-getxopts mris_curvature_stats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_curvature_stats -m --writeCurvatureFiles -G \
            -o $stats -F smoothwm $xopts $subjid $hemi curv sulc);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    rm -f .xdebug_mris_curvature_stats
    echo $cmd > $touchdir/$hemi.curvstats.touch
  end # Loop over hemilist
endif

#----------------                 ------------------#
#---------------- Cortical Ribbon ------------------#
##---------------   -cortribbon   ------------------#
#----------------                 ------------------#
if($DoCortRibbonVolMask) then
  echo "#--------------------------------------------" \
      |& tee -a $LF |& tee -a $CF
  echo "#@# Cortical ribbon mask `date`" \
      |& tee -a $SF|& tee -a $LF|& tee -a $CF
  cd $subjdir/mri > /dev/null
  set cmd = (mris_volmask --aseg_name aseg.presurf \
    --label_left_white   2 --label_left_ribbon   3 \
    --label_right_white 41 --label_right_ribbon 42 \
    --save_ribbon --parallel)
  if($LHonly) set cmd = ($cmd --lh-only )
  if($RHonly) set cmd = ($cmd --rh-only )
  # the 'mris_volmask --parallel' race-condition bug is fixed in this commit:
  # https://github.com/freesurfer/freesurfer/commit/ad53c019a98f3c8132b2a13e062f63baf4efe388
  set xopts = `fsr-getxopts mris_volmask $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = ($cmd $xopts)
  set cmd = ($cmd $subjid)
  $PWD |& tee -a $LF
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/cortical_ribbon.touch
endif

#----------------                         -----------------#
#---------------- Cortical Parcellation 2 -----------------#
##---------------       -cortparc2        -----------------#
#----------------                         -----------------#
if($DoCortParc2) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------"\
      |& tee -a $LF |& tee -a $CF
    echo "#@# Cortical Parc 2 $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_ca_label $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set CPAtlas = ${GCSDIR}/${hemi}.${DESTRIEUX_GCS}
    set annot = ../label/$hemi.aparc.${DESTRIEUX_NAME}.annot
    set cmd = (mris_ca_label)
    if($UseAseg) set cmd = ($cmd -l ../label/$hemi.cortex.label)
    if($UseAseg) set cmd = ($cmd -aseg ../mri/$AsegForSurf)
    if($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd $xopts)
    if($longitudinal) then
      # longitudinal:
      set cmd = ($cmd -long -R \
                   $longbasedir/label/${hemi}.aparc.${DESTRIEUX_NAME}.annot)
    endif
    set cmd = ($cmd $subjid $hemi ../surf/$hemi.sphere.reg $CPAtlas $annot)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_ca_label_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.aparc2.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------------                         -----------------#
#---------------- Cortical Parcellation 3 -----------------#
##---------------       -cortparc3        -----------------#
#----------------                         -----------------#
if($DoCortParc3) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------"\
      |& tee -a $LF |& tee -a $CF
    echo "#@# Cortical Parc 3 $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts mris_ca_label $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set CPAtlas = ${GCSDIR}/${hemi}.${DKTATLAS_GCS}
    set annot = ../label/$hemi.aparc.${DKTATLAS_NAME}.annot
    set cmd = (mris_ca_label)
    if($UseAseg) set cmd = ($cmd -l ../label/$hemi.cortex.label)
    if($UseAseg) set cmd = ($cmd -aseg ../mri/$AsegForSurf)
    if($NoRandomness) set cmd = ($cmd -seed $RngSeed)
    set cmd = ($cmd $xopts)
    if($longitudinal) then
      # longitudinal:
      set cmd = ($cmd -long -R \
                   $longbasedir/label/${hemi}.aparc.${DKTATLAS_NAME}.annot)
    endif
    set cmd = ($cmd $subjid $hemi ../surf/$hemi.sphere.reg $CPAtlas $annot)
    echo "\n $cmd \n" |& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_ca_label_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.aparc2.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------                ----------#
#---------- WM/GM Contrast ----------#
##---------  -pctsurfcon   ----------#
#----------                ----------#
# for longitutinal stream, skip in base (as rawavg does not exist)
if($DoPctSurfCon && ( ! $DoCreateBaseSubj )) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# WM/GM Contrast $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set xopts = `fsr-getxopts pctsurfcon $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (pctsurfcon --s $subjid)
    if($hemi == lh) set cmd = ($cmd --lh-only)
    if($hemi == rh) set cmd = ($cmd --rh-only)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = pctsurfcon_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.pctsurfcon.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#-----------------                         ------------------#
#----------------- Relabel Hypointensities ------------------#
##----------------      -hyporelabel       ------------------#
#-----------------                        ------------------ #
if($DoRelabelHypos) then
  echo "#-----------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# Relabel Hypointensities `date`" \
    |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF
  set xopts = `fsr-getxopts mri_relabel_hypointensities $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (mri_relabel_hypointensities $xopts)
  if ($LHonly) set cmd = ($cmd -lh )
  if ($RHonly) set cmd = ($cmd -rh )
  if ($NoWMSA) then
    set cmd = (cp aseg.presurf.mgz  aseg.presurf.hypos.mgz)
  else
    set cmd = ($cmd aseg.presurf.mgz ../surf aseg.presurf.hypos.mgz)
  endif
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/relabelhypos.touch
endif

#-----------------             ------------------ #
#-----------------  Final Aseg ------------------ #
##----------------  -apas2aseg ------------------ #
#--- Not really apas2aseg, but keeping the flag - #
if($DoAPas2ASeg) then
  echo "#-----------------------------------------"  |& tee -a $LF |& tee -a $CF
  echo "#@# APas-to-ASeg `date`"  |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF
  set cmd = (mri_surf2volseg --o aseg.mgz --i aseg.presurf.hypos.mgz \
     --fix-presurf-with-ribbon $mdir/ribbon.mgz --threads $OMP_NUM_THREADS)
  set udlist = aseg.presurf.hypos.mgz 
  if(! $RHonly) then
    set udlist = ($udlist $ldir/lh.cortex.label $sdir/lh.white $sdir/lh.pial)
    set cmd = ($cmd  --lh-cortex-mask $ldir/lh.cortex.label --lh-white $sdir/lh.white --lh-pial $sdir/lh.pial)
  endif
  if(! $LHonly) then
    set udlist = ($udlist $ldir/rh.cortex.label $sdir/rh.white $sdir/rh.pial)
    set cmd = ($cmd  --rh-cortex-mask $ldir/rh.cortex.label --rh-white $sdir/rh.white --rh-pial $sdir/rh.pial)
  endif
  if($LHonly) set cmd = ($cmd --lh)
  if($RHonly) set cmd = ($cmd --rh)
  set xopts = `fsr-getxopts mri_surf2volseg-aseg $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = ($cmd $xopts)
  set ud = `UpdateNeeded aseg.mgz $udlist`
  if($ud || $ForceUpdate) then
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    echo $cmd > $touchdir/apas2aseg.touch
  else
    echo "Updated not needed forf aseg.mgz" | tee -a $LF
  endif
endif

# Cache global brain volume stats (needs aseg.mgz above). WMParc because it computes stats
if(($DoSegStats || $DoParcStats || $DoParcStats2 || $DoParcStats3 || $DoWMParc) && \
  ! $LHonly && ! $RHonly) then
  set cmd = (mri_brainvol_stats --subject $subjid)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
endif

#-----------------               -----------------#
##----------------  -aparc2aseg  -----------------#
#-----------------               -----------------#
if($DoAParc2ASeg) then
  cd $subjdir/mri > /dev/null
  foreach parc (aparc aparc.$DESTRIEUX_NAME aparc.$DKTATLAS_NAME)
    echo "#-----------------------------------------" |& tee -a $LF |& tee -a $CF
    echo "#@# AParc-to-ASeg ${parc} `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
    $PWD |& tee -a $LF
    if($parc == aparc || $parc == aparc.${DKTATLAS_NAME}) then
      set lhbase = 1000;
      set rhbase = 2000;
    endif
    if($parc == aparc.${DESTRIEUX_NAME}) then
      set lhbase = 11100
      set rhbase = 12100
    endif
    set cmd = (mri_surf2volseg --o $parc+aseg.mgz --label-cortex --i aseg.mgz --threads $OMP_NUM_THREADS)
    set udlist = aseg.mgz 
    if(! $RHonly) then
      set udlist = ($udlist $ldir/lh.$parc.annot $ldir/lh.cortex.label $sdir/lh.white $sdir/lh.pial)
      set cmd = ($cmd --lh-annot $ldir/lh.$parc.annot $lhbase --lh-cortex-mask $ldir/lh.cortex.label \
       --lh-white $sdir/lh.white --lh-pial $sdir/lh.pial)
    endif
    if(! $LHonly) then
      set udlist = ($udlist $ldir/rh.$parc.annot $ldir/rh.cortex.label $sdir/rh.white $sdir/rh.pial)
      set cmd = ($cmd --rh-annot $ldir/rh.$parc.annot $rhbase --rh-cortex-mask $ldir/rh.cortex.label \
       --rh-white $sdir/rh.white --rh-pial $sdir/rh.pial)
    endif
    if($LHonly) set cmd = ($cmd --lh)
    if($RHonly) set cmd = ($cmd --rh)
    set xopts = `fsr-getxopts mri_surf2volseg-$parc+aseg $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = ($cmd $xopts)
    set ud = `UpdateNeeded $parc+aseg.mgz $udlist`
    if($ud || $ForceUpdate) then
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
      echo $cmd > $touchdir/apas2aseg.touch
    else
      echo "Updated not needed forf $parc+aseg.mgz" | tee -a $LF
    endif
  end
endif

#-----------------          ------------------#
##----------------  -wmparc ------------------#
#-----------------          ------------------#
if($DoWMParc) then
  echo "#-----------------------------------------"  |& tee -a $LF |& tee -a $CF
  echo "#@# WMParc `date`"  |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir/mri > /dev/null
  $PWD |& tee -a $LF
  set lhbase = 3000;
  set rhbase = 4000;
  set parc = aparc
  set cmd = (mri_surf2volseg --o wmparc.mgz --label-wm --i aparc+aseg.mgz --threads $OMP_NUM_THREADS)
  set udlist = aparc+aseg.mgz 
  if(! $RHonly) then
    set udlist = ($udlist $ldir/lh.$parc.annot $ldir/lh.cortex.label $sdir/lh.white $sdir/lh.pial)
    set cmd = ($cmd --lh-annot $ldir/lh.$parc.annot $lhbase --lh-cortex-mask $ldir/lh.cortex.label \
     --lh-white $sdir/lh.white --lh-pial $sdir/lh.pial)
  endif
  if(! $LHonly) then
    set udlist = ($udlist $ldir/rh.$parc.annot $ldir/rh.cortex.label $sdir/rh.white $sdir/rh.pial)
    set cmd = ($cmd --rh-annot $ldir/rh.$parc.annot $rhbase --rh-cortex-mask $ldir/rh.cortex.label \
     --rh-white $sdir/rh.white --rh-pial $sdir/rh.pial)
  endif
  if($LHonly) set cmd = ($cmd --lh)
  if($RHonly) set cmd = ($cmd --rh)
  set xopts = `fsr-getxopts mri_surf2volseg-wmparc $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = ($cmd $xopts)
  set ud = `UpdateNeeded wmparc.mgz $udlist`
  if($ud || $ForceUpdate) then
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;
    echo $cmd > $touchdir/apas2aseg.touch
  else
    echo "Updated not needed for wmparc.mgz" | tee -a $LF
  endif

  cd $subjdir
  set cmd = (mri_segstats)
  if ($NoRandomness) set cmd = ($cmd --seed $RngSeed)
  set cmd = ($cmd --seg mri/wmparc.mgz --sum stats/wmparc.stats \
    --pv mri/norm.mgz --excludeid 0 \
    --brainmask mri/brainmask.mgz --in mri/norm.mgz --in-intensity-name norm \
    --in-intensity-units MR --subject $subjid --surf-wm-vol \
    --ctab $FREESURFER_HOME/WMParcStatsLUT.txt )
  if ( -e mri/transforms/talairach.xfm ) then
    set cmd = ($cmd --etiv);
  else
    echo "INFO: mri_segstats will not calculate eTIV" |& tee -a $LF
    echo "      due to missing talairach.xfm file" |& tee -a $LF
  endif
  if(-e $synthsegtiv) set cmd = ($cmd --stiv $synthsegtiv)
  if ($RHonly || $LHonly) set cmd = ($cmd --no-global-stats)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  set cmd = ($cmd $xopts);
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/wmaparc.stats.touch
endif

#----------                          -----------#
#---------- Surface Anatomical Stats -----------#
##---------       -parcstats         -----------#
#----------                          -----------#
if($DoParcStats) then

  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Parcellation Stats $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set annot = ../label/$hemi.aparc.annot
    set ctab  = ../label/aparc.annot.ctab
    set xopts = `fsr-getxopts mris_anatomical_stats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    foreach surfname (white pial)
      if($surfname == white) set stats = ../stats/$hemi.aparc.stats
      if($surfname == pial)  set stats = ../stats/$hemi.aparc.pial.stats
      set cmd = (mris_anatomical_stats $TH3Opt -mgz)
      if ($RHonly || $LHonly) set cmd = ($cmd -noglobal)
      if($UseAseg) set cmd = ($cmd -cortex ../label/$hemi.cortex.label)
      set cmd = ($cmd -f $stats -b -a $annot -c $ctab $xopts \
        $subjid $hemi $surfname);
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($DoParallel) then
        set CMDF = mris_anatomical_stats_${hemi}_${surfname}.cmd
        echo "$cmd" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      else
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    end
    echo $cmd > $touchdir/$hemi.aparcstats.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------                            ------------#
#---------- Surface Anatomical Stats 2 ------------#
##---------         -parcstats2         -----------#
#----------                            ------------#
if($DoParcStats2) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Parcellation Stats 2 $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set annot = ../label/$hemi.aparc.${DESTRIEUX_NAME}.annot
    set stats = ../stats/$hemi.aparc.${DESTRIEUX_NAME}.stats
    set ctab  = ../label/aparc.annot.${DESTRIEUX_NAME}.ctab
    set xopts = `fsr-getxopts mris_anatomical_stats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_anatomical_stats  $TH3Opt -mgz)
    if ($RHonly || $LHonly) set cmd = ($cmd -noglobal)
    if($UseAseg) set cmd = ($cmd -cortex ../label/$hemi.cortex.label)
    set cmd = ($cmd -f $stats -b -a $annot -c $ctab $xopts $subjid $hemi white);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_anatomical_stats_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.aparcstats2.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#----------                            -----------#
#---------- Surface Anatomical Stats 3 -----------#
##---------         -parcstats3        -----------#
#----------                            -----------#
if($DoParcStats3) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Parcellation Stats 3 $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set annot = ../label/$hemi.aparc.${DKTATLAS_NAME}.annot
    set stats = ../stats/$hemi.aparc.${DKTATLAS_NAME}.stats
    set ctab  = ../label/aparc.annot.${DKTATLAS_NAME}.ctab
    set xopts = `fsr-getxopts mris_anatomical_stats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_anatomical_stats  $TH3Opt -mgz)
    if ($RHonly || $LHonly) set cmd = ($cmd -noglobal)
    if($UseAseg) set cmd = ($cmd -cortex ../label/$hemi.cortex.label)
    set cmd = ($cmd -f $stats -b -a $annot -c $ctab $xopts $subjid $hemi white);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_anatomical_stats_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.aparcstats3.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#--------------            --------------#
##-------------  -segstats --------------#
#--------------            --------------#
if($DoSegStats) then
  # Stats on the automatic segmentation
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# ASeg Stats `date`" \
    |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir > /dev/null
  $PWD |& tee -a $LF
  set xopts = `fsr-getxopts mri_segstats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (mri_segstats)
  if ($NoRandomness) set cmd = ($cmd --seed $RngSeed)
  set cmd = ($cmd --seg mri/aseg.mgz --sum stats/aseg.stats) # This should probably be aseg.presurf
  set cmd = ($cmd --pv mri/norm.mgz --empty)
  set cmd = ($cmd --brainmask mri/brainmask.mgz --brain-vol-from-seg)
  set cmd = ($cmd --excludeid 0 --excl-ctxgmwm)
  if ( -e mri/ribbon.mgz ) then
    set cmd = ($cmd --supratent)
  else
    echo "\nINFO: mri_segstats will not calculate Supratentorial" |& tee -a $LF
    echo "      due to missing ribbon.mgz file" |& tee -a $LF
  endif
  set cmd = ($cmd --subcortgray)
  set cmd = ($cmd --in mri/norm.mgz --in-intensity-name norm)
  set cmd = ($cmd --in-intensity-units MR)
  if ( -e mri/transforms/talairach.xfm ) then
    set cmd = ($cmd --etiv);
  else
    echo "\nINFO: mri_segstats will not calculate eTIV" |& tee -a $LF
    echo "      due to missing talairach.xfm file" |& tee -a $LF
  endif
  if(-e $synthsegtiv) set cmd = ($cmd --stiv $synthsegtiv)
  if ( ( -e surf/lh.white$FS_GII ) && ( -e surf/rh.white$FS_GII ) ) then
    set cmd = ($cmd --surf-wm-vol)
    if ( ( -e surf/lh.pial$FS_GII ) && ( -e surf/rh.pial$FS_GII ) ) then
      set cmd = ($cmd --surf-ctx-vol --totalgray)
    else
      echo "\nINFO: ?h.pial$FS_GII surfaces not available to mri_segstats.\n"\
       |& tee -a $SF |& tee -a $LF |& tee -a $CF
    endif
  else
    echo "\nINFO: ?h.white$FS_GII surfaces not available to mri_segstats.\n"\
     |& tee -a $SF |& tee -a $LF |& tee -a $CF
  endif
  if( ( -e surf/lh.orig.nofix$FS_GII ) && ( -e surf/rh.orig.nofix$FS_GII ) ) then
     set cmd = ($cmd --euler)
  endif
  set cmd = ($cmd --ctab $FREESURFER_HOME/ASegStatsLUT.txt)
  set cmd = ($cmd --subject $subjid $xopts);
  if ($RHonly || $LHonly) set cmd = ($cmd --no-global-stats)
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/segstats.touch
endif

#--------------                    -----------------#
##-------------  -aparc+aseg-stats -----------------#
#--------------                    -----------------#
# This is not something you want to do in general. The volumes
# of cortical structures should be obtained from the aparc.stats,
# but getting the intensity means and stddevs can be useful.
if($DoAParcASegStats) then
  echo "#--------------------------------------------" \
    |& tee -a $LF |& tee -a $CF
  echo "#@# AParcASeg Stats `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF
  cd $subjdir > /dev/null
  set xopts = `fsr-getxopts mri_segstats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
  set cmd = (mri_segstats)
  if ($NoRandomness) set cmd = ($cmd --seed $RngSeed)
  set cmd = ($cmd --seg mri/aparc+aseg.mgz --sum stats/aparc+aseg.stats)
  set cmd = ($cmd --pv mri/norm.mgz )
  set cmd = ($cmd --excludeid 0 --ctab-default --empty)
  set cmd = ($cmd --brain-vol-from-seg --brainmask mri/brainmask.mgz)
  set cmd = ($cmd --in mri/norm.mgz --in-intensity-name norm)
  set cmd = ($cmd --in-intensity-units MR)
  set cmd = ($cmd --subject $subjid);
  if ( -e mri/transforms/talairach.xfm ) then
    set cmd = ($cmd --etiv);
  else
    echo "INFO: mri_segstats will not calculate eTIV" |& tee -a $LF
    echo "      due to missing talairach.xfm file" |& tee -a $LF
  endif
  if(-e $synthsegtiv) set cmd = ($cmd --stiv $synthsegtiv)
  set cmd = ($cmd $xopts);
  if ($RHonly || $LHonly) set cmd = ($cmd --no-global-stats)
  $PWD |& tee -a $LF
  echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
  if($RunIt) $fs_time $cmd |& tee -a $LF
  if($status) goto error_exit;
  echo $cmd > $touchdir/aparc+aseg.stats.touch
endif

#--------                      --------#
#-------- Brodmann Area Labels --------#
##-------      -balabels       --------#
#--------                      --------#
# Create Brodmann area labels by mapping from fsaverage,
# then create the ?h.BA_exvivo.annot file from these labels,
# then generate a ?h.BA_exvivo.stats file from that annot.
if ($DoBaLabels) then
  cd $subjdir/label
  $PWD |& tee -a $LF

  # if fsaverage is not in subjects dir, put it there
  set HaveFsAverage=1;
  if ( ! -e $SUBJECTS_DIR/fsaverage) then
    echo "INFO: fsaverage subject does not exist in SUBJECTS_DIR" \
      |& tee -a $LF |& tee -a $CF
    set HaveFsAverage=0;
  else
    # check if the latest-greatest fsaverage is here (which would not be
    # the case if running on subjects processed by an older version)
    if ( ! -e $SUBJECTS_DIR/fsaverage/label/lh.entorhinal_exvivo.thresh.label) then
      echo "INFO: fsaverage subject does not have uptodate *rhinal labels!" \
        |& tee -a $LF |& tee -a $CF
      set HaveFsAverage=0;
      set cmd=(rm -Rf fsaverage)
      echo "\n cd $SUBJECTS_DIR; $cmd; cd - \n"|& tee -a $LF |& tee -a $CF
      cd $SUBJECTS_DIR
      if($RunIt && -e fsaverage) $fs_time $cmd |& tee -a $LF
      cd -
    endif
  endif
  if ( ! $HaveFsAverage ) then
    echo "INFO: Creating symlink to fsaverage subject..." \
      |& tee -a $LF |& tee -a $CF
    set cmd=(ln -s $FREESURFER_HOME/subjects/fsaverage)
    echo "\n cd $SUBJECTS_DIR; $cmd; cd - \n"|& tee -a $LF |& tee -a $CF
    cd $SUBJECTS_DIR
    if($RunIt && ! -e fsaverage) $cmd |& tee -a $LF
    cd -
  endif

  foreach hemi ($hemilist)
    echo "#--------------------------------------------"|& tee -a $LF |& tee -a $CF 
    echo "#@# BA_exvivo Labels $hemi `date`" |& tee -a $SF |& tee -a $LF |& tee -a $CF

    # need to split parallel processing into sets so as not to exceed 4GB
    set EV_LABELS_1 = (BA1_exvivo  BA2_exvivo BA3a_exvivo  BA3b_exvivo  BA4a_exvivo)
    set EV_LABELS_2 = (BA4p_exvivo BA6_exvivo BA44_exvivo  BA45_exvivo)
    set EV_LABELS_3 = (V1_exvivo V2_exvivo MT_exvivo entorhinal_exvivo perirhinal_exvivo)
    # labels from Grill-Spector at the Stanford Vision and Perception Neuroscience Lab
    # http://vpnl.stanford.edu/vcAtlas, MPM = max prop map
    set EV_LABELS_4 = (FG1.mpm.vpnl FG2.mpm.vpnl FG3.mpm.vpnl FG4.mpm.vpnl \
                       hOc1.mpm.vpnl hOc2.mpm.vpnl hOc3v.mpm.vpnl hOc4v.mpm.vpnl)
    set ALL_EV_LABELS = ("$EV_LABELS_1" "$EV_LABELS_2" "$EV_LABELS_3" "$EV_LABELS_4")
    set EV_IDXS = (1 2 3) # Don't include 4 here

    # generate labels
    # run in three sets, so as not to consume more than 4GB in parallel mode
    foreach labelset ($EV_IDXS 4)
      set CMDFS = () # see earlier notes on -parallel implementation
      foreach balabel ( $ALL_EV_LABELS[$labelset] )
        if ( ! -e $SUBJECTS_DIR/fsaverage/label/${hemi}.${balabel}.label ) then
          echo "-------------------------------------------------------------------------" |& tee -a $LF |& tee -a $CF
          echo "ERROR: Label ${balabel} does not exist in SUBJECTS_DIR fsaverage!"         |& tee -a $LF |& tee -a $CF
          echo "       The fsaverage link probably points to an older freesurfer version"  |& tee -a $LF |& tee -a $CF
          echo " $SUBJECTS_DIR/fsaverage/label/${hemi}.${balabel}.label" |& tee -a $LF |& tee -a $CF
          echo "-------------------------------------------------------------------------" |& tee -a $LF |& tee -a $CF
          goto error_exit;
        endif
        set cmd=(mri_label2label \
          --srcsubject fsaverage \
          --srclabel $SUBJECTS_DIR/fsaverage/label/${hemi}.${balabel}.label \
          --trgsubject $subjid \
          --trglabel ./${hemi}.${balabel}.label \
          --hemi ${hemi} \
          --regmethod surface)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($DoParallel) then
          set CMDF = mri_label2label_${balabel}_${hemi}.cmd
          echo "$cmd" > $CMDF
          set CMDFS = ( $CMDFS $CMDF )
        else
          if($RunIt) $fs_time $cmd |& tee -a $LF
          if($status) goto error_exit;
        endif
      end # balabel
      if($RunIt && $DoParallel) then
        reconbatchjobs $LF $CMDFS |& tee -a $LF
        if($status) goto error_exit;
      endif
    end # labelset

    # merge labels from Grill-Spector at the Stanford Vision and Perception Neuroscience Lab
    set annot = ./$hemi.mpm.vpnl.annot
    if($RunIt) rm -f $annot
    set ctabvpnl = $FREESURFER_HOME/average/colortable_vpnl.txt
    set cmd = (mris_label2annot --s $subjid  --ctab $ctabvpnl --hemi $hemi \
       --a mpm.vpnl --maxstatwinner --noverbose \
       --l $hemi.FG1.mpm.vpnl.label   --l $hemi.FG2.mpm.vpnl.label \
       --l $hemi.FG3.mpm.vpnl.label   --l $hemi.FG4.mpm.vpnl.label \
       --l $hemi.hOc1.mpm.vpnl.label  --l $hemi.hOc2.mpm.vpnl.label \
       --l $hemi.hOc3v.mpm.vpnl.label --l $hemi.hOc4v.mpm.vpnl.label)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    # generate .thresh labels
    # run in three sets, so as not to consume more than 4GB in parallel mode
    foreach labelset ($EV_IDXS)
      set CMDFS = () # see earlier notes on -parallel implementation
      foreach balabel ( $ALL_EV_LABELS[$labelset] )
        set cmd=(mri_label2label \
          --srcsubject fsaverage \
          --srclabel $SUBJECTS_DIR/fsaverage/label/${hemi}.${balabel}.thresh.label \
          --trgsubject $subjid \
          --trglabel ./${hemi}.${balabel}.thresh.label \
          --hemi ${hemi} \
          --regmethod surface)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($DoParallel) then
          set CMDF = mri_label2label_${balabel}_${hemi}.cmd
          echo "$cmd" > $CMDF
          set CMDFS = ( $CMDFS $CMDF )
        else
          if($RunIt) $fs_time $cmd |& tee -a $LF
          if($status) goto error_exit;
        endif
      end # balabel
      if($RunIt && $DoParallel) then
        reconbatchjobs $LF $CMDFS |& tee -a $LF
        if($status) goto error_exit;
      endif
    end # labelsets

    # create .annot
    set cmd=(mris_label2annot \
        --s $subjid \
        --hemi $hemi \
        --ctab $FREESURFER_HOME/average/colortable_BA.txt \
        --l $hemi.BA1_exvivo.label \
        --l $hemi.BA2_exvivo.label \
        --l $hemi.BA3a_exvivo.label \
        --l $hemi.BA3b_exvivo.label \
        --l $hemi.BA4a_exvivo.label \
        --l $hemi.BA4p_exvivo.label \
        --l $hemi.BA6_exvivo.label \
        --l $hemi.BA44_exvivo.label \
        --l $hemi.BA45_exvivo.label \
        --l $hemi.V1_exvivo.label \
        --l $hemi.V2_exvivo.label \
        --l $hemi.MT_exvivo.label \
        --l $hemi.perirhinal_exvivo.label \
        --l $hemi.entorhinal_exvivo.label \
        --a BA_exvivo \
        --maxstatwinner \
        --noverbose )
    if($RunIt) if ( -e ./$hemi.BA_exvivo.annot) rm -fv ./$hemi.BA_exvivo.annot
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    # create .thresh.annot
    set cmd=(mris_label2annot \
        --s $subjid \
        --hemi $hemi \
        --ctab $FREESURFER_HOME/average/colortable_BA_thresh.txt \
        --l $hemi.BA1_exvivo.thresh.label \
        --l $hemi.BA2_exvivo.thresh.label \
        --l $hemi.BA3a_exvivo.thresh.label \
        --l $hemi.BA3b_exvivo.thresh.label \
        --l $hemi.BA4a_exvivo.thresh.label \
        --l $hemi.BA4p_exvivo.thresh.label \
        --l $hemi.BA6_exvivo.thresh.label \
        --l $hemi.BA44_exvivo.thresh.label \
        --l $hemi.BA45_exvivo.thresh.label \
        --l $hemi.V1_exvivo.thresh.label \
        --l $hemi.V2_exvivo.thresh.label \
        --l $hemi.MT_exvivo.thresh.label \
        --l $hemi.perirhinal_exvivo.thresh.label \
        --l $hemi.entorhinal_exvivo.thresh.label \
        --a BA_exvivo.thresh \
        --maxstatwinner \
        --noverbose )
    if($RunIt) if ( -e ./$hemi.BA_exvivo.thresh.annot) rm -fv ./$hemi.BA_exvivo.thresh.annot
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    # generate stats
    set annot = ./$hemi.BA_exvivo.annot
    set stats = ../stats/$hemi.BA_exvivo.stats
    set ctab  = ./BA_exvivo.ctab
    set xopts = `fsr-getxopts mris_anatomical_stats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_anatomical_stats  $TH3Opt -mgz )
    if ($RHonly || $LHonly) set cmd = ($cmd -noglobal)
    set cmd = ($cmd -f $stats \
            -b -a $annot -c $ctab $xopts $subjid $hemi white);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    # generate .thresh stats
    set annot = ./$hemi.BA_exvivo.thresh.annot
    set stats = ../stats/$hemi.BA_exvivo.thresh.stats
    set ctab  = ./BA_exvivo.thresh.ctab
    set xopts = `fsr-getxopts mris_anatomical_stats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_anatomical_stats  $TH3Opt -mgz -f $stats)
    if ($RHonly || $LHonly) set cmd = ($cmd -noglobal)
    set cmd = ($cmd  -b -a $annot -c $ctab $xopts $subjid $hemi white);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

  end # hemi
endif # DoBaLabels

#----------            ------------#
##---------  -label-V1 ------------#
#----------            ------------#
if($DoLabelV1) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Label V1 $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    if ( ! -e $SUBJECTS_DIR/V1_average) then
      echo "ERROR: V1_average subject does not exist in SUBJECTS_DIR!"
      goto error_exit;
    endif
    cd $subjdir/label > /dev/null
    $PWD |& tee -a $LF
    set cmd=(predict_v1.sh)
    if( ! $RunIt) set cmd=($cmd -p)
    set cmd = ($cmd -h $hemi $subjid);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = predicit_v1_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.label_v1.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

#--------                          --------#
#-------- Entorhinal Cortex Labels --------#
##-------  -label-exvivo-ec-avg    --------#
#--------                          --------#
# create entorhinal cortex labels by mapping from exvivo subjects,
# then generate ?h.EC_exvivo_average.stats files
if ($DoLabelExvivoEC) then
  cd $subjdir/label
  $PWD |& tee -a $LF
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
        |& tee -a $LF |& tee -a $CF
    echo "#@# Ex-vivo Entorhinal Cortex Label $hemi `date`" \
        |& tee -a $SF |& tee -a $LF |& tee -a $CF
    if ( ! -e $SUBJECTS_DIR/${hemi}.EC_average) then
      echo "INFO: ${hemi}.EC_average subject does not exist in SUBJECTS_DIR" \
        |& tee -a $LF |& tee -a $CF
      echo "INFO: Creating symlink to ${hemi}.EC_average subject..." \
        |& tee -a $LF |& tee -a $CF
      set cmd=(ln -s $FREESURFER_HOME/subjects/${hemi}.EC_average)
      echo "\n cd $SUBJECTS_DIR; $cmd; cd - \n"|& tee -a $LF |& tee -a $CF
      cd $SUBJECTS_DIR
      if($RunIt && ! -e ${hemi}.EC_average) $cmd |& tee -a $LF
      cd -
    endif

    # generate label
    set cmd = (mris_spherical_average \
                 -erode 1 \
                 -orig white \
                 -t 0.4 \
                 -o ${subjid} \
                 label ${hemi}.entorhinal \
                 $hemi sphere.reg \
                 ${hemi}.EC_average \
                 ${hemi}.EC_exvivo_average.label)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

    # generate stats
    set label = ./$hemi.EC_exvivo_average.label
    set stats = ../stats/$hemi.EC_exvivo_average.stats
    set xopts = `fsr-getxopts mris_anatomical_stats $V8XoptsFile $GlobXOptsFile $XOptsFile `;
    set cmd = (mris_anatomical_stats  $TH3Opt -mgz)
    if ($RHonly || $LHonly) set cmd = ($cmd -noglobal)
    set cmd = ($cmd -f $stats \
            -b -l $label $xopts $subjid $hemi white);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($RunIt) $fs_time $cmd |& tee -a $LF
    if($status) goto error_exit;

  end # hemi
endif # DoLabelExvivoEC


#--------                          --------#
#-------- Local Gyrification Index --------#
##-------           -lgi           --------#
#--------                          --------#
if ($DoLocalGyriIndex) then
  cd $subjdir/surf
  $PWD |& tee -a $LF
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#--------------------------------------------" \
        |& tee -a $LF |& tee -a $CF
    echo "#@# Local Gyrification Index $hemi `date`" \
        |& tee -a $SF |& tee -a $LF |& tee -a $CF
    set cmd=(mris_compute_lgi --i ${hemi}.pial)
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = mris_compute_lgi_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
  end # hemi
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif # DoLocalGyriIndex


#-----------------          ------------------#
##----------------  -qcache ------------------#
#-----------------          ------------------#
# Create the smoothed surfaces to fsaverage target needed by Qdec.
if ($DoQdecCache) then
  # check for the target subject 'fsaverage' (if using as default target)
  # and create symlink from distribution dir if not found in subjects dir
  if (("${target}" == "fsaverage") && ( ! -e $SUBJECTS_DIR/fsaverage)) then
    echo "INFO: fsaverage subject does not exist in SUBJECTS_DIR" \
      |& tee -a $LF |& tee -a $CF
    echo "INFO: Creating symlink to fsaverage subject..." \
      |& tee -a $LF |& tee -a $CF
    set cmd=(ln -s $FREESURFER_HOME/subjects/fsaverage)
    echo "\n cd $SUBJECTS_DIR; $cmd; cd - \n"|& tee -a $LF |& tee -a $CF
    cd $SUBJECTS_DIR
    if($RunIt && ! -e fsaverage) $cmd |& tee -a $LF
    cd -
  endif

  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    foreach measure ($measurelist)
      echo "#--------------------------------------------" \
          |& tee -a $LF |& tee -a $CF
      echo "#@# Qdec Cache preproc $hemi $measure $target `date`" \
          |& tee -a $SF |& tee -a $LF |& tee -a $CF

      if ("${measuredir}" != "") then
        cd ${measuredir}
      else
        cd $subjdir/surf
      endif
      $PWD |& tee -a $LF

      set MeasFile=(${hemi}.${measure})
      # strip .mgz from filename (does nothing if not .mgz extension):
      set MeasFile=`basename ${MeasFile} .mgz`
      set MeasFile=(${MeasFile}.${target})
      set cmd=(mris_preproc \
          --s ${subjid} \
          --hemi ${hemi} \
          --meas ${measure} \
          --target ${target} \
          --out ${MeasFile}.mgh)
      if ("${measuredir}" != "") set cmd = ($cmd --surfdir ${measuredir})
      echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
      if($DoParallel) then
        set CMDF = mris_preproc_${hemi}_${measure}_${target}.cmd
        echo "$cmd" > $CMDF
        set CMDFS = ( $CMDFS $CMDF )
      else
        if($RunIt) $fs_time $cmd |& tee -a $LF
        if($status) goto error_exit;
      endif
    end # measure
  end # hemi
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif

  # now surf2surf
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    foreach measure ($measurelist)
      set MeasFile=(${hemi}.${measure})
      # strip .mgz from filename (does nothing if not .mgz extension):
      set MeasFile=`basename ${MeasFile} .mgz`
      set MeasFile=(${MeasFile}.${target})
      foreach fwhm ($fwhmlist)
        echo "#--------------------------------------------" \
            |& tee -a $LF |& tee -a $CF
        echo "#@# Qdec Cache surf2surf $hemi $measure fwhm$fwhm $target `date`" \
            |& tee -a $SF |& tee -a $LF |& tee -a $CF
        set OutFile=(${hemi}.${measure})
        # strip .mgz from filename (does nothing if not .mgz extension):
        set OutFile=`basename ${OutFile} .mgz`
        set OutFile=(${OutFile}.fwhm${fwhm}.${target})
        set cmd=(mri_surf2surf --prune\
            --s ${target} \
            --hemi ${hemi} \
            --fwhm ${fwhm} \
            --sval ${MeasFile}.mgh \
            --tval ${OutFile}.mgh)
        if($SmoothCortexOnly)   set cmd = ($cmd --cortex)
        if(! $SmoothCortexOnly) set cmd = ($cmd --no-cortex)
        echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
        if($DoParallel) then
          set CMDF = mris_surf2surf_${hemi}_${measure}_${fwhm}_${target}.cmd
          echo "$cmd" > $CMDF
          set CMDFS = ( $CMDFS $CMDF )
        else
          if($RunIt) $fs_time $cmd |& tee -a $LF
          if($status) goto error_exit;
        endif
        echo $cmd > $touchdir/${hemi}.${measure}.${fwhm}.qcache.touch
      end # fwhm
    end # measure
  end # hemi
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif

  # file move
  foreach hemi ($hemilist)
    foreach measure ($measurelist)
      foreach fwhm ($fwhmlist)
        set OutFile=(${hemi}.${measure})
        # strip .mgz from filename (does nothing if not .mgz extension):
        set OutFile=`basename ${OutFile} .mgz`
        set OutFile=(${OutFile}.fwhm${fwhm}.${target})
        if($RunIt) then
          if ("${measuredir}" != "") then
            set cmd = (mv -f -v ${OutFile}.mgh $subjdir/surf)
            echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
            $cmd |& tee -a $LF
          endif
        endif
        echo $cmd > $touchdir/$hemi.$measure.$fwhm.qcache.touch
      end # fwhm
    end # measure
  end # hemi

  if($RunIt) rm -Rf tmp.mris_preproc.* # cleanup
endif # DoQdecCache


#----------                                     --------------#
#---------- Surface Vertices Number Match Check --------------#
##---------             -vno-check              --------------#
#----------                                     --------------#
if($DoVnoMatchCheck) then
  set CMDFS = () # see earlier notes on -parallel implementation
  foreach hemi ($hemilist)
    echo "#-----------------------------------------" \
      |& tee -a $LF |& tee -a $CF
    echo "#@# Vno Match Check $hemi `date`" \
      |& tee -a $SF |& tee -a $LF |& tee -a $CF
    cd $subjdir/scripts > /dev/null
    $PWD |& tee -a $LF
    set cmd = (vno_match_check $subjid $hemi);
    echo "\n $cmd \n"|& tee -a $LF |& tee -a $CF
    if($DoParallel) then
      set CMDF = vno_match_check_${hemi}.cmd
      echo "$cmd" > $CMDF
      set CMDFS = ( $CMDFS $CMDF )
    else
      if($RunIt) $fs_time $cmd |& tee -a $LF
      if($status) goto error_exit;
    endif
    echo $cmd > $touchdir/$hemi.vnomatchcheck.touch
  end # Loop over hemilist
  if($RunIt && $DoParallel) then
    reconbatchjobs $LF $CMDFS |& tee -a $LF
    if($status) goto error_exit;
  endif
endif

if($DoSubfields) then
  echo "Running subfield segmentation scripts ---------------" | tee -a $LF
  set scrlist = (segmentHA_T1.sh segmentThalamicNuclei.sh segmentBS.sh)
  foreach scr ($scrlist)
    echo "#@# $scr `date` --------------" | tee -a $LF
    date | tee -a $LF
    echo "cd `pwd`" | tee -a $LF
    set cmd = ($scr $subjid)
    echo $cmd  |& tee -a $LF
    if($RunIt) $fs_time $cmd  |& tee -a $LF
    if($status) goto error_exit;
  end
  echo "---------------------------------" |& tee -a $LF
  echo "Done with subfield scripts " |& tee -a $LF
endif

if($#TermScriptList) then
  echo "Running termination scripts ---------------" | tee -a $LF
  cd $SUBJECTS_DIR
  foreach TermScript ($TermScriptList)
    echo "Termination script $TermScript --------------" | tee -a $LF
    date | tee -a $LF
    echo "cd `pwd`" | tee -a $LF
    set cmd = ($TermScript $subjid)
    echo $cmd  |& tee -a $LF
    if($RunIt) $fs_time $cmd  |& tee -a $LF
    if($status) goto error_exit;
  end
  echo "---------------------------------" |& tee -a $LF
  echo "Done with termination scripts " |& tee -a $LF
endif

#--------------                    ----------------#
##-------------  END OF RECON-ALL  ----------------#
#--------------                    ----------------#

if($?SET_FS_CMD_TIMING) then
  # copy information about this process for profiling
  cp /proc/$$/status $SUBJECTS_DIR/${subjid}/scripts/proc.status
  # copy information about the cpu for profiling
  cp /proc/cpuinfo $SUBJECTS_DIR/${subjid}/scripts/cpuinfo
  chmod ug+w $SUBJECTS_DIR/${subjid}/scripts/proc.status $SUBJECTS_DIR/${subjid}/scripts/cpuinfo
endif

echo "" |& tee -a $LF

set EndTime = `date`;
set tSecEnd = `date '+%s'`;
@ tSecRun = $tSecEnd - $tSecStart;
set tRunHours = `echo $tSecRun/3600|bc -l`
set tRunHours = `printf %6.3f $tRunHours`
echo "Started at $StartTime " |& tee -a $LF
echo "Ended   at $EndTime" |& tee -a $LF
echo "#@#%# recon-all-run-time-hours $tRunHours" |& tee -a $LF

if($#NotifyFile != 0) then
  echo "INFO: touching notification file $NotifyFile" |& tee -a $LF
  touch $NotifyFile
endif

if($DoIsRunning && $#IsRunningFile) rm -f $IsRunningFile

# Create the Done File
if($#DoneFile) then
  echo "------------------------------" > $DoneFile
  echo "SUBJECT $subjid" >> $DoneFile
  echo "START_TIME $StartTime"      >> $DoneFile
  echo "END_TIME $EndTime"          >> $DoneFile
  echo "RUNTIME_HOURS $tRunHours"   >> $DoneFile
  echo "USER $user"                 >> $DoneFile
  echo "HOST `hostname`"            >> $DoneFile
  echo "PROCESSOR `uname -m`"       >> $DoneFile
  echo "OS `uname -s`"              >> $DoneFile
  echo "UNAME `uname -a`"           >> $DoneFile
  echo "VERSION $FS_RECON_VERSION"  >> $DoneFile
  echo "CMDPATH $0"                 >> $DoneFile
  echo "CMDARGS $argv0"             >> $DoneFile
endif

echo "recon-all -s $subjid finished without error at `date`" \
    |& tee -a $LF |& tee -a $SF

if($#mailuser != 0) then
  echo "recon-all -s $subjid finished without error at `date`" | \
    mail -s "$subjid DONE `date`" $mailuser
endif

echo "done"

# add to usage tracking file, if configured and writable
# a sysadmin would need to have users set the environment var
# RECONALL_USAGE_FILE to a world-writable file. example:
# setenv RECONALL_USAGE_FILE /space/freesurfer/recon-all_run_log
if($?RECONALL_USAGE_FILE) then
  if(-e $RECONALL_USAGE_FILE) then
    if(-w $RECONALL_USAGE_FILE) then
      if ($RunIt) then
        echo "`date` `cat $FREESURFER_HOME/build-stamp.txt`" \
            >> $RECONALL_USAGE_FILE
        endif
      endif
  endif
endif

exit 0

#--------------                  ----------------#
##-------------  EXIT RECON-ALL  ----------------#
#--------------                  ----------------#

#-------------------------------------------------#
error_exit:
#-------------------------------------------------#
  uname -a | tee -a $LF | tee -a $SF
  echo "" |& tee -a $LF |& tee -a $SF
  echo "recon-all -s $subjid exited with ERRORS at `date`" \
    |& tee -a $LF |& tee -a $SF
  echo "" |& tee -a $LF |& tee -a $SF
  echo "For more details, see the log file $LF"
  echo "To report a problem, see http://surfer.nmr.mgh.harvard.edu/fswiki/BugReporting"|& tee -a $LF
  echo ""
  # Handle IsRunningFile
  if($DoIsRunning && $#IsRunningFile) rm -f $IsRunningFile
  # Mail the user
  if($#mailuser != 0) then
    echo "recon-all -s $subjid finished with errors at `date`" | \
      mail -s "$subjid ERROR `date`" $mailuser
  endif
  # Create an error file with date, cmd, etc of error
  if ( $?ErrorFile ) then
    echo "------------------------------" > $ErrorFile
    echo "SUBJECT $subjid" >> $ErrorFile
    echo "DATE `date`"     >> $ErrorFile
    echo "USER $user"      >> $ErrorFile
    echo "HOST `hostname`" >> $ErrorFile
    echo "PROCESSOR `uname -m`" >> $ErrorFile
    echo "OS `uname -s`"    >> $ErrorFile
    uname -a                >> $ErrorFile
    echo $FS_RECON_VERSION  >> $ErrorFile
    echo $0                 >> $ErrorFile
    echo "PWD `pwd`"        >> $ErrorFile
    echo "CMD $cmd"         >> $ErrorFile
  endif
  if($#DoneFile) then
    echo "1" > $DoneFile
  endif
  # Finally exit
  exit 1;
endif

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

while( $#argv != 0 )

  set flag = $argv[1]; shift;

  switch($flag)

    # Note: these two are parsed at the beginning and can also be controlled by FS_V8_XOPTS
    case "-v8": 
    case "--v8": 
      set UseV8 = 1
      setenv FS_V8_XOPTS 1
      breaksw;
    case "-no-v8": 
    case "--no-v8": 
      set UseV8 = 0
      setenv FS_V8_XOPTS 0
      breaksw;
        
    case "-license": 
        if ( $#argv < 1) goto arg1err;
        setenv FS_LICENSE $argv[1]; shift;
	if(! -e $FS_LICENSE) then
          echo "ERROR: cannot find $FS_LICENSE"
          exit 1
        endif
        breaksw;
        
    case "-restart": 
        if ( $#argv < 1) goto arg1err;
        set RestartFile = $argv[1]; shift;
        set DoRestart = 1
        breaksw;
        
    case "-no-cerebellum":
    case "-nocerebellum":
    case "-NO-CEREBELLUM":
    case "-NOCEREBELLUM":
	set nocerebellum=( -nocerebellum)
	breaksw ;
    case "-lh": # see also -hemi
    case "-lh-only":
      set LHonly = 1 ;
      set hemilist = lh
      breaksw
    case "-rh": # see also -hemi
    case "-rh-only":
      set hemilist = rh
      set RHonly = 1 ;
      breaksw
    case "-subject":
    case "-subjid":
    case "-sid":
    case "-s":
    case "--s":
      if ( $#argv < 1) goto arg1err;
      set subjid = $argv[1]; shift;
      set subjid = `basename $subjid`; # removes trailing /
      breaksw

    case "-sb":
      # Hidden option: same as -s but no basename;
      # needed when passing a subdir of a subject
      # as a subject as with xhemi
      if( $#argv < 1) goto arg1err;
      set subjid = $argv[1]; shift;
      set xhemi = 1
      breaksw

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

    case "-i"
    case "--i"
      if( $#argv < 1) goto arg1err;
      set InputVol = "$argv[1]"; shift;
      if(! -e "$InputVol") then
        echo "ERROR: cannot find $InputVol"
        goto error_exit;
      endif
      if (-d "$InputVol") then
        echo "ERROR: You cannot give recon-all a folder as input. It must be an image file."
        echo "If you have multiple files, you need multiple -i flags."
        goto error_exit;
      endif
      if(! -r "$InputVol") then
        echo "ERROR: $InputVol exists but is not readable"
        goto error_exit;
      endif
      set InVolDir  = `dirname  "$InputVol"`;
      set InVolBase = `basename "$InputVol"`;
      pushd $InVolDir > /dev/null
      set InVolDir = `pwd`;
      popd > /dev/null
      set InputVol = "$InVolDir/$InVolBase";
      set InputList = ($InputList "$InputVol");
      set DoConvertInput = 1;
      breaksw

    case "-T2"
    case "-t2"
      if( $#argv < 1) goto arg1err;
      set InputT2Vol = "$argv[1]"; shift;
      if(! -e "$InputT2Vol") then
        echo "ERROR: cannot find $InputT2Vol"
        goto error_exit;
      endif
      if(! -r "$InputT2Vol") then
        echo "ERROR: $InputT2Vol exists but is not readable"
        goto error_exit;
      endif
      set T2InVolDir  = `dirname  "$InputT2Vol"`;
      set T2InVolBase = `basename "$InputT2Vol"`;
      pushd $T2InVolDir > /dev/null
      set T2InVolDir = `pwd`;
      popd > /dev/null
      set InputT2Vol = "$T2InVolDir/$T2InVolBase";
      set DoConvertT2Input = 1;
      # MOD: turn on T2/FLAIR pial editing when FLAIR specified
      # This can backfire, eg, if not all the preceeding steps
      # are included
      set DoT2pial         = 1; 
      breaksw

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

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

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

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

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

    case "-FLAIR"
    case "-flair"
      if( $#argv < 1) goto arg1err;
      set InputFlairVol = "$argv[1]"; shift;
      if(! -e "$InputFlairVol") then
        echo "ERROR: cannot find $InputFlairVol"
        goto error_exit;
      endif
      if(! -r "$InputFlairVol") then
        echo "ERROR: $InputFlairVol exists but is not readable"
        goto error_exit;
      endif
      set FlairInVolDir  = `dirname  "$InputFlairVol"`;
      set FlairInVolBase = `basename "$InputFlairVol"`;
      pushd $FlairInVolDir > /dev/null
      set FlairInVolDir = `pwd`;
      popd > /dev/null
      set InputFlairVol = "$FlairInVolDir/$FlairInVolBase";
      set DoConvertFlairInput = 1;
      # MOD: turn on T2/FLAIR pial editing when FLAIR specified
      # This can backfire, eg, if not all the preceeding steps
      # are included
      set DoFLAIRpial = 1; 
      breaksw

    # flags -long, -no-orig-pial and -uselongbasectrlvol are all associated
    # with longitudinal processing
    case "-long":
    case "-longitudinal":
      set longitudinal = 1;
      set NoRandomness = 1;
      if ( $#argv < 2) goto arg1err;
      # get the subject name to use for timepoint
      set tpNid = $argv[1]; shift;
      set tpNid = `basename $tpNid`; # remove trailing /
      # get the subject to use for the base subject
      set longbaseid = $argv[1]; shift;
      set longbaseid = `basename $longbaseid`; # remove trailing /
      # and create subjid to reflect its longitudinal relation to longbaseid
      set subjid = ${tpNid}.long.${longbaseid}
      breaksw

    case "-uselongbasectrlvol":
      set UseLongbaseCtrlVol = 1;
      breaksw

    case "-uselongbasewmedits":
      set UseLongbaseWMedits = 1;
      breaksw

    case "-long-samseg": 
      # -long-samseg subject_base longtp
      # where base is a subject created with 
      #   samseg2recon --base --s subject_base  --samseg samseglongdir
      #   recon-all -s subject_base -autorecon2-samseg -autorecon3
      # and
      #   longtp is a subject created with
      #   samseg2recon --long tpno --s longtp  --samseg samseglongdir
      # Then run
      #   recon-all -long-samseg  subject_base longtp -autorecon2-samseg -autorecon3
      # The subject names do not need to keep any special pattern
      # samseglongdir is the folder created by samseg-long
      set LongSamseg = 1
      set longitudinal = 1;
      set NoRandomness = 1;
      if ( $#argv < 2) goto arg1err;
      set longbaseid = $argv[1]; shift;
      set longbaseid = `basename $longbaseid`; # remove trailing /
      # get the subject name to use for timepoint
      set subjid = $argv[1]; shift;
      breaksw

    case "-asegfusion":
      set UseAsegFusion = 1;
      set UseAsegBase = 0
      breaksw
    case "-noasegfusion":
      set UseAsegFusion = 0;
      breaksw

    case "-asegbase":
      set UseAsegBase = 1
      set UseAsegFusion = 0;
      breaksw
    case "-noasegbase":
      set UseAsegBase = 0
      breaksw

    case "-addtp":
      # 'fake'-add a new timepoint
      set DoAddTp = 1;
      breaksw

    case "-base-affine":
      set DoAffineBase = 1;
      # don't break here, but also switch on -base:
    case "-base":
      if ( $#argv < 1) goto arg1err;
      set subjid = $argv[1]; shift;
      set subjid = `basename $subjid`; # removes trailing /
      set DoCreateBaseSubj = 1;
      set NoRandomness = 1;
      breaksw

    case "-base-init":
      set DoCreateBaseInput = 1;
      breaksw
    case "-nobase-init":
      set DoCreateBaseInput = 0;
      breaksw

    case "-base-tp":
    case "-tp":
      if ( $#argv < 1) goto arg1err;
      set basetpid = $argv[1]; shift;
      set basetpid = `basename $basetpid`; # removes trailing /
      set BaseSubjsList = ($BaseSubjsList $basetpid);
      if($DoCreateBaseSubj) then
        if ("$basetpid" == "$subjid") then
          echo "ERROR: you need to specify a new ID for the base/template. "
          echo "It cannot be one of the time points."
          echo "Find more info at:"
          echo "http://surfer.nmr.mgh.harvard.edu/fswiki/LongitudinalProcessing"
          exit 1;
        endif
      endif
      breaksw

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

    case "-xmask":
      if ( $#argv < 1) goto arg1err;
      set CustomMaskInput = $argv[1]; shift;
      if(! -e "$CustomMaskInput") then
        echo "ERROR: cannot find $CustomMaskInput"
        goto error_exit;
      endif
      set CustomMaskInputDir  = `dirname  "$CustomMaskInput"`;
      set CustomMaskInputBase = `basename "$CustomMaskInput"`;
      pushd $CustomMaskInputDir > /dev/null
      set CustomMaskInputDir = `pwd`;
      popd > /dev/null
      set CustomMaskInput = "$CustomMaskInputDir/$CustomMaskInputBase";
      breaksw

    case "-motioncor":
    case "-mc": 
     set DoMotionCor = 1;
      breaksw
    case "-nomotioncor":
    case "-nomc":
      set DoMotionCor = 0;
      breaksw

    case "-robust-motioncor":
    case "-motioncor-robust":
      set DoMotionCor = 1;
      set DoRobustMotionCor = 1;
      breaksw
    case "-norobust-motioncor":
    case "-nomotioncor-robust":
      set DoRobustMotionCor = 0;
      breaksw

    case "-flirt-motioncor":
    case "-motioncor-flirt":
      set DoMotionCor = 1;
      set DoRobustMotionCor = 0;
      breaksw

    case "-3T":
    case "-3t":
      set UseYa3tTalAtlas = 1;
      set DoNuIntensityCor3T = 1;
      breaksw

    case "-talairach":
      set DoTalairach = 1;
      breaksw
    case "-talairach-nu":
      set DoTalairach = 1;
      set DoTalairachUseNu = 1;
      breaksw
    case "-notalairach":
    case "-no-talairach":
      set DoTalairach = 0;
      set DoTalCheck = 0;
      breaksw
    case "-use-mritotal":
      set UseMincMritotal = 1;
      breaksw
    case "-schwartzya3t-atlas":
      set UseYa3tTalAtlas = 1;
      breaksw
    case "-custom-tal-atlas":
      if ( $#argv < 1) goto arg1err;
      set CustomTalAtlas = $argv[1]; shift;
      breaksw
    case "-samseg-reg":
      set DoSamsegReg = 1;
      breaksw

    case "-tal-check":
    case "-talairach-check":
    case "-talcheck":
      set DoTalCheck = 1;
      breaksw;
    case "-notal-check":
    case "-notalairach-check":
    case "-no-tal-check":
    case "-no-talairach-check":
    case "-notalcheck":
    case "-no-talcheck":
      set DoTalCheck = 0;
      breaksw;

    case "-deface":
      set DoDeface = 1;
      breaksw
    case "-nodeface":
      set DoDeface = 0;
      breaksw

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

    # note: norm3diters and normmaxgrads is applied to both runs of
    # mri_normalize.  use -norm1-b, -norm1-n, -norm2-b, -norm2-n to
    # distinguish -b and -n of the two mri_normalize runs
    case "-norm3diters":
      if ( $#argv < 1) goto arg1err;
      set Norm3dIters = $argv[1]; shift;
      breaksw

    case "-normmaxgrad":
      if ( $#argv < 1) goto arg1err;
      set NormMaxGrad = $argv[1]; shift;
      breaksw
    case "-norm1-b":
      if ( $#argv < 1) goto arg1err;
      set Norm1_b = $argv[1]; shift;
      breaksw
    case "-norm1-n":
      if ( $#argv < 1) goto arg1err;
      set Norm1_n = $argv[1]; shift;
      breaksw
    case "-norm2-b":
      if ( $#argv < 1) goto arg1err;
      set Norm2_b = $argv[1]; shift;
      breaksw
    case "-norm2-n":
      if ( $#argv < 1) goto arg1err;
      set Norm2_n = $argv[1]; shift;
      breaksw

    case "-normalization":
      set DoNormalization = 1;
      breaksw
    case "-nonormalization":
      set DoNormalization = 0;
      breaksw
    case "-normalization2":
      set DoNormalization2 = 1;
      breaksw
    case "-nonormalization2":
      set DoNormalization2 = 0;
      breaksw
    case "-usecontrolpoints":
      set UseControlPoints = 1;
      breaksw

    case "-maskbfs":
      set DoMaskBFS = 1;
      breaksw
    case "-nomaskbfs":
      set DoMaskBFS = 0;
      breaksw

    case "-skullstrip":
      set DoSkullStrip = 1;
      breaksw
    case "-noskullstrip":
      set DoSkullStrip = 0;
      breaksw

    case "-multistrip":
      set DoMultiStrip = 1;
      set DoSkullStrip = 1;
      set DoCleanPFH   = 1;
      breaksw
    case "-nomultistrip":
      set DoMultiStrip = 0;
      breaksw

    case "-watershed":
      echo $argv[1];
      if ( $#argv < 1 ) goto arg1err;
      switch($argv[1])
        case "nowatershed":
          set WaterShed = 0; breaksw;
        case "normal":
          set WaterShed = 1; breaksw;
        case "watershedonly":
          set WaterShed = 2; breaksw;
        case "watershedtemplate":
          set WaterShed = 3; breaksw;
        case "atlas":
          set WaterShed = 4; breaksw;
        default:
          echo "ERROR: -watershed argument $argv[1] unrecognized."
          echo "Valid arguments are: atlas, nowatershed, normal, watershedonly,"
          echo "and watershedtemplate."
          goto error_exit;
        breaksw;
      endsw
      shift;
      breaksw
    case "-wsless":
      set WSLess = 1; breaksw
    case "-wsmore":
      set WSMore = 1; breaksw
    case "-wsatlas":
      set WSAtlas = 1; breaksw
    case "-no-wsatlas":
      set WSAtlas = 0; breaksw
    case "-wsthresh":
      if ( $#argv < 1) goto arg1err;
      set WSPctPreFlood = $argv[1]; shift;
      breaksw
    case "-wsseed":
      if ( $#argv < 3) goto arg3err;
      set WSSeedPoint = ($argv[1] $argv[2] $argv[3]);
      shift;shift;shift;
      breaksw
    case "-wsgcaatlas":
      set WSGcaAtlas = 1; breaksw
    case "-nowsgcaatlas":
    case "-no-wsgcaatlas":
      set WSGcaAtlas = 0; breaksw
    case "-wstalxfm":
      set WSUseTalXfm = 1; breaksw
    case "-no-wstalxfm":
      set WSUseTalXfm = 0; breaksw
    case "-wscopy":
      set WSCopy = 1; breaksw

    case "-gcut":
      set DoGcut = 1;
      breaksw

    case "-no-gcut":
    case "-nogcut":
      set DoGcut = 0;
      breaksw

    case "-nuintensitycor":
    case "-nu_correct":
      set DoNuIntensityCor = 1;
      breaksw
    case "-nonuintensitycor":
      set DoNuIntensityCor = 0;
      breaksw

    case "-nuintensitycor-mask":
      set DoNuIntensityCor = 1;
      set UseMaskNuCorrect = 1;
      breaksw
    case "-nuintensitycor-nomask":
      set DoNuIntensityCor = 1;
      set UseMaskNuCorrect = 0;
      breaksw
    case "-nuintensitycor-mask-dilate":
      set DoNuIntensityCor = 1;
      set UseMaskNuCorrect = 1;
      if ( $#argv < 1) goto arg1err;
      set DilateMaskNuCorrect = $argv[1]; shift;
      breaksw
    case "-nuintensitycor-mask-nodilate":
      set DoNuIntensityCor = 1;
      set UseMaskNuCorrect = 1;
      set DilateMaskNuCorrect = ();
      breaksw

    case "-nuintensitycor-3T":
    case "-nuintensitycor-3t":
      set DoNuIntensityCor = 1;
      set DoNuIntensityCor3T = 1;
      breaksw

    case "-numakeuchar":
      set DoNuMakeUchar = 1;
      breaksw
    case "-no-numakeuchar":
    case "-nonumakeuchar":
      set DoNuMakeUchar = 0;
      breaksw

    case "-gcareg":
      set DoGCAReg = 1;
      breaksw
    case "-nogcareg":
      set DoGCAReg = 0;
      breaksw

    case "-emregmask":
      # MOD HCP: mask when running mri_em_reg, default is brainmask.mgz
      if ( $#argv < 1) goto arg1err;
      set EMRegMaskArg = $argv[1]; shift
      if(! -e $EMRegMaskArg) then
        echo "ERROR: cannot find $EMRegMaskArg"
        exit 1;
      endif
      set EMRegMaskArg = `getfullpath $EMRegMaskArg`
      breaksw

    case "-canorm":
      set DoCANormalize = 1;
      breaksw
    case "-nocanorm":
      set DoCANormalize = 0;
      breaksw
    case "-canorm-usecps":
      set DoCANormalize = 1;
      set UseCPsWithCaNorm = 1;
      breaksw

    case "-careg":
      set DoCAReg = 1;
      breaksw
    case "-nocareg":
      set DoCAReg = 0;
      breaksw

    case "-seg-wlo"
      if( $#argv < 1) goto arg1err;
      set WMSeg_wlo = (-wlo $argv[1]); shift;
      breaksw
    case "-seg-ghi"
      if( $#argv < 1) goto arg1err;
      set WMSeg_ghi = (-ghi $argv[1]); shift;
      breaksw

    case "-ca-align":
      set UseCAAlign = (-align);
      breaksw
    case "-no-ca-align":
      set UseCAAlign = ();
      breaksw

    case "-ca-align-after":
      set UseCAAlignAfter = (-align-after);
      breaksw
    case "-no-ca-align-after":
      set UseCAAlignAfter = ();
      breaksw

    case "-rmneck":
      set DoRemoveNeck = 1;
      breaksw
    case "-normneck":
      set DoRemoveNeck = 0;
      breaksw

    case "-skull-lta":
      set DoSkullLTA  = 1;
      breaksw
    case "-noskull-lta":
      set DoSkullLTA  = 0;
      breaksw

    case "-calabel":
      set DoCALabel = 1;
      breaksw
    case "-nocalabel":
      set DoCALabel = 0;
      breaksw

    case "-ccseg":
      set DoCCSeg = 1;
      breaksw
    case "-no-ccseg":
      # Note: this will be overriden if DoCALabel=1
      set DoCCSeg = 0;
      breaksw

    case "-asegmerge":
      set DoASegMerge = 1;
      breaksw
    case "-no-asegmerge":
      # Note: this will be overriden if DoCCSeg=1 (as well as DoCALabel=1)
      set DoASegMerge = 0;
      breaksw

    case "-subcortseg":
      set DoGCAReg         = 1;
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoCANormalize    = 1;
      set DoCAReg          = 1;
      set DoCALabel        = 1;
      set DoSegStats       = 0;
      breaksw

    case "-nosubcortseg":
      set DoGCAReg         = 0;
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoCANormalize    = 0;
      set DoCAReg          = 0;
      set DoCALabel        = 0;
      set DoSegStats       = 0;
      set NoNormMGZ        = 1;
      breaksw

    case "-noaseg":
      set UseAseg          = 0;
      set DoGCAReg         = 0;
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoCANormalize    = 0;
      set DoCAReg          = 0;
      set DoCALabel        = 0;
      set DoSegStats       = 0;
      set NoNormMGZ        = 1;
      set DoAParc2ASeg     = 0;
      set DoAPas2ASeg      = 0;
      set DoWMParc         = 0;
      set DoCortRibbonVolMask = 0;
      breaksw

    case "-noaseg-inorm2":
      set NoAsegInorm2     = 1;
      breaksw

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

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

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

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

    case "-dkt2020":
      set DKTATLAS_GCS = DKTaparc.atlas.acfb40.noaparc.i12.2020-05-13.gcs
      breaksw

    case "-segmentation":
    case "-segment":
      set DoSegmentation = 1;
      breaksw
    case "-nosegmentation":
    case "-nosegment":
      set DoSegmentation = 0;
      breaksw

    case "-fill":
      set DoFill = 1;
      breaksw
    case "-nofill":
      set DoFill = 0;
      breaksw

    case "-allow-filled-edit":
      setenv FS_ALLOW_FILLED_EDIT 1
      breaksw
    case "-no-allow-filled-edit":
      setenv FS_ALLOW_FILLED_EDIT 0
      breaksw

    case "-pons-crs":
      if ( $#argv < 3) goto arg3err;
      set PonsSeedCRS = ($argv[1] $argv[2] $argv[3]);
      shift;shift;shift;
      breaksw
    case "-cc-crs":
      if ( $#argv < 3) goto arg3err;
      set CCSeedCRS = ($argv[1] $argv[2] $argv[3]);
      shift;shift;shift;
      breaksw
    case "-lh-crs":
      if ( $#argv < 3) goto arg3err;
      set LHSeedCRS = ($argv[1] $argv[2] $argv[3]);
      shift;shift;shift;
      breaksw
    case "-rh-crs":
      if ( $#argv < 3) goto arg3err;
      set RHSeedCRS = ($argv[1] $argv[2] $argv[3]);
      shift;shift;shift;
      breaksw

    case "-tessellate":
    case "-tess":
      set DoTessellate = 1;
      breaksw
    case "-notessellate":
    case "-notess":
      set DoTessellate = 0;
      breaksw

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

    # now in recon-config.yaml
    # Decimation is done as part of DoTessellate
    #case "-decimate":
    #  set DoDecimation = 1;
    #  breaksw
    #case "-decimation-area":
    #  desired average face area after decimation
    #  set DecimationFaceArea = $argv[1]; shift 
    #  breaksw
    case "-no-decimate":
      set DoDecimation = 0;
      breaksw

    # now in recon-config.yaml
    #case "-remesh"
      # Use Martin's code to remesh ?h.orig to improve triangle quality
      #set DoRemesh = 1; 
      #breaksw
    case "-noremesh"
    case "-no-remesh"
      set DoRemesh = 0; 
      breaksw

    # now in recon-config.yaml
    #case "-ants-denoise"
      # Use ANTS denoising prior to mri_segment
      #set DoAntsDenoising = 1; 
      #breaksw
    case "-no-ants-denoise"
      set DoAntsDenoising = 0; 
      breaksw

    case "-smooth1":
      set DoSmooth1 = 1;
      breaksw
    case "-nosmooth1":
      set DoSmooth1 = 0;
      breaksw

    case "-inflate1":
      set DoInflate1 = 1;
      breaksw
    case "-noinflate1":
      set DoInflate1 = 0;
      breaksw

    case "-svinitinflated":
      set SvInitInflated = 1;
      breaksw
    case "-nosvinitinflated":
      set SvInitInflated = 0;
      breaksw

    case "-qsphere":
      set DoQSphere = 1;
      breaksw
    case "-noqsphere":
      set DoQSphere = 0;
      breaksw

    case "-fix":
      set DoFix = 1;
      breaksw
    case "-nofix":
      set DoFix = 0;
      breaksw

    case "-fix-with-ga":
      set FixWithGA = 1;
      breaksw

    case "-fix-with-ga-errflag":
      set DoFix = 1;
      set FixWithGA = 1;
      set FixWithErrFlag = 1;
      breaksw

    case "-no-fix-with-ga":
      set FixWithGA = 0;
      breaksw

    case "-fix-diag-only":
      set DoFix = 1;
      set FixWithGA = 1;
      set FixDiagOnly = 1;
      breaksw

    case "-use-old-fixer":
      set UseOldTopoFix = 1;
      set UseNewTopoFix = 0;
      breaksw

    case "-use-new-fixer":
      set UseOldTopoFix = 0;
      set UseNewTopoFix = 1;
      breaksw

    case "-white-preaparc":
    case "-white.preaparc":
      set DoWhitePreAparc = 1;
      breaksw
    case "-nowhite-preaparc":
    case "-no-white-preaparc":
      set DoWhitePreAparc = 0;
      breaksw

    case "-cortex-label":
      set DoCortexLabel = 1;
      breaksw
    case "-no-cortex-label":
      set DoCortexLabel = 0;
      breaksw

    case "-whitesurfs":
    case "-white":
      set DoWhiteSurfs = 1;
      breaksw
    case "-nowhitesurfs":
    case "-nowhite":
      set DoWhiteSurfs = 0;
      breaksw

    case "-high-myelin":
      if($#argv < 1) goto arg1err;
      set HighMyelinFactor = $argv[1]; shift
      set UseHighMyelin = 1
      breaksw

    case "-smooth2":
      set DoSmooth2 = 1;
      breaksw
    case "-nosmooth2":
      set DoSmooth2 = 0;
      breaksw

    case "-autodetgwstats":
      set DoAutoDetGWStats = 1
      breaksw
    case "-no-autodetgwstats":
    case "-noautodetgwstats":
      set DoAutoDetGWStats = 0
      breaksw
      breaksw

    case "-inflate2":
      set DoInflate2 = 1;
      breaksw
    case "-noinflate2":
      set DoInflate2 = 0;
      breaksw

    case "-curvHK":
      set DoCurvHK = 1;
      breaksw
    case "-nocurvHK":
      set DoCurvHK = 0;
      breaksw

    case "-curvstats":
      set DoCurvStats = 1;
      breaksw
    case "-nocurvstats":
      set DoCurvStats = 0;
      breaksw

    case "-sphere":
      set DoSphere = 1;
      breaksw
    case "-nosphere":
      set DoSphere = 0;
      breaksw

    case "-surfreg":
      set DoSurfReg = 1;
      breaksw
    case "-nosurfreg":
      set DoSurfReg = 0;
      breaksw

    case "-jacobian_white":
      set DoJacobianWhite = 1;
      breaksw
    case "-nojacobian_white":
      set DoJacobianWhite = 0;
      breaksw

    case "-jacobian_dist0":
      set DoJacobianDist0 = 1;
      breaksw
    case "-nojacobian_dist0":
      set DoJacobianDist0 = 0;
      breaksw

    case "-avgcurv":
      set DoAvgCurv = 1;
      breaksw
    case "-noavgcurv":
      set DoAvgCurv = 0;
      breaksw

    case "-cortparc":
      set DoCortParc = 1;
      breaksw
    case "-nocortparc":
      set DoCortParc = 0;
      breaksw

    case "-pialsurfs":
    case "-pial":
      set DoPialSurfs = 1;
      breaksw
    case "-nopialsurfs":
    case "-nopial":
      set DoPialSurfs = 0;
      breaksw

    case "-pial-noaparc":
    case "-pial_noaparc":
      set DoPialSurfs = 1;
      set PialNoAparc = 1;
      breaksw

    # backward compatibility with single-run mris_make_surfaces:
    case "-finalsurfs":
      set DoWhiteSurfs = 1;
      set DoPialSurfs = 0;
      set DoSurfVolume = 1;
      breaksw

    case "-nofinalsurfs":
      set DoWhiteSurfs = 0;
      set DoPialSurfs = 0;
      breaksw

    case "-surfvolume":
      set DoSurfVolume = 1;
      breaksw;

    case "-cortribbon":
      set DoCortRibbonVolMask = 1;
      breaksw
    case "-nocortribbon":
      set DoCortRibbonVolMask = 0;
      breaksw

    case "-parcstats":
      set DoParcStats = 1;
      breaksw
    case "-noparcstats":
      set DoParcStats = 0;
      breaksw

    case "-cortparc2":
      set DoCortParc2 = 1;
      breaksw
    case "-nocortparc2":
      set DoCortParc2 = 0;
      breaksw

    case "-parcstats2":
      set DoParcStats2 = 1;
      breaksw
    case "-noparcstats2":
      set DoParcStats2 = 0;
      breaksw

    case "-cortparc3":
      set DoCortParc3 = 1;
      breaksw
    case "-nocortparc3":
      set DoCortParc3 = 0;
      breaksw

    case "-parcstats3":
      set DoParcStats3 = 1;
      breaksw
    case "-noparcstats3":
      set DoParcStats3 = 0;
      breaksw

    case "-pctsurfcon":
      set DoPctSurfCon = 1;
      breaksw
    case "-nopctsurfcon":
    case "-no-pctsurfcon":
      set DoPctSurfCon = 0;
      breaksw

    case "-hyporelabel":
      set DoRelabelHypos = 1;
      breaksw
    case "-nohyporelabel":
      set DoRelabelHypos = 0;
      breaksw

    case "-aparc2aseg":
      set DoAParc2ASeg = 1;
      breaksw
    case "-noaparc2aseg":
      set DoAParc2ASeg = 0;
      breaksw

    case "-apas2aseg":
      set DoAPas2ASeg = 1;
      breaksw
    case "-noapas2aseg":
      set DoAPas2ASeg = 0;
      breaksw

    case "-aparc+aseg-stats":
      set DoAParcASegStats = 1;
      breaksw
    case "-no-aparc+aseg-stats":
      set DoAParcASegStats = 0;
      breaksw

    case "-segstats":
      set DoSegStats = 1;
      breaksw
    case "-nosegstats":
      set DoSegStats = 0;
      breaksw

    case "-wmparc":
      set DoWMParc = 1;
      breaksw
    case "-nowmparc":
      set DoWMParc = 0;
      breaksw

    case "-balabels":
    case "-ba_labels":
    case "-ba-labels":
    case "-label_ba":
    case "-label_BA":
      set DoBaLabels = 1;
      breaksw;

    case "-nobalabels":
    case "-noba_labels":
    case "-noba-labels":
    case "-nolabel_ba":
    case "-nolabel_BA":
    case "-no_ba_labels":
    case "-no-ba-labels":
    case "-no_label_ba":
    case "-no_label_BA":
      set DoBaLabels = 0;
      breaksw;

    case "-label_v1":
    case "-label_V1":
    case "-label-v1":
    case "-label-V1":
      set DoLabelV1 = 1;
      breaksw;

    case "-label_exvivo_ec_avg":
    case "-label-exvivo-ec-avg":
    case "-label_exvivo_EC_avg":
    case "-label-exvivo-EC-avg":
      set DoLabelExvivoEC = 1;
      breaksw;

    case "-nolabel_exvivo_ec_avg":
    case "-nolabel-exvivo-ec-avg":
    case "-nolabel_exvivo_EC_avg":
    case "-nolabel-exvivo-EC-avg":
    case "-no_label_exvivo_ec_avg":
    case "-no-label-exvivo-ec-avg":
    case "-no_label_exvivo_EC_avg":
    case "-no-label-exvivo-EC-avg":
      set DoLabelExvivoEC = 0;
      breaksw;

#---------------------------------------------------#
# Note: end of flags for recon-all stages above, 
# below are 'autorecon' and other multi-stage flags
#---------------------------------------------------#

    case "-all":
    case "-autorecon-all":
      set DoCreateBaseInput = 1;
      set DoMotionCor      = 1;
      set DoTalairach      = 1;
      set DoTalCheck       = 1;
      set DoNormalization  = 1;
      set DoSkullStrip     = 1;
      set DoNuIntensityCor = 1;
      set DoGCAReg         = 1;
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoCANormalize    = 1;
      set DoCAReg          = 1;
      set DoCALabel        = 1;
      set DoNormalization2 = 1;
      set DoMaskBFS        = 1;
      set DoSegmentation   = 1;
      set DoFill           = 1;
      set DoTessellate     = 1;
      set DoSmooth1        = 1;
      set DoInflate1       = 1;
      set DoQSphere        = 1;
      set DoFix            = 1;
      set DoAutoDetGWStats = 1;
      set DoWhitePreAparc  = 1;
      set DoCortexLabel    = 1;
      set DoSmooth2        = 1;
      set DoInflate2       = 1;
      set DoCurvHK         = 1;
      set DoSphere         = 1;
      set DoSurfReg        = 1;
      set DoAvgCurv        = 1;
      set DoJacobianWhite  = 1;
      set DoCortParc       = 1;
      set DoWhiteSurfs     = 1;
      set DoPialSurfs      = 1;
      set DoCurvStats      = 1;
      set DoCortRibbonVolMask = 1;
      set DoParcStats      = 1;
      set DoCortParc2      = 1;
      set DoParcStats2     = 1;
      set DoCortParc3      = 1;
      set DoParcStats3     = 1;
      set DoPctSurfCon     = 1;
      set DoRelabelHypos   = 1;
      set DoAParc2ASeg     = 1;
      set DoAPas2ASeg      = 1;
      set DoSegStats       = 1;
      set DoWMParc         = 1;
      set DoBaLabels       = 1;
      breaksw

    case "-autorecon1":
      set DoCreateBaseInput = 1;
      set DoMotionCor      = 1;
      set DoTalairach      = 1;
      set DoTalCheck       = 1;
      set DoNormalization  = 1;
      set DoSkullStrip     = 1;
      set DoNuIntensityCor = 1;
      breaksw

    case "-gcatrain-iter":
      if($#argv < 2) goto arg2err;
      set gcafile = $argv[1]; shift;
      if(! -e $gcafile) then
        echo "ERROR: cannot find $gcafile"
        exit 1;
      endif
      set gcafile = `getfullpath $gcafile`
      set GCA    = `basename $gcafile`
      set GCADIR = `dirname $gcafile`
      set GCAOutputName = $argv[1]; shift;
      set DoGCAReg         = 1;
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoCANormalize    = 1;
      set DoCAReg          = 1;
      set DoCALabel        = 0;
      set DoSegStats       = 0;
      breaksw

    case "-gcareg-iters":
      if($#argv < 1) goto arg1err;
      set GCARegIterations = $argv[1]; shift;
      breaksw
    case "-gcareg-tol":
      if($#argv < 1) goto arg1err;
      set GCARegTol = $argv[1]; shift;
      breaksw

    case "-autorecon2":
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoSegStats       = 0;
      set DoCANormalize    = 1;
      set DoGCAReg         = 1;
      set DoCAReg          = 1;
      set DoCALabel        = 1;
      set DoNormalization2 = 1;
      set DoMaskBFS        = 1;
      set DoSegmentation   = 1;
      set DoFill           = 1;
      set DoTessellate     = 1;
      set DoSmooth1        = 1;
      set DoInflate1       = 1;
      set DoQSphere        = 1;
      set DoFix            = 1;
      set DoSmooth2        = 1;
      set DoInflate2       = 1;
      set DoAutoDetGWStats = 1;
      set DoWhitePreAparc  = 1;
      set DoCortexLabel    = 1;
      set DoCurvHK         = 1;
      breaksw

    case "-autorecon2-synthseg":
    case "-autorecon2-samseg":
      set DoASegMerge = 1;
      set DoNormalization2 = 1;
      set DoMaskBFS        = 1;
      set DoSegmentation   = 1;
      set DoFill           = 1;
      set DoTessellate     = 1;
      set DoSmooth1        = 1;
      set DoInflate1       = 1;
      set DoQSphere        = 1;
      set DoFix            = 1;
      set DoSmooth2        = 1;
      set DoInflate2       = 1;
      set DoAutoDetGWStats = 1;
      set DoWhitePreAparc  = 1;
      set DoCortexLabel    = 1;
      set DoCurvHK         = 1;
      set DoSegStats       = 0;
      breaksw

    case "-autorecon2-volonly":
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoSegStats       = 0;
      set DoCANormalize    = 1;
      set DoGCAReg         = 1;
      set DoCAReg          = 1;
      set DoCALabel        = 1;
      set DoNormalization2 = 1;
      set DoMaskBFS        = 1;
      set DoSegmentation   = 1;
      set DoFill           = 1;
      breaksw

    case "-autorecon2-perhemi":
    case "-autorecon2-surfonly":
    case "-autorecon2-surfsonly":
    case "-autorecon2-surf":
    case "-autorecon2-surfs":
      set DoTessellate     = 1;
      set DoSmooth1        = 1;
      set DoInflate1       = 1;
      set DoQSphere        = 1;
      set DoFix            = 1;
      set DoAutoDetGWStats = 1;
      set DoWhitePreAparc  = 1;
      set DoCortexLabel    = 1;
      set DoSmooth2        = 1;
      set DoInflate2       = 1;
      set DoSegStats       = 0;
      set DoCurvHK         = 1;
      breaksw

    case "-autorecon2-inflate1":
      set DoGCAReg         = 1;
      set DoRemoveNeck     = 0;
      set DoSkullLTA       = 0;
      set DoCANormalize    = 1;
      set DoCAReg          = 1;
      set DoCALabel        = 1;
      set DoSegStats       = 0;
      set DoNormalization2 = 1;
      set DoMaskBFS        = 1;
      set DoSegmentation   = 1;
      set DoFill           = 1;
      set DoTessellate     = 1;
      set DoSmooth1        = 1;
      set DoInflate1       = 1;
      breaksw

    case "-autorecon2-cp":
    case "-autorecon2-noaseg":
      set DoNormalization2 = 1;
      #set DoMaskBFS        = 1; # should this be active?
      set DoSegmentation   = 1;
# no break!
    case "-autorecon2-wm":
    case "-autorecon2-fill":
    case "-autorecon2-filled":
      set DoFill           = 1;
      set DoTessellate     = 1;
      set DoSmooth1        = 1;
      set DoInflate1       = 1;
      set DoQSphere        = 1;
      set DoFix            = 1;
      set DoMaskBFS        = 1;
      set DoAutoDetGWStats = 1;
      set DoWhitePreAparc  = 1;
      set DoCortexLabel    = 1;
      set DoSmooth2        = 1;
      set DoInflate2       = 1;
      set DoSegStats       = 0;
      set DoCurvHK         = 1;
      breaksw

    case "-autorecon-bfs":
    case "-autorecon-pial": # does more than pial
      set DoMaskBFS        = 1;
      set DoAutoDetGWStats = 1;
      set DoWhitePreAparc  = 1;
      set DoCortexLabel    = 1;
      set DoSmooth2        = 1;
      set DoInflate2       = 1;
      set DoSegStats       = 1;
      set DoCurvHK         = 1;
      set DoSphere         = 1;
      set DoSurfReg        = 1;
      set DoAvgCurv        = 1;
      set DoJacobianWhite  = 1;
      set DoCortParc       = 1;
      set DoWhiteSurfs     = 1;
      set DoPialSurfs      = 1;
      set DoPctSurfCon     = 1;
      set DoCurvStats      = 1;
      set DoCortRibbonVolMask = 1;
      set DoParcStats      = 1;
      set DoCortParc2      = 1;
      set DoParcStats2     = 1;
      set DoCortParc3      = 1;
      set DoParcStats3     = 1;
      set DoRelabelHypos   = 1;
      set DoAParc2ASeg     = 1;
      set DoAPas2ASeg      = 1;
      set DoWMParc         = 1;
      set DoBaLabels       = 1;
      breaksw

    case "-autorecon3":
      set DoSphere         = 1;
      set DoSurfReg        = 1;
      set DoAvgCurv        = 1;
      set DoJacobianWhite  = 1;
      set DoCortParc       = 1;
      set DoWhiteSurfs     = 1;
      set DoPialSurfs      = 1;
      set DoCurvStats      = 1;
      set DoCortRibbonVolMask = 1;
      set DoParcStats      = 1;
      set DoCortParc2      = 1;
      set DoParcStats2     = 1;
      set DoCortParc3      = 1;
      set DoParcStats3     = 1;
      set DoPctSurfCon     = 1;
      set DoRelabelHypos   = 1;
      set DoAParc2ASeg     = 1;
      set DoAPas2ASeg      = 1;
      set DoSegStats       = 1;
      set DoWMParc         = 1;
      set DoBaLabels       = 1;
      breaksw

    # skips unnecessary steps (sphere reg) in autorecon3 when refining pial surface only
    case "-autorecon3-T2pial":
    case "-T2pial-only":
      set DoT2pial         = 1;
      set DoCurvStats      = 1;
      set DoCortRibbonVolMask = 1;
      set DoParcStats      = 1;
      set DoCortParc2      = 1;
      set DoParcStats2     = 1;
      set DoCortParc3      = 1;
      set DoParcStats3     = 1;
      set DoPctSurfCon     = 1;
      set DoRelabelHypos   = 1;
      set DoAParc2ASeg     = 1;
      set DoAPas2ASeg      = 1;
      set DoSegStats       = 1;
      set DoWMParc         = 1;
      set DoBaLabels       = 1;
      breaksw

    case "-autorecon-hemi":
      if ( $#argv < 1) goto arg1err;
      set hemilist = $argv[1]; shift;
      if($hemilist != lh && $hemilist != rh) then
        echo "ERROR: hemi = $hemilist, must be either lh or rh"
        goto error_exit;
      endif
      set LF_DEFAULT_NAME = "recon-all-${hemilist}.log"
      set SF_DEFAULT_NAME = "recon-all-status-${hemilist}.log"
      set CF_DEFAULT_NAME = "recon-all-${hemilist}.cmd"
      set DoTessellate     = 1;
      set DoSmooth1        = 1;
      set DoInflate1       = 1;
      set DoQSphere        = 1;
      set DoFix            = 1;
      set DoSmooth2        = 1;
      set DoInflate2       = 1;
      set DoAutoDetGWStats = 1;
      set DoWhitePreAparc  = 1;
      set DoCortexLabel    = 1;
      set DoCurvHK         = 1;
      set DoCurvStats      = 1;
      set DoSphere         = 1;
      set DoSurfReg        = 1;
      set DoAvgCurv        = 1;
      set DoJacobianWhite  = 1;
      set DoCortParc       = 1;
      set DoWhiteSurfs     = 1;
      set DoPialSurfs      = 1;
      set DoCortRibbonVolMask = 0;
      set DoParcStats      = 1;
      set DoCortParc2      = 1;
      set DoParcStats2     = 1;
      set DoCortParc3      = 1;
      set DoParcStats3     = 1;
      set DoPctSurfCon     = 1;
      set DoRelabelHypos   = 1;
      set DoAParc2ASeg     = 0;
      set DoAPas2ASeg      = 0;
      set DoWMParc         = 0;
      set DoSegStats       = 0;
      set DoBaLabels       = 1;
      if($hemilist == lh) set LHonly = 1 
      if($hemilist == rh) set RHonly = 1 
      breaksw

#-------------------------------------------------#
# below are utility flags and special modifiers
#-------------------------------------------------#

    case "-hemi":
      if ( $#argv < 1) goto arg1err;
      set hemilist = $argv[1]; shift;
      if($hemilist != lh && $hemilist != rh) then
        echo "ERROR: hemi = $hemilist, must be either lh or rh"
        goto error_exit;
      endif
      if($hemilist == lh) set LHonly = 1 
      if($hemilist == rh) set RHonly = 1 
      breaksw

    # This is a temporary flag to test how changing the way the vertex
    # area is computed in mrisurf.c affects a recon. It is set by default!
    case "-fixvertexarea"
      setenv FIX_VERTEX_AREA;
      breaksw
    case "-nofixvertexarea"
      unsetenv FIX_VERTEX_AREA;
      breaksw

    case "-norandomness":
      set NoRandomness = 1;
      breaksw

    case "-randomness":
      set NoRandomness = 0;
      breaksw

    # Whether to use mri_em_register for skullstripping
    case "-emreg-strip":
      set EMRegStrip = 1;
      breaksw
    case "-no-emreg-strip":
      set EMRegStrip = 0;
      # If not using emreg, then use an lta created from the talairach.xfm
      # This will change GCASkull to  RB_all_withskull_2019_10_22.talxfm.mni305.gca below
      breaksw

    # Whether to use mri_em_register as init for mri_ca_register
    case "-emreg-aseg":
      set EMRegAseg = 1;
      breaksw
    case "-no-emreg-aseg":
      set EMRegAseg = 0;
      # If not using emreg, then use an lta created from the talairach.xfm
      # This will change  GCA to RB_all_2019_10_25.talxfm.mni305.gca below
      breaksw
    case "-emreg":
      set EMRegAseg = 1;
      set EMRegStrip = 1;
      breaksw
    case "-no-emreg":
      set EMRegStrip = 0;
      set EMRegAseg = 0;
      breaksw

    case "-wmseg-from-aseg"
      set WMSegFromASeg = 1; # use aseg WM instead of mri_segment
      set DoSegmentation = 1
      breaksw

    case "-no-wmseg-from-aseg"
      set WMSegFromASeg = 0; # use mri_segment instead of WM from aseg
      breaksw

    # -th3 turns on new volume calc for mris_anat_stats
    case "-th3":
      set TH3Flag = 1
      breaksw
    case "-no-th3":
      set TH3Flag = 0
      breaksw

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

    case "-rng-seed":
      if( $#argv < 1) goto arg1err;
      set RngSeed = $argv[1]; shift;
      set NoRandomness = 1;
      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 "-xopts-use"
      set XOptsUse = 1; # Use pre-existing xopts
      breaksw
    case "-xopts-clean"
      set XOptsClean = 1; # Delete pre-existing xopts
      breaksw
    case "-xopts-overwrite"
      set XOptsOverwrite = 1; # Overwrite pre-existing xopts
      breaksw

    case "-termscript"
      if( $#argv < 1) goto arg1err;
      set ts = $argv[1]; shift
      which $ts >& /dev/null
      if($status) then
        echo "ERROR: termination script $ts does not exist in your path"
        exit 1;
      endif
      set TermScriptList = ($TermScriptList $ts);
      breaksw

    case "-clean":
      set DoCleanCSDF  = 1;
      set DoCleanCW256 = 1;
      set DoCleanTal   = 1;
      set DoCleanLta   = 1;
      set DoCleanCP    = 1;
      set DoCleanTWM   = 1;
      set DoCleanSeed  = 1;
      set DoCleanPFH   = 1;
      set DoCleanBM    = 1;
      set DoCleanASeg  = 1;
      set DoCleanWM    = 1;
      set DoCleanFilled = 1;
      set DoCleanBFSE  = 1;
      set DoCleanXopts = 1;
      set DoCleanT2    = 1;
      set DoCleanFLAIR = 1;
      breaksw

    case "-clean-xopts":
      set DoCleanXopts = 1;
      breaksw

    case "-clean-cw256":
      set DoCleanCW256 = 1;
      breaksw

    case "-clean-cp":
      set DoCleanCP   = 1;
      breaksw

    case "-clean-twm":
      set DoCleanTWM  = 1;
      breaksw

    case "-clean-wm":
      set DoCleanWM   = 1;
      breaksw

    case "-clean-filled":
      set DoCleanFilled = 1;
      breaksw

    case "-clean-cpwm":
    case "-clean-wmcp":
      set DoCleanWM   = 1;
      set DoCleanCP   = 1;
      breaksw

    case "-clean-seed":
      set DoCleanSeed   = 1;
      breaksw

    case "-clean-tal":
      set DoCleanTal   = 1;
      breaksw

    case "-clean-lta":
      set DoCleanLta   = 1;
      breaksw

    case "-clean-pfh":
      set DoCleanPFH   = 1;
      breaksw

    case "-clean-bm":
      set DoCleanBM   = 1;
      breaksw

    case "-clean-aseg":
      set DoCleanASeg   = 1;
      breaksw

    case "-clean-bfse":
      set DoCleanBFSE   = 1;
      breaksw

    case "-clean-T2":
      set DoCleanT2 = 1;
      breaksw

    case "-clean-FLAIR":
      set DoCleanFLAIR = 1;
      breaksw

    case "-superclean":
    case "-super-clean":
      set DoSuperClean = 1;
      breaksw

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

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

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

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

    case "-noappendlog":
      set AppendLog = 0;
      breaksw

    case "-noappendstatus":
      set AppendStatus = 0;
      breaksw

    case "-noappend":
      set AppendLog = 0;
      set AppendStatus = 0;
      breaksw

    case "-done":
      if ( $#argv < 1) goto arg1err;
      set DoneFile = $argv[1]; shift;
      rm -f $DoneFile
      breaksw

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

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

    case "-csurfdir":
      if ( $#argv < 1) goto arg1err;
      setenv FREESURFER_HOME $argv[1]; shift;
      if(! -e $FREESURFER_HOME) then
        echo "ERROR: cannot find $FREESURFER_HOME"
        goto error_exit;
      endif
      pushd $FREESURFER_HOME > /dev/null
      setenv FREESURFER_HOME `pwd`;
      breaksw

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

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

    case "-onlyversions":
      set DoVersionsOnly = 1;
      breaksw

    case "-allowcoredump":
      limit coredumpsize unlimited
      breaksw

    case "-noisrunning":
    case "-no-isrunning":
      set DoIsRunning = 0;
      breaksw

    case "-chunk":
      setenv FS_USE_MRI_CHUNK 1
      breaksw
    case "-no-chunk":
      unsetenv FS_USE_MRI_CHUNK
      breaksw

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

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

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

    case "-no-sbatch":
      set DoSBatch = 0;
      breaksw

    case "-force-update":
      set ForceUpdate = 1;
      breaksw

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

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

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

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

    case "-grp":
      if ( $#argv < 1) goto arg1err;
      set grp = $argv[1];
      set curgrp = `id -gn`;
      if($grp != $curgrp) then
        echo "ERROR: current group ($curgrp) does not equal specified group $grp"
        goto error_exit;
      endif
      breaksw

    case "-cm":
      set ConformMin = 1;
      echo "INFO: all volumes are conformed to the min voxel size"
      breaksw

    case "-conform-dc":
      set ConformKeepDC = 1;
      echo "INFO: keeping DC when conforming"
      breaksw

    case "-highres":
    case "-hires":
      set HiRes = 1;
      set ConformMin = 1;
      set DoDecimation = 1;
      echo "INFO: hi-res volumes are conformed to the min voxel size"
      # per testing by Natalia Zaretskaya, Mar 2015, the flags which
      # normally disable the aseg steps are no longer necessary (which
      # means aseg.mgz can be created with hi-res data).
      breaksw

    case "-conf2hires":
      set DoConf2Hires = 1;
      set DoSurfVolume = 1;
      set HiRes = 0;
      set ConformMin = 0;
      set UseCubic = 0; # The conformed should be generated with trilin interp
      set DoPialSurfs = 0; # will be done in conf2hires
      which conf2hires >& /dev/null
      if($status) then
        echo "ERROR: cannot find conf2hires"
        exit 1;
      endif
      breaksw

    case "-use-aseg":
      set UseAseg = 1;
      breaksw

    case "-no-use-aseg":
      set UseAseg = 0;
      breaksw

    case "-noneg":
      set UseNoNeg = 1;
      breaksw

    case "-nothicken":
      set NoThicken = 1;
      breaksw

    case "-uncompress":
      set UnCompress = 1;
      breaksw

    case "-bigventricles":
      set BigVentricles = 1;
      breaksw

    case "-nobigventricles":
      set BigVentricles = 0;
      breaksw

    case "-secondpassrenorm":
      set DoSecondPassRenorm = 1;
      breaksw

    case "-mprage":
      set IsMPRAGE = 1;
      breaksw;

    case "-no-mprage":
      set IsMPRAGE = 0;
      breaksw;

    case "-washu_mprage":
      set IsWashuMPRAGE = 1;
      breaksw;

    case "-cw256":
      set DoConformWidth256 = 1;
      breaksw;

    case "-nowmsa":
      set NoWMSA = 1;
      breaksw;

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

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

    case "-qcache":
      set DoQdecCache = 1;
      breaksw;

    case "-smooth-cortex-only"
      set SmoothCortexOnly = 1;
      breaksw;

    case "-no-smooth-cortex-only"
      set SmoothCortexOnly = 0;
      breaksw;

    case "-measure":
      if ( $#argv < 1) goto arg1err;
      if ( $UserMeasureList ) then
        set measurelist = ($measurelist $argv[1]); shift;
      else
        set measurelist = $argv[1]; shift;
        set UserMeasureList = 1; # allow for multiple instances of -measure
      endif
      breaksw

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

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

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

    case "-vno_match_check":
    case "-vno_check":
    case "-vno-check":
      set DoVnoMatchCheck = 1;
      breaksw;

    case "-make"
      echo "ERROR: -make is no longer supported"
      exit 1;
      if ( $#argv < 1) goto arg1err;
      set DoMakefile = 1;
      set MakefileTarget = $argv[1]; shift;
      breaksw;

    case "-time":
      set DoTime = 1;
      breaksw;

    case "-notime":
      set DoTime = 0;
      breaksw;

    case "-lgi":
    case "-lGI":
    case "-localGI":
      set DoLocalGyriIndex = 1;
      breaksw;

    case "-use-concat-lta-tal":
      set UseConcatLtaTal = 1;
      breaksw;

    case "-show-edits":
    case "-show_edits":
    case "-showedits":
      set DoShowEdits = 1;
      breaksw;

    case "-parallel":
      set DoParallel = 1;
      if ( ! $OMP_NUM_SET ) then
        # the user can override this thread count with -openmp
        setenv OMP_NUM_THREADS 4
        setenv FS_OMP_NUM_THREADS 4 # support for re-entrant recon-all
      endif
      # override: -itkthreads <num_threads>
      setenv ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS 4
      breaksw

    case "-openmp":
    case "-threads"
    case "--threads"
    case "-nthreads"
      if ( $#argv < 1) goto arg1err;
      setenv OMP_NUM_THREADS $argv[1]; shift;
      setenv FS_OMP_NUM_THREADS $OMP_NUM_THREADS # re-entrant recon-all
      set OMP_NUM_SET = 1
      breaksw;

    case "-itkthreads":
      # located after -parallel so as to allow threadcount override
      if ( $#argv < 1) goto arg1err;
      setenv ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS $argv[1]; shift;
      breaksw;

    case "-subfields":
      # Hippo, Amyg, Thal, and BrainStem, only using T1
      set DoSubfields = 1;
      breaksw;

    # hippocampal subfield processing (in vivo atlas, Dickerson data)
    case "-hippo-subfields":
    case "-hippocampal-subfields-T1":
    case "-hippocampal-subfields-T1T2":
    case "-hippocampal-subfields-T2":
      echo " "
      echo "ERROR: the hippocampal subfield module is now in separate scripts:"
      echo "  segmentHA_T1.sh"
      echo "  segmentHA_T2.sh"
      echo "  segmentHA_T1_long.sh"
      echo " "
      echo "For help, please execute the corresponding script  with the flag --help: "
      echo " "
      echo "     segmentHA_T1.sh --help"
      echo "     segmentHA_T2.sh --help"
      echo "     segmentHA_T1_long.sh --help"
      echo " "
      echo "or visit the following page: "
      echo " "
      echo "https://surfer.nmr.mgh.harvard.edu/fswiki/HippocampalSubfieldsAndNucleiOfAmygdala" 
      echo " "
      exit 1;
      breaksw;

    # processing of brainstem substructures
    case "-brainstem-structures":
      echo " "
      echo "ERROR: the brainstem module is now a separate script: segmentBS.sh"
      echo " "
      echo "For help, please execute the script with the flag --help: "
      echo " "
      echo "     segmentBS.sh --help"
      echo " "
      echo "or visit the following page: "
      echo " "
      echo "https://surfer.nmr.mgh.harvard.edu/fswiki/BrainstemSubstructures"
      echo " "
      breaksw;

   
    case "-cubic":
      set UseCubic = 1;
      breaksw
    case "-nocubic":
    case "-no-cubic":
    case "-no_cubic":
      set UseCubic = 0;
      breaksw

    case "-fix_mtl":
    case "-fix-mtl":
      set UseFixMtl = 1;
      breaksw
    case "-nofix_mtl":
    case "-nofix-mtl":
    case "-no_fix_mtl":
    case "-no-fix-mtl":
      set UseFixMtl = 0;
      breaksw

    case "-T2pial":
    case "-t2pial":
      set DoT2pial = 1;
      breaksw
    case "-noT2pial":
    case "-no-T2pial":
    case "-no_T2pial":
    case "-no-t2pial":
    case "-no_t2pial":
      set DoT2pial = 0;
      breaksw

    case "-FLAIRpial":
    case "-flairpial":
      set DoFLAIRpial = 1;
      breaksw
    case "-noFLAIRpial":
    case "-no-FLAIRpial":
    case "-no_FLAIRpial":
    case "-no-flairpial":
    case "-no_flairpial":
      set DoFLAIRpial = 0;
      breaksw

    case "-bbr-init-coreg"
      set BBRInit = coreg;
      breaksw
    case "-bbr-init-fsl"
      set BBRInit = fsl;
      breaksw
    case "-bbr-init-spm"
      set BBRInit = spm;
      breaksw
    case "-bbr-init-rr"
      set BBRInit = rr;
      breaksw
    case "-bbr-init-header"
      set BBRInit = header;
      breaksw
    case "-bbr-init-best"
      set BBRInit = best;
      breaksw

    default:
      echo ERROR: Flag $flag unrecognized.
      echo $cmdline
      goto error_exit;
      breaksw
  endsw
end

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

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

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

#-------------------------------------------------#
arg3err:
#-------------------------------------------------#
  echo "ERROR: flag $flag requires three arguments"
  exit 1

#-------------------------------------------------#
check_params:
#-------------------------------------------------#
  if($UseGifti) setenv FS_GII .gii

  if($DoT2pial && $DoFLAIRpial) then
    echo "Cannot specify both T2 and FLAIR for pial correction."
    goto error_exit;
  endif

  if(! $DoVersionsOnly) then
    if($#subjid != 1) then
      echo "ERROR: must specify a subject id"
      exit 1;
    endif

    if(! $?SUBJECTS_DIR ) then
      echo "ERROR: environment variable SUBJECTS_DIR not set"
      echo "  this can be done by setting it in the shell before"
      echo "  executing recon-all or by using the -sd flag"
      exit 1;
    endif

    if(! -e $SUBJECTS_DIR ) then
      echo "ERROR: SUBJECTS_DIR $SUBJECTS_DIR does not exist."
      exit 1;
    endif

    # Get the full path #
    pushd $SUBJECTS_DIR > /dev/null
    setenv SUBJECTS_DIR `$PWD`;
    popd > /dev/null

    set subjdir = $SUBJECTS_DIR/$subjid
    set mdir = $subjdir/mri
    set sdir = $subjdir/surf
    set ldir = $subjdir/label
    set tdir = $subjdir/touch

    # Note: vertexvol now hard codes --th3
    if($TH3Flag)   set TH3Opt = "-th3"
    if(! $TH3Flag) set TH3Opt = "-no-th3"

    if($DoConf2Hires) then
      set DoPialSurfs = 0;
      if($HiRes) then
        echo "ERROR: cannot use -hires with -conf2hires"
        exit 1;
      endif
      if($ConformMin) then
        echo "ERROR: cannot use -cm with -conf2hires"
        exit 1;
      endif
      if($DoCreateBaseSubj) then
        echo "ERROR: do not use -conf2hires with -base (it is unneeded)"
        exit 1;
      endif
    endif

    set fname = $subjdir/scripts/DoConf2Hires
    if(-e $fname && ! $DoConf2Hires && ($DoPialSurfs || $DoT2pial || $DoFLAIRpial)) then
      echo "ERROR: previous calls to recon-all included -conf2hires but this one does not."
      echo "If you want to run without conf2hires, delete file $fname"
      exit 1;
    endif

    set AsegForSurf = aseg.presurf.mgz
    if($SynthSegForSurf) set AsegForSurf = synthseg.rca.mgz

    if(-e $subjdir/mri/rawavg.synthsr.mgz && ! $DoSynthSR) then
      echo "ERROR: $subjdir/mri/rawavg.synthsr.mgz exists but -synthsr not specified"
      exit 1
    endif


    if($TopoFitLevel >= 1 || $JosaReg) then
      if($?FS_ALLOW_DEEP == 0) setenv FS_ALLOW_DEEP 0
      if(! $FS_ALLOW_DEEP) then
        echo "ERROR: cannot use ML routines"
        exit 1;
      endif
    endif

    if($TopoFitLevel >= 1) then
      if($DoConf2Hires) then
        echo "ERROR: topofit not testd with conf2hires"
        exit 1
      endif
      # set DoSegmentation = 1; # wm.mgz is still needed later, so don't unset
      set DoFill           = 0;
      set DoTessellate     = 0;
      set DoSmooth1        = 0;
      set DoInflate1       = 0;
      set DoQSphere        = 0;
      set DoFix            = 0;
      set DoWhitePreAparc  = 0;
      set DoWhiteSurfs     = 0;
      set DoSmooth2        = 0;
      set UseStopMaskSCM   = 0;
      set DoPialSurfs      = 0;
      if($TopoFitLevel >= 2) set DoSphere  = 0; 
      set IntensityBFS = 110; # 255 can throw off TF
    endif

    if($JosaReg) set DoSurfReg = 1;

    if($UseSamseg && $UseSynthSeg) then
      echo "ERROR: cannot specify -samseg AND -synthseg"
      exit 1
    endif

    if($xhemi) then
      set DoASegMerge    = 0
      set UseSynthStrip  = 0
      set UseSynthMorph  = 0
      set UseSynthSeg    = 0
      set CblumFromSynthSeg = 0
      set SynthSegForSurf = 0
      set FixVSinus = 0
      set FixEntoWM = 0
      set FixGA = 0
      set FixMCADura = 0
    endif

    # This is a bit of a hack as we want these to run regardless of
    # whether CALabel or SynthSeg or Samseg is run.
    if($DoCALabel) then
      set DoCCSeg = 1;
      set DoASegMerge = 1;
    endif

    if($UseSamseg || $UseSynthSeg) then
      set DoCALabel        = 0;
      set UseSynthMorph    = 1
      set DoSamsegReg      = 0;
    endif

    if($UseSynthMorph) then
      set DoTalairach      = 0;
      set DoTalCheck       = 0;
      #set DoGCAReg         = 0; # keep em_reg
      set DoCAReg          = 0; # turn off ca_reg
      set DoSamsegReg      = 0;
    endif

    # If not using emreg, then use an lta created from the talairach.xfm, get matching GCA
    if($EMRegStrip == 0) set GCASkull = RB_all_withskull_2019_10_22.talxfm.mni305.gca
    if($EMRegAseg  == 0) set GCA      = RB_all_2019_10_25.talxfm.mni305.gca

    if($DoCreateBaseSubj && ($DoT2pial || $DoFLAIRpial)) then
      echo "ERROR: do not use T2 or FLAIR when creating the longitudinal base image."
      exit 1;
    endif

    #------------ Longitudinal ---------------#
    set longbasedir = ()
    if($longitudinal || $LongSamseg) then
      set longbasedir = $SUBJECTS_DIR/$longbaseid
    endif
    if($longitudinal && ! $LongSamseg) then
      # assert that $tpNid does not contain .long.
      set haslong = `echo $tpNid | grep "\.long\."`
      if ( "$haslong" != "" ) then
        echo ""
        echo "ERROR: Detected \'.long.\' in a subject id!"
        echo ""
        echo "       If you are trying to run or re-run a longitudinal time point"
        echo "       please specify the following parameters:"
        echo ""
        echo "       \' -long <tpNid> <templateid> \'"
        echo ""
        echo "       where <tpNid> is the time point id (SAME as cross sectional"
        echo "       ID) and <templateid> is the ID created in the -base run."
        echo "       The directory <tpNid>.long.<templateid> will be created"
        echo "       automatically or used for output, if it already exists."
        echo ""
        echo "       If you are running a \'-base\' please specify a different name."
        echo "       Usage of \'.long.\' is reserved for the automatically created"
        echo "       longitudinal output."
        echo ""
        exit 1;
      endif

      #make sure cross sectional tpNid exists:
      if ( ! -e ${SUBJECTS_DIR}/${tpNid} ) then
        echo ""
        echo "ERROR: Cross sectional tpNid: ${SUBJECTS_DIR}/${tpNid}"
        echo "       does not exist!"
        echo ""
        exit 1;
      endif

      # check if base/template specified
      if($#longbaseid != 1) then
        echo ""
        echo "ERROR: Specify the <templateid> for this subject template "
        echo "       (created during the -base run):"
        echo ""
        echo "       \' -long  <tpNid> <templateid> \'"
        echo ""
        exit 1;
      endif

      # Error if longbaseid contains .long.
      set haslong = `echo $longbaseid | grep "\.long\."`
      if ( "$haslong" != "" ) then
        echo ""
        echo "ERROR: The <templateid> may not contain .long. (reserved for"
        echo "       automatic output of a longitudinal time point)."
        echo "       Specify the <templateid> for this subject template "
        echo "       (created during the -base run):"
        echo ""
        echo "       \' -long  <tpNid> <templateid> \'"
        echo ""
        exit 1;
      endif

      if(! -e $longbasedir) then
        echo "ERROR: cannot find base/template dir: $longbasedir"
        echo ""
        exit 1;
      endif
      if ( ! -e ${longbasedir}/${BaseSubjsListFname}) then
        echo "ERROR: file ${longbasedir}/${BaseSubjsListFname} does not exist!"
        echo ""
        exit 1;
      else
        set found_tpNid = 0
        set found_longbaseid = 0
        foreach f (`cat ${longbasedir}/${BaseSubjsListFname}`)
          if (${f} == ${tpNid}) set found_tpNid = 1
          if (${f} == ${longbaseid}) set found_longbaseid = 1
        end
        if ( ! $found_tpNid && ! $DoAddTp  ) then
          echo "ERROR: $tpNid is not in ${longbasedir}/${BaseSubjsListFname}"
          echo ""
          exit 1
        endif
        # check that baseid is not the same as any of the timepoint subj IDs
        if ( $found_longbaseid ) then
          echo "ERROR: Template/base ID cannot be the same as a time point ID"
          echo "       (in ${longbasedir}/${BaseSubjsListFname})"
          echo ""
          echo "       Find more info at:"
          echo "       http://surfer.nmr.mgh.harvard.edu/fswiki/LongitudinalProcessing"
          echo ""
          exit 1
        endif
      endif

    else # ================= if cross run or base or LongSamseg ==========================

      # make sure $subjid does not contain .long.
      set haslong  = `echo $subjid | grep "\.long\."`
      set hasxhemi = `echo $subjid | grep xhemi`
      if ( "$haslong" != "" && "$hasxhemi" == "" ) then
        echo ""
        echo "ERROR: Are you trying to run or re-run a longitudinal time point?"
        echo "       If so, please specify the following parameters:"
        echo ""
        echo "       \' -long <tpNid> <templateid> \'"
        echo ""
        echo "       where <tpNid> is the time point id (SAME as cross sectional"
        echo "       ID) and <templateid> is the ID created in the -base run."
        echo "       The directory <tpNid>.long.<templateid> will be created"
        echo "       automatically or used for output, if it already exists."
        echo ""
        exit 1;
      endif

    endif

    # error if base subject is run as a regular subject:
    if ( ! $DoCreateBaseSubj  )  then
      if ( -e $subjdir/$BaseSubjsListFname ) then
        echo ""
        echo "ERROR: It appears that this subject ID is an existing"
        echo "       base/template from longitudinal processing (-base):"
        echo "       $subjid"
        echo "       If you are trying to re-run a -base template you"
        echo "       need to pass the -base and all -tp flags: "
        echo ""
        echo "       \' -base <templateid> -tp <tpNid> ... -all \'"
        echo ""
        echo "       (Instead of -all you can pass other flags, such"
        echo "       as -autorecon2 -autorecon3 to run only parts.)"
        exit 1;
      endif
    endif

    # error if existing regular (cross run) is run as base
    if ( $DoCreateBaseSubj && -e $subjdir) then
      if ( ! -e $subjdir/$BaseSubjsListFname ) then
        echo ""
        echo "ERROR: It appears that the -base templateID that you passed:"
        echo "       -base $subjid"
        echo "       is an existing regular (cross sectional) run!"
        echo "       Please make sure you pass a new name (not one of"
        echo "       the time points) for the template with -base."
        echo "       For example, if you are trying to create a -base:"
        echo ""
        echo "       \' -base BertTemplate -tp Bert1 -tp Bert2 ... \'"
        echo ""
        exit 1;
      endif
    endif

    if($DoCreateBaseSubj) then
      if($#BaseSubjsList == 0) then
        echo "ERROR: must specify subjects for base subject using -base-tp" 
        exit 1;
      endif
    endif

    #---------------------------------------------------------#
    if($#InputList == 0) then
      if(! $DoCreateBaseSubj) then
        if($longitudinal) mkdir -p ${subjdir}
        if(! -e $subjdir) then
          echo "ERROR: cannot find $subjdir"
          exit 1;
        endif
        if(! -w $subjdir) then
          echo "ERROR: you do not have write permission to $subjdir"
          exit 1;
        endif
      endif
    else # An input was passed
      if( -e $subjdir) then
        echo "ERROR: You are trying to re-run an existing subject with (possibly)"
        echo " new input data (-i). If this is truly new input data, you should delete"
        echo " the subject folder and re-run, or specify a different subject name."
        echo " If you are just continuing an analysis of an existing subject, then "
        echo " omit all -i flags."
        exit 1;
      endif
      mkdir -p $subjdir
    endif
  else
    set subjdir = /tmp
  endif

  # Check that the current version is acceptable. See fs-check-version for rules
  if($DoCreateBaseSubj == 0 || $DoCreateBaseSubj == 1 && -d $subjdir) then
    set checkfile = `fs_temp_file`
    set cmd = (fs-check-version --s $subjid --o $checkfile)
    echo $cmd
    $cmd
    set ok = `cat $checkfile`
    rm -f $checkfile
    if(! $ok) then
      echo "recon-all: version check failed"
      echo $cmd
      echo ""
      exit 1
    endif
    # Check OS 
    fs-check-os --check
    if($status) then # If it fails, run again verbosely
      fs-check-os --v --check 
      exit 1
    endif
  endif

  if(! $?FREESURFER_HOME ) then
    echo "ERROR: environment variable FREESURFER_HOME not set."
    exit 1;
  endif

  if(! -e $FREESURFER_HOME ) then
    echo "ERROR: FREESURFER_HOME $FREESURFER_HOME does not exist."
    exit 1;
  endif

  if(! -e ${GCADIR}/$GCA ) then
    echo "ERROR: cannot find ${GCADIR}/$GCA" |& tee -a $LF
    exit 1;
  endif

  if(! -e ${GCADIR}/$GCASkull && ($DoSkullLTA || $DoSkullStrip)) then
    echo "ERROR: cannot find ${GCADIR}/$GCASkull" \
      |& tee -a $LF
    exit 1;
  endif

  foreach hemi ($hemilist)
    set avgtif = ${AvgCurvTifPath}/$hemi.${AvgCurvTif};
    if(! -e $avgtif) then
      echo "ERROR: cannot find $avgtif."
      exit 1;
    endif
    set GCSHemi = ${GCSDIR}/$hemi.$GCS
    if(! -e $GCSHemi) then
      echo "ERROR: cannot find $GCSHemi."
      exit 1;
    endif
    set CPAtlas = ${GCSDIR}/$hemi.$GCS
    if(! -e $CPAtlas) then
      echo "ERROR: cannot find $CPAtlas."
      exit 1;
    endif
  end

  if($XOptsUse == 1 && $XOptsClean == 1) then
    echo "ERROR: cannot specify both -xopts-clean and -xopts-use"
    exit(1);
  endif

  if($IsMPRAGE == 1 && $IsWashuMPRAGE == 1) then
    echo "ERROR: cannot specify both -mprage and -washu_mprage"
    exit(1);
  endif

  mkdir -p $subjdir/scripts
  set XOptsPreExist = $subjdir/scripts/expert-options
  if(-e $XOptsPreExist) then
    # There is a pre-existing xopts file
    if($#XOptsFile == 0) then
      # XOpts not passed on cmd line
      if($XOptsUse == 0 && $XOptsClean == 0) then
        echo "ERROR: there is a pre-existing expert options file."
        echo "You must explicitly specify whether to:"
        echo "  1. Use the pre-existing file (-xopts-use)"
        echo "  2. Delete the pre-existing file (-xopts-clean)"
        exit(1);
      endif
      if($XOptsClean == 1) then
        rm -f $XOptsPreExist
        set XOptsFile = ();
      endif
      if($XOptsUse == 1) then
        set XOptsFile = $XOptsPreExist;
      endif
    else
      # XOpts was passed on cmd line, but pre-existing xopts file
      if(! $XOptsOverwrite) then
        echo "ERROR: there is a pre-existing expert options file and"
        echo "you have specified an expert options file on the command-line."
        echo "If you want to use the file specified on the command-line,"
        echo "you must run with -xopts-overwrite, or you may edit the "
        echo "existing file $XOptsFile (and not use the -expert option)."
        exit(1);
      endif
      # If it gets here, then overwrite
      rm -f $XOptsPreExist
      cp $XOptsFile $XOptsPreExist
      if($status) goto error_exit;
    endif
  else
    # No pre-existing file
    if($#XOptsFile != 0) then
      # Expert options file specified on cmd line, make copy
      cp $XOptsFile $XOptsPreExist
      if($status) goto error_exit;
    endif
  endif

  set GlobXOptsFile = $SUBJECTS_DIR/global-expert-options.txt
  if(-e $GlobXOptsFile) then
    fsr-checkxopts $GlobXOptsFile
    if($status) goto error_exit
    if($XOptsUse == 0) then
      echo "ERROR: there is a global expert options file ($GlobXOptsFile)"
      echo "but you have not specified -xopts-use. If you want to use"
      echo "this file, then add -xopts-use. If you do not want to use"
      echo "this file, then delete it and re-run."
      exit(1);
    endif
    cp $GlobXOptsFile $subjdir/scripts/global-expert-options.copy
  else
    set GlobXOptsFile = ()
  endif

  if($DoConf2Hires) then
    touch $subjdir/scripts/DoConf2Hires
  endif

  if($#NotifyFile != 0) then
    rm -f $NotifyFile;
    set tmpdir = `dirname $NotifyFile`;
    mkdir -p $tmpdir;
    pushd $tmpdir > /dev/null;
    set tmpdir = `$PWD`;
    set NotifyFile = $tmpdir/`basename $NotifyFile`;
    popd > /dev/null;
  endif

  if($#WaitForFile != 0) then
    set tmpdir = `dirname $WaitForFile`;
    mkdir -p $tmpdir;
    pushd $tmpdir > /dev/null;
    set tmpdir = `$PWD`;
    set WaitForFile = $tmpdir/`basename $WaitForFile`;
    popd > /dev/null;
  endif

  if($DoFill && ! $FS_ALLOW_FILLED_EDIT) then
    set filledauto = $subjdir/mri/filled.auto.mgz
    if(-e $filledauto) then
      echo "ERROR: $filledauto exists but option is not turned on for this run"
      echo "This probably means that you ran with the option turned on at some point"
      echo "If you do not want to use this option, then delete the auto file with"
      echo "  rm -f $filledauto"
      echo "  Note that if you have made edits to filled.mgz, they will be lost when you re-run"
      echo "If you want to run with this option, then add -allow-filled-edit or run"
      echo "  setenv FS_ALLOW_FILLED_EDIT 1"
      echo ""
      exit 1
    endif
  endif

  if($NoFixMCADura) set FixMCADura = 0
  if($NoFixVSinus)  set FixVSinus = 0
  if($NoFixEntoWM) then
     set FixEntoWM = 0
     set FixGA = 0
  endif
  if($NoFixGA) set FixGA = 0

  if($FixGA && ! $FixEntoWM) then
    echo "ERROR: --fix-ento-wm is necessary with --fix-ga"
    exit 1
  endif

  if($SkipNuIntensityCor) set DoNuIntensityCor = 0;

  if($DoAntsN3) set DoAntsN4 = 0

  if(! $DoCleanTal && ! $DoCleanCP && ! $DoCleanBM && ! $DoConvertInput && \
     ! $DoCleanASeg && ! $DoCleanWM && ! $DoCleanFilled && ! $DoCleanSeed && ! $DoCleanCW256 && \
     ! $DoCortParc && ! $DoCortParc2 && ! $DoGCAReg && \
     ! $DoMotionCor && ! $DoTalairach && ! $DoTalCheck && ! $DoCleanXopts && \
     ! $DoNormalization  && \
     ! $DoNormalization2  && ! $DoParcStats && ! $DoParcStats2 && \
     ! $DoVersionsOnly && ! $DoDeface &&  ! $DoCleanPFH && \
     ! $DoSkullStrip && ! $DoSegmentation && ! $DoNuIntensityCor &&\
     ! $DoFill && ! $DoTessellate && ! $DoAParc2ASeg && ! $DoWMParc && \
     ! $DoSmooth1  && ! $DoInflate1 && ! $DoQSphere && ! $DoRemoveNeck &&\
     ! $DoFix  && ! $DoSmooth2 && ! $DoInflate2  && ! $DoSphere &&\
     ! $DoSkullLTA && ! $DoQdecCache  && ! $DoVnoMatchCheck &&\
     ! $DoSurfReg  && ! $DoAvgCurv && ! $DoSegStats &&\
     ! $DoMorphRGB && ! $DoAutoDetGWStats && ! $DoWhitePreAparc && ! $DoWhiteSurfs && \
     ! $DoCortexLabel && \
     ! $DoCortRibbonVolMask && ! $DoJacobianWhite && ! $DoJacobianDist0 && \
     ! $DoCANormalize && ! $DoCAReg && ! $DoCALabel && \
     ! $DoMaskBFS && ! $DoAParcASegStats && ! $DoLocalGyriIndex && \
     ! $DoMakefile && ! $DoParallel && ! $DoRelabelHypos && ! $DoCurvHK && \
     ! $DoSurfVolume && ! $DoASegMerge && ! $DoCCSeg && ! $DoCurvStats && ! $DoLabelV1 && \
     ! $DoCreateBaseSubj && ! $DoBaLabels && ! $DoShowEdits && \
     ! $DoLabelExvivoEC && ! $DoPialSurfs && ! $DoConf2Hires && \
     ! $DoSubfields  && \
     ! $DoPctSurfCon && ! $DoT2pial && ! $DoFLAIRpial && \
     ! $DoConvertT2Input && ! $DoConvertFlairInput && ! $DoSuperClean &&\
     ! $DoCortParc3 && ! $DoParcStats3 && ! $DoAPas2ASeg && ! $UseHighMyelin) then
     echo "ERROR: nothing to do. You must specify an operation to perform by adding"
     echo "flags. Eg, -all, -autorecon1, -autorecon2, -autorecon3, etc."
     exit 1;
  endif

  if($WSMore && $WSLess) then
    echo "ERROR: cannot specify both -wsmore and -wsless"
    exit 1;
  endif

  if( ($WSMore || $WSLess) && $WSPctPreFlood ) then
    echo "ERROR: cannot specify -wsmore or -wsless and -wsthresh"
    exit 1;
  endif

  if($DoParallel == 1 && $#hemilist == 1) then
    echo "ERROR: cannot use -parallel with a single hemi"
    exit 1;
  endif

  if($UseSynthSeg && $CblumFromSynthSeg) then
    echo "ERROR: cannot -synthseg and -cblum-from-synthseg"
    exit 1
  endif
  if($UseSynthSeg && $SynthSegForSurf) then
    echo "ERROR: cannot -synthseg and -synthseg-for-surf"
    exit 1
  endif

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


#-------------------------------------------------#
usage_exit:
#-------------------------------------------------#
  echo ""
  echo "USAGE: $ProgName"
  echo ""
  echo " Required Arguments:";
  echo "   -subjid <subjid>"
  echo "   -<process directive>"
  echo ""
  echo " Fully-Automated Directive:"
  echo "  -all           : performs all stages of cortical reconstruction"
  echo "  -autorecon-all : same as -all"
  echo ""
  echo " Manual-Intervention Workflow Directives:"
  echo "  -autorecon1    : process stages 1-5 (see below)"
  echo "  -autorecon2    : process stages 6-23"
  echo "                   after autorecon2, check white surfaces:"
  echo "                     a. if wm edit was required, then run -autorecon2-wm"
  echo "                     b. if control points added, then run -autorecon2-cp"
  echo "                     c. proceed to run -autorecon3"
  echo "  -autorecon2-cp : process stages 12-23 (uses -f w/ mri_normalize, -keep w/ mri_seg)"
  echo "  -autorecon2-wm : process stages 15-23"
  echo "  -autorecon2-inflate1 : 6-18"
  echo "  -autorecon2-perhemi : tess, sm1, inf1, q, fix, sm2, inf2, finalsurf, ribbon"
  echo "  -autorecon3    : process stages 24-34"
  echo "                     if edits made to correct pial, then run -autorecon-pial"
  echo "  -hemi ?h       : just do lh or rh (default is to do both)"
  echo ""
  echo "  Autorecon Processing Stages (see -autorecon# flags above):"
  echo "    1.  Motion Correction and Conform"
  echo "    2.  NU (Non-Uniform intensity normalization)"
  echo "    3.  Talairach transform computation"
  echo "    4.  Intensity Normalization 1"
  echo "    5.  Skull Strip"
  echo ""
  echo "    6.  EM Register (linear volumetric registration)"
  echo "    7.  CA Intensity Normalization"
  echo "    8.  CA Non-linear Volumetric Registration "
  echo "    9.  Remove neck"
  echo "    10. EM Register, with skull"
  echo "    11. CA Label (Aseg: Volumetric Labeling) and Statistics"
  echo ""
  echo "    12. Intensity Normalization 2 (start here for control points)"
  echo "    13. White matter segmentation"
  echo "    14. Edit WM With ASeg"
  echo "    15. Fill (start here for wm edits)"
  echo "    16. Tessellation (begins per-hemisphere operations)"
  echo "    17. Smooth1"
  echo "    18. Inflate1"
  echo "    19. QSphere"
  echo "    20. Automatic Topology Fixer"
  echo "    21. White Surfs (start here for brain edits for pial surf)"
  echo "    22. Smooth2"
  echo "    23. Inflate2"
  echo ""
  echo "    24. Spherical Mapping"
  echo "    25. Spherical Registration "
  echo "    26. Spherical Registration, Contralater hemisphere"
  echo "    27. Map average curvature to subject"
  echo "    28. Cortical Parcellation (Labeling)"
  echo "    29. Cortical Parcellation Statistics"
  echo "    30. Pial Surfs"
  echo "    31. WM/GM Contrast"
  echo "    32. Cortical Ribbon Mask"
  echo "    33. Cortical Parcellation mapped to ASeg"
  echo "    34  Brodmann and exvio EC labels"
  echo ""
  echo " Step-wise Directives"
  echo "  See -help"
  echo ""
  echo " Expert Preferences"
  echo "  -pons-crs C R S : col, row, slice of seed point for pons, used in fill"
  echo "  -cc-crs C R S : col, row, slice of seed point for corpus callosum, used in fill"
  echo "  -lh-crs C R S : col, row, slice of seed point for left hemisphere, used in fill"
  echo "  -rh-crs C R S : col, row, slice of seed point for right hemisphere, used in fill"
  echo "  -nofill        : do not use the automatic subcort seg to fill"
  echo "  -watershed cmd : control skull stripping/watershed program"
  echo "  -xmask file : custom external brain mask to replace automated skullstripping"
  echo "  -wsless : decrease watershed threshold (leaves less skull, but can strip more brain)"
  echo "  -wsmore : increase watershed threshold (leaves more skull, but can strip less brain)"
  echo "  -wsatlas : use atlas when skull stripping"
  echo "  -no-wsatlas : do not use atlas when skull stripping"
  echo "  -no-wsgcaatlas : do not use GCA atlas when skull stripping"
  echo "  -wsthresh pct : explicity set watershed threshold"
  echo "  -wsseed C R S : identify an index (C, R, S) point in the skull"
  echo "  -norm3diters niters : number of 3d iterations for mri_normalize"
  echo "  -normmaxgrad maxgrad : max grad (-g) for mri_normalize. Default is 1."
  echo "  -norm1-b N : in the _first_ usage of mri_normalize, use control "
  echo "               point with intensity N below target (default=10.0) "
  echo "  -norm2-b N : in the _second_ usage of mri_normalize, use control "
  echo "               point with intensity N below target (default=10.0) "
  echo "  -norm1-n N : in the _first_ usage of mri_normalize, do N number "
  echo "               of iterations"
  echo "  -norm2-n N : in the _second_ usage of mri_normalize, do N number "
  echo "               of iterations"
  echo "  -cm           : conform volumes to the min voxel size "
  echo "  -no-fix-with-ga : do not use genetic algorithm when fixing topology"
  echo "  -fix-diag-only  : topology fixer runs until ?h.defect_labels files"
  echo "                    are created, then stops"
  echo "  -seg-wlo wlo : set wlo value for mri_segment and mris_make_surfaces"
  echo "  -seg-ghi ghi : set ghi value for mri_segment and mris_make_surfaces"
  echo "  -nothicken   : pass '-thicken 0' to mri_segment"
  echo "  -no-ca-align-after : turn off -align-after with mri_ca_register"
  echo "  -no-ca-align : turn off -align with mri_ca_label"
  echo "  -deface      : deface subject, written to orig_defaced.mgz"
  echo ""
  echo "  -expert file     : read-in expert options file"
  echo "  -xopts-use       : use pre-existing expert options file"
  echo "  -xopts-clean     : delete pre-existing expert options file"
  echo "  -xopts-overwrite : overwrite pre-existing expert options file"
  echo "  -termscript script : run script before exiting (multiple -termscript flags possible)"
  echo "   This can be good for running custom post-processing after recon-all"
  echo "   The script must be in your path. The subjid is passed as the only argument"
  echo "   The current directory is changed to SUBJECTS_DIR before the script is run"
  echo "   The script should exit with 0 unless there is an error"
  echo ""
  echo "  -mprage : assume scan parameters are MGH MP-RAGE protocol"
  echo "  -washu_mprage : assume scan parameters are Wash.U. MP-RAGE protocol."
  echo "                  both mprage flags affect mri_normalize and mri_segment,"
  echo "                  and assumes a darker gm."
  echo "  -schwartzya3t-atlas : for tal reg, use special young adult 3T atlas"
  echo ""
  echo "  -threads num  : set number of threads to use"
  echo ""
  echo " Notification Files (Optional)"
  echo "  -waitfor file : wait for file to appear before beginning"
  echo "  -notify  file : create this file after finishing"
  echo ""
  echo " Status and Log files (Optional)"
  echo "  -license  file : specify license file, otherwise defaults to FREESURFER/license"
  echo "  -log     file : default is scripts/recon-all.log"
  echo "  -status  file : default is scripts/recon-all-status.log"
  echo "  -noappend     : start new log and status files instead of appending"
  echo "  -no-isrunning : do not check whether this subject is currently being processed"
  echo ""
  echo " Segmentation of substructures of hippocampus and brainstem "
  echo " (These deprecated; please see segmentHA_T1.sh, segmentHA_T1.sh, segmentHA_T1_long.sh, segmentBS.sh)"
  echo "  -hippocampal-subfields-T1 : segmentation of hippocampal subfields using input T1 scan"
  echo "  -hippocampal-subfields-T2 file ID : segmentation using an additional scan (given by file);"
  echo "                                      ID is a user-defined identifier for the analysis"
  echo "  -hippocampal-subfields-T1T2 file ID : segmentation using additional scan (given by file) and input T1"
  echo "                                        simultaneously; ID is a user-defined identifier for the analysis"
  echo "  -brainstem-structures : segmentation of brainstem structures"
  echo ""
  echo " Other Arguments (Optional)"
  echo "  -sd subjectsdir : specify subjects dir (default env SUBJECTS_DIR)"
  echo "  -mail username  : mail user when done"
  echo "  -umask umask    : set unix file permission mask (default 002)"
  echo "  -grp groupid    : check that current group is alpha groupid "
  echo "  -onlyversions   : print version of each binary and exit"
  echo "  -debug          : print out lots of info"
  echo "  -allowcoredump  : set coredump limit to unlimited"
  echo "  -dontrun        : do everything but execute each command"
  echo "  -version        : print version of this script and exit"
  echo "  -help           : voluminous bits of wisdom"
  echo ""

  if(! $PrintHelp) exit 1;

  echo $FS_RECON_VERSION
  echo ""

  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

Performs all, or any part of, the FreeSurfer cortical reconstruction
process. This help only gives some simple information. For more
detailed documentation, see https://surfer.nmr.mgh.harvard.edu

Basic usages:

1. Subject dir does not exist:

  recon-all -subject subjectname -i invol1 <-i invol2> -all

Creates analysis directory $SUBJECTS_DIR/subjectname, converts one or
more input volumes to MGZ format in subjectname/mri/orig, and runs
all processing steps. If subjectname exists, then an error is returned
when -i is used; but this can be overridden with -force (in which
case any pre-existing source volumes are deleted).

2. Manual conversion into mgz:

  mkdir -p $SUBJECTS_DIR/subjectname/mri/orig
  mri_convert invol1 $SUBJECTS_DIR/subjectname/mri/orig/001.mgz
  mri_convert invol2 $SUBJECTS_DIR/subjectname/mri/orig/002.mgz
  recon-all -subject subjectname -all

If no input volumes are given, then it is assumed that the subject
directory has already been created and that the raw data already
exists in MGZ format in subjid/mri/orig as XXX.mgz, where XXX is a
3-digit, zero-padded number.


SUBJECT IDENTIFICATION STRING

-s subjectname
-sid subjectname
-subjid subjectname
-subject subjectname

'subjectname' is the FreeSurfer subject identification string which doubles
as the name of the reconstruction root directory for this subject. This
reconstruction should be referenced by this string for all FreeSurfer
commands and in the register.dat matrix (for functional interfacing).


SPECIFYING DIRECTIVES

Directives instruct recon-all which part(s) of the reconstruction
stream to run. While it is possible to do everything in one shot (using
the -all flag), there can be some benefits to customizing the
stream. These benefits include stopping to perform manual editing as
well as parallelization. Directives are either clustered or step-wise.
Clustered directives are sets of steps that can be performed by
specifying a single flag. A step-wise directive refers to a single
step.  Directives accumulate. A step can be removed from a cluster by
adding -no<step> after the cluster flag. For example, specifying
-all followed by -notalairach will perform all the reconstruction
steps except talairaching. However, note that if -notalairach *preceeded*
-all, talairaching would still be performed.


CLUSTERED DIRECTIVES

-all
-autorecon-all

Perform all reconstruction steps.

-autorecon1

Motion correction through skull strip.

-autorecon2

Subcortical segmentation through make white surfaces.

-autorecon2-cp

Normalization2 through make final surfaces.

-autorecon2-wm

Fill through make white surfaces. Used after editing wm volume after running
-autorecon2.

-autorecon-pial

Makes final surfaces (white and pial). Used after editing brain.finalsurfs
volume after running -autorecon2. The brain.finalsurfs.mgz volume may be
edited to fix problems with the pial surface.

-autorecon3

Spherical morph, automatic cortical parcellation, pial surf and ribbon mask.


STEP-WISE DIRECTIVES

Step-wise directives allow the user to implement a single step in the
reconstruction process. See also STEP DESCRIPTION SUMMARIES below.
They also allow users to include/exclude a step from a clustered
DIRECTIVE. To include a step, use -step (eg, -skullstrip). To exclude
a step, use -nostep (eg -noskullstrip).

Run times are approximate for an Intel Xeon E5-2643 64bit 3.4GHz processor:

  -<no>motioncor          2 min
  -<no>talairach        < 1 min
  -<no>normalization      2 min
  -<no>skullstrip        15 min
  -<no>nuintensitycor     1 min
  -<no>gcareg            15 min
  -<no>canorm             1 min
  -<no>careg              1 hour
  -<no>rmneck             1 min
  -<no>skull-lta         12 min
  -<no>calabel           34 min
  -<no>normalization2     3 min
  -<no>maskbfs          < 1 min
  -<no>segmentation       1 min
  -<no>fill               1 min
  -<no>tessellate       < 1 min     per hemisphere
  -<no>smooth1          < 1 min     per hemisphere
  -<no>inflate1           1 min     per hemisphere
  -<no>qsphere            3 min     per hemisphere
  -<no>fix               15 min     per hemisphere
  -<no>white              3 min     per hemisphere
  -<no>smooth2          < 1 min     per hemisphere
  -<no>inflate2         < 1 min     per hemisphere
  -<no>curvHK           < 1 min     per hemisphere
  -<no>curvstats        < 1 min     per hemisphere
  -<no>sphere            40 min     per hemisphere
  -<no>surfreg           50 min     per hemisphere
  -<no>jacobian_white   < 1 min     per hemisphere
  -<no>avgcurv          < 1 min     per hemisphere
  -<no>cortparc           1 min     per hemisphere
  -<no>pial               4 min     per hemisphere
  -<no>surfvolune       < 1 min     per hemisphere
  -<no>cortribbon        15 min
  -<no>parcstats        < 1 min     per hemisphere
  -<no>cortparc2          1 min     per hemisphere
  -<no>parcstats2       < 1 min     per hemisphere
  -<no>cortparc3          1 min     per hemisphere
  -<no>parcstats3       < 1 min     per hemisphere
  -<no>pctsurfcon       < 1 min     per hemisphere
  -<no>hyporelabel      < 1 min     per hemisphere
  -<no>aparc2aseg         1 min
  -<no>apas2aseg          1 min
  -<no>segstats           3 min
  -<no>wmparc             7 min
  -<no>balabels           5 min     per hemisphere

  -all                    7 hours   both hemipheres

If -parallel is specified, runtime is reduced to 3 hours.


SEGMENTATION OF HIPPOCAMPAL SUBFIELDS  AND NUCLEI OF THE AMYGDALA (CROSS-SECTIONAL AND LONGITUDINAL)

The following flags can be used to obtain a segmentation of the hippocampal subfields,
as well as of the nuclei of the amygdala.
The methods are described in [17] (hippocampus) and [19] (amygdala). There is also a
longitudinal version of the algorithm [20]. You can find further information here:
https://surfer.nmr.mgh.harvard.edu/fswiki/HippocampalSubfieldsAndNucleiOfAmygdala

Note that the following 6.0 flags have been deprecated:

-hippocampal-subfields-T1
-hippocampal-subfields-T2 
-hippocampal-subfields-T1T2 

And replaced by the following scripts (for help, run them with flag --help): 

segmentHA_T1.sh: Uses the T1 scan which the recon-all stream has processed at 1 mm 
resolution or higher (with -cm).

segmentHA_T2.sh: It uses an additional scan in the segmentation, typically  (but
not necessarily) a T2 volume with higher resolution, at least in the coronal plane. 
This additional scan can be used in isolation or in combination with the T1 volume
processed with recon-all

segmentHAsegment_T1_long.sh: This is the longitudinal version of segmentHA_T1.sh.


SEGMENTATION OF BRAINSTEM STRUCTURES

This module performs segmentation of brains structures (medulla, pons, midbrain, SCP) on 
the T1 scan which the  recon-all stream has processed, at 1 mm or higher resolution (with 
-cm). The method is described in [18]. You can read more at: 
http://surfer.nmr.mgh.harvard.edu/fswiki/BrainstemSubstructures

Note that the following 6.0 flag has been deprecated:

-brainstem-structures

And replaced by the following script (for help, run it with flag --help): 

segmentBS.sh


EXPERT PREFERENCES

-pons-crs C R S

Specify a seed point for the pons during the fill operation. This is
used to cut the brain stem from brain. By default, this point will be
determined automatically. It should only be specified if there is a
cut failure. To determine what this point should be, find the center
of the pons in the T1 volume (in tkmedit) and record the column, row,
and slice. Creates a file called scripts/seed-ponscrs.man.dat
with the CRS.

-cc-crs C R S

Specify a seed point for the corpus callosum during the fill
operation. This is used to help separate the hemispheres.  By default,
this point will be determined automatically. It should only be
specified if there is a cut failure.  To determine what this point
should be, find the center of the CC in the T1 volume (in tkmedit) and
record the column, row, and slice. Creates a file called
scripts/seed-cccrs.man.dat with the CRS.

-lh-crs C R S

Specify a seed point for the left hemisphere during the fill
operation. This is used to help identify the left hemisphere.  By
default, this point will be determined automatically. It should only
be specified if there is a cut failure.  To determine what this point
should be, find a point in the white matter mass of the left
hemisphere in the T1 volume (in tkmedit) and record the column, row,
and slice. Creates a file called scripts/seed-cccrs.man.dat with the
CRS. Remember that tkmedit displays the volume in radiological
convention (ie, left is right).

-rh-crs C R S

Same as -lh-crs but for the right hemisphere. Creates a file called
scripts/seed-rhcrs.man.dat with the CRS.

-watershed cmd

This controls how the skull stripping will be performed. Legal values are
normal (the default), atlas, nowatershed, watershedonly, and watershedtemplate.

-wsmore/-wsless

Increase/decrease the preflooding height (threshold) when skull
stripping. -wsmore will expand the skull surface; -wsless will shrink
the skull surface.  See also -wsthresh.

-wsthresh pctheight

Explicitly set the preflooding height when skull stripping.

-wsseed R C S

Supply a point in the volume that the user believes to be in the white
matter.  By default, this point will be determined automatically. It
should only be specified if there is a strip failure. To determine
what this point should be, find a point in the white matter using
tkmedit and record the Volume Index values (NOT the XYZ coordinates).

-no-wsgcaatlas

Disable usage of the GCA atlas when running mri_watershed skull-stripping.
The default is to use the GCA atlas to locate anatomy aiding skull-strip.

-gca gcafile

Specify the name of the gaussian classifier array (GCA) file
to be used with GCA registration and automatic subcortical
segmentation. It must be found in the FREESURFER_HOME/average directory (or
use -gca-dir to specify an alternate path).
The Default is RB_all_YYYY-MM-DD.gca located in
FREESURFER_HOME/average. This has no effect unless the GCA registration
or subcortical segmentation stages are to be performed.

-gca-skull gcafile

Specify the name of the gaussian classifier array (GCA) file to be used with
registration with skull.  It must be found in the FREESURFER_HOME/average
directory (or use -gca-dir to specify an alternate path).
The default is RB_all_withskull_YYYY-MM-DD.gca located in
FREESURFER_HOME/average.

-gcs gcsfile

Specify the name of the gaussian classifier surface atlas (GCS) file
to be used for the cortical parcellation stage. It must be found in the
FREESURFER_HOME/average directory (or use -gcs-dir to specify an alternate
path). The default is named
curvature.buckner40.filled.desikan_killiany.2007-06-20.gcs and is located in
FREESURFER_HOME/average.

-twm twmfile

Where (twmfile) is a control.dat format file (a point set in freeview)
with points manually selected to be in the white matter inferior to
hippocampus in the temporal lobe. This option is passed to mri_ca_register.

-nuiterations

Number of iterations in the non-uniform intensity correction.
Default is 2.

-norm3diters niters

Use niters 3d normalization iterations (passes as -n to _both_ runs of
mri_normalize).

-normmaxgrad maxgrad

Passes "-g maxgrad" to _both_ runs of mri_normalize. Max grad default is 1.

-norm1-b N

In the _first_ usage of mri_normalize (during creation of T1.mgz), use
control point with intensity N below target (default=10.0)

-norm1-n N

In the _first_ usage of mri_normalize, do N number of iterations

-norm2-b N

In the _second_ usage of mri_normalize (during creation of brain.mgz), use
control point with intensity N below target (default=10.0)

-norm2-n N

In the _second_ usage of mri_normalize, do N number of iterations

-noaseg

Skips subcortical segmentation steps (same as -nosubcortseg), and does
not use aseg.presurf.mgz for inorm2, wm segmentation, or filling. 
Use this flag for brains that do not support usage of Freesurfers subcortical
segmentation, such as baby brains, or non-human primates.

-noaseg-inorm2

Does not use aseg.presurf.mgz for the second mri_normalize step.

-bigventricles

If a subject has enlarged ventricles due to atrophy, include the -bigventricles
flag with the -autorecon2 stage in order to prevent surfaces extending into
the ventricle regions. The flag directly affects the binary mri_ca_register,
and mris_make_surfaces indirectly via aseg.presurf.mgz.

-norandomness

The random number generator used by certain binaries is seeded with the
same number, thus producing identical results from run to run.

-cw256

Include this flag after -autorecon1 if images have a FOV > 256.  The
flag causes mri_convert to conform the image to dimensions of 256^3.

-notal-check

Skip the automatic failure detection of Talairach alignment.

-qcache

Produce the pre-cached files required by the Qdec utility, allowing rapid
analysis of group data.  These files are created by running mris_preproc,
which creates smoothed surface data files sampled to the 'fsaverage'
common-space surface. By default, the surface data for thickness, curv, sulc,
area and jacobian_white are smoothed at 0, 5, 10, 15, 20, and 25 mm FWHM.
If just one set of surface data needs to be processed, then the option
-measure <surfmeas> can follow -qcache, where <surfmeas> is one of: thickness,
curv, sulc, area, jacobian_white or any surface measure. Multiple instances
of -measure <meas> is supported.  The -measuredir option allows
specifying a directory other than the default of surf. Another option is
-fwhm <num> where <num> is a value in mm.  Also, -target <name> allows
specifying a common-space target other than fsaverage (the default).
qcache is also a target for make, eg. recon-all -make qcache
See also: http://surfer.nmr.mgh.harvard.edu/fswiki/Qdec

-smooth-cortex-only

Only applies with -qcache. Only smooth data if it is part of the ?h.cortex.label.
This prevents values in the medial wall (which are meaningless) from being
smoothed into cortical areas. This is the default and you will have to turn
it off with -no-smooth-cortex-only.

-no-smooth-cortex-only

Allow medial wall values to smooth into cortex.

-make target

Runs recon-all through 'make', the standard utility used to create a file
only if its dependencies are out-of-date.  This -make option makes use of the
file recon-all.makefile, where the dependency chain is specified.
A 'target' argument must be specified.  The valid targets are:

  all
  autorecon1
  autorecon2
  autorecon2-volonly
  autorecon2-perhemi
  autorecon3
  qcache

These targets correspond to their flag equivalents in recon-all.  The
difference in behaviour is that files are created only if the file does not
exist or if an input file used to create it has a newer date than the file
in need of creation.  It is also possible to supply the full pathname to a
particular file as a target.

The flag -dontrun can also be specified to show the commands that will run
without excuting them.

-lgi
-lGI
-localGI

Computes local measurements of pial-surface gyrification at thousands of
points over the cortical surface. See reference [13] for details.

-label_v1

Create a label of V1, based on Hinds et al., NeuroImage 39 (2008) 1585-1599.

-balabels
-ba-labels
-ba_labels

Creates Brodmann area labels of BA1, BA2, BA3a, BA3b, BA4a, BA4p, BA6, BA44,
BA45, V1, V2, and V5/MT (and perirhinal) by mapping labels from the 
'fsaverage' subject, which must exist within the SUBJECTS_DIR.  
Based on:
"Cortical Folding Patterns and Predicting Cytoarchitecture", Fischl et al.,
Cerebral Cortex 2007.

-threads num
-openmp num

Set the number of threads available to openMP-enabled tools.


EXPERT OPTIONS FILE

While the expert preferences flags supported by recon-all cover most
of the instances where special flags need to be passed to a FreeSurfer
binary, to allow passing an arbitrary flag to a binary, recon-all
supports the reading of a user-created "expert options" (xopts) file
containing options to append to the command string. This may be used
to specify new options or to override default values. There are two
types xopts file, local and global. The local file you pass on the
command line and is used only for the subject you run it with. The
global is place in $SUBJECTS_DIR/global-expert-options.txt and will be
used with every call to recon-all for subjects in $SUBJECTS_DIR. If
both contain options for the same command, then the local xopts file
takes precedence.

Each line of the xopts file corresponds to one command. The first item
is the name of the command; the items following it on rest of the line
will be passed as the extra options.  For example, if a file called
expert.opts is created containing these lines:

  mri_em_register -p .5
  mris_topo_fixer -asc

then the option "-p .5" will be passed to mri_em_register, and "-asc"
will be passed to mris_topo_fixer.  The name of the expert options file
is passed to recon-all with the -expert flag, eg.

  recon-all -expert expert.opts ...

When an expert options is passed, it will be copied to
scripts/expert-options.  Future calls to recon-all, the user MUST
explicitly specify how to treat this file.  Options are (1) use the
file (-xopts-use), or (2) delete it (-xopts-clean). If this file exsts
and the user specifies another expert options file, then the user must
also specify -xopts-overwrite. If the file global-expert-options.txt
exists in $SUBJECTS_DIR, then options in that file are also used. They
will appear before options in the passed file (and so will superseded
the global).

The following FreeSurfer binaries will accept an expert option:

  talairach_avi
  mri_normalize
  mri_watershed
  mri_em_register
  mri_ca_normalize
  mri_ca_register
  mri_remove_neck
  mri_ca_label
  mri_segstats
  mri_mask
  mri_segment
  mri_edit_wm_with_aseg
  mri_pretess
  mri_fill
  mri_tessellate
  mris_smooth
  mris_inflate
  mris_sphere
  mris_fix_topology
  mris_topo_fixer
  mris_remove_intersection
  mris_make_surfaces
  mris_surf2vol
  mris_register
  mris_jacobian
  mrisp_paint
  mris_ca_label
  mris_anatomical_stats
  mri_aparc2aseg


NOTIFICATION FILES

Notification files allow the user to cascade invocations to recon-all,
with one invocation waiting until another one terminates. This is done
by specifying a file that must exist before an invocation can precede
(-waitfor) and/or specifying a file that is created when an invocation
terminates (-notify). This type of interprocess communication can
allow users to parallelize the stream. If this is to be done, note
that each hemisphere can be run separately by specifying the -hemi
flag.


LOG AND STATUS FILES

By default, log and status files are created in subjid/scripts. The
log file contains all the output from all the programs that have been
run during the invocation to recon-all. The status file has a list of
all the programs that have been run and the time at which each
started. The log file is intended to be a record of what was done
whereas the status file allows the user to easily see where in the
stream a currently running process is. The log file should be sent
with all bug reports. By default, these files are called recon-all.log
and recon-all-status.log, but this can be changed with the -log and
-status options. By default, the log and status are appended to. New
log and status files can be forced with the -noappend flag.


OTHER ARGUMENTS

-sd subjectsdir

This allows the user to specify the root of the FreeSufer subjects
directory. If unspecified, the environment variable SUBJECTS_DIR
is used.

-mail username

Send email to username when the process terminates.


STEP DESCRIPTION SUMMARIES

Motion Correction (-<no>motioncor)

When there are multiple source volumes, this step will correct for
small motions between them and then average them together. The input
are the volumes found in file(s) mri/orig/XXX.mgz. The output will be
the volume mri/orig.mgz. If no runs are found, then it looks for
a volume in mri/orig (or mri/orig.mgz). If that volume is there, then
it is used in subsequent processes as if it was the motion corrected
volume. If no volume is found, then the process exits with errors.
The motion correction step uses a robust registration [14] procedure
to produce highly accurate registrations of the brain, ignoring outlier
regions, such as differen cropping planes, jaw, neck, eye movement etc.

Talairach (-<no>talairach)

This computes the affine transform from the orig volume to the MNI305
atlas using Avi Snyders 4dfp suite of image registration tools,
through a FreeSurfer script called talairach_avi. Several of the downstream
programs use talairach coordinates as seed points. You can/should check
how good the talairach registration is using
"tkregister2 --s subjid --fstal-avi". You must have an "fsaverage" subject in
your SUBJECTS_DIR. tkregister2 allows you to compare the orig volume
against the talairach volume resampled into the orig space. If you modify
the registration, it will change the talairach.xfm file. Your edits will
be *not* be overwritten unless you run recon-all specifying -clean-tal.
Run "tkregister2 --help" for more information.
Creates the files mri/transform/talairach.auto.xfm and talairach.xfm.
The flag -tal-check will check the registration against known-good transforms.
Adding the flag -use-mritotal after -talairach will use the MINC program
mritotal (see Collins, et al., 1994) to perform the transform.

Normalization (-<no>normalization)

Performs intensity normalization of the orig volume and places the
result in mri/T1.mgz. Attempts to correct for fluctuations in
intensity that would otherwise make intensity-based segmentation much
more difficult. Intensities for all voxels are scaled so that the mean
intensity of the white matter is 110. If there are problems with the
normalization, users can add control points. See also Normalization2.

Skull Strip (-<no>skullstrip)

Removes the skull from mri/T1.mgz and stores the result in
mri/brainmask.auto.mgz and mri/brainmask.mgz.
Runs the mri_watershed program. If the strip fails, users can specify
seed points (-wsseed) or change the threshold (-wsthresh, -wsmore, -wsless).
The -autorecon1 stage ends here.

NU Intensity Correction (-<no>nuintensitycor)

Non-parametric Non-uniform intensity Normalization (N3), corrects for
intensity non-uniformity in MR data,  making relatively few assumptions
about the data.  This runs the MINC tool 'nu_correct'.  By default, one
iteration of nu_correct is run.  The flag -nuiterations specification
of some other number of iterations.

Automatic Subcortical Segmentation (-<no>subcortseg)

This is done in six stages. (1) GCA linear registration
(-gcareg). This is an initial registration to a template. (2)
Canonical Normalization (-canorm), (3) Canonical Registration
(-careg). (4) Neck removal (-rmneck), (5) Registration, w/skull
(-skull-lta), and (6) Subcortical labeling (-calabel).
The stages are listed next.

EM (GCA) Registration (-<no>gcareg)

Computes transform to align the mri/nu.mgz volume to the default GCA atlas
found in FREESURFER_HOME/average (see -gca flag for more info).
Creates the file mri/transforms/talairach.lta.
The -autorecon2 stage starts here.

CA Normalize (-<no>canorm)

Further normalization, based on GCA model.
Creates mri/norm.mgz.
Note: -canorm-usecps will enable usage of control points during normalization.

CA Register (-<no>careg)

Computes a nonlinear transform to align with GCA atlas.
Creates the file mri/transform/talairach.m3z.

Remove neck (-<no>rmneck)

The neck region is removed from the NU-corrected volume mri/nu.mgz.
Makes use of transform computed from prior CA Register stage.
Creates the file mri/nu_noneck.mgz.

EM Registration, with Skull (-<no>skull-lta)

Computes transform to align volume mri/nu_noneck.mgz with GCA volume
possessing the skull.
Creates the file mri/transforms/talairach_with_skull_2.lta.

CA Label (-<no>calabel)

Labels subcortical structures, based in GCA model.
Creates the files mri/aseg.auto.mgz and mri/aseg.presurf.mgz.

ASeg Stats (-<no>segstats)

Computes statistics on the segmented subcortical structures found
in mri/aseg.mgz. Writes output to file stats/aseg.stats.

Normalization2 (-<no>normalization)

Performs a second (major) intensity correction using only the brain
volume as the input (so that it has to be done after the skull strip).
Intensity normalization works better when the skull has been removed.
Creates a new brain.mgz volume. The -autorecon2-cp stage begins here.
If -noaseg flag is used, then aseg.presurf.mgz is not used by mri_normalize.

WM Segmentation (-<no>segmentation)

Attempts to separate white matter from everything else. The input is
mri/brain.mgz, and the output is mri/wm.mgz.  Uses intensity,
neighborhood, and smoothness constraints.  This is the volume that is
edited when manually fixing defects. Calls mri_segment,
mri_edit_wm_with_aseg, and mri_pretess. To keep previous edits, run
with -keep. If -noaseg is used, them mri_edit_wm_aseg is skipped.

Cut/Fill (-<no>fill)

This creates the subcortical mass from which the orig surface is
created. The mid brain is cut from the cerebrum, and the hemispheres
are cut from each other. The left hemisphere is binarized to 255.
The right hemisphere is binarized to 127.  The input is mri/wm.mgz
and the output is mri/filled.mgz. Calls mri_fill. If the cut fails,
then seed points can be supplied (see -cc-crs, -pons-crs, -lh-crs,
-rh-crs). The actual points used for the cutting planes in the
corpus callosum and pons can be found in scripts/ponscc.cut.log.
The stage -autorecon2-wm begins here.  This is the last stage of
volumetric processing. If -noaseg is used, then aseg.presurf.mgz is 
not used by mri_fill.

Tessellation (-<no>tessellate)

This is the step where the orig surface (ie, surf/?h.orig.nofix) is
created. The surface is created by covering the filled hemisphere with
triangles. Runs mri_tessellate. The places where the points of the
triangles meet are called vertices. Creates the file surf/?h.orig.nofix
Note: the topology fixer will create the surface ?h.orig.

Orig Surface Smoothing (-<no>smooth1, -<no>smooth2)

After tesselation, the orig surface is very jagged because each
triangle is on the edge of a voxel face and so are at right angles to
each other. The vertex positions are adjusted slightly here to reduce
the angle. This is only necessary for the inflation processes.
Creates surf/?h.smoothwm(.nofix). Calls mris_smooth. Smooth1 is the step
just after tessellation, and smooth2 is the step just after topology
fixing.

Inflation (-<no>inflate1, -<no>inflate2)

Inflation of the surf/?h.smoothwm(.nofix) surface to create
surf/?h.inflated. The inflation attempts to minimize metric distortion
so that distances and areas are perserved (ie, the surface is not
stretched). In this sense, it is like inflating a paper bag and not a
balloon.  Inflate1 is the step just after tessellation, and inflate2
is the step just after topology fixing. Calls mris_inflate. Creates
?h.inflated, ?h.sulc, ?h.curv, and ?h.area.

QSphere (-<no>qsphere)

This is the initial step of automatic topology fixing. It is a
quasi-homeomorphic spherical transformation of the inflated surface designed
to localize topological defects for the subsequent automatic topology fixer.
Calls mris_sphere. Creates surf/?h.qsphere.nofix.

Automatic Topology Fixer (-<no>fix)

Finds topological defects (ie, holes in a filled hemisphere) using
surf/?h.qsphere.nofix, and changes the orig surface (surf/?h.orig.nofix)
to remove the defects. Changes the number of vertices.  All the defects
will be removed, but the user should check the orig surface in the volume
to make sure that it looks appropriate. Calls mris_topo_fixer.
Creates surf/?h.orig (by iteratively fixing surf/?h.orig.nofix).

White Surface (-<no>white)

Creates the ?h.white surfacees as well as the curvature file (?h.curv).
The white surface is created by "nudging" the orig surface so that it
closely follows the white-gray intensity gradient as found in the T1 volume.
Calls mris_make_surfaces.  See also "Pial Surface" and "Final Surfaces".

Spherical Inflation (-<no>sphere)

Inflates the orig surface into a sphere while minimizing metric
distortion.  This step is necessary in order to register the surface
to the spherical atlas. (also known as the spherical morph). Calls
mris_sphere. Creates surf/?h.sphere.  The -autorecon3 stage begins here.

Ipsilateral Surface Registation (Spherical Morph) (-<no>surfreg)

Registers the orig surface to the spherical atlas through
surf/?h.sphere. The surfaces are first coarsely registered by aligning
the large scale folding patterns found in ?h.sulc and then fine tuned
using the small-scale patterns as in ?h.curv.
Calls mris_register. Creates surf/?h.sphere.reg.

Jacobian (-<no>jacobian_white)

Computes how much the white surface was distorted in order to register
to the spherical atlas during the -surfreg step. Creates ?h.jacobian_white
(a curv formatted file). This step follows the surface registration step.

Surface Registation, maximal distortion, with Jacobian (-<no>jacobian_dist0)

Run spherical registration with no metric distortion penalty. This will
cause surface geometry to align regardless of the amount of distortion
induced (ie, distance contraints are turned off). The distortion will then
be quantified by the Jacobian of the transform. Creates ?h.jacobian_dist0 (a
curv formatted file) and ?h.sphere.dist0.jacobian.reg (a surface file). This
step is not run automatically because it can add about an hour per hemi.
Note: the file ?h.jacobian_white (see prior help text) is the Jacobian of
the white surface to spherical atlas alignment from -surfreg.

Contralateral Surface Registation (Spherical Morph) (-<no>contrasurfreg)

Same as ipsilateral but registers to the contralateral atlas.
Creates lh.rh.sphere.reg and rh.lh.sphere.reg.

Average Curvature (-<no>avgcurv)

Resamples the average curvature from the atlas to that of the subject.
Allows the user to display activity on the surface of an individual
with the folding pattern (ie, anatomy) of a group. Calls mrisp_paint.
Creates surf/?h.avg_curv.

Cortical Parcellation (-<no>cortparc, -<no>cortparc2, -<no>cortparc3 )

Assigns a neuroanatomical label to each location on the cortical surface.
Incorporates both geometric information derived from the cortical model
(sulcus and curvature), and neuroanatomical convention.
Calls mris_ca_label.  -cortparc creates label/?h.aparc.annot,
-cortparc2 creates /label/?h.aparc.a2009s.annot, and
-cortparc3 creates /label/?h.aparc.DKTatlas40.annot.

Pial Surface (-<no>pial)

Creates the ?h.pial surfaces as well as the thickness file (?h.thickness).
The pial surface is created by expanding the white surface so that it closely
follows the gray-CSF intensity gradient as found in the T1 volume.  The
cortical parcellation is also used to refine the surface in certain areas.
Calls mris_make_surfaces.  See also "Final Surfaces".

Final Surfaces (-<no>finalsurfs)

!!! DEPRECATED !!! This flag is intended to emulate the old-style single-run
mris_make_surfaces, where the white and pial surfaces are created at the same
time without aid from the cortical parcellation data.

WM/GM Contrast (-<no>pctsurfcon)

Computes the vertex-by-vertex percent contrast between white and gray matter.
The computation is:

         100*(W-G)
   pct = ---------
         0.5*(W+G)

The white matter is sampled 1mm below the white surface. The gray matter is
sampled 30% the thickness into the cortex. The volume that is sampled is
rawavg.mgz.  The output is stored in the surf dir of the given subject as
?h.w-g.pct.mgh.  Non-cortical regions (medial wall) are zeroed.
A stats file named ?h.w-g.pct.stats is also computed.

Surface Volume (-surfvolume)

Creates the ?h.volume file by first creating the ?h.mid.area file by
adding ?h.area(.white) to ?h.area.pial, then dividing by two.  Then
?h.volume is created by multiplying ?.mid.area with ?h.thickness.
This step is also run at the end of the -pial step.

Cortical Ribbon Mask (-<no>cortribbon)

Creates binary volume masks of the cortical ribbon, ie, each voxel is
either a 1 or 0 depending upon whether it falls in the ribbon or not.
Saved as ?h.ribbon.mgz.  Uses mgz regardless of whether the -mgz
option is used.

Parcellation Statistics (-<no>parcstats, -<no>parcstats2, -<no>parcstats3)

Runs mris_anatomical_stats to create a summary table of cortical
parcellation statistics for each structure, including 1. structure
name 2. number of vertices 3. total wm surface area (mm^2) 4. total gray
matter volume (mm^3) 5. average cortical thickness (mm) 6. standard
error of cortical thickness (mm) 7. integrated rectified mean wm
curvature 8. integrated rectified Gaussian wm curvature 9. folding index
10. intrinsic curvature index.
For -parcstats, the file is saved in stats/?h.aparc.stats.
For -parcstats2, the file is saved in stats/?h.aparc.${DESTRIEUX_NAME}.stats.
For -parcstats3, the file is saved in stats/?h.aparc.${DKTATLAS_NAME}.stats.

Curvature Statistics  (-<no>curvstats)

Runs mris_curvature_stats to create a summary file (stats/?h.curv.stats)
of cortical curvature statistics.

LONGITUDINAL PROCESSING

The longitudinal processing scheme aims to incorporate the subject-wise
correlation of longitudinal data into the processing stream in order to
increase sensitivity and repeatability, see [14-16]. Care is taken to
avoid introduction of asymmetry-induced bias.

Here is a summary of the longitudinal workflow, where tpN refers to the
name of one timepoint of subject data, and longbase refers to the name
given to the base subject of a collection of timepoints:

1) cross-sectionally process tpN subjects (the default workflow):
  recon-all -s tp1 -i path_to_tp1_dicom -all
  recon-all -s tp2 -i path_to_tp2_dicom -all

2) create and process the unbiased base (subject template):
  recon-all -base longbase -tp tp1 -tp tp2 -all

3) longitudinally process tpN subjects:
  recon-all -long tp1 longbase -all
  recon-all -long tp2 longbase -all

4) do comparisons on results from 3), e.g. calculate differences
between tp2.long.longbase - tp1.long.longbase

Note that the longitudinal processing stream always produces output subject
data containing  .long.  in the name (to help distinguish from the default
stream).

Notice that the -all flag is included in the -base and -long calls above.
A work directive flag is required.

Other flags:

-uselongbasectrlvol

With -long: Switch on use of control-points from the base in the long
runs for intensity normalization (T1.mgz).

-uselongbasewmedits

With -long: Optionally transfer WM edits from base/template.
Default: map WM edits from corresponding cross run.

-no-orig-pial

If the orig pial surface data is not available, then specify this flag so that
mris_make_surfaces does not attempt to use it.

-noasegfusion

Do not create 'fused' aseg from the longbase timepoints, which would normally
be used to initialize the ca_labeling.  Instead, initialize using the longbase
aseg.mgz.

-addtp

If a new timepoint needs to be added to a longitudinal run where a base subject
has already been created (from prior timepoints), then the -addtp command
can be added to the -long command in order to 'fix-up' the longitudinal
stream to accept the new timepoint. Note that the base subject is *not*
recomputed using the new timepoint. This potentially introduces a bias, and it
is recommended to NOT add a time point this way! Instead recreate the base
from all time points and run all longitudinals again.
See the LongitudinalProcessing wiki page.

Example:

  recon-all -long <tpNsubjid> <longbasesubjid> -addtp -all

In this example, 'tnNsubjid' is the subject name (assumed processed in the
cross-sectional stream) to add as a new timepoint and upon which to run
the longitudinal stream (creating <tpNsubjid>.long.<longbasesubjid>).



USING IMAGES FROM A 3T SCANNER 

The -3T flag enables two specific options in recon-all for images acquired with
a 3T scanner:  3T-specific NU intensity correction parameters are used in the 
Non-Uniform normalization stage, and the Schwartz 3T atlas is used for 
Talairach alignment.


T2 OR FLAIR TO IMPROVE PIAL SURFACES

Pial surfaces can be improved using the different contrast in T2 or FLAIR
images. The original pial surfaces without T2/FLAIR data are saved as  
?h.woT2.pial or ?h.woFLAIR.pial, and new ?h.pial surfaces are created.  One 
example where this is useful is when there is dura in the brainmask.mgz that 
isn't removed by skull stripping. The flags for these commands are:

  -T2 <input T2 volume>  or -FLAIR <input FLAIR volume> 
    (Specify the  path to the T2 or FLAIR image to use)
  -T2pial or -FLAIRpial 
    (Create new pial surfaces using T2 or FLAIR images)

An example of running a subject through Freesurfer with a T2 image is:
  
  recon-all -s subjectname -i /path/to/input -T2 /path/to/T2_input -T2pial -all

T2 or FLAIR images can also be used with Freesurfer subjects that have already
been processed without them. Note that autorecon3 should also be re-ran to 
compute statistics based on the new surfaces. For example:
  
  recon-all -s subjectname -T2 /path/to/T2_volume -T2pial -autorecon3


MANUAL CHECKING AND EDITING OF SURFACES

To manually edit segmenation, run the following command (make sure
that your SUBJECTS_DIR environment variable is properly set).

  tkmedit subjid wm.mgz -aux T1.mgz

The surfaces can be loaded through the menu item
File->LoadMainSurface. To enable editing, set Tools->EditVoxels.  It
may also be convenient to bring up the reconstruction toolbar with
View->ToolBars->Reconstruction. Alt-C toggles between the main (wm)
and auxiliary (T1) volumes. Middle clicking will set a voxel value to
255; left clicking will set a voxel value to 0. Only edit the wm
volume. When finished, File->SaveMainVolume.

To view the inflated surface simultaneosly with the volume, run the
following command from a different shell:

  tksurfer subjid lh inflated

To goto a point on the surface inside the volume, click on the point
and hit SavePoint (icon looks like a floppy disk), then, in tkmedit,
hit GotoSavedPoint (icon looks like an open file).

Be sure to see the tutorials found at:
https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial


TOUCH FILES

This script creates a directory called "touch". Each time a stage is
run a "touch file" is created (eg, skull_strip.touch). This will be
used in the future to automatically determine which stages need to be
run or re-run. The modification time of the touch file is important.
The content is irrelevent, though it often contains a command-line.


FLATTENING

Flattening is not actually done in this script. This part just documents
how one would go about performing the flattening. First, load the subject
surface into tksurfer:

  tksurfer subjid lh inflated

Load the curvature through the File->Curvature->Load menu (load
lh.curv). This should show a green/red curvature pattern. Red = sulci.

Right click before making a cut; this will clear previous points. This
is needed because it will string together all the previous places you
have clicked to make the cut. To make a line cut, left click on a line
of points. Make the points fairly close together; if they are too far
appart, the cut fails. After making your line of points, execute the
cut by clicking on the Cut icon (scissors with an open triangle for a
line cut or scissors with a closed triangle for a closed cut). To make
a plane cut, left click on three points to define the plane, then left
click on the side to keep. Then hit the CutPlane icon.

Fill the patch. Left click in the part of the surface that you want to
form your patch. Then hit the Fill Uncut Area button (icon = filled
triangle). This will fill the patch with white. The non-patch area
will be unaccessible through the interface.  Save the patch through
File->Patch->SaveAs. For whole cortex, save it to something like
lh.cort.patch.3d. For occipital patches, save it to lh.occip.patch.3d.

Cd into the subject surf directory and run

  mris_flatten -w N -distances Size Radius lh.patch.3d lh.patch.flat

where N instructs mris_flatten to write out an intermediate surface
every N interations. This is only useful for making movies; otherwise
set N=0.  Size is maximum number of neighbors; Radius radius (mm) in
which to search for neighbors. In general, the more neighbors that are
taken into account, the less the metric distortion but the more
computationally intensive. Typical values are Size=12 for large
patches, and Size=20 for small patches. Radius is typically 7.
Note: flattening may take 12-24 hours to complete. The patch can be
viewed at any time by loading the subjects inflated surface, then
loading the patch through File->Patch->LoadPatch...


GETTING HELP

See https://surfer.nmr.mgh.harvard.edu
Send email to freesurfer@nmr.mgh.harvard.edu


REFERENCES

See https://www.zotero.org/freesurfer

[1] Collins, DL, Neelin, P., Peters, TM, and Evans, AC. (1994)
Automatic 3D Inter-Subject Registration of MR Volumetric Data in
Standardized Talairach Space, Journal of Computer Assisted Tomography,
18(2) p192-205, 1994 PMID: 8126267; UI: 94172121

[2] Cortical Surface-Based Analysis I: Segmentation and Surface
Reconstruction Dale, A.M., Fischl, Bruce, Sereno, M.I.,
(1999). Cortical Surface-Based Analysis I: Segmentation and Surface
Reconstruction.  NeuroImage 9(2):179-194

[3] Fischl, B.R., Sereno, M.I.,Dale, A. M.  (1999) Cortical
Surface-Based Analysis II: Inflation, Flattening, and Surface-Based
Coordinate System. NeuroImage, 9, 195-207.

[4] Fischl, Bruce, Sereno, M.I., Tootell, R.B.H., and Dale, A.M.,
(1999). High-resolution inter-subject averaging and a coordinate
system for the cortical surface. Human Brain Mapping, 8(4): 272-284

[5] Fischl, Bruce, and Dale, A.M., (2000).  Measuring the Thickness of
the Human Cerebral Cortex from Magnetic Resonance Images.  Proceedings
of the National Academy of Sciences, 97:11044-11049.

[6] Fischl, Bruce, Liu, Arthur, and Dale, A.M., (2001). Automated
Manifold Surgery: Constructing Geometrically Accurate and
Topologically Correct Models of the Human Cerebral Cortex. IEEE
Transactions on Medical Imaging, 20(1):70-80

[7] Non-Uniform Intensity Correction.
http://www.nitrc.org/projects/nu_correct/

[8] Fischl B, Salat DH, Busa E, Albert M, Dieterich M, Haselgrove C,
van der Kouwe A, Killiany R, Kennedy D, Klaveness S, Montillo A,
Makris N, Rosen B, Dale AM. Whole brain segmentation: automated
labeling of neuroanatomical structures in the human
brain. Neuron. 2002 Jan 31;33(3):341-55.

[9] Bruce Fischl, Andre van der Kouwe, Christophe Destrieux, Eric
Halgren, Florent Segonne, David H. Salat, Evelina Busa, Larry
J. Seidman, Jill Goldstein, David Kennedy, Verne Caviness, Nikos
Makris, Bruce Rosen, and Anders M. Dale.  Automatically Parcellating
the Human Cerebral Cortex. Cerebral Cortex January 2004; 14:11-22.

[10] Fischl B, Salat DH, van der Kouwe AJW, Makris N, Ségonne F, Dale
AM. Sequence-Independent  Segmentation of Magnetic Resonance Images.
NeuroImage 23 Suppl 1, S69-84.

[11] Segonne F, Dale, AM, Busa E, Glessner M, Salvolini U, Hahn HK,
Fischl B, A Hybrid Approach to the Skull-Stripping Problem in MRI.
NeuroImage, 22,  pp. 1160-1075, 2004

[12] Han et al.,  Reliability of MRI-derived measurements of human
cerebral cortical thickness: The effects of field strength, scanner
upgrade and manufacturer, (2006) NeuroImage, 32(1):180-194.

[13] Schaer et al., A Surface-based Approach to Quantify Local Cortical
Gyrification (2007) IEEE Transactions on Medical Imaging.

[14] Martin Reuter, H Diana Rosas, Bruce Fischl.
Highly Accurate Inverse Consistent Registration: A Robust Approach.
NeuroImage 53(4), 1181-1196, 2010. http://dx.doi.org/10.1016/j.neuroimage.2010.07.020

[15] Martin Reuter, Bruce Fischl.
Avoiding Asymmetry-Induced Bias in Longitudinal Image Processing.
NeuroImage 51(1), 19-21, 2011. http://dx.doi.org/10.1016/j.neuroimage.2011.02.076

[16] Martin Reuter, Nicholas J Schmansky, H Diana Rosas, Bruce Fischl.
Within-Subject Template Estimation for Unbiased Longitudinal Image Analysis.
NeuroImage 61(4), 1402-1418, 2012. http://dx.doi.org/10.1016/j.neuroimage.2012.02.084

[17] Iglesias, J.E., Augustinack, J.C., Nguyen, K., Player, C.M., Player, A., Wright,
M., Roy, N., Frosch, M.P., McKee, A.C., Wald, L.L., Fischl, B., and Van Leemput, K.,
A computational atlas of the hippocampal formation using ex vivo, ultra-high resolution
MRI: Application to adaptive segmentation of in vivo MRI.  Neuroimage 115, 2015, 117-137. 
http://dx.doi.org/10.1016/j.neuroimage.2015.04.042

[18] Iglesias, J.E., Van Leemput, K., Bhatt, P., Casillas, C., Dutt, S., Schuff, N.,
Truran-Sacrey, D., Boxer, A., and Fischl, B., Bayesian segmentation of brainstem 
structures in MRI. Neuroimage 113, 2015, 184-195.
http://dx.doi.org/10.1016/j.neuroimage.2015.02.065

[19] Saygin, Z.M. & Kliemann, D. (joint 1st authors), Iglesias, J.E., van der Kouwe, A.J.W.,
Boyd, E., Reuter, M., Stevens, A., Van Leemput, K., McKee, A., Frosch, M.P., Fischl, B.,
and Augustinack, J.C., High-resolution magnetic resonance imaging reveals nuclei of the 
human amygdala: manual segmentation to automatic atlas. Neuroimage 155, 2017, 370-382.
http://doi.org/10.1016/j.neuroimage.2017.04.046

[20] Iglesias, J.E., Van Leemput, K., Augustinack, J., Insausti, R., Fischl, B., 
and Reuter, M., Bayesian longitudinal segmentation of hippocampal substructures in brain MRI
using subject-specific atlases. Neuroimage 141, 2016, 542-555. 
http://doi.org/10.1016/j.neuroimage.2016.07.020




