#! /bin/csh -f

### pfbrik: marty sereno -- cmdline run tkmedit plane filter on a BRIK
# 15/03/01 -- 01a: initial hack

### default parms
set prescale = 3.0
set kcnt = 5
set kfwhm = 1.25

### tmpfiles
set tmptcl = TmpTclScript.$$.tcl
set tmpmgz1 = Tmp1Mgz.$$.mgz
set tmpmgz2 = Tmp2Mgz.$$.mgz
onintr cleanup

### help
if ($#argv < 1) then
  echo ""
  echo "Use: pfbrik <scan+orig.BRIK> [-opts]"
  echo ""
  echo " Gaussian plane-filter an AFNI BRIK w/tkmedit"
  echo ""
  echo " Input/Output:"
  echo "   input: non-conforming BRIK (e.g., MPRAGE)"
  echo "   output: conforming 256^3, 1mm^3 BRIK"
  echo ""
  echo " Options:"
  echo "   -prescale <float>    ($prescale) inpix/prescale = byte"
  echo "   -kcnt <n>            ($kcnt) kernel cell width"
  echo "   -kfwhm <mm>          ($kfwhm) kernel fwhm in mm"
  echo ""
  exit
endif

### get args, options (any order)
set i = 1
set argv2 = ""  # non-opt args
while ($i <= "$#argv")
  set arg = $argv[$i]
  # 0-arg (none)
  if ("$arg" == "-someflag") then
    set someflag = 1
    @ i++; continue
  endif
  # 1-arg
  @ i2 = $i + 1
  if ($#argv >= $i2) then
    if ("$arg" == "-prescale") then
      set prescale = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-kcnt") then
      set kcnt = $argv[$i2]
      @ i+=2; continue
    endif
    if ("$arg" == "-kfwhm") then
      set kfwhm = $argv[$i2]
      @ i+=2; continue
    endif
  endif
  # errs, non-options args
  if ("$arg" =~ "-*") then
    echo "option: $arg => bad option, or missing arg(s)"
    exit
  else
    set argv2 = "$argv2 $argv[$i]"
  endif
  @ i++
end
set inbrik = $argv2[1]

### inbrik
if ($inbrik == "") then
  echo "pfbrik: ### no input file"
  exit
endif
if (! -e $inbrik) then
  echo "pfbrik: ### input file $inbrik not found"
  exit
endif
if ($inbrik !~ *+orig.BRIK) then
  echo "pfbrik: ### input file $inbrik doesn't end in +orig.BRIK"
  exit
endif

### outbrik
set stem = `basename $inbrik "+orig.BRIK"`
set outbrik = ${stem}-pf+orig.BRIK
if (-e $outbrik) then
  echo "pfbrik: ### $outbrik already exists  ...move it aside first"
  exit
endif

### BRIK -> COR -> run plane filter -> COR -> BRIK
brik2cor $inbrik $tmpmgz1 -p $prescale
cat << EOF > $tmptcl
  set kcnt $kcnt
  set kfwhm $kfwhm
  run_wmfilter gauss to_buf1 1    ;# force=1 overwrite
  set inoutim $tmpmgz2
  write_images
  exit
EOF
tkmedit $tmpmgz1 -tcl $tmptcl
cor2brik $tmpmgz2 $outbrik

### cleanup
cleanup:
rm -f $tmptcl $tmpmgz1 $tmpmgz2

