#!/bin/tcsh

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

#set version   = "0.0";  set rev_dat   = "May 30"
# [PT] birth
#
#set version   = "0.1";  set rev_dat   = "May 30"
# [PT] bug fixing/checking
#
#set version   = "0.2";  set rev_dat   = "May 30"
# [PT] 
#   + reattach any tables, 
#   + and put in 'cmap INT_CMAP' properties
#
#set version   = "0.3";  set rev_dat   = "May 30"
# [PT] 
#   + all intermediate files are now *.nii.gz, to play more nicerly
#     with @animal_warper
#
#set version   = "0.4";  set rev_dat   = "March 3, 2021"
# [PT] 
#   + Squashing the WEIRDEST bug ever, where either line spacing or
#     not doublequoting a safe filename caused an error.  Thanks,
#     Veena, for helping to track this down.
#
set version   = "0.5";  set rev_dat   = "April 14, 2022"
# [PT] 
#   + Squash a bug: no replacement was happening at present, since the
#     grep string in the table was incorrect.  Fixed that, and hopefully
#     should check to prevent such a mismatch of information from 
#     happening again.
#
# ----------------------------------------------------------------

set this_prog = "@djunct_modal_smoothing_with_rep"
set tpname    = "${this_prog:gas/@djunct_//}"
set here      = "$PWD"

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

set iset    = ""                  # 'warped' dset, dset to check

set odir           = "."
set opref          = ""

set pppp           = "`3dnewid -fun11`"
set wdir_name      = "__workdir_MSWR_${pppp}"
set tpref          = "mswr"

set gpref          = "glue"       # to be glued together

set glue_list      = ( )
set count_remake   = 0
set count_remake2  = 0

set DO_CLEAN       = 1
set owrite         = ""

set modesmooth     = ""


