#!/bin/tcsh


# -----------------------------------------------------------------
# Multipurpose, driven viewer.  Meant to be used for auto QC in
# scripts. 
# 
# This function constructed by: PA Taylor (NIMH, NIH, USoA)
# 
# Dec, 2016:
#     + conception and start.
#
# Jan, 2017:
#     + add I/O.
#
# Jan, 2017b:
#     + if ulay/olay are in different files, have tmp readdir.
#     + default now to proceed if no olay given but also no 
#       '-olay_off' is used.
#
# Jan, 2017c:
#     + better centering of slices.
#
# Jan, 2017d:
#     + better slice selection/centering.
#     + adjust for different orders of orientation
#
set version   = "1.6"
set rev_dat   = "Feb 6, 2017"
#     + olay quotes
#
set version   = "2.0"
set rev_dat   = "Feb 23, 2017"
#     + no zipped nifti

# For more info about opts/fields, see:
#
# https://afni.nimh.nih.gov/pub/dist/doc/program_help/AFNI.afnirc.html
#
# https://afni.nimh.nih.gov/pub/dist/doc/program_help/README.environment.html

# ----------------- default/initialized environments --------------

# GUI settings for simplicity
setenv AFNI_NOSPLASH          YES
setenv AFNI_SPLASH_MELT       NO
setenv AFNI_ENVIRON_WARNINGS  NO
setenv AFNI_COMPRESSOR        NONE
setenv AFNI_IMAGE_GLOBALRANGE VOLUME
# -------------------------------------------------------------------

# ------------------- default/initialized variables -----------------

set ulay = ""                    # inp underlay 
set olay = ""                    # inp overlay  
set see_olay = "+"               # turn *off* olay disp

set ftype = PNG                  # output file format

set impref  = "image_file"       # prefix of output; other things added
set odir    = "."                # default output directory is "here"

set my_cbar = "Plasma"           # colorbar, if necessary
set bufac   = "2"                # blowup factor
set frange  = "0"                # either this (autorange), or user puts in
set USER_FRANGE = 0              # internal toggle only
set thrnew  = "0."               # threshold value (zero default)
set thrflag = "*"                # threshold flags

set crossh = "OFF"               # crosshairs OFF by default
set opac   =  6                  # opacity of overlay

set mx     =  3                  # 'x' dim of montage
set my     =  3                  # 'y' dim of montage
set delsag = -1                  # (int) slice space in sag orient
set delaxi = -1                  # (int) slice space in axi orient
set delcor = -1                  # (int) slice space in cor orient
set USER_COORS = 0               # switch to let user pick IJK
set coors  = ( 0 0 0 )
set gapord = ( 0 0 0 )

# for SET_PBAR_ALL
set pbar_sign = "-"              # + is pos. only, - is both (switch for both)
set ncolors   = "99"             # default number of colors
set topval    = 1                # upper scale value in colorbar

# for SET_FUNC_ALPHA
set alpha_par    = "Off"         # 
set alpha_floor  = ""            # 
set alpha_edgize_no = 0          # =1 -> SETENV AFNI_EDGIZE_OVERLAY NO

set do_quit = "QUITT"            # quick-quit; not subject to change

# tmp dir, in case under- and overlays are in separate dirs
set tmp_dir  = "__tmp_ImG_837261"
set DO_CLEAN = 0
set read_dir = ""
set read_ulay = tmp_ulay.nii

set USER_ULAY_RANGE = 0          # def: user doesn't enter ulay range
set ulay_nz = "-non-zero"
# -------------------------------------------------------------------
# ----------------------------- ugh ---------------------------------

# needed to deal with orientation permutability : AIL, LAI, PSR, etc.

set listori = ( 'R' 'L' 'A' 'P' 'I' 'S' )
set listind = (  1   1   2   2   3   3  )

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

