#! /bin/csh -f

#
# mc-afni
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:18 $
#    $Revision: 1.7 $
#
# 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: mc-afni,v 1.7 2007/01/09 22:41:18 nicks Exp $';

unset verbose ;

set instem  = ();
set outstem = ();
set afnisession = ./mctmp
set afniprefix = $$
set targstem = ();
set targoff  = 0;  # target offset

set cleanup     = 1;
set inplaneres  = ();  # in-plane resolution 
set betplaneres = ();  # between-plane resolution (ie, slice thick)
set TR          = ();
set UseBVOL2AFNI = 0;

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

goto parse_args;
parse_args_return:

## Create the output directory ##
set outdir  = `dirname $outstem`;
set outbase = `basename $outstem`;
mkdir -p $outdir
pushd $outdir > /dev/null;
set outdir = `pwd`;
popd > /dev/null;

goto check_params;
check_params_return:

####### check that the AFNI commands exist #######
foreach cmd (to3d 3dvolreg)
  which $cmd > /dev/null
  if($status) then
    echo "ERROR: cannot find AFNI command $cmd"
    exit 1;
  endif
end

set mcdat = $outdir/$outbase.mcdat 
if(-e $mcdat) then
  if(! -w $mcdat) then
    echo "ERROR: $mcdat file exists but you do not have write permission"
    echo "change the permissions on this file and re-run"
    exit 1;
  endif
endif

## Get dimensions of input ##
set hdr0 = $instem"_000.hdr";
set nx     = `cat $hdr0 | awk '{print $2}'`
set ny     = `cat $hdr0 | awk '{print $1}'`
set nt     = `cat $hdr0 | awk '{print $3}'`
set endian = `cat $hdr0 | awk '{print $4}'`
set nz = `getnslices $instem`;
echo "Input: Nrows $ny, Ncols $nx, Nslices $nz, Ntp $nt, Endian $endian"

set inext = `getbext $instem`; # bshort or bfloat

### Convert input bfile to afni ###
set afnistem = $afnisession/$afniprefix
if(! $UseBVOL2AFNI) then
  mkdir -p $afnisession
  set cmd = "bfile2afni -i $instem -o $afnistem "
  set cmd = "$cmd -inplaneres $inplaneres -betplaneres $betplaneres"
  set cmd = "$cmd -TR $TR"
  echo "---- Converting Input to AFNI ----------"
  pwd
  echo $cmd
  echo "---------------------------------------"
  $cmd
  if($status) exit 1;
else
  echo "---- Converting Input to AFNI ----------"
  set cmd = "bvol2afni -i $instem -o $afnistem"
  pwd
  echo $cmd
  echo "---------------------------------------"
  $cmd
  if($status) exit 1;
endif

