#!/usr/bin/tcsh -f

#
# make_average_surface
#
# Creates average surfaces and curvatures from a set of subjects.
#
# --help option will show usage
#
# Original Author: Doug Greve
#
# 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
#
#

# uncomment this to increase number of allowable open files to maximum:
#limit descriptors unlimited

set VERSION = 'make_average_surface mockbuild-local';
setenv FIX_VERTEX_AREA

set PrintHelp = 0;
set UseSymLink = 1;
set sdout = ();
set inputargs = ($argv);
set surflist = (white pial)
set ForceUpdate = 0

if ( $?SUBJECTS) then
  set SUBJECTS=($SUBJECTS)
endif
if ( $?SUBJECTS_DIR) then
  set SUBJECTS_DIR=($SUBJECTS_DIR)
endif
set average_subject=average
set sphere_reg=sphere.reg
set transform_fname = "talairach.xfm"
set XFORM_FLAG="-X $transform_fname"
set ico_no=7
set DoXHemi = 0;
set topdir = ();
set DoTemplateOnly = 0;
set hemilist = ();
set measlist = ()
set UseAnnot = 1;
set UseAnnotTemplate = 0;
set annotlist = ()
set DoCortexLabel = 1;
set NoSurf2Surf = "";
set DestLTA = ()
set ConfFlag = "-conform"
set threads = 1

# these should match latest declarations in recon-all
set DESIKAN_GCS = curvature.buckner40.filled.desikan_killiany.2010-03-25.gcs
set DESTRIEUX_GCS = destrieux.simple.2009-07-29.gcs

# note: SUBJECTS can be set by --subjects
# SUBJECTS_DIR can be set by --sdir
# average_subject can be set by --out
# sphere_reg can be set by --surf-reg
# transform_fname can be set by --xform (default is no file specified)
# XFORM_FLAG appends -X to transform_fname if --xform is specified

