#!/bin/csh -f
# spatialsmooth-sess
#
# $Id: spatialsmooth-sess,v 1.4 2003/10/01 21:54:43 greve Exp $

set VERSION = '$Id: spatialsmooth-sess,v 1.4 2003/10/01 21:54:43 greve Exp $';

set cmdargs = ($argv);

set fsd     = "bold";
set instem  = (); 
set outstem = (); 
set RunList0 = ();
set RunListFile = ();
set PrintHelp = 0;
set HPF = ();
set inorm = 0;

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

set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;
  goto usage_exit;
  exit 1;
endif

set PWDCMD = `getpwdcmd`;

set SessList = `getsesspath $argv`;
if($status || $#SessList == 0) then
  getsesspath $argv 
  exit 1;
endif

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

set ProjectDir = `pwd`;

#------------------------------------------------------------------#
set StartTime = `date`;
foreach sess ($SessList)
  set sessid = `basename $sess`;

  # Create a log file #
  if(-w .) then
    mkdir -p log
    set LF = $ProjectDir/log/spatialsmooth-$sessid-$fsd.log
    rm -f $LF
  else
    set LF = /dev/null
  endif

  echo "spatiallysmooth-sess" >> $LF
  echo $VERSION   >> $LF
  echo $sessid    >> $LF
  uname -a        >> $LF
  date            >> $LF
  pwd             >> $LF
  echo $cmdargs   >> $LF
  echo "ProjectDir $ProjectDir" >> $LF

  echo "------------------------------------------------" |& tee -a $LF
  echo "------------------------------------------------" |& tee -a $LF
  echo $sess |& tee -a $LF
  date |& tee -a $LF

  ### Check that the target directory is there ###
  if(! -d $sess/$fsd) then
    echo "ERROR: $sess/$fsd does not exist"   |& tee -a $LF
    exit 1;
  endif

  ### Check that the target directory is writable ###
  if(! -w $sess/$fsd) then
    echo "ERROR: $sess/$fsd is not writable"   |& tee -a $LF
    exit 1;
  endif

  ### Goto the functional subdirectory ###
  pushd $sess/$fsd

  if($#RunListFile == 0) then
    set RunList = `getrunlist .`;
    if($status || $#RunList == 0) then
      echo "ERROR: $sess/$fsd has no runs"  |& tee -a $LF
      exit 1;
    endif
  else  
    if(! -e $RunListFile) then
      echo "ERROR: cannot find $RunListFile"
      exit 1;
    endif
    set RunList = (`cat $RunListFile`);
  endif
  echo "RunList $RunList" |& tee -a $LF

  if($inorm) then
    set seqinfo = seq.info
    if(! -e $seqinfo) then
      echo "ERROR: cannot find $seqinfo"
      exit 1;
    endif
    set TR  = `cat $seqinfo | awk '{if($1=="TR") print $2}'`;
    set IPR = `cat $seqinfo | awk '{if($1=="rowpixelsize") print $2}'`;
    set BPR = `cat $seqinfo | awk '{if($1=="slcpixelsize") print $2}'`;
  endif

  ## Go through each run ##
  foreach run ($RunList)

    # Make sure input has a .bhdr file #
    set bhdr = $run/$instem.bhdr
    if(! -e $bhdr) then
      set bhdr0 = $run/f.bhdr
      if(! -e $bhdr0) then
        echo "WARNING: cannot find $bhdr or $bhdr0"
        exit 1;
      endif
      echo "INFO: could not find $bhdr, using $bhdr0"
      cp $bhdr0 $bhdr 
    endif

    # Construct and run the command for this run #
    set cmd = (ipfsl -i $run/$instem -o $run/$outstem -pct .1)
    set cmd = ($cmd -fwhm $fwhm)
    if($#HPF != 0)  set cmd = ($cmd -t $HPF -1)
    echo ---------------------------------------------- |& tee -a $LF
    $PWDCMD   |& tee -a $LF
    echo $cmd |& tee -a $LF
    echo ---------------------------------------------- |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) then
      echo "ERROR: ipfsl failed"
      exit 1
    endif

  if($inorm) then
    echo "INFO: intensity normalizing smoothed volume"
    set cmd = (inorm -i $run/$outstem -TR $TR -ipr $IPR -bpr $BPR)    
    echo ---------------------------------------------- |& tee -a $LF
    $PWDCMD   |& tee -a $LF
    echo $cmd |& tee -a $LF
    echo ---------------------------------------------- |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) then
      echo "ERROR: ipfsl failed"
      exit 1
    endif
  endif

  end # Loop over runs


  popd > /dev/null

end # Loop over sessions #

echo "Started at $StartTime" |& tee -a $LF
echo "Ended   at `date`"     |& tee -a $LF
echo "spatiallysmooth-sess Done" |& tee -a $LF

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 "-fwhm":
      if ( $#argv == 0) goto arg1err;
      set fwhm = $argv[1]; shift;
      breaksw

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

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

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

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

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

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

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

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

    case "-g":
    case "-s":
    case "-sf":
    case "-d":
    case "-df":
      shift;
      # ignore getsesspath arguments 
      breaksw

    case "-cwd":
      # ignore getsesspath arguments 
      breaksw

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

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

end

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

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

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

  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($#fwhm == 0) then
    echo "ERROR: no FWHM specified"
    exit 1
  endif

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

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: spatialsmooth-sess"
  echo ""
  echo "Required Arguments"
  echo "   -i instem      : input  functional volume stem "
  echo "   -o outstem     : output functional volume stem "
  echo "   -fwhm          : gaussian fwhm (sigma = fwhm/2.36)"
  echo ""
  echo "Session Arguments (Required)"
  echo "   -sf sessidfile  "
  echo "   -df srchdirfile "
  echo "   -s  sessid      "
  echo "   -d  srchdir     "
  echo "   -fsd fsdir      (optional)"
  echo ""
  echo "Other Arguments"
  echo "   -inorm          : intensity norm smoothed volume"
  echo "   -umask umask    : set unix file permission mask"
  echo "   -version        : print version and exit"
  echo "   -help           : print help and exit"
  echo ""

  if(! $PrintHelp ) exit 1;

  echo "This program uses the FSL IP program to do 3D gaussian"
  echo "spatial smoothing (www.fmrib.ox.ac.uk/fsl). It will operate "
  echo "on the input volume in each run. The output volume will be "
  echo "placed in the same directory. FWHM is the full-width, half-"
  echo "maximum of the spatial filter."
  echo ""
  echo " Example:"
  echo ""
  echo "spatialsmooth-sess -s sessid -d sessdir -i fmc -o fmcsm5 -fwhm 5"
  echo ""
  echo "This will smooth the motion corrected volume with a gaussian "
  echo "kernel with FWHM of 5 mm. The result will be placed in the volume"
  echo "fmcsm5. This is the stem that should be referenced when creating"
  echo "the anlysis."
  echo ""
  echo "$VERSION"
  echo ""

exit 1;