### Convert target bfile to afni ###
if($#targstem != 0) then
  set targprefix = targ-$afniprefix
  set targafnistem = $afnisession/$targprefix
  if(! $UseBVOL2AFNI) then
    set cmd = "bfile2afni -i $targstem -o $targafnistem"
    set cmd = "$cmd -inplaneres $inplaneres -betplaneres $betplaneres"
    set cmd = "$cmd -TR $TR"
    echo "---- Converting Target to AFNI ----------"
    pwd
    echo $cmd
    echo "---------------------------------------"
    $cmd
    if($status) exit 1;
  else
    echo "---- Converting Target to AFNI ----------"
    set cmd = "bvol2afni -i $targstem -o $targafnistem"
    pwd
    echo $cmd
    echo "---------------------------------------"
    $cmd
    if($status) exit 1;
  endif
else
  set targprefix = $afniprefix
endif

echo "-------------- Motion Correcting ---------------------------"
pushd $afnisession > /dev/null
if(-e $afniprefix.volreg+orig.BRIK) rm -f $afniprefix.volreg+orig.BRIK;
if(-e $afniprefix.volreg+orig.HEAD) rm -f $afniprefix.volreg+orig.HEAD;

pwd
if($#targstem != 0 && $targstem != $instem) then
  set leave_echo_on = 1;
  if(! $?echo ) set leave_echo_on = 0;
  set echo ;
  #set VR = /usr/pubsw/packages/AFNI/current/bin/3dvolreg
  set VR = 3dvolreg
  $VR -verbose -dfile $mcdat \
      -prefix $afniprefix.volreg  \
      -base targ-$afniprefix+orig\[$targoff\] $afniprefix+orig
  set st = $status;
  if($st) then
    echo "ERROR: 3dvolreg existed with status $st"
    exit 1;
  endif
  if(! $leave_echo_on) unset echo ;
else
  set leave_echo_on = 1;
  if(! $?echo ) set leave_echo_on = 0;
  set echo ;
  3dvolreg -verbose -dfile $mcdat\
             -prefix $afniprefix.volreg  \
             -base $targoff $afniprefix+orig
  set st = $status;
  if($st) then
    echo "ERROR: 3dvolreg existed with status $st"
    exit 1;
  endif
  if(! $leave_echo_on) unset echo ;
endif

# add total distplacment
set tmpmc = /tmp/tmp_$$.mcdat
addmcparams $mcdat > $tmpmc
mv $tmpmc $mcdat

popd > /dev/null


#------------------------- obsolete --------------------------------#
if(0) then 
echo "-------------- Converting back to bshort -----------------"
afni_to_bshort $afnisession/$afniprefix.volreg+orig.BRIK $outstem $nx $ny $nz $nt
set st = $status;
if($st) then
  echo "ERROR: afni_to_bshort existed with status $st"
  exit 1;
endif
### afni_to_bshort does not do endian, so must do it here ###
set os = `uname -s`;
if( ($endian == 0 && $os == Linux) || \
    ($endian == 1 && $os == IRIX)  || \
    ($endian == 1 && $os == SunOS) )  then

  set newendian = 1;
  if($endian) set newendian = 0;
  set s = 0;
  while($s < $nz)
    set hdr = `printf %s_%03d.hdr $outstem $s`;
    echo "$ny $nx $nt $newendian" > $hdr
    @ s = $s + 1;
  end

  set cmd = "bfileconvert -i $outstem -oend $endian"
  echo "----------- Swapping bytes ------------------------"
  pwd
  echo $cmd
  echo "---------------------------------------------------"
  $cmd
  if($status) exit 1;
endif
endif
#------------------------- end obsolete --------------------------------#

set cmd = (mri_convert $afnisession/$afniprefix.volreg+orig.BRIK \
  $outstem"_000".$inext)
echo $cmd
$cmd
if($status) exit 1;

#afni2bvol -i $afnisession/$afniprefix.volreg+orig.BRIK \
#  -o $outstem -oext $inext
#if($status) exit 1;

## Clean up the anfi files ##
if( $cleanup ) then
  rm -f $afnisession/$afniprefix+orig.*
  rm -f $afnisession/$afniprefix.volreg+orig.*
  rm -f $afnisession/$targprefix+orig.* >& /dev/null
  rmdir $afnisession >& /dev/null
endif

if(-e $instem.bhdr) cp $instem.bhdr $outstem.bhdr

echo "----------------------------------------------------"
echo "Those using the AFNI motion correction should cite:"
echo "  RW Cox and A Jesmanowicz."
echo "  Real-time 3D image registration for functional MRI."
echo "  Magnetic Resonance in Medicine, 42: 1014-1018, 1999."
echo "----------------------------------------------------"

echo "mc-afni completed SUCCESSFULLY"

exit 0;

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

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

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

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

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

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

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

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

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

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

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

    case "-bvol2afni":
      set UseBVOL2AFNI = 1;
      breaksw

    case "-version":
      echo $VERSION
      exit 0;
      breaksw

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

    case "-verbose":
      set verbose ;
      breaksw

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

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

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

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

end

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

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

  set errs = 0;

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

  set i0 = $instem"_000.hdr";
  if(! -e $i0) then
    echo "ERROR: cannot find $i0"
    exit 1;
  endif

  if ($#targstem != 0) then
    set i0 = $targstem"_000.hdr";
    if(! -e $i0) then
      echo "ERROR: cannot find $i0"
      exit 1;
    endif
  endif

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

  if($#inplaneres == 0) then
    # Automatically determine resolutions if not specified
    mri_info --cres $instem.bhdr --o /tmp/tmp.$$.dat
    set inplaneres = `cat /tmp/tmp.$$.dat`;
    mri_info --sres $instem.bhdr --o /tmp/tmp.$$.dat
    set betplaneres = `cat /tmp/tmp.$$.dat`;
    mri_info --tr $instem.bhdr --o /tmp/tmp.$$.dat
    set TR = `cat /tmp/tmp.$$.dat`;
    set TR = `echo $TR/1000 | bc -l`;
    rm /tmp/tmp.$$.dat
  endif

  if($#inplaneres == 0) then
    echo "ERROR: must specify an in-plane resolution"
    set errs = 1;
  endif

  if($#betplaneres == 0) then
    echo "ERROR: must specify a between-planes resolution"
    set errs = 1;
  endif

  if($#TR == 0) then
    set TR = 1;
    echo "INFO: no TR specified ... using $TR seconds"
  endif

  if($errs) then
    echo "ERRORS detected ... aborting"
    exit 1;
  endif

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

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

############--------------##################
usage_exit:
  echo "USAGE: mc-afni"
  echo "Options:";
  echo "   -i stem : input  volume "
  echo "   -ipr mm : in-plane resolution"
  echo "   -bpr mm : between-plane resolution"
  echo "   -o stem : output volume "
  echo "   -t stem : target (input volume)"
  echo "   -toff offset  : target volume offset   ($targoff)"
  echo "   -session dir  : afni session directory ($afnisession)"
  echo "   -prefix  name : afni prefix            (procid)"
  echo "   -nocleanup    : do not delete temporary files"
  echo "   -scriptonly scriptname   : don't run, just generate a script"
  echo "   -version : print version and exit"
exit 1;
