#! /bin/tcsh -f

#
# roixrunsum-sess - cross-run summary of an ROI
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:18 $
#    $Revision: 1.2 $
#
# 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: roixrunsum-sess,v 1.2 2007/01/09 22:41:18 nicks Exp $';

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

set roidef = ();
set analysis = ();
set type = ();
set synth = ();
set monly = 0;

set PrintHelp = 0;

if($#argv == 0) goto usage_exit;

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

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

set PWD = `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:

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

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

# get full path for cfg and info files #
pushd $analysis > /dev/null;
set analysisdir = `pwd`;
popd > /dev/null;
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}'`;

### 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(! -e $analysis) then
    echo "ERROR: $analysis does not exist"
    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

  foreach run ($RunList)
    if($type == jackknife) then
      set a = $analysis-jk$run;
    else
      set a = $analysis-$run;
    endif
    if(! -e $a/$roidef) then
      echo "ERROR: cannot find $a/$roidef"
      exit 1;
    endif
  end

  set outdir = $analysis/$roidef
  mkdir -p $outdir
  set outfile = $outdir/h-$typecode-xrun_000.bfloat

  #set MLF = /tmp/roixrunsum_$$.m
  set MLF = roixrunsum.m
  rm -f $MLF

#--------------------------------------------------------#
tee $MLF <<EOF
  global QuitOnError;
  monly    = $monly;
  RoiDef   = '$roidef';
  Analysis = '$analysis';
  Type     = '$type';
  RunList  = [$RunList];
  outfile  = '$outfile';

  if(~monly) QuitOnError = 1; 
  else       QuitOnError = 0; 
  end

  nthrun = 1;
  for run = RunList
    if(strcmp(Type,'jackknife'))
      hfile = sprintf('%s-jk%03d/%s/h_000.bfloat',Analysis,run,RoiDef);
      %hofffile = sprintf('%s-jk%03d/%s/h-offset_000.bfloat',...
      %   Analysis,run,RoiDef);
    else
      hfile = sprintf('%s-%03d/%s/h_000.bfloat',Analysis,run,RoiDef);
      %hofffile = sprintf('%s-%03d/%s/h-offset_000.bfloat',...
      %   Analysis,run,RoiDef);
    end

    [h ev sxa] = fast_ldsxabfile(hfile);
    if(isempty(h))
      fprintf('ERROR: cannot load %s\n',hfile);
      return;
    end
    h = squeeze(h);

    for c = 1:sxa.Nnnc
      i1 = (c-1)*sxa.Nh + 1;
      i2 = i1 + sxa.Nh - 1;
      hall(nthrun,c,:) = h(i1:i2);
    end

    nthrun = nthrun + 1;
  end

  fmri_svbfile(hall,outfile);

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

if(! $monly) then
  cat $MLF | matlab -display iconic
  rm -f $MLF
endif

echo ""

end # Loop over sessions

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 "-roidef":
      if ( $#argv == 0) goto arg1err;
      set roidef = $argv[1]; shift;
      breaksw

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

    case "-synth":
      if( $#argv < 3) then
        echo "ERROR: -synth needs 3 arguments"
        exit 1;
      endif
      set synth = ($argv[1] $argv[2] $argv[3]);
      shift; shift; shift; 
      breaksw

    case "-monly":
      set monly = 1;
      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($#roidef == 0) then
    echo "ERROR: no roidef specified"
    exit 1;
  endif

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

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

  if($type == jackknife) then
    set typecode = jk
  else
    set typecode = pr;
  endif

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

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: roixrunsum-sess"
  echo ""
  echo "Required Arguments:";
  echo "   -roidef roidefname "
  echo "   -analysis analysisname : name of functional analysis"
  echo "   -type perrun or jackknife"
  echo ""
  echo "Other Arguments (Optional)"
  echo "   -synth amp delta tau"
  echo ""
  echo "Session Arguments (Required)"
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  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

This will collect data ROI into a summary.
