#!/bin/csh -f
# stxgrinder-sess
#
set VERSION = '$Id: mkcontrast-sess,v 1.1 2003/03/04 21:22:09 greve Exp $'
set cmdargs = ($argv);

set contrast   = ();
set analname   = ();
set ScriptOnly = 0;
set fsd        = "bold";
set umaskarg = ();
set actcond = ();
set ctrlcond = ();
set ncond = ();
set wcond = ();
set setwdelay = 0;
set sumdelays = ();
set showcmtx = ();
set nircorr = 0;
set deltarange = ();
set taurange   = (1.25 1.25);
set sumconds = (-sumconds);
set rmprestim = ();

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

# Create a log file #
if(-w .) then
  set logdir = `pwd`/log;
  mkdir -p $logdir
  set LF = $logdir/mkcontrast-sess.log
  rm -f $LF
else
  set LF = /dev/null
endif

echo "mkcontrast-sess log file" >> $LF
echo $VERSION >> $LF
echo '$0'     >> $LF
uname -a      >> $LF
date          >> $LF
echo "$argv"  >> $LF
which mkcontrast >> $LF

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

## Get the number of conditions ##
set tmp = `grep nCond $datfile`;
@ Nc = $tmp[2] - 1;
echo "INFO: Found $Nc Non-Null Conditions"

