#! /bin/csh -f

#
# spatialsmooth-sess
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: greve $
#    $Date: 2007/09/26 18:02:37 $
#    $Revision: 1.15.2.2 $
#
# 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: spatialsmooth-sess,v 1.15.2.2 2007/09/26 18:02:37 greve Exp $';

set cmdargs = ($argv);

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

set infmt   = ();
set outfmt  = bhdr;
if($?FSF_OUTPUT_FORMAT) then
  set outfmt = $FSF_OUTPUT_FORMAT;
endif

set nolog = 0;
set tmpdir = ();
set cleanup = 1;

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 . && ! $nolog) 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 && $use_new_inorm == 0) 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)
    set infmt = `getformat_from_stem $run/$instem`
    if($status) then
      echo "ERROR: cannot find $run/$instem"
      exit 1;
    endif
    set infunc  = $run/$instem.$infmt
    set outfunc = $run/$outstem.$outfmt

    if($UpdateOnly) then
      test $infunc -nt $outfunc
      if($status) then
        pwd
        ls -lt $outfunc $infunc | tee -a $LF
        echo "Update not needed" | tee -a $LF
        continue
      endif
    endif

    if($UseFSL) then
      # Construct and run the command for this run #
      set cmd = (ipfsl -i $run/$instem -o $run/$outstem -pct .1)
      set cmd = ($cmd -fwhm $fwhm -outfmt $outfmt)
      if($#infmt != 0)  set cmd = ($cmd -infmt $infmt)
      if($#tmpdir == 0) set cmd = ($cmd -scratch tmp.ipfsl)
      if($#tmpdir != 0) set cmd = ($cmd -scratch $tmpdir)
      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(! -e $run/$outstem.$outfmt) then
        echo "ERROR: ipfsl failed to create output"
        exit 1
      endif
      if($#tmpdir == 0) rm -r tmp.ipfsl
    else
      set cmd = (mri_fwhm --i $infunc --o $outfunc --fwhm $fwhm --smooth-only) 
      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: mri_fwhm failed"
        exit 1
      endif
    endif

    if($inorm) then
      echo "INFO: intensity normalizing smoothed volume"
      if(! $use_new_inorm) then
        set cmd = (inorm -i $run/$outstem -TR $TR -ipr $IPR -bpr $BPR)    
      else
        set cmd = (inorm2 -i $run/$outstem);
      endif
      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: inorm 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 "-noinorm":
    case "-no-inorm":
      set inorm = 0;
      breaksw

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

    case "-inorm-old":
      set use_new_inorm = 0;
      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 "-tmp":
      if ( $#argv == 0) goto arg1err;
      set tmpdir = $argv[1]; shift;
      set cleanup = 0;
      breaksw

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

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

    case "-update":
      set UpdateOnly = 1;
      breaksw

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

    case "-fsl":
      set UseFSL = 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

  if($UseFSL) then
    set ip = $FSLDIR/bin/ip
    if(! -e $ip) then
      echo "ERROR: cannot find $ip"
      exit 1;
    endif
  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 "   -update         : only run if input is newer than output"
  echo "   -no-inorm       : do not intensity norm smoothed volume"
  echo "   -inorm-old      : use old inorm"
  echo "   -infmt format   : <autodetect>, bhdr, mgh, nii.gz, etc"
  echo "   -outfmt format  : <bhdr>, mgh, nii.gz, etc"
  echo ""
  echo "   -fsl : use FSL version 3.3 ip command"
  echo "   -version        : print version and exit"
  echo "   -nolog          : do create a log file"
  echo "   -help           : print help and exit"
  echo ""

  if(! $PrintHelp ) exit 1;

  echo "This program performs 3D gaussian spatial smoothing. It will"
  echo "operate 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. It will also automatically run intensity normalization"
  echo "(ie, inorm-sess) for the smoothed volume unless -noinorm is "
  echo "specified."
  echo ""
  echo "$VERSION"
  echo ""

exit 1;
