#!/bin/csh -f
# paint-sess-old: version 1.8 of paint-sess. Uses the old paint command and
# the old vss functions.
#
set VERSION = '$Id$'
set FASTVER = `cat $FMRI_ANALYSIS_DIR/docs/version`;

set inputargs = "$argv";

set map        = sig;
set contrast   = ();
set offsetlist = ();
set allframes  = 1;
set analysis   = ();
set grpname    = ();
set space      = native;
set spacedir   = ();
set ScriptOnly = 0;
set umaskarg   = ();
set hemi       = ();
set subject    = ();
set surf       = ();
set SessList   = ();
set isxavgmethod = ();
set IsGroup = 0;
set getsubjfromreg = 0;
set dmax = 1;

if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

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

##### Create a log file ######
  set LF = /dev/null
if(0) then
set logdir = `pwd`/log;
mkdir -p $logdir
if(! -e $logdir) then
  echo "WARNING: could not create $logdir"
  set LF = /dev/null
else
  set LF = $logdir/paint-sess-old.log
  if(-e $LF) mv $LF $LF.old
endif
endif

echo "-----------------------------------------------------------------"
echo "paint-sess-old logfile is $LF"
echo "-----------------------------------------------------------------"

echo "paint-sess-old log file" >> $LF
echo $VERSION >> $LF
echo "FAST Version $FASTVER"  >> $LF
id            >> $LF
pwd           >> $LF
echo "$0"     >> $LF
echo "$inputargs"  >> $LF
uname -a      >> $LF
date          >> $LF
which paint   >> $LF

goto parse_args;
parse_args_return:

set SessList = `getsesspath $inputargs`;
if($status) then
  echo "$SessList" |& tee -a $LF
  exit 1;
endif

goto check_params;
check_params_return:

## 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}'`;

## Prepare the script, if need be ##
if($ScriptOnly) then
  mkdir -p scripts
  if(! -d scripts) then
    echo "ERROR ($sess): cannot create `pwd`/scripts"
    exit 1;
  endif

  if($IsSess) then
    set scriptfile = scripts/run-paint-$analysis-$contrast-sess
  else
    set scriptfile = scripts/run-paint-$analysis-$contrast-$grpname
  endif
  rm -f $scriptfile
  touch $scriptfile
  echo "#\!/bin/csh -f" >> $scriptfile
  echo "cd .." >> $scriptfile
  chmod a+x $scriptfile
endif

## Loop through each hemi (if needed) ##
foreach hs ($hemi)

  if($space == sph ) then 
     echo "------ $hs hemisphere ------" |& tee -a $LF
  endif

  date |& tee -a $LF

  ## Go through each session ##
  foreach sess ($SessList)
    set regfile = ();

    set mapdir = $sess/$fsd/$analysis/$spacesubdir/$contrast;
    if(! -e $mapdir) then
      echo "ERROR: $mapdir does not exist" |& tee -a $LF
      exit 1;
    endif
    set mapstem = $mapdir/$map

    if(! $IsGroup ) then
      set regfile = $sess/$fsd/register.dat;
      if($getsubjfromreg) set subject = `head -n 1 $regfile`;
    endif
    echo "INFO: Painting onto $subject" |& tee -a $LF

    if(! -e $SUBJECTS_DIR/$subject) then
      echo "ERROR: cannot find $subject in $SUBJECTS_DIR" |& tee -a $LF
      exit 1;
    endif

    if( $space == tal ) then
      set talres = `gettalres $mapstem`
      if($status) then
        echo "$talres" |& tee -a $LF
        exit 1;
      endif
      set talreg = $mapdir/talreg-$subject.dat
      mktalreg -subject $subject -reg $talreg -res $talres |& tee -a $LF
      if($status) exit 1;        
      set regfile = $talreg;
    endif

    if($space == sph ) then 
      set nframes = `getnframes $mapstem-$hs`;
    else  
      set nframes = `getnframes $mapstem`;
    endif
    if($allframes) then
      set offsetlist = ();
      @ n = 0;
      while($n < $nframes) 
        set offsetlist = ($offsetlist $n);
        @ n = $n + 1;
      end
    endif


    foreach offset ($offsetlist)
      if($IsGroup) then
        set outstem  = $mapdir/$map-$offset-$subject
      else
        set outstem  = $mapdir/$map-$offset
      endif

      if($space == native || $space == tal) then
        set surffile = $SUBJECTS_DIR/$subject/surf/$hs.$surf
        if(! -e $surffile) then
          echo "ERROR: subject $subject does not have a $surf surface"
          echo "       could not find $surffile"
          exit 1;
        endif

        if($offset > ($nframes - 1)) then
          echo "ERROR: Offset $offset too large, max =  $nframes -1"
          exit 1;
        endif

        set nslices = `getnslices $mapstem`;
        set cmd = "paint $mapstem"_%03d.bfloat" $hs $surf $outstem-$hs.w"
        set cmd = "$cmd  -imageoffset $offset -regdat $regfile -nslices $nslices"
        set cmd = "$cmd  -dmax $dmax -dstep .25"
      else if($space == sph) then
        set cmd = "mri-sph2surf -i $mapstem -o $outstem "
        set cmd = "$cmd -hemi $hs -s $subject -offset $offset "
      endif

      if($ScriptOnly) then
        echo $cmd >> $scriptfile
        echo " " >> $scriptfile
        echo " " >> $scriptfile
      else
        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: paint failed"
          exit 1;
        endif
      endif

    end # loop over offset list

  end # loop over SessList #

