#!/bin/tcsh 

# quickspecSL generates a .spec file, generally after running
# SurfLayers.  With SUMA, the output .spec will open at the first
# surface specified during the SurfLayers command and step through all
# interpolations towards the second surface specified. To specify
# -both_lr option, directory files should be present & consistently
# named. SUMA will open both hemis simultaneously. Finally, you can
# create a spec file that relates inflated surfaces to their
# anatomically-correct counterparts. Use SurfSmooth for inflating.

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

# [PT] -bothlr -> -both_lr, to match SurfLayers
#set ver         = 0.05
# [ST] incorporate inflated surfaces with proper LDPs
#set ver         = 0.06
# [ST] edits to the help, comments, formatting
#set ver         = 0.07
#
set ver         = 0.08
# [PT] rename opts, to match better with SurfLayers
#    + rename some vars, too, to match with opt names


# ----------------------------------------------------------------------

set surf        = ( "" "" )
set csurf       = ( "" "" )
set surf_imed_pref = "isurf"
set anatldps    = ( "" "" )
set allinfs     = ( "" "" )
set infs        = ( "" "" )
set infl_surf_imed_pref = "infl.isurf"
set prog_name   = $0:t
set out_spec    = "newspec"
set both_lr     = ""
set lhshere     = ""
set rhshere     = ""
set hemientered = ""
set hemicontra  = ""

# ------------------------ process user options --------------------------

if ("$#" <  "1") then
   goto HELP
endif

