#!/usr/bin/tcsh -f

#
# trac-all
#
# For when you need to look beneath the surface
#
# Original Author: Anastasia Yendiki
#
# Copyright © 2021 The General Hospital Corporation (Boston, MA) "MGH"
#
# Terms and conditions for use, reproduction, distribution and contribution
# are found in the 'FreeSurfer Software License Agreement' contained
# in the file 'LICENSE' found in the FreeSurfer distribution, and here:
#
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense
#
# Reporting: freesurfer@nmr.mgh.harvard.edu
#
#

umask 002

set VERSION = 'trac-all mockbuild-local';
set ProgName = `basename $0`
set inputargs = ($argv)

if ($?PBS_JOBID && `domainname` == nmr.mgh.harvard.edu) then
  echo "WARN: The intended usage of $ProgName is not to submit it as a job."
  echo "WARN: It is to be run directly on the command line."
  echo "WARN: If run on the cluster, $ProgName will submit the jobs for you."
  echo "WARN: Each subject listed in your dmrirc will be submitted as a job."
  echo "WARN: If run on a single node, it will run everything serially."
endif

set onpbs = 0
if (`where pbsubmit` != "") set onpbs = 1

setenv FSLOUTPUTTYPE NIFTI_GZ
setenv LANG en_US.UTF-8

#------------ Set default options -----------------------------------------#

set PrintHelp = 0	# Print help and exit
set DoVersionsOnly = 0	# Print versions and exit

set debug = 0		# Generate more output
set umaskid = ()	# Unix file permission mask
set groupid = ()	# Unix user group ID
set allowcore = 0	# Unlimit core dump size

set DoTime = 0		# Time main commands
set fs_time = ()

set submitfile = ()	# Name of file for writing jobs to be run in parallel

set logfile = ()	# Name of log file
set cmdfile = ()	# Name of command file
set AppendLog = 1	# Append to log file if it exists

set DoIsRunning = 1     # Create a lock file while processing continues

set RunIt = 1		# If 0, do everything but run commands (for debugging)

set DoCleanCSDF = 0	# If 1, ignore FREESURFER_HOME of previous processing

set dopreproc = 0	# Perform select processing steps
set dobedpost = 0
set dopaths = 0
set dostats = 0

set docorr = 0
set doqa = 0
set dointra = 0
set dotensor = 0
set dointer = 0
set dopriors = 0

set rcfile = ()		# Run command file

#------------ Parse input arguments and configuration file ----------------#

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
  echo $VERSION
  exit 0
endif

# Set defaults
set doinfant = 0
set dtroot = ()
set subjlist = ()
set runlist = ()
set dcmroot = ()
set dcmlist = ()
set bveclist = ()
set bvecfile = ()
set bvallist = ()
set bvalfile = ()
set bmax = ()
set bshell = ()
set nb0 = ()
set dob0 = 0
set b0mlist = ()
set b0plist = ()
set echospacing = ()
set epifactor = ()
set pedir = ()
set dTE = ()
set doeddy = 2
set dorotbvecs = 1
set intrareg = ()
set intracost = ()
set intradof = ()
set intrarot = ()
set interreg = ()
set intercost = ()
set intertrg = ()
set segname = aparc+aseg
set gmgrow = ()
set usethalnuc = ()
set usemaskanat = 1
set thrbet = 0.3
set baselist = ()
set pathfile = ()
set pathlist = ()
set gmids = ()
set ncpts = ()
set trainfile = ()
set trainsubjlist = ()
set ntrainlist = ()
set avgname = ()
set reinit = 0
set usetrunc = 1
set do1out = 0
set doxyzprior = 0
set dosegprior = 1
set dotangprior = 0
set dopathsubdirs = 0
set nstick = 2
set fmin = 0.05
set nburnin = 200
set nsample = ()
set nupdate = 0
set nkeep = 5
set doinitprop = 1
set pmin = ()
set projmin = -3
set projmax = 3
set dproj = .1
set overwrite = 1
set trcdir = $FREESURFER_HOME/bin

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:

