#! /bin/tcsh -f

#
# tdr-fidmat - used tdr_fidmat.m
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:19 $
#    $Revision: 1.10 $
#
# 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: tdr-fidmat,v 1.10 2007/01/09 22:41:19 nicks Exp $';

set inputargs = ($argv);

set rawkfiddir = ();
set rawkepidir = ();
set outmat     = ();
set fwhm       = 0;
set monly      = 0;
set cleanup    = 1;
set convmdh    = 1;
set TE         = ();
set PERev      = ();
set RORev      =  0;
set Interleaved = 1;
set nslices    = ();
set fidechospacing = ();
set fidecho1ped    = ();

#set fidecho1ped   = 1980;   # PED of first FID echo (us)
#set fidechospacing = 820; # Time between FID echoes (us) (Actually uses double)
#set nfidechoes     = 64; # But we'll only use half (odd echoes), 

#set epiechospacing = 470; # us
#set epidelsamp = 30;      # us
#set epitdwell = 3.2;      # us

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

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

set umask = `umask`;

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

##### Create a log file ######
set logdir = $outdir/log;
mkdir -p $logdir
if(! -e $logdir) then
  echo "WARNING: could not create $logdir"
  set LF = /dev/null
else
  set LF = $logdir/tdr-fidmat.log
  if(-e $LF) mv $LF $LF.old
endif
echo "--------------------------------------------------------------"
echo "tdr-fidmat logfile is $LF"
echo "--------------------------------------------------------------"

echo "tdr-fidmat log file" >> $LF
echo $VERSION >> $LF
id            >> $LF
pwd           >> $LF
echo $0        >> $LF
echo $inputargs  >> $LF
uname -a      >> $LF
date          >> $LF

set StartTime = `date`;

pushd $rawkfiddir > /dev/null
set rawkfiddir = `pwd`;
popd > /dev/null

