#! /bin/csh -f

#
# stxgrinder-sess-perrun
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:19 $
#    $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'

set inputargs = "$argv";

set contrast    = ();
set pxform      = log10;
set analysis    = ();
set grpname     = ();
set space       = native;
set spacedir    = ();
set ScriptOnly  = 0;
set umaskarg    = ();
set hemi        = ();
set SessList     = ();
set nolog = 0;

set IsSess = 0;
set IsGrp  = 0;

set n = `echo $argv | grep version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif

if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

goto parse_args;
parse_args_return:

set SessList = `getsesspath $inputargs`;
if($status) then
  echo "$SessList"
  exit 1;
endif

goto check_params;
check_params_return:

## Get functional subdirectory from the info file ##
set infofile = $analysis/analysis.info
if(! -e $infofile) then
  echo "ERROR: cannot find $infofile"
  exit 1;
endif
set fsd = `cat $analysis/analysis.info | awk '{if($1 == "fsd") print $2}'`;
set runlistfile = `cat $infofile | awk '{if($1 == "runlistfile") print $2}'`;

## Look for nolog option ##
set n = `echo $inputargs | grep nolog | wc -l` 
if($n != 0) set nolog = 1;

##### Create a log file ######
if(! $nolog) then
  set logdir = `pwd`/log;
  mkdir -p $logdir
  if(! -e $logdir) then
    echo "ERROR: could not create $logdir"
    exit 1;
  endif
  set LF = $logdir/stxgrinder-sess-perrun-$fsd-$analysis-$contrast.log
  if(-e $LF) mv $LF $LF.old
else
  echo "No log file"
  set LF = /dev/null
endif

echo "stxgrinder-sess-perrun Logfile is $LF"

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

## Loop through each hemi (if needed) ##
foreach sess ($SessList)

  set sessid = `basename $sess`;
  echo "-------------------------------------------------------"
  echo "-------------------------------------------------------"
  echo "Session: $sess "

  pushd $sess/$fsd > /dev/null;

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

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

  foreach run ($RunList)
    set instem = $analysis-$run/h
    set outdir = $analysis-$run/$contrast
    set sigstem   = $outdir/sig
    set pminstem  = $outdir/minsig
    set ipminstem = $outdir/iminsig
    set statstem  = $outdir/t
    set fstatstem  = $outdir/f
    set fsigstem  = $outdir/fsig
    set cmd = "stxgrinder -cmtx $cmtx -i $instem -o $sigstem "
    set cmd = "$cmd -pmin $pminstem -ipmin $ipminstem -statstem $statstem"
    set cmd = "$cmd -fstat $fstatstem -fsig $fsigstem "

    echo "-------------------------------------------------"
    pwd  |& tee -a $LF
    echo $cmd |& tee -a $LF
    echo "-------------------------------------------------"
    $cmd |& tee -a $LF
    if($status) then
      echo "ERROR: stxgrinder failed" |& tee -a $LF
      exit 1;
    endif
    cp $cmtx $outdir
  end

end # end loop over sess list #

date | tee -a $LF
echo " "
echo "stxgrinder-sess-perrun completed SUCCESSFULLY" | tee -a $LF
echo " "

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

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

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

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

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

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

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

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

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

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

    case "-nolog"
      breaksw

    case "-cwd"
      breaksw

    case "-s":
    case "-sf":
    case "-df":
    case "-d":
    case "-g":
      shift;
      breaksw

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

end

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

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

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

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

  set cmtx = `pwd`/$analysis/$contrast.mat
  if(! -e $cmtx) then
    echo "ERROR: cannot find $cmtx, see mkcontrast-sess"
    exit 1;
  endif

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

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

############--------------##################
usage_exit:
  echo "USAGE: stxgrinder-sess-perrun"
  echo "Options:";
  echo "   -analysis  analysisname : name of session-level functional analysis";
  echo "   -contrast  contrastname : contrast name"
  echo "   -pxform    xform : <log10>, ln, none";
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo "   -scriptonly    : don't run, just generate a script"
  echo "   -version       : print version and exit"
  echo "   -umask umask   : set unix file permission mask"
exit 1;
