#! /bin/csh -f

#
# selxavg3-sess
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: greve $
#    $Date: 2007/11/28 23:00:46 $
#    $Revision: 1.32.2.1 $
#
# 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: selxavg3-sess,v 1.32.2.1 2007/11/28 23:00:46 greve Exp $'

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

set analysis = ();
set flacfile = ();
set fsd = bold
set geometry = volume
set subject = ();
set perrun = 0;
set jkrun  = 0;

set OutParent = ();
set nolog = 0;
set monly = 0;
set MLF = ();
set LF = ();

set DoGLMFit = 1;
set DoContrasts = 1;
set DoFWHM = 1;
set SaveRes = 0;
set UseFloat = 0;

set Skip  = 0;
set Overwrite = 0;

set DoSynth = 0;
set SynthNoiseAmp = 1;
set SynthSignalAmp = 0;
set SynthSeed = -1;

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

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

set SessList = `getsesspath $argv`;
if($status || $#SessList == 0) then
  echo $SessList
  exit 1;
endif

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

set StudyDir = `pwd`;

if($#analysis) then
  # 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
  set fsd  = `cat $infofile | awk '{if($1 == "fsd") print $2}'`;
  set analysisname = $analysis
else
  set analysisname = `cat $flacfile | awk '{if($1 == "flacname") print $2}'`
  set inherit = $flacfile
  while(1)
    set tmp = `cat $inherit | awk '{if($1 == "INHERIT") print $2}'`
    if($#tmp != 0) then
      set inherit = $tmp;
      continue
    endif
    set fsd = `cat $inherit | awk '{if($1 == "fsd") print $2}'`
    echo "fsd = $fsd"
    break;
  end
endif

##### Create a log file ######
if($#LF == 0) then
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/selxavg3-sess-$fsd-$analysis-$DateStr.log
    if(-e $LF) mv $LF $LF.old
  endif
endif
endif
echo "--------------------------------------------------------------"
echo "selxavg3-sess logfile is $LF"
echo "--------------------------------------------------------------"

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

set StartTime = `date`;

if($#MLF == 0) set MLF = /tmp/selxavg3-sess-$$.m
rm -f $MLF
echo "% `date`  " >> $MLF
echo "% `pwd`  " >> $MLF
echo "% $flacfile $analysis  " >> $MLF
echo "  " >> $MLF
echo "  " >> $MLF


set okfile = /tmp/selxavg3-sess-$$.ok
rm -f $okfile

### Go through each session ###
@ nthsess = 0;
@ nprocs = 0;
foreach sess ($SessList)
  @ nthsess = $nthsess + 1;

  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

  set funcdir = $sess/$fsd
  set anadir = $sess/$fsd/$analysisname
  if($#OutParent == 0) then
    set anadir = $sess/$fsd/$analysisname
  else
    set anadir = $OutParent/$sessbase/$fsd/$analysisname
  endif
  echo anadir = $anadir | tee -a $LF
  if(-e $anadir && $DoGLMFit) then
    echo "analysis $analysis alread exists for $sessbase" | tee -a $LF
    if($Skip == 0 && $Overwrite == 0 && ! $monly && ! $perrun && ! $jkrun) then
      echo "ERROR: analysis $analysis already exists. You must " | tee -a $LF
      echo "       specify whether to -skip or -overwrite" | tee -a $LF
      exit 1;
    endif
    if($Skip) then
      if(! -e $anadir/X.mat) then
        echo "ERROR: analysis dir $anadir exists, but it does not look like "
        echo "anything is there. Try reanalyzing just this session ($sessbase)"
        echo "with the -overwrite flag."
        exit 1;
      endif
      echo " ... skipping" | tee -a $LF
      continue;
    endif
    if( ! $monly && ! $perrun && ! $jkrun) then
      echo " ... reanalyzing (deleting old analysis)" | tee -a $LF
      rm -f $anadir/* $anadir/*/*sig* $anadir/*/*cnr* $anadir/*/*ces* >& /dev/null
    endif
  endif
  @ nprocs = $nprocs + 1;

  echo "%--------------------------------" >> $MLF
  echo "which fast_selxavg3"               >> $MLF
  echo "okfile         = '$okfile';"       >> $MLF
  echo "if(fast_fileexists(okfile)) delete(okfile); end" >> $MLF
  echo "monly          = $monly;"          >> $MLF
  echo "perrun         = $perrun;"         >> $MLF
  echo "jkrun          = $jkrun;"          >> $MLF
  echo "DoGLMFit       = $DoGLMFit;"       >> $MLF
  echo "DoContrasts    = $DoContrasts;"    >> $MLF
  echo "DoSynth        = $DoSynth;"        >> $MLF
  echo "UseFloat       = $UseFloat;"       >> $MLF
  echo "SynthNoiseAmp  = $SynthNoiseAmp;"  >> $MLF
  echo "SynthSignalAmp = $SynthSignalAmp;" >> $MLF
  echo "SynthSeed      = $SynthSeed;"      >> $MLF
  echo "sess           = '$sess';"         >> $MLF
  echo "analysis = '$analysis';" >> $MLF
  echo "flacname = '$flacfile';" >> $MLF
  echo "outtop = '$OutParent';" >> $MLF
  echo "fast_selxavg3;" >> $MLF
  echo "if(~fast_fileexists(okfile) && ~monly); quit; end" >> $MLF
  if($#SessList > 1 && ! $monly)  then
    echo "clear all;" >> $MLF
    echo "pack;" >> $MLF
  endif
  echo "  " >> $MLF
  echo "  " >> $MLF

end # Loop over sessions #

echo "------------------------------------------" >> $LF
cat $MLF >> $LF
echo "------------------------------------------" >> $LF

if(! $monly && $nprocs > 0) then
  echo "------------------------------------------" | tee -a $LF
  echo "------- matlab output --------------------" | tee -a $LF
  cat $MLF | matlab -display iconic | tee -a $LF
  echo "------------------------------------------" | tee -a $LF
  rm $MLF
  if(! -e $okfile) then
    echo "ERROR: fast_selxavg3() failed\n";
    exit 1;
  endif
  rm -f $okfile
endif

# Copy the flac or analysis.*
if(! $monly) then
  foreach sess ($SessList)
    set sessbase = `basename $sess`;
    set sessdir  = `dirname  $sess`;
    if($#OutParent == 0) then
      set anadir = $sess/$fsd/$analysisname
    else
      set anadir = $OutParent/$sessbase/$fsd/$analysisname
    endif
    if($#flacfile) then
      cp $flacfile $anadir 
    else
      cp $cfgfile $anadir
      cp $infofile $anadir
    endif
  end
endif

# Compute FWHM
if($DoFWHM && ! $monly) then
  echo "-------------------------------------------" |& tee -a $LF
  echo "Computing FWHM" |& tee -a $LF
  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($#OutParent == 0) then
      set anadir0 = $sess/$fsd/$analysisname
    else
      set anadir0 = $OutParent/$sessbase/$fsd/$analysisname
    endif

    if($perrun) then
      set anadirlist = (`ls -d $anadir0/pr[0-9][0-9][0-9]`)
    else if ($jkrun) then
      set anadirlist = (`ls -d $anadir0/jk[0-9][0-9][0-9]`)
    else
      set anadirlist = ($anadir0);
    endif

    foreach anadir ($anadirlist)

      set resdir = $anadir/res
      if(! -e $resdir) continue

      # concat the residuals together
      set all = $resdir/all.nii
      set cmd = (mri_concat $resdir/res-???.* --o $all)
      pwd |& tee -a $LF
      echo $cmd |& tee -a $LF
      $cmd |& tee -a $LF
      if($status) exit 1;

      # Compute FWHM
      set sumfile = $anadir/fwhm.sum
      set datfile = $anadir/fwhm.dat
      if($geometry == volume) then
        # Volume-based cmd line
        set cmd = (mri_fwhm --mask $anadir/mask.nii --i $all)
        set cmd = ($cmd --sum $sumfile --dat $datfile)
      else
        # Surface-based cmd line
        set reg = $sess/$fsd/register.dat
        if($#subject == 0) then
          set subjectuse = `reg2subj $reg`
        else
          set subjectuse = $subject
        endif
        set cmd = (mris_fwhm --i $all --s $subjectuse \
                   --hemi $geometry --sum $sumfile)
      endif
      pwd |& tee -a $LF
      echo $cmd |& tee -a $LF
      $cmd |& tee -a $LF
      if($status) exit 1;
      if(! $SaveRes) rm -r $resdir

    end # loop over anadir

  end # End Loop over session

endif

if($#flacfile == 0) then
  echo "Copying h.dat" | tee -a $LF
  # Just use the most recent one
  set sxadat = $anadir/h.dat
  set cmd = (cp $sxadat $analysis)
  echo $cmd
  $cmd |& tee -a $LF
endif

if($nprocs == 0) then
  echo "INFO: no data sets needed processing" | tee -a $LF
  exit 0;
endif

echo "Started at $StartTime" | tee -a $LF
echo "Ended   at `date`" | tee -a $LF

echo " " | tee -a $LF
echo "selxavg3-sess completed" | tee -a $LF
echo " " | tee -a $LF

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

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

    case "-hemi":
    case "-surf":
      if( $#argv < 1) goto arg1err;
      set geometry =  $1; shift;
      breaksw

    case "-subject":
      # For surfaced-based estimation of fwhm
      if( $#argv < 1) goto arg1err;
      set subject =  $1; shift;
      breaksw

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

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

    case "-contrasts-only":
    case "-co":
      set DoGLMFit = 0;
      set DoContrasts = 1;
      breaksw

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

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

    case "-svres":
      set SaveRes = 1;
      breaksw

    case "-no-fwhm":
      set DoFWHM = 0;
      breaksw

    case "-skip":
      set Skip = 1;
      breaksw

    case "-float":
      set UseFloat = 1;
      breaksw

    case "-double":
      set UseFloat = 0;
      breaksw

    case "-overwrite":
      set Overwrite = 1;
      breaksw

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

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

    case "-synth":
      set DoSynth = 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 && $flacfile == 0) then
    echo "ERROR: no analysis name or flac file specified"
    exit 1
  endif

  if($#analysis != 0) then 
    if(! -d $analysis ) then
      echo "ERROR: analysis $analysis does not exist, see mkanalysis-sess"
      exit 1;
    endif
  endif

  if($#flacfile != 0) then
    if(! -e $flacfile ) then
      echo "ERROR: flac file $flacfile does not exist"
      exit 1;
    endif
  endif

  if($perrun && $jkrun) then
    echo "ERROR: cannot -perrun AND -jkrun"
    exit 1
  endif

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

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: selxavg3-sess"
  echo ""
  echo "Required Arguments:";
  echo "   -analysis analysisname : name of functional analysis"
  echo ""
  echo "Optional Arguments:";
  echo ""
  echo "   -skip           : skip session of already analyzed"
  echo "   -overwrite      : delete analysis if session of already analyzed"
  echo "   -contrasts-only : only compute contrasts (estimation done) <-co>"
  echo "   -svres          : save residuals (usually not needed)"
  echo "   -hemi hemi      : assume raw data is on a the surface of the given hemi"
  echo "   -subject subject : override subject name"
  echo "   -perrun        : analyze each run separately"
  echo "   -jkrun         : jackknife runs"
  echo "   -no-fwhm       : do not compute FWHM"
  echo "   -float         : use single-precision float instead of double"
  echo ""
  echo "Session Arguments (Required)"
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo ""
  echo "Other args"
  echo "   -version       : print version and exit"
  echo "   -debug"
  echo "   -nolog         : do not create a log file"
  echo "   -log logfile   : specify log file explicitly"
  echo "   -outparent dir : save output to this dir instead of in session"
  echo ""
exit 1;
