#! /bin/csh -f

#
# ipfsl - front-end for FSL's IP program
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: greve $
#    $Date: 2007/04/25 23:41:20 $
#    $Revision: 1.9 $
#
# Copyright (C) 2002-2007,
# The General Hospital Corporation (Boston, MA). 
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-bugs@nmr.mgh.harvard.edu
#


set VERSION = '$Id: ipfsl,v 1.9 2007/04/25 23:41:20 greve Exp $';

set inputargs = ($argv);

set instem     = ();
set outstem    = ();
set maskstem   = ();
set makemask   = 0;
set pctthresh  = ();
set fslargs    = ();
set infmt      = ();
set outfmt  = bhdr;
if($?FSF_OUTPUT_FORMAT) then
  set outfmt = $FSF_OUTPUT_FORMAT;
endif

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(! $?FSLDIR) then
  echo "ERROR: FSLDIR environment variable not defined"
  exit 1;
endif
set IPFSL = $FSLDIR/bin/ip
if(! -e $IPFSL) then
  echo "ERROR: cannot find $IPFSL"
  exit 1;
endif

setenv FSLOUTPUTTYPE NIFTI

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`;

echo "# ---------- Converting to .nii ------------------ #"
set infmtuse = `getformat_from_stem $instem $infmt`
if($status) then
  echo "$infmtuse" 
  exit 1;
endif
echo "Input  format is $infmtuse"
echo "Output format is $outfmt"
set cmd = (mri_convert $instem.$infmtuse)
set cmd = ($cmd $scratchdir/$inbase.nii)
$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.nii)
set cmd = ($cmd $outstem.$outfmt)
$cmd
if($status) then
  pwd
  echo $cmd
  echo "ERROR: mri_convert failed"
  exit 1;
endif

if($makemask) then
  cp $inmatfile $scratchdir/$maskbase.mat
  echo "# ---------- Converting mask to bshort ------------------ #"
  set cmd = (mri_convert $scratchdir/$maskbase.nii)
  set cmd = ($cmd $maskstem.$outfmt )
  $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);
      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 "-fmt":
      if($#argv < 0) goto arg1err;
      set infmt  = $argv[1]; shift;
      set outfmt = $argv[1]; shift;
      breaksw

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

    case "-outfmt":
      if($#argv < 0) goto arg1err;
      set outfmt = $argv[1]; 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 "   -infmt  format : <auto>, bhdr, mgh, mgz, nii, nii.gz"
  echo "   -outfmt format : <bhdr>, mgh, mgz, nii, nii.gz"
  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."
  echo ""
exit 1;
