#! /bin/csh -f

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

set cmdargs = ($argv);

set funcstem  = f; 
set fsd       = "bold";
set RunListFile = ();
set PrintHelp = 0;
set fftflag   = 0;
set maskthresh = 0;
set sumsuffix = ();
set SessSumFile = ();
set SessSumOnly = 0;
set tpexcfile = ();
set spikethresh = 25;
set monly = 0;
set MLF = ();

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;
  exit 1;
endif

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:

if(! $fftflag) then
  if($#sumsuffix) then
    set LF = log/spikedet-sess-$funcstem.$sumsuffix.log
  else
    set LF = log/spikedet-sess-$funcstem.log
  endif
else
  set LF = log/spikedet-sess-$funcstem-fft.log
endif
if(-e $LF) mv $LF $LF.bak

date | tee -a $LF
pwd  | tee -a $LF
echo $0  | tee -a $LF
echo $cmdargs | tee -a $LF
echo $VERSION | tee -a $LF
hostname  | tee -a $LF

#------------------------------------------------------------------#
if($#SessSumFile) then
  if(-e $SessSumFile) mv $SessSumFile $SessSumFile.bak
endif
set StartTime = `date`;
foreach sess ($SessList)
  set sessid = `basename $sess`;

  echo "------------------------------------------------" | tee -a $LF
  echo $sess | tee -a $LF
  date | tee -a $LF

  ### Check that the target directory is there ###
  if(! -d $sess/$fsd) then
    echo "ERROR: $sess/$fsd does not exist"   | tee -a $LF
    exit 1;
  endif

  ### Check that the target directory is writable ###
  if(! -w $sess/$fsd) then
    echo "ERROR: $sess/$fsd is not writable"   | tee -a $LF
    exit 1;
  endif

  if($#RunListFile == 0) then
    set RunList = `getrunlist $sess/$fsd`;
    if($status || $#RunList == 0) then
      echo "ERROR: $sess/$fsd has no runs"  | tee -a $LF
      exit 1;
    endif
  else  
    if(! -e $sess/$fsd/$RunListFile) then
      echo "ERROR: cannot find $RunListFile"| tee -a $LF
      exit 1;
    endif
    set RunList = (`cat $sess/$fsd/$RunListFile`);
  endif
  echo "RunList $RunList" | tee -a $LF


  ## Go through each run ##
  foreach run ($RunList)

    # Generate the run-by-run summary file
    if(! $SessSumOnly) then
      # Construct and run the command for this run #
      set cmd = (spikedet --i $sess/$fsd/$run/$funcstem --thresh $spikethresh)
      if($fftflag) set cmd = ($cmd --fft)
      if("$maskthresh" != "0") set cmd = ($cmd --mask $maskthresh)
      if($#sumsuffix) set cmd = ($cmd --suffix $sumsuffix)
      if($monly) set cmd = ($cmd --monly $MLF)
      if($#tpexcfile) set cmd = ($cmd --tpexc $sess/$fsd/$run/$tpexcfile)
      pwd | tee -a $LF
      echo $cmd | tee -a $LF
      $cmd | tee -a $LF
      if($status) then
        echo "ERROR: spikedet failed" | tee -a $LF
        exit 1
      endif
      if($monly) exit 1;
    endif

    if($#SessSumFile) then
      if(! $#sumsuffix) then
        set runsum = $sess/$fsd/$run/$funcstem.spike.sum
      else
        set runsum = $sess/$fsd/$run/$funcstem.$sumsuffix.sum
      endif
      if(! -e $runsum) then
        echo "ERROR: cannot find $runsum" | tee -a $LF
        exit 1;
      endif
      set jkzmax  = `cat $runsum | grep jkzmax  | awk '{print $2}'`;
      set nspikes = `cat $runsum | grep nspikes | awk '{print $2}'`;
      echo "$sessid $run $jkzmax $nspikes" >> $SessSumFile
      if($nspikes > 0) then
        echo "#  Slice   TP     JKZ" >> $SessSumFile
        grep \# $runsum >> $SessSumFile
      endif
    endif

  end # Loop over runs

end # Loop over sessions #

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

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


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

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

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

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

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

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

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

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

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

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

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

    case "-sesssumonly":
      set SessSumOnly = 1;
      breaksw

    case "-fft":
      set fftflag = 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;
      setenv MRI_UMASK $1; shift;
      breaksw

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

end

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

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

if($SessSumOnly == 1 && ! $#SessSumFile) then
  echo "ERROR: need SessSum File with -sesssumonly"
  exit 1;
endif

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

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: spikedet-sess"
  echo ""
  echo "Opttional Arguments"
  echo "   -f funcstem      : input  functional volume stem <f>"
  echo "   -thresh thresh   : spike threshold (default is 25)"
  echo "   -fsd fsd         : functional subdir <bold> "
  echo "   -rlf runlistfile : run list file "
  echo "   -fft             : perform 2D FFT prior to spike detection"
  echo "   -mask maskthresh : mask OUT regions over thresh"
  echo "   -suffix suffix   : summary will be funcstem.suffix.sum"
  echo "   -sesssum fname   : summarize all data in file fname"
  echo "   -sesssumonly     : only create summary from already-proc data"
  echo "   -tpexc tpexcfile : not for use with FS-FAST yet"
  echo ""
  echo "Session Arguments (Required)"
  echo "   -sf sessidfile  "
  echo "   -df srchdirfile "
  echo "   -s  sessid      "
  echo "   -d  srchdir     "
  echo "   -fsd fsdir      (optional)"
  echo ""
  echo "Other Arguments"
  echo "   -umask umask    : set unix file permission mask"
  echo "   -version        : print version and exit"
  echo "   -help           : print help and exit"
  echo ""

  if(! $PrintHelp) exit 1;

  echo $VERSION

  echo "------------------------------------------------------------"
  cat $0 | awk 'BEGIN{prt=0}{if(prt) print $0; if($1 == "BEGINHELP") prt = 1 }'

  echo "------------------------------------------------------------"
  spikedet --help

exit 1;

#---- Everything below here is printed out as part of help -----#
BEGINHELP

fMRI Spike detection. This is a front end for spikedet, whose help is 
printed below.


