#! /bin/csh -f

#
# spatevfilter-sess
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:18 $
#    $Revision: 1.3 $
#
# 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: spatevfilter-sess,v 1.3 2007/01/09 22:41:18 nicks Exp $';

set inputargs = ($argv);
set analysis = ();
set spatevdef = ();
set spatevfildef = ();
set nkeepopt = ();
set regmethodopt = ();
set debugopt = ();

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

set PWDCMD = `getpwdcmd`;
if($status) exit 1;

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:

# get full path for cfg and info files #
pushd $analysis > /dev/null;
set analysisdir = `$PWDCMD`;
popd > /dev/null;
set cfgfile  = $analysisdir/analysis.cfg
set infofile = $analysisdir/analysis.info
if(! -e $infofile) then
  echo "ERROR: cannot find $infofile"
  exit 1;
endif

## Get parameters from the info file ##
set fsd       = `cat $infofile | awk '{if($1 == "fsd") print $2}'`;
set funcstem  = `cat $infofile | awk '{if($1 == "funcstem") print $2}'`;
set parname   = `cat $infofile | awk '{if($1 == "parname") print $2}'`;
set TR        = `cat $infofile | awk '{if($1 == "TR") print $2}'`;
set tpexclude = `cat $infofile | awk '{if($1 == "tpexclude") print $2}'`;
set runlistfile = `cat $infofile | awk '{if($1 == "runlistfile") print $2}'`;

##### Create a log file ######
set logdir = `$PWDCMD`/log;
mkdir -p $logdir
if(! -e $logdir) then
  echo "WARNING: could not create $logdir"
  set LF = /dev/null
else
  set LF = $logdir/spatev-sess-$fsd-$analysis.log
  if(-e $LF) mv $LF $LF.old
endif
echo "--------------------------------------------------------------"
echo "spatev-sess logfile is $LF"
echo "--------------------------------------------------------------"

echo "spatev-sess log file" >> $LF
echo $VERSION >> $LF
id            >> $LF
pwd           >> $LF
echo $0     >> $LF
echo $inputargs  >> $LF
uname -a      >> $LF
date          >> $LF

set svdsubdir = $analysis-osf

### Go through each session ###
foreach sess ($SessList)

  set sessbase = `basename $sess`;
  echo "-------------------------------------------" |& tee -a $LF
  echo "$sess " |& tee -a $LF
  date |& tee -a $LF

  if(! -d $sess) then
    echo "ERROR: $sess does not exist"   |& tee -a $LF
    exit 1;
  endif

  cd $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: ($sessbase) could not find runlistfile $runlistfile"
      exit 1;
    endif
    set RunList = (`cat $runlistfile`);
  endif

  echo "INFO ($sessbase): RunList = $RunList"

  #------------- Jackknife Loop ------------------#
  foreach run ($RunList)  

    set instem = $run/$funcstem
    set rawsevectstem = $run/$svdsubdir/$spatevdef-vy
    set rawsevalstem = $run/$svdsubdir/sy
    set signalsevectstem = $run/$svdsubdir/$spatevdef-vs
    set signalsevalstem = $run/$svdsubdir/ss
    set outstem = $run/$spatevfildef

    set cmd = (spatevfilter -i $instem -o $outstem)
    set cmd = ($cmd -rawsevect $rawsevectstem);
    set cmd = ($cmd -rawseval  $rawsevalstem);
    set cmd = ($cmd -signalsevect $signalsevectstem);
    set cmd = ($cmd -signalseval  $signalsevalstem);
    set cmd = ($cmd $nkeepopt $regmethodopt $debugopt);

    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 ($sess): spatevfilter failed"
      exit 1;
    endif

  end
  #------------- End Jackknife Loop ------------------#

end

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

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

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

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

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

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

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

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

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

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

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

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

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

    case "-cwd":
      # ignore getsesspath arguments 
      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 ($#analysis == 0) then
     echo "ERROR: no analysis name specified"
     exit 1
  endif

  if(! -d $analysis ) then
    echo "ERROR: analysis $analysis does not exist, see mkanalysis-sess"
    exit 1;
  endif

  if($#spatevdef == 0) then
    echo "ERROR: no spatevdef specfied"
    exit 1;
  endif

  if($#spatevfildef == 0) then
    echo "ERROR: no spatevfildef specfied"
    exit 1;
  endif

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

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

############--------------##################
usage_exit:
  echo "USAGE: spatevfilter-sess"
  echo "Options:";
  echo "   -analysis analysisname : name of session-level functional analysis"
  echo "   -spatevdef    name"
  echo "   -spatevfildef name"
  echo "   -nkeep n"
  echo "   -regmethod method"
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo "   -scriptonly    : don't run, just generate a script"
  echo "   -umask umask   : set unix file permission mask"
  echo "   -version       : print version and exit"
exit 1;
