#!/bin/tcsh -f
# xcorr

set VERSION = 'xcorr dev';

set outvol = ();
set invol1 = ();
set invol2 = ();

set tmpdir = ();
set cleanup = 1;
set LF = /dev/null; # no log

set inputargs = ($argv);
set PrintHelp = 0;
if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;
  goto usage_exit;
endif
set n = `echo $argv | grep -e -version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif

source $FREESURFER_HOME/sources.csh

goto parse_args;
parse_args_return:
goto check_params;
check_params_return:

set StartTime = `date`;
set tSecStart = `date '+%s'`;
set year  = `date +%Y`
set month = `date +%m`
set day   = `date +%d`
set hour   = `date +%H`
set min    = `date +%M`

set outdir = `dirname $outvol`
mkdir -p $outdir
pushd $outdir > /dev/null
set outdir = `pwd`;
popd > /dev/null

if($#tmpdir == 0) then
  set tmpdir = `fs_temp_dir --scratch --base $outdir`
endif
mkdir -p $tmpdir

# Set up log file
if($#LF == 0) set LF = $tmpdir/xcorr.log
if($LF != /dev/null) rm -f $LF
echo "Log file for xcorr" >> $LF
date  | tee -a $LF
echo "" | tee -a $LF
echo "setenv SUBJECTS_DIR $SUBJECTS_DIR" | tee -a $LF
echo "cd `pwd`"  | tee -a $LF
echo $0 $inputargs | tee -a $LF
echo "" | tee -a $LF
cat $FREESURFER_HOME/build-stamp.txt | tee -a $LF
echo $VERSION | tee -a $LF
uname -a  | tee -a $LF

#========================================================

set fnorm1 = $tmpdir/fnorm1.mgh
set cmd = (mri_concat $invol1 --fnorm --o $fnorm1)
echo $cmd | tee -a $LF
$cmd | tee -a $LF
if($status) goto error_exit;

set fnorm2 = $tmpdir/fnorm2.mgh
set cmd = (mri_concat $invol2 --fnorm --o $fnorm2)
echo $cmd | tee -a $LF
$cmd | tee -a $LF
if($status) goto error_exit;

set prod = $tmpdir/prod.mgh
set cmd = (fscalc $fnorm1 mul $fnorm2 -o $prod)
echo $cmd | tee -a $LF
$cmd | tee -a $LF
if($status) goto error_exit;

set cmd = (mri_concat $prod --sum --o $outvol)
echo $cmd | tee -a $LF
$cmd | tee -a $LF
if($status) goto error_exit;

#========================================================

# Cleanup
if($cleanup) rm -rf $tmpdir

# Done
echo " " |& tee -a $LF
set tSecEnd = `date '+%s'`;
@ tSecRun = $tSecEnd - $tSecStart;
set tRunHours = `echo $tSecRun/3600|bc -l`
set tRunHours = `printf %5.2f $tRunHours`
echo "Started at $StartTime " |& tee -a $LF
echo "Ended   at `date`" |& tee -a $LF
echo "Xcorr-Run-Time-Sec $tSecRun" |& tee -a $LF
echo " " |& tee -a $LF
echo "xcorr Done" |& tee -a $LF
exit 0

###############################################

############--------------##################
error_exit:
echo "ERROR: $cmd" | tee -a $LF
echo "xcorr exited with errors" | tee -a $LF

exit 1;
###############################################

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

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

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

    case "--i1":
      if($#argv < 1) goto arg1err;
      set invol1 = $argv[1]; shift;
      if(! -e $invol1) then
        echo "ERROR: cannot find $invol1"
        exit 1;
      endif
      breaksw

    case "--i2":
      if($#argv < 1) goto arg1err;
      set invol2 = $argv[1]; shift;
      if(! -e $invol2) then
        echo "ERROR: cannot find $invol2"
        exit 1;
      endif
      breaksw

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

    case "--nolog":
    case "--no-log":
      set LF = /dev/null
      breaksw

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

    case "--nocleanup":
      set cleanup = 0;
      breaksw

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

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

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

end

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

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

if($#outvol == 0) then
  echo "ERROR: must spec output"
  exit 1;
endif
if($#invol1 == 0) then
  echo "ERROR: must spec input volume 1"
  exit 1;
endif
if($#invol2 == 0) then
  echo "ERROR: must spec input volume 2"
  exit 1;
endif


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

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

############--------------##################
usage_exit:
  echo ""
  echo "xcorr --i1 f1 --i2 f2 --o xcorrfile"
  echo "  --log logfile"
  echo "  --tmp tmpdir"
  echo "  --no-cleanup"
  echo ""

  if(! $PrintHelp) exit 1;
  echo $VERSION
  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

Computes the voxel-for-voxel correlation coefficient between two volumes.
Each voxel has a time course in each volume. Each time course is normalized,
then multiplied together, and the product is summed to compute the Pearson
correlation coefficient at each voxel.


