#!/bin/csh -f
# condfit-sess - random effects intersubject averaging condition fitting
#
set VERSION = '$Id'
set cmdargs = "$argv";

set contrast   = ();
set analysis   = ();
set grpname    = ();
set space      = ();
set ScriptOnly = 0;
set umaskarg = ();
set hemi = ();
set nolog = 0;
set condfitargs = ();

## Print usage if no args ##
if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

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

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

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

## Look for nolog option ##
set n = `echo $argv | grep nolog | wc -l` 
if($n != 0) then
  set nolog = 1;
endif

##### Create a log file ######
if(! $nolog) then
  set logdir = `pwd`/log;
  mkdir -p $logdir
  if(! -e $logdir) then
    echo "ERROR: could not create $logdir"
    exit 1;
  endif
  set LF = $logdir/condfit-sess-$analysis-$contrast.log
  if(-w $LF) then
    mv -f $LF $LF.old 
  else
    set LF = /dev/null
  endif
else
  set LF = /dev/null
endif

echo "Log file is $LF"
touch $LF

echo "condfit-sess log file" >> $LF
echo $VERSION   >> $LF
id              >> $LF
uname -a        >> $LF
date            >> $LF
pwd             >> $LF
echo '$0'       >> $LF
echo "$cmdargs" >> $LF
which condfit >> $LF
#df -k . >> $LF

## Get functional subdirectory from the info file ##
set infofile = $analysis/analysis.info
if(! -e $infofile) then
  echo "ERROR: cannot find $infofile" |& tee -a $LF
  exit 1;
endif
set fsd = `cat $infofile | awk '{if($1 == "fsd") print $2}'`;

echo "------ infofile: $infofile ---------" >> $LF
cat $infofile >> $LF
echo "-----------------------------------------" >>$LF

mkdir -p scripts
set scriptfile = scripts/run-condfit-$analysis-$contrast
rm -f $scriptfile
touch $scriptfile
echo "#\!/bin/csh -f" >> $scriptfile
echo "cd .." >> $scriptfile
chmod a+x $scriptfile

foreach hs ($hemi)

  if($space == sph) echo "hemisphere: $hs " |& tee -a $LF
  date |& tee -a $LF
  set instems = ();
  set inhoffstems = ();
  foreach sess ($SessList)

    # Make sure the Session Dir exists (redundant) ##
    if(! -d $sess/$fsd) then
      echo "ERROR: $sess/$fsd does not exist"   |& tee -a $LF
      exit 1;
    endif
    if(! -d $sess/$fsd/$analysis) then
      echo "ERROR: $sess/$fsd/$analysis does not exist"   |& tee -a $LF
      exit 1;
    endif
    if(! -d $sess/$fsd/$analysis/$space) then
      echo "ERROR: $sess/$fsd/$analysis/$space does not exist"   |& tee -a $LF
      exit 1;
    endif
  
    if($space != sph) then
      set instem = $sess/$fsd/$analysis/$space/h
      set inhoffstem = $sess/$fsd/$analysis/$space/h-offset
      set inregfile = $sess/$fsd/$analysis/$space/register.dat;
      if(! -e $inregfile ) then
        echo "ERROR: $inregfile does not exist"|& tee -a $LF
        exit 1;
      endif
    else
      set instem = $sess/$fsd/$analysis/$space/h-$hs
      set inhoffstem = $sess/$fsd/$analysis/$space/h-$hs-offset
    endif

    set instems     = ($instems     -i $instem);
    set inhoffstems = ($inhoffstems -i $inhoffstem);

  end # loop over SessList #
  
  set outdir      = $grpname/$fsd/$analysis/$space-rfx/$contrast
  set outhoffstem = $grpname/$fsd/$analysis/$space-rfx/h-offset
  set coeffstem   = $outdir/coeff
  set eresstdstem = $outdir/eresstd
  set tstem       = $outdir/t
  set sigstem     = $outdir/sig
  set minsigstem  = $outdir/minsig
  set iminsigstem = $outdir/iminsig
  if($space == sph) then
    set coeffstem   = $coeffstem-$hs
    set eresstdstem = $eresstdstem-$hs
    set tstem       = $tstem-$hs
    set sigstem     = $sigstem-$hs
    set minsigstem  = $minsigstem-$hs
    set iminsigstem = $iminsigstem-$hs
    set outhoffstem = $grpname/$fsd/$analysis/$space-rfx/h-$hs-offset
  endif
  
  if($space == tal) then
    set outregfile = $grpname/$fsd/$analysis/$space-rfx/register.dat
    set cpregcmd = "cp $inregfile $outregfile"
  else
    set cpregcmd = ();
  endif

  ## Build the condfit command-line #
  set cmd = (condfit $condfitargs $instems -sig $sigstem)
  set cmd = ($cmd -coeff $coeffstem -eresstd $eresstdstem)
  #set cmd = "$cmd  -minsig $minsigstem -iminsig $iminsigstem"

  ## Build the meanimg command-line #
  set cmd2 = "meanimg $inhoffstems -o $outhoffstem"

  echo "---------------------------------------------------" | tee -a $LF
  pwd  | tee -a $LF
  echo $cmd | tee -a $LF
  echo "---------------------------------------------------" | tee -a $LF
  echo $cmd >> $scriptfile
  echo "\n\n" >> $scriptfile
  echo 'if($status) exit 1' >> $scriptfile
  echo "" >> $scriptfile
  echo $cpregcmd >> $scriptfile
  echo 'if($status) exit 1' >> $scriptfile
  echo $cmd2 >> $scriptfile
  echo "\n\n" >> $scriptfile
  echo 'if($status) exit 1' >> $scriptfile
  echo "\n\n" >> $scriptfile

