#!/bin/csh -f
# tkregister-sess
#
set VERSION = '$Id: tkregister-sess,v 1.7 2003/12/09 20:17:24 greve Exp $';
set inputargs = ($argv);
set DateString = "`date '+%y%m%d%H%M'`"

set umaskarg     = ();
set rsd          = ();
set fsd          = bold;
set asd          = 3danat;
set samesessanat = 0;
set nocopy       = 0;
set nolog        = 0;
set anatvol      = T1;
set UseNew       = 1;
set Surf         = white;
set Run          = ();
set Plane        = "cor";
set Slice        = ();
set Inorm        = 0;
set VolView      = targ;
set regfilename  = register.dat
set funcstem     = f;

## If there are no options, just print the usage ##
if($#argv == 0) then
  goto usage_exit;
  exit 1;
endif

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

## 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 "WARNING: could not create $logdir"
    set LF = /dev/null
  else
    set LF = $logdir/tkregister-sess.log
    if(-e $LF) mv $LF $LF.old
  endif
else
  set LF = /dev/null
endif

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

echo "tkregister-sess log file" >> $LF
echo $VERSION  >> $LF
echo "" >> $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR " >> $LF
pwd  >> $LF
echo "$0 $inputargs" >> $LF
echo "" >> $LF
hostname  >> $LF
which tkregister >> $LF

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:

## Loop through each session ##
foreach sess ($SessList)

  echo " " |& tee -a $LF
  echo "Session: $sess ----------------" |& tee -a $LF
  date  |& tee -a $LF
  pushd $sess > /dev/null
  set sessid = `basename $sess`;

  ## Get the anatomical directory ##
  if($samesessanat) then
    ## Anatomical directory is in the session ##
    set anatdir = `getfirstrundir-sess $asd`;
  else
    ## Anatomical directory is in the database ##
    if(! -e subjectname) then
      echo "ERROR: file 'subjectname' does not exist in $sess"
      exit 1;
    endif
    set subject = `cat subjectname`;
    if(! -e $SUBJECTS_DIR/$subject) then
      echo "ERROR: $subject is not in SUBJECTS_DIR"
      echo "  SUBJECTS_DIR is $SUBJECTS_DIR"
      exit 1;
    endif
    set anatdir = $SUBJECTS_DIR/$subject/mri/$anatvol;
  endif

  echo "INFO: anatdir set to $anatdir"
  if(! -e $anatdir ) then
    echo "ERROR: $anatdir does not exist"
    exit 1;
  endif

  ## Get absolute path for anatdir ##
  pushd $anatdir > /dev/null
  set anatdir = `pwd`;
  popd > /dev/null

  ## Make sure the functional subdirectory exists ##
  if($rsd != $fsd && ! $nocopy) then
    if(! -e $fsd) then
      echo "ERROR: $fsd does not exist"
      exit 1;
    endif
  endif

  ## Get the directory of the functional registration data ##
  if(! -e $rsd ) then
    echo "ERROR: $rsd does not exist"
    exit 1;
  endif
  if($#Run == 0) then
    set funcdir = `getfirstrundir-sess $rsd`;
    set Run = `basename $funcdir`;
  else
    set funcdir = $rsd/$Run
    if(! -e $funcdir) then
      echo "ERROR: $Run does not exist in $rsd"
      exit 1;
    endif
  endif

  cd $funcdir
  ## Make sure there is not a register.dat in the data dir ##
  if(-e $regfilename ) then
    echo "INFO: found $regfilename in `pwd` ..."
    echo "      ... moving to $regfilename.orig"
    mv $regfilename $regfilename.orig
  endif

  set regfile = ../$regfilename

  if($UseNew) then
    if(! -e $regfile ) then
      echo ""
      echo "INFO: no registration found, using default"
      echo ""
      sleep 2
      set mkregopt = (--regheader)
      if(! $samesessanat) set mkregopt = ($mkregopt --subject $subject)
    else
      set mkregopt = ();
    endif
    set movstem = ./$funcstem;
    if(! -e $movstem"_000.hdr") then
      echo "ERROR: cannot find $movstem'_000.hdr'" |& tee -a $LF
      pwd |& tee -a $LF
      exit 1;
    endif
    set movext = `getbext $movstem`;
    #set TKR2 = ~/sg1/build/tkregister2/tkregister2
    set TKR2 = tkregister2
    set cmd = ($TKR2 --targ $anatdir --mov $movstem $movext)
    set cmd = ($cmd $mkregopt --reg $regfile --plane $Plane)
    set cmd = ($cmd --title $subject--$sessid--$Run)
    set cmd = ($cmd --volview $VolView)
    if($#Slice) set cmd = ($cmd --slice $Slice)
    if($Inorm)  set cmd = ($cmd --inorm)
    if($#Surf != 0) then
      set lhsurfpath = $SUBJECTS_DIR/$subject/surf/lh.$Surf;
      set rhsurfpath = $SUBJECTS_DIR/$subject/surf/rh.$Surf;
      if(! -e $lhsurfpath || ! -e $rhsurfpath ) then
        echo ""
        echo "----------------------------------------------------"
        echo "INFO: surface $Surf does not exist for $subject, so it will"
        echo "not be loaded into the display. This may be because"
        echo "the subject's anatomical data has not been processed"
        echo "with FreeSurfer in order to reconstruct the surface."
        echo "You can change the surface from $Surf with the -surf"
        echo "option (followed by the name of the surface."
        echo "Continuing..."
        echo "----------------------------------------------------"
        echo ""
      else
       set cmd = ($cmd --surf $Surf);
      endif
    endif
    echo "________________________________________________" |& tee -a $LF
    pwd  |& tee -a $LF
    echo $cmd |& tee -a $LF
    echo "________________________________________________" |& tee -a $LF

    ## Run tkregister2 ##
    $cmd |& tee -a $LF
    if($status) then
      echo "ERROR: tkregister2 failed"
      exit 1;
    endif
  else
    # Use the old tkregister #
    ## Get the registration file ##
    ##   First, look for $regfile, 
    ##     Then, look for same-session-reg.dat,
    ##       Then, create a default
    if(! -e $regfile ) then
      set regfile = ../same-session-reg.dat
      if( -e $regfile ) then
        echo "INFO: using same-session-reg.dat"
        cp $regfile ../$regfile
        set regfile = ../$regfile
      else
        echo ""
        echo "INFO: no registration found, using default"
        echo ""
        sleep 1
        set regfile = ();
      endif
    else
      echo "INFO: using ../$regfile"
    endif

    ## Create the register file option for tkregister ##
    if($#regfile != 0) then
      set regoption = "-regdat $regfile"
      cp $regfile $regfile.$DateString
    else
      set regoption = "-mkdefault"
    endif

    ## Construct the command-line ##
    echo "________________________________________________" |& tee -a $LF
    set tkregister = tkregister
    set cmd = "$tkregister local $anatdir $regoption" 
    pwd  |& tee -a $LF
    echo $cmd |& tee -a $LF
    echo "________________________________________________" |& tee -a $LF

    ## Run tkregister ##
    $cmd |& tee -a $LF
    if($status) then
      echo "ERROR: tkregister failed"
      exit 1;
    endif

    if($#regfile == 0) then
      mv $regfile ..
      set regfile = ../$regfile
    endif
  endif

  ## Make sure the functional subdirectory exists ##
  if($rsd != $fsd && ! $nocopy) then

    ## Get voxel dimensions of bold run ##
    set fsdseqfile = $sess/$fsd/seq.info
    if(! -e $fsdseqfile ) then
      echo "ERROR: cannot find $fsdseqfile"
      exit 1;
    endif
    set inplaneres  = `cat $fsdseqfile|awk '{if($1=="rowpixelsize")print $2}'`;
    set betplaneres = `cat $fsdseqfile|awk '{if($1=="slcpixelsize")print $2}'`;

    if($#inplaneres == 0) then
      echo "ERROR: seq.info file does not appear to be formated correctly"
      echo "       Try running fixseqinfo-sess."
      exit 1;
    endif

    set fsdreg = $sess/$fsd/$regfile
    if(-e $fsdreg) mv $fsdreg $fsdreg.$DateString
    head -n 1 $regfile >> $fsdreg  # subject name
    echo $inplaneres   >> $fsdreg  # pixel size
    echo $betplaneres  >> $fsdreg  # slice thick
    echo 0.15          >> $fsdreg  # intensity
    set tmp = `cat $fsdreg | tail -n 1`;
    if($#tmp > 1) then
      tail -n 4 $regfile >> $fsdreg  # matrix
    else
      tail -n 5 $regfile >> $fsdreg  # matrix+float2int
    endif
  endif

  popd > /dev/null

end  # foreach sess ($SessList)


echo "tkregister-sess completed SUCCESSFULLY"

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

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

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

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

    case "-volview":
      if ( $#argv == 0) goto arg1err;
      set VolView = $argv[1]; shift;
      if($VolView != mov && $VolView != targ) then
        echo "ERROR: volview = $VolView, must be mov or targ"
        exit 1;
      endif
      breaksw

    case "-inorm":
      set Inorm = 1;
      breaksw

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

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

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

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

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

    case "-nosurf":
      set Surf = ();
      breaksw

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

    case "-useold":
      set UseNew = 0;
      breaksw

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

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

    case "-sessanat":
    case "-samesessanat":
      set samesessanat = 1;
      set Surf = ();
      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($#rsd == 0) set rsd = $fsd;

  if($samesessanat && $#Surf != 0) then
    echo "ERROR: cannot specify a surface when using same-session anat"
    exit 1;
  endif


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

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

############--------------##################
usage_exit:
  echo "USAGE: tkregister-sess"
  echo "Options:";
  echo "   -sf sessidfile  ..."
  echo "   -df srchdirfile ..."
  echo "   -s  sessid      ..."
  echo "   -d  srchdir     ..."
  echo "   -surf surfacename : display surfacename as an overlay (white)"
  echo "   -nosurf        : don't display a surface"
  echo "   -rsd dir       : subdirectory with data to register ($rsd)"
  echo "   -fsd dir       : functional subdirectory ($fsd)"
  echo "   -asd dir       : anatomical subdirectory ($asd)"
  echo "   -nocopy        : do not copy registration to fsd"
  echo "   -sessanat      : register to same-session anatomical"
  echo "   -anatvol dir   : specify subdirectory of subjid/mri"
  echo "   -volview volid : starup with either <targ> or mov"
  echo "   -plane orient  : starup with orient. <cor>, sag, or ax"
  echo "   -slice sliceno : starup with slice. Default is 128."
  echo "   -regfile file  : use file instead of register.dat"
  echo "   -umask umask   : set unix file permission mask"
  echo "   -version       : print version and exit"
  echo "   -useold        : use tkregister instead of tkregister2"
exit 1;
