#! /bin/csh -f

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

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

set analysis = ();
set ScriptOnly = 0;
set TopDir = `pwd`;
set synthflag = "";
set omnibus  = 1;
set sveres   = 0;
set svacf    = 0;
set svsignal = 0;
set svsnr    = 0;
set OutParent = ();
set maskdir = masks
set svbeta = 0;
set firstslice = ();
set nslices = ();
set loginput = 0;
set nolog = 0;
set monly = 0;
set MLF = ();
set sxamver = ();
set UseMRIread = 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

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

set StudyDir = `$PWD`;

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 TRAnalysis = `cat $infofile   | awk '{if($1 == "TR") print $2}'`;
set fsd       = `cat $infofile | awk '{if($1 == "fsd") print $2}'`;
set funcstem  = `cat $infofile | awk '{if($1 == "funcstem") print $2}'`;
set maskstem  = `cat $infofile | awk '{if($1 == "maskstem") print $2}'`;
set parname   = `cat $infofile | awk '{if($1 == "parname") print $2}'`;
set ncond     = `cat $infofile | awk '{if($1 == "nconditions") print $2}'`;
set tpexclude = `cat $infofile | awk '{if($1 == "tpexclude") print $2}'`;
set runlistfile = `cat $infofile | awk '{if($1 == "runlistfile") print $2}'`;
set designtype = `cat $infofile | awk '{if($1 == "designtype") print $2}'`;
if($#designtype == 0) then
  set designtype = `cat $infofile | awk '{if($1 == "avgtype") print $2}'`;
endif

if($designtype != "event-related" && $designtype != "blocked") then
  echo "ERROR: the design type of this analysis is $designtype"
  echo "  selxavg-sess can only be used to analyse event-related and blocked"
  exit 1;
endif

# Determine if this analysis uses a gamma fit (needed when making
# default contrasts
set tmp1 = `cat $cfgfile | grep gammafit`;
set tmp2 = `cat $cfgfile | grep spmhrf`;
if($#tmp1 == 0 && $#tmp2 == 0) then
  set IsGammaFit = 0;
else
  set IsGammaFit = 1;
endif

set WhitenFlag = `cat $cfgfile | awk '{if($1 == "-whiten") print 1}'`;
if($#WhitenFlag == 0) set WhitenFlag = 0;
echo "INFO: WhitenFlag = $WhitenFlag"

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

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

set StartTime = `date`;

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

  set sessbase = `basename $sess`;
  set sessdir  = `dirname  $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

  # Check whether to compute the whitening matrix
  if($WhitenFlag) then
    echo "INFO: computing whitening filter" |& tee -a $LF
    date |& tee -a $LF
    cd $StudyDir
    set cmd = (mkdesmtx-sess -a $analysis -s $sessbase -d $sessdir)
    set cmd = ($cmd -mktcvm -mask brain)
    echo $cmd |& tee -a $LF
    $cmd |& tee -a $LF 
    if($status) 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`);
    foreach run ($RunList)
      if(! -e $run) then
        echo "ERROR: cannot find run $run in `pwd`";
        echo "Make sure runs in run list file are 3-digit, zero padded"
        exit 1;
      endif
    end
  endif

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

  set d = `echo $TR-$TRAnalysis | bc -l`;
  set a = `echo "sqrt($d*$d)" | bc -l`;
  set TRSame = `echo "if($a > .001) 0; if($a < .001) 1" | bc -l` ;

  # This does not work on Sun
  #set TRSame = `echo "tmp=sqrt(($TR-$TRAnalysis)^2); if (tmp < .001)  print 1 else print 0 " | bc -l`;

  if(! $TRSame) then
    echo "ERROR: TR for $sessbase = $TR, Analysis TR = $TRAnalysis"
    exit 1;
  endif

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

  if($ScriptOnly) then
    mkdir -p scripts
    set scriptfile = scripts/run-selxavg-$analysis
    rm -f $scriptfile
    touch $scriptfile
    echo "#\!/bin/csh -f" >> $scriptfile
    echo "cd .." >> $scriptfile
    chmod a+x $scriptfile
  endif

  set instems = ();
  set pars    = ();
  set tpexcludes = ();
  set whtnmtx = ();
  foreach run ($RunList)  
    set instem = $run/$funcstem
    set parfile = $run/$parname
    if(! -e $parfile) then
      echo "ERROR: cannot find $parfile"
      exit 1;
    endif

    set pars = ($pars $parfile);

    set tpexarg = ();
    if($#tpexclude != 0) then
      set tpexfile = $run/$tpexclude
      if(-e $tpexfile) then
        set tpexarg = "-tpexclfile $tpexfile"
        echo "INFO: adding exclude file $tpexfile"
      else
        set tpexarg = "-tpexclfile noexcl"
      endif
    endif

    if($WhitenFlag) set whtnmtx = ($whtnmtx -whtnmtx $analysis/tcvm$run.mat)

    set instems = ($instems -i $instem $tpexarg);
  end # loop over runs

  # Count number of conditions, compare with analysis
  set ncondact = `countncond $pars`;
  if($ncondact != $ncond) then
    echo "ERROR: there are $ncondact non-null conditions in the "
    echo "paradigm file. However, $ncond non-null conditions were"
    echo "specified when mkanalysis was run. These must be made"
    echo "consistent in order to run selxavg-sess."
    exit 1;
  endif

  set cmd = "selxavg2"

  if($#OutParent == 0) then
    set OutDir = $analysis
  else
    set OutDir = $OutParent/$sessbase/$fsd/$analysis
  endif

  set cmd = ($cmd -TR $TR -parname $parname -o $OutDir/h )
  set cmd = ($cmd $instems $tpexcludes -cfg $cfgfile $synthflag)
  set cmd = ($cmd -ipr $inplaneres)
  if($omnibus) then
    set cmd = ($cmd -pomnibus  $OutDir/omnibus/fsig)
    set cmd = ($cmd -fomnibus  $OutDir/omnibus/f)
  endif
  if($sveres)    set cmd = ($cmd -eresdir   $OutDir/eres)
  if($svacf)     set cmd = ($cmd -acfdir    $OutDir/acf)
  if($svsignal)  set cmd = ($cmd -signaldir $OutDir/signal)
  if($svsnr)     set cmd = ($cmd -snrdir    $OutDir/estsnr)
  if($svbeta)    set cmd = ($cmd -beta      $OutDir/beta)
  if($#maskstem) set cmd = ($cmd -mask      $maskdir/$maskstem)
  if($#firstslice) set cmd = ($cmd -firstslice $firstslice)
  if($#nslices)    set cmd = ($cmd -nslices    $nslices)
  if($loginput)    set cmd = ($cmd -log)
  if($monly)       set cmd = ($cmd -monly $MLF)
  if($#sxamver)    set cmd = ($cmd -sxamver $sxamver)
  if($UseMRIread)  set cmd = ($cmd -mriread)

  set cmd = ($cmd $whtnmtx)
  echo "--------------------------------------------------------" |& tee -a $LF
  pwd |& tee -a $LF
  echo $cmd |& tee -a $LF
  echo "--------------------------------------------------------" |& tee -a $LF

  if(! $ScriptOnly) then
    $cmd |& tee -a $LF
    if($status) then
      echo "ERROR ($sess): selxavg failed"
      exit 1;
    endif
    cp $analysis/h.dat $analysisdir
    cp $analysisdir/analysis.cfg $analysis
    cp $analysisdir/analysis.info $analysis
    echo $StudyDir > $analysis/studydir
  else
    echo "$cmd" >> $scriptfile
    echo "\n\n" >> $scriptfile
  endif

end # Loop over sessions #

# Create the default all-v-fixation and omnibus contrast matrices #
cd $TopDir
set cmd1 = (mkcontrast -sxadat $analysisdir/h.dat -sumconds \
            -o $analysisdir/allvres)
set cmd2 = (mkcontrast -sxadat $analysisdir/h.dat -sumconds \
            -o $analysisdir/zallvres -rmprestim)
set cmd3 = (mkcontrast -sxadat $analysisdir/h.dat -o $analysisdir/omnibus)
set cmd4 = (mkcontrast -sxadat $analysisdir/h.dat \
            -o $analysisdir/zomnibus -rmprestim)
if(! $ScriptOnly) then
  $cmd1
  $cmd3
  if(! $IsGammaFit) $cmd2 # dont remove baseline from gamma
  if(! $IsGammaFit) $cmd4
else
  if(! -d scripts) mkdir scripts
  set scriptfile = scripts/run-mkcontrast-$analysis
  rm -f $scriptfile
  touch $scriptfile
  echo "#\!/bin/csh -f" >> $scriptfile
  echo "cd .." >> $scriptfile
  echo $cmd1 >> $scriptfile
  echo $cmd2 >> $scriptfile
  echo $cmd3 >> $scriptfile
  #echo $cmd4 >> $scriptfile
  echo "\n\n" >> $scriptfile
  chmod a+x $scriptfile
endif

echo "Started at $StartTime"
echo "Ended   at `date`"

echo " "
echo "COMPLETED SUCCESSFULLY"
echo " "

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

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

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

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

    case "-outparent":
    case "-op":
      if ( $#argv == 0) goto arg1err;
      set OutParent = $1; shift;
      breaksw

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

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

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

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

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

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

    case "-noomnibus":
      set omnibus = 0;
      breaksw

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

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

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

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

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

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

    case "-log":
      set loginput = 1;
      breaksw

    case "-mriread":
      set UseMRIread = 1; 
      breaksw

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

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

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

    case "-synth":
      set synthflag = "-synth -1";
      breaksw

    case "-scriptonly":
      set ScriptOnly = 1;
      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

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

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: selxavg-sess"
  echo ""
  echo "Required Arguments:";
  echo "   -analysis analysisname : name of functional analysis"
  echo ""
  echo "Optional Arguments:";
  echo "   -sveres   : save residual error to analysis/eres/eRRR"
  echo "   -svsignal : save signal estimate to analysis/signal/sRRR"
  echo "   -svsnr    : save estimate of SNR to analysis/estsnr"
  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 ""
exit 1;
