#!/bin/tcsh -ef

# .... IN PROGRESS WRITING HELP ....

#### ---> get names from files to attach?

#set version   = "1.0";  set rev_dat   = "Oct 08, 2017"
#  + inception
#
#set version   = "1.2";  set rev_dat   = "Oct 11, 2017"
# + helpifying
# + seems to be stable...
# 
#set version   = "1.21";  set rev_dat   = "Oct 25, 2017"
# + more helpifying
# 
#set version   = "1.22";  set rev_dat   = "Dec 20, 2017"
# + make output prefix a dir, because there might be a loooot of files
# + take old "-prefix ..." functionality and move it to an option
#   flag name "-prefix_files"
#
set version   = "1.23";  set rev_dat   = "Dec 22, 2017"
# + new opt to output the 3dTcatted or 3dTstatted summation files
#
# ---------------------------------------------------------------

set this_prog = "fat_proc_connec_vis"
set tpname    = "${this_prog:gas/fat_proc_//}"
set here      = $PWD

# ----------------- find AFNI and set viewer ---------------------

# find AFNI binaries directory and viewer location
set adir      = ""
set my_viewer = ""
which afni >& /dev/null
if ( $status ) then
    echo "** Cannot find 'afni' (?!)."
    goto BAD_EXIT
else
    set aa   = `which afni`
    set adir = $aa:h
endif

# ----------------------- set defaults --------------------------

set here = $PWD

set fNN       = ()         # to be list of int ROI maps
set odir      = ""
set opref     = "wmc"
set merge_lab = ""

#set tmp_code = `3dnewid -fun11`    # should be essentially unique hash
set wdir = ""
set DO_CLEAN = 1
set cmd_file = ""                 # def: same name as viewer
set run_file = ""                 # def: same name as viewer
set output_cmd  = 1               # def: output copy of this command

set NO_OR     = 0
set tsmoo_kpb = 0.01
set tsmoo_nit = 6
set iso_choice = "isorois+dsets"

set DO_OUT_TCAT  = "0"            # [PT: Dec 22, 2017] new opt output
set DO_OUT_TSTAT = "0"            # [PT: Dec 22, 2017] new opt output

# ------------------- process options, a la rr ----------------------

