#! /bin/csh -f

#
# ksgrinder - front end for KSS_grinder
#
# 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 os = `uname -s`;
if($os != "SunOS") then
  echo "ERROR: must be on SunOS"
  exit 1;
endif

set inputargs = ($argv);
set fmrianalver = `cat $FMRI_ANALYSIS_DIR/docs/version`;
set VERSION = '$Id: ksgrinder,v 1.2 2007/01/09 22:41:18 nicks Exp $'

## If there are no arguments, just print useage and exit ##
if ( $#argv == 0  )  goto usage_exit;

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

set PWDCMD = `getpwdcmd`;

# Set Default Values #
set thresh  = 0;
set smooth  = "-S";
set delay = 0;
set detrend = "-D";
set signedpvals = "-P";
set instem = ();
set parfile = ();
set ksparfile = ();
set poscondlist = ();
set negcondlist = ();
set outstem = ();
set firstslice = 0;
set nslices = -1;

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

set outdir = `dirname $outstem`;
mkdir -p $outdir;
pushd $outdir > /dev/null
set outdir = `$PWDCMD`;
popd > /dev/null

## Get path for log-file ##
set LF = $outstem"_ks.log"
echo "Logfile is $LF"
rm -f $LF;
touch $LF;
echo ------------------------------------------ >> $LF
echo "ksgrinder $VERSION" >> $LF
echo "Comments or questions: analysis-bugs@nmr.mgh.harvard.edu" >> $LF
uname -a >> $LF
hostname >> $LF
date >> $LF
pwd >> $LF
echo $0 >> $LF
echo $inputargs >> $LF
which KSS_grinder >> $LF

# Create parfile suitable for KSS_grinder
if($#ksparfile == 0) then
  set ksparfile = /tmp/ksgrinder_$$.para
  rm -f $ksparfile
  par2kspar -parfile $parfile -ksparfile $ksparfile \
            $poscondlist $negcondlist -delay $delay |& tee -a $LF
  if($status) exit 1;
  set rmksparfile = 1;
else
  set rmksparfile = 0;
endif

echo "---------------------------------------" >> $LF
echo "KS Parfile: $ksparfile" >> $LF
cat $ksparfile >> $LF
echo "---------------------------------------" >> $LF

set cmdargs = ( -N $thresh $smooth $detrend $signedpvals -p $ksparfile)

@ slice = $firstslice
@ lastslice = $firstslice + $nslices - 1;
date |& tee -a $LF
while($slice <= $lastslice)

  set infile = `printf "%s_%03d.%s" $instem $slice $bext`;
  if(! -e $infile) then
    echo "ERROR: cannot find $infile"
    exit 1;
  endif

  set outfile = `printf "%s_%03d.bfloat" $outstem $slice`;

  set cmd = (KSS_grinder $cmdargs -i $infile -o $outfile)
  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: KSS_grinder exited with non-zero status" |& tee -a $LF
    exit 1;
  endif

  # Check that the output file exists #
  if(! -e $outfile) then
    echo "ERROR: cannot find output file $outfile" |& tee -a $LF
    exit 1;
  endif

  @ slice = $slice + 1;

end

# Only keep the 3rd frame and convert from ln to log10 #
if($nslices == $nslicesvol) then
  echo "INFO: extracting the 3rd frame" |& tee -a $LF
  bfileconvert -i $outstem -o $outstem -fp 2 -np 1 -ln2log10 |& tee -a $LF
  if($status) then
    echo "WARNING: 3rd frame was not extracted" |& tee -a $LF
    echo "WARING: significances are still in natural log" |& tee -a $LF
    exit 1;
  endif
else
  echo "WARING: 3rd frame was not extracted" |& tee -a $LF
  echo "WARING: significances are still in natural log" |& tee -a $LF
endif

if($rmksparfile) rm -f $ksparfile 

echo "ksgrinder completed SUCCESSFULLY " |& tee -a $LF
echo " " |& tee -a $LF
date |& tee -a $LF


exit 0

############################################################

############--------------##################
parse_args:

set cmdline = ($argv);
while( $#argv != 0 )

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

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

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

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

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

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

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

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

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

    case "-detrend":
      set detrend = "-D"; 
      breaksw

    case "-nodetrend":
      set detrend = ""
      breaksw

    case "-smooth":
      set smooth = "-S";
      breaksw

    case "-nosmooth":
      set smooth = ""; 
      breaksw

    case "-debug":
      set verbose = 1; 
      set echo = 1;
      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 ($#instem == 0) then
     echo "ERROR: must specify an input stem";
     exit 1
  endif

  bfvcheck $instem;
  if($status) exit 1;

  set tmp = `getbfvdim $instem`;
  set nslicesvol = $tmp[1];
  if($nslices < 0) set nslices = $nslicesvol;
  set bext = $tmp[5];

  if ($#outstem == 0) then
     echo "ERROR: must specify output stem";
     exit 1
  endif

  if($#parfile == 0 ) then
    echo "ERROR: must specify a paradigm file"
    exit 1;
  endif
  if(! -e $parfile ) then
    echo "ERROR: cannot find $parfile"
    exit 1;
  endif

  if($#ksparfile && ($#poscondlist || $#negcondlist)) then
    echo "ERROR: cannot specify a contrast and a ksparfile"
    exit 1;
  endif

  if($#ksparfile == 0) then
    if($#poscondlist == 0) then
      echo "ERROR: must specify a positive condition list"
      exit 1;
    endif
    if($#negcondlist == 0) then
      echo "ERROR: must specify a negative condition list"
      exit 1;
    endif
  endif


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


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

############--------------##################
parse_cfg:
  @ n = 1;
  while($n < $#argv)
    if("$argv[$n]" == "-cfg") then
      @ m = $n + 1;
      set cfgfile = $argv[$m];
      if(! -e $cfgfile ) then
        echo "ERROR: $cfgfile does not exist"
        exit 1;
      endif
    endif
    @ n = $n + 1;
  end

  if($#cfgfile == 0) then
    echo "ERROR: must specify config file with -cfg flag";
    exit 1;
  endif

  echo "--- Parsing Config File: $cfgfile ----"
  set cfgargs = `cat $cfgfile`;
  echo $cfgargs
  set argv = ($cfgargs $argv);

goto parse_cfg_return;
#--------------------------------------------------------------------#

#--------------------------------------------------------------------#
usage_exit:
  echo "USAGE: ksgrinder [options]"
  echo "  -i inputstem "
  echo "  -o outputstem "
  echo "  -parfile paradigm file"
  echo "  -p positive-condition"
  echo "  <-p positive-condition>"
  echo "  -n negative-condition"
  echo "  <-n negative-condition>"
  echo "  -thresh threshold value (default: 0)"
  echo "  -smooth/-nosmooth (flag) turn on/off smoothing (default: on)"
  echo "  -detrend/-nodentrend (flag) turn on/off detrending (default: on)"
  echo "  -delay hemodynamic delay (in TRs)"
exit 1;
#--------------------------------------------------------------------#