# Get FID parameters
set fidmeasasc = $rawkfiddir/meas.asc
if($#fidecho1ped == 0) then
  set tmp = `parse-measasc $fidmeasasc "alTE[0]"`
  if($status) then
    echo "$tmp" | tee -a $LF
    exit 1;
  endif
  set fidecho1ped = $tmp
endif

if($#fidechospacing == 0) then
  set tmp = `parse-measasc $fidmeasasc "sWiPMemBlock.adFree[2]"`
  if($status) then
    echo "$tmp"| tee -a $LF
    exit 1;
  endif
  set fidechospacing = `echo "$tmp*1000" |bc -l`; # convert to us
endif

set tmp = `parse-measasc $fidmeasasc "sWiPMemBlock.alFree[10]"`
if($status) then
  echo "$tmp"| tee -a $LF
  exit 1;
endif
set nfidechoes = $tmp

set tmp = `parse-measasc $fidmeasasc "m_iNoOfFourierColumns"`
if($status) then
  echo "$tmp"| tee -a $LF
  exit 1;
endif
set ncols = $tmp;

set tmp = `parse-measasc $fidmeasasc "m_iNoOfFourierLines"`
if($status) then
  echo "$tmp"| tee -a $LF
  exit 1;
endif
set nrows = $tmp;

set tmp = `parse-measasc $fidmeasasc "nslices"`
if($status) then
  echo "$tmp"| tee -a $LF
  exit 1;
endif
set nslices = $tmp;

# Get EPI parameters
set epimeasasc = $rawkepidir/meas.asc
set tmp = `parse-measasc $epimeasasc "m_lEchoSpacing"`
if($status) then
  echo "$tmp"| tee -a $LF
  exit 1;
endif
set epiechospacing = $tmp

set tmp = `parse-measasc $epimeasasc "m_alRegridDelaySamplesTime"`
if($status) then
  echo "$tmp"| tee -a $LF
  exit 1;
endif
set epidelsamp = $tmp

set tmp = `parse-measasc $epimeasasc "sRXSPEC.alDwellTime[0]"`
if($status) then
  echo "$tmp"| tee -a $LF
  exit 1;
endif
set epitdwell = `echo "$tmp/1000" |bc -l`; # convert to us

echo "fidecho1ped $fidecho1ped" | tee -a $LF
echo "fidechospacing $fidechospacing" | tee -a $LF
echo "nfidechoes $nfidechoes" | tee -a $LF
echo "epiechospacing $epiechospacing" | tee -a $LF
echo "epidelsamp $epidelsamp " | tee -a $LF
echo "epitdwell $epitdwell " | tee -a $LF
echo "nrows $nrows" | tee -a $LF
echo "ncols $ncols" | tee -a $LF
echo "nslices $nslices" | tee -a $LF

set fidmghdir = $outdir/tmp/fid
if($convmdh) then
  mkdir -p $fidmghdir
  set cmd = (mri_convert_mdh --srcdir $rawkfiddir \
        --outdir $fidmghdir \
        --dim 1 $nslices $nfidechoes $nrows $ncols 0 \
        --fasterdim echo)
  echo "---------------------------------" |& tee -a $LF
  date |& tee -a $LF
  echo $cmd |& tee -a $LF
  $cmd |& tee -a $LF
  if($status) exit 1;
else
  if(! -e $fidmghdir) then
    echo "ERROR: $fidmghdir does not exist, run without --noconvmdh"
    exit 1;
  endif
endif

date | tee -a $LF

set MLF = $fidmghdir/run_tdr_fidmat-$TE.m
rm -f $MLF

#---------------------------------------------#
tee -a > /dev/null $MLF  <<EOF
  fidecho1ped = $fidecho1ped;   
  fidechospacing = $fidechospacing; 
  nfidechoes = $nfidechoes ; 
  
  % EPI timing parameters - note EPI data not needed here
  epiechospacing = $epiechospacing; 
  delsamp = $epidelsamp ;
  tDwell = $epitdwell;
  
  % Dimensions: applies to both EPI and FID - should just get this from data
  nrows = $nrows;
  ncols = $ncols;
  nslices = $nslices;

  fiddir = '$fidmghdir';
  fidfwhm = [$fwhm];
  TE = $TE;
  perev = $PERev;
  rorev = $RORev;
  interleaved = $Interleaved;
  outmat = '$outmat';
  tdr_fidmat2;
EOF
#---------------------------------------------#

if(! $monly) then
  cat $MLF >> $LF
  cat $MLF | matlab -display iconic -nojvm -nosplash | & tee -a $LF
endif

if($cleanup) then
  echo "Deleting mgh files" |& tee -a $LF
  set cmd = (rm -r $fidmghdir)
  echo $cmd |& tee -a $LF
  $cmd |& tee -a $LF
endif

echo "Started at $StartTime" |& tee -a $LF
echo "Ended   at `date`"     |& tee -a $LF
echo "tdr-fidmat done"       |& tee -a $LF


exit 0

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

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

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

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

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

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

    case "--fidesp":
      if ( $#argv == 0) goto arg1err;
      set fidechospacing = $argv[1]; shift;
      echo "INFO: overriding meas.out FID Echo Spacing"
      breaksw

    case "--fide1ped":
      if ( $#argv == 0) goto arg1err;
      set fidecho1ped = $argv[1]; shift;
      echo "INFO: overriding meas.out FID First Echo Time"
      breaksw

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

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

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

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

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

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

    case "--notinterleaved"
      set Interleaved = 0;
      breaksw

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

    case "--noconvmdh":
      set convmdh = 0;
      breaksw

    case "--verbose":
      set verbose = 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($#rawkfiddir == 0) then
    echo "ERROR: must specify an fid rawk dir"
    exit 1;
  endif
  if(! -e $rawkfiddir ) then
    echo "ERROR: $rawkfiddir does not exist"
    exit 1;
  endif

  if($#rawkepidir == 0) then
    echo "ERROR: must specify an epi rawk dir"
    exit 1;
  endif
  if(! -e $rawkepidir ) then
    echo "ERROR: $rawkepidir does not exist"
    exit 1;
  endif

  if($#outmat == 0) then
    echo "ERROR: must specify an output mat file"
    exit 1;
  endif

  if($#TE == 0) then
    echo "ERROR: must specify a TE"
    exit 1;
  endif

  if($#PERev == 0) then
    echo "ERROR: must specify PERev"
    exit 1;
  endif

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

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

############--------------##################
usage_exit:
  echo ""
  echo "USAGE: tdr-fidmat"
  echo ""
  echo "  --fidkdir dir : directory where FID map meas.{out,asc}"
  echo "  --epikdir dir : directory where EPI map meas.asc"
  echo "  --outmat  matfile"
  echo "  --TE TE  : TE of functional in ms"
  echo "  --perev PERev : must supply"
  echo "  --rorev RORev : default is no RORev (0)"
  echo "  --noitnterleaved : do not assume slice interleaving"
  echo "  --fwhm    fwhm"
  echo "  --nocleanup : do not delete intermediate mgh files"
  echo "  --noconvmdh : do not convert mdh files (already there)"
  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 FID map for a functional set of data.

EPI rawk dir only needed to get EPI parameters. You still must
specify a TE (in ms) and number of slices.

BUGS:

If there is an even number of slices with interleaving, it will
get the interleaving wrong.
