Hi Stefano, I think I found and fixed the problem. Can you try these?

On 3/19/2024 7:30 AM, Stefano Delli Pizzi wrote:

        External Email - Use Caution

Hi Doug,

The raw functional file is firstly passed with motion correction (i.e., mc-sess -s ID -fsd rest -per-run) and AROMA filtering.
Next, I have renamed the ICA filtered file as f.nii.gz.
Then, I run:

preproc-sess -s ${1} -surface fsaverage lhrh -nomc -fwhm 0 -mni305 -fsd rest -per-run -sliceorder even -force

There are issues with labels since excluding motion correction doesn't produce key files necessary for concatenating the files. The preprocessing script is searching for the fmcpr.nii.gz file, which cannot be found because it is not created using the -nomc option.

When I duplicate and rename the file f.nii.gz as fmcpr.nii.gz and rerun preproc, the operation is done and the fmcpr.odd.sm0.fsaverage.lh is created.

However, when I run the next steps (fcseed-sess -s ID -cfg wm.config -overwrite), a second error occurs (reported below) because the script searches for fmcpr, which cannot be produced since I used -mc.

ERROR: could not determine file for /Volumes/mnu/MRI/PPMI/NIFTI/FreeSurfer/rs-fMRI_AROMA/ID/rest/001/fmcpr This error seems to be related to the script searching for the fmcpr file, which isn't available due to the use of -mc.

Thank you.

Best regards,


Stefano




Il giorno 18 mar 2024, alle ore 17:16, Stefano Delli Pizzi <sdellipi...@gmail.com> ha scritto:

Hi Doug have you any news
Thank you very much!
Stefano

Il giorno 12 mar 2024, alle ore 10:26, Stefano Delli Pizzi <sdellipi...@gmail.com> ha scritto:

Thank you.
I’m attaching the file.
Stefano
<preproc-sess>

Il giorno 11 mar 2024, alle ore 22:20, Douglas N. Greve <dgr...@mgh.harvard.edu> ha scritto:

can you send me this file /Applications/freesurfer/7.4.1/fsfast/bin/preproc-sess


On 3/11/2024 3:58 AM, Stefano Delli Pizzi wrote:

        External Email - Use Caution

It seems to me that I've done what you suggest. Attached is a new outputs.
Thanks
Stefano

Il giorno 10 mar 2024, alle ore 23:44, Douglas N. Greve <dgr...@mgh.harvard.edu> ha scritto:

Are you sure that you are using the new version that I gave you? It looks like the previous version. Also, it does not look like the entire terminal output.

On 3/8/2024 12:11 PM, Stefano Delli Pizzi wrote:

        External Email - Use Caution

The entire terminal output is attached.
Thanks!

Il giorno 8 mar 2024, alle ore 15:56, Douglas N. Greve <dgr...@mgh.harvard.edu> ha scritto:

entire terminal output


_______________________________________________
Freesurfer mailing list
Freesurfer@nmr.mgh.harvard.edu
https://mail.nmr.mgh.harvard.edu/mailman/listinfo/freesurfer
The information in this e-mail is intended only for the person to whom it is addressed.  If you believe this e-mail was sent to you in error and the e-mail contains patient information, please contact the Mass General Brigham Compliance HelpLine at https://www.massgeneralbrigham.org/complianceline <https://www.massgeneralbrigham.org/complianceline> .


The information in this e-mail is intended only for the person to whom it is addressed.  If you believe this e-mail was sent to you in error and the e-mail contains patient information, please contact the Mass General Brigham Compliance HelpLine at https://www.massgeneralbrigham.org/complianceline <https://secure-web.cisco.com/1jYq_7i1WV2KuJNwpF_8LuUmEt1uXm4GShRtNXC1xe4Y_Bcgi7ubGv5tYLWaiMMMvai3kMGIy815rdOHCuxa26TgzCG7N39_7gO7R1qweyEpbyWhg2jPzT7Jn6y5R9IDYEnulWkwidyb-Qib5lu4h6a_s5YcAdb0N9IiBeDpqWrbBe0hv15Vk8W8n6xL2cuFQJvTXex04uH4CPIgZEpJ6hpPWv7aOcOY-RxxGp_lf2-1SdLn_S3KEKrLQ68nS_U4WOd-L3Q1TxZnV8azAM2dMdrMpcc6aFGCMa7ROC27axgF_fs3uFwdABdIGbgPRYiaC/https%3A%2F%2Fwww.massgeneralbrigham.org%2Fcomplianceline> .



#! /bin/tcsh -f

#
# preproc-sess - runs preprocessing (mc, spatsmooth, mkbrainmask, inorm)
#
# Original Author: Doug Greve
#
# Copyright © 2021
# The General Hospital Corporation (Boston, MA). 
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-b...@nmr.mgh.harvard.edu
#

# To get per-run reg with smoothing, make sure -fwhm is after -per-run:
# preproc-sess -s risk001 -per-run -fwhm 5 -fsd bold 
# This creates fmcpr.sm5, then
# mkanalysis-sess -native -funcstem fmcpr.sm5 ...

set VERSION = 'preproc-sess @FS_VERSION@';

set inputargs = ($argv);
set DateStr = "`date '+%y%m%d%H%M'`"

set instem   = ();
set mcinstem   = ();
set mcoutstem  = ();
set stcinstem   = ();
set stcoutstem  = ();
set sminstem   = ();
set smoutstem  = ();
set inormstem  = ();
set maskdir    = masks
set maskstem   = brain;
set UseSmoothMask = 0;
set fwhm     = ();
set surffwhm = ();
set volsurffwhm  = (); # for testing
set SliceOrder = ();
set SliceDelayFile = ()
set nSliceGroups = 1;
set fsd      = ();
set mcrun    = ();
set mctargstem = ();
set mctargframe = ();
set PerRun = 0;
set PerSess = 0;
set RunListFile = ();

set UpdateOnly = 1;
set DoTemplate = 1;
set DoMC     = 1;
set DoSTC    = 0;
set DoMask   = 1;
set DoVolSmooth = 1;
set DoSurfSmooth = 0;
set DoSmooth = 1; # any smoothing
set DoInorm  = 0;
set ProjFrac = (); # default will be 0.5
set ProjFracExpKey = ()
set DoProjAvg = 0;
set DoReg = 1;
set ToSurf = 0;
set subject = ();
set hemi = ();
set ToMNI305 = 0;
set ToCVS = 0;
set RawRes = 2;
set RegDOF = 6;
set regfile = ();
set UseB0DC = 0;
set ApplySubCortMask = 1;
set InitCoReg = 1;
set InitFSL = 0;
set InitSPM = 0;
set InitHeader = 0;
set BBRXopts = ()
set IntermediateFSD = ()
set IntermediateStem = ()
set contrast = bold
set UseCortexLabel = 1;

set nskip = 0; # for inorm
set nolog = 0;
set targgrp = ();

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

set PWD = `getpwdcmd`;
if($status) exit 1;