set ac = 1
while ($ac <= $#argv)
    if ("$argv[$ac]" == "-help" || "$argv[$ac]" == "-h") then
        goto HELP

    else if ("$argv[$ac]" == "-ver") then
        echo $ver
        exit 0

    # -------------------

    else if ("$argv[$ac]" == "-surf_A") then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac ++
        set surf[1] = $argv[$ac]

    else if ("$argv[$ac]" == "-surf_B") then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac ++
        set surf[2] = $argv[$ac]

    else if ("$argv[$ac]" == "-surf_intermed_pref") then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac ++
        set surf_imed_pref = $argv[$ac]


    else if ( "$argv[$ac]" == "-both_lr" ) then
        set both_lr = 1


    else if ("$argv[$ac]" == "-infl_surf_A") then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac ++
        set infs[1] = $argv[$ac]

    else if ("$argv[$ac]" == "-infl_surf_B") then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac ++
        set infs[2] = $argv[$ac]

    else if ("$argv[$ac]" == "-infl_surf_intermed_pref") then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac ++
        set infl_surf_imed_pref = $argv[$ac]

    else if ("$argv[$ac]" == "-out_spec") then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac ++
        set out_spec = $argv[$ac]

    # ---------- fin ------------------

    else
        echo "** unknown option $argv[$ac]"
        exit 1
    endif
    @ ac ++
end

# ------------------------ checks -------------------------

if ($surf[1] == "" || $surf[2] == "" ) then
   echo "Not enough inputs: Use both -surf_A and -surf_B options"
   exit 1
endif

# check if contralateral input surfaces exist
set allgiis = `\ls *.gii`
if ($both_lr) then
    foreach checkall ( $allgiis )
        set lhshere = ($lhshere `echo $checkall | grep lh\?.`)
        set lhshere = ($lhshere `echo $checkall | grep lh.`)
        set rhshere = ($rhshere `echo $checkall | grep rh\?.`)
        set rhshere = ($rhshere `echo $checkall | grep rh.`)
    end
    if (("$lhshere" != "") && ("$rhshere" != "")) then
            echo "-both_lr given and files for both hemispheres found" 
        else
            echo "-both_lr given but files for only one hemisphere found"
        exit 1
    endif
endif

# ------------------------ BEGIN --------------------------

touch ${out_spec}.spec

# note execution info
echo "# Creation information:"         >> ${out_spec}.spec
echo "#     user    : $user"           >> ${out_spec}.spec
echo "#     date    : `date`"          >> ${out_spec}.spec
echo "#     machine : `uname -n`"      >> ${out_spec}.spec
echo "#     pwd     : $cwd"            >> ${out_spec}.spec
echo "#     command : $prog_name $argv">> ${out_spec}.spec
echo ""                     >> ${out_spec}.spec

# anat-and-inflated surfaces, separate from hemi & lateralization code:
if (("${infl_surf_imed_pref}" != "") && ($infs[1] != "")) then
    set qs_str = "-tsnad GII S1 $surf[1] Y SAME"
    set statei = 1

    # first the anatomically-correct surfaces
    set anatldps = ($surf[1]) #start it with surf1
    foreach surfs ( `\ls ${surf_imed_pref}.*.gii` $surf[2] )
      @ statei ++
       set qs_str = "$qs_str -tsnad GII S$statei $surfs Y SAME"
       set anatldps = ($anatldps $surfs)
    end

      set numasurfs = $statei # number of anatomical surfaces
      @ statei ++

    # then inflated versions with anatomically-correct surfaces as their LDPs
    set qs_str = "$qs_str -tsnad GII S$statei $infs[1] N $surf[1]" 
    foreach restofinfs ( `\ls ${infl_surf_imed_pref}*.gii` $infs[2] )
      set ref = `echo "(${statei}-${numasurfs})+1" | bc`
      @ statei ++
      set reffile = "$anatldps[$ref]"
      set qs_str = "$qs_str -tsnad GII S$statei $restofinfs N $reffile"
      set allinfs = ($infs[1] ${infl_surf_imed_pref}*.gii $infs[2])
    end

    # double check that N of anat surfs and N of inflated surfs are equal
    if ( $#allinfs != $#anatldps ) then
        echo "** number of inflated surfaces doesn't match # of anat surfaces"
        exit 1
    endif

    # otherwise make the spec file
    quickspec -spec tempspectail $qs_str
    cat tempspectail >> ${out_spec}.spec
    \rm tempspectail

    # print to terminal
    echo ""; echo "EXECUTE anat+inflated .spec WITH:"
    echo "suma -spec ${out_spec}.spec -sv ../*SurfVol.nii*"; echo ""

exit 0
endif

   # otherwise, no inflated surfaces are involved, so check
   # lateralization in command & determine contralat (used with -both_lr)
   echo $surf[1] |grep -i 'lh\.' > /dev/null
   if ($status == 0) then
      set hemientered = "lh"
      set hemicontra = "rh"
      set csurf[1] = `echo $surf[1] | sed 's/lh./rh./'`
      set csurf[2] = `echo $surf[2] | sed 's/lh./rh./'`
   else 
      set hemientered = "rh"
      set hemicontra = "lh"
      set csurf[1] = `echo $surf[1] | sed 's/rh./lh./'`
      set csurf[2] = `echo $surf[2] | sed 's/rh./lh./'`
   endif

if ($both_lr == "") then
    # build single hemi spec
    set qs_str = "-tsnad GII S1 $surf[1] Y SAME"
    set statei = 1
    foreach surfs ( `\ls ${surf_imed_pref}.${hemientered}*.gii` $surf[2] )
      @ statei ++
       set qs_str = "$qs_str -tsnad GII S$statei $surfs Y $surf[1]"
    end

    quickspec -spec tempspectail $qs_str

    \cat tempspectail >> ${out_spec}.spec
    \rm tempspectail

    # print to terminal
    echo ""
    echo "++ If you want to: jump to script directory:"
    echo "     cd ${PWD}"
    echo "++ Execute with:"
    echo "     suma -spec ${out_spec}.spec -sv ../*SurfVol.nii*"
    echo ""

else if ( $both_lr ) then
    # build both hemi spec
       set statei = 1
       set qs_str = "-tsnad GII S1 $surf[1] Y SAME"
       foreach surfs ( `\ls ${surf_imed_pref}.${hemientered}*.gii` $surf[2] )
         @ statei ++
          set qs_str = "$qs_str -tsnad GII S$statei $surfs Y $surf[1]"
       end
       quickspec -spec qstest$hemientered $qs_str

       set statei = 1
       set cqs_str = "-tsnad GII S1 $csurf[1] Y SAME"
       foreach surfs ( `\ls ${surf_imed_pref}.${hemicontra}*.gii` $csurf[2] )
         @ statei ++
          set cqs_str = "$cqs_str -tsnad GII S$statei $surfs Y $csurf[1]"
       end
       quickspec -spec qstest$hemicontra $cqs_str

   inspec -LRmerge qstest${hemientered} qstest${hemicontra} -prefix tempmerge

   \cat tempmerge.spec >> ${out_spec}.spec
   \rm tempmerge.spec qstest*
   \mv ${out_spec}.spec ${out_spec}_both.spec

   echo ""
   echo ""
   echo "++ If you want to: jump to script directory:"
   echo "     cd ${PWD}"
   echo "++ Execute with:"
   echo "     suma -spec ${out_spec}_both.spec -sv ../*SurfVol.nii*"
   echo ""

endif

exit 0

HELP:

cat << SCRIPT_HELP_STRING

Overview ~1~ 

This program makes a *.spec file after a set of intermediate surfaces 
have been generated with SurfLayers. 

It can also make a *.spec file that relates inflated surfaces to
anatomically-correct surfaces. An example of this is shown below in
the "Usage Example" section.

Options ~1~

  -surf_A   SA   :inner (anatomically-correct) boundary surface dataset
                  (e.g. smoothwm.gii)

  -surf_B   SB   :outer (anatomically-correct) boundary surface dataset
                  (e.g. pial.gii)

  -surf_intermed_pref  SIP 
                 :prefix for (anatomically-correct) intermediate surfaces,
                  typically output by SurfLayers 
                  (def: ${surf_imed_pref})

  -infl_surf_A  ISA 
                 :inner (inflated) boundary surface dataset
                  (e.g. infl.smoothwm.gii)

  -infl_surf_B  ISB  
                 :outer (inflated) boundary surface dataset
                  (e.g. infl.pial.gii)

  -infl_surf_intermed_pref  ISIP
                 :prefix for (inflated) intermediate surfaces,
                  typically output by SurfLayers 
                  (def: ${infl_surf_imed_pref})

  -both_lr       :specify an output spec for both hemispheres, 
                  if surfaces for both exist

  -out_spec      :name for output *.spec file 
                  (def: ${out_spec}.spec) 

Examples ~1~

  1) 

    quickspecSL                                  \
        -surf_A    lh.white.gii                  \
        -surf_B    lh.pial.gii                   \
        -surf_intermed_pref  lh.isurf


  2) 

    quickspecSL                                  \
        -both_lr                                 \
        -surf_A lh.white.gii                     \
        -surf_B lh.pial.gii


  3) First, make inflated boundary surfaces before running SurfLayers
     on the both those and the original surfaces:

    SurfSmooth -i rh.smoothwm.gii -met NN_geom -Niter 240    \
        -o_gii -surf_out rh.inf.smoothwm_240 -match_size 9

    SurfSmooth -i rh.pial.gii -met NN_geom -Niter 240        \
        -o_gii -surf_out rh.inf.pial_240 -match_size 9

    quickspecSL                                              \
        -surf_A             rh.white.gii                     \
        -surf_B             rh.pial.gii                      \
        -surf_intermed_pref rh.isurf                         \
        -infl_surf_A        rh.inf.smoothwm_240.gii          \
        -infl_surf_B        rh.inf.pial_240.gii              \
        -infl_surf_intermed_pref  infl.rh.isurf

Notes ~1~

If you have any questions, please contact:

   S. Torrisi (torrisi@berkeley.edu) 
   D. Glen    (glend@mail.nih.gov) 

for more info.

SCRIPT_HELP_STRING

goto GOOD_EXIT

# ----------------------------------------------------------------------

SHOW_VERSION:
   echo "version  $ver"
   goto GOOD_EXIT

FAIL_MISSING_ARG:
    echo "** ERROR! Missing an argument after option flag: '$argv[$ac]'"
    goto BAD_EXIT

BAD_EXIT:
    exit 1

GOOD_EXIT:
    exit 0