echo "++ My command: $argv"

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

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

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

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

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

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

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

    else if ( "$argv[$ac]" == "-blowup" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set bufac = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-set_xhairs" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set crossh = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-opacity" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set opac = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-del_slice_sag" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set delsag = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-del_slice_axi" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set delaxi = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-del_slice_cor" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set delcor = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-thr_olay" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set thrnew = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-thrflag" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set thrflag = "$argv[$ac]"
        
    # refers to olay
    else if ( "$argv[$ac]" == "-func_range" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set frange = "$argv[$ac]"
        set USER_FRANGE = 1
        
    # refers to olay
    else if ( "$argv[$ac]" == "-func_range_perc" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set frange_perc = "$argv[$ac]"
        set USER_FRANGE = 2

    else if ( "$argv[$ac]" == "-pbar_posonly" ) then
        set pbar_sign = "+"
        
    else if ( "$argv[$ac]" == "-cbar_ncolors" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set ncolors = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-cbar_topval" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set topval = "$argv[$ac]"
        
    # SAVE_ALLJPEG [c].imagewindowname filename
    # SAVE_ALLPNG  [c].imagewindowname filename
    # SAVE_MPEG    [c].imagewindowname filename
    # SAVE_AGIF    [c].imagewindowname filename
    # SAVE_JPEG [c.]windowname filename
    # SAVE_PNG [c.]windowname filename
    else if ( "$argv[$ac]" == "-save_ftype" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set ftype = "$argv[$ac]"

    # takes 3 numbers!!!
    else if ( "$argv[$ac]" == "-set_ijk" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set coors[1] = "$argv[$ac]"
        @ ac += 1
        set coors[2] = "$argv[$ac]"
        @ ac += 1
        set coors[3] = "$argv[$ac]"
        set USER_COORS = 1

    else if ( "$argv[$ac]" == "-montx" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set mx = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-monty" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set my = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-alpha_par" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set alpha_par = "$argv[$ac]"

    else if ( "$argv[$ac]" == "-alpha_floor" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set alpha_floor = "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-alpha_edgize_no" ) then
        setenv AFNI_EDGIZE_OVERLAY NO

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

    # AFNI_IMAGE_LABEL_MODE    = 1     // draw labels in UL of Image windows
    # AFNI_IMAGE_LABEL_SIZE    = 3     // size of labels in Image windows
    # AFNI_IMAGE_LABEL_COLOR   = white // color of labels in Image windows
    # AFNI_IMAGE_LABEL_SETBACK = 0.01  // distance from edges for labels
    else if ( "$argv[$ac]" == "-label_mode" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        setenv AFNI_IMAGE_LABEL_MODE  "$argv[$ac]"

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

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

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

    # default = VOLUME
    else if ( "$argv[$ac]" == "-globalrange" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        setenv AFNI_IMAGE_GLOBALRANGE  "$argv[$ac]"
        
    else if ( "$argv[$ac]" == "-ulay_range" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set umin = "$argv[$ac]"
        @ ac += 1
        set umax = "$argv[$ac]"
        set USER_ULAY_RANGE = 1

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

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

   endif
   @ ac += 1
end

# -------------------------------------------------------------------
# ------------------ check about auxiliary progs --------------------

# from Bob's @snapshot* progs

set nerr = 0
set errm = "** ERROR:"

# (Ubuntu hassle ->) not using: pamcomp
set plist = ( Xvfb djpeg cjpeg pnmcat pbmtext  \
                pamstretch pbmtopgm )
foreach pppp ( $plist )
  set wwww = `which $pppp`
  if( $status != 0 )then
    @ nerr++
    set errm = "$errm $pppp"
  endif
end
if( $nerr > 0 )then
  echo "$errm -- not found in path -- program fails"
  goto BAD_EXIT
endif

# -------------------------------------------------------------------
# -------------------------- check INPUTS ---------------------------

echo "\n------------------ start of optionizing ------------------\n" 

# need more cowbell
if ( ("$ulay" == "") ) then
    echo "** ERROR: need to have an underlay, at least!!"
    goto BAD_EXIT
endif

# need more cowbell, but will proceed anyways
if (( "$olay" == "" ) && ( "$see_olay" == "+" )) then
    echo "+* Noting: you did NOT provide an overlay, and yet"
    echo "           you did NOT turn off the overlay with '-olay_off'"
    echo "       --> so I assume you just want to view the underlay." 
    set see_olay = "-"
endif

# check blowup factor
set check_list = ( `seq 1 1 4` )
set innit = 0
foreach i ( $check_list )
    if ( $bufac == ${check_list[${i}]} ) then
        echo "++ Using blowup factor: $bufac"
        set innit = 1
        break
    endif
end
if ( $innit == 0 ) then
    echo "+* BAD blowup factor:  $bufac!"
    echo "   ---> needs to be (exactly) one of:  $check_list\n\n"
    goto BAD_EXIT
endif

# check opacity
set check_list = ( `seq 1 1 9` )
set innit = 0
foreach i ( $check_list )
    if ( $opac == ${check_list[${i}]} ) then
        echo "++ Using opacity:  $opac"
        set innit = 1
        break
    endif
end
if ( $innit == 0 ) then
    echo "+* BAD opacity:  $opac!"
    echo "   ---> needs to be (exactly) one of:  $check_list\n\n"
    goto BAD_EXIT
endif

# in so many cases we need a tmp working directory
set read_dir = "$odir/$tmp_dir"
if ( ! -e $read_dir ) then
    echo "++ Making temporary work directory to copy vis files: $read_dir"
    mkdir $read_dir
endif

# for scaling ulay uniformly with reasonable values when brightness
# range is the same across the volume
set urange = `echo $AFNI_IMAGE_GLOBALRANGE`
if ( ( $urange == "VOLUME" ) || ( $urange == "DSET" )  \
    || ( $urange == "YES" ) ) then

    if ( $USER_ULAY_RANGE ) then
        echo "++ Copying ulay to visualize (volumetric) within user's range:"

        # will be 0 if no percent; otherwise, >0 if percent
        set is_umin_perc = `echo ${umin} | awk '{print index ( $0,"%" ) }'`
        set is_umax_perc = `echo ${umax} | awk '{print index ( $0,"%" ) }'`

        if ( ($is_umin_perc > 0) && ($is_umax_perc > 0) ) then
            # percentages!
            set pmin  = "$umin"
            set pmax  = "$umax"

            set amin  = `3dBrickStat $ulay_nz -percentile ${umin} 1 ${umin} "$ulay"`
            set amax  = `3dBrickStat $ulay_nz -percentile ${umax} 1 ${umax} "$ulay"`
                
            set umin = $amin[2]
            set umax = $amax[2]

            echo "++ Copying ulay to visualize (volumetric) within user's range:"
            echo "  [${pmin},${pmax}] -> [${umin},${umax}]"

        else
            echo "++ Copying ulay to visualize (volumetric) within user's range:"
            echo "   [${umin}, ${umax}]"
        endif
    else
        set ubs  = `3dBrickStat $ulay_nz -percentile 2 96 98 "$ulay"`
        set umin = $ubs[2]
        set umax = $ubs[4]

        echo "++ Copying ulay to visualize between 2%-98% (volumetric):"
        echo "   [${umin},${umax}]"
    endif

    # copy over *thresholded* version to temporary read dir
    3dcalc                                        \
        -overwrite                                \
        -a "$ulay"                                  \
        -expr "a*within(a,${umin},${umax})+${umin}*step($umin-a)+${umax}*step(a-$umax)" \
        -prefix $read_dir/$read_ulay

else
    if ( `3dinfo -datum "$ulay"` == "rgb" ) then
        # not sure why 3dcalc won't preserve rgb-ness...
        3dcopy                                        \
            -overwrite                                \
            "$ulay" $read_dir/$read_ulay
    else
        echo "++ For ulay, AFNI_IMAGE_GLOBALRANGE is set to be: $urange"
        # just copy over *original* version to temporary read dir
        3dcalc                                        \
            -overwrite                                \
            -a "$ulay"                                \
            -expr "a"                                 \
            -prefix $read_dir/$read_ulay
    endif
endif

# IF we don't want to see the olay, then set it to be the ulay, for
# later simplicity with the automontaging
if ( "$see_olay" == "-" ) then
    echo "++ No overlay viewing"
    set olay = ""
    # don't need to copy anything, just set this for scripty purposes,
    # doesn't affect visualization.
    set read_olay = $read_ulay
    set Dim  = `3dinfo -n4 "$ulay"`

else

    set Dim  = `3dinfo -n4 "$olay"`
    set read_olay = tmp_olay.nii

    3dcalc                                    \
        -a "$olay"                            \
        -expr 'a'                             \
        -prefix $read_dir/$read_olay          \
        -overwrite

    # set frange, if user hasn't, based on data:
    if ( $USER_FRANGE == 0 ) then

        set vv = `3dBrickStat -non-zero      \
                    -percentile 98 1 98      \
                    $read_dir/$read_olay`
        set frange = $vv[2]

        set maxolay = `3dinfo -max $read_dir/$read_olay`
        set minolay = `3dinfo -min $read_dir/$read_olay`
        echo "++ No user-entered function range ('-frange ...') value."
        echo "   --> Ergo, calculating based on 98th %ile, getting: $frange"
        echo "   ----> ... noting that range of values is: [$minolay, $maxolay]"
    else if ( $USER_FRANGE == 1 ) then
        echo "++ User-entered function range value value (${frange}%)"
    else if ( $USER_FRANGE == 2 ) then
        set vv = `3dBrickStat -non-zero                           \
                    -percentile $frange_perc 1 $frange_perc       \
                    -non-zero   $read_dir/$read_olay`
        set frange = $vv[2]
        set maxolay = `3dinfo -max $read_dir/$read_olay`
        set minolay = `3dinfo -min $read_dir/$read_olay`
        echo "++ User-entered function range value as percentile (${frange_perc}%)"
        echo "   --> Ergo, calculating FUNC_RANGE, getting: $frange"
        echo "   ----> ... noting that range of values is: [$minolay, $maxolay]"
    endif
endif

# Calculate numbers of slices in each direction, if not given by user.
# Take number of mont wins plus a couple to calculate.
@  Nwin  = $mx * $my
# silly stuff to deal with orientation
set ori  = `3dinfo -orient "$ulay"`
set ori0 = `echo $ori | awk '{print substr($0,1,1)}'`
set ori1 = `echo $ori | awk '{print substr($0,2,1)}'`
set ori2 = `echo $ori | awk '{print substr($0,3,1)}'`
set all_ori = ( $ori0 $ori1 $ori2 )
set order  = ()
foreach oo ( $all_ori )
    foreach i ( `seq 1 1 ${#listori}` )
        if ( $oo == "$listori[${i}]" ) then
            set order  = ( $order ${listind[$i]} )
            break
        endif
    end
end
echo "++ Cryptic info: $ori -> $all_ori -> $order"

echo "++ Dimensions (xyzt): $Dim"

foreach i ( `seq 1 1 3` )
    if( $gapord[$order[$i]] <= 0 ) then
        @ gapord[$order[$i]] = $Dim[$i] / ( $Nwin )
        if( $gapord[$order[$i]] <= 0 ) then
            @ gapord[$order[$i]] = 1
        endif
    endif
end

echo "++ Slice spacing ordered (x,y,z) is:  $gapord"

# get ceilings of 'montage number + 1', in each direction
set xo2 = `echo "scale=2; ( $mx + 1 ) / 2." | bc`
set cmx = `echo $xo2 | perl -nl -MPOSIX -e 'print ceil($_);'`
set yo2 = `echo "scale=2; ( $my + 1 ) / 2." | bc`
set cmy = `echo $yo2 | perl -nl -MPOSIX -e 'print ceil($_);'`

@ tot     = $mx * $my 
@ hpan    = ( ( $cmy - 1 ) * $mx ) + $cmx    
#echo "$cmx $cmy $tot $hpan"
set pfrac = `echo "scale=5; ( $hpan / ( $tot + 1 ) ) " | bc` # ????
echo "++ pfrac = $pfrac"

# These need to reflect the order of the original.  Ugh, annoying
# conditions.
if ( $USER_COORS == 1 ) then
    echo "++ Will have user's chosen: SET_IJK $coors"
else
    foreach i ( `seq 1 1 3` )
        set qfrac = `echo "scale=5; ( $pfrac ) " | bc` # frac to center
        set qsh   = ""#+ 1"                             # zerobase count offset
        if ( ( $all_ori[$i] == 'R' ) || ( $all_ori[$i] == 'P' )  \
            || ( $all_ori[$i] == 'S' ) ) then
            #echo "++ Coor calc:  $all_ori[$i] for $order[$i]"
            set qfrac = `echo "scale=5; ( 1 - $pfrac ) " | bc`
        #else
        #    echo "++ Coor value: $all_ori[$i] for $order[$i]"
        endif
        set nn        = `echo "scale=0; ( ( $Dim[$i] * $qfrac ) $qsh )" | bc`
        set coors[$i] = `echo $nn | perl -nl -MPOSIX -e 'print floor($_);'`
    end
    echo "++ Will have: SET_IJK $coors"
endif

echo "\n------------------- end of optionizing -------------------\n" 

# -------------------------------------------------------------------
# ------------------------- Make virtual frame ----------------------

# start the X virtual frame buffer on display #xdisplay, a la bob

set ranval = `count -dig 1 1 999999 R1`

if( $?xdisplay == 0 )then
  set killX     = 1
  set ntry      = 1
  set Xnotfound = 1
  while( $Xnotfound )
    set xdisplay = `count -dig 1 3 999 R1`
    if( -e /tmp/.X${xdisplay}-lock ) continue
    echo " -- trying to start Xvfb :${xdisplay}"
    Xvfb :${xdisplay} -screen 0 1024x768x24 &
    sleep 1
    jobs > zzerm.$ranval.txt
    grep -q Xvfb zzerm.$ranval.txt
    set Xnotfound = $status
    \rm -f zzerm.$ranval.txt
    if( $Xnotfound == 0 )break ;
    @ ntry++
    if( $ntry > 99 )then
      echo "** ERROR: can't start Xvfb -- exiting"
      goto BAD_EXIT
    endif
  end
endif

setenv DISPLAY :${xdisplay}
set OW = "OPEN_WINDOW"

# -------------------------------------------------------------------
# ---------------- The actual, driven command! ----------------------

afni -noplugins -no_detach  -echo_edu                               \
     -com "SWITCH_UNDERLAY ${read_ulay}"                            \
     -com "SWITCH_OVERLAY  ${read_olay}"                            \
     -com "SET_PBAR_ALL    ${pbar_sign}${ncolors} $topval $my_cbar" \
     -com "SET_FUNC_RANGE  ${frange}"                               \
     -com "SET_THRESHNEW   $thrnew $thrflag"                        \
     -com "SEE_OVERLAY     ${see_olay}"                             \
     -com "SET_FUNC_ALPHA  $alpha_par $alpha_floor"                 \
     -com "SET_XHAIRS  ${crossh}"                                   \
     -com "$OW sagittalimage opacity=${opac} mont=${mx}x${my}:${gapord[1]}" \
     -com "$OW coronalimage  opacity=${opac} mont=${mx}x${my}:${gapord[2]}" \
     -com "$OW axialimage    opacity=${opac} mont=${mx}x${my}:${gapord[3]}" \
     -com "SET_IJK $coors"                                                    \
     -com "SAVE_${ftype} sagittalimage ${odir}/${impref}.sag blowup=${bufac}" \
     -com "SAVE_${ftype} coronalimage  ${odir}/${impref}.cor blowup=${bufac}" \
     -com "SAVE_${ftype} axialimage    ${odir}/${impref}.axi blowup=${bufac}" \
     -com "${do_quit}"                                                        \
     "${read_dir}"

# A la bob:  stop Xvfb if we started it ourselves
if( $?killX ) kill %1

if ( $DO_CLEAN ) then
    echo "\n+* Removing temporary image directory '$odir/$tmp_dir'.\n"
    # AKA $read_dir, at present
    \rm    $odir/$tmp_dir/*
    \rmdir $odir/$tmp_dir
else
    echo "\n++ NOT removing temporary directory '$odir/$tmp_dir'.\n"
endif
 
goto GOOD_EXIT

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

# various FAIL condition labels follow

SHOW_VERSION:

    echo "\n\n++ Version: $version\n\n"

    goto GOOD_EXIT

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

SHOW_HELP:

cat <<EOF

 ++ help file a-comin' (someday).

    minimal usage:  

        $ viewer_afni.tcsh -ulay FILE_ULAY -olay FILE_OLAY
 
EOF

    goto GOOD_EXIT

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

FAIL_MISSING_ARG:
   echo "** missing parameter for option $argv[$ac]"
   goto BAD_EXIT

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

BAD_EXIT:
    exit 1

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

GOOD_EXIT:
    exit 0

