#!/bin/tcsh

@global_parse `basename $0` "$*" ; if ($status) exit 0

# make surface spec files from the surface files
#
# usage @SUMA_Make_Spec_FS [options]
#
# options:
#       -sid    subject_id      : specify subject ID
#       -fspath FreeSurfer_path : specify path to FreeSurfer files
#       -neuro                  : use neurological orientation
#       -debug  level           : display extra output
#

# [Dec 30, 2016]: PT+RCR updated.
#    + new renumbering of aparc/aseg files for both 2000 and 2009
#      atlases
#    + replaces functionality of 'rank' data sets
#    + produce tissue maps based on hopefully good guesses of FS
#      labeling
# [Aug 20, 2019] PT : indent properly, for readability
# [Aug 20, 2019] PT : update help
# [Sep  4, 2019] RCR: check for valid 'mris_convert --help' output
# [Sep  4, 2019] PT : add in new opt: '-extra_fs_dsets ..'
#    + so more $fsdsets can be created with surfs (for F. Lalonde)
# [Nov 14, 2019] PT : new default: *rank* dsets will not be output
#    + have new option to create rank dsets:  -make_rank_dsets
# [Nov 19, 2019] RCR: new option: -fs_setup
# [Jan 27, 2020] RCR: compress *.nii, but not SV, new opt: -no_compress
# [Feb  3, 2020] RCR: add -extra_annot_labels
# [Feb 27, 2020] RCR: add -fsannot_ver (for older version of files)
#    + also, -extra_annot_labels output is passed on to -extra_fs_dsets
# [Mar  5, 2020] RCR/DRG: for extra annot's, pass along without colormap
#    + use mris_convert/3dcopy for now, instead of FSread_annot/ConvertDset
# [Jan 27, 2021] PT : add another driving script in L_MAKE_DRIVE_SCRIPT block
#    + has both AFNI+SUMA run, plus talk 
# [Mar  3, 2021] PT : add some functionality in new L_MASK_QC_ROIS block
#    + make a nice WB mask
#    + make some QC images of mask(s), segmentations and ROIs
#    + make some tables of ROI info
# [May 12, 2021] PT : remove old NIFTI message about needing even matrix
#      dimensions for anatomical input to recon-all.  Yikes, that wasn't
#      need, just the way we were viewing it...
# [Jul 16, 2024] DRG : before adding all possible surface
#      attributes to a spec file, check which are actually available 

set ver = 2.2.4

#----------------------------------------------------------------------
goto L_INIT_VARS
     L_INIT_VARS_DONE:

goto L_CHECK_USAGE
     L_CHECK_USAGE_DONE:

goto L_PARSE_COMMAND
     L_PARSE_COMMAND_DONE:

goto L_VERIFY_PROGRAMS
     L_VERIFY_PROGRAMS_DONE:

goto L_SET_SURF_DIRS
     L_SET_SURF_DIRS_DONE:

goto L_CHECK_FOR_OVERWRITE
     L_CHECK_FOR_OVERWRITE_DONE:

goto L_LOOK_FOR_SURF
     L_LOOK_FOR_SURF_DONE:

goto L_CREATE_BRICK
     L_CREATE_BRICK_DONE:

goto L_CONVERT_SURFACES
     L_CONVERT_SURFACES_DONE:

goto L_CREATE_SPEC
     L_CREATE_SPEC_DONE:

goto L_ICO
     L_ICO_DONE:

goto L_TEST_SURF_VOL
     L_TEST_SURF_VOL_DONE:

# PT added [Jan 27, 2021]
goto L_MAKE_DRIVE_SCRIPT
     L_MAKE_DRIVE_SCRIPT_DONE:

# PT added [Dec 30, 2016]
goto L_RENUMBER_ROIS
     L_RENUMBER_ROIS_DONE:

# PT added [Mar 3, 2021]
goto L_MASK_QC_ROIS
     L_MASK_QC_ROIS_DONE:

# [27 Jan 2020 rickr]
goto L_COMPRESS_FILES
     L_COMPRESS_FILES_DONE:

goto L_GOOD_END   # finished, woohooo!


####################################################################
# variable initialization

L_INIT_VARS:

    set DO_MAKE_RANK_DSETS = 0   # [PT: Nov 14, 2019] the new normal
    set USING_NIFTI = 0
    set prog_name = $0:t
    set endstr = "$prog_name ... finished"
    set debug     = 0
    set ldlist = (141 60)
    set do_compress = 1
    #set fsdsets = (thickness.gii.dset)
    #set fsdsets = (thickness curv sulc $fsdsets_extra ) 
    set inflates = ()
    
    # list of possible surface attributes that could be added to spec
    # file
    set poss_surf_attribs = (       \
            smoothwm                \
            pial                    \
            inflated                \
            occip.patch.3d          \
            occip.patch.flat        \
            occip.flat.patch.3d     \
            fusiform.patch.flat     \
            full.patch.3d           \
            full.patch.flat         \
            full.flat.patch.3d      \
            full.flat               \
            flat.patch              \
            sphere                  \
            white                   \
            sphere.reg              \
            rh.sphere.reg           \
            lh.sphere.reg           \
            pial-outer-smoothed     \
            )
    # initialize empty list of attributes to be added to spec file;
    # gets populated based on what dsets are actually available (below)
    set surf_attribs = ( )

goto L_INIT_VARS_DONE


####################################################################
# check usage, and possibly print help

