#! /bin/csh -f

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

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

set analysis = ();
set TopDir = `pwd`;
set synthflag = ();
set sveres   = 1;
set svsignal = 0;
set svsnr    = 1;
set firstslice = ();
set nslices    = ();

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 parname   = `cat $infofile | awk '{if($1 == "parname") 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

##### 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/selxavg-jk-sess-$fsd-$analysis-$DateStr.log
  if(-e $LF) mv $LF $LF.old
endif
echo "--------------------------------------------------------------"
echo "selxavg-jk-sess logfile is $LF"
echo "--------------------------------------------------------------"

echo "selxavg-jk-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`;
  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

  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 TRSame = `echo "tmp=sqrt(($TR-$TRAnalysis)^2); if (tmp < .0001)  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"

  set fsigmergelist = ();
  foreach jkrun ($RunList)  
    set analysisdir = $analysis-jk$jkrun
    set instems     = ();
    set pars        = ();
    set tpexcludes  = ();

    foreach run ($RunList)  
      if($run == $jkrun) continue;

      set instem = $run/$funcstem
      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

      set instems = ($instems -i $instem $tpexarg);
    end

    set cmd = (selxavg2)
    set cmd = ($cmd -TR $TR -parname $parname -o $analysisdir/h )
    set cmd = ($cmd $instems $tpexcludes -cfg $cfgfile $synthflag)
    set cmd = ($cmd -ipr $inplaneres)
    set cmd = ($cmd -pomnibus $analysisdir/omnibus/fsig)
    if($sveres)   set cmd = ($cmd -eresdir   $analysisdir/eres)
    if($svsignal) set cmd = ($cmd -signaldir $analysisdir/signal)
    if($svsnr)    set cmd = ($cmd -snrdir    $analysisdir/estsnr)
    if($#firstslice != 0) set cmd = ($cmd -firstslice $firstslice);
    if($#nslices != 0) set cmd = ($cmd -nslices $nslices);
    echo "-------------------------------------------------" |& tee -a $LF
    pwd |& tee -a $LF
    echo $cmd |& tee -a $LF
    echo "---------------------------------------------------" |& tee -a $LF

    $cmd |& tee -a $LF
    if($status) then
      echo "ERROR ($sess): selxavg2 failed"
      exit 1;
    endif
    echo $StudyDir > $analysisdir/studydir

    set fsigmergelist = ($fsigmergelist $analysisdir/omnibus/fsig)

  end # End loop over jackknifed runs

  # Merge fsigs into one and put in first Run omnibus
  set fsigall = $analysis-jk$RunList[1]/omnibus/fsigall
  set cmd = (concat-bvolumes $fsigmergelist $fsigall)
  $cmd |& tee -a $LF
  if($status) then
    pwd |& tee -a $LF
    echo $cmd |& tee -a $LF
    echo "ERROR: merging fsig volumes"
  endif

end # End loop over sessions

echo " "
echo "Started at $StartTime "
echo "Ended   at `date`"
echo " "
echo "selxavg-jk-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 == 0) goto arg1err;
      set analysis = $argv[1]; shift;
      set analysis = `basename $analysis`; # remove trailing /
      breaksw

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

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

    case "-nosveres":
      set sveres = 0;
      breaksw

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

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

    case "-svsnr":
      set svsnr = 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 "-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($#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-jk-sess"
  echo ""
  echo "Required Arguments:";
  echo "   -analysis analysisname : name of functional analysis"
  echo ""
  echo "Optional Arguments:";
  echo "   -nosveres : do not save residual error"
  echo "   -svsignal : save estimated signal"
  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 "Creates analysis-jkXXX. By default, the residual error"
  echo "is saved in analysis-jkXXX/eres. An omnibus test is"
  echo "also performed and saved in analysis-jkXXX/omnibus/fsig."
  echo "These results are subsequently used by evfunc-jk-sess"
  echo "and evspatfil-jk-sess. In the omnibus directory of the"
  echo "first run, a volume will be created called fsigall in"
  echo "which each jk analysis is represented by a plane."
  echo ""
exit 1;
