#!/bin/csh -f
#
# d2afni
#
# converting GE dicom files to afni brik
# call to3d then add Rx info to the header
# 
#
# Requires: dicom2 from http://www.barre.nom.fr/medical/dicom2/
#           AFNI tools from NIH
#           dicomrx from http://cfmri.ucsd.edu/download/
#           Center for fMRI, UCSD
#
# What this script does:
#  1) call to3d to create AFNI brik
#  2) ADD Rx info to the header of the AFNI brik
# 
#
# Version History
#  1.0 050902 KL initial version
#  1.1 060205 KL now supports long argument list
#  2.0 060824 KL added -session flag 
#
# Send Comments/Questions to kunlu@ucsd.edu 
set VERSION = 'v 1.1 2005/09/26';
set inputargs = ($argv);
set DateStr = "`date '+%y%m%d%H%M'`"

set prefix;
set dfile;
set session = '.';

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

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


goto parse_args;
parse_args_return:

echo $inputargs > {$prefix}cmdlinelist.tmp
to3d -@ < {$prefix}cmdlinelist.tmp

set dfile=$inputargs[$#inputargs] 
if ($prefix != '') then
   echo "dicomrx -brik $session/$prefix $dfile"
   dicomrx -brik $session/$prefix $dfile
else
    echo "ERROR: please specify -prefix!"
endif

#if (-e "$prefix+orig.BRIK") then
#else
#   echo "ERROR: could not find $prefix+orig.BRIK!"
#endif 
if (-e {$prefix}cmdlinelist.tmp) then
   rm -f {$prefix}cmdlinelist.tmp
endif

exit 1


parse_args:
while( $#argv != 0)

  set flag = $argv[1]; shift;
  switch(`echo $flag | cut -c1-4`)
    case "-pre":
      if ( $#argv == 0) goto arg1err;
      set prefix = $argv[1]; shift;
      breaksw
    case "-ses":
      if ( $#argv == 0) goto arg1err;
      set session = $argv[1]; shift;
      breaksw
    default:
      breaksw
  endsw

end

goto parse_args_return;

usage_exit:
    echo "Name"
    echo "     d2afni - converts GE dicom files to AFNI datasets (supports NIFTI) "
    echo "              and adds Rx info to the header. " 
    echo "Usage"
    echo "     same as to3d  <to3d -help> "
    echo "Output"
    echo "     a dataset in AFNI brik or NIFTI format "
    echo "Example"
    echo "     FSPGR: d2afni -prefix name     anatdir/i* "
    echo "            d2afni -prefix name.nii anatdir/i* "
    echo "     EPI:   d2afni -prefix name     -time:zt #slices # reps TR alt+z epidir/i* "
    echo "            d2afni -prefix name.nii -time:zt #slices # reps TR alt+z epidir/i* "    
    echo "Report Bugs"
    echo "     report bugs to kunlu@ucsd.edu"
    echo "Version"
    echo "     $VERSION"
    echo ""
exit 1;

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