#!/bin/csh -f
# ipfsl - front-end for FSL's IP program
#
# $Id: ipfsl,v 1.1 2003/03/04 21:22:08 greve Exp $
#

set VERSION = '$Id: ipfsl,v 1.1 2003/03/04 21:22:08 greve Exp $';
set FASTVER = `cat $FSFAST_HOME/docs/version`;

set inputargs = ($argv);

set instem     = ();
set outstem    = ();
set maskstem   = ();
set makemask   = 0;
set pctthresh  = ();
set fslargs    = ();

set scratchdir = ();
set cleanup    = 1;
set debug      = 0;

if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

set n = `echo $argv | grep version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif

if(! $?FSL_DIR) then
  echo "ERROR: FSL_DIR environment variable not defined"
  exit 1;
endif
set IPFSL = $FSL_DIR/bin/ip
if(! -e $IPFSL) then
  echo "ERROR: cannot find $IPFSL"
  exit 1;
endif

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

#---------------------------------------------------#
set outdir = `dirname $outstem`;
mkdir -p $outdir
if($makemask) then
  set maskdir = `dirname $maskstem`;
  mkdir -p $maskdir
endif

#---------------------------------------------------#
if($#scratchdir == 0) then
  set scratchdir = /tmp/ipfsl_$$
else
  set scratchdir = $scratchdir/ipfsl
endif
mkdir -p $scratchdir
echo "Scratch Dir is $scratchdir" 

#---------------------------------------------------#
set inbase  = `basename $instem`;
set outbase = `basename $outstem`;

#---------------------------------------------------#
if( -e $instem"_000.bshort") then
  set bvoltype = bshort;
else
  if( -e $instem"_000.bfloat") then
    set bvoltype = bfloat
  else
    echo "ERROR: cannot find $instem"
    exit 1;
  endif
endif

echo "# ---------- Converting bvolume to .img ------------------ #"
set cmd = (mri_convert $instem --in_type $bvoltype )
set cmd = ($cmd $scratchdir/$inbase.img --out_type analyze4d)
$cmd
if($status) then
  pwd
  echo $cmd
  echo "ERROR: mri_convert failed"
  exit 1;
endif
set inmatfile = $scratchdir/$inbase.mat

echo "# ---------- Using IP to preprocess ------------------ #"
pushd $scratchdir > /dev/null
set cmd = ($IPFSL $inbase $outbase $pctthresh $fslargs)
$cmd
if($status) then
  pwd
  echo $cmd
  echo "ERROR: ip failed"
  exit 1;
endif
popd > /dev/null
set outmatfile = $scratchdir/$outbase.mat
cp $inmatfile $outmatfile

echo "# ---------- Converting output to bvolume ------------------ #"
set cmd = (mri_convert $scratchdir/$outbase.img --in_type analyze4d)
set cmd = ($cmd $outstem --out_type $bvoltype)
$cmd
if($status) then
  pwd
  echo $cmd
  echo "ERROR: mri_convert failed"
  exit 1;
endif

if($makemask) then
  echo "# ---------- Converting mask to bshort ------------------ #"
  set cmd = (mri_convert $scratchdir/$maskbase.img --in_type analyze4d)
  set cmd = ($cmd $maskstem --out_type bshort)
  $cmd
  if($status) then
    pwd
    echo $cmd
    echo "ERROR: mri_convert failed"
    exit 1;
  endif
endif

# Delete temporary files #
if($cleanup ) then
  rm -r $scratchdir
endif

date
echo "ipfsl Done"

exit 0;
###############################################

############--------------##################
parse_args:
set cmdline = ($argv);
while( $#argv != 0 )

  set flag = $argv[1]; shift;
  
  switch($flag)

    case "-i":
      if ( $#argv == 0) goto arg1err;
      set instem = $argv[1]; shift;
      breaksw

    case "-o":
      if ( $#argv == 0) goto arg1err;
      set outstem = $argv[1]; shift;
      breaksw

    case "-m":
      if ( $#argv == 0) goto arg1err;
      set maskstem = $argv[1]; shift;
      set makemask = 1;
      set maskbase = `basename $maskstem`
      set fslargs = ($fslargs -m $maskbase); shift;     
      breaksw

    case "-pctthresh"
    case "-pct":
      if ( $#argv == 0) goto arg1err;
      set pctthresh = $argv[1]; shift;
      breaksw

    case "-fwhm":
      if ( $#argv == 0) goto arg1err;
      set fwhm = $argv[1]; shift;
      set sigma = `echo "$fwhm/2.36" | bc -l`;
      set fslargs = ($fslargs -s $sigma); 
      breaksw

    case "-s":
    case "-i":
    case "-I":
      if ( $#argv == 0) goto arg1err;
      set fslargs = ($fslargs $flag $#argv[1]); shift;
      breaksw

    case "-t":
      if( $#argv < 2) then
        echo "ERROR: -t requires 2 arguments"
        exit 1;
      endif
      set fslargs = ($fslargs $flag $argv[1] $argv[2]); 
      shift;shift;
      breaksw

    case "-scratch":
      if ( $#argv == 0) goto arg1err;
      set scratchdir = $argv[1]; shift;
      breaksw

    case "-nocleanup":
      set cleanup = 0;
      breaksw

    case "-verbose":
      set verbose = 1;
      breaksw

    case "-echo":
      set echo = 1;
      breaksw

    case "-debug":
      set verbose = 1;
      set echo = 1;
      set debug = 1;
      breaksw

    case "-umask":
      if ( $#argv == 0) goto arg1err;
      umask $1; shift;
      breaksw

    default:
      echo ERROR: Flag $flag unrecognized. 
      echo $cmdline
      exit 1
      breaksw
  endsw

end

goto parse_args_return;
############--------------##################

############--------------##################
check_params:

  if($#instem == 0) then
     echo "ERROR: no input specified"
     exit 1
  endif

  if($#outstem == 0) then
     echo "ERROR: no output specified"
     exit 1
  endif

  if($#pctthresh == 0) then
     echo "ERROR: no threshold specified"
     exit 1
  endif

goto check_params_return;
############--------------##################

############--------------##################
arg1err:
  echo "ERROR: flag $flag requires one argument"
  exit 1
############--------------##################

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: ipfsl"
  echo ""
  echo "Required Arguments:";
  echo "   -i instem"
  echo "   -o outstem "
  echo "   -pctthresh thresh : percent of grand-mean for thresholding"
  echo ""
  echo "IP Optional Arguments:";
  echo "   -s sigma     : std of gaussian spatial smoothing (mm)"
  echo "   -fwhm fwhm   : fwhm of gaussian spatial smoothing (mm)"
  echo "       sigma = fwhm/2.36"
  echo "   -m maskstem  : create binary mask, apply to fmri data and save mask"
  echo "   -i targetmean : global intensity normalisation (separate "
  echo "        intensity rescaling for each 3D volume)"
  echo "   -I targetmean : grand mean intensity normalisation (one "
  echo "        intensity scaling for the whole 4D data set)"
  echo "   -t hp_sigma lp_sigma: Bandpass temporal filtering; nonlinear"
  echo "        highpass and Gaussian linear lowpass (with sigmas in "
  echo "        volumes, not seconds); set either sigma<0 to skip that filter"
  echo ""
  echo "Other Arguments (Optional)"
  echo "   -scratch    dir : put temporary files here"
  echo "   -nocleanup      : dont delete tempoaryr file"
  echo "   -umask umask    : set unix file permission mask"
  echo "   -version        : print version and exit"
  echo ""
  echo "This is a front-end for the fsl ip program. It works on bvolumes"
  echo "instead of analyze."
  echo ""
exit 1;