if($#ncond != 0) then
  if($ncond != $Nc) then
    echo "ERROR: number of conditions specfied with -ncond ($ncond) does not"
         "       match number in analysis ($Nc)"
    exit 1;
  endif
endif


## Get the number of delays (ie, estimates) ##
set tmp = `grep Nh $datfile`;
@ Nh = $tmp[2];
echo "INFO: Found $Nh Delays"

## Check that the conditions are within range ##
foreach c ($actcond $ctrlcond)
  if($c > $Nc || $c < 0) then
    echo "ERROR: Condition ID $c out of range (0:$Nc)"
    exit 1;
  endif
end

## Set the weight of the active and control conditions ##
set wact  = `echo 1/$#actcond  | bc -l`;
set wctrl = `echo -1/$#ctrlcond | bc -l`;

if($#wcond == 0) then
  ## Preset the condition weights to zero ##
  @ c = 1;
  while($c <= $Nc)
    set wcond = ($wcond 0);
    @ c = $c + 1;
  end

  ## Set the active condition weights ##
  foreach c ($actcond)
    if($c != 0) set wcond[$c] = $wact;
  end
  ## Set the control condition weights ##
  foreach c ($ctrlcond)
    if($c != 0) set wcond[$c] = $wctrl;
  end
endif

echo "Condition Weights: $wcond" | tee -a $LF

## Set the delay weights ###
if($nircorr == 0) then
  if($setwdelay == 0) then
    set wdelay = ();
    @ d = 1;
    while($d <= $Nh)
      set wdelay = ($wdelay 1);
      @ d = $d + 1;
    end
  else 
    echo "###################################"
    echo "### Enter $Nh Delay Weights (Return)"
    set wdelay = ($<)
    if($#wdelay != $Nh) then
      echo "ERROR: entered $#wdelay weights, needed $Nh"
      exit 1;
    endif
  endif
endif

set cmtxfile = $analname/$contrast

set cmd = (mkcontrast -sxadat $datfile -wcond $wcond $sumconds -o $cmtxfile)
set cmd = ($cmd  $sumdelays $showcmtx $rmprestim)
if($nircorr != 0) then
  set cmd = ($cmd -ircorr $nircorr -deltarange $deltarange -taurange $taurange)
else
  set cmd = ($cmd -wdelay $wdelay )
endif

## Prepare the script, if need be ##
if($ScriptOnly) then
  mkdir -p $analname/scripts
  set scriptfile = $analname/scripts/run-mkcontrast-$analname-$contrast
  rm -f $scriptfile
  touch $scriptfile
  echo "#\!/bin/csh -f" >> $scriptfile
  echo "cd `pwd`" >> $scriptfile
  echo $cmd >> $scriptfile
  echo " " >> $scriptfile
  echo " " >> $scriptfile
  chmod a+x $scriptfile
else
  echo $cmd
  $cmd
  if($status) then
    echo "ERROR running mkcontrast"
    echo "$cmd"
  endif
endif



date | tee -a $LF

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

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

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

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

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

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

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

    case "-wcond":
      if($#ncond == 0) then
        echo "ERROR: must specify -ncond before -wcond"
        exit 1;
      endif
      if( $#argv < $ncond) then
        echo "ERROR: need $ncond arguments for -wcond"
        exit 1;
      endif
      set wcond = ($argv[1-$ncond]); 
      foreach tmp ($wcond)
        shift;
      end
      breaksw

    case "-nosumconds":
      set sumconds = ();
      breaksw

    case "-sumdelays":
      set sumdelays = "-sumdelays";
      breaksw

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

    case "-deltarange":
    case "-dr":
      if( $#argv == < 2) then
        echo "ERROR: -deltarange option requires 2 arguments"
        exit 1;
      endif
      set deltarange = ($argv[1] $argv[2]); shift;shift;
      breaksw

    case "-taurange":
    case "-tr":
      if( $#argv == < 2) then
        echo "ERROR: -taurange option requires 2 arguments"
        exit 1;
      endif
      set taurange = ($argv[1] $argv[2]); shift;shift;
      breaksw


    case "-rmprestim":
      set rmprestim = "-rmprestim";
      breaksw

    case "-showcmtx":
      set showcmtx = "-showcmtx";
      breaksw

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

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

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

    case "--version":
    case "-version":
      echo $VERSION
      exit 0;
      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 "-scriptonly":
      set ScriptOnly = 1;
      breaksw

    case "-s":
    case "-sf":
    case "-df":
    case "-d":
    case "-g":
      # ignore getsesspath arguments 
      shift;
      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 ($#contrast == 0) then
     echo "ERROR: no contrast specified"
     exit 1
  endif

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

  if(! -d $analname ) then
    echo "ERROR: analysis $analname does not exist"
    exit 1;
  endif

  set datfile = $analname/h.dat
  if(! -e $datfile) then
    echo "ERROR: cannot find $datfile"
    exit 1;
  endif

  if($#wcond == 0) then
    if($#actcond == 0) then
      echo "ERROR: no active conditions or wcond specified"
      exit 1;
    endif
    if($#ctrlcond == 0) then
      echo "ERROR: no control conditions or wcond specified"
      exit 1;
    endif
  else
    if($#actcond != 0 || $#ctrlcond != 0) then
      echo "ERROR: cannot specify -wcond with -a or -c"
      exit 1;
    endif
  endif

  if($nircorr != 0 && $setwdelay) then
    echo "ERROR: cannot use -ircorr and -setwdelay at the same time";
    exit 1;
  endif

  if($nircorr != 0 && $#deltarange != 2) then
    echo "ERROR: must set delayrange with -ircorr"
    exit 1;
  endif

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

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

############--------------##################
usage_exit:
  echo "USAGE: mkcontrast-sess"
  echo "Options:";
  echo "   -contrast contrastname : contrast name"
  echo "   -analysis analysisname : name of session-level functional analysis";
  echo "   -a a1 <-a a2> ... : positive contrast conditions"
  echo "   -c c1 <-c c2> ... : negative contrast conditions"
  echo "   -setwdelay        : prompt for setting of delay weights "
  echo "   -sumdelays        : sum weighted delays"
  echo "   -rmprestim        : subtract prestimulus baseline"
  echo "   -nosumconds       : don't sum conditions (for f-test)"
  echo "   -ircorr nircorr   : correlate with gamma function"
  echo "   -deltarange dmin dmax : range of delta for gamma function"
  echo "   -taurange   tmin tmax : range of tau for gamma function"
  echo "   -umask umask      : set unix file permission mask"
  echo "   -scriptonly       : don't run, just generate a script"
  echo "   -version          : print version and exit"
exit 1;