if($#argv == 0) then
  # zero args is allowed only if SUBJECTS env var is declared
  if ( ! $?SUBJECTS) then
    goto usage_exit;
  endif
endif

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:


# This will put the data under $sdout (SUBJECTS_DIR by default)
set ddir = ${sdout}/${average_subject}

mkdir -p ${ddir} \
        ${ddir}/surf \
        ${ddir}/mri \
        ${ddir}/mri/transforms \
        ${ddir}/scripts \
        ${ddir}/label \
        ${ddir}/stats
cd $sdout/${average_subject}

set LF = ${ddir}/scripts/make_average_surface.log
if(-e $LF) mv $LF $LF.bak

echo "" | tee -a $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" | tee -a $LF
echo $0 $inputargs | tee -a $LF
echo "" | tee -a $LF
echo $VERSION | tee -a $LF
date | tee -a $LF
pwd | tee -a $LF
echo "output ddir is $sdout" | tee -a $LF
id | tee -a $LF

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

#
# Begin script guts...
#
echo ==================== | tee -a $LF
echo make_average_surface | tee -a $LF
echo ==================== | tee -a $LF
date | tee -a $LF
pwd | tee -a $LF
echo $0 | tee -a $LF
echo $inputargs | tee -a $LF
echo input subjects: ${SUBJECTS}  | tee -a $LF
echo output subject: ${average_subject}  | tee -a $LF
echo transform_fname $transform_fname   | tee -a $LF

set mni305 = $FREESURFER_HOME/average/mni305.cor.mgz
if($transform_fname == talairach.xfm) then
  # Copy MNI 305 to output mri dir
  if(! -e $mni305) then
    echo "ERROR: cannot find $mni305"
    exit 1;
  endif
  cp $mni305 $sdout/${average_subject}/mri
  # Set the MNI305 xfm fname to 'auto'
  set mnivol = $sdout/${average_subject}/mri/mni305.cor.mgz
  set cmd = (mri_add_xform_to_header -c auto $mnivol $mnivol)
  echo $cmd | tee -a $LF
  $cmd  | tee -a $LF
  if($status) exit 1;
  set templatevol = $mni305
else 
  # Set the volume geometry template to the average subject orig. If that
  # does not exist, create a template from the first subject's orig. The
  # content does not matter, just the volume geom. In theory, should get
  # this from the xform itself
  set templatevol = $sdout/${average_subject}/mri/orig.mgz
  if(! -e $templatevol) then
    set templatevol = $sdout/${average_subject}/mri/volgeom.template.mgz
    set src = $SUBJECTS_DIR/$SUBJECTS[1]/mri/orig.mgz
    set xfm = $SUBJECTS_DIR/$SUBJECTS[1]/mri/transforms/$transform_fname
    set ud = `UpdateNeeded $templatevol $xfm $src`
    if($ud || $ForceUpdate) then
      set cmd = (mri_convert $src -at $xfm $templatevol)
      echo $cmd |& tee -a $LF
      $cmd |& tee -a $LF
      if($status) exit 1
    endif
  endif
  set XFORM_FLAG = "$XFORM_FLAG -t $templatevol"
endif

# Create a file with the list of subjects (will not include xhemi)
set subjlistfile = `fs_temp_file`
rm -f $subjlistfile
foreach s ($SUBJECTS)
  echo $s >> $subjlistfile
end
cp $subjlistfile list.subjects.txt
set subjlistfile = $sdout/$average_subject/list.subjects.txt

# These are files that will exist when making surfaces from
# subcortical structures with seg2surf (DNG)
set fname = $SUBJECTS_DIR/$SUBJECTS[1]/rgb.dat
if(-e $fname) then
  cp $fname $sdout/$average_subject
endif
set fname = $SUBJECTS_DIR/$SUBJECTS[1]/segname
if(-e $fname) then
  cp $fname $sdout/$average_subject
endif

# Include cross-hemi registration
if($DoXHemi) then
  set tmp = ();
  foreach s ($SUBJECTS)
    set tmp = ($tmp $s $s/xhemi)
  end
  set SUBJECTS = ($tmp);
endif

#------------------------------------------------------------
# Make the lh and rh template first so that other jobs can be started
foreach hemi ($hemilist)
  echo ""  | tee -a $LF
  # ------------------------------------------------------------------
  echo "#@# Making $hemi registration template ---------"  | tee -a $LF
  set atlas = $hemi.reg.template.tif
  set cmd = (mris_make_template -norot)
  # In general, don't use annot for the template; this has not been
  # fully tested and may cause some problems. It is consistent with
  # recon-all and surfreg to not use the annot, so, if you do use it,
  # make sure that you turn on using the annot during the reg in those
  # programs.
  if($UseAnnotTemplate) set cmd = ($cmd -annot aparc)
  set cmd = ($cmd $hemi $sphere_reg $SUBJECTS $atlas)
  pwd | tee -a $LF
  echo $cmd | tee -a $LF
  $cmd |& tee -a $LF
  if($status) exit(1);
end

#------------------------------------------------------------
# Now do everything else
foreach hemi ($hemilist)
  if($DoTemplateOnly) continue;

  echo ""  | tee -a $LF
  cd $sdout/$average_subject

  #--------------------------------------------------------------
  foreach surf ($surflist)
    echo "#@# Making average $hemi.$surf surface ---------------------"  | tee -a $LF
    date  | tee -a $LF
    set cmd = (mris_make_average_surface $NoSurf2Surf $ConfFlag $DestLTA $XFORM_FLAG \
                -threads $threads -i $ico_no -o $surf -sdir-out $sdout\
                ${hemi} \
                ${surf} ${sphere_reg} \
                ${average_subject} \
                $SUBJECTS )
    pwd  | tee -a $LF
    echo $cmd  | tee -a $LF
    $cmd |& tee -a $LF
    if($status) then
      echo "mris_average_surface failed"  | tee -a $LF
      exit 1;
    endif
    echo ""  | tee -a $LF
  end # loop over surfaces
  pushd surf
  ln -sf $hemi.white $hemi.orig
  popd

  #--------------------------------------------------------------
  # Create sphere and sphere.reg.  mris_make_average_surface creates
  # its own sphere.reg (unless using the surf2surf option) so delete
  # it and copy ico
  rm -f surf/$hemi.$sphere_reg
  if($ico_no == 7) then
    # for historical reasons, use ?h.sphere.reg for ico7
    set icoreg = ${FREESURFER_HOME}/average/surf/${hemi}.sphere.reg 
  else
    set icoreg = ${FREESURFER_HOME}/average/surf/${hemi}.sphere.ico$ico_no.reg 
  endif
  set ud = (`UpdateNeeded surf/$hemi.sphere $templatevol $icoreg`)
  if($ud || $ForceUpdate) then
    set cmd = (mris_convert --vol-geom $templatevol $icoreg surf/$hemi.sphere)
    echo $cmd  | tee -a $LF
    $cmd |& tee -a $LF
    if($status) then
      echo "mris_convert failed"  | tee -a $LF
      exit 1;
    endif
  endif

  # Create a link to sphere.reg (want to do this? or reg to fsaverage?)
  if($UseSymLink) then
    cd surf
    ln -sf  $hemi.sphere $hemi.sphere.reg
    ln -sf  $hemi.sphere $hemi.$average_subject.sphere.reg
    cd ..
  else
    cp  surf/$hemi.sphere surf/$hemi.sphere.reg
    cp  surf/$hemi.sphere surf/$hemi.$average_subject.sphere.reg
  endif
  echo "---------------------------------------------------"  | tee -a $LF
  echo "" | tee -a $LF

  #--------------------------------------------------------------
  echo "#@# Smoothing, inflating, etc $hemi ----------------" | tee -a $LF
  cd $sdout/${average_subject}/surf
  pwd | tee -a $LF

  # Smooth white to get smoothwm (should average the indiv smoothwms?)
  set ud = `UpdateNeeded ./${hemi}.smoothwm ./${hemi}.white `
  if($ud || $ForceUpdate) then
    set cmd = (mris_smooth -nw -n 5 ./${hemi}.white ./${hemi}.smoothwm)
    echo $cmd |& tee -a $LF
    $cmd | tee -a $LF
    if($status) exit 1;
    echo "" | tee -a $LF
  endif

  # Inflate the smoothwm
  set ud = `UpdateNeeded ./${hemi}.inflated ./${hemi}.smoothwm`
  if($ud || $ForceUpdate) then
    set niters = "-n 15";
    if($ico_no <= 5) set niters = "-n 2";
    set cmd = (mris_inflate -dist .01 -f .001 -no-save-sulc $niters ./${hemi}.smoothwm ./${hemi}.inflated)
    echo $cmd |& tee -a $LF
    $cmd | tee -a $LF
    if($status) exit 1;
    echo "" | tee -a $LF
  endif

  cd $sdout/$average_subject

  # Create average annot
  if($UseAnnot) then
    foreach annot ($annotlist)
      set cmd = (annot2std --o label/$hemi.$annot.annot --$hemi \
        --f $subjlistfile --t $average_subject --a $annot \
        --srcsurfreg $sphere_reg --trgsurfreg sphere.reg --overwrite)
      if($DoXHemi) set cmd = ($cmd --xhemi)
      echo $cmd | tee -a $LF
      $cmd |& tee -a $LF
      if($status) exit 1
    end

    # Create cortex label from Christophe's aparc
    if($DoCortexLabel) then
      set annot = $ddir/label/$hemi.aparc.a2009s.annot
      if(! -e $annot) then
        echo "ERROR: cannot find $annot" |& tee -a $LF
        exit 1;
      endif
      set ctxlabel = $ddir/label/$hemi.cortex.label
      set white = $ddir/surf/$hemi.white
      set ud = `UpdateNeeded $ctxlabel $annot $white`
      if($ud || $ForceUpdate) then
        set cmd = (mri_cor2label --i $annot --thresh 0.5 --surf-path $white --l $ctxlabel)
        echo $cmd | tee -a $LF
        $cmd |& tee -a $LF
        if($status) exit 1
      endif
    endif # DoCortexLabel
  endif # UseAnnot

  # Create average surface measures
  foreach meas ($measlist)
    set measout = $ddir/surf/stack.$hemi.$meas.mgh
    set cmd = (mris_preproc --out $measout  --f $subjlistfile \
      --target $average_subject --hemi $hemi --meas $meas \
      --srcsurfreg $sphere_reg --log $ddir/scripts/mris_preproc.$hemi.$meas.log)
    if($DoCortexLabel == 0 || $meas == sulc || $meas == curv) set cmd = ($cmd --no-cortex-only)
    if($DoXHemi) set cmd = ($cmd --xhemi)
    echo $cmd | tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1
    # Compute average across subject
    set avgmeas = $ddir/surf/$hemi.$meas.avg.mgh
    if($meas == area) set avgmeas = $ddir/surf/$hemi.white.avg.area.mgh; # backcompat
    set cmd = (mri_concat $measout --mean --o $avgmeas)
    echo $cmd | tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1
    # Compute std across subject
    set stdmeas = $ddir/surf/std.$hemi.$meas.mgh
    set cmd = (mri_concat $measout --std --o $stdmeas)
    echo $cmd | tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1
    # Convert avg to curv
    set tval = $ddir/surf/$hemi.$meas
    set cmd = (mri_surf2surf --sval $avgmeas --s $average_subject \
     --tval $tval --trg_type curv --hemi $hemi)
    pwd | tee -a $LF
    echo $cmd | tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1
    # Delete temporary stuff
    if($meas != area) rm $avgmeas 
  end # meas
end # hemi


echo "---------------------------------------------------" | tee -a $LF
echo "" | tee -a $LF
set tSecEnd = `date '+%s'`;
@ tSecRun = $tSecEnd - $tSecStart;
set tRunHours = `echo $tSecRun/3600|bc -l`
set tRunHours = `printf %5.2f $tRunHours`
echo "make_average_surface-Run-Time-Hours $tRunHours" |& tee -a $LF
date | tee -a $LF
echo "make_average_surface done" | tee -a $LF
echo ""

exit 0

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

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

  set flag = $argv[1];
  if (! $getting_subjects) then
    shift;
  endif

  switch($flag)

    case "--help":
      set PrintHelp = 1;
      goto usage_exit;
      exit 0;

    case "--version":
      echo $VERSION
      exit 0;

    case "--s":
    case "--subjects":
      if ( $#argv == 0) goto arg1moreerr;
      set SUBJECTS = $argv[1]; shift;
      # loop on getting variable number of subject names
      set getting_subjects = 1; # see 'default:' case
      breaksw

    case "--f":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if ( $#argv == 0) goto arg1moreerr;
      set fname = $argv[1]; shift;
      if(! -e $fname) then
        echo "ERROR: cannot find $fname"
        exit 1;
      endif
      if($?SUBJECTS) then
        set SUBJECTS = ($SUBJECTS `cat $fname`)
      else
        set SUBJECTS = (`cat $fname`)
      endif
      breaksw

    case "--fsgd":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if ( $#argv == 0) goto arg1err;
      set fsgdf = $argv[1]; shift;
      if(! -e $fsgdf) then
        echo "ERROR: cannot find $fsgdf";
        exit 1;
      endif
      set sl = `cat $fsgdf | awk '{if($1 == "Input") print $2}'`;
      set SUBJECTS = ($sl);
      breaksw

    case "--out":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if ( $#argv == 0) goto arg1err;
      set average_subject = $argv[1]; shift;
      breaksw

    case "--surfreg":
    case "--surf-reg":
    case "--surf_reg":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if ( $#argv == 0) goto arg1err;
      set sphere_reg = $argv[1]; shift;
      breaksw

    case "--surf":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if( $#argv == 0) goto arg1err;
      set surflist = $argv[1]; shift;
      breaksw

    case "--topdir":
    case "--sd-out":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if( $#argv < 1) goto arg1err;
      set sdout = $argv[1]; shift;
      breaksw

    case "--sd":
    case "--sdir":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if ( $#argv == 0) goto arg1err;
      set SUBJECTS_DIR = $argv[1]; shift;
      setenv SUBJECTS_DIR $SUBJECTS_DIR
      breaksw

    case "--xform":
    case "--s-xform":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if($#argv < 1) goto arg1err;
      set transform_fname = $argv[1]; shift;
      set XFORM_FLAG = "-X $transform_fname";
      breaksw

    case "--mni152":
      # Use synthmorph nonlinear reg to mni space
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      set transform_fname = synthmorph.1.0mm.1.0mm/warp.to.mni152.1.0mm.1.0mm.nii.gz
      set XFORM_FLAG = "-X $transform_fname";
      breaksw

    case "--s-dest-lta":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if($#argv < 1) goto arg1err;
      set DestLTA = "-d $argv[1]"; shift;
      breaksw

    case "--ico":
    case "--i":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if ( $#argv == 0) goto arg1err;
      set ico_no = $argv[1]; shift;
      breaksw

    case "--meas"
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if($#argv < 1) goto arg1err;
      set measlist = ($measlist $argv[1]); shift;
      breaksw

    case "--symlink":
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      set UseSymLink = 1;
      breaksw

    case "--annot"
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if($#argv < 1) goto arg1err;
      set annotlist = ($annotlist $argv[1]); shift;
      breaksw

    case "--threads"
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      if($#argv < 1) goto arg1err;
      set threads = $argv[1]; shift
      breaksw

    case "--no-annot":
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      set UseAnnot = 0;
      set UseAnnotTemplate = 0
      breaksw

    case "--annot-template"
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      set UseAnnotTemplate = 1
      breaksw

    case "--no-annot-template"
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      set UseAnnotTemplate = 0
      breaksw

    case "--no-cortex-label":
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      set DoCortexLabel = 0;
      breaksw

    case "--no-symlink":
    case "--no-link":
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      set UseSymLink = 0;
      breaksw

    case "--nocleanup":
      # This has no effect, but needed for compat with make_average_volume
      set cleanup = 0;
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--no-surf2surf":
      # for mris_make_average_surface to use old method of parametric surface
      set NoSurf2Surf = "-no-surf2surf"; 
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw


    case "--debug":
    case "--echo":
      set echo = 1;
      set verbose = 1;
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--template-only":
      set DoTemplateOnly = 1;
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--no-template-only":
      set DoTemplateOnly = 0;
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--xhemi":
      set DoXHemi = 1;
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--lh":
      set hemilist = (lh)
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--rh":
      set hemilist = (rh)
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--lhrh":
      set hemilist = (lh rh)
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--no-xhemi":
      set DoXHemi = 0;
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    case "--conform":
    case "-conform":
      set ConfFlag = "-conform"
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw
    case "--no-conform":
    case "-no-conform":
    case "-noconform":
      set ConfFlag = "-noconform"
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    # These 0-arg flags passed to make_average_subject, but dont apply here.
    case "--no-surf":
    case "--no-vol":
    case "--force":
    case "--link":
    case "--keep-all-orig":
    case "--no-ribbon":
    case "--ctab-default":
      if ( $getting_subjects ) then
        set getting_subjects = 0;
        # got em all, from --subjects variable arg loop
      endif
      breaksw

    # These 1-arg flags passed to make_average_subject, but dont apply here.
    # Need to eat the argument.
    case "--ctab":
    case "--rca-threads":
    case "--v-xform":
      if ( $getting_subjects ) then
        # got em all, from --subjects variable arg loop
        set getting_subjects = 0;
        shift;
      endif
      shift;
      breaksw


    default:
      if ( $getting_subjects ) then
        # loop on getting variable number of subjects,
        # until a new flag is found, or no more args
        set SUBJECTS = ( $SUBJECTS $argv[1] ); shift;
        set getting_subjects = 1;
      else
        echo ERROR: Flag $flag unrecognized.
        echo $cmdline
        exit 1
      endif
      breaksw
  endsw

end

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

############--------------##################
check_params:
  if (! $?SUBJECTS) then
    echo "ERROR: no subjects declared!"
    echo "Either declare subjects in SUBJECTS variable,"
    echo "or declare using --subjects argument."
    exit 1
  endif
  if (! $?SUBJECTS_DIR) then
    echo "ERROR: SUBJECTS_DIR is not declared!"
    echo "Either set the SUBJECTS_DIR environment variable,"
    echo "or declare using --sdir argument, the root directory"
    echo "for subject data files."
    exit 1
  endif
  if(! -e $SUBJECTS_DIR ) then
    echo "ERROR: SUBJECTS_DIR $SUBJECTS_DIR does not exist."
    exit 1;
  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($#sdout == 0) set sdout = $SUBJECTS_DIR;
  if($#hemilist == 0) set hemilist = (lh rh)
  if($#annotlist == 0) set annotlist = (aparc.DKTatlas aparc aparc.a2009s)
  if($#measlist == 0) set measlist = (sulc curv thickness area volume inflated.H)
goto check_params_return;
############--------------##################

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

############--------------##################
arg1moreerr:
  echo "ERROR: flag $flag requires one or more arguments"
  exit 1
############--------------##################

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: make_average_surface"
  echo ""
  echo "Required Arguments"
  echo "   --subjects <subj1> <subj2> ... <subjN>"
  echo "             : or declare subjects in SUBJECTS env var"
  echo "   --fsgd fsgdfile : get subject list from fsgd"
  echo ""
  echo "Optional Arguments"
  echo "   --out <average subject name>    : default name is 'average'"
  echo "   --sdir <SUBJECTS_DIR to use instead of the one in the env>"
  echo "   --sd      : same as --sdir"
  echo "   --sd-out topdir : put data here"
  echo "   --xform <transform_fname>       : filename of transform file"
  echo "   --mni152 : set xform to synthmorph.1.0mm.1.0mm/warp.to.mni152.1.0mm.1.0mm.nii.gz"
  echo "   --ico <number>  : specify icosahedron number, default is 7 (ic7.tri)"
  echo "   --surf-reg <surface name>   : alternative registration surface"
  echo "   --lh : only do left  hemi (default is to do both)"
  echo "   --rh : only do right hemi (default is to do both)"
  echo "                                 default: sphere.reg"
  echo "   --force   : overwrite existing average subject data"
  echo "   --annot-template : use annotation when making tif"
  echo "   --template-only : useful when creating iterative atlases"
  echo "   --no-template-only : turns off --template-only"
  echo "   --no-annot : do not create average annotations (does not affect use with template)"
  echo "   --no-cortex-label : do not create ?h.cortex.label"
  echo "   --annot annotname <--annot annotname > : supply list of annots to use (default $annotlist)"
  echo "   --meas measname <--meas measname > : supply list of meass to use (default $measlist)"
  echo "   --no-surf2surf : use old parametric surface method (may give big faces at the poles)"
  echo ""
  echo "   --help       : short descriptive help"
  echo "   --no-symlink : do not use symbolic links (just copy files)"
  echo "   --no-lik     : same as --no-symlink"
  echo "   --version : script version info"
  echo "   --echo    : enable command echo, for debug"
  echo "   --debug   : same as --echo"
  echo ""
  echo "See also: recon-all, make_final_surfaces, morph_subject"
  echo ""

  if(! $PrintHelp) exit 1;

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

Creates average surfaces and curvatures from a set of subjects.

Calls mris_average_curvature, mris_make_average_surface, mris_smooth,
mris_inflate, and mris_curvature.

EXAMPLE

make_average_surface --out avgsubject --subjects subj1 subj2 subj3 subj4

will create $SUBJECTS_DIR/avgsubject with average surfaces for orig,
white, pial, inflated for each hemi.

SEE ALSO

make_average_subject, make_average_volume

GETTING HELP

Run recon-all --help for extensive text on the reconstruction process.
Or, send email to freesurfer@nmr.mgh.harvard.edu.
Also see http://surfer.nmr.mgh.harvard.edu.