end # loop over hemispheres #

echo "----------------------------------------------------------"

date | tee -a $LF
echo " "
echo "paint-sess-old completed SUCCESSFULLY" | tee -a $LF
echo " "

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

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

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

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

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

    case "-spacedir":
      if ( $#argv == 0) goto arg1err;
      set spacedir = $argv[1]; shift;
      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 "-group":
      echo "ERROR: -group flag is no longer valid. Specify the group "
      echo "       using the  -s or -sf flag."
      exit 1;
      breaksw

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

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

    case "-dmax":
      if ( $#argv == 0) goto arg1err;
      set dmax = $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 "-old": # ignored
      breaksw

    case "-cwd":
      set IsSess = 1;  # otherwise, ignore getsesspath arguments 
      breaksw

    case "-s":
    case "-sf":
    case "-df":
    case "-d":
    case "-g":
      set IsSess = 1;  # otherwise, ignore getsesspath arguments 
      shift;
      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"|& tee -a $LF 
     exit 1
  endif

  if($#analysis == 0) then
     echo "ERROR: no analysis name specified"|& tee -a $LF 
     exit 1
  endif

  if($space != native && $space != tal && $space != sph) then
    echo "ERROR: no paint support for space $space"
    exit 1;
  endif

  if($#hemi == 0) 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( $#surf == 0 ) then
    set surf = white;
    echo "INFO: painting onto $surf" |& tee -a $LF 
  endif

  ## Determine whether Group or Individual Data ##
  @ nGroup = 0;
  foreach sess ($SessList)
    set sessinfo = $sess/session.info
    set IsGroup = `grep GroupAverage $sessinfo | wc -l`;
    if($IsGroup) @ nGroup = $nGroup + 1;
  end
  if($IsGroup && ($nGroup != $#SessList) ) then
    echo "ERROR: cannot mix individual and group sessions"
    exit 1;
  endif

  ## Individual Contingencies ##
  if(! $IsGroup) then
    if($space == native) then
      set spacesubdir = ();
    else
      set spacesubdir = $spacedir;
    endif
  endif

  if($#spacedir == 0) set spacedir = $space;

  ## Group Contingencies ##
  if($IsGroup) then
    if($#subject == 0) then
      echo "ERROR: $sess is a group average, need -subject"|& tee -a $LF 
      exit 1;
    endif
    if($#isxavgmethod == 0) then
      echo "ERROR: must supply -isxavg method with group data" |& tee -a $LF 
      exit 1;
    endif
    if($isxavgmethod != "fixed" && $isxavgmethod != "random") then
      echo "ERROR: -isxavg must be either fixed or random" |& tee -a $LF 
      exit 1;
    endif
    if($space == "native") then
      echo "ERROR: currently no support for painting group data in native space"\
           |& tee -a $LF 
      exit 1;
    endif
    if($isxavgmethod == "fixed") then
      set spacesubdir = $spacedir-ffx
    else
      set spacesubdir = $spacedir-rfx
    endif
  endif

  if($#subject == 0) set getsubjfromreg = 1;


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

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

############--------------##################
usage_exit:
  echo "USAGE: paint-sess-old"
  echo "Options:";
  echo "   -analysis analysisname : session-level functional analysis name"
  echo "   -contrast contrastname : contrast name"
  echo "   -map      mapname      : <sig>, minsig, iminsig, t"
  echo "   -offset   n            : 0-based image offset"
  echo "   -subject  subjectname  : name of subject on which to paint (with group data)"
  echo "   -space    spacename    : space from which to paint (native, tal, sph)"
  echo "   -isxavg   method       : fixed or random (with group data)"
  echo "   -hemi     hemisphere   : with sph space <lh rh>";
  echo "   -surf     surface      : surface on which to paint (white)"
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
#  echo "   -fsd dir       : functional subdirectory (bold)"
  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;