# ------------------- 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

    #  ---------- inputs: required ---------------

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

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

    else if ( "$argv[$ac]" == "-prefix" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set opref = `basename "$argv[$ac]"`
        set odir  = `dirname  "$argv[$ac]"`

    #  ---------- opts ---------------

    else if ( "$argv[$ac]" == "-no_clean" ) then
        set DO_CLEAN = 0

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

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

    else
        echo "\n\n** ERROR: unexpected option #$ac = '$argv[$ac]'\n\n"
        goto BAD_EXIT
        
    endif
    @ ac += 1
end

# =======================================================================
# ============================ ** SETUP ** ==============================
# =======================================================================

echo "++ Prepare for running ${this_prog} (ver = ${version})"

if ( "${iset}" == "" ) then
    echo "** ERROR: missing input file. Use '-input ..'"
    goto BAD_EXIT
endif

set i_avspace = `3dinfo -av_space "${iset}"`

if ( "${opref}" == "" ) then
    echo "** ERROR: missing output name. Use '-prefix ..'"
    goto BAD_EXIT
endif



# ===================== output dir + wdir =======================
 
# check output directory, use input one if nothing given

\mkdir -p ${odir}

# place wdir in the odir
set wdir = "${odir}/${wdir_name}"

\mkdir -p ${wdir}

# =========================== Get to work ==============================

# ------------------------ copy and prep

set dset_inp   = ${tpref}_00_cp.nii.gz
set dset_smoo0 = ${tpref}_01_modsmoo.nii.gz

# cp input dset to wdir
3dcalc ${owrite}                       \
    -a "${iset}"                       \
    -expr 'a'                          \
    -prefix "${wdir}/${dset_inp}"

# also copy tables to try to reattach later, as well as INT_CMAP
# property
3drefit -cmap INT_CMAP        "${wdir}/${dset_inp}"
3drefit -copytables "${iset}" "${wdir}/${dset_inp}"


# -------------------- to wdir and modally smooth

cd ${wdir}            # move into workdir

# initial modal smoothing
3dLocalstat ${owrite}                                     \
   -stat     mode                                         \
   -nbhd     "SPHERE(-${modesmooth})"                     \
   -prefix   "${dset_smoo0}"                              \
   "${dset_inp}"

# useful later, if visually checking
3drefit -cmap INT_CMAP            "${dset_smoo0}"
3drefit -copytables "${dset_inp}" "${dset_smoo0}"

# -------- go through and *check* if we need to make any new dsets ---------

# get upper index
### [PT: Mar 30, 2021] on one system, consistently this program usage
### caused an error 'Unknown user: 1~.' when this was spaced across a
### few lines and the variable was not in double quotes.  I still
### don't know precisely why, but I know when to take a hint...
set nvi = `3dinfo -nvi "${dset_smoo0}"`

foreach nn ( `seq 0 1 ${nvi}` ) 
    set nnn    = `printf "%05d" "${nn}"`
    set report = "rep_${nnn}.txt"

    # make report
    adjunct_aw_tableize_roi_info.py             \
        "${report}"                             \
        "${dset_smoo0}[${nn}]"                  \
        "${dset_smoo0}[${nn}]"                  \
        "${dset_inp}[${nn}]"                    \
        "${dset_inp}[${nn}]"                    \
        "${modesmooth}"

    set check_lost = `grep "Selector of lost ROIs"  "${report}"`
    set check_diff = `grep "Nroi difference"        "${report}"`
    set ndiff      = ${check_diff[5]}
    
    # check for inconsistencies in difference measures
    if ( ( ${#check_lost} > 0 ) && ( "${ndiff}" == "0" ) ) then
        echo "** ERROR: disagreement (A) between lines in report?"
        echo "   ${check_lost}"
        echo "   ${check_diff}"
        goto BAD_EXIT
    endif

    if ( "${ndiff}" != "0" ) then
        if ( "${check_lost}" == "" ) then
            echo "** ERROR: disagreement (B) between lines in report?"
            echo "   ${check_lost}"
            echo "   ${check_diff}"
            goto BAD_EXIT
        endif

        @ count_remake += 1
    endif

    # after this, we assume both lines of differences are consistent
end

# -------- go through and *check* if we need to make any new dsets ---------

if ( ${count_remake} == 0 ) then
    # nothing to remake; just copy file "up", since wdir is subdir of
    # odir
    echo "++ No lost ROIs to replace from modal smoothing"
    echo "   of dset: ${iset}"

    3dcopy  ${owrite}       \
        "${dset_smoo0}"     \
        "../${opref}"
    # tables/CMAP done below

else
    
    # go back through list and make ROIs
    foreach nn ( `seq 0 1 ${nvi}` ) 
        set nnn    = `printf "%05d" "${nn}"`
        set report = "rep_${nnn}.txt"

        set check_lost = `grep "Selector of lost ROIs"  "${report}"`
        set check_diff = `grep "Nroi difference"        "${report}"`
        set ndiff      = ${check_diff[5]}

        if ( ${#check_lost} > 0 ) then
            # REMAKE this volume
            echo "++ Modal smoothing check [${nnn}] : REMAKE"
            if ( "${ndiff}" == "0" ) then
                echo "** ERROR: disagreement between lines in report (pass2)?"
                echo "   ${check_lost}"
                echo "   ${check_diff}"
                goto BAD_EXIT
            endif

            @ count_remake2 += 1

            set str_sel = "${check_lost[7]}"  # which ROIs to be put back
            echo "++ Use this str selector about lost ROIs: ${str_sel}"

            set remake  = ${gpref}_${nnn}_RE.nii.gz

            3dcalc  ${owrite}                                   \
                -a      "${dset_smoo0}[${nn}]"                  \
                -b      "${dset_inp}[${nn}]<${str_sel}>"        \
                -expr   'b+not(b)*a'                            \
                -prefix ${remake}
        else
            # DON'T REMAKE this volume
            echo "++ Modal smoothing check [${nnn}] : no remake"

            set remake  = ${gpref}_${nnn}_OK.nii.gz

            3dcalc  ${owrite}                                   \
                -a      "${dset_smoo0}[${nn}]"                  \
                -expr   'a'                                     \
                -prefix ${remake}

        endif

        3drefit -cmap INT_CMAP            ${remake}
        3drefit -copytables "${dset_inp}" ${remake}
        set glue_list = ( ${glue_list}    ${remake} )

    end

    if ( ${count_remake} != ${count_remake2} ) then
        echo "** ERROR: different numbers of counts for each pass:"
        echo "          pass 1:  ${count_remake}"
        echo "          pass 2:  ${count_remake2}"
        goto BAD_EXIT
    endif


    3dTcat  ${owrite}         \
        -prefix ALL_GLUED.nii.gz \
        ${glue_list}

    3drefit -cmap INT_CMAP            ALL_GLUED.nii.gz
    3drefit -copytables "${dset_inp}" ALL_GLUED.nii.gz

    3dcopy  ${owrite}         \
        ALL_GLUED.nii.gz      \
        "../${opref}"
    # tables/CMAP done below

    echo "++ Replace some ROIs in modal smoothing"
    echo "   of dset: ${iset}"

endif


# an annoying thing: if the ${opref} was specified with no NIFTI ext,
# then 3drefit won't be able to work with it; 3dinfo CAN get info from
# it, however
set check_nii = `3dinfo -is_nifti "../${opref}"`

if ( "${check_nii}" == "1" ) then
    # is nifti
    3drefit -cmap INT_CMAP            "../${opref}"
    3drefit -copytables "${dset_inp}" "../${opref}"
else
    # is BRIK/HEAD, use av_space to make sure we get the right one
    3drefit -cmap INT_CMAP            "../${opref}${i_avspace}"
    3drefit -copytables "${dset_inp}" "../${opref}${i_avspace}"
endif


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

if ( $DO_CLEAN == 1 ) then
    echo "\n+* Removing temporary workdir '${wdir}*'\n"
    # in working directory at present, so just go up and remove it
    cd ..
    \rm -rf ${wdir_name}
else
    echo "\n+* NOT removing temporary files '${wdir}*'\n"
endif

cd "${here}"

echo ""
echo "++ DONE.  Output from modal smoothing (with replacement):"
echo "       ${odir}/${opref}"
echo ""


goto GOOD_EXIT

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

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

OVERVIEW ~1~

Brief script to perform modal (= "Glenian") smoothing of ROI maps, but
also to check and see if that smoothing process eliminated any ROIs.
If it did, put those lost souls back.  NB: those replaced ROIs could
be ugly or weird!

written by PA Taylor
ver = ${version}

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

COMMAND OPTIONS ~1~

-hview
-help
-ver
-input       (NB: assumes < 10**5 subbricks in this dset)
-prefix
-modesmooth  (NB: fills in X in: 3dLocalstat -nbhd "SPHERE(-X)" ...)
-overwrite
-no_clean

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

GOOD_EXIT:
    exit 0
