#!/bin/tcsh
# @ROI_modal_grow
# dilate ROIs in volumetric dataset with non-zero modal smoothing


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

set progname = @ROI_modal_grow

# --------------------- version history with changes -----------------------
#
set version = "1.00"
#

set dset = ""
set outdir = "rmgrow"
set niters = ""
set maskset = ""
set outprefix = "rmg"
set keep_rm_files = ""
set NN = "-1"

set here = "$PWD"
# ------------------------ process user options --------------------------

if ( $#argv == 0 ) goto HELP

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

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

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

    else if ("$argv[$ac]" == "-input") then
        set this_opt = "$argv[$ac]"
        @ ac ++
        if ( $ac > $#argv ) then
            echo "** missing parameter for option '${this_opt}'"
            exit 1
        endif
        set dset =  $argv[$ac]
    else if ("$argv[$ac]" == "-mask") then
        set this_opt = "$argv[$ac]"
        @ ac ++
        if ( $ac > $#argv ) then
            echo "** missing parameter for option '${this_opt}'"
            exit 1
        endif
        set maskset =  $argv[$ac]
    else if ("$argv[$ac]" == "-outdir") then
        set this_opt = "$argv[$ac]"
        @ ac ++
        if ( $ac > $#argv ) then
            echo "** missing parameter for option '${this_opt}'"
            exit 1
        endif
        set outdir =  $argv[$ac]
    else if ("$argv[$ac]" == "-niters") then
        set this_opt = "$argv[$ac]"
        @ ac ++
        if ( $ac > $#argv ) then
            echo "** missing parameter for option '${this_opt}'"
            exit 1
        endif
        set niters =  $argv[$ac]
    else if ("$argv[$ac]" == "-prefix") then
        set this_opt = "$argv[$ac]"
        @ ac ++
        if ( $ac > $#argv ) then
            echo "** missing parameter for option '${this_opt}'"
            exit 1
        endif
        set outprefix =  $argv[$ac]

    else if ("$argv[$ac]" == "-NN") then
        set this_opt = "$argv[$ac]"
        @ ac ++
        if ( $ac > $#argv ) then
            echo "** missing parameter for option '${this_opt}'"
            exit 1
        endif
        if ("$argv[$ac]" == "1") then
           # facing neighbors only - default
           set NN = "-1"
        else if ("$argv[$ac]" == "2") then
           # >sqrt 2 - 2D diagonal neighbors
           set NN = "-1.415"
        else if ("$argv[$ac]" == "3") then
           # >sqrt 3 - 3D diagonal neighbors
           set NN = "-1.74"
        else
           echo "Only values of 1,2,3 allowed"
           exit 1
        endif
    endif
    
    else if ( "$argv[$ac]" == "-keep_rm_files" ) then
        set keep_rm_files = 1

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

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

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

# ------------------------- check for required inputs
if ($dset == "") then
    echo "No input dataset provided"
    exit 1
endif

if ("${niters}" == "") then
    echo "Must select number of iterations"
    exit 1
endif

# ------------------------- make OUTDIR
# We don't allow output directory to be $PWD -- must be a subdir; too
# complicated with copying fnames

\mkdir -p "${outdir}"
cd "${outdir}"
if ( "${PWD}" == "${here}" ) then
    echo "** ERROR: Output directory cannot be same current working dir."
    echo "          Please specify new output directory"
    exit 1
endif
cd -

# copy the datasets into the directory and rename
3dcopy $dset "${outdir}/rm_rgm_00.nii.gz"
# copy any atlas and label tables over
3drefit -copytables $dset "${outdir}/rm_rgm_00.nii.gz"

if ("$maskset" != "") then
   3dcopy $maskset "${outdir}/maskset.nii.gz"
   set maskset = maskset.nii.gz
endif

cd "${outdir}"
set inset = rm_rgm_00.nii.gz

foreach iter (`count -digits 2 1 $niters`)
    3dLocalstat -nbhd "SPHERE(${NN})" -stat nzmode -overwrite \
       -prefix rm_rgm_${iter}.nii.gz $inset
    set inset = rm_rgm_${iter}.nii.gz
end

if ("$maskset" != "") then
   3dcalc -datum short -nscale -a $inset -b $maskset  \
      -expr 'a*step(b)' -prefix ${outprefix}.nii.gz -overwrite
else
   3dcalc -datum short -nscale -a $inset -expr a  \
      -prefix ${outprefix}.nii.gz -overwrite
endif

# copy any atlas and label tables over to final output
3drefit -cmap INT_CMAP -copytables rm_rgm_00.nii.gz ${outprefix}.nii.gz


if ($keep_rm_files != "") then
   \rm rm_rgm_${iter}.nii.gz 
endif

exit 0


# ===========================================================================
HELP:

cat << SCRIPT_HELP_STRING

Overview ~1~

Script to grow a set of regions in a volumetric dataset using modal
smoothing.

Usage Example ~1~

    @ROI_modal_grow                                      \
      -input  mydset.nii.gz                              \
      -outdir myoutdir                                   \
      -niters 5                                          \
      -mask mymask.nii.gz                                \
      -prefix rmg_name                                  

   Note only the input dataset and the number of iteration levels
   are required.

Options ~1~

    -input input_dset   :required input dataset. This dataset should be
                         set of integer values. The program mostly assumes
                         approximate isotropic voxels.

    -outdir outdirname  :directory name for output. All output goes to
                         this directory. Default is rmgrow.

    -niters nn          :number of iterations for modal growth - 
                         something like dilation level here - generally
                         this will make sense for values from about 1-10

    -mask maskset       :mask dataset at same grid as the input dataset.
                         this could be a dilated version of the original mask
                         or a larger region like a cortical ribbon mask.
                         Not required but often desirable.

    -prefix baseprefix  :base name of final output dataset, i.e. baseprefix.nii.gz
                         Default is rmg, so output would be rmg.nii.gz

    -NN [1,2,3]         :neighborhood type using in finding mode, 
                         1 - facing neighbors, 2-edges, 3-corners

Also see these programs with these similar functions: 
   3dROImaker - grows regions using regular dilation iteratively
   3dmask_tool - dilates and erodes sets of input files or a single output mask
   3dmerge, 3dAutomask, 3dcalc - all can do dilation
   3dLocalstat - modal and nonzero modal smoothing
   ROIgrow - dilates surface ROI (patches) within the mesh of the surface

SCRIPT_HELP_STRING

   exit 0
