#! /bin/csh -f

#
# mktemplate-sess
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: greve $
#    $Date: 2007/06/27 04:29:05 $
#    $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 VERSION = '$Id: mktemplate-sess,v 1.2 2007/06/27 04:29:05 greve Exp $';
set inputargs = ($argv);

set fsd          = bold;
set nolog        = 0;
set NthRun       = ();
set NthFrame     = ();
set DoMidFrame     = 0;
set PerRun       = 0;
set RunListFile  = ();
set funcstem     = f;
set tempstem     = template;
set UpdateOnly = 1;
set DoView = 0;
set DoConcat = 0;
set PrintHelp = 0;

## If there are no options, just print the usage ##
if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e  -version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;  
  goto usage_exit;
endif

goto parse_args;
parse_args_return:

set SessList = `getsesspath $inputargs`;
if($status || $#SessList == 0) then
  getsesspath $inputargs |& tee -a $LF
  echo "ERROR: cannot find any sessions" |& tee -a $LF
  exit 1;
endif

goto check_params;
check_params_return:

##### Create a log file ######
if(! $nolog) 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/mktemplate-sess.log
    if(-e $LF) mv $LF $LF.old
  endif
else
  set LF = /dev/null
endif

echo "--------------------------------------------------------------"
echo "mktemplate-sess logfile is $LF"
echo "--------------------------------------------------------------"

echo "mktemplate-sess log file" >> $LF
echo $VERSION >> $LF
uname -a >> $LF
date >> $LF
pwd >> $LF
echo UpdateOnly $UpdateOnly >> $LF 
echo $inputargs       >> $LF 
which mktemplate-sess >> $LF 

## Loop through each session ##
set concatlist = ();
foreach sess ($SessList)

  echo " " |& tee -a $LF
  echo "Session: $sess ----------------" |& tee -a $LF
  date  |& tee -a $LF

  ## Make sure the functional subdirectory exists ##
  if(! -e $sess/$fsd) then
    echo "ERROR: $sess/$fsd does not exist" |& tee -a $LF
    exit 1;
  endif

  if(! $PerRun) then  #----------------------------------------------
    # Make one template for all runs
    if($#NthRun == 0) then
      set funcdir = `getfirstrundir-sess $sess/$fsd`;
      if($status) then
        echo "$funcdir" |& tee -a $LF
        exit 1;
      endif
    else
      set funcdir = $sess/$fsd/$Run
      if(! -e $funcdir) then
        echo "ERROR: $Run does not exist in $sess/$fsd" |& tee -a $LF
        exit 1;
      endif
    endif

    set ext = `stem2fmt $funcdir/$funcstem`
    if($status) then
      echo "$ext" |& tee -a $LF
      exit 1;
    endif
    echo "Detected input format at $ext" |& tee -a $LF
    set srcvol = $funcdir/$funcstem.$ext
   
    set templatevol = $sess/$fsd/template.$FSF_OUTPUT_FORMAT;

    set UpdateNeeded = 1;
    if($UpdateOnly) then
      test $srcvol -nt $templatevol
      if($status) then
        pwd | tee -a $LF
        ls -lt $srcvol $templatevol | tee -a $LF
        echo "Update not needed" | tee -a $LF
        set UpdateNeeded = 0;
      endif
    endif

    if($UpdateNeeded) then
      set cmd = (mri_convert $srcvol $templatevol)
      if($DoMidFrame) set cmd = ($cmd --mid-frame);
      if($#NthFrame) set cmd = ($cmd --frame $NthFrame);
      pwd  |& tee -a $LF
      echo $cmd |& tee -a $LF
      $cmd  |& tee -a $LF
      if($status) exit 1;
    endif

    if($DoView)  tkmedit -f $templatevol

    if($DoConcat) set concatlist = ($concatlist $templatevol);

  else #-------------------------------------------------------
    # Do separately for each run
    set RunList = `getrunlist $sess/$fsd $RunListFile`;
    set st = $status;
    if($st) then
      echo "ERROR: getting run list"
      echo "  $RunList"
      exit 1;
    endif
   
    foreach Run ($RunList)
      echo "  Run: $Run ----------------" |& tee -a $LF
      date  |& tee -a $LF
      set funcdir = $sess/$fsd/$Run

      set ext = `stem2fmt $funcdir/$funcstem`
      if($status) then
        echo "$ext" |& tee -a $LF
        exit 1;
      endif
      echo "Detected input format at $ext" |& tee -a $LF
      set srcvol = $funcdir/$funcstem.$ext
      set templatevol = $funcdir/template.$FSF_OUTPUT_FORMAT;

      set UpdateNeeded = 1;
      if($UpdateOnly) then
        test $srcvol -nt $templatevol
        if($status) then
          pwd | tee -a $LF
          ls -lt $srcvol $templatevol | tee -a $LF
          echo "Update not needed" | tee -a $LF
          set UpdateNeeded = 0;
        endif
      endif

      if($UpdateNeeded) then
        set cmd = (mri_convert $srcvol $templatevol)
        if($DoMidFrame) set cmd = ($cmd --mid-frame);
        if($#NthFrame) set cmd = ($cmd --frame $NthFrame);
        pwd  |& tee -a $LF
        echo $cmd |& tee -a $LF
        $cmd  |& tee -a $LF
        if($status) exit 1;
      endif

      if($DoView)  tkmedit -f $templatevol
      if($DoConcat) set concatlist = ($concatlist $templatevol);
    end  # Loop over runs

  endif

end  # foreach sess ($SessList)

if($DoConcat) then
  set cmd = (mri_concat $concatlist --o $ConcatFile)
  pwd |& tee -a $LF
  echo $cmd |& tee -a $LF
  $cmd |& tee -a $LF
  if($status) exit 1;
endif

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

exit 0;

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

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

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

    case "-nthrun":
      # for cross-run template
      if ( $#argv == 0) goto arg1err;
      set NthRun = $argv[1]; shift;
      breaksw

    case "-perrun":
      set PerRun = 1;
      set DoMidFrame = 1;
      breaksw

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

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

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

    case "-mid-frame":
      set DoMidFrame = 1;
      breaksw

    case "-view":
      set DoView = 1;
      breaksw

    case "-concat":
      if ( $#argv < 1) goto arg1err;
      set ConcatFile = $argv[1]; shift
      set DoConcat = 1;
      breaksw

    case "-force":
      set UpdateOnly = 0;
      breaksw

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

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

    case "-debug":
      set verbose = 1;
      set echo = 1;
      breaksw

    case "-cwd":
      breaksw

    case "-s":
    case "-sf":
    case "-df":
    case "-d":
    case "-g":
      shift;
      breaksw

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

end

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

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

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

  if($#NthFrame && $DoMidFrame) then
    echo "ERROR: cannot -frame and -mid-frame"
    exit 1;
  endif
  if(! $#NthFrame && ! $DoMidFrame) set NthFrame = 0;

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

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

############--------------##################
usage_exit:
  echo "USAGE: mktemplate-sess"
  echo ""
  echo "  -nthrun nthrun   : 0-based run number (def 0)"
  echo "  -frame  nthframe : 0-based frame number (def 0)"
  echo "  -perrun : register each run separately (implies -mid-frame)"
  echo ""
  echo "  -fsd dir     : functional subdirectory ($fsd)"
  echo "  -rlf RLF       : run-list file (with -perrun)"
  echo "  -funcstem stem : default is f"
  echo ""
  echo "  -veiw : dont create template, just view it"
  echo "  -concat concatfile : concatenate all templates into one file"
  echo "  -force : force an update"
  echo ""
  echo "  -sf sessidfile  ..."
  echo "  -df srchdirfile ..."
  echo "  -s  sessid      ..."
  echo "  -d  srchdir     ..."
  echo "  -version       : print version and exit"
  echo ""
  if(! $PrintHelp ) exit 1;

  echo " "
  echo "$VERSION "
  echo " "

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

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

Make a template.