if ( $#argv == 0 ) goto SHOW_HELP

set ac = 1
while ( $ac <= $#argv )
    # terminal options
    if ( ("$argv[$ac]" == "-h" ) || ("$argv[$ac]" == "-help" )) then
        goto SHOW_HELP
    endif
    if ( "$argv[$ac]" == "-ver" ) then
        goto SHOW_VERSION
    endif

    # --------------- input dset(s) ----------------

    # input volume 'source', likely to have opposite contrast to the
    # b0/T2w to which we are matching.
    if ( "$argv[$ac]" == "-in_rois" ) then
        set i0 = $ac
        # check that this ain't the end of argv[] entries
        if ( $i0 == $#argv ) then
            echo "** ERROR: need at least one dset after $argv[$ac]!"
            goto BAD_EXIT
        else 
            # check that next argv[] member isn't a new option: shd be
            # a dset
            @ i0 += 1
            set c0 = ""
            while ( ( $i0 <= $#argv ) && ( "$c0" != "-" )  )
                set fNN = ( $fNN "$argv[$i0]" )
                @ ac += 1

                @ i0 += 1
                if ( $i0 <= $#argv ) then
                    set c0 = `echo $argv[$i0] | awk '{print substr($0,1,1)}'`
                endif
            end

            if ( $#fNN == 0 ) then
                echo "** ERROR: need at least one dset after $argv[$ac]!"
                goto BAD_EXIT
            else
                echo "++ User has listed $#fNN followers_NN dsets"
            endif
        endif
    echo "TEMP: $fNN"

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

    # [PT: Dec 20, 2017] makes a new dir (if not preexisting)
    # specified by the user, and then splashes everything into that
    # dir; opref is specified by default name
    else if ( "$argv[$ac]" == "-prefix" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set odir   = "$argv[$ac]"

    # [PT: Dec 20, 2017] this splashes everything into a preexisting
    # dir
    else if ( "$argv[$ac]" == "-prefix_file" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set odir  = `dirname  "$argv[$ac]"`
        set opref = `basename "$argv[$ac]"`

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

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

    # isorois+dsets, mergerois, etc. might need quotes here, and extra
    # input for LAB_OUT, if used.
    else if ( "$argv[$ac]" == "-iso_opt" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set iso_choice = "$argv[$ac]"
    
    else if ( "$argv[$ac]" == "-wdir" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set wdir = "$argv[$ac]"

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

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

    # recognize naming convention of 3dTrackID output, and ignore
    # "or"-logic ROIs
    else if ( "$argv[$ac]" == "-trackid_no_or" ) then
        set NO_OR = 1
     
    else if ( "$argv[$ac]" == "-no_clean" ) then
        set DO_CLEAN = 0

    else
        echo "** unexpected option #$ac = '$argv[$ac]'"
        exit 2

   endif
   @ ac += 1
end

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

# ========================= output dir ==========================

if ( "$odir" == "" ) then
    echo "** ERROR: need to use either '-prefix ...' or '-prefix_file ...':"
    echo "   See the helpfile for more information."
    goto BAD_EXIT
endif 

# default output dir, if nothing input.
if ( ! -e "$odir" ) then
    echo "+* Output directory didn't exist.  Trying to make '$odir' now."
    mkdir "$odir"
endif

echo ""
echo "++ The output directory/prefix will be:"
echo "     $odir/$opref"
echo ""

# make the working directory
set wdir  = "$odir/__WDIR_${tpname}_${opref}"
if ( ! -e $wdir ) then
    echo "++ Making working directory: $wdir"
    mkdir $wdir
else
    echo "+* WARNING: Somehow found a premade working directory (?):"
    echo "     $wdir"

    # don't clean preexisting directories-- could be user
    # mistake.
    echo "   NB: will *not* clean it afterwards."
    set DO_CLEAN = "0"
endif

set ocmd   = "${opref}_cmd.txt"      # name for output command
set orun   = "${opref}_runsuma.tcsh" # basic suma view command

# ----> here, only need wdir if outputting imgs but no vol; see below

# =======================================================================
# =========================== ** PROCESS ** =============================
# =======================================================================

echo "\n-----> STARTING $this_prog ---->"

# ---------------------------- CMD ---------------------------------

echo "\n\nThis command:"
echo "$this_prog $argv\n\n"

if ( "$cmd_file" == "" ) then
    set cmd_file = "$odir/$ocmd"
endif
if ( "$run_file" == "" ) then
    set run_file = "$odir/$orun"
endif

# copy original command:
# dump copy of command into workdir/..
if ( $output_cmd == 1 ) then
    echo "++ Echoing the command to: $cmd_file"

    set rec_afni_ver = `afni -ver`
    echo "### AFNI version:"                           > $cmd_file
    echo "# $rec_afni_ver\n"                          >> $cmd_file
    echo "### Executed from the directory location:"  >> $cmd_file
    echo "# $here\n"                                  >> $cmd_file
    echo "### The command was:"                       >> $cmd_file
    echo "# $this_prog $argv"                         >> $cmd_file
    echo "\n"                                         >> $cmd_file
endif

# ============================ input files ==============================

# make sure we can read volumes OK
foreach ff ( $fNN )
    set check = `3dinfo "$ff"`
    if ( "$#check" == "0" ) then
        echo "** ERROR: can't find input file:  $ff !"
        goto BAD_EXIT
    else
        echo "++ Found input file:   $ff"
    endif
end

# get unique list all NN followers
set ilist = ()
set orlist = ()
if ( $#fNN > 0 ) then
    echo "++ Initially, have $#fNN input ROIs."
    foreach i ( `seq 1 1 $#fNN` ) 

        set ffi = "$fNN[$i]"

        # assumes we have 3dTrackID output
        if ( $NO_OR == "1" ) then

            # remove extension++ (or --)
            set ppi = `3dinfo -prefix_noext $ffi`
            # split at "__"
            set breakA = `echo $ppi:q | sed 's/__/ /g'`
            # ROI label/name is second piece
            set np    = $#breakA
            if ( $np != 2 ) then
                echo "** ERROR: while trying to parse file names"
                echo "     I ran into the file: $ffi"
                echo "     which has >1 instance of '__' in it"
                echo "     ... and I don't know how to deal with it!"
                echo "     You flagged this as 3dTrackID output--"
                echo "     are you *sure* of that?"
                goto BAD_EXIT
            endif
            
            set roi2 = "$breakA[${np}]"
            # first instance of "ROI", keyword in 3dTrackID naming
            set a1   = "$breakA[1]"
            set cind = `echo "$a1" | awk '{print index($0,"ROI")}'`
            @ dind   = $cind + 4
            set roi1 = `echo "$a1" | awk -v m="$dind" '{print substr($0,m)}'`

            if ( "$roi1" != "$roi2" ) then
                set ilist = ( $ilist $ffi )
            else
                set orlist = ( $orlist $ffi )
            endif
            
        else
            # take 'em all
            set ilist = ( $ilist $ffi )
        endif

    end
endif

# ------------- echo results ----------------

if ( $#orlist > 0 ) then
    echo ""
    echo "++ Files NOT to be included (N=$#orlist):"
    foreach ii ( `seq 1 1 $#orlist` )
        printf "%5d   %s\n" $ii "$orlist[$ii]"
    end
    echo ""
endif

echo ""
echo "++ Files to be included (N=$#ilist):"
foreach ii ( `seq 1 1 $#ilist` )
    printf "%5d   %s\n" $ii "$ilist[$ii]"
end
echo ""

# ========================= Now do work! ==========================

echo "++ Now, start putting the files together."

set idx = 0
set iidx = `printf "%02d" $idx`

set fout = $wdir/vv_${iidx}_zero.nii
3dcalc               \
    -overwrite       \
    -a $ilist[1]     \
    -expr '0*a'      \
    -prefix $fout

set fin  = $fout
set fout = $wdir/vv_${iidx}_tcat.nii
# concat padded version; [0]th brick isn't counted, but we need
# something there to pad-- duplicate [1]st one
3dTcat                          \
    -overwrite -echo_edu        \
    -prefix $fout               \
    $fin $ilist
@ idx += 1

if ( "$DO_OUT_TCAT" == "1" ) then
    set ooo = $odir/${opref}_tcat.nii.gz
    echo "++ Output tcat-ed (multibrick) file:"
    echo "      $ooo"
    
    3dcopy $fout $ooo
endif

# now get int labels
set iidx = `printf "%02d" $idx`
set fin  = $fout
set fout = $wdir/vv_${iidx}_tstat.nii
3dTstat                         \
    -overwrite -echo_edu        \
    -argmax                     \
    -prefix $fout               \
    $fin
@ idx += 1

if ( "$DO_OUT_TSTAT" == "1" ) then
    set ooo = $odir/${opref}_tstat.nii.gz
    echo "++ Output ttat-ed (single-brick) file:"
    echo "      $ooo"
    
    3dcopy $fout $ooo
endif

if ( "$iso_choice" == "mergerois" ) then
    set merge_lab = "$odir/$opref"
endif

# now get int labels
set iidx = `printf "%02d" $idx`
set fin  = $fout
set fout = $odir/$opref
IsoSurface                            \
    -$iso_choice   $merge_lab         \
    -input $fin                       \
    -o_gii $fout                      \
    -Tsmooth $tsmoo_kpb $tsmoo_nit

echo "++ View with: "
echo "       suma -onestate -i ${fout}*.gii\n"
echo "   ... and possibly add something like '-vol dt_FA.nii.gz'?\n"

#echo   "#\!/bin/tcsh\n"                      > $run_file
#printf "suma -onestate -i ${opref}*.gii "   >> $run_file

#set runf = `ls $run_file`
#echo "++ Basic SUMA command saved in: "
#echo "       $runf\n"

if ( "$DO_CLEAN" == "1" ) then
    cd $here
    echo "\n Removing temporary working directory ($wdir).\n"
    \rm -rf $wdir
else
    echo "\n NOT Removing temporary working directory.\n"
endif

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

goto GOOD_EXIT

# ========================================================================
# ========================================================================

SHOW_HELP:
cat << EOF
# -----------------------------------------------------------------------

 This program is for visualizing the volumetric output of tracking,
 mostly for the '-dump_rois ...' from 3dTrackID.  These are basically
 the WMC (white matter connection) maps through which tract bundles run
 (for DET and MINIP tracking modes), or through which a suprathreshold
 number of tracts run in PROB mode.

 This program creates surface-ized views of the separate WMCs which can
 be viewed simultaneously in 3D with SUMA. 

  Ver. $version (PA Taylor, ${rev_dat})

-------------------------------------------------------------------------

  RUNNING:

  $this_prog  \
    -in_rois       NETROIS       \
    -prefix        PPP           \
   {-prefix_file   FFF}          \
   {-tsmoo_kpb     KPB}          \
   {-tsmoo_niter   NITER}        \
   {-iso_opt       ISO_OPT}      \
   {-trackid_no_or}              \
   {-output_tcat}                \
   {-output_tstat}               \
   {-wdir          WWW}          \
   {-no_clean}


  where

    -in_rois NETROIS   :list of separate files, each with single ROI
                        volume mask; can include wildcards, etc. to specify
                        the list

    -prefix      PPP   :directory to contain the output files: *cmd.txt and 
                        surface files such as *.gii and *.niml.dset; the
                        namebase of files within this directory will be the 
                        default for the program, "$opref".  The value PPP
                        can contain parts of a path in it. 
         or
    -prefix_file FFF   :prefix for the output files: *cmd.txt and surface
                        files such as *.gii and *.niml.dset; can include
                        path steps; and can make one level of a new directory.
                        For example, if FFF were "A/B", then the program
                        could make a new directory called "A" if it didn't
                        exist already and populate it with individual files
                        having the same prefix "B".

    -tsmoo_kpb   KPB   :"KPB" parameter in IsoSurface program;  default
                        value is ${tsmoo_kpb}.
    -tsmoo_niter NITER :"NITER" parameter in IsoSurface program;  default
                        value is ${tsmoo_nit}.
    -iso_opt   ISO_OPT :input one of the "iso* options" from IsoSurface 
                        program, such as "isorois+dsets", "mergerois", etc. 
                        Quotations around the entry may be needed, esp
                        if something like the "-mergerois [LAB_OUT]" route
                        is being followed.
                        Default: ${iso_choice}

    -trackid_no_or     :use this option to have the program recognize the 
                        naming convention of 3dTrackID output and to ignore
                        the OR-logic ROIs, including only the AND-logic (AKA
                        pairwise) connections.  This is mainly useful when 
                        wildcard expressions are using for '-in_rois NETROIS'.

    -output_tcat       :flag to output the multibrick file of concatenated
                        ROI masks; note that the [0]th brick will be all
                        zeros (it is just a place holder).  So, if there are
                        N ROI maps concatenated, there will be N+1 bricks
                        in the output dset, which has name PPP_tcat.nii.gz.
    -output_tstat      :flag to output the single brick file from the 3dTstat
                        operation on the tcat dset.  If there were N ROI maps
                        concatenated, then the largest value should be N.
                        The output file's name will be PPP_tstat.nii.gz.

    -wdir    WWW       :"__WDIR_${tpname}_PPP", where PPP is the input 
                        prefix.
    -no_clean          :is an optional switch to NOT remove working 
                        directory WWW; (default: remove working dir).

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

  EXAMPLE

    $this_prog \
        -in_rois o.prob/NET*       \
        -prefix surf_prob          \
        -trackid_no_or     

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

EOF

    goto GOOD_EXIT

SHOW_VERSION:
    echo "version  $version (${rev_dat})"
    goto GOOD_EXIT

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

BAD_EXIT:
    exit 1

# send everyone here, in case there is any cleanup to do
GOOD_EXIT:
    exit 0