L_CHECK_USAGE:

    if ( $#argv == 0 ) then
        # show help on no args   28 Feb 2017 [rickr]

        # echo "usage: $prog_name [options] -sid SUBJECT_ID"
        # echo "usage: $prog_name -help"
        # set endstr = ""
        goto L_HELP_END
    endif

goto L_CHECK_USAGE_DONE


####################################################################
# parse the command line

L_PARSE_COMMAND:

    echo "++ Running @SUMA_Make_Spec_FS version: $ver"

    # init command line arg values

    set fs_dir      = "."
    set subj_id      = ""
    set neuro_ori   = 0
    set sfieldname  = 'FreeSurferSurface'
    set sex = 'asc'
    set stp = 'FreeSurfer'
    set ldu = ()
    set ldpref = ()
    set use_mgz = 0
    set set_space = ''
    set args     = $#argv
    set count    = 1
    set extra_annot_labels = ( )        #  3 Feb 2020 [rickr]
    set fsdsets_extra  = ( )
    set fsannot_ver  = ""               # 27 Feb 2020 [rickr]

    while ( $count <= $args )
        switch ( "$argv[$count]" )

            # ----------------------------------------------------------
            # usage: -help
            case "-h":
            case "-help":
            
                goto L_HELP_END      # and don't ya' come back, neither

            breaksw

            # ----------------------------------------------------------
            # usage: -sid SUBJECT_ID
            case "-sid":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -sid SUBJECT_ID"
                    goto L_BAD_END
                endif

                @ count ++
                set subj_id  = $argv[$count]

            breaksw

            # ----------------------------------------------------------
            # usage: -fsannot_ver YEAR (e.g. 2009)
            case "-fsannot_ver":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -fsannot_ver YEAR"
                    goto L_BAD_END
                endif

                @ count ++
                set fsannot_ver  = $argv[$count]

            breaksw

            # ----------------------------------------------------------
            # usage: -fspath FREESURFER_PATH
            case "-fspath":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -fspath FREESURFER_PATH"
                    goto L_BAD_END
                endif

                @ count ++
                set fs_dir  = $argv[$count]

                if ( ! -d $fs_dir ) then
                    set endstr = "failure: directory not found - '$fs_dir'"
                    goto L_BAD_END
                endif

            breaksw

            # ----------------------------------------------------------
            # usage: -fs_setup          : source SetUpFreeSurfer.csh
        
            case "-fs_setup":

                # if $FREESURFER_HOME is set
                # and $FREESURFER_HOME/SetUpFreeSurfer.csh exists,
                # source it

                if ( ! $?FREESURFER_HOME ) then
                   echo '** -fs_setup requires $FREESURFER_HOME to be set'
                   set endstr = "failure: cannot apply -fs_setup"
                   goto L_BAD_END
                endif

                set fs_setupstr  = '$FREESURFER_HOME/SetUpFreeSurfer.csh'
                set fs_setupfile = $FREESURFER_HOME/SetUpFreeSurfer.csh

                if ( ! -f $fs_setupfile ) then
                   echo "** missing $fs_setupstr"
                   set endstr = "failure: cannot apply -fs_setup"
                   goto L_BAD_END
                endif

                # do the deed
                echo "++ sourcing $fs_setupstr"
                source $fs_setupfile

            breaksw

            # ----------------------------------------------------------
            # usage : -neuro
            case "-neuro":

                # do not allow overlapping options    15 Jun 2017 [rickr]
                if ( $neuro_ori != 0 ) then
                    echo '** cannot use any -*IFTI options with -neuro'
                    goto L_BAD_END
                endif

                set neuro_ori = 1
            breaksw

            # ----------------------------------------------------------
            # usage : -no_compress                    27 Jan 2020 [rickr]
            case "-no_compress":

                # then turn off compression
                set do_compress = 0
            breaksw

            # ----------------------------------------------------------
            # usage : -nocor
            case "-nocor":
                set endstr = "Option -nocor obsolete. "
                set endstr = "$endstr See -help for important details."
                goto L_BAD_END

                #set neuro_ori = -1
                #set sfieldname = 'SurfaceName'
                #set sex = 'gii'
                #set stp = 'GIFTI'

            breaksw

            # ----------------------------------------------------------
            # usage : -GNIFTI
            case "-GNIFTI":
            case "-NIFTI":
            case "-GIFTI":
            case "-IFTI":

                # do not allow overlapping options    15 Jun 2017 [rickr]
                if ( $neuro_ori != 0 ) then
                    echo '** cannot use any -*IFTI options with -neuro'
                    goto L_BAD_END
                endif

                set neuro_ori = -1
                set sfieldname = 'SurfaceName'
                set sex = 'gii'
                set stp = 'GIFTI'
                set USING_NIFTI = 1      # [PT: Feb,2017] really useful...

            breaksw

            # ----------------------------------------------------------
            # [PT: Nov 14, 2019] the *rank* dsets have been superseded
            # by the safer/more uniform *REN* ones;  now only make the former
            # if users explicitly ask for it
            # usage : -make_rank_dsets 
            case "-make_rank_dsets":

                set DO_MAKE_RANK_DSETS = 1

            breaksw

            # ----------------------------------------------------------
            # usage : -set_space SPACE
            case "-set_space":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -set_space SPACE"
                    goto L_BAD_END
                endif

                @ count ++
                set set_space  = $argv[$count]

            breaksw

            # ----------------------------------------------------------
            # usage : -neuro
            case "-use_mgz":

                set use_mgz = 1

            breaksw

            # ----------------------------------------------------------
            # usage : -debug DEBUG_LEVEL
            case "-debug":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -debug DEBUG_LEVEL"
                    goto L_BAD_END
                endif

                @ count ++
                set debug = $argv[$count]

                if ( "$debug" > 2 ) then
                    set debug = 2
                endif
                if ( "$debug" < 0 ) then
                    set debug = 0
                endif

            breaksw

            # ----------------------------------------------------------
            # usage : -inflate VAL
            case "-inflate":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -inflate INF"
                    goto L_BAD_END
                endif

                @ count ++
                set ff = 0
                foreach inf ($inflates)
                    if ($inf == "$argv[$count]") then
                        set ff = 1
                    endif
                end
                if ($ff == 0) then
                    set inflates = ($inflates $argv[$count])
                endif

            breaksw


            # ----------------------------------------------------------
            # usage : -extra_annot_labels AA BB CC ...
            case "-extra_annot_labels":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -extra_annot_labels AA BB CC ..."
                    goto L_BAD_END
                endif

                @ i0   = $count + 1    # $i0 will always lead $count by one

                # keep track of first char of next arg (not '-')
                set c0 = `echo $argv[$i0] | cut -b 1`

                while ( ( $i0 <= $#argv ) && ( "$c0" != "-" ) )
                    set extra_annot_labels = ($extra_annot_labels "$argv[$i0]")

                    @ i0 ++
                    @ count ++ 
                    if ( $i0 <= $#argv ) then
                        # get first char of next arg, to be check in while()
                        set c0 = `echo $argv[$i0] | cut -b 1`
                    endif
                end

                if ( $#extra_annot_labels == 0 ) then
                    echo "** ERROR: need at least one dset after $argv[$count]"
                    goto BAD_EXIT
                else
                    echo "++ will track $#extra_annot_labels extra annot labels"
                endif

            breaksw

            # ----------------------------------------------------------
            # usage : -extra_fs_dsets AA BB CC ...
            case "-extra_fs_dsets":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -extra_fs_dsets AA BB CC ..."
                    goto L_BAD_END
                endif

                @ i0   = $count + 1    # $i0 will always lead $count by one
                set c0 = ""
                while ( ( $i0 <= $#argv ) && ( "$c0" != "-" ) )
                    set fsdsets_extra = ( $fsdsets_extra "$argv[$i0]" )

                    @ i0 ++
                    @ count ++ 
                    if ( $i0 <= $#argv ) then
                        # get first char of next arg, to be check in while()
                        set c0 = `echo $argv[$i0] \
                                        | awk '{print substr($0,1,1)}'`
                    endif
                end

                if ( $#fsdsets_extra == 0 ) then
                    echo "** ERROR: need at least one dset after $argv[$count]"
                    goto BAD_EXIT
                else
                    echo "++ User has listed $#fsdsets_extra 'extra' FS dsets"
                endif

            breaksw

            # ----------------------------------------------------------
            # usage : -ld VAL
            case "-ld":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -ld LD"
                    goto L_BAD_END
                endif

                @ count ++
                set ldu = ($ldu $argv[$count])

            breaksw

            # ----------------------------------------------------------
            # usage : -ldpref LDpref
            case "-ldpref":

                if ( $count >= $args ) then
                    set endstr = "arg usage: -ldpref LDpref"
                    goto L_BAD_END
                endif

                @ count ++
                set ldpref = ($ldpref $argv[$count])

            breaksw

            # ----------------------------------------------------------
            # usage : -no_ld
            case "-no_ld":

                set ldlist = ()

            breaksw


            # ----------------------------------------------------------
            # bad argument
            default:

                set endstr = "invalid option: '$argv[$count]'"
                apsearch -popt `basename $0` -word $argv[$count]
                goto L_BAD_END

            breaksw
        endsw

        @ count ++
    end
    
    if ( $subj_id == "" ) then
        set endstr = "missing required option: -sid"
        goto L_BAD_END
    endif


    # [PT: Sep 4, 2019] Put this array definition here, to allow users
    # to input other dsets from surf/ dir
    set fsdsets = (thickness curv sulc $fsdsets_extra ) 

    if ($#inflates == 0 && $neuro_ori == -1) then
        set inflates = ($inflates 200) 
    endif

    if ( $debug ) echo "-- usage okay"
    if ( $debug > 1 ) then
        set echo
    endif
    if ( $#ldu ) then
        set ldlist = ($ldu)
    endif
    if ($#ldpref == 0 && $#ldlist != 0) then
        set ldpref = ()
        foreach lldd ($ldlist)
            set ldpref = ($ldpref std.$lldd.)
        end
    endif
    if ($#ldpref != 0 && $#ldpref != $#ldlist) then
        set endstr = "Not enough -ldpref options for $#ldlist values"  
        goto L_BAD_END
    endif

    set spec_files   = ({$subj_id}_lh.spec {$subj_id}_rh.spec )
    set sample_spec  = $spec_files[1]
    set afni_prefix  = ${subj_id}_SurfVol
    if ( $neuro_ori != -1 ) then
        set afni_dataset = $afni_prefix+orig
    else
        set afni_dataset = $afni_prefix 
    endif
    # set and go to the base directory
    cd $fs_dir
    set start_dir = $cwd

    if ( $debug ) echo "-- using start_dir '$start_dir'"

goto L_PARSE_COMMAND_DONE


####################################################################
# make sure programs exist

L_VERIFY_PROGRAMS:

    set failed_pgms = 0

    # check that programs are in the path
    foreach test_command ( afni to3d suma mris_convert )

        (which $test_command) >& /dev/null

        if ( $status ) then
            echo "program not found in path: $test_command"
            @ failed_pgms ++
            continue
        endif

        # $test_command was found, but maybe additional checks are warranted

        if ( $test_command == mris_convert ) then
            # Unfortunately, all -help variants seem to set $status,
            # so parse the actual text, looking for 'surface'.
            set nl = `$test_command --help |& \grep surface | wc -l`
            if ( "$nl" == 0 ) then
                echo "** apparent failure to run $test_command"
                echo "   $test_command --help starts with:"
                echo ""
                $test_command --help |& head -n 10
                echo ""
                echo "---------------------------------------------------------"
                echo "** if this requires SetUpFreeSurfer.csh, consider option:"
                echo "     -fs_setup"
                echo ""
                @ failed_pgms ++
                continue                # in case more checks are added
            endif
        endif
    end

    if ( $failed_pgms ) then
        set endstr = "$failed_pgms program(s) not found"
        goto L_BAD_END
    endif

    # check that a couple of commands actually work
    foreach test_command ( afni mris_convert )
        $test_command --version >& /dev/null

        if ( $status ) then
            echo "program failure: $test_command"
            @ failed_pgms ++
        endif
    end

    if ( $failed_pgms ) then
        set endstr = "$failed_pgms program(s) not working correctly"
        goto L_BAD_END
    endif

    if ( $debug ) echo "-- all programs found"

goto L_VERIFY_PROGRAMS_DONE


####################################################################
# 1. set surf_dir and orig_dir - check cwd and parent
# 2. create SUMA directory at the same level as surf_dir and store the
#    results there


L_SET_SURF_DIRS:

    # find surf directory

    if ( -d surf ) then
        set surf_dir = ./surf
        set label_dir = ./label
    else if ( $cwd:t == surf ) then
        set surf_dir = .
        set label_dir = ../label
    else if ( -d ../surf ) then
        set surf_dir = ../surf
        set label_dir = ../label
    else
        # this is a general failure case, even if we find one
        set surf_dirs = ( `find . -maxdepth 4 -type d -name surf -print` )
   
        if ( $#surf_dirs == 0 ) then
            echo "failure: cannot find directory 'surf' under '$fs_dir'"
            echo "(subject to a maximum search depth of 4 subdirectories)"

            set endstr = ""
        else if ( $#surf_dirs == 1 ) then
            echo "surf directory found at '$surf_dirs[1]'"
            set endstr = "consider running program from '$surf_dirs[1]:h'"
        else
            echo "multiple surf directories found:"
            set count = 1
            while ( $count <= $#surf_dirs )
                echo "     $surf_dirs[$count]"
                @ count ++
            end

            set endstr = ( "consider running program from one of the" \
                           "surf directories" )
        endif

        goto L_BAD_END
    endif

    # verify surf dir permissions
    if ( ! -w $surf_dir ) then
        set endstr = "failure: no write permissions for directory '$surf_dir'"
        goto L_BAD_END
    endif

    if ( $debug ) echo "-- using surf directory '$surf_dir'..."

    # now check for orig dir

    set orig_dir = ""
    foreach test_dir (  $surf_dir/orig       \
                        $surf_dir/mri/orig   \
                        orig                 \
                        mri/orig             \
                        ../orig              \
                        ../mri/orig )
        if ( -d $test_dir ) then
            set orig_dir = $test_dir
            break
        endif
    end

    set orig_mgz = ""
    foreach test_mgz (  $surf_dir/orig.mgz       \
                        $surf_dir/mri/orig.mgz   \
                        orig.mgz                 \
                        mri/orig.mgz             \
                        ../orig.mgz              \
                        ../mri/orig.mgz )
        if ( -f $test_mgz ) then
            set orig_mgz = $test_mgz
            break
        endif
    end
    
    set other_mgz = ()
    set other_candidates = ( T1 aparc+aseg aparc.a2005s+aseg        \
                             aparc.a2009s+aseg aseg.auto aseg       \
                             brain.finalsurfs brain brainmask.auto  \
                             brainmask norm nu nu_noneck lh.ribbon  \
                             rh.ribbon wm.asegedit wm wm.seg )

    foreach candidate ($other_candidates)
        foreach dcand ($surf_dir/ $surf_dir/mri/ ./ mri/ ../ ../mri/ )
            if ( -f $dcand$candidate.mgz ) then 
                set other_mgz = ($other_mgz $dcand$candidate.mgz)
                break
            endif
        end
    end
   
    if ( $orig_dir == "" && $orig_mgz == "") then
        set endstr = "failure: cannot find directory 'orig' or file 'orig.mgz' under $fs_dir"
        goto L_BAD_END
    endif

    if ( $orig_dir == "" ) then
        set endstr = "failure: script expects an 'orig' directory even if it is empty."
        goto L_BAD_END 
    endif
    
    # verify orig dir permissions
    if ( ! -w $orig_dir ) then
        set endstr = "failure: no write permissions for directory '$orig_dir'"
        goto L_BAD_END
    endif

    if ( $debug ) echo "-- using orig directory '$orig_dir'..."

    # decide whether we need to make surf/SUMA directory

    set suma_dir = ./SUMA

    if ( -d $suma_dir ) then
        if ( $debug ) echo "-- $suma_dir already exists, continuing..."
    else
        echo "++ creating directory '$suma_dir' for results..."
        mkdir $suma_dir
        if ( $status ) then
            set endstr = "failure: cannot create directory '$suma_dir'"
        goto L_BAD_END
        endif
    endif

goto L_SET_SURF_DIRS_DONE


####################################################################
# verify non-existence of spec files and AFNI files

L_CHECK_FOR_OVERWRITE:

    set test_failures = 0

    foreach test_file ( $suma_dir/$spec_files[1]           \
                        $suma_dir/$spec_files[2]           \
                        $suma_dir/$afni_dataset.HEAD       \
                        $suma_dir/$afni_dataset.BRIK       \
                        $orig_dir/$afni_dataset.HEAD       \
                        $orig_dir/$afni_dataset.BRIK       \
                        $orig_dir/$afni_prefix'+orig.HEAD' \
                        $orig_dir/$afni_prefix'+orig.BRIK' \
                        $suma_dir/$afni_prefix'+orig.HEAD' \
                        $suma_dir/$afni_prefix'+orig.BRIK' \
                        $suma_dir/$afni_prefix'.nii'       \
                        $suma_dir/$afni_prefix'.nii.gz')
        if ( -f $test_file ) then
            if ( $test_failures == 0 ) then
                echo "failure: will not overwrite files: "
                set test_failures = 1
            endif

            echo "        '$test_file'"
        endif
    end

    if ( $test_failures ) then
        set endstr = "please remove these files if you want to rerun the script."
        goto L_BAD_END
    endif

goto L_CHECK_FOR_OVERWRITE_DONE

####################################################################
# find surface files

L_LOOK_FOR_SURF:

    cd $surf_dir

    set list_lh = "X"   # init to something useless - allows nice empty check
    set list_rh = "X"

    # check for possible attributes, and keep list of ones that are
    # present (to add to spec file later)
    foreach attrib ( $poss_surf_attribs )
        set found_attrib = 0
        if ( -f lh.$attrib ) then
            set list_lh = ( $list_lh lh.$attrib )
            set found_attrib = 1
        endif
        if ( -f rh.$attrib ) then
            set list_rh = ( $list_rh rh.$attrib )
            set found_attrib = 1
        endif
        if ( $found_attrib == 1 ) then
            set surf_attribs = ( $surf_attribs $attrib )
        endif
    end

    set list_lh = ( $list_lh[2-] )   # now remove the leading "X"
    set list_rh = ( $list_rh[2-] )

    if ( $#list_lh == 0 && $#list_rh == 0 ) then
        set endstr = "found no LH or RH surface files under '$surf_dir'"
        goto L_BAD_END
    endif

    if ( $#list_lh > 0 ) then
        echo "-- found $#list_lh LH surfaces"
        if ( $debug ) echo "    --" $list_lh
    endif

    if ( $#list_rh > 0 ) then
        echo "-- found $#list_rh RH surfaces"
        if ( $debug ) echo "    --" $list_rh
    endif

    cd $start_dir

goto L_LOOK_FOR_SURF_DONE


####################################################################
# convert to ascii via mris_convert (found earlier)

L_CONVERT_SURFACES:

    cd $surf_dir
    foreach surf ( $list_lh $list_rh )
        # run mris_convert and verify
        if ( $surf =~ *patch* || $surf =~ *.flat) then
            echo  "-- running 'mris_convert -p $surf $surf.asc'"
            mris_convert -p $surf $surf.asc
        else
            echo "-- running 'mris_convert $surf $surf.asc'"
            mris_convert $surf $surf.asc >& ___out
            tail ___out ; \rm -f ___out
        endif

        if ( $neuro_ori == -1 ) then
            if ( ! -f xmatras.1D ) then
                set c_ras = (`mri_info --cras --ras_good $start_dir/$orig_mgz`)
                set minus = `ccalc "$c_ras[3]*-1"` 
                echo 1 0 0 $c_ras[1] 0 1 0 $c_ras[2] 0 0 1 $minus > xmatras.1D
            endif
            #If using new conversion, change surfaces to gifti with proper
            #coordinate shift.
            if ( $surf =~ *.white* ||     \
                 $surf =~ *.smoothwm* ||  \
                 $surf =~ *.pial*) then
                # hmmm, identical commands suggest the second
                # -ixmat_1D does not belong (currently left for future
                # bickering)
                ConvertSurface                                   \
                    -sv $start_dir/$suma_dir/$afni_dataset.nii   \
                    -i $surf.asc                                 \
                    -ixmat_1D xmatras.1D -overwrite -o $surf.gii
            else
                ConvertSurface                                   \
                    -sv $start_dir/$suma_dir/$afni_dataset.nii   \
                    -i $surf.asc                                 \
                    -ixmat_1D xmatras.1D -overwrite -o $surf.gii
            endif
        endif

        if ( ! -f $surf.${sex} ) then
            echo "failure: could not create surface $surf.${sex}"

            if ( ! -w . ) then
                set endstr = "--> no write permissions in this directory"
            else
                set endstr = "--> is your FreeSurfer license installed?"
            endif

            goto L_BAD_END
        endif

        if ( $debug ) then
            echo "++ $surf.${sex} created"
            if ( -f $start_dir/$suma_dir/$surf.${sex} ) then
                echo "++ overwriting '$suma_dir/$surf.${sex}'"
            endif
        endif
   
        #tmp fix for rh.lh.sphere.reg.gii side 
        if ( "$surf.${sex}" == rh.lh.sphere.reg.gii) then
            echo "++ Fixing side for rh.lh.sphere.reg.gii"
            sed 's:CortexLeft:CortexRight:' rh.lh.sphere.reg.gii > __tmpfix
            if ($status) then
                echo "** Failed to fix side for rh.lh.sphere.reg.gii"
            else 
                mv __tmpfix rh.lh.sphere.reg.gii
            endif 
        endif
   
        \mv -f $surf.${sex} $start_dir/$suma_dir   # how barbaric!

        if ( $status ) then
            set endstr = ( "failure: cannot write"   \
                           "'$suma_dir/$surf.${sex}'" )
            goto L_BAD_END
        endif
    end # foreach surf ...

    cd $start_dir

    #and do the labels
    if ( -d $label_dir) then
        cd $label_dir
        if ( $fsannot_ver != "" ) then
           set fsannot_opt = "-FSversion $fsannot_ver"
        else
           set fsannot_opt = ""
        endif

        # ------------------------------------------------------------
        # process any extra annotation labels - use mris_convert
        # (convert and create GIFTI versions to pass to MapIcosahedron)
        if ( $#extra_annot_labels > 0 ) then
           echo "++ have $#extra_annot_labels extra labels, " \
                "including as if -extra_fs_dsets"

           # find a surface to use as input to mris_convert
           set sinput = ''
           set surf_names = ( white smoothwm pial )
           foreach stmp ( $surf_names )
              if ( -f ../$surf_dir/lh.$stmp && -f ../$surf_dir/rh.$stmp ) then
                 set sinput = $stmp
                 break
              endif
           end

           if ( $sinput != "" ) then
              echo "-- using $sinput as surf input to mris_convert"

              foreach exlab ( $extra_annot_labels )
                 # convert and make a GIFTI version
                 foreach hand ( lh rh )
                    set efile = ${hand}.$exlab.annot
                    if ( ! -f $efile ) then
                        echo ""
                        echo "** annot label '$exlab', missing file: $efile"
                        echo ""
                        continue
                    endif

                    set isurf = ../$surf_dir/$hand.$sinput
                    set ddd = $start_dir/$suma_dir

                    # Until we fix FSread_annot 
                    #
                    # FSread_annot   -input $efile                     \
                    #     $fsannot_opt                                 \
                    #     -roi_1D  $ddd/${hand}.$exlab.annot.1D.roi    \
                    #     -dset    $ddd/${hand}.$exlab.annot.niml.dset \
                    #     -cmap_1D $ddd/${hand}.$exlab.annot.1D.cmap 

                    mris_convert --annot $efile $isurf  \
                                 $ddd/${hand}.$exlab.FS.annot.gii

                    # This has a color map, but suma does not properly use it.
                    # Use 3dcopy instead, to just get color index values (and
                    # essentially throw away the colormap).
                    #
                    # ConvertDset -i $ddd/${hand}.$exlab.FS.annot.gii \
                    #             -o $ddd/${hand}.$exlab.annot.niml.dset
                    
                    3dcopy $ddd/${hand}.$exlab.FS.annot.gii \
                           $ddd/${hand}.$exlab.annot.niml.dset
                 end
              end
           else
              echo "** missing surf input to mris_convert for -extra_fs_dsets"
           endif
        endif
        
        # ------------------------------------------------------------
        # convert standard annot files
        foreach hand ( lh rh )
            if ( -f ${hand}.aparc.a2005s.annot ) then
                set ddd = $start_dir/$suma_dir
                FSread_annot   -input ${hand}.aparc.a2005s.annot       \
                     $fsannot_opt                                      \
                    -roi_1D  $ddd/${hand}.aparc.a2005s.annot.1D.roi    \
                    -dset    $ddd/${hand}.aparc.a2005s.annot.niml.dset \
                    -cmap_1D $ddd/${hand}.aparc.a2005s.annot.1D.cmap 
            endif
     
            if ( -f ${hand}.aparc.a2009s.annot ) then
                set ddd = $start_dir/$suma_dir
                FSread_annot   -input ${hand}.aparc.a2009s.annot       \
                     $fsannot_opt                                      \
                    -roi_1D  $ddd/${hand}.aparc.a2009s.annot.1D.roi    \
                    -dset    $ddd/${hand}.aparc.a2009s.annot.niml.dset \
                    -cmap_1D $ddd/${hand}.aparc.a2009s.annot.1D.cmap 
            endif

            foreach pp (prob predict)
                if ( -f ${hand}.v1.${pp}.label ) then
                    sed '1,2s/^/#/' ${hand}.v1.${pp}.label                \
                        > ${hand}.v1.${pp}.label.1D
                    ConvertDset                                           \
                            -input ${hand}.v1.${pp}.label.1D'[$]'         \
                            -node_index_1D ${hand}.v1.${pp}.label.1D'[0]' \
                            -o_niml                                       \
                            -prefix $start_dir/$suma_dir/${hand}.v1.${pp} 
                    \rm -f ${hand}.v1.${pp}.label.1D
                    cd $start_dir/$suma_dir/
                    3drefit -sublabel 0 v1_${pp} ${hand}.v1.${pp}.niml.dset
                    cd -
                endif
            end
     
        end
        cd $start_dir
    endif
   
    #and the thickness data
    cd $surf_dir
    foreach hand ( lh rh )
        foreach tp ($fsdsets)
            if ( -f ${hand}.${tp} ) then
                echo "++ Converting surf dsets:  ${hand}.${tp}"
                mris_convert -c ${hand}.${tp} ${hand}.white ${hand}.${tp}.gii
                mv  ${hand}.${tp}.gii   \
                    $start_dir/$suma_dir/${hand}.${tp}.gii.dset
            endif
        end
    end
    cd $start_dir
   
    #and make semi inflated surfaces
    cd $suma_dir
    if ($#inflates > 0) then
        foreach inf ($inflates)
            set surf_attribs = ($surf_attribs inf_${inf})
        end
        foreach hand ( lh rh )
            foreach inf ($inflates) 
                if ( -f ${hand}.white.asc ) then
                    set iis = ${hand}.white.asc
                else if ( -f ${hand}.white.gii ) then
                    set iis = ${hand}.white.gii
                else
                    set endstr = ( "failure: Did not find white for inflation" )
                    goto L_BAD_END
                endif
                SurfSmooth  \
                    -i ${iis}    -met NN_geom \
                    -Niter $inf  -o_gii   -surf_out ${hand}.inf_${inf} \
                    -match_vol 0.01
                if ( $hand == lh ) then
                    set list_lh = ($list_lh ${hand}.inf_${inf})
                else
                    set list_rh = ($list_rh ${hand}.inf_${inf})
                endif
            end
        end
    endif
    cd $start_dir
   
goto L_CONVERT_SURFACES_DONE


####################################################################
# actually create the spec file

L_CREATE_SPEC:

    cd $suma_dir

    foreach hand ( lh rh )
        if ( $hand == lh ) then
            set list_cur = ( $list_lh )      # get a current list copy
        else
            set list_cur = ( $list_rh )
        endif

        set spec_file = {$subj_id}_$hand.spec

        if ( $debug ) echo "++ creating spec file '$spec_file'..."

        (echo "# delimits comments" > $spec_file) >& /dev/null

        if ( $status ) then
            set endstr = ( "failure: no permissions to create spec file" \
            "'$suma_dir/$spec_file'" )
            goto L_BAD_END
        endif

        # note user, date, machine, pwd, command line
        echo ""                     >> $spec_file
        echo "# Creation information:"            >> $spec_file
        echo "#     user    : $user"            >> $spec_file
        echo "#     date    : `date`"            >> $spec_file
        echo "#     machine : `uname -n`"         >> $spec_file
        echo "#     pwd     : $cwd"            >> $spec_file
        echo "#     command : $prog_name $argv"         >> $spec_file
        echo ""                     >> $spec_file
   
        # define the group
        echo "# define the group"            >> $spec_file
        echo "        Group = $subj_id"            >> $spec_file
        echo ""                     >> $spec_file

        # define the states
        echo "# define various States"            >> $spec_file
        foreach attrib ( $surf_attribs )
            echo "        StateDef = $attrib"         >> $spec_file
        end
        echo ""                     >> $spec_file

        foreach surf ( $list_cur )
            set s_head = `echo $surf | cut -d. -f1`   # up to first '.'
            set s_state = `echo $surf | cut -d. -f2-`   # after first '.'
            
            set label_dset = ""      
            # check for SAME mapping ref
            if ( "$surf.${sex}" == "$s_head.smoothwm.${sex}" ) then
                set map_ref = SAME
                if ( -f ${hand}.aparc.a2005s.annot.niml.dset ) then
                    set label_dset = ${hand}.aparc.a2005s.annot.niml.dset
                endif
                if ( -f ${hand}.aparc.a2009s.annot.niml.dset ) then
                    set label_dset = ${hand}.aparc.a2009s.annot.niml.dset
                endif
            else
                set map_ref = $s_head.smoothwm.${sex}
            endif
       
            # check for SAME mapping ref case for pial-outer
            if ( "$surf.${sex}" == "$s_head.pial-outer-smoothed.${sex}" ) then
                set map_ref = SAME
            else
                #abide by previous setting
            endif
       
            # EmbedDimension is 2 for .flat surfaces, else 3
            if ( $surf =~ *.flat* ) then
                set embed_ref = 2
            else
                set embed_ref = 3
            endif

            # Anatomical flag
            if ( $surf =~ *.white* ||\
                 $surf =~ *.smoothwm* ||\
                 $surf =~ *.pial*) then
                set anatomical = Y
            else
                set anatomical = N
            endif
       
            echo "NewSurface"               >> $spec_file
            echo "        SurfaceFormat = ASCII"      >> $spec_file
            echo "        SurfaceType = ${stp}"      >> $spec_file
            echo "        ${sfieldname} = $surf.${sex}"   >> $spec_file
            echo "        LocalDomainParent = $map_ref"      >> $spec_file
            echo "        SurfaceState = $s_state"      >> $spec_file
            echo "        EmbedDimension = $embed_ref"      >> $spec_file
            echo "        Anatomical = $anatomical" >> $spec_file
            if ("$label_dset" != "") \
                echo "        LabelDset = $label_dset" >> $spec_file
                echo ""                  >> $spec_file
        end # foreach surf

        echo "++ created spec file'$suma_dir/$spec_file'"
    end    # foreach hand

    # Create both.spec file
    set spec_file = {$subj_id}_both.spec
    set sample_spec = ${subj_id}_lh.spec

    if ( $debug ) echo "++ creating spec file '$spec_file'..."

    (echo "# delimits comments" > $spec_file) >& /dev/null

    if ( $status ) then
        set endstr = ( "failure: no permissions to create spec file" \
                       "'$suma_dir/$spec_file'" )
        goto L_BAD_END
    endif

    # note user, date, machine, pwd, command line
    echo ""                     >> $spec_file
    echo "# Creation information:"            >> $spec_file
    echo "#     user    : $user"            >> $spec_file
    echo "#     date    : `date`"            >> $spec_file
    echo "#     machine : `uname -n`"         >> $spec_file
    echo "#     pwd     : $cwd"            >> $spec_file
    echo "#     command : $prog_name $argv"         >> $spec_file
    echo ""                     >> $spec_file
   
    # define the group
    echo "# define the group"            >> $spec_file
    echo "        Group = $subj_id"            >> $spec_file
    echo ""                     >> $spec_file

    # define the states
    echo "# define various States"            >> $spec_file
    foreach attrib ( $surf_attribs )
        if (  $attrib =~ *sphere*  || \
              $attrib =~ *flat*    || \
              $attrib =~ *infla*) then
            echo "        StateDef = ${attrib}_lh"         >> $spec_file
            echo "        StateDef = ${attrib}_rh"         >> $spec_file
        else
            echo "        StateDef = $attrib"         >> $spec_file
        endif
    end
    echo ""                     >> $spec_file
    foreach hand ( lh rh )
        if ( $hand == lh ) then
            set list_cur = ( $list_lh )      # get a current list copy
        else
            set list_cur = ( $list_rh )
        endif

        foreach surf ( $list_cur )
            set s_head = `echo $surf | cut -d. -f1`   # up to first '.'
            set s_state = `echo $surf | cut -d. -f2-` # after first '.'
       
            if ( $s_state =~ *sphere* || \
                 $s_state =~ *flat*   || \
                 $s_state =~ *infla*) then
                set s_state = "${s_state}_${hand}"
            endif
       
            set label_dset = ""
            # check for SAME mapping ref
            if ( "$surf.${sex}" == "$s_head.smoothwm.${sex}" ) then
                set map_ref = SAME
                if ( -f ${hand}.aparc.a2005s.annot.niml.dset ) then
                    set label_dset = ${hand}.aparc.a2005s.annot.niml.dset
                endif
                if ( -f ${hand}.aparc.a2009s.annot.niml.dset ) then
                    set label_dset = ${hand}.aparc.a2009s.annot.niml.dset
                endif
            else
                set map_ref = $s_head.smoothwm.${sex}
            endif

            # EmbedDimension is 2 for .flat surfaces, else 3
            if ( $surf =~ *.flat* ) then
                set embed_ref = 2
            else
                set embed_ref = 3
            endif

            # Anatomical flag
            if ( $surf =~ *.white* ||\
                 $surf =~ *.smoothwm* ||\
                 $surf =~ *.pial*) then
                set anatomical = Y
            else
                set anatomical = N
            endif

            echo "NewSurface"                           >> $spec_file
            echo "        SurfaceFormat = ASCII"        >> $spec_file
            echo "        SurfaceType = ${stp}"         >> $spec_file
            echo "        ${sfieldname} = $surf.${sex}" >> $spec_file
            echo "        LocalDomainParent = $map_ref" >> $spec_file
            echo "        SurfaceState = $s_state"      >> $spec_file
            echo "        EmbedDimension = $embed_ref"  >> $spec_file
            echo "        Anatomical = $anatomical"     >> $spec_file
            if ("$label_dset" != "") \
                echo "        LabelDset = $label_dset"  >> $spec_file
                echo ""                                 >> $spec_file
        end
    end    # foreach hand

    echo "++ created spec file'$suma_dir/$spec_file'"

    cd $start_dir

goto L_CREATE_SPEC_DONE


####################################################################
# actually create an AFNI dataset

L_CREATE_BRICK:

    cd $orig_dir
    # verify existence of 256 COR files, Checking for 256 is now
    # obsolete ZSS Oct 14 04
    set cor_files = ( `echo COR-???` ) >& /dev/null 
    
    if ( $status || $use_mgz == 1) then
        if ($orig_mgz != "") then   
            #Try the orig.mgz business
            echo "No COR files, converting $orig_mgz ..."
            cd $start_dir
            mri_convert -ot cor $orig_mgz $orig_dir
            cd $orig_dir
        else 
            if ($use_mgz == 0) then
                set endstr = "failure: No COR files and no $orig.mgz"
            else
                set endstr = "failure: No mgz files"
            endif
            goto L_BAD_END
        endif
    else
        if ($orig_mgz != "" && $neuro_ori != -1) then  
            echo ""
            echo "Notice: Found COR files and $orig_mgz"
            echo "******** Will use COR files."
            echo ""
        else if ($orig_mgz == "" && $neuro_ori == -1) then  
            set endstr = "No orig_mgz found for -nocor option"
            goto L_BAD_END
        endif
    endif
   
    #check again
    set cor_files = ( `echo COR-???` ) >& /dev/null 
    if ( $status ) then
        set endstr = "failure: did not find COR files under '$orig_dir'"
        goto L_BAD_END
        #else if ( $#cor_files != 256 ) then
        #set endstr = "failure: 256 COR files required under '$orig_dir'"
        #goto L_BAD_END
    endif

    # create BRIK with to3d

    #SLAB changed by ZSS Mar 12 04. was 0.5 mm off. Bug pointed
    #out by A. Thomas. Good info found here:
    #www.wideman-one.com/gw/brain/fs/coords/fscoords.htm
    
    #New block added for reading COR images that are no longer 
    #256x256x256 / 1mm cubic voxels ZSS Oct 20 04
      
    set Sr = `\grep -w imnr0 COR-.info`
    set i0 = $Sr[$#Sr]
    set Sr = `\grep -w imnr1 COR-.info`
    set i1 = $Sr[$#Sr]
    set Sr = `\grep -w fov COR-.info`
    set FOV = `ccalc -eval $Sr[$#Sr] \* 1000`
    set Sr = `\grep -w x COR-.info | \grep -v xform`
    set nx = $Sr[$#Sr]
    set Sr = `\grep -w y COR-.info`
    set ny = $Sr[$#Sr]
    set Sr = `\grep -w thick COR-.info`
    set zthick = `ccalc -eval $Sr[$#Sr] \* 1000`
    set Sr = `\grep -w psiz COR-.info`
    set psize = `ccalc -eval $Sr[$#Sr] \* 1000`

    set xSLAB0 = `ccalc -eval $nx \* $psize / 2`
    set xSLAB1 = `ccalc -eval $xSLAB0 - $psize`
    set ySLAB0 = `ccalc -eval $ny \* $psize / 2`
    set ySLAB1 = `ccalc -eval $ySLAB0 - $psize`
    set zSLAB0 = `ccalc -eval '('$i1 - $i0 + 1')' \* $zthick / 2`
    set zSLAB1 = `ccalc -eval $zSLAB0 - $zthick`

    
    if ( $neuro_ori == 1 ) then
        to3d \
            -prefix $afni_prefix \
            -xSLAB $xSLAB0'L'-$xSLAB1'R' \
            -ySLAB $ySLAB0'S'-$ySLAB1'I' \
            -zSLAB $zSLAB0'P'-$zSLAB1'A' '3Db:0:0:'$nx':'$ny':1:COR-???'
        #to3d -prefix $afni_prefix -xSLAB 127L-128R -ySLAB 128S-127I \
        #  -zSLAB 128P-127A $cor_files
    else if ( $neuro_ori == 0 ) then
        to3d \
            -prefix $afni_prefix \
            -xSLAB $xSLAB0'R'-$xSLAB1'L' \
            -ySLAB $ySLAB0'S'-$ySLAB1'I' \
            -zSLAB $zSLAB0'P'-$zSLAB1'A' '3Db:0:0:'$nx':'$ny':1:COR-???'
        #to3d -prefix $afni_prefix -xSLAB 128R-127L -ySLAB 128S-127I \
        #  -zSLAB 128P-127A $cor_files
    else if ( $neuro_ori == -1 ) then
        if ( "$orig_mgz" == '' ) then
            set endstr = "Could not locate orig_mgz volume"
            goto L_BAD_END
        endif
        mri_convert -ot nii $start_dir/$orig_mgz \
                $start_dir/$suma_dir/${orig_mgz:t:r}".nii"
    else 
        set endstr = "Bad value for neuro_ori of $neuro_ori"
        goto L_BAD_END
    endif

    if ( $neuro_ori == -1 ) then
        mv \
            $start_dir/$suma_dir/${orig_mgz:t:r}".nii"  \
            $start_dir/$suma_dir/$afni_dataset.nii
        # need an AFNI ID code for afni/suma communication [12 Apr 2024 rickr]
        3drefit -newid $start_dir/$suma_dir/$afni_dataset.nii
        echo "++ created AFNI file '$suma_dir/$afni_dataset.nii'"
    else
        mv $afni_dataset.HEAD $afni_dataset.BRIK* $start_dir/$suma_dir

        echo "++ created AFNI file '$suma_dir/$afni_dataset.HEAD'"
        echo "++ created AFNI file '$suma_dir/$afni_dataset.BRIK'"
    endif

    cd $start_dir
    
    if ($#other_mgz > 0) then
        #       cat /Applications/freesurfer/FreeSurferColorLUT.txt | grep -v "^#" | sed '/^[[:space:]]*$/d' > fslut.txt
        # first unranked original datasets - reliably constant across subjects
        @FS_roi_label -name ALL -labeltable $start_dir/$suma_dir/fs_table
        if -e $start_dir/$suma_dir/fs_table.niml.lt then
            echo "Made roi label table for AFNI - fs_table.niml.lt"
        else
            echo "ERROR: failed to make roi label table fs_table.niml.lt"
        endif

        #Do the other .mgz files
        foreach other ($other_mgz)
            #@SUMA_FSvolToBRIK $other $start_dir/$suma_dir/$other:t:r
            #rm -f $start_dir/$suma_dir/COR-??? $start_dir/$suma_dir/COR-.info \
            #                                                     >& /dev/null
            mri_convert -ot nii $other $start_dir/$suma_dir/${other:t:r}".nii"
            #Now shift the damned volumes to match the surface volumes
            cd $start_dir/$suma_dir/
            if ($neuro_ori != -1 ) then
                @Align_Centers                \
                    -base $afni_dataset       \
                    -dset ${other:t:r}".nii"  \
                    -no_cp
            endif
            if ( "${other:t:r}" == "aparc.a2005s+aseg" ||   \
                 "${other:t:r}" == "aparc.a2009s+aseg" ||   \
                 "${other:t:r}" == "aseg" ||                \
                 "${other:t:r}" == "aparc+aseg" ) then
                # put atlas labels into FreeSurfer segmentation datasets
                # first use generic FS table that's the same for all datasets
                # [PT]  ??? Put parentheses here???
                if ( -e $start_dir/$suma_dir/fs_table.niml.lt ) then
                    3drefit -labeltable $start_dir/$suma_dir/fs_table.niml.lt \
                        "${other:t:r}.nii"
                    @MakeLabelTable -replace                      \
                        -atlasize_labeled_dset "${other:t:r}.nii"
                endif

                if ( $DO_MAKE_RANK_DSETS ) then

                    echo "++ Caveat emptor:  *rank* dsets coming your way"
                    # now ranked datasets-removing empty indices - easier
                    # to color in AFNI
                    3dmerge -1rank -prefix "${other:t:r}_rank.nii" \
                        ${other:t:r}".nii"
                    if (0) then
                        # kill this block soon.
                        set kk = `echo ${other:t:r} | cut -f 1 -d '+'`
                        mv ${kk}.rankmap.1D ${other:t:r}.rankmap.1D 
                    endif
                    @FS_roi_label                             \
                        -name ALL                             \
                        -rankmap ${other:t:r}_rank.rankmap.1D \
                        -labeltable ${other:t:r}_rank         \
                        > ${other:t:r}_rank.niml.lt.log
                    if ($status) then
                        echo "Failed to make roi labels for $other"
                    else
                        3drefit \
                            -labeltable ${other:t:r}_rank.niml.lt \
                            "${other:t:r}_rank.nii"
                        @MakeLabelTable \
                            -replace    \
                            -atlasize_labeled_dset "${other:t:r}_rank.nii"
                    endif

                endif

            endif
            cd - 
        end
    endif
    
    #Change from orig space
    if ( ${set_space} != '') then
        cd $start_dir/$suma_dir/
        3drefit -space ${set_space} *.nii* *.HEAD
        cd -
    endif
      
goto L_CREATE_BRICK_DONE

####################################################################
# echo run MapIcosahedron 

L_ICO:

    if ($#ldlist < 1) goto L_ICO_DONE
   
    echo ""
    echo "------------------------------------------------------------------"
    echo "Running MapIcosahedron for both hemispheres at ld values of $ldlist"
    cd $start_dir/$suma_dir/
    set ild = 0
    foreach ld ($ldlist)
        @ ild ++
        set both = ()
        foreach hem (lh rh)
            set sp = {$subj_id}_${hem}.spec
            set dm = ()
            if ($#fsdsets > 0) then
                foreach fsd ($fsdsets)
                    if ( -f ${hem}.${fsd}.gii.dset ) then
                        set dm = ($dm "-dset_map" ${hem}.${fsd}.gii.dset)
                    endif
                end
            endif

            if ($#extra_annot_labels > 0) then
                foreach alab ($extra_annot_labels)
                    set aset = ${hem}.${alab}.annot.niml.dset
                    if ( -f $aset ) then
                        set dm = ($dm "-NN_dset_map" $aset)
                    endif
                end
            endif

            if ( -f $sp) then
                # possibly add -verb    19 Mar 2017 [rickr]
                if ( $debug ) then
                    set vb = "-verb"
                else
                    set vb = ""
                endif
                MapIcosahedron $vb -spec $sp -ld $ld $dm -prefix $ldpref[$ild] 
                set both = ($both ${ldpref[$ild]}{$subj_id}_${hem}.spec)
            endif
        end # foreach hem
        if ($#both == 2) then
            inspec -LRmerge $both -prefix ${ldpref[$ild]}{$subj_id}_both.spec
        endif
    end # foreach ld
    # pass a better sample spec file along
    set sample_spec = $ldpref[1]${subj_id}_lh.spec
    cd -
   
goto L_ICO_DONE

####################################################################
# echo details for the user to launch suma and afni, in order to
# check the alignment

L_TEST_SURF_VOL:

    echo ""
    echo "------------------------------------------------------------------"
    echo "Please verify that the datasets are aligned properly in both"
    echo "afni and suma.  You may do this by running the following commands:"
    echo ""
    echo "    cd $suma_dir"
    echo "    afni -niml &"
    if ( -f ${suma_dir}/${afni_dataset}.nii ) then
        set ovol = ${afni_dataset}.nii
    else if ( -f ${suma_dir}/${afni_dataset}.nii.gz ) then
        set ovol = ${afni_dataset}.nii.gz
    else 
        set ovol = $afni_dataset
    endif
    echo "    suma -spec $spec_file -sv $ovol"

    echo "suma -spec $sample_spec -sv $ovol" > $suma_dir/run_suma_00_basic.txt

goto L_TEST_SURF_VOL_DONE

####################################################################
# [PT, Jan 26, 2020]
# have an AFNI+suma driving script made

L_MAKE_DRIVE_SCRIPT:

printf "" >   $suma_dir/run_suma_01_with_afni.tcsh
cat << EOF >> $suma_dir/run_suma_01_with_afni.tcsh
#!/bin/tcsh

# This is an example script for driving AFNI+SUMA and having them talk

set suma_spec = std.141.*_both.spec
set all_sv    = ( *SurfVol*{nii,HEAD}* )
set dset_sv   = \${all_sv[1]}

if ( \$status || "\${?suma_spec}" == "0" ) then
    echo "** Some badness with finding files"
    exit 1
endif

# --------------------- preliminary settings -----------------------

# you can set other env vars if you want
setenv AFNI_ENVIRON_WARNINGS       NO
setenv SUMA_DriveSumaMaxCloseWait   6
setenv SUMA_DriveSumaMaxWait        6

set portnum = `afni -available_npb_quiet`

# ------------------------- open the GUIs --------------------------

afni -npb \${portnum} -niml  &

sleep 2

suma                                                    \
    -onestate                                           \
    -npb   \${portnum}                                   \
    -spec  \${suma_spec}                                 \
    -sv    \${dset_sv} &

sleep 2

DriveSuma                                               \
    -npb \${portnum}                                     \
    -com viewer_cont -key 't' -key '.' 

# ------------------------- Finish up ---------------------------

if ( \$status ) then
    echo "** Some badness with driving SUMA"
    exit 1
endif

echo ""
echo "++ AFNI+SUMA should be up and talking now..."
echo ""

EOF

goto L_MAKE_DRIVE_SCRIPT_DONE

####################################################################
# [PT, Dec 30, 2016]
# finally replacing rank utility.

L_RENUMBER_ROIS:

    echo "\n\n++ Going to make renumbered ROIs now."
    echo "    --> done for colorbar and making tissue maps."
    echo "        See '@SUMA_renumber_FS -help' for description.\n\n"

    @SUMA_renumber_FS $suma_dir

goto L_RENUMBER_ROIS_DONE

####################################################################
# [PT, Mar 3 2021]
# Make a useful WB mask and QC images;  also make tables of ROI info.

L_MASK_QC_ROIS:

    echo "\n\n++ Going to make a nice WB mask."
    echo "       ... and some useful QC images."
    echo "       ... and some useful ROI info tables.\n\n"

    adjunct_suma_fs_mask_and_qc             \
        -sid       ${subj_id}               \
        -suma_dir  $suma_dir

    adjunct_suma_fs_roi_info                \
        -sid       ${subj_id}               \
        -suma_dir  $suma_dir

goto L_MASK_QC_ROIS_DONE

####################################################################
# [27 Jan 2020 rickr]
# compress SUMA/*.nii, except for SurfVol

L_COMPRESS_FILES:

    # maybe the user does not want to compress
    if ( ! $do_compress ) then
        if ( $debug ) echo "-- skipping NIFTI compression"
        goto L_COMPRESS_FILES_DONE
    endif

    # be sure gzip is in the path
    (which gzip) >& /dev/null
    if ( $status ) then
        echo "program not found in path: gzip, skipping compress"
        goto L_COMPRESS_FILES_DONE
    endif

    cd $suma_dir

    # do this very simply, for clarity
    # first zip everything, then unzip SurfVol
    if ( -f $afni_dataset.nii ) then
       echo "\n\n++ Compressing all remaining .nii files, except for SurfVol.\n"

       gzip *.nii
       gunzip $afni_dataset.nii.gz
    endif

    cd -


goto L_COMPRESS_FILES_DONE

####################################################################
# display help and exit

L_HELP_END:

cat <<EOF

OVERVIEW ~1~

$prog_name - prepare for surface viewing in SUMA

This script goes through the following steps:
    + verify existence of necessary programs 
      (afni, to3d, suma, mris_convert)
    + determine the location of surface and COR files
    + creation of ascii surface files via 'mris_convert'
    + creation of left and right hemisphere SUMA spec files
    + creation of an AFNI dataset from the COR files via 'to3d'
    + creation of AFNI datasets from various .mgz volumes created
      by FreeSurfer. The segmentation volumes with aseg in the 
      name are best viewed in AFNI with the FreeSurfer_Seg_255
      colormap. See bottom of @SUMA_FSvolToBRIK -help for more
      info.
    + renumbered data sets output, to replace old '*rank*' file data
      sets. Also new tissue maps based on FS functions and
      labels. Collectively, these are the '*REN*' dsets in the output
      directory.  (Rank dsets are no longer output by default, from
      Nov, 2019; instead, use -make_rank_dsets if really needed.)
    + convenience dsets for afni_proc.py processing with tissue-based
      regressors (fs_ap_* files: subset of ventricle and WM maps)

    + all created files are stored in a new SUMA directory

USAGE ~1~ 

        $prog_name [options] -sid SUBJECT_ID

  examples ('-NIFTI' is really useful-- see below!):

        $prog_name -help
        $prog_name -NIFTI -sid subject1
        $prog_name -NIFTI -fspath subject1/surface_stuff -sid subject1
        $prog_name -NIFTI -sid 3.14159265 -debug 1

OPTIONS ~1~

    -help    : show this help information

    -debug LEVEL    : print debug information along the way
          e.g. -debug 1
          the default level is 0, max is 2

          A debug level of 2 will "set echo", so one can follow the actual
          commands executed in the script.

    -fs_setup       : source \$FREESURFER_HOME/SetUpFreeSurfer.csh

          This might be useful on OS X, as FreeSurfer uses DYLD_LIBRARY_PATH,
          which does not propagate to child shells.  Then this program would
          require them to source SetUpFreeSurfer.csh from .cshrc, which might
          happen too often and could be irrirating.

          With -fs_setup, that will happen from within this script, so it is
          not necessary to do from the .cshrc file.

    -fspath PATH    : path to 'surf' and 'orig' directories
          e.g. -fspath subject1/surface_info
          the default PATH value is './', the current directory

          This is generally the location of the 'surf' directory,
          though having PATH end in surf is OK.  The mri/orig
          directory should also be located here.

          Note: when this option is provided, all file/path
          messages will be with respect to this directory.

    -extra_annot_labels L1 L2 ...  : convert extra annot files into ROI dsets
          e.g. -extra_annot_labels aparc

          FS typically outputs annotation files:
                lh.aparc.a2005s.annot
                rh.aparc.a2005s.annot
                lh.aparc.a2009s.annot
                rh.aparc.a2009s.annot
          from each of which Make_Spec extracts a colormap, ROI and a
          displayable surface dataset.

          Use this option to specify other labels to extract.

          If LABEL is specified, then expected annotation files will be:
                lh.LABEL.annot
                rh.LABEL.annot

    -extra_fs_dsets AA BB CC ...
                    : FS calculates many types of data on the surface,
          listed in their surf/ output directory.  By default, this
          program brings the following ones into the SUMA surface realm:
                thickness   curv   sulc
          which get turned into 'std.141.{l,r}h.curv.niml.dset' and
          '{l,r}h.curv.gii.dset' files, for example.
          This option allows the user to list *other* dsets to include,
          as well.  Ones that users have selected are, for example:
                volume   area   area.pial   curv.pial

    -make_rank_dsets : before Nov 14, 2019, *rank* dsets used to be
          created by this command by default; these dsets mapped the
          FreeSurfer ROI numbering to a 1..N set of labels, where N
          was the number of ROIs.  Because this number might *not* be
          constant across a group (though, the ROI string labels in
          each would be), we don't recommend using these; the *REN*
          dsets are renumbered in a consistent, mapped way, and so
          those are more useful.  The present option is purely for
          backward compatibility, for Zome Special Scientists out
          there who might still use these dsets.

    -use_mgz        : use MGZ volumes even if COR volumes are there

    -neuro          : use neurological orientation
          e.g. -neuro
          the default is radiological orientation

          In the default radiological orientation, the subject's
          right is on the left side of the image.  In the
          neurological orientation, left is really left.

        * This is not compatible with -NIFTI.

    -nocor: This option is no longer supported because it created
            GIFTI surfaces with coordinates in RAI, rather than LPI
            which is the GIFTI standard. While using RAI surfaces
            within AFNI/SUMA is not problematic, the resultant GIFTI
            surfaces do not port well to other software.
            The replacement option for -nocor is -GNIFTI but the
            surfaces will have negated coordinates along the x and y
            compared to those with -nocor.
            GIFTI surfaces produced with SUMA programs compiled before
            August 1st 2013 will have their X and Y coordinates 
            negated and will no longer line up with the anatomy. 
            Correcting such surfaces can be done with ConvertSurface
            with the following command:

                ConvertSurface                \
                    -i lh.smoothwm.gii        \
                    -o_gii lh.smoothwm        \
                    -overwrite                \
                    -xmat_1D NegXY

            or for an entire SUMA directory:

                cd SUMA
                tcsh
                foreach ss (*.gii)
                    ConvertSurface            \
                        -i \$ss                \
                        -o_gii \$ss            \
                        -overwrite            \
                        -xmat_1D NegXY
                end

    -GNIFTI/-GIFTI/-IFTI: same as -NIFTI

    -NIFTI :Produce files in exchangeable formats. With this option
           :COR volumes are no longer used and output volumes
           :and surfaces are in alignment with the original 
           :volume used to create the surface. All volumes are
            written out NIFTI format, and all surfaces are
            in GIFTI format.

            This option is incompatible with -neuro or -use_mgz

         ** Note: from 22 Feb 2013 through 20 Mar 2017, use of -NIFTI
                  would distort standard mesh surfaces.  To evaluate
                  effects of this, consider: MapIcosahedron -write_dist.

                * If you are seeing this message, that problem was fixed
                  years ago.

    -inflate INF: Create modereately inflated surfaces using
                  SurfSmooth. INF controls the amount of smoothness
                  in the final image. It is the number of iterations
                  in the command such as: 
                    SurfSmooth               \
                        -i lh.white.asc      \
                        -met NN_geom         \
                        -Niter 200           \
                        -o_gii               \
                        -surf_out lh.inf_200 \
                        -match_vol 0.01

                  You can use multiple instances of -inflate to create
                  inflations of various levels.
    -set_space  SPACE: Set the space flag of all volumes to
            SPACE (orig, MNI, TLRC, MNIa). The default is 
            orig space.
            You should only use this option when the volume you
            passed to FreeSurfer was not in 'orig' space.
            Use '3dinfo -space YOUR_DATASET' to find the space 
            of a certain dataset.

    -sid SUBJECT_ID : required subject ID for file naming

    -ld LD : Create standard mesh surfaces with mesh density
             linear depth (see MapIcosahedron -help, option -ld)
             set to LD. You can use multiple -ld options.
             By default the script will run ld values of 141 and
             60.
    -ldpref LDpref: Supply what ends up being the -prefix option
                    for MapIcosahedron. By default it is std.LD.
                    You need as many -ldpref as you have -ld
    -no_ld: Do not run MapIcosahedron.

NOTES ~1~

  Making use of FreeSurfer's -contrasurfreg output with MapIcosahedron:
  This script will create SUMA versions of lh.rh.sphere.reg and 
  rh.lh.sphere.reg but in this current state, MapIcosahedron does
  not attempt to use them for backward compatibility.
  Should you want to create standard mesh surfaces with node
  index correspondence across the hemispheres you will need to run
  MapIcosahedron manually in the output SUMA/ directory. 

  For example:
        MapIcosahedron                        \
            -spec SUBJ_rh.spec -ld 60         \
            -dset_map rh.thickness.gii.dset   \
            -dset_map rh.curv.gii.dset        \
            -dset_map rh.sulc.gii.dset        \
            -morph rh.lh.sphere.reg.gii       \
            -prefix std.60.lhreg.

  This command is very similar to the one use to create the default
  output spec file std.60.SUBJ_rh.spec (look at the top of the spec
  file for a record of the command that created it), except for the
  last two options -morph and -prefix.  By using -morph
  rh.lh.sphere.reg.gii the resultant standard-mesh right hemispheres
  (std.60.lhreg.rh.*.gii) will have node index correspondence with
  std.60.lh.*.gii surfaces.  To verify visually the correspondence,
  run the following:

     count -column 0 36001 > std.60.lh.rh.nodeindex.1D.dset
     suma -noniml -spec std.60.SUBJ_lh.spec &
     suma -noniml -spec std.60.SUBJ_rh.spec &
     suma -noniml -spec std.60.lhreg.SUBJ_rh.spec &

  Then load std.60.lh.rh.nodeindex.1D.dset into each of the three SUMA
  windows. Note how the color pattern (node indices) matches between
  SUBJ_lh and lhreg.SUBJ_rh surfaces, but NOT between SUBJ_lh and
  SUBJ_rh surfaces.

COMMENTS ~1~

  0. More help may be found at:
     https://afni.nimh.nih.gov/pub/dist/doc/htmldoc/SUMA/main_toc.html
  1. Surface file names should look like 'lh.smoothwm'.
  2. Patches of surfaces need the word patch in their name, in
     order to use the correct option for 'mris_convert'.
  3. Flat surfaces must have .flat in their name.
  4. You can tailor the script to your needs. Just make sure you
     rename it or risk having your modifications overwritten with
     the next SUMA version you install.

  Authors to pester:
    R. Reynolds  (reynoldr@mail.nih.gov)
    Z. Saad      (saadz@mail.nih.gov)
    M. Beauchamp (michael.beauchamp@bcm.edu)

EOF

    exit


####################################################################
# failure!

L_BAD_END:

    echo ""
    if ( "$endstr" != "" ) echo "$endstr"
    echo program failure: exiting...
    echo ""

    exit

####################################################################
# finished!

L_GOOD_END:

    if ( $USING_NIFTI == 0 ) then
        echo "\n\n"
        echo "WARNING!"
        echo "  You didn't use the '-NIFTI' or '-GIFTI' or similarly-named"
        echo "  option flag! Are you *sure* you didn't want to?  Learning about"
        echo "  this option changed my life-- it might just change yours, too."
        echo "  Please read the helpfile entry for '-NIFTI' if you don't know"
        echo "  what I'm talking about here."
        echo "\n\n"
    endif

    if ( $debug > 1 ) unset echo

    echo ""
    if ( "$endstr" != "" ) then
        echo "$endstr"
        echo ""
    endif

    exit   # just to be consistent

