#! /bin/csh -f

#
# bfile2afni
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:16 $
#    $Revision: 1.3 $
#
# 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: bfile2afni,v 1.3 2007/01/09 22:41:16 nicks Exp $'

if($#argv == 0) goto usage_exit;

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

# in-plane resolution in mm
set inplaneres = ();    # in-plane resolution in mm (ie, slice thick)
set betplaneres = ();   # between-plane resolution in mm (ie, slice thick)
set TR = ();            # seconds
set firstplane = ();    # First Frame (0-based)
set nplanes = ();       # Number of Frames past first
set cleanup = 1;

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

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

set tmp = `cat $hdr0`;
set nrows = $tmp[1];             # x: fastest       MGH-NMR:(R to L)
set ncols = $tmp[2];             # y: next-fasted   MGH-NMR:(S to I)
set nfrms = $tmp[3];             # t: next-next-fasted      
set nslcs = `getnslices $bstem`; # z: slowest       MGH-NMR:(P to A)
set endian = $tmp[4];              

set tmpdir = ();
if($#firstplane != 0 || $#nplanes != 0) then
  if($#firstplane == 0) set firstplane = 0;
  if($#nplanes == 0)    @ nplanes = $nfrms - $firstplane;
  set tmpdir = `dirname $afnistem`/tmp-$$
  bfileconvert -i $bstem -fp $firstplane -np $nplanes -o $tmpdir/tmp
  if($status) exit 1;
  set bstem = $tmpdir/tmp
  set nfrms = $nplanes;
  echo "tmp dir is $tmpdir"
endif

set bext = `getbext $bstem`; # bshort or bfloat

## Compute Half FOVs for each spatial dimension ##
set xHalfFOV = `echo "$ncols*$inplaneres/2" | bc -l`;
set yHalfFOV = `echo "$nrows*$inplaneres/2" | bc -l`;
set zHalfFOV = `echo "$nslcs*$betplaneres/2" | bc -l`;

## Specify Direction of each axis according to MGH-NMR convention that
## each slice is coronal. This may have no meaning for the actual orientation
## of the slices.
set xDir = "R-L";   # In-Plane, Right
set yDir = "S-I";   # In-Plane, Down
set zDir = "P-A";   # Between Planes

## Determine whether the data are byte swapped or not ##
set os = `uname -s`;
if( ($endian == 0 && $os == Linux) || \
    ($endian == 1 && $os == IRIX)  || \
    ($endian == 1 && $os == SunOS) )  then
  set swapped = 1;
  if($bext == bshort) then
    #set SwapCmd = 2swap;
    set SwapCmd = ();
    set code3D = "3Ds"; 
  else # bfloat
    set SwapCmd = 4swap;
    set code3D = "3Df";
  endif
else # not swapped
  set swapped = 0;
  set SwapCmd = ();
  if($bext == bshort) then
    set code3D = "3D"; 
  else # bfloat
    set code3D = "3Df";
  endif
endif

## Set up size and precision of the "2D slices" ###
if($bext == bshort) then
  set code = $code3D":"0":"0":"$ncols":"$nrows":"$nfrms":"
else # bfloat
  set code = $code3D":"0":"0":"$ncols":"$nrows":"$nfrms":"
endif
echo "code = $code"

set afniprefix  = `basename $afnistem`;
set afnisession = `dirname  $afnistem`;
mkdir -p $afnisession

# Make sure target files are not there #
rm -f $afnistem+orig.BRIK
rm -f $afnistem+orig.HEAD

pwd

to3d \
  -epan \
  -session $afnisession    \
  -prefix $afniprefix      \
  -time:tz $nfrms $nslcs $TR"sec" seqplus \
  -xFOV $xHalfFOV$xDir \
  -yFOV $yHalfFOV$yDir \
  -zFOV $zHalfFOV$zDir \
  -gsfac 1.0 \
  $code$bstem"_???.$bext" 


if($status) then
  echo "ERROR: afni to3d exited with errors"
  exit 1;
endif


if($#SwapCmd != 0) then
  echo "Swapping bytes using $SwapCmd"
  $SwapCmd $afnistem+orig.BRIK
  if($status) then
    echo "ERROR: afni $SwapCmd exited with errors"
    exit 1;
  endif
endif

if($#tmpdir) then
  #echo "Deleting tmp dir $tmpdir"
  #rm -r $tmpdir
endif


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 bstem = $argv[1]; shift;
      breaksw

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

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

    case "-umask":
      if ( $#argv == 0) goto arg1err;
      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

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

end

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


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

  set errs = 0;

  if($#bstem == 0) then
    echo "ERROR: no input stem specified"
    set errs = 1;
  endif

  if($#afnistem == 0) then
    echo "ERROR: no output stem specified"
    set errs = 1;
  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
    echo "INFO: no TR specified ... using 2 seconds"
    set TR = 2;
  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: bfile2afni"
  echo "Options:";
  echo "   -i bfilestem    : input  volume "
  echo "   -o afnistem     : output volume "
  echo "   -inplaneres  mm : in-plane resolution"
  echo "   -betplaneres mm : between-plane resolution"
  echo "   -TR sec         : time between volume scans"
  echo "   -fp firstframe "
  echo "   -np nframes "
  echo "   -version : print version and exit"
exit 1;