end

echo "exit 0" >> $scriptfile
echo "------ scriptfile ----------" >> $LF
cat $scriptfile >> $LF
echo "----------------------------" >> $LF
if(! $ScriptOnly) then
  echo "Running $scriptfile"
  pushd scripts > /dev/null
  set scriptname = `basename $scriptfile`;
  ./$scriptname |& tee -a $LF
  if($status) then
    echo "ERROR: error running $scriptfile" |& tee -a $LF
    exit 1;
  endif
  popd > /dev/null
endif

date | tee -a $LF
echo "condfit-sess completed SUCCESSUFULLY" |& tee -a $LF


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

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

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

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

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

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

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

    case "-grpname":
    case "-group":
      if ( $#argv == 0) goto arg1err;
      set grpname = $argv[1]; shift;
      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 "-g":
    case "-s":
    case "-sf":
    case "-df":
    case "-d":
      # ignore getsesspath arguments 
      shift;
      breaksw

    default:
      set condfitargs = ($condfitargs $flag);
      breaksw
  endsw

end

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

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

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

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

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

  set cmtx = $analysis/$contrast.mat
  if(-e $cmtx) then
    echo "ERROR: you already have a contrast called $contrast"
    exit 1;
  endif

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

  if ($#space == 0) then
     echo "ERROR: must specify a sampling space"
     exit 1
  endif
  if($space != "tal" && $space != "sph") then
     echo "ERROR: no support for resampling into $space space"
     exit 1
  endif

  if($#hemi != 0 && $space != sph) then
    echo "ERROR: -hemi can only be used with sph space"
    exit 1;
  endif
  if($#hemi == 0 && $space == sph) set hemi = (lh rh);
  foreach hs ($hemi)
    if($hs != lh && $hs != rh) then
      echo "ERROR: hemi must be either lh or rh ($hs)";
      exit 1;
    endif
  end

  if($space != sph) set hemi = nohemi;

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

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

############--------------##################
usage_exit:
  echo "USAGE: condfit-sess"
  echo "Options:";
  echo "   -analysis analysisname : session-level functional analysis name"
  echo "   -contrast contrastname : contrast name"
  echo "   -group    groupname    : name of group"
  echo "   -space    spacename    : space in which to average (native, tal, sph)"
  echo "   -hemi     hemisphere   : with sph space <lh rh>";
  echo "   -wcond    weightlist   : list of weights for conditions"
  echo "   -exclcond list         : list of conditions toexclude"
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo "   -scriptonly    : don't run, just generate a script"
  echo "   -version       : print version and exit"
exit 1;


if(0) then
    case "-wcond":
      if( $#argv == 0) goto arg1err;
      set wcond = ();
      while($#argv != 0 && ! `isargflag $argv[1]`)
        set wcond = ($wcond $argv[1]); shift;
      end
      set condfitbaseargs = ($condfitbaseargs -wcond $wcond);
      breaksw

    case "-exclcond":
      if( $#argv == 0) goto arg1err;
      set exclcond = ();
      while($#argv != 0 && ! `isargflag $argv[1]`)
        set exclcond = ($exclcond $argv[1]); shift;
      end
      set condfitbaseargs = ($condfitbaseargs -exclcond $exclcond);
      breaksw

    case "-synth":
      set synthflag = "-synth"
      set condfitbaseargs = ($condfitbaseargs -synth -1);
      breaksw

    case "-pctsigch":
      set pctsigch = 1;
      set condfitbaseargs = ($condfitbaseargs -pctsigch);
      breaksw

    case "-zprestim":
      set zprestim = 1;
      set condfitbaseargs = ($condfitbaseargs -zprestim);
      breaksw
end