set SessList = `getsesspath $argv`;
if($status || $#SessList == 0) then
  getsesspath $argv 
  exit 1;
endif

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

##### Create a log file ######
if($nolog) then 
  set LF = /dev/null
else
  set logdir = log;
  mkdir -p $logdir
  if(! -e $logdir) then
    echo "WARNING: could not create $logdir"
    set LF = /dev/null
  else
    if($#SessList > 1) then
      set LF = $logdir/preproc-sess.$$.log
    else
      set sb = `basename $SessList`
      set LF = $logdir/preproc-sess.$sb.log
    endif
    if(-e $LF) mv $LF $LF.old
  endif
endif
echo "--------------------------------------------------------------"
echo "preproc-sess logfile is $LF"
echo "--------------------------------------------------------------"

echo "preproc-sess log file" >> $LF
echo $VERSION | tee -a $LF
echo "$user"  | tee -a $LF
echo "setenv FREESURFER_HOME $FREESURFER_HOME" | tee -a $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" | tee -a $LF
uname -a        | tee -a $LF
pwd             | tee -a $LF
echo $0         | tee -a $LF
echo $inputargs | tee -a $LF
date          | tee -a $LF

echo "instem   $instem " | tee -a $LF
echo "mc   $DoMC     $mcinstem $mcoutstem " | tee -a $LF
echo "stc  $DoSTC    $stcinstem $stcoutstem"  | tee -a $LF
echo "sm   $DoVolSmooth $sminstem $smoutstem "| tee -a $LF
echo "mask $DoMask   $maskstem"| tee -a $LF

set ProjectDir = `pwd`;

set StartTime = `date`;
#------------------------------------------------#
foreach sess ($SessList)
  set sessid     = `basename $sess`;
  set sessparent = `dirname $sess`;

  # Create a log file #
  if(-w . && $nolog != 1) then
    mkdir -p log
    set LF = $ProjectDir/log/preproc-$sessid-$fsd.log
    rm -f $LF
  else
    set LF = /dev/null
  endif

  echo "preproc-sess" >> $LF
  echo $sessid      >> $LF
  echo $VERSION     >> $LF
  uname -a          >> $LF
  date              >> $LF
  pwd               >> $LF
  echo $inputargs   >> $LF
  echo "ProjectDir $ProjectDir" >> $LF

  if($DoTemplate) then
    set cmd = (mktemplate-sess -s $sessid -d $sessparent -fsd $fsd -funcstem 
$instem)
    if($#RunListFile) set cmd = ($cmd -rlf $RunListFile);
    if($nolog)      set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    echo "$sessid Template -----------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($DoReg) then
    set cmd = (register-sess -s $sessid -d $sessparent -fsd $fsd -delete-dat)
    set cmd = ($cmd -dof $RegDOF -$contrast)
    if($#RunListFile) set cmd = ($cmd -rlf $RunListFile);
    if($PerRun)     set cmd = ($cmd -per-run)
    if($PerSess) set cmd = ($cmd -per-session)
    if($nolog)      set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    if($UseB0DC)    set cmd = ($cmd -b0dc)
    if($InitCoReg) set cmd = ($cmd -init-coreg)
    if($InitFSL)   set cmd = ($cmd -init-fsl)
    if($InitSPM)   set cmd = ($cmd -init-spm)
    if($InitHeader) set cmd = ($cmd -init-header)
    if($#IntermediateFSD) set cmd = ($cmd -bbr-int $IntermediateFSD 
$IntermediateStem)
    if($#BBRXopts) set cmd = ($cmd -bbr-xopts $BBRXopts)
    echo "$sessid Registration -----------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($DoMask) then # Must be after reg now
    set cmd = (mkbrainmask-sess -maskstem $maskstem)
    set cmd = ($cmd -fsd $fsd)
    set cmd = ($cmd -s $sessid -d $sessparent)
    if($PerRun)     set cmd = ($cmd -per-run)
    if($PerSess) set cmd = ($cmd -per-session)
    if($#RunListFile) set cmd = ($cmd -rlf $RunListFile);
    if($nolog) set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    if($UseB0DC)    set cmd = ($cmd -b0dc) # only used to get the right reg file
    if($RegDOF != 6) set cmd = ($cmd -dof $RegDOF)
    echo "$sessid Mask ------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($DoMC) then
    set cmd = (mc-sess -fstem $mcinstem -fmcstem $mcoutstem)
    set cmd = ($cmd -s $sessid -d $sessparent -fsd $fsd)
    if($#RunListFile) set cmd = ($cmd -rlf $RunListFile);
    if($PerRun)   set cmd = ($cmd -per-run)
    if($PerSess) set cmd = ($cmd -per-session)
    if($nolog)      set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    echo "$sessid MC -----------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($DoSTC) then
    set cmd = (stc-sess -i $stcinstem -o $stcoutstem -ngroups $nSliceGroups)
    if($#SliceOrder) set cmd = ($cmd -so $SliceOrder)
    if($#SliceDelayFile) set cmd = ($cmd -sdf $SliceDelayFile)
    set cmd = ($cmd -s $sessid -d $sessparent -fsd $fsd)
    if($#RunListFile != 0)  set cmd = ($cmd -rlf $RunListFile);
    if($nolog)      set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    echo "$sessid STC -----------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($ToSurf) then
    set cmd = (rawfunc2surf-sess -fwhm $fwhm)
    set cmd = ($cmd -s $sessid -d $sessparent -fsd $fsd)
    # By default it will do both, so set -hemi to anything
    if("$hemi" == lh || "$hemi" == rh) set cmd = ($cmd -hemi $hemi)
    if($subject == self) set cmd = ($cmd -self)
    if($subject != self) set cmd = ($cmd -trgsubject $subject)
    if($#RunListFile != 0)  set cmd = ($cmd -rlf $RunListFile);
    if($#SliceOrder) set cmd = ($cmd -stc $SliceOrder)
    if($#SliceDelayFile) set cmd = ($cmd -sdf $SliceDelayFile)
    if($nolog)      set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    if($UseB0DC)    set cmd = ($cmd -b0dc)
    if($RegDOF != 6) set cmd = ($cmd -dof $RegDOF)
    if($PerRun)      set cmd = ($cmd -per-run)
    if($PerSess)     set cmd = ($cmd -per-session)
    if($DoMC == 0)   set cmd = ($cmd -no-mc)
    if($#ProjFrac)   set cmd = ($cmd -projfrac $ProjFrac -expkey 
$ProjFracExpKey)
    if($#volsurffwhm) set cmd = ($cmd -volsurffwhm $volsurffwhm) # for testing
    if(! $UseCortexLabel) set cmd = ($cmd -no-cortex-label)
    echo "$sessid To Surface -----------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($ToMNI305 || $ToCVS) then
    set cmd = (rawfunc2tal-sess -fwhm $fwhm )
    set cmd = ($cmd -s $sessid -d $sessparent -fsd $fsd)
    if($RawRes == 1) set cmd = ($cmd -1mm)
    if($#RunListFile != 0)  set cmd = ($cmd -rlf $RunListFile);
    if($#SliceOrder) set cmd = ($cmd -stc $SliceOrder)
    if($#SliceDelayFile) set cmd = ($cmd -sdf $SliceDelayFile)
    if($nolog)       set cmd = ($cmd -nolog);
    if($UpdateOnly)  set cmd = ($cmd -update);
    if($UseB0DC)     set cmd = ($cmd -b0dc)
    if($RegDOF != 6) set cmd = ($cmd -dof $RegDOF)
    if($ApplySubCortMask)   set cmd = ($cmd -subcort-mask)
    if(! $ApplySubCortMask) set cmd = ($cmd -no-subcort-mask)
    if($PerRun)   set cmd = ($cmd -per-run)
    if($PerSess) set cmd = ($cmd -per-session)
    if($DoMC == 0)   set cmd = ($cmd -no-mc)
    if($ToCVS) set cmd = ($cmd -cvs)
    echo "$sessid To MNI305 -----------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($DoVolSmooth) then
    set cmd = (spatialsmooth-sess -i $sminstem -o $smoutstem -fwhm $fwhm)
    set cmd = ($cmd -fsd $fsd -s $sessid -d $sessparent)
    if($UseSmoothMask)  set cmd = ($cmd -mask);
    if($#RunListFile != 0)  set cmd = ($cmd -rlf $RunListFile);
    if($nolog)      set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    echo "$sessid Volume Smoothing ---------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($DoSurfSmooth) then
    set cmd = (surfsmooth-sess -i $sminstem -o $smoutstem -fwhm $fwhm)
    set cmd = ($cmd -fsd $fsd -s $sessid -d $sessparent -reg $regfile)
    if($#ProjFrac)  set cmd = ($cmd -projfrac $ProjFrac)
    if($DoProjAvg)  set cmd = ($cmd -projfrac-avg)
    if($#RunListFile != 0)  set cmd = ($cmd -rlf $RunListFile);
    if($nolog)      set cmd = ($cmd -nolog);
    if($UpdateOnly) set cmd = ($cmd -update);
    if($PerRun)   set cmd = ($cmd -perrun)
    echo "$sessid Surface Smoothing ---------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

  if($DoInorm) then
    # Should probably remove this
    set cmd = (inorm-sess -funcstem $inormstem )
    set cmd = ($cmd  -fsd $fsd -nskip $nskip)
    set cmd = ($cmd -s $sessid -d $sessparent)
    if($#RunListFile != 0) set cmd = ($cmd -rlf $RunListFile);
    if($nolog)     set cmd = ($cmd -nolog);
    echo "$sessid Inorm ------------------------" |& tee -a $LF
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
  endif

end

echo "----------------------------------------" |& tee -a $LF
echo "Started at $StartTime" |& tee -a $LF
echo "Ended   at `date`"     |& tee -a $LF

echo "preproc-sess done"

exit 0

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

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

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

    case "-i":
    case "-in":
      if ( $#argv == 0) goto arg1err;
      set instem = $argv[1]; shift;
      breaksw

    case "-reg":
      set DoReg = 1;
      breaksw

    case "-noreg":
    case "-no-reg":
      set DoReg = 0;
      breaksw

    case "-reg-dof":
      if ( $#argv == 0) goto arg1err;
      set RegDOF = $argv[1]; shift;
      breaksw

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

    case "-mc-in":
    case "-mcin":
      if ( $#argv == 0) goto arg1err;
      set mcinstem = $argv[1]; shift;
      breaksw

    case "-mc-out":
    case "-mcout":
      if ( $#argv == 0) goto arg1err;
      set mcoutstem = $argv[1]; shift;
      breaksw

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

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

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

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

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

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

    case "-vol-fwhm":
    case "-fwhm":
      if ( $#argv == 0) goto arg1err;
      set fwhm = $argv[1]; shift;
      if($fwhm != 0) then
        set DoVolSmooth = 1;
        set DoSurfSmooth = 0;
        set DoSmooth = 1;
      else
        set DoVolSmooth = 0;
        set DoSurfSmooth = 0;
        set DoSmooth = 0;
      endif
      breaksw

    case "-smooth-mask":
      set UseSmoothMask = 1;
      breaksw

    case "-no-smooth-mask":
      set UseSmoothMask = 0;
      breaksw

    case "-surf-fwhm":
      if ( $#argv == 0) goto arg1err;
      set fwhm = $argv[1]; shift;
      if($fwhm != 0) then
        set DoVolSmooth = 0;
        set DoSurfSmooth = 1;
        set DoSmooth = 1;
      endif
      breaksw

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

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

    case "-bbr-int":
      if($#argv < 2) goto arg2err;
      set IntermediateFSD = $argv[1]; shift;
      set IntermediateStem = $argv[1]; shift;
      breaksw

    case "-bold":
    case "-t2":
      set contrast = bold
      breaksw
    case "-t1":
      set contrast = t1
      breaksw

    case "-projfrac":
      if ( $#argv < 2) goto arg2err;
      set ProjFrac = $argv[1]; shift;
      set ProjFracExpKey = $argv[1]; shift;
      breaksw

    case "-projfrac-avg":
      set DoProjAvg = 1;
      breaksw

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

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

    case "-runlistfile":
    case "-rlf":
      if ( $#argv == 0) goto arg1err;
      set RunListFile = $argv[1]; shift;
      breaksw

    case "-nomc":
    case "-no-mc":
      set DoMC = 0;
      breaksw

    case "-per-run":
    case "-perrun":
      set PerRun = 1;
      set PerSess = 0;
      set DoSmooth = 0;
      set DoVolSmooth = 0;
      set DoSurfSmooth = 0;
      breaksw

    case "-per-session":
    case "-persession":
      set PerSess = 1;
      set PerRun = 0;
      breaksw

    case "-no-stc":
    case "-nostc":
      set DoSTC = 0;
      breaksw

    case "-stc":
    case "-sliceorder":
    case "-so":
      if ( $#argv == 0) goto arg1err;
      set SliceOrder = $argv[1]; shift;
      set DoSTC = 1;
      breaksw

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

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

    case "-no-smooth":
    case "-nosmooth":
      set DoVolSmooth = 0;
      set DoSurfSmooth = 0;
      set DoSmooth = 0;
      breaksw

    case "-surf":
    case "-surface":
      if($#argv< 2) goto arg2err;
      set subject = $argv[1]; shift;
      set hemi = $argv[1]; shift;
      set ToSurf = 1;
      #set PerRun = 1;
      #set PerSess = 0;
      if($subject != self && ! -e $SUBJECTS_DIR/$subject) then
        echo "ERROR: cannot find $subject in $SUBJECTS_DIR"
        exit 1;
      endif
      breaksw

    case "-mni305-2mm":
    case "-mni305":
      set RawRes = 2;
      set ToMNI305 = 1;
      set ToCVS = 0;
      #set PerRun = 1;
      #set PerSess = 0;
      breaksw

    case "-cvs":
      set RawRes = 2;
      set ToMNI305 = 0;
      set ToCVS = 1;
      #set PerRun = 1;
      #set PerSess = 0;
      breaksw

    case "-usual":
      set subject = fsaverage;
      set hemi = lhrh
      set ToSurf = 1;
      set RawRes = 2;
      set ToMNI305 = 1;
      set PerRun = 1;
      set PerSess = 0;
      set fwhm = 5;
      breaksw

    case "-mni305-1mm":
      set RawRes = 1;
      set ToMNI305 = 1;
      #set PerRun = 1;
      #set PerSess = 0;
      breaksw

    case "-subcort-mask":
    case "-subcort":
      set ApplySubCortMask = 1;
      breaksw
    case "-no-subcort-mask":
    case "-no-subcort":
      set ApplySubCortMask = 0;
      breaksw

    case "-init-coreg":
      set InitCoReg = 1;
      set InitFSL = 0;
      set InitSPM = 0;
      set InitHeader = 0;
      breaksw
    case "-init-fsl":
      set InitCoReg = 0;
      set InitFSL = 1;
      set InitSPM = 0;
      set InitHeader = 0;
      breaksw
    case "-init-spm":
      set InitCoReg = 0;
      set InitFSL = 0;
      set InitSPM = 1;
      set InitHeader = 0;
      breaksw
    case "-init-header":
      set InitCoReg = 0;
      set InitFSL = 0;
      set InitSPM = 0;
      set InitHeader = 1;
      breaksw

    case "-b0dc":
      set UseB0DC = 1;
      breaksw

    case "-a":
    case "-analysis":
      if($#argv< 1) goto arg1err;
      set analysis = $argv[1]; shift;
      if(! -e $analysis) then
        echo "ERROR: cannot find $analysis"
        exit 1;
      endif
      set fsd = `getana -a $analysis -t fsd`;
      set RunListFile = `getana -a $analysis -t runlistfile`;
      set RegDOF = `getana -a $analysis -t RegDOF`;
      set PerRun = `getana -a $analysis -t IsPerRun`;
      set PerSess = `getana -a $analysis -t IsPerSession`;
      set UseB0DC = `getana -a $analysis -t UseB0DC`;
      if($#UseB0DC == 0) set UseB0DC = 0;
      set ApplySubCortMask = `getana -a $analysis -t ApplySubCortMask`;
      set fwhm = `getana -a $analysis -t RawFWHM`;
      if($fwhm == 0 || $PerRun) set DoVolSmooth = 0;
      set SliceOrder = `getana -a $analysis -t stc`;
      if($SliceOrder != none) set DoSTC = 1;
      if($SliceOrder == none) set SliceOrder = ();
      set SliceDelayFile = `getana -a $analysis -t sdf`;
      if($SliceDelayFile != none) then
        set DoSTC = 1;
        set SliceDelayFile = $analysis/$SliceDelayFile
      else 
        set SliceDelayFile = ()
      endif
      set nSliceGroups = `getana -a $analysis -t nslicegroups`;
      set ToSurf = `getana -a $analysis -t IsSurface`;
      if($ToSurf) then
        set subject = `getana -a $analysis -t subject`;
        set hemi    = `getana -a $analysis -t hemi`;
      endif
      set ToMNI305 = `getana -a $analysis -t IsMNI305`;
      set ToCVS    = `getana -a $analysis -t IsCVS`;
      if($ToMNI305 || $ToCVS) then
        set RawRes = `getana -a $analysis -t RawRes`;
      endif
      set volsurffwhm = `getana -a $analysis -t VolSurfFWHM`;
      if($#volsurffwhm && $volsurffwhm != 0) set DoVolSmooth = 1;
      breaksw

    case "-no-inorm":
    case "-noinorm":
      set DoInorm = 0;
      breaksw

    case "-inorm":
      set DoInorm = 1;
      breaksw

    case "-no-template":
      set DoTemplate = 0;
      breaksw

    case "-no-mask":
    case "-nomask":
      set DoMask = 0;
      breaksw

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

    case "-update":
      set UpdateOnly = 1;
      breaksw

    case "-force":
    case "-noupdate":
    case "-no-update":
      set UpdateOnly = 0;
      breaksw

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

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

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

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

    case "-g":
    case "-s":
    case "-sf":
    case "-d":
    case "-df":
      shift;
      # ignore getsesspath arguments 
      breaksw

    case "-cwd":
      # ignore getsesspath arguments 
      breaksw

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

end

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

############--------------##################
check_params:
  if($#instem == 0) set instem = "f";

  if($#fsd == 0) then
    echo "ERROR: you must specify a functional subdirectory with -fsd"
    echo "       eg, -fsd bold or -fsd rest"
    exit 1
  endif

  if($DoMC || $DoReg) then
    if($PerRun == 0 && $PerSess == 0) then
      echo "ERROR: You must specify -per-run or -per-session"
      exit 1;
    endif
  endif

  if($DoMC) then
    if($#mcinstem  == 0) set mcinstem  = $instem
    if($#mcoutstem == 0) then
      if($PerRun) then
        set mcoutstem = $mcinstem"mcpr"
      else # PerSess
        set mcoutstem = $mcinstem"mc"
      endif    
    endif    
  else
    # Don't append "pr" even if per-run
    set mcoutstem = $instem;
  endif

  if($DoSTC) then
    if($#stcinstem  == 0) set stcinstem  = $mcoutstem
    if($#stcoutstem == 0) then
      if($#SliceOrder)  set stcoutstem = $stcinstem.$SliceOrder
      if($#SliceDelayFile)  set stcoutstem = $stcinstem.sdf
    endif
  else
    set stcoutstem = $mcoutstem
  endif

  if($ToSurf || $ToMNI305 || $ToCVS) then
    if($#fwhm == 0) then
      echo "ERROR: must specify -fwhm with -surface or -mni305 or -cvs."
      echo "       Set it to 0 for no smoothing"
      exit 1;
    endif
    set DoVolSmooth = 0;
    set DoSurfSmooth = 0;
    set DoSmooth = 0;  
  endif

  if($DoSmooth) then
    if($#fwhm == 0) then
      echo "ERROR: must specify FWHM when doing smoothing"
      echo "If not smoothing, use -nosmooth"
      exit 1;
    endif
    if($#sminstem  == 0) set sminstem  = $stcoutstem
    if($#smoutstem == 0) then
      if($DoVolSmooth) set smoutstem = $sminstem."sm"$fwhm
      if($DoSurfSmooth) set smoutstem = $sminstem."sm"$fwhm
    endif
  endif

  if($DoInorm && $#inormstem == 0) then
    if($DoVolSmooth) then
      set inormstem = $smoutstem;
    else if($DoMC) then
      set inormstem = $mcoutstem;
    else
      set inormstem = $mcinstem;
    endif
  endif

  if(! $DoMC && ! $DoSTC  && ! $DoSmooth && ! $DoMask && ! $DoTemplate) then
    echo "ERROR: nothing to do"
    exit 1;
  endif

  if($#ProjFrac && $DoProjAvg) then
    echo "ERROR: cannot -projfrac and -projfrac-avg"
    exit 1;
  endif

  if($UseB0DC && $#ProjFracExpKey) then
    # This can actually be done but will create a conflict at the time of 
mkanalysis
    echo "WARNING: specifying -b0dc and -projfrac at the same time may create a 
conflict when mkanalysis-sess is run"
    #exit 1;
  endif

  if($#regfile == 0) then
    if(! $UseB0DC) set regfile = register.dof$RegDOF.lta
    if($UseB0DC)   set regfile = register.dof$RegDOF.b0dc.lta
  endif

  if($#SliceDelayFile != 0 && $#SliceOrder != 0) then
    echo "ERROR: cannot specify both -so and -sdf"
    exit 1;
  endif

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

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: preproc-sess"
  echo ""
  echo "  -per-run : motion cor and reg to middle TP of each run"
  echo "  -per-session : motion cor and reg to 1st TP of 1st run"
  echo "  -fwhm FWHM : smoothing level (mm)"
  echo ""
  echo "  -update        : only run a stage if input is newer than output 
(default)"
  echo "  -force         : force reprocessing of all stages (turns off -update)"
  echo "  -no-update     : same as -force"
  echo "  -sliceorder so : turn on slice timing correction (STC) with the given 
slice order"
  echo "  -ngroups nSliceGroups : number of SMS slice groups for STC"
  echo "  -surface subject hemi : set hemi to lhrh to do both"
  echo "  -mni305-2mm    : sample raw data to mni305 at 2mm (same as -mni305)"
  echo "  -mni305-1mm    : sample raw data to mni305 at 1mm"
  echo "  -cvs : sample raw data to cvs_avg35_inMNI152 at 2mm (not with 
-mni305)"
  echo "  -b0dc : apply B0 distortion correction (looks for 
fsd/b0dcmap.nii.gz); see epidewarp.fsl"
  echo ""
  echo "Session Arguments (some combination required)"
  echo "  -sf sessidfile  ..."
  echo "  -df srchdirfile ..."
  echo "  -s  sessid      ..."
  echo "  -d  srchdir     ..."
  echo "  -fsd    fsd <bold>"
  echo "  -rlf    rlf  : run list file (default all runs)"
  echo ""
  echo "Registration options"
  echo "  -init-fsl : use fsl to initialize bbr registration"
  echo "  -init-spm : use spm to initialize bbr registration (needs matlab)"
  echo "  -init-header : use geometry to initialize bbr registration"
  echo "  -bbr-int ifsd istem : use intermediate volume in sess/ifsd/RRR/istem"
  echo ""
  echo "Other options (probably not too useful)"
  echo ""
  echo "  -nomc     : don't do motion correction"
  echo "  -nostc    : don't do slice-timing correction"
  echo "  -nosmooth : don't do smoothing"
  echo "  -nomask   : don't create brain mask"
  echo "  -noreg    : don't do registration"
  echo "  -noinorm  : don't do inorm"
  echo "  -no-subcort-mask : do not apply subcortical masking"
  echo ""
  echo "  -mcin   mcinstem    : stem to use as input  to MC"
  echo "  -mcout  mcoutstem   : stem to use as output of MC"
  echo "  -stcin  stcinstem   : stem to use as input  to STC "
  echo "  -stcout stcoutstem  : stem to use as output of STC "
  echo "  -smin   sminstem    : stem to use as input  to smoothing "
  echo "  -smout  sminstem    : stem to use as output of smoothing "
  echo "  -mask   maskstem    : <brain>"
  echo ""
  echo "  -i    instem    : stem to use as overal input <f>"
#  echo "  -vol-fwhm  fwhm : 3D fwhm (mm) (not with -surf-fwhm)"
#  echo "  -surf-fwhm fwhm : 2D fwhm (mm) (not with -vol-fwhm)"
#  echo "  -smooth-mask   : use mask when volume smoothing"
#  echo "  -no-smooth-mask: do not use mask when volume smoothing"
#  echo "  -inorm        : perform intensity normalization (off by default)"
#  echo "  -nskip N      : do not use first N TRs when inorming"
  echo ""
  echo ""
  echo "  -regfile regfile   : registration file for use with -surf-fwhm 
(register.dat)"
  echo "  -bbr-xopts bbr.xopts : pass expert options to bbregister"
  echo "  -projfrac frac expkey : projection fraction for use with -surf-fwhm 
(0.5)"
  echo "    expkey is a code string used to make sure that the output file name 
is unique."
  echo "    This should be passed to mkanalysis-sess with -expkey. "
  echo "    Example: -projfrac 0.2 pf020"
  echo "  -projfrac-avg  : average over ribbon (not with -projfrac)"
  echo "  -no-cortex-label : do not use cortex label for masking surfaces"
  echo ""

  if(! $PrintHelp) exit 1;

  echo $VERSION

  cat $0 | awk 'BEGIN{prt=0}{if(prt) print $0; if($1 == "BEGINHELP") prt = 1 }'

exit 1;


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

This will run preprocessing steps: motion correction (MC),
slice-timing correction (STC), functional-anatomical registration,
mask creation, intensity normalization, resampling to common space,
and spatial smoothing. 

-per-run 

Motion correct and register using the middle time point of each run.
This is the option that you should use.

-per-session

Motion correct and register using the first time point of the first
run.  This is mainly for compatability with version 4.

-fwhm FWHM

Specify a full-width/half-max (in mm) when smoothing. If you do not
want to smooth, specify 0 (but you must specify something).

-update

Only perform a stage if the output is newer than the input or if the
output does not exist. This can be very convenient as you do not have to
keep track of what has been done. Just specify all the sessions and
and it will figure out what needs to be done. This is the default
behavior. See also -force.

-force
-noupdate

Force processing of all stages regardless of what has been done
before. This turns off -update

-sliceorder so

Perform slice-timing correction with the given slice order. Legal
values are siemens, up, down, odd, and even. Siemens slice order is
interleaved starting on the first slice for an odd number of slices or
the second slice for an even number. "up" is 1st, 2nd, 3rd,
etc. "down" is last, next to last, etc. odd is 1st, 3rd, 5th, , etc,
then 2nd, 4th, 6th, etc. "even" is 2nd, 4th, 6th, etc, then 1st, 3rd,
5th, etc.  See also stc-sess.

-sdf slicedelayfile

Provide a text file that gives the slice delay of each slice in
fractions of TR rather than computing it analytically from up,
down, etc. Usually the middle of the TR has a value of 0.  The
format should be the same as the output of the slicedelay program.
This allows for arbitrary slice orders.

-surface subject hemi

Sample raw data onto the surface of the hemisphere of the given
subject.  Hemi should be lh, rh, or lhrh (for both). Both -surface and
-mni305can be specified (in which case it will do both).

-mni305

Sample raw data into the mni305 2mm space. Both -mni305 and -surface can be
specified (in which case it will do both).

-i instem 

Explicitly specify input stem. Default is f.


EXAMPLE 1 

To perform template creation, MC, registration, mask creation, sampling
to the lh and rh hemispheres of fsaverage and to the mni305 2mm space,

  preproc-sess -sf sessidlist -df sessdirlist 
    -surface fsaverage lhrh -mni305 -fwhm 5


EXAMPLE 2

To perform template creation, MC, registration, mask creation,
sampling to the lh and rh hemispheres of native subject anatomy and
to the mni305 2mm space,

  preproc-sess -sf sessidlist -df sessdirlist 
    -surface self lhrh -mni305 -fwhm 5


INPUTS AND OUTPUTS

Unless otherwise specified, the input stem is f, and the input stems
and output stems of the other stages are automatically determined as
follows:

Input to MC is instem (default is f) Output of MC is instem"mcpr" (ie,
the MC input stem with "mcpr" appended to the end, eg, "fmcpr"). When
per-session is used, the MC default stem will be instem"mc".

Input  to STC is outstem of MC  
Output of STC is stcinstem.SliceOrder where SliceOrder is the slice
order used (eg, "siemens", see -sliceorder above).

Input  to smoothing is outstem of STC (or MC if no STC)
Output of smoothing is sminstem"smFWHM" (ie, the smoothing 
input stem with "sm" appended to the end and then the specified
FWHM appended to that).


====================================================================
These options are obsolete but still functional

-vol-fwhm fwhm

Specify the fwhm for 3D spatial smoothing. There is no default.  The
output will have "smFWHM" appened to it. Eg, for -vol-fwhm 5, then the
output will have "sm5" appened. If you do not want to perform
smoothing, use -nosmooth. See also spatialsmooth-sess. Cannot be run
with -surf-fwhm.

-surf-fwhm fwhm

Specify the fwhm for 2D (surface) spatial smoothing. The raw data are
resampled to the surface, smoothed, and then put back into the volume
(so that they can be analyzed in standard volumetric fashion). Values
not on the surface are not changed.  Surface smoothing can be slow, so
be patient! Requires that registration have been performed
(spmregister-sess or fslregister-sess).  The output will have
"smFWHMs" appened to it. Eg, for -surf-fwhm 5, then the output will
have "sm5s" appened. If you do not want to perform smoothing, use
-nosmooth. See also surfsmooth-sess. Cannot be run with -vol-fwhm.
Any per-run instruction will force surface smoothing to use
"register.dat" in each run directory. The registration file name can
be changed with -reg. By default, samples midway between the white and
pial surfaces (ie, projection fraction of 0.5), but this can be
changed with -projfrac. Or the average over the ribbon can be computed
with -projfrac-avg (but this will be slow).

-inorm

Not needed anymore. Turn on computing of intensity normalization
factor (creates stem.meanval). This was necssary for the old selxavg.


#! /bin/csh -f

#
# rawfunc2surf-sess
#
# Original Author: Doug Greve
#
# Copyright © 2021
# The General Hospital Corporation (Boston, MA). 
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-b...@nmr.mgh.harvard.edu
#

set VERSION = 'rawfunc2surf-sess @FS_VERSION@';

set inputargs = ($argv);

set fsd        = bold;
set instem     = ()
set mc = mc
set outstem    = ();
set regfile    = ();
set RegDOF     = 6;
set trgsubject = fsaverage
set hemilist = ()
set ProjFrac = 0.5;
set interp = trilin
set PerRun = 1;
set maskname = brain
set maskdir = masks
set maskstem = ();
set RunListFile = ();
set volsurffwhm = (); # smooth in the volume, for testing
set fwhm = ();
set UpdateOnly = 0;
set nolog = 0;
set debug = 0;
set DoSelf = 0;
set PrintHelp = 0;
set SurfReg = sphere.reg
set ExpKey = ();
set ExpKeyNeeded = 0;
set SliceOrder = ();
set SliceDelayFile = ();
set SaveUnsmoothed = 0;
set UseB0DC = 0;
set b0dcmapstem = b0dcmap
set UseCortexLabel = 1;

set outfmt = nii
if($?FSF_OUTPUT_FORMAT) then
  set outfmt = $FSF_OUTPUT_FORMAT
endif

## If there are no options, just print the usage ##
if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e  -version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;  
  goto usage_exit;
endif

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:

set SessList = `getsesspath $inputargs`;
if($status || $#SessList == 0) then
  getsesspath $inputargs 
  echo "ERROR: cannot find any sessions"
  exit 1;
endif

goto check_params;
check_params_return:

# Create a string like lhrh
set hemistr = ();
foreach hemi ($hemilist)
  set hemistr = $hemistr$hemi
end

set ProjectDir = `pwd`;

## Loop through each session ##
@ nthsess = 0;
foreach sess ($SessList)
  set sessid = `basename $sess`
  @ nthsess = $nthsess + 1;

  ##### Create a log file ######
  set LF = /dev/null
  if(! $nolog) then
    set logdir = $ProjectDir/log;
    mkdir -p $logdir
    set LF = $logdir/rawfunc2surf-sess.$sessid.$fsd.$outstem.$hemistr$ExpKey.log
    if(-e $LF) mv $LF $LF.old
  endif
  echo "rawfunc2surf-sess log file" >> $LF
  echo $VERSION >> $LF
  uname -a >> $LF
  date >> $LF
  pwd >> $LF
  echo $0 $inputargs  >> $LF 
  echo UpdateOnly $UpdateOnly >> $LF 

  echo "------------------------------ " |& tee -a $LF
  echo "$nthsess/$#SessList $sessid" |& tee -a $LF

  set subject = `cat $sess/subjectname`;
  if($DoSelf) set trgsubject = $subject

  set b0dcmap = ();
  set pedir = 2; #2=row direction
  if($UseB0DC) then
    set b0dcmap = `stem2fname $sess/$fsd/$b0dcmapstem`;
    if($status) then
      echo "$b0dcmap"|& tee -a $LF
      exit 1;
    endif
    set pedirfile = $sess/$fsd/$b0dcmapstem.pedir.txt
    if(-e $pedirfile) then
      set pedir = `cat $pedirfile`
      echo "Setting PE direction so $pedir" | tee -a $LF
    endif
  endif

  set RunList = `getrunlist $sess/$fsd $RunListFile`;
  if($status) then
    echo "$RunList" |& tee -a $LF
    exit 1;
  endif

  # Handle masks first
  foreach hemi ($hemilist)
    if(! $PerRun) then
      # Per-session
      set reg = $sess/$fsd/$regfile
      if(! -e $reg) then
        echo "ERROR: cannot find $reg" | tee -a $LF
        echo "Try running register-sess" | tee -a $LF
        exit 1;
      endif
      set maskstempath = $sess/$fsd/$maskdir/$maskname
      set mask = `stem2fname $maskstempath`
      if($status) then
        echo "$mask" | tee -a $LF
        echo "Try running mkbrainmask-sess" | tee -a $LF
        exit 1;
      endif
      set outmask = $sess/$fsd/$maskdir/$maskstem.$hemi$ExpKey.$outfmt
      set UpdateNeeded = `UpdateNeeded $outmask $reg $mask $b0dcmap`;
      if(! $UpdateOnly) set UpdateNeeded = 1;    
      if($UpdateNeeded) then
        set cmd = (mri_vol2surf --mov $mask --reg $reg \
          --trgsubject $trgsubject --interp nearest --projfrac $ProjFrac\
          --hemi $hemi --o $outmask --noreshape)
        if($UseCortexLabel) set cmd = ($cmd --cortex)
        if($trgsubject != $subject) set cmd = ($cmd --surfreg $SurfReg)
        if($UseB0DC) set cmd = ($cmd --vsm $b0dcmap $pedir)
        echo $cmd | tee -a $LF
        $cmd | tee -a $LF
        if($status) exit 1;
        set cmd = (mri_binarize --i $outmask --min .00001 --o $outmask)
        echo $cmd | tee -a $LF
        $cmd | tee -a $LF
        if($status) exit 1;
      else
        echo "$outmask does not need updating" | tee -a $LF
      endif
      continue;
    endif

    # Must be per-run to get here
    foreach Run ($RunList)
      echo "  $nthsess/$#SessList $sessid $Run $hemi ---------" |& tee -a $LF
      echo "    `date`"  |& tee -a $LF
      set funcdir = $sess/$fsd/$Run

      set reg = $sess/$fsd/$Run/$regfile
      if(! -e $reg) then
        echo "ERROR: cannot find $reg" | tee -a $LF
        echo "Try running register-sess with -per-run" | tee -a $LF
        exit 1;
      endif
      # Use only one mask for all runs so no pruning necessary
      #set maskstempath = $sess/$fsd/$maskdir/$maskname
      # This creates problems when there is motion or
      # or removed and replace subject in scanner
      # So go back to using run-based mask
      set maskstempath = $sess/$fsd/$Run/$maskdir/$maskname
      set mask = `stem2fname $maskstempath`
      if($status) then
        echo "$mask" | tee -a $LF
        echo "Try running mkbrainmask-sess with -per-run" | tee -a $LF
        exit 1;
      endif

      # Create a .pr mask here, then merge them together into a single mask 
later
      set outmask = $sess/$fsd/$Run/$maskdir/$maskstem.$hemi$ExpKey.pr.$outfmt
      set UpdateNeeded = `UpdateNeeded $outmask $reg $mask $b0dcmap`;
      if(! $UpdateOnly) set UpdateNeeded = 1;    
      if($UpdateNeeded) then
        set cmd = (mri_vol2surf --mov $mask --reg $reg \
          --trgsubject $trgsubject --interp nearest --projfrac $ProjFrac\
          --hemi $hemi --o $outmask --noreshape)
        if($UseCortexLabel) set cmd = ($cmd --cortex)
        if($trgsubject != $subject) set cmd = ($cmd --surfreg $SurfReg)
        if($UseB0DC) set cmd = ($cmd --vsm $b0dcmap $pedir)
        echo $cmd | tee -a $LF
        $cmd | tee -a $LF
        if($status) exit 1;
        set cmd = (mri_binarize --i $outmask --min .00001 --o $outmask)
        echo $cmd | tee -a $LF
        $cmd | tee -a $LF
        if($status) exit 1;
      else
        echo "$outmask does not need updating" | tee -a $LF
      endif
    end # loop over runs

    # Merge run-level masks and prune
    set prmasklist = ()
    foreach Run ($RunList)
      set prmask = $sess/$fsd/$Run/$maskdir/$maskstem.$hemi$ExpKey.pr.$outfmt
      set prmasklist = ($prmasklist $prmask)
    end
    set finalmask = $sess/$fsd/$maskdir/$maskstem.$hemi$ExpKey.pr.$outfmt
    set UpdateNeeded = `UpdateNeeded $finalmask $prmasklist`;
    if(! $UpdateOnly) set UpdateNeeded = 1;    
    if($UpdateNeeded) then
      set cmd = (mri_concat --o $finalmask --mean $prmasklist)
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) exit 1;      
      set cmd = (mri_binarize --i $finalmask --min 10e-10 --o $finalmask)
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) exit 1;      
      # Now copy it to each run, remove the .pr
      foreach Run ($RunList)
        set prmask = $sess/$fsd/$Run/$maskdir/$maskstem.$hemi$ExpKey.$outfmt
        cp $finalmask $prmask |& tee -a $LF
        if($status) exit 1;      
      end
    else
      echo "$finalmask does not need updating" | tee -a $LF
    endif
  end # loop over hemi

  # Now do time series data
  foreach hemi ($hemilist)
    foreach Run ($RunList)
      echo "  $nthsess/$#SessList $sessid $Run $hemi ---------" |& tee -a $LF
      echo "    `date`"  |& tee -a $LF
      set funcdir = $sess/$fsd/$Run
      set invol = `stem2fname $funcdir/$instem`
      if($status) then
        echo "$invol" |& tee -a $LF
        exit 1;
      endif

      # Get the mask and reg to use
      if($PerRun) then
        set outmask = $sess/$fsd/$Run/$maskdir/$maskstem.$hemi$ExpKey.$outfmt
        set reg = $sess/$fsd/$Run/$regfile
      else
        set outmask = $sess/$fsd/$maskdir/$maskstem.$hemi$ExpKey.$outfmt
        set reg = $sess/$fsd/$regfile
      endif

      set outvol = $funcdir/$outstem.$hemi$ExpKey.$outfmt
      set UpdateNeeded = `UpdateNeeded $outvol $invol $reg $outmask`;
      if(! $UpdateOnly) set UpdateNeeded = 1;
      if($UpdateNeeded == 0) then
        echo "    $sessid $Run Update not needed" | tee -a $LF
        continue
      endif

      set cmd = (mri_vol2surf --mov $invol --reg $reg \
        --trgsubject $trgsubject --interp $interp --projfrac $ProjFrac\
        --hemi $hemi --o $outvol --noreshape)
      if($UseCortexLabel) set cmd = ($cmd --cortex)
      if($trgsubject != $subject) set cmd = ($cmd --surfreg $SurfReg)
      if($UseB0DC) set cmd = ($cmd --vsm $b0dcmap $pedir)
      if($#volsurffwhm) set cmd = ($cmd --fwhm $volsurffwhm) # dont do for mask
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) exit 1;

      # Smooth raw data within mask
      if($fwhm != 0) then
        if($SaveUnsmoothed) cp $outvol $funcdir/$outstem0.$hemi$ExpKey.$outfmt
        set cmd = (mris_fwhm --s $trgsubject --hemi $hemi --smooth-only \
          --i $outvol --fwhm $fwhm --o $outvol --mask $outmask --no-detrend)
        echo $cmd | tee -a $LF
        $cmd | tee -a $LF
        if($status) exit 1;
      endif
    end  # Loop over runs
  end # Loop over hemis

end  # foreach sess ($SessList)

echo "" |& tee -a $LF
date |& tee -a $LF
echo "rawfunc2surf-sess completed " |& tee -a $LF

exit 0;

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

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

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

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

    case "-runlistfile":
    case "-rlf":
      if ( $#argv == 0) goto arg1err;
      set RunListFile = $argv[1]; shift;
      breaksw

    case "-per-run":
    case "-perrun":
      set PerRun = 1;
      breaksw

    case "-per-session":
    case "-no-per-run":
    case "-no-perrun":
      set PerRun = 0;
      #set ExpKeyNeeded = 1;
      breaksw

    case "-surfreg":
      if ( $#argv == 0) goto arg1err;
      set SurfReg = $argv[1]; shift;
      set ExpKeyNeeded = 1;
      breaksw

    case "-expkey":
      if($#argv < 1) goto arg1err;
      set ExpKey = $argv[1]; shift;
      set ExpKey = (.$ExpKey); # prepend a dot
      breaksw

    case "-update":
      set UpdateOnly = 1;
      breaksw

    case "-force":
      set UpdateOnly = 0;
      breaksw

    case "-nearest":
      set interp = "nearest"e
      set ExpKeyNeeded = 1;
      breaksw

    case "-trilin":
      set interp = "trilin"
      breaksw

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

    case "-stc":
    case "-sliceorder":
    case "-so":
      if ( $#argv == 0) goto arg1err;
      set SliceOrder = $argv[1]; shift;
      if($SliceOrder != siemens && $SliceOrder != up && $SliceOrder != down && \
         $SliceOrder != odd && $SliceOrder != even && $SliceOrder != none) then
         echo "ERROR: -stc is $SliceOrder, must be siemens, up, down, odd, 
even, or none"
         exit 1;
      endif
      breaksw

    case "-sdf":
      if ( $#argv == 0) goto arg1err;
      set SliceDelayFile = $argv[1]; shift;
      set DoSTC = 1;
      breaksw

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

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

    case "-b0dc":
    case "-b0dcor":
    case "-vsm":
      set UseB0DC = 1;
      set ExpKey = ".b0dc"
      breaksw

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

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

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

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

    case "-lh":
      set hemilist = ($hemilist lh);
      breaksw

    case "-rh":
      set hemilist = ($hemilist rh);
      breaksw

    case "-self":
      set DoSelf = 1;
      breaksw

    # should not use either of these
    case "-o":
    case "-outstem":
      if ( $#argv == 0) goto arg1err;
      set outstem = $argv[1]; shift;
      breaksw

    case "-mask":
      # output mask stem
      if ( $#argv == 0) goto arg1err;
      set maskstem = $argv[1]; shift;
      breaksw

    case "-save-unsmoothed":
      set SaveUnsmoothed = 1;
      breaksw

    case "-no-mc":
      set mc = ""
      breaksw

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

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

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

    case "-cwd":
      breaksw

    case "-s":
    case "-sf":
    case "-df":
    case "-d":
    case "-g":
      shift;
      breaksw

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

end

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

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

if($#fwhm == 0) then
  echo "ERROR: you must enter a FWHM. Use 0 for no smoothing."
  exit 1;
endif
if($ExpKeyNeeded && $#ExpKey == 0) then
  echo "ERROR: experts key needed (-expkey)"
  exit 1;
endif

if($#instem == 0) then
  # Note that if no MC, then there will be no "pr" appended
  set instem = f${mc}
  if($mc != "" && $PerRun)   set instem = fmcpr
  if($#SliceOrder != 0) set instem = $instem.$SliceOrder
  if($#SliceDelayFile != 0) set instem = $instem.sdf
endif

if($DoSelf) then
  set subjstr = self
else
  set subjstr = $trgsubject
endif

if($#outstem == 0) set outstem = $instem
set outstem0 = $outstem.sm0.$subjstr; # for saving unsmoothed
if($#volsurffwhm == 0) then
  set outstem  = $outstem.sm$fwhm.$subjstr; # hemi appended later
else
  set outstem  = $outstem.vsm$volsurffwhm.sm$fwhm.$subjstr; # hemi appended 
later
endif

if($#maskstem == 0) set maskstem = $maskname
set maskstem = $maskstem.$subjstr # hemi appended later

if($#hemilist == 0) set hemilist = (lh rh);
echo "instem $instem"
echo "outstem $outstem.hemi"

if($#regfile == 0) then
  if(! $UseB0DC) set regfile = register.dof$RegDOF.lta
  if($UseB0DC)   set regfile = register.dof$RegDOF.b0dc.lta
endif

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

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

############--------------##################
usage_exit:
  echo "rawfunc2surf-sess"
  echo ""
  echo " Session Arguments (some required)"
  echo "  -sf sessidfile  ..."
  echo "  -df srchdirfile ..."
  echo "  -s  sessid      ..."
  echo "  -d  srchdir     ..."
  echo ""
  echo "  -fwhm FWHMmm : smooth by FWHM mm (enter 0 for no smoothing)"
  echo ""
  echo "Optional Arguments"
  echo "  -i instem    :  fmcpr (default is fmcpr)"
  echo "  -fsd dir     : functional subdirectory ($fsd)"
  echo "  -self : map to native subject surface instead of fsaverage"
  echo ""
  echo "Expert Options"
  echo "  -reg regfile : default is register.dof$RegDOF.lta"
  echo "  -nearest     : use nearest neighbor interp (default is trilin)"
  echo "  -surfreg SurfReg : change from $SurfReg"
  echo "  -per-session : use session-level registration and mask instead of 
-per-run"
  echo "  -no-cortex-label : do not use cortex label for masking"
  echo "  -dof DOF"
  echo ""
  echo "Other options"
  echo "  -save-unsmoothed : save sm0 in addition to smoothed data"
  echo "  -update : only run if update is needed"
  echo "  -force : force an update (default)"
  echo "  -version       : print version and exit"
  echo "  -debug"
  echo ""
  if(! $PrintHelp ) exit 1;

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

Resamples raw functional data onto the cortical surface.


#! /bin/csh -f

#
# rawfunc2tal-sess
#
# Original Author: Doug Greve
#
# Copyright © 2021
# The General Hospital Corporation (Boston, MA). 
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-b...@nmr.mgh.harvard.edu
#

set VERSION = 'rawfunc2tal-sess @FS_VERSION@';

set inputargs = ($argv);

set fsd        = bold;
set instem     = ();
set outstem    = ();
set regfile    = ();
set RegDOF     = 6;
set target = mni305
set res = 2;
set talxfm = talairach.xfm
set interp = trilin
set PerRun = 1;
set maskname = brain
set maskdir = masks
set maskstem = ();
set fwhm = ();
set MaskedSmoothing = 1;
set RunListFile = ();
set UpdateOnly = 0;
set ExpKey = ();
set ExpKeyNeeded = 0;
set SliceOrder = ();
set SliceDelayFile = ();
set UseB0DC = 0;
set b0dcmapstem = b0dcmap
set ApplySubCortMask = 1;
set UseCVS = 0;
set mc = mc

set nolog = 0;
set debug = 0;
set PrintHelp = 0;

set outfmt = nii
if($?FSF_OUTPUT_FORMAT) then
  set outfmt = $FSF_OUTPUT_FORMAT
endif

## If there are no options, just print the usage ##
if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e  -version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;  
  goto usage_exit;
endif

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:

set SessList = `getsesspath $inputargs`;
if($status || $#SessList == 0) then
  getsesspath $inputargs 
  echo "ERROR: cannot find any sessions"
  exit 1;
endif

goto check_params;
check_params_return:

set ProjectDir = `pwd`;

## Loop through each session ##
@ nthsess = 0;
foreach sess ($SessList)
  set sessid = `basename $sess`
  @ nthsess = $nthsess + 1;

  ##### Create a log file ######
  set LF = /dev/null
  if(! $nolog) then
    set logdir = $ProjectDir/log;
    mkdir -p $logdir
    set LF = $logdir/rawfunc2tal-sess.$sessid.$fsd.$outstem$ExpKey.log
    if(-e $LF) mv $LF $LF.old
  endif
  echo "rawfunc2tal-sess log file" >> $LF
  echo $VERSION >> $LF
  uname -a >> $LF
  date >> $LF
  pwd >> $LF
  echo $0 $inputargs  >> $LF 
  echo UpdateOnly $UpdateOnly >> $LF 
  set subject = `cat $sess/subjectname`

  echo "------------------------------ " |& tee -a $LF
  echo "$nthsess/$#SessList $sessid $subject" |& tee -a $LF

  ## Make sure the functional subdirectory exists ##
  if(! -e $sess/$fsd) then
    echo "ERROR: $sess/$fsd does not exist" |& tee -a $LF
    exit 1;
  endif

  set b0dcmap = ();
  set pedir = 2; #2=row direction
  if($UseB0DC) then
    set b0dcmap = `stem2fname $sess/$fsd/$b0dcmapstem`;
    if($status) then
      echo "$b0dcmap"|& tee -a $LF
      exit 1;
    endif
    set pedirfile = $sess/$fsd/$b0dcmapstem.pedir.txt
    if(-e $pedirfile) then
      set pedir = `cat $pedirfile`
      echo "Setting PE direction so $pedir" | tee -a $LF
    endif
  endif

  if(! $PerRun) then
    set reg = $sess/$fsd/$regfile
    if(! -e $reg) then
      echo "ERROR: cannot find $reg" | tee -a $LF
      echo "Try running register-sess" | tee -a $LF
      exit 1;
    endif
    set maskstempath = $sess/$fsd/$maskdir/$maskname
    set mask = `stem2fname $maskstempath`
    if($status) then
      echo "$mask" | tee -a $LF
      echo "Try running mkbrainmask-sess" | tee -a $LF
      exit 1;
    endif
    # Create the mask in the mni305/CVS space, create .pr then merge later
    set outmask = $sess/$fsd/$maskdir/$maskstem$ExpKey.$outfmt
    set UpdateNeeded = `UpdateNeeded $outmask $reg $mask $b0dcmap`;
    if(! $UpdateOnly) set UpdateNeeded = 1;    
    if($UpdateNeeded) then
      if($UseCVS == 0) then
        set cmd = (mri_vol2vol --mov $mask --reg $reg \
          --tal --talres $res --talxfm $talxfm --nearest \
          --no-save-reg --o $outmask)
        if($UseB0DC) set cmd = ($cmd --vsm $b0dcmap $pedir)
      else
        set gcam = 
$SUBJECTS_DIR/$subject/cvs/final_CVSmorph_tocvs_avg35_inMNI152.m3z
        if(! -e $gcam) then
          echo "ERROR: cannot find $gcam" | tee -a $LF
          exit 1;
        endif
        set dstreg = 
$FREESURFER_HOME/subjects/cvs_avg35_inMNI152/mri.2mm/register.lta
        set cmd = (mri_vol2vol --vsm-pedir $pedir --gcam $mask $reg $gcam 
$dstreg)
        if($UseB0DC) set cmd = ($cmd $b0dcmap)
        if(! $UseB0DC) set cmd = ($cmd 0)
        set cmd = ($cmd 0 $outmask)
      endif
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) exit 1;
      # Take intersection with whole brain or subcort mask
      set mask = $brainmask
      if($ApplySubCortMask) set mask = $subcortmask
      set cmd = (mri_mask $outmask $mask $outmask)
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) exit 1;
    else
      echo "$outmask does not need updating" | tee -a $LF
    endif
  endif

  set RunList = `getrunlist $sess/$fsd $RunListFile`;
  if($status) then
    echo "$RunList" |& tee -a $LF
    exit 1;
  endif

  # Build masks for each run
  if($PerRun) then
    foreach Run ($RunList)
      echo "  $nthsess/$#SessList $sessid $Run ----------------" |& tee -a $LF
      echo "    `date`"  |& tee -a $LF
      set funcdir = $sess/$fsd/$Run

      set reg = $sess/$fsd/$Run/$regfile
      if(! -e $reg) then
        echo "ERROR: cannot find $reg" | tee -a $LF
        echo "Try running register-sess with -per-run" | tee -a $LF
        exit 1;
      endif
      set maskstempath = $sess/$fsd/$Run/$maskdir/$maskname
      set mask = `stem2fname $maskstempath`
      if($status) then
        echo "$mask" | tee -a $LF
        echo "Try running mkbrainmask-sess with -per-run" | tee -a $LF
        exit 1;
      endif

      # Create the mask in the mni305/CVS space, create .pr then merge later
      set outmask = $sess/$fsd/$Run/$maskdir/$maskstem$ExpKey.pr.$outfmt
      set UpdateNeeded = `UpdateNeeded $outmask $reg $mask $b0dcmap`;
      if(! $UpdateOnly) set UpdateNeeded = 1;    
      if($UpdateNeeded) then
        if($UseCVS == 0) then
          set cmd = (mri_vol2vol --mov $mask --reg $reg \
            --tal --talres $res --talxfm $talxfm --nearest \
            --no-save-reg --o $outmask)
          if($UseB0DC) set cmd = ($cmd --vsm $b0dcmap $pedir)
        else
          set gcam = 
$SUBJECTS_DIR/$subject/cvs/final_CVSmorph_tocvs_avg35_inMNI152.m3z
          if(! -e $gcam) then
            echo "ERROR: cannot find $gcam" | tee -a $LF
            exit 1;
          endif
          set dstreg = 
$FREESURFER_HOME/subjects/cvs_avg35_inMNI152/mri.2mm/register.lta
          set cmd = (mri_vol2vol --vsm-pedir $pedir --gcam $mask $reg $gcam 
$dstreg)
          if($UseB0DC) set cmd = ($cmd $b0dcmap)
          if(! $UseB0DC) set cmd = ($cmd 0)
          set cmd = ($cmd 0 $outmask)
        endif
        echo $cmd | tee -a $LF
        $cmd | tee -a $LF
        if($status) exit 1;
        # Take intersection with whole brain
        set mask = $brainmask
        if($ApplySubCortMask) set mask = $subcortmask
        set cmd = (mri_mask $outmask $mask $outmask)
        echo $cmd | tee -a $LF
        $cmd | tee -a $LF
        if($status) exit 1;
      else
        echo "$outmask does not need updating" | tee -a $LF
      endif
    end  # Loop over runs

    # Merge run-level masks and prune
    set prmasklist = ()
    foreach Run ($RunList)
      set prmask = $sess/$fsd/$Run/$maskdir/$maskstem$ExpKey.pr.$outfmt
      set prmasklist = ($prmasklist $prmask)
    end
    set finalmask = $sess/$fsd/$maskdir/$maskstem$ExpKey.$outfmt
    set UpdateNeeded = `UpdateNeeded $finalmask $prmasklist`;
    if(! $UpdateOnly) set UpdateNeeded = 1;    
    if($UpdateNeeded) then
      set cmd = (mri_concat --o $finalmask --mean $prmasklist)
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) exit 1;      
      set cmd = (mri_binarize --i $finalmask --min 10e-10 --o $finalmask)
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) exit 1;      
      # Now copy it to each run, remove the .pr
      foreach Run ($RunList)
        set prmask = $sess/$fsd/$Run/$maskdir/$maskstem$ExpKey.$outfmt
        cp $finalmask $prmask |& tee -a $LF
        if($status) exit 1;      
      end
    else
      echo "$finalmask does not need updating" | tee -a $LF
    endif
  endif

  # Convert the native functional space data to mni305/cvs
  foreach Run ($RunList)
    echo "  $nthsess/$#SessList $sessid $Run ----------------" |& tee -a $LF
    echo "    `date`"  |& tee -a $LF
    set funcdir = $sess/$fsd/$Run

    # Get the mask and reg to use
    if($PerRun) then
      set outmask = $sess/$fsd/$Run/$maskdir/$maskstem$ExpKey.$outfmt
      set reg = $sess/$fsd/$Run/$regfile
    else
      set outmask = $sess/$fsd/$maskdir/$maskstem$ExpKey.$outfmt
      set reg = $sess/$fsd/$regfile
    endif
    set invol = `stem2fname $funcdir/$instem`
    if($status) then
      echo "$invol" |& tee -a $LF
      exit 1;
    endif

    set outvol = $funcdir/$outstem$ExpKey.$outfmt
    set UpdateNeeded = `UpdateNeeded $outvol $invol $reg $outmask`;
    if(! $UpdateOnly) set UpdateNeeded = 1;    
    if($UpdateNeeded == 0) then
      echo "    $sessid $Run Update not needed" | tee -a $LF
      continue
    endif

    if($UseCVS == 0) then
      set cmd = (mri_vol2vol --mov $invol --reg $reg \
        --tal --talres $res --talxfm $talxfm --interp $interp \
        --no-save-reg --o $outvol)
      if($UseB0DC) set cmd = ($cmd --vsm $b0dcmap $pedir)
    else
      set gcam = 
$SUBJECTS_DIR/$subject/cvs/final_CVSmorph_tocvs_avg35_inMNI152.m3z
      if(! -e $gcam) then
        echo "ERROR: cannot find $gcam" | tee -a $LF
        exit 1;
      endif
      set dstreg = 
$FREESURFER_HOME/subjects/cvs_avg35_inMNI152/mri.2mm/register.lta
      set cmd = (mri_vol2vol --vsm-pedir $pedir --gcam $invol $reg $gcam 
$dstreg)
      if($UseB0DC) set cmd = ($cmd $b0dcmap)
      if(! $UseB0DC) set cmd = ($cmd 0)
      set cmd = ($cmd 0 $outvol)
    endif
    echo $cmd | tee -a $LF
    $cmd | tee -a $LF
    if($status) exit 1;

    # Smooth if desired
    if($fwhm > 0) then
      set cmd = (mri_fwhm --i $outvol --o $outvol --smooth-only) 
      if($#fwhm)   set cmd = ($cmd --fwhm $fwhm); # 3D smoothing
      if($MaskedSmoothing) set cmd = ($cmd --mask $outmask)
      echo $cmd |& tee -a $LF
      $cmd |& tee -a $LF
      if($status) exit 1;
    endif

  end  # Loop over runs

end  # foreach sess ($SessList)

echo "" |& tee -a $LF
date |& tee -a $LF
echo "rawfunc2tal-sess completed " |& tee -a $LF

exit 0;

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

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

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

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

    case "-runlistfile":
    case "-rlf":
      if ( $#argv == 0) goto arg1err;
      set RunListFile = $argv[1]; shift;
      breaksw

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

    case "-cvs"
      set target = cvs_avg35_inMNI152;
      set UseCVS = 1;
      set res = 2;
      breaksw

    case "-no-masked-smooth":
      set MaskedSmooth = 0;
      set ExpKeyNeeded = 1;
      breaksw

    case "-per-run":
    case "-perrun":
      set PerRun = 1;
      breaksw

    case "-per-session":
    case "-no-per-run":
    case "-no-perrun":
      set PerRun = 0;
      #set ExpKeyNeeded = 1;
      breaksw

    case "-update":
      set UpdateOnly = 1;
      breaksw

    case "-force":
      set UpdateOnly = 0;
      breaksw

    case "-nearest":
      set interp = "nearest"
      set ExpKeyNeeded = 1;
      breaksw

    case "-subcort-mask":
    case "-subcort":
      set ApplySubCortMask = 1;
      breaksw
    case "-no-subcort-mask":
    case "-no-subcort":
      set ApplySubCortMask = 0;
      breaksw

    case "-trilin":
      set interp = "trilin"
      breaksw

    case "-1mm":
      set res = 1;
      breaksw

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

    case "-stc":
    case "-sliceorder":
    case "-so":
      if ( $#argv == 0) goto arg1err;
      set SliceOrder = $argv[1]; shift;
      if($SliceOrder != siemens && $SliceOrder != up && $SliceOrder != down && \
         $SliceOrder != odd && $SliceOrder != even && $SliceOrder != none) then
         echo "ERROR: -stc is $SliceOrder, must be siemens, up, down, odd, 
even, or none"
         exit 1;
      endif
      breaksw

    case "-sdf":
      if ( $#argv == 0) goto arg1err;
      set SliceDelayFile = $argv[1]; shift;
      set DoSTC = 1;
      breaksw

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

    case "-expkey":
      if($#argv < 1) goto arg1err;
      set ExpKey = $argv[1]; shift;
      set ExpKey = (.$ExpKey); # prepend a dot
      breaksw

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

    case "-b0dc":
    case "-b0dcor":
    case "-vsm":
      set UseB0DC = 1;
      set ExpKey = ".b0dc"
      breaksw

    # these should not be used
    case "-o":
    case "-outstem":
      if ( $#argv == 0) goto arg1err;
      set outstem = $argv[1]; shift;
      breaksw
    case "-mask":
      # output mask stem
      if ( $#argv == 0) goto arg1err;
      set maskstem = $argv[1]; shift;
      breaksw

    case "-no-mc":
      set mc = ""
      breaksw

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

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

    case "-cwd":
      breaksw

    case "-s":
    case "-sf":
    case "-df":
    case "-d":
    case "-g":
      shift;
      breaksw

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

end

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

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

if($#fwhm == 0) then
  echo "ERROR: you must enter a FWHM. Use 0 for no smoothing."
  exit 1;
endif
if($ExpKeyNeeded && $#ExpKey == 0) then
  echo "ERROR: experts key needed (-expkey)"
  exit 1;
endif

if($#instem == 0) then
  # Note that if no MC, then there will be no "pr" appended
  set instem = f${mc}
  if($mc != "" && $PerRun)   set instem = fmcpr
  if($#SliceOrder != 0) set instem = $instem.$SliceOrder
  if($#SliceDelayFile != 0) set instem = $instem.sdf
endif

if($#outstem == 0) set outstem = $instem
set outstem = $outstem.sm$fwhm.$target.$res"mm"

if($#maskstem == 0) set maskstem = $maskname
set maskstem = $maskstem.$target.$res"mm"

if($#regfile == 0) then
  if(! $UseB0DC) set regfile = register.dof$RegDOF.lta
  if($UseB0DC)   set regfile = register.dof$RegDOF.b0dc.lta
endif

if($UseCVS == 0) then
  if($res == 2) then
    set subcortmask = 
$FREESURFER_HOME/subjects/fsaverage/mri.2mm/subcort.mask.mgz
    set brainmask = $FREESURFER_HOME/subjects/fsaverage/mri.2mm/brainmask.mgz
  else
    set subcortmask = 
$FREESURFER_HOME/subjects/fsaverage/mri/subcort.mask.1mm.mgz
    set brainmask = $FREESURFER_HOME/subjects/fsaverage/mri/brainmask.mgz
  endif
else
  set subcortmask = 
$FREESURFER_HOME/subjects/cvs_avg35_inMNI152/mri.2mm/subcort.mask.mgz
  set brainmask = 
$FREESURFER_HOME/subjects/cvs_avg35_inMNI152/mri.2mm/brainmask.mgz
endif
if($ApplySubCortMask && ! -e $subcortmask) then
  echo "ERROR: cannot find $subcortmask"      
  exit 1;
endif


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

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

############--------------##################
usage_exit:
  echo "rawfunc2tal-sess"
  echo ""
  echo " Session Arguments (some required)"
  echo "  -sf sessidfile  ..."
  echo "  -df srchdirfile ..."
  echo "  -s  sessid      ..."
  echo "  -d  srchdir     ..."
  echo ""
  echo "  -fwhm FWHMmm : smooth by FWHM mm  (enter 0 for no smoothing)"
  echo ""
  echo " Optional Arguments"
  echo "  -1mm         : set output resolution to 1mm (default is 2mm)"
  echo "  -i instem  : default is fmcpr"
  echo "  -fsd dir     : functional subdirectory ($fsd)"
  echo "  -rlf RLF     : run-list file"
  echo ""
  echo "Expert Options"
  echo "  -no-masked-smooth : do not mask when smoothing"
  echo "  -nearest     : use nearest neighbor interp (default is trilin)"
  echo "  -xfm tal.xfm : xfm file found in subject/mri/transforms (default is 
$talxfm)"
  echo "  -reg regfile : default is register.dof$RegDOF.lta"
  echo "  -per-session : use session-level registration and mask instead of 
-per-run"
  echo "  -no-subcort-mask : do not apply subcortical mask"
  echo "  -cvs : use cvs_avg35_inMNI152 instead of MNI305 (res fixed at 2mm)"
  echo "  -dof DOF"
  echo ""
  echo "Other options"
  echo "  -update : only run if update is needed"
  echo "  -force : force an update (default)"
  echo "  -version       : print version and exit"
  echo "  -debug"
  echo ""
  if(! $PrintHelp ) exit 1;

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

Resamples raw data into "talairach" space. This is MNI305 space
sampled at 2mm isotropic.


_______________________________________________
Freesurfer mailing list
Freesurfer@nmr.mgh.harvard.edu
https://mail.nmr.mgh.harvard.edu/mailman/listinfo/freesurfer
The information in this e-mail is intended only for the person to whom it is 
addressed.  If you believe this e-mail was sent to you in error and the e-mail 
contains patient information, please contact the Mass General Brigham 
Compliance HelpLine at https://www.massgeneralbrigham.org/complianceline 
<https://www.massgeneralbrigham.org/complianceline> .
Please note that this e-mail is not secure (encrypted).  If you do not wish to 
continue communication over unencrypted e-mail, please notify the sender of 
this message immediately.  Continuing to send or respond to e-mail after 
receiving this message means you understand and accept this risk and wish to 
continue to communicate over unencrypted e-mail. 

Reply via email to