# Source run command file
if ($#rcfile) then
  source $rcfile

  if ($status) then
    echo "ERROR: Syntax error in configuration file $rcfile"
    exit 1
  endif
endif

# Set defaults for registration (depending on adult or infant stream)
goto set_reg_defaults;
set_reg_defaults_return:

# Set defaults for pathway reconstruction (depending on adult or infant stream)
goto set_path_defaults;
set_path_defaults_return:

goto check_params;
check_params_return:

echo "INFO: SUBJECTS_DIR is $SUBJECTS_DIR"
echo "INFO: Diffusion root is $dtroot"

pushd $FREESURFER_HOME > /dev/null
set freesurfer_home_true = `pwd`;
popd > /dev/null
echo "Actual FREESURFER_HOME $freesurfer_home_true"

if ($onpbs) then
  set pbslogdir = `fs_temp_dir`
  if (! $#submitfile) set submitfile = $pbslogdir/submit.txt
endif

if ($#submitfile) then
  rm -f $submitfile

  set presubmitfile = `echo $submitfile | awk -v FS=\. \
    '{s=""; for (i=1;i<NF;i++) s=s$i"."; print s"pre."$NF}'`
  rm -f $presubmitfile

  set postsubmitfile = `echo $submitfile | awk -v FS=\. \
    '{s=""; for (i=1;i<NF;i++) s=s$i"."; print s"post."$NF}'`
  rm -f $postsubmitfile
endif

if ($#logfile) then
  if (-e $logfile && ! $AppendLog) mv -f $logfile $logfile.old
endif

if ($#cmdfile) then
  rm -f $cmdfile
endif

set cmdopts = ()
if ($DoTime) set cmdopts = ($cmdopts -time)
if (! $DoIsRunning) set cmdopts = ($cmdopts -no-isrunning)
if (! $RunIt) set cmdopts = ($cmdopts -dontrun)
if ($debug) set cmdopts = ($cmdopts -debug)
if ($#umaskid) set cmdopts = ($cmdopts -umask $umaskid)
if ($#groupid) set cmdopts = ($cmdopts -grp $groupid)
if ($allowcore) set cmdopts = ($cmdopts -allowcoredump)

# Select a subset of scans to process
set cmd = `printf "%dp;" $runlist`
set subjlist = `printf '%s\n' $subjlist | sed -n "$cmd"`
set dcmlist  = `printf '%s\n' $dcmlist  | sed -n "$cmd"`
if ($#bveclist) set bveclist = `printf '%s\n' $bveclist | sed -n "$cmd"`
if ($#bvallist) set bvallist = `printf '%s\n' $bvallist | sed -n "$cmd"`
if ($#b0mlist)  set b0mlist  = `printf '%s\n' $b0mlist  | sed -n "$cmd"`
if ($#b0plist)  set b0plist  = `printf '%s\n' $b0plist  | sed -n "$cmd"`
if ($#baselist) set baselist = `printf '%s\n' $baselist | sed -n "$cmd"`

# Find unique subject IDs
set subjids = `printf '%s\n' $subjlist | sort --unique`
if ($#baselist) set baseids = `printf '%s\n' $baselist | sort --unique`

#------------ Loop over subjects ------------------------------------------#
set subjdirs = ()
set basedirs = ()

if ($#baselist == 0) then	#--->>> A single time point for each subject
  foreach subj ($subjids)
    # Find this subject's scans
    set scanlist = `printf '%s\n' $subjlist \
                    | awk -v subj=$subj '{if ($1==subj) print NR}'`

    set cmd = `printf "%dp;" $scanlist`
    set my_dcmlist = `printf '%s\n' $dcmlist | sed -n "$cmd"`
    if ($#bveclist) set my_bveclist = `printf '%s\n' $bveclist | sed -n "$cmd"`
    if ($#bvallist) set my_bvallist = `printf '%s\n' $bvallist | sed -n "$cmd"`
    if ($#b0mlist)  set my_b0mlist  = `printf '%s\n' $b0mlist  | sed -n "$cmd"`
    if ($#b0plist)  set my_b0plist  = `printf '%s\n' $b0plist  | sed -n "$cmd"`
    if ($#echospacing > 1) \
      set my_echospacing  = `printf '%s\n' $echospacing  | sed -n "$cmd"`
    if ($#epifactor > 1) \
      set my_epifactor    = `printf '%s\n' $epifactor    | sed -n "$cmd"`
    if ($#pedir > 1) \
      set my_pedir        = `printf '%s\n' $pedir        | sed -n "$cmd"`
    if ($#dTE > 1) \
      set my_dTE          = `printf '%s\n' $dTE          | sed -n "$cmd"`

    if (-e $trainfile) then
      if ($do1out) then
        foreach k (`awk '{print NR}' $trainfile`)
          set slist = `sed -n "$k p" $trainfile`

          if (`basename $slist[1]` == $subj) then
            set dtroot = `dirname $slist[1]`
            shift slist
            set trainsubjlist = ($slist)
          endif
        end
      else
        set trainsubjlist = `cat $trainfile`
      endif
    endif

    set dtdir = $dtroot/$subj

    set subjdirs = ($subjdirs $dtdir)

    if ($dostats) continue

    # Check FreeSurfer directory
    if (($dointra || $dointer) && ! $do1out) then
      set fsdir = $SUBJECTS_DIR/$subj

      if (! -e $fsdir) then
        echo "ERROR: cannot find $fsdir"
        exit 1
      endif

      if (! -r $fsdir) then
        echo "ERROR: $fsdir exists but is unreadable"
        exit 1
      endif
    endif

    mkdir -p $dtdir/scripts

    # Check diffusion directory
    if (! -w $dtdir) then
      echo "ERROR: cannot write in $dtdir"
      exit 1
    endif

    #---------- Check build stamp -------------------------------------------#
    # This allows the user to require that the build stamp be
    # consistent from one trac-all/recon-all invocation to the next.
    # Good for frozen versions.

    if ($?REQUIRE_FS_MATCH == 0) setenv REQUIRE_FS_MATCH 0

    set bstampfile0 = $FREESURFER_HOME/build-stamp.txt
    set bstampfile  = $dtdir/scripts/build-stamp.txt

    if (-e $bstampfile0) then
      if (! -e $bstampfile) cp $bstampfile0 $bstampfile

      set bstamp0 = `cat $bstampfile0`
      set bstamp  = `cat $bstampfile`

      if ("$bstamp0" != "$bstamp") then
        if ($REQUIRE_FS_MATCH) then
          echo "ERROR: FreeSurfer build stamps do not match"
          echo "Subject Stamp: $bstamp"
          echo "Current Stamp: $bstamp0"
          exit 1;
        else
          echo "INFO: FreeSurfer build stamps do not match"
          echo "Subject Stamp: $bstamp"
          echo "Current Stamp: $bstamp0"
        endif
      endif
    endif

    #---------- Create log and command files --------------------------------#

    if ($DoVersionsOnly) then
      if (-e /dev/stdout) then
        set LF = /dev/stdout
      else
        set LF = /dev/null
      endif
    else
      if ($#logfile) then
        if (`basename $logfile` == $logfile) then
          set LF = $dtdir/scripts/$logfile
          if (-e $LF && ! $AppendLog) mv -f $LF $LF.old
        else
          set LF = $logfile
        endif
      else
        set LF = $dtdir/scripts/trac-all.log
        if (-e $LF && ! $AppendLog) mv -f $LF $LF.old
      endif

      if ($#cmdfile) then
        if (`basename $cmdfile` == $cmdfile) then
          set CF = $dtdir/scripts/$cmdfile
          rm -f $CF
        else
          set CF = $cmdfile
        endif
      else
        set CF = ($dtdir/scripts/trac-all.cmd)
        rm -f $CF
      endif
    endif

    if (-e $LF) then
      printf '\n\n' >> $LF
      echo "New invocation of $ProgName"  >> $LF
      printf '\n\n' >> $LF
    endif
  
    date >> $LF
    pwd >> $LF
    echo $0 >> $LF
    echo $inputargs >> $LF
    echo "Subject $subj" >> $LF
    echo "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
    whoami >> $LF
    hostname >> $LF
    uname -a >> $LF
    limit >> $LF
    if (-e /usr/bin/free) then
      echo "" >> $LF
      /usr/bin/free >> $LF
      echo "" >> $LF
    endif
    if ("`uname -s`" == "Darwin") then
      echo "" >> $LF
      /usr/bin/top -l 1 | grep PhysMem >> $LF
      echo "" >> $LF
    endif

    echo "########################################" >> $LF
    echo "Program versions:"		>> $LF
    echo $VERSION               	>> $LF
    mri_convert --all-info		>> $LF
    flirt -version			>> $LF
    bbregister --version		>> $LF
    mri_cvs_register --version		>> $LF
    $trcdir/dmri_motion --all-info	>> $LF
    $trcdir/dmri_train --all-info	>> $LF
    $trcdir/dmri_paths --all-info	>> $LF
    $trcdir/dmri_pathstats --all-info	>> $LF
    $trcdir/dmri_mergepaths --all-info	>> $LF
    $trcdir/dmri_group --all-info	>> $LF

    if ($DoVersionsOnly) continue

    #---------- Check FREESURFER_HOME consistency ---------------------------#

    set CSDF = $dtdir/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
    else
      echo $FREESURFER_HOME > $CSDF
    endif

    # Put a copy of myself (this script) in the scripts dir
    cp $0 $dtdir/scripts/$ProgName.local-copy

    # Write all parameters to local copy of dmrirc
    set RCF = $dtdir/scripts/dmrirc.local
    if (-e $RCF) mv -f $RCF $RCF.orig

    echo "# Run command file generated automatically by $ProgName" 	>> $RCF
    echo "#"							 	>> $RCF
    echo "setenv FREESURFER_HOME $FREESURFER_HOME"			>> $RCF
    echo "setenv SUBJECTS_DIR $SUBJECTS_DIR"				>> $RCF
    echo "set dtroot = ($dtroot)"					>> $RCF
    echo "set subj = ($subj)"						>> $RCF
    echo "#"							 	>> $RCF
    echo "# Processing steps to be performed"			 	>> $RCF
    echo "#"							 	>> $RCF
    echo "set docorr = ($docorr)"					>> $RCF
    echo "set doqa = ($doqa)"						>> $RCF
    echo "set dointra = ($dointra)"					>> $RCF
    echo "set dotensor = ($dotensor)"					>> $RCF
    echo "set dointer = ($dointer)"					>> $RCF
    echo "set dopriors = ($dopriors)"					>> $RCF
    echo "#"							 	>> $RCF
    echo "# Options for image corrections and tensor fit"	 	>> $RCF
    echo "#"							 	>> $RCF
    echo "set dcmroot = ($dcmroot)"					>> $RCF
    echo "set dcmfile = ($my_dcmlist)"					>> $RCF
    if ($#bveclist) then
      echo "set bvecfile = ($my_bveclist)"				>> $RCF
    else
      echo "set bvecfile = ($bvecfile)"					>> $RCF
    endif
    if ($#bvallist) then
      echo "set bvalfile = ($my_bvallist)"				>> $RCF
    else
      echo "set bvalfile = ($bvalfile)"					>> $RCF
    endif
    echo "set bmax = ($bmax)"						>> $RCF
    echo "set bshell = ($bshell)"					>> $RCF
    echo "set nb0 = ($nb0)"						>> $RCF
    echo "set dob0 = ($dob0)"						>> $RCF
    if ($#b0mlist) then
      echo "set b0mfile = ($my_b0mlist)"				>> $RCF
    else
      echo "set b0mfile = ()"						>> $RCF
    endif
    if ($#b0plist) then
      echo "set b0pfile = ($my_b0plist)"				>> $RCF
    else
      echo "set b0pfile = ()"						>> $RCF
    endif
    if ($#echospacing > 1) then
      echo "set echospacing = ($my_echospacing)"			>> $RCF
    else
      echo "set echospacing = ($echospacing)"				>> $RCF
    endif
    if ($#epifactor > 1) then
      echo "set epifactor = ($my_epifactor)"				>> $RCF
    else
      echo "set epifactor = ($epifactor)"				>> $RCF
    endif
    if ($#pedir > 1) then
      echo "set pedir = ($my_pedir)"					>> $RCF
    else
      echo "set pedir = ($pedir)"					>> $RCF
    endif
    if ($#dTE > 1) then
      echo "set dTE = ($my_dTE)"					>> $RCF
    else
      echo "set dTE = ($dTE)"						>> $RCF
    endif
    echo "set doeddy = ($doeddy)"					>> $RCF
    echo "set dorotbvecs = ($dorotbvecs)"				>> $RCF
    echo "set thrbet = ($thrbet)"					>> $RCF
    echo "#"							 	>> $RCF
    echo "# Options for registrations"				 	>> $RCF
    echo "#"							 	>> $RCF
    echo "set intrareg = ($intrareg)"					>> $RCF
    echo "set intracost = ($intracost)"					>> $RCF
    echo "set intradof = ($intradof)"					>> $RCF
    echo "set intrarot = ($intrarot)"					>> $RCF
    echo "set interreg = ($interreg)"					>> $RCF
    echo "set intercost = ($intercost)"					>> $RCF
    echo "set intertrg = ($intertrg)"					>> $RCF
    echo "#"							 	>> $RCF
    echo "# Options for anatomical segmentation"		 	>> $RCF
    echo "#"							 	>> $RCF
    echo "set segname = ($segname)"					>> $RCF
    echo "set gmgrow = ($gmgrow)"					>> $RCF
    echo "set usethalnuc = ($usethalnuc)"				>> $RCF
    echo "set usemaskanat = ($usemaskanat)"				>> $RCF
    echo "#"							 	>> $RCF
    echo "# Options for ball-and-stick model fit"		 	>> $RCF
    echo "#"							 	>> $RCF
    echo "set nstick = ($nstick)"					>> $RCF
    echo "#"							 	>> $RCF
    echo "# Options for path reconstructions"				>> $RCF
    echo "#"							 	>> $RCF
    echo "set pathlist = ($pathlist)"					>> $RCF
    echo "set gmids = ($gmids)"						>> $RCF
    echo "set ncpts = ($ncpts)"						>> $RCF
    echo "set trainsubjlist = ($trainsubjlist)"				>> $RCF
    echo "set ntrainlist = ($ntrainlist)"				>> $RCF
    echo "set avgname = ($avgname)"					>> $RCF
    echo "set reinit = ($reinit)"					>> $RCF
    echo "set usetrunc = ($usetrunc)"					>> $RCF
    echo "set doxyzprior = ($doxyzprior)"				>> $RCF
    echo "set dosegprior = ($dosegprior)"				>> $RCF
    echo "set dotangprior = ($dotangprior)"				>> $RCF
    echo "set dopathsubdirs = ($dopathsubdirs)"				>> $RCF
    echo "set fmin = ($fmin)"						>> $RCF
    echo "set nburnin = ($nburnin)"					>> $RCF
    echo "set nsample = ($nsample)"					>> $RCF
    echo "set nupdate = ($nupdate)"					>> $RCF
    echo "set nkeep = ($nkeep)"						>> $RCF
    echo "set doinitprop = ($doinitprop)"				>> $RCF
    echo "set pmin = ($pmin)"						>> $RCF
    echo "set projmin = ($projmin)"					>> $RCF
    echo "set projmax = ($projmax)"					>> $RCF
    echo "set dproj = ($dproj)"						>> $RCF
    echo "set overwrite = ($overwrite)"					>> $RCF
    echo "#"							 	>> $RCF
    echo "# Location of TRACULA executables"			 	>> $RCF
    echo "#"							 	>> $RCF
    echo "set trcdir = ($trcdir)"					>> $RCF

    if ($dopreproc) then	# Pre-processing #############
      set cmd = trac-preproc
      set cmd = ($cmd -c $RCF)
      set cmd = ($cmd -log $LF)
      set cmd = ($cmd -cmd $CF)
      set cmd = ($cmd $cmdopts)
      if ($#submitfile) then
        echo $cmd >> $submitfile
      else
        echo $cmd
        $cmd
        if ($status) exit 1
      endif
    else if ($dobedpost) then	# Bedpost ####################
      # Create symbolic link to brain mask with the name that bedpostx expects
      if ($usemaskanat) then
        set bedmask = ../dlabel/diff/${segname}_mask.$reg.nii.gz
      else
        set bedmask = ../dlabel/diff/lowb_brain_mask.nii.gz
      endif

      set cmd = (ln -sf $bedmask $dtdir/dmri/nodif_brain_mask.nii.gz)
      echo $cmd |& tee -a $LF |& tee -a $CF
      if ($RunIt) then
        $cmd |& tee -a $LF
        if ($status) exit 1
      endif

      if (! $onpbs) then
        if ($#submitfile) then
          set cmd =  (bedpostx_preproc.sh $dtdir/dmri 0)
          echo $cmd >> $presubmitfile
          set nslice = `mri_info --nslices $dtdir/dmri/lowb.nii.gz`
          @ islice = 0
          while ($islice < $nslice)
            set cmd = (bedpostx_single_slice.sh $dtdir/dmri)
            set cmd = ($cmd $islice --nf=$nstick --fudge=1 --bi=1000)
            set cmd = ($cmd --nj=1250 --se=25 --model=1 --cnonlinear)
            echo $cmd >> $submitfile
            @ islice = $islice + 1
          end
          set cmd = (bedpostx_postproc.sh $dtdir/dmri)
          echo $cmd >> $postsubmitfile
        else
          echo "WARN: Running bedbostx locally - this might take a while" \
            |& tee -a $LF
          echo "WARN: It is recommended to run this step on a cluster" \
            |& tee -a $LF
          set cmd = (bedpostx_mgh -n $nstick -model 1 $dtdir/dmri)
          echo $cmd |& tee -a $LF |& tee -a $CF
          if ($RunIt) then
            $cmd |& tee -a $LF
            if ($status) exit 1
          endif
        endif
      endif
    else if ($dopaths) then	# Path reconstruction ########
      set cmd = trac-paths
      set cmd = ($cmd -c $RCF)
      set cmd = ($cmd -log $LF)
      set cmd = ($cmd -cmd $CF)
      set cmd = ($cmd $cmdopts)
      if ($#submitfile) then
        echo $cmd >> $submitfile
      else
        echo $cmd
        $cmd
        if ($status) exit 1
      endif
    endif
  end
else				#--->>> Multiple time points for each subject
  # Loop over base subjects
  foreach bsubj ($baseids)
    # Find this subject's time points
    set scanlist = `printf '%s\n' $baselist \
                    | awk -v base=$bsubj '{if ($1==base) print NR}'`

    set cmd = `printf "%dp;" $scanlist`
    set tplist = `printf '%s\n' $subjlist | sed -n "$cmd" | sort --unique`
    set tplist = `printf "%s.long.$bsubj " $tplist`

    if (-e $trainfile) then
      if ($do1out) then
        foreach k (`awk '{print NR}' $trainfile`)
          set slist = `sed -n "$k p" $trainfile`

          if (`basename $slist[1]` == $bsubj) then
            set dtroot = `dirname $slist[1]`
            shift slist
            set trainsubjlist = ($slist)
          endif
        end
      else
        set trainsubjlist = `cat $trainfile`
      endif
    endif

    set dtdir = $dtroot/$bsubj

    # Depending on which step of the analysis I am performing,
    # I may need to process the time points, the base, or all of the above
    set proclist = ()

    if ($dopreproc) then
      set proclist = ($tplist $bsubj)
    else if ($dobedpost || $dostats) then
      set proclist = ($tplist)
    else if ($dopaths) then
      set proclist = ($bsubj)
    endif

    set LFlist = ()
    set CFlist = ()
    set RCFlist = ()

    @ iproc = 1
    while ($iproc <= $#proclist)
      set subj = $proclist[$iproc]

      set dtdir = $dtroot/$subj

      if ($subj != $bsubj) then
        # Find this time point's scans
        set scanlist = `printf '%s\n' $subjlist \
                        | awk -v subj=$subj -v bsubj=$bsubj \
                              '{if ($1".long."bsubj == subj) print NR}'`

        set cmd = `printf "%dp;" $scanlist`
        set my_dcmlist = `printf '%s\n' $dcmlist | sed -n "$cmd"`
        if ($#bveclist) \
          set my_bveclist     = `printf '%s\n' $bveclist     | sed -n "$cmd"`
        if ($#bvallist) \
          set my_bvallist     = `printf '%s\n' $bvallist     | sed -n "$cmd"`
        if ($#b0mlist)  \
          set my_b0mlist      = `printf '%s\n' $b0mlist      | sed -n "$cmd"`
        if ($#b0plist)  \
          set my_b0plist      = `printf '%s\n' $b0plist      | sed -n "$cmd"`
        if ($#echospacing > 1) \
          set my_echospacing  = `printf '%s\n' $echospacing  | sed -n "$cmd"`
        if ($#epifactor > 1) \
          set my_epifactor    = `printf '%s\n' $epifactor    | sed -n "$cmd"`
        if ($#pedir > 1) \
          set my_pedir        = `printf '%s\n' $pedir        | sed -n "$cmd"`
        if ($#dTE > 1) \
          set my_dTE          = `printf '%s\n' $dTE          | sed -n "$cmd"`

        set subjdirs = ($subjdirs $dtdir)
        set basedirs = ($basedirs $dtroot/$bsubj)
      endif

      if ($dostats) then
        @ iproc = $iproc + 1
        continue
      endif

      if (($dointra || $dointer) && ! $do1out) then
        # Check FreeSurfer directory
        set fsdir = $SUBJECTS_DIR/$subj

        if (! -e $fsdir) then
          echo "ERROR: cannot find $fsdir"
          exit 1
        endif

        if (! -r $fsdir) then
          echo "ERROR: $fsdir exists but is unreadable"
          exit 1
        endif
      endif

      mkdir -p $dtdir/scripts

      # Check diffusion directory
      if (! -w $dtdir) then
        echo "ERROR: cannot write in $dtdir"
        exit 1
      endif

      #---------- Check build stamp -------------------------------------------#
      # This allows the user to require that the build stamp be
      # consistent from one trac-all/recon-all invocation to the next.
      # Good for frozen versions.

      if ($?REQUIRE_FS_MATCH == 0) setenv REQUIRE_FS_MATCH 0

      set bstampfile0 = $FREESURFER_HOME/build-stamp.txt
      set bstampfile  = $dtdir/scripts/build-stamp.txt

      if (-e $bstampfile0) then
        if (! -e $bstampfile) cp $bstampfile0 $bstampfile

        set bstamp0 = `cat $bstampfile0`
        set bstamp  = `cat $bstampfile`

        if ("$bstamp0" != "$bstamp") then
          if ($REQUIRE_FS_MATCH) then
            echo "ERROR: FreeSurfer build stamps do not match"
            echo "Subject Stamp: $bstamp"
            echo "Current Stamp: $bstamp0"
            exit 1;
          else
            echo "INFO: FreeSurfer build stamps do not match"
            echo "Subject Stamp: $bstamp"
            echo "Current Stamp: $bstamp0"
          endif
        endif
      endif

      #---------- Create log and command files --------------------------------#

      if ($DoVersionsOnly) then
        if (-e /dev/stdout) then
          set LF = /dev/stdout
        else
          set LF = /dev/null
        endif
      else
        if ($#logfile) then
          if (`basename $logfile` == $logfile) then
            set LF = $dtdir/scripts/$logfile
            if (-e $LF && ! $AppendLog) mv -f $LF $LF.old
          else
            set LF = $logfile
          endif
        else
          set LF = ($dtdir/scripts/trac-all.log)
          if (-e $LF && ! $AppendLog) mv -f $LF $LF.old
        endif

        if ($#cmdfile) then
          if (`basename $cmdfile` == $cmdfile) then
            set CF = $dtdir/scripts/$cmdfile
            rm -f $CF
          else
            set CF = $cmdfile
          endif
        else
          set CF = ($dtdir/scripts/trac-all.cmd)
          rm -f $CF
        endif
      endif

      if (-e $LF) then
        printf '\n\n' >> $LF
        echo "New invocation of $ProgName"  >> $LF
        printf '\n\n' >> $LF
      endif
  
      date >> $LF
      pwd >> $LF
      echo $0 >> $LF
      echo $inputargs >> $LF
      echo "Subject $subj" >> $LF
      echo "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
      whoami >> $LF
      hostname >> $LF
      uname -a >> $LF
      limit >> $LF
      if (-e /usr/bin/free) then
        echo "" >> $LF
        /usr/bin/free >> $LF
        echo "" >> $LF
      endif
      if ("`uname -s`" == "Darwin") then
        echo "" >> $LF
        /usr/bin/top -l 1 | grep PhysMem >> $LF
        echo "" >> $LF
      endif

      echo "########################################" >> $LF
      echo "Program versions:"			>> $LF
      echo $VERSION               		>> $LF
      mri_convert --all-info			>> $LF
      flirt -version				>> $LF
      bbregister --version			>> $LF
      mri_cvs_register --version		>> $LF
      $trcdir/dmri_train --all-info		>> $LF
      $trcdir/dmri_paths --all-info		>> $LF
      $trcdir/dmri_pathstats --all-info		>> $LF
      $trcdir/dmri_mergepaths --all-info	>> $LF
      $trcdir/dmri_group --all-info		>> $LF

      if ($DoVersionsOnly) continue

      #---------- Check FREESURFER_HOME consistency ---------------------------#

      set CSDF = $dtdir/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
      else
        echo $FREESURFER_HOME > $CSDF
      endif

      # Put a copy of myself (this script) in the scripts dir
      cp $0 $dtdir/scripts/$ProgName.local-copy

      # Write all parameters to local copy of dmrirc
      set RCF = $dtdir/scripts/dmrirc.local
      if (-e $RCF) mv -f $RCF $RCF.orig

      echo "# Run command file generated automatically by $ProgName" 	>> $RCF
      echo "#"							 	>> $RCF
      if ($subj == $bsubj) then
        echo "# This is a base template for longitudinal tractography"	>> $RCF
        echo "set tplist = ($tplist)"					>> $RCF
      else
        echo "# This is a time point for longitudinal tractography"	>> $RCF
      endif
      echo "#"							 	>> $RCF
      echo "setenv FREESURFER_HOME $FREESURFER_HOME"			>> $RCF
      echo "setenv SUBJECTS_DIR $SUBJECTS_DIR"				>> $RCF
      echo "set dtroot = ($dtroot)"					>> $RCF
      echo "set subj = ($subj)"						>> $RCF
      echo "#"							 	>> $RCF
      echo "# Processing steps to be performed"			 	>> $RCF
      echo "#"							 	>> $RCF
      if ($subj == $bsubj) then
        echo "set docorr = (0)"						>> $RCF
        echo "set doqa = (0)"						>> $RCF
      else
        echo "set docorr = ($docorr)"					>> $RCF
        echo "set doqa = ($doqa)"					>> $RCF
      endif
      echo "set dointra = ($dointra)"					>> $RCF
      echo "set dointer = ($dointer)"					>> $RCF
      if ($subj == $bsubj) then
        echo "set dotensor = (0)"					>> $RCF
        echo "set dopriors = ($dopriors)"				>> $RCF
      else
        echo "set dotensor = ($dotensor)"				>> $RCF
        echo "set dopriors = (0)"					>> $RCF
      endif
      echo "#"							 	>> $RCF
      echo "# Options for image corrections and tensor fit"	 	>> $RCF
      echo "#"							 	>> $RCF
      echo "set dcmroot = ($dcmroot)"					>> $RCF
      if ($subj != $bsubj) then
        echo "set dcmfile = ($my_dcmlist)"				>> $RCF
      else
        echo "set dcmfile = ()"						>> $RCF
      endif
      if ($#bveclist && $subj != $bsubj) then
        echo "set bvecfile = ($my_bveclist)"				>> $RCF
      else
        echo "set bvecfile = ($bvecfile)"				>> $RCF
      endif
      if ($#bvallist && $subj != $bsubj) then
        echo "set bvalfile = ($my_bvallist)"				>> $RCF
      else
        echo "set bvalfile = ($bvalfile)"				>> $RCF
      endif
      echo "set bmax = ($bmax)"						>> $RCF
      echo "set bshell = ($bshell)"					>> $RCF
      echo "set nb0 = ($nb0)"						>> $RCF
      echo "set dob0 = ($dob0)"						>> $RCF
      if ($subj != $bsubj && $#b0mlist) then
        echo "set b0mfile = ($my_b0mlist)"				>> $RCF
      else
        echo "set b0mfile = ()"						>> $RCF
      endif
      if ($subj != $bsubj && $#b0plist) then
        echo "set b0pfile = ($my_b0plist)"				>> $RCF
      else
        echo "set b0pfile = ()"						>> $RCF
      endif
      if ($subj != $bsubj) then
        if ($#echospacing > 1) then
          echo "set echospacing = ($my_echospacing)"			>> $RCF
        else
          echo "set echospacing = ($echospacing)"			>> $RCF
        endif
        if ($#epifactor > 1) then
          echo "set epifactor = ($my_epifactor)"			>> $RCF
        else
          echo "set epifactor = ($epifactor)"				>> $RCF
        endif
        if ($#pedir > 1) then
          echo "set pedir = ($my_pedir)"				>> $RCF
        else
          echo "set pedir = ($pedir)"					>> $RCF
        endif
        if ($#dTE > 1) then
          echo "set dTE = ($my_dTE)"					>> $RCF
        else
          echo "set dTE = ($dTE)"					>> $RCF
        endif
      else
        echo "set echospacing = ()"					>> $RCF
        echo "set epifactor = ()"					>> $RCF
        echo "set pedir = ()"						>> $RCF
        echo "set dTE = ()"						>> $RCF
      endif
      echo "set doeddy = ($doeddy)"					>> $RCF
      echo "set dorotbvecs = ($dorotbvecs)"				>> $RCF
      echo "set thrbet = ($thrbet)"					>> $RCF
      echo "#"							 	>> $RCF
      echo "# Options for registrations"			 	>> $RCF
      echo "#"							 	>> $RCF
      echo "set intrareg = ($intrareg)"					>> $RCF
      echo "set intracost = ($intracost)"				>> $RCF
      echo "set intradof = ($intradof)"					>> $RCF
      echo "set intrarot = ($intrarot)"					>> $RCF
      echo "set interreg = ($interreg)"					>> $RCF
      echo "set intercost = ($intercost)"				>> $RCF
      echo "set intertrg = ($intertrg)"					>> $RCF
      echo "#"							 	>> $RCF
      echo "# Options for anatomical segmentation"		 	>> $RCF
      echo "#"							 	>> $RCF
      echo "set segname = ($segname)"					>> $RCF
      echo "set gmgrow = ($gmgrow)"					>> $RCF
      echo "set usethalnuc = ($usethalnuc)"				>> $RCF
      echo "set usemaskanat = ($usemaskanat)"				>> $RCF
      echo "#"							 	>> $RCF
      echo "# Options for ball-and-stick model fit"		 	>> $RCF
      echo "#"							 	>> $RCF
      echo "set nstick = ($nstick)"					>> $RCF
      echo "#"						 		>> $RCF
      echo "# Options for path reconstructions"				>> $RCF
      echo "#"							 	>> $RCF
      echo "set pathlist = ($pathlist)"					>> $RCF
      echo "set gmids = ($gmids)"					>> $RCF
      echo "set ncpts = ($ncpts)"					>> $RCF
      echo "set trainsubjlist = ($trainsubjlist)"			>> $RCF
      echo "set ntrainlist = ($ntrainlist)"				>> $RCF
      echo "set avgname = ($avgname)"					>> $RCF
      echo "set reinit = ($reinit)"					>> $RCF
      echo "set usetrunc = ($usetrunc)"					>> $RCF
      echo "set doxyzprior = ($doxyzprior)"				>> $RCF
      echo "set dosegprior = ($dosegprior)"				>> $RCF
      echo "set dotangprior = ($dotangprior)"				>> $RCF
      echo "set dopathsubdirs = ($dopathsubdirs)"			>> $RCF
      echo "set fmin = ($fmin)"						>> $RCF
      echo "set nburnin = ($nburnin)"					>> $RCF
      echo "set nsample = ($nsample)"					>> $RCF
      echo "set nupdate = ($nupdate)"					>> $RCF
      echo "set nkeep = ($nkeep)"					>> $RCF
      echo "set doinitprop = ($doinitprop)"				>> $RCF
      echo "set pmin = ($pmin)"						>> $RCF
      echo "set projmin = ($projmin)"					>> $RCF
      echo "set projmax = ($projmax)"					>> $RCF
      echo "set dproj = ($dproj)"					>> $RCF
      echo "set overwrite = ($overwrite)"				>> $RCF
      echo "#"							 	>> $RCF
      echo "# Location of TRACULA executables"			 	>> $RCF
      echo "#"							 	>> $RCF
      echo "set trcdir = ($trcdir)"					>> $RCF

      set LFlist  = ($LFlist $LF)
      set CFlist  = ($CFlist $CF)
      set RCFlist = ($RCFlist $RCF)

      @ iproc = $iproc + 1
    end

    if ($dopreproc) then	# Pre-processing #############
      set cmd = ()
      @ iproc = 1
      while ($iproc <= $#proclist)
        set cmd = ($cmd trac-preproc)
        set cmd = ($cmd -c $RCFlist[$iproc])
        set cmd = ($cmd -log $LFlist[$iproc])
        set cmd = ($cmd -cmd $CFlist[$iproc])
        set cmd = ($cmd $cmdopts;)
        @ iproc = $iproc + 1
      end
      if ($#submitfile) then
        echo $cmd >> $submitfile
      else
        echo $cmd
        /bin/tcsh -fc "$cmd"
        if ($status) exit 1
      endif
    else if ($dobedpost) then	# Bedpost ####################
      @ iproc = 1
      while ($iproc <= $#proclist)
        # Create symbolic link to brain mask with the name that bedpostx expects
        if ($usemaskanat) then
          set bedmask = ../dlabel/diff/${segname}_mask.$reg.nii.gz
        else
          set bedmask = ../dlabel/diff/lowb_brain_mask.nii.gz
        endif

        set cmd = (ln -sf $bedmask)
        set cmd = ($cmd   $dtroot/$proclist[$iproc]/dmri/nodif_brain_mask.nii.gz)
        echo $cmd |& tee -a $LF |& tee -a $CF
        if ($RunIt) then
          $cmd |& tee -a $LF
          if ($status) exit 1
        endif

        if (! $onpbs) then
          if ($#submitfile) then
            set cmd =  (bedpostx_preproc.sh $dtroot/$proclist[$iproc]/dmri 0)
            echo $cmd >> $presubmitfile
            set nslice = `mri_info --nslices \
                          $dtroot/$proclist[$iproc]/dmri/lowb.nii.gz`
            @ islice = 0
            while ($islice < $nslice)
              set cmd = (bedpostx_single_slice.sh $dtroot/$proclist[$iproc]/dmri)
              set cmd = ($cmd $islice --nf=$nstick --fudge=1 --bi=1000)
              set cmd = ($cmd --nj=1250 --se=25 --model=1 --cnonlinear)
              echo $cmd >> $submitfile
              @ islice = $islice + 1
            end
            set cmd = (bedpostx_postproc.sh $dtroot/$proclist[$iproc]/dmri)
            echo $cmd >> $postsubmitfile
          else
            echo "WARN: Running bedbostx locally - this might take a while" \
              |& tee -a $LFlist[$iproc]
            echo "WARN: It is recommended to run this step on a cluster" \
              |& tee -a $LFlist[$iproc]
            set cmd = (bedpostx_mgh -n $nstick -model 1 $dtroot/$proclist[$iproc]/dmri)
            echo $cmd |& tee -a $LFlist[$iproc] |& tee -a $CFlist[$iproc]
            if ($RunIt) then
              $cmd |& tee -a $LFlist[$iproc]
              if ($status) exit 1
            endif
          endif
        endif
        @ iproc = $iproc + 1
      end
    else if ($dopaths) then	# Path reconstruction ########
      set cmd = trac-paths
      set cmd = ($cmd -c $RCF)
      set cmd = ($cmd -log $LF)
      set cmd = ($cmd -cmd $CF)
      set cmd = ($cmd $cmdopts)
      if ($#submitfile) then
        echo $cmd >> $submitfile
      else
        echo $cmd
        /bin/tcsh -fc "$cmd"
        if ($status) exit 1
      endif
    endif
  end
endif

if ($dostats) then
  # Check root diffusion directory
  if (! -w $dtroot) then
    echo "ERROR: cannot write in $dtroot"
    exit 1
  endif

  if (! $#baselist) then
    set statdir = $dtroot/stats
  else
    set statdir = $dtroot/stats.long
  endif

  if ($RunIt) then
    mkdir -p $statdir
  endif

  if ($xspace == cvs) then
    set cvstemp = `dirname $intertrg`		# Assuming ../mri/norm.mgz
    set cvstemp = `dirname $cvstemp`
    set cvstemp = `basename $cvstemp`
    set cvswarp = final_CVSmorph_to$cvstemp
  endif

  foreach ntrain ($ntrainlist)
    set outdir = dpath

    if ($dopathsubdirs) then
      set outdir = $outdir/${nsample}samp

      set ptype = ()

      if ($dosegprior) then
        set ptype = seg14
      endif
      if ($dotangprior) then
        if ($#ptype) then
          set ptype = $ptype.tang
        else
          set ptype = tang
        endif
      endif
      if ($doxyzprior) then
        if ($#ptype) then
          set ptype = $ptype.xyz
        else
          set ptype = xyz
        endif
      endif
      if (! $#ptype) then
        set ptype = none
      endif

      set outdir = $outdir/$ptype
    endif

    set avgmode = $avgname${ntrain}_${xspace}_$reg

    foreach pathname ($pathlist)
      if ($RunIt) then
        rm -f $statdir/$pathname.$avgmode.inputs.txt

        @ k = 1
        while ($k <= $#subjdirs)
          set pathdir = $subjdirs[$k]/$outdir/${pathname}_$avgmode

          if (-e $pathdir/path.pd.nii.gz) then
            if (! $#baselist) then			# Cross-sectional
              set xfmdir = $subjdirs[$k]/dmri/xfms
              set labdir = $subjdirs[$k]/dlabel
              set refvol = $labdir/diff/${segname}_mask.$reg.nii.gz
            else					# Longitudinal
              set xfmdir = $basedirs[$k]/dmri/xfms
              set labdir = $basedirs[$k]/dlabel
              set refvol = $labdir/anatorig/${segname}_mask.nii.gz
            endif

            if (-e $pathdir/path.ref.txt) then		# No need to interpolate
              set inputs = ($pathdir)
            else
              set inputs = ($pathdir $refvol)

              if ($xspace == mni || $xspace == rob) then
                if (! $#baselist) then			# Cross-sectional
                  set inputs = ($inputs $xfmdir/diff2$xspace.$reg.lta)
                else					# Longitudinal
                  set inputs = ($inputs $xfmdir/anatorig2$xspace.lta)
                endif
              else if ($xspace == cvs) then
                if (! $#baselist) then			# Cross-sectional
                  set inputs = ($inputs $xfmdir/diff2anatorig.$reg.lta)
                  if (-e $xfmdir/cvs/$cvswarp.m3z) then
                    set inputs = ($inputs $xfmdir/cvs/$cvswarp.m3z)
                  endif
                else					# Longitudinal
                  if (-e $xfmdir/cvs/$cvswarp.m3z) then
                    set inputs = ($inputs $xfmdir/cvs/$cvswarp.m3z)
                  endif
                endif
              else if ($xspace == syn) then
                if (! $#baselist) then			# Cross-sectional
                  set inputs = ($inputs $xfmdir/diff2syn.lta)
                  set inputs = ($inputs $xfmdir/syn_warp.m3z)
                else					# Longitudinal
                  set inputs = ($inputs $xfmdir/anatorig2syn.$reg.lta)
                  set inputs = ($inputs $xfmdir/syn_warp.m3z)
                endif
              else if ($xspace == fnt) then
                if (! $#baselist) then			# Cross-sectional
                  set inputs = ($inputs $xfmdir/diff2fsl_warp.m3z)
                else					# Longitudinal
                  set inputs = ($inputs $xfmdir/anatorig2diff.$reg.lta)
                  set inputs = ($inputs $xfmdir/diff2fsl_warp.m3z)
                endif
              endif
            endif

            echo $inputs >> $statdir/$pathname.$avgmode.inputs.txt
          endif

          @ k = $k + 1
        end

        if (! -e $statdir/$pathname.$avgmode.inputs.txt) then
          echo "ERROR: no pathway reconstructions found"
          exit 1
        endif
      endif

      set cmd = $trcdir/dmri_group
      set cmd = ($cmd --list $statdir/$pathname.$avgmode.inputs.txt)
      set cmd = ($cmd --ref  $intertrg)
      set cmd = ($cmd --out  $statdir/$pathname.$avgmode)
      if ($#inputs == 1)	set cmd = ($cmd --nointerp)

      set LF = $statdir/$pathname.$avgmode.log

      if ($RunIt) then
        if ($#submitfile) then
          echo "$cmd |& tee -a $LF" >> $submitfile
        else
          echo $cmd
          $cmd |& tee -a $LF
          if ($status) exit 1
        endif
      endif
    end
  end
endif

if ($onpbs && $RunIt) then
  if (! $?MYPBSMAXJOBS) setenv MYPBSMAXJOBS 30

  if ($dopreproc) then
    if (! $?MYPBSWAIT) setenv MYPBSWAIT 30
    if ($xspace == cvs) setenv MYPBSARCH "ppn=4,vmem=28gb"
    echo Queueing pre-processing
    set preid = `fsl_sub_mgh -l $pbslogdir/log -m a -N trcpre -t $submitfile`
  else if ($dobedpost) then
    if (! $?MYPBSWAIT) setenv MYPBSWAIT 0
    bedpostx_mgh -n $nstick -model 1 `printf '%s/dmri ' $subjdirs`
  else if ($dopaths) then
    if (! $?MYPBSWAIT) setenv MYPBSWAIT 30
    if ($xspace == cvs) setenv MYPBSARCH "ppn=4,vmem=28gb"
    echo Queueing path reconstruction
    set trcid = `fsl_sub_mgh -l $pbslogdir/log -m a -N trc -t $submitfile`
  else if ($dostats) then
    if (! $?MYPBSWAIT) setenv MYPBSWAIT 30
    if ($xspace == cvs) setenv MYPBSARCH "ppn=4,vmem=28gb"
    echo Queueing group tables
    set grpid = `fsl_sub_mgh -l $pbslogdir/log -m a -N trcgrp -t $submitfile`
  endif
endif

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

exit 0
#############------------------------------------#######################
##################>>>>>>>>>>>>>.<<<<<<<<<<<<<<<<<#######################
#############------------------------------------#######################

############--------------##################
parse_args:
set cmdline = ($argv)

while( $#argv != 0 )
  set flag = $argv[1]; shift;

  switch($flag)
    case "-subject":
    case "-subjid":
    case "-sid":
    case "-s":
      if ($#argv < 1) goto arg1err;
      set subjlist = $argv[1]; shift;
      set subjlist = `basename $subjlist`	# to remove trailing /
      breaksw

    case "-i":
      if ($#argv < 1) goto arg1err;
      set dcmlist = "$argv[1]"; shift;
      if (! -e "$dcmlist") then
        echo "ERROR: cannot find $dcmlist"
        exit 1
      endif
      if (! -r "$dcmlist") then
        echo "ERROR: $dcmlist exists but is not readable"
        exit 1
      endif
      set dcmroot = `dirname  "$dcmlist"`
      set dcmlist = `basename "$dcmlist"`
      breaksw

    case "-c":
      if ($#argv < 1) goto arg1err;
      set rcfile = "$argv[1]"; shift;
      if (! -e "$rcfile") then
        echo "ERROR: cannot find $rcfile"
        exit 1
      endif
      if (! -r "$rcfile") then
        echo "ERROR: $rcfile exists but is not readable"
        exit 1
      endif
      breaksw

    case "-prep":
      set dopreproc = 1
      set docorr = 1
      set doqa = 1
      set dointra = 1
      set dotensor = 1
      set dointer = 1
      set dopriors = 1
      set dobedpost = 0
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-bedp":
      set dopreproc = 0
      set dobedpost = 1
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-path":
      set dopreproc = 0
      set dobedpost = 0
      set dopaths = 1
      set dostats = 0
      breaksw

    case "-stat":
      set dopreproc = 0
      set dobedpost = 0
      set dopaths = 0
      set dostats = 1
      breaksw

    case "-corr":
      set dopreproc = 1
      set docorr = 1
      set dobedpost = 0
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-nocorr":
      set docorr = 0
      breaksw

    case "-qa":
      set dopreproc = 1
      set doqa = 1
      set dobedpost = 0
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-noqa":
      set doqa = 0
      breaksw

    case "-intra":
      set dopreproc = 1
      set dointra = 1
      set dobedpost = 0
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-nointra":
      set dointra = 0
      breaksw

    case "-tensor":
      set dopreproc = 1
      set dotensor = 1
      set dobedpost = 0
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-notensor":
      set dotensor = 0
      breaksw

    case "-inter":
      set dopreproc = 1
      set dointer = 1
      set dobedpost = 0
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-nointer":
      set dointer = 0
      breaksw

    case "-prior":
      set dopreproc = 1
      set dopriors = 1
      set dobedpost = 0
      set dopaths = 0
      set dostats = 0
      breaksw

    case "-noprior":
      set dopriors = 0
      breaksw

    case "-infant":
      set doinfant = 1
      breaksw

    case "-cleancsdf":
      set DoCleanCSDF = 1
      breaksw

    case "-time":
      set DoTime = 1
      breaksw

    case "-notime":
      set DoTime = 0
      breaksw

    case "-noappendlog":
      set AppendLog = 0
      breaksw

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

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

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

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

    case "-sd":
      if ($#argv < 1) goto arg1err;
      setenv SUBJECTS_DIR $argv[1]; shift;
      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"
        exit 1
      endif
      pushd $FREESURFER_HOME > /dev/null
      setenv FREESURFER_HOME `pwd`;
      breaksw

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

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

    case "-allowcoredump":
      set allowcore = 1
      limit coredumpsize unlimited
      breaksw

    case "-debug":
      set debug = 1
      breaksw

    case "-dontrun":
      set RunIt = 0
      breaksw

    case "-onlyversions":
      set DoVersionsOnly = 1
      breaksw

    default:
      echo "ERROR: flag $flag unrecognized"
      echo $cmdline
      exit 1
      breaksw
  endsw
end

goto parse_args_return;

############--------------##################
set_reg_defaults:

# These variables are deprecated, but check for backwards compatibility
if ($?doregflt) then
  if ($doregflt) set intrareg = 1
endif
if ($?doregbbr) then
  if ($doregbbr) set intrareg = 3
endif
if ($?doregcvs) then
  if ($doregcvs) set interreg = 4
endif
if ($?doregmni) then
  if ($doregmni) set interreg = 2
endif
if ($?mnitemp && ($interreg == 1 || $interreg == 2)) then
  set intertrg = $mnitemp
endif
if ($?cvstemp && $interreg == 4) then
  set intertrg = $cvstempdir/$cvstemp/mri/norm.mgz
endif

# Default settings for intra-subject registration
if (! $#intrareg) then
  if   ($doinfant) set intrareg = 2
  if (! $doinfant) set intrareg = 3
endif

switch ($intrareg)
  case 1:	# Affine with a correlation ratio cost
    set reg = flt
    set intracost = corratio
    breaksw
  case 2:	# Affine with a mutual information cost
    set reg = flt
    set intracost = mutualinfo
    breaksw
  case 3:	# Affine with a boundary-based cost
    set reg = bbr
    breaksw
  default:
    echo "ERROR: $intrareg not a valid option for intra-subject registration"
    exit 1
    breaksw
endsw

if ($reg == flt) then			# Parameters for affine registration
  if ($doinfant) then
    if (! $#intradof) set intradof = 6
    if (! $#intrarot) set intrarot = 90
  else
    if (! $#intradof) set intradof = 12
    if (! $#intrarot) set intrarot = 90
  endif
else if ($reg == bbr) then
  if (! $#intradof) set intradof = 6
endif

# Default settings for inter-subject registration
if (! $#interreg) then
  if   ($doinfant) set interreg = 3
  if (! $doinfant) set interreg = 5
endif

switch ($interreg)
  case 1:	# Affine T1-to-T1 with a correlation ratio cost
    set xspace = mni
    set intercost = corratio
    breaksw
  case 2:	# Affine T1-to-T1 with a mutual information cost
    set xspace = mni
    set intercost = mutualinfo
    breaksw
  case 3:	# Affine T1-to-T1 with a robust cost
    set xspace = rob
    breaksw
  case 4:	# Nonlinear T1-to-T1 with CVS
    set xspace = cvs
    breaksw
  case 5:	# Nonlinear FA-to-FA with SyN
    set xspace = syn
    setenv MY_MORPHS_DO_NOT_CONFORM_DEAL_WITH_IT
    breaksw
  case 6:	# Nonlinear FA-to-FA with FNIRT
    set xspace = fnt
    breaksw
  default:
    echo "ERROR: $interreg not a valid option for inter-subject registration"
    exit 1
    breaksw
endsw

if (! $#intertrg) then			# Target for inter-subject registration
  if ($xspace == mni || $xspace == rob) then
    if ($doinfant) then
      set intertrg = $FREESURFER_HOME/trctrain/inf/WUSTL_T1_infant_template.nii.gz
    else
      set intertrg = $FSLDIR/data/standard/MNI152_T1_1mm_brain.nii.gz
    endif
  else if ($xspace == cvs) then
    if ($doinfant) then
      echo "ERROR: CVS registration not available for infants"
      exit 1
    else
      set intertrg = $FREESURFER_HOME/subjects/cvs_avg35/mri/norm.mgz
    endif
  else if ($xspace == syn) then
    if ($doinfant) then
      echo "ERROR: SyN registration not available for infants"
      exit 1
    else
      set intertrg = $FREESURFER_HOME/trctrain/hcp/MGH35_HCP_FA_template.nii.gz
    endif
  else if ($xspace == fnt) then
    if ($doinfant) then
      echo "ERROR: FNIRT registration not available for infants"
      exit 1
    else
      set intertrg = $FSLDIR/data/standard/FMRIB58_FA_1mm.nii.gz
    endif
  endif
endif

goto set_reg_defaults_return;

############--------------##################
set_path_defaults:

# Default settings for pathway reconstruction
if ($doinfant) then
  if (! $#trainfile) set trainfile = $FREESURFER_HOME/trctrain/inf/trainlist.txt
  if (! $#usethalnuc) set usethalnuc = 0
  if (! $#gmgrow)     set gmgrow = 1
  if (! $#pmin)       set pmin = .1
else
  if (! $#trainfile) set trainfile = $FREESURFER_HOME/trctrain/hcp/trainlist.txt
  if (! $#usethalnuc) set usethalnuc = 1
  if (! $#gmgrow)     set gmgrow = 2
  if (! $#pmin && ! $#baselist) set pmin = .2
  if (! $#pmin &&   $#baselist) set pmin = .02
endif

if (! $#pathfile) set pathfile = `dirname $trainfile`/pathlist.txt

if (! $#pathlist) then		# Pathway names
  if (! -e $pathfile) then
    echo "ERROR: Cannot find list of pathways $pathfile"
    exit 1
  endif

  set pathlist = `awk '{print $1}' $pathfile`
endif

if (! $#gmids) then		# Non-cortex label IDs to allow as pathway ends
  if (! -e $pathfile) then
    echo "ERROR: Cannot find list of pathways $pathfile"
    exit 1
  endif

  set gmids = ()
  foreach pname ($pathlist)
    set gmids = ($gmids `awk -v p=$pname '{if ($1 == p) print $2}' $pathfile`)
  end
endif

if (! $#ncpts) then		# Number of spline control points
  if (! -e $pathfile) then
    echo "ERROR: Cannot find list of pathways $pathfile"
    exit 1
  endif

  set ncpts = ()
  foreach pname ($pathlist)
    set ncpts = ($ncpts `awk -v p=$pname '{if ($1 == p) print $3}' $pathfile`)
  end
endif

if (! $#nsample) then		# Number of MCMC samples
  if (! $#baselist) set nsample =  7500		# Cross-sectional case
  if   ($#baselist) set nsample = 12000		# Longitudinal case
endif

goto set_path_defaults_return;

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

############--------------##################
check_params:
  if (! $DoVersionsOnly) then
    if (-e $trainfile) then
      if ($do1out) then
        # Leave-one-out training file:
        # The first subject of each line is the test subject,
        # the remaining subjects of the line are the training subjects
        set dlist = `cat $trainfile | awk '{print $1}'`
        set slist = ()
        foreach dname ($dlist)
          set slist = ($slist `basename $dname`)
        end

        if ($#baselist == 0) then	# A single time point for each subject
          set subjids = ($slist)

          set runlist = ()
          foreach subj ($subjids)
            set runlist = ($runlist `printf '%s\n' $subjlist \
                           | awk -v subj=$subj '{if ($1==subj) print NR}'`)
          end
        else				# Multiple time points for each subject
          set baseids = ($slist)

          set runlist = ()
          foreach base ($baseids)
            set runlist = ($runlist `printf '%s\n' $baselist \
                           | awk -v base=$base '{if ($1==base) print NR}'`)
          end
        endif

        if (! $#ntrainlist) then
          set ntrainlist = `head -1 $trainfile | wc -w | awk '{print $1 - 1}'`
        endif
      else
        # Simple training file:
        # The file lists the training subjects
        # Info on the test subjects comes from dmrirc
        set ntrainlist = `wc -w $trainfile | awk '{print $1}'`
      endif
    else if ($dopriors || $dopaths) then
      echo "ERROR: Cannot find list of training subjects $trainfile"
      exit 1
    endif

    if (! $#avgname) then
      set avgname = avg
    endif

    if (! $?subjlist) then
      echo "ERROR: must specify a subject id"
      exit 1
    endif

    if ($#runlist == 0) then			# Process all subjects
      set runlist = `printf '%s\n' $subjlist | awk '{print NR}'`
    else
      foreach iscan ($runlist)
        if ($iscan > $#subjlist) then
          echo "ERROR: $iscan is in run list but have only $#subjlist scans"
          exit 1
        endif
      end
    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 trac-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

    if (! $#dtroot) then		# Save output under SUBJECTS_DIR
      set dtroot = $SUBJECTS_DIR
    endif

    if ($#gmids != $#pathlist) then
      echo "ERROR: length of pathway list ($pathlist) and endpoint label ID list"
      echo "ERROR: ($gmids) do not match"
      exit 1
    endif

    if ($#ncpts != $#pathlist) then
      echo "ERROR: length of pathway list ($pathlist) and control point list
      echo "ERROR: ($ncpts) do not match"
      exit 1
    endif

    foreach n ($ncpts)
      if ($n < 2) then
        echo "ERROR: number of control points cannot be less than 2"
        exit 1
      endif
    end

    if ($#bmax && $#bshell) then
      echo "ERROR: cannot specify both bshell and bmax"
      exit 1
    endif

    if ($#runlist > $#subjlist) then
      echo "ERROR: run list is longer than subject ID list"
      exit 1
    endif

    if ($docorr) then
      if ($#dcmlist != $#subjlist) then
        echo "ERROR: must specify as many subject IDs as DWI scans"
        exit 1
      endif

      if ($#bveclist > 0 && $#bveclist != $#subjlist) then
        echo "ERROR: must specify as many gradient vector tables as DWI scans"
        exit 1
      endif

      if ($#bvallist > 0 && $#bvallist != $#subjlist) then
        echo "ERROR: must specify as many b-value tables as DWI scans"
        exit 1
      endif

      if ($dob0) then
        if (! $#echospacing) then
          echo "ERROR: for B0 distortion correction, must specify echo spacing"
          exit 1
        else if ($#echospacing > 1 && $#echospacing != $#subjlist) then
          echo "ERROR: must specify one echo spacing or one for each DWI scan"
          exit 1
        endif
      endif

      if ($dob0 == 1) then
        if ($#b0mlist != $#subjlist) then
          echo "ERROR: for B0 distortion correction with field maps,"
          echo "ERROR: must specify as many magnitude maps as DWI scans"
          exit 1
        endif

        if ($#b0plist != $#subjlist) then
          echo "ERROR: for B0 distortion correction with field maps,"
          echo "ERROR: must specify as many phase maps as DWI scans"
          exit 1
        endif
      endif

      if ($dob0 > 1 || $doeddy > 1) then
        if (! $#pedir) then
          echo "ERROR: for B0 distortion correction with reverse-polarity DWIs"
          echo "ERROR: or for model-based eddy-current distortion correction,"
          echo "ERROR: must specify PE direction"
          exit 1
        else if ($#pedir > 1 && $#pedir != $#subjlist) then
          echo "ERROR: for B0 distortion correction with reverse-polarity DWIs"
          echo "ERROR: or for model-based eddy-current distortion correction,"
          echo "ERROR: must specify one PE direction or one for each DWI scan"
          exit 1
        endif

        if (! $#epifactor) then
          echo "ERROR: for B0 distortion correction with reverse-polarity DWIs"
          echo "ERROR: or for model-based eddy-current distortion correction,"
          echo "ERROR: must specify EPI factor"
          exit 1
        else if ($#epifactor > 1 && $#epifactor != $#subjlist) then
          echo "ERROR: for B0 distortion correction with reverse-polarity DWIs"
          echo "ERROR: or for model-based eddy-current distortion correction,"
          echo "ERROR: must specify one EPI factor or one for each DWI scan"
          exit 1
        endif
      endif
    endif

    if ($#baselist > 0 && $#baselist != $#subjlist) then
      echo "ERROR: must specify a base template name for every DWI scan"
      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 ((! $dopreproc || (! $docorr && ! $doqa && ! $dointra && \
                        ! $dotensor && ! $dointer && ! $dopriors)) && \
       ! $dobedpost && ! $dopaths && ! $dostats) then
    echo "ERROR: no analysis step (-{prep,bedp,path,stat}) has been selected"
    exit 1
  endif

goto check_params_return;

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: $ProgName"
  echo ""
  echo "Using a configuration file to set analysis options:"
  echo "  -c <file> : dmrirc file (see dmrirc.example)"
  echo ""
  echo "Using only mandatory inputs with all default options:"
  echo "  -s <subjectname> : subject name (if not defined in dmrirc)"
  echo "  -i <file> : input DWI DICOM (if not defined in dmrirc)"
  echo ""
  echo "Choosing which part of the analysis to do:"
  echo "  -prep     : do pre-processing (step 1, all substeps)"
  echo "  -bedp     : do bedpost (step 2)"
  echo "  -path     : do pathway reconstruction (step 3)"
  echo "  -stat     : assemble pathway measures from multiple subjects (step 4)"
  echo ""
  echo "Performing a part of the preprocessing or skipping a part:"
  echo "  -corr     : do image corrections (step 1.1)"
  echo "  -nocorr   : don't do step 1.1"
  echo "  -qa       : do image quality assessment (step 1.2)"
  echo "  -noqa     : don't do step 1.2"
  echo "  -intra    : do intra-subject registration (step 1.3)"
  echo "  -nointra  : don't do step 1.3"
  echo "  -tensor   : do tensor fit (step 1.4)"
  echo "  -notensor : don't do step 1.4"
  echo "  -inter    : do inter-subject registration (step 1.5)"
  echo "  -nointer  : don't do step 1.5"
  echo "  -prior    : do pathway priors (step 1.6)"
  echo "  -noprior  : don't do step 1.6"
  echo ""
  echo "Analysis steps:"
  echo "  1. Pre-processing"
  echo "     1.1 Image corrections (eddy-current and/or B0)"
  echo "     1.2 Image quality assessment (head motion measures)"
  echo "     1.3 Intra-subject registration (individual DWI to individual T1)"
  echo "     1.4 Tensor fit"
  echo "     1.5 Inter-subject registration (individual DWI/T1 to template)"
  echo "     1.6 Pathway priors from atlas and T1"
  echo "  2. Stick-and-ball model fitting with bedpost"
  echo "  3. Pathway reconstruction"
  echo "  4. Assemble pathway measures from all subjects"
  echo ""
  echo "Other options:"
  echo "  -infant         : use infant brain processing options"
  echo "  -jobs <file>    : write a text file with command lines that can be"
  echo "                    run in parallel but do not run them - the user can"
  echo "                    then submit each line as a job on a compute cluster"
  echo "  -log <file>     : unique log file instead of scripts/trac-all.log"
  echo "  -noappendlog    : overwrite old log files instead of appending"
  echo "  -cmd <file>     : unique cmd file instead of scripts/trac-all.cmd"
  echo "  -no-isrunning   : do not check whether subjects are currently being processed"
  echo "  -sd subjectsdir : specify subjects dir (default env SUBJECTS_DIR)"
  echo "  -umask umask    : set unix file permission mask (default 002)"
  echo "  -grp groupid    : check that current group is alpha groupid "
  echo "  -allowcoredump  : set coredump limit to unlimited"
  echo "  -debug          : generate much more output"
  echo "  -dontrun        : do everything but execute each command"
  echo "  -onlyversions   : print version of each binary and exit"
  echo "  -version        : print version of this script and exit"
  echo "  -help           : print full contents of help"
  echo ""

  if (! $PrintHelp) exit 1

  echo $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

Recostruct white-matter pathways using an atlas of the underlying anatomy.

BASIC USAGE
There are two ways to use this script.

> Using only mandatory inputs with all default options:
  trac-all -{prep,bedp,path,stat} -subject subjectname -i dicomfile

> Using a file called dmrirc to define custom options:
  trac-all -{prep,bedp,path,stat} -c dmrirc

If a dmrirc file is not specified, then the subject name and input DWI
DICOM must be specified on the command line. If a dmrirc file is specified,
then the options set in that file override any corresponding command line
options.

STEP-WISE DIRECTIVES
Any of the two basic forms of usage described above must include an
argument (-prep for pre-processing, -bedp for bedpost, -path for path
reconstruction, or -stat for group tables) that specifies which part of
the analysis to perform. The four parts must be performed in that order.

It is also possible to perform a certain step of the pre-processing
(with -stepname) or to skip a certain step from the pre-processing (with
-nostepname). The default pre-processing performs all steps.

If there are conflicting step-wise arguments, the ones that come later
in the command line override the ones that come earlier.

Various aspects of each processing step can be configured in the dmrirc
file. See example configuration files ($FREESURFER_HOME/bin/dmrirc.*) for
more details:
  dmrirc.example : Single session, single DWI scan per session
  dmrirc.multiscan.example : Single session, multiple DWI scans per session
  dmrirc.long.example : Multiple sessions, single DWI scan per session
  dmrirc.long.multiscan.example : Multiple sessions, multiple DWI scans per session

> Step 1: Pre-processing
          -prep to do this step

  Pre-processing includes steps 1.1 through 1.6 below.

> Step 1.1: Image corrections
            -corr to do this step, -nocorr to skip this step

  Eddy current and susceptibility distortion correction.

> Step 1.2: Image quality assessment
            -qa to do this step, -noqa to skip this step

  Estimation of between-volume and within-volume head motion.

> Step 1.3: Intra-subject registration
            -intra to do this step, -nointra to skip this step

  Individual DWI-to-T1 registration.

> Step 1.4: Tensor fit
            -tensor to do this step, -notensor to skip this step

  Tensor model fitting on DWIs.

> Step 1.5: Inter-subject registration
            -inter to do this step, -nointer to skip this step

  Individual-to-template registration, affine or nonlinear, T1- or DWI-based.

> Step 1.6: Pathway priors
            -prior to do this step, -noprior to skip this step

  Combine training data and subject's own data to generate pathway priors.

> Step 2: Bedpost (cluster highly recommended for this step)
          -bedp to do this step

  Ball-and-stick model fitting on DWIs with bedpostx.

> Step 3: Pathway reconstruction
          -path to do this step

  Do the actual tractography.

> Step 4: Assemble pathway measures from multiple subjects
          -stat to do this step

  Combine whole-path or along-the-path measures (anisotropy and 
  diffusivity) from multiple subjects to feed into group analyses.

OTHER OPTIONS
-infant         : use infant brain processing options
-jobs <file>    : write a text file with command lines that can be
                  run in parallel but do not run them - the user can
                  then submit each line as a job on a compute cluster
-log <file>     : default is scripts/trac-all.log
-noappendlog    : overwrite old log files instead of appending
-cmd <file>     : default is scripts/trac-all.cmd
-no-isrunning   : do not check whether subjects are currently being processed
-sd subjectsdir : specify subjects dir (default env SUBJECTS_DIR)
-umask umask    : set unix file permission mask (default 002)
-grp groupid    : check that current group is alpha groupid 
-allowcoredump  : set coredump limit to unlimited
-debug          : print out more info and generate more files
-dontrun        : do everything but execute each command
-onlyversions   : print version of each binary and exit
-version        : print version of this script and exit
-help           : print full contents of help

FOR MARTINOS CENTER CLUSTER USERS
Do not submit trac-all as a job with pbsubmit or qsub. Run it directly on the
command line. If run on a local machine, trac-all will run all analyses locally.
If run on the cluster, trac-all will submit the analysis of each subject listed
in your dmrirc file as a job.

SEE ALSO: dmrirc.example, dmrirc.multiscan.example, dmrirc.long.example,
          dmrirc.long.multiscan.example

