#!/bin/csh -f
# svdfilter-sess
#
# $Id$
set VERSION = '$Id$';

set inputargs = ($argv);
set DateStr = "`date '+%y%m%d%H%M'`"

set StudyDir = `pwd`;

set analysis = ();
set outstem  = ();
set sigthresh = ();
set dimfrac = 1;
set filfunc = ();

set mask = brain;
set func = ();

set contrast = ();
set map = sig;

set monly = 0;
set MLF = ();
set QuitOnError = 0;
set PrintHelp = 0;

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

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 = `pwd`;
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 runlistfile = `cat $infofile | awk '{if($1 == "runlistfile") print $2}'`;
if($#func == 0) \
  set func    = `cat $infofile | awk '{if($1 == "funcstem") print $2}'`;

set designtype  = `cat $infofile | awk '{if($1 == "designtype") print $2}'`;
if($designtype != "event-related" && $designtype != "blocked") then
  echo "ERROR: the design type of this analysis is $designtype"
  echo "  kmacfwht-sess can only be used to analyse event-related and blocked"
  exit 1;
endif

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

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

### Go through each session ###
set StartTime = `date`;
foreach sess ($SessList)

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

  set fsdpath = $sess/$fsd
  cd $fsdpath

  if(! $monly) set MLF = /tmp/svdfilter-$$.m
  rm -f $MLF
  echo "MLF is $MLF" |& tee -a $LF

  set RunList = `getrunlist . $runlistfile`;
  if($status || $#RunList == 0) then
     echo "ERROR: $sess/$fsd has no runs"  |& tee -a $LF
     exit 1;
  endif
  echo "INFO ($sessbase): RunList = $RunList" 

  set xmatfile = $RunList[1]/$analysis.mat
  if(! -e $xmatfile ) then
    echo "$xmatfile does not exist, running mkdesmtx-sess" |& tee -a $LF
    pushd $StudyDir > /dev/null
    set cmd = (mkdesmtx-sess -s $sessbase -d $sesspar -a $analysis)
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF
    if($status) exit 1;
    popd > /dev/null
  endif

#-----------------------------------------------------------------#
tee $MLF>/dev/null <<EOF

clear all;
fsd = '$fsdpath';
analysis = '$analysis';
runidlist = splitstring('$RunList');
extregrstem = '$outstem';

funcrstem    = '$func';
filfuncrstem = '$filfunc';
maskrstem = '$mask';
dimfrac   = [$dimfrac];
sigthresh = [$sigthresh];
cd(fsd);

fast_svdfilter;

EOF
#-----------------------------------------------------------------#

  if(! $monly ) then
    cat $MLF | matlab -display iconic |& tee -a $LF
  endif

end # Sessions

echo " "
echo "Started at $StartTime "
echo "Ended   at `date`"
echo " "
echo "svdfilter-sess Done"
echo " "

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

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

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

    case "-a":
    case "-analysis":
      if ( $#argv < 1) goto arg1err;
      set analysis = $argv[1]; shift;
      set analysis = `basename $analysis`; # remove trailing /
      breaksw

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

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

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

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

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

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

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

    case "-nomask":
      set mask = ();
      breaksw

    case "-help":
      goto help;
      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;
      umask $1; shift;
      breaksw

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

end

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

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

  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($#outstem == 0) set outstem = svd-xreg

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

  if($#dimfrac == 0) set dimfrac = 1.0;


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

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

############--------------##################
arg2err:
  echo "ERROR: flag $flag requires two arguments"
  exit 1
############--------------##################

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: svdfilter-sess"
  echo ""
  echo "Required Arguments:";
  echo "   -analysis  analysisname : name of functional analysis"
  echo "   -sigthresh  sigthresh : -log10(pthresh)"
  echo ""
  echo "Optional Arguments:";
  echo "   -dimfrac    dimfrac   : default is 1"
  echo "   -o outputstem : default is svd-xreg"
  echo "   -f funcstem : default is that from analysis"
  echo "   -ffil filfuncstem : filtered output"
  echo "   -mask  stem: default is brain"
  echo "   -nomask  : do not use a mask"
  echo ""
  echo "Session Arguments (Required)"
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo ""
  echo "Session Arguments (Optional)"
  echo "   -umask umask   : set unix file permission mask"
  echo "   -version       : print version and exit"
  echo ""
  echo ""

  if($PrintHelp) \
  cat $0 | awk 'BEGIN{prt=0}{if(prt) print $0; if($1 == "BEGINHELP") prt = 1 }'

exit 1;

#---- Everything below here is printed out as part of help -----#
BEGINHELP

Creates non-parametric temporal nuisance regressors from the
eigenvectors of the almost-raw input data. These are stored in a way
that can be accessed using the -extreg flag with mkanalysis-sess.new.

The voxels used to compute the eigenvectors can be constrained in
several ways: (1) binary mask (default is to use only brain voxels)
and (2) exclude those whose task-related activity exceeds a threshold
(sigthresh).  Finally, the eigenvectors themselves can be tested for
activity and excluded. The task-related activity is defined by the
analysis.

Once the voxels have been chosen, the time courses are de-meaned and the
SVD is computed. The underlaying dimensionality is computed as the
integer where the eigenspectrum intersects the eigenspectrum of
white noise from an equivalent sized data set. This number can be
modified with -fracdim, in which case the dimension used is the 
dimension found times fracdim (ie, set 0<fracdim<1 to use fewer).

By default, the eigenvectors will be stored in stem svd-xreg in
the same directory as the raw data that it was derived from.
