#!/bin/csh -f
# mtp-repack - repacks data given the indices in the incomplete data
# before which a sham volume should be inserted.
#
# Notes:
#  1. fillmethod is ignored -- uses interpolation 
#

set VERSION = '$Id: mtp-repack,v 1.1 2000/06/14 21:24:52 greve Exp greve $'
set cmdargs = ($argv);

set instem  = ();
set outstem = ();
set TR = ();
set mtpfile = ();
set tpxfile = ();
set fillmethod = ();
set mfile = ();
set monly = 0;
set firstslice = ();
set nslices    = ();
set force = 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:

goto check_params;
check_params_return:

## Autodetect First and Number of Slices ##
if($#firstslice == 0) then
  set firstslice = `getfirstsliceno $instem`;
  if($status) then
    echo "ERROR: detecting slice $firstslice of $instem"
    exit 1;
  endif
endif
if($#nslices == 0) then
  set nslices = `getnslices $instem $firstslice`;
  if($status) then
    echo "ERROR: nslices of $instem"
    exit 1;
  endif
endif

## Get/Create output directory ##
set outdir = `dirname $outstem`;
mkdir -p $outdir

set MATLAB = `getmatlab`;
if($status) exit 1;

if ($monly) then
  set QuitOnError = 0;
  set TARGET = "tee $mfile"
  rm -f $mfile;
else
  set QuitOnError = 1;
  set TARGET =  "$MATLAB -display iconic"
endif  

## Set up the log file ##
set LF = $outstem-mtp-repack.log
echo "Logfile is $LF"
rm -f $LF
echo "Log file for mtp-repack " >>& $LF
date >>& $LF
echo $0 >>& $LF
echo $VERSION >>& $LF
echo "$LF" >>& $LF
echo "CommandLine: $cmdargs" >>& $LF
echo "Current Dir: `pwd`" >>& $LF
echo "UName: `uname -a`" >>& $LF
df $outdir >>& $LF
echo "Force $force" >>& $LF
echo "Matlab: $MATLAB" >>& $LF
echo "-------------- matlab output ----------------------------" >>& $LF
#-------------- matlab code ----------------------------#
$TARGET <<EOF | tee -a $LF

  fprintf('\n\n');

  QuitOnError = $QuitOnError;
  instem      = '$instem';
  inext       = 'bshort';
  outstem     = '$outstem';
  outext      = 'bshort';
  fillmethod  = '$fillmethod';
  mtpfile     = '$mtpfile';
  tpxfile     = '$tpxfile';
  TR          = $TR;
  fslc        = $firstslice;
  nslc        = $nslices;
  lslc        = fslc + nslc - 1;        

  % Get the dimensions of the input volume %
  [nrows ncols ntp fs ns endian] = fmri_bfiledim(instem);

  % Read in the indices of the missing time points %
  fid = fopen(mtpfile,'r');
  if(fid < 0)
    msg = sprintf('Could not open %s',mtpfile);
    qoe(msg); error(msg);
  end
  imtp = fscanf(fid,'%d');
  fclose(fid);
  if(isempty(imtp))
    msg = sprintf('No time points found in %s',mtpfile);
    qoe(msg); error(msg);
  end

  % Check for funny-business in the missing time points %
  imtp_max = max(imtp);
  if(imtp_max > ntp)
    fprintf('WARNING: missing time point > number of time points, ignoring\n');
  end
  ind = find(imtp <= ntp);
  imtp = imtp(ind);
  if(isempty(imtp))
    msg = sprintf('No time points less than %d found in %s',ntp,mtpfile);
    qoe(msg); error(msg);
  end
  fprintf('Missing time points (old volume): ');
  fprintf('%3d ',imtp);
  fprintf('\n');

  % create an index map between the new and old time points %
  ind_n2o = [];
  imtp_new = []; % indices of missing points in the new volume %
  istart = 1;
  for i = 1:length(imtp)
    if(i==1) iend = istart + imtp(i) - 2;
    else     iend = istart + imtp(i) - imtp(i-1) - 1;
    end
    ind_n2o = [ind_n2o [istart:iend]];
    istart = iend + 2;
    imtp_new = [imtp_new istart-1]; 
  end
  fprintf('Missing time points (new volume): ');
  fprintf('%3d ',imtp_new);
  fprintf('\n');

  % add the ones after the last missing tp %
  iend = istart + ntp - length(ind_n2o) - 1;
  ind_n2o = [ind_n2o [istart:iend]];
  ntp_new = length(ind_n2o);

  % Create the time point exclusion file %
  fid = fopen(tpxfile,'w');
  if(fid < 0)
    msg = sprintf('Could not open %s',tpxfile);
    qoe(msg); error(msg);
  end
  tpx = TR*imtp_new;
  fprintf(fid,'%8.4f \n',tpx);
  fclose(fid);

  %% Go through each slice %%
  for slice = fslc : lslc
    fprintf('Slice %2d\n',slice);

    % load input (incomplete) data slice %
    fname = sprintf('%s_%03d.%s',instem,slice,inext);
    f = fmri_ldbfile(fname);
    
    % repack %
    fnew = zeros(nrows,ncols,ntp_new);
    fnew(:,:,ind_n2o) = f;

    % interpolate %
    img0 = fnew(:,:,imtp_new-1);
    img1 = fnew(:,:,imtp_new+1);
    fnew(:,:,imtp_new) = (img0+img1)/2;

    % save repacked data %
    fname = sprintf('%s_%03d.%s',outstem,slice,outext);
    fmri_svbfile(fnew,fname);

  end

  return;
  if(QuitOnError)  quit; end
  
EOF
#------------ end matlab -----------------------#
echo "-------------- matlab done ----------------------------" >>& $LF

date >>& $LF
echo "mtp-repack completed successfully" | tee -a $LF


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 "-fill":
      if ( $#argv == 0) goto arg1err;
      set fillmethod = $argv[1]; shift;
      breaksw

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

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

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

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

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

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

    case "--version":
    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 "-force":
      set force = 1;
      breaksw

    case "-verbose":
      set verbose = 1;
      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:

  if ($#instem == 0) then
     echo "ERROR: no input stem specified"
     exit 1
  endif

  if ($#outstem == 0) then
     echo "ERROR: no output stem specified"
     exit 1
  endif

  if ($instem == $outstem && ! $force) then
    echo "  ERROR/WARNING: output and input stems are the same."
    echo "  This will cause the input data to be overwritten."
    echo "  If this is what you want to happen, then add -force"
    echo "  to the command line."
    exit 1;
  endif

  if ($instem == $outstem && $force) then
    echo "  WARNING: output and input stems are the same."
    echo "  This will cause the input data to be overwritten."
    echo "  Hit Control-C now to abort if this is not what you want!"
    sleep 8;
    echo "  Continuing ..."
  endif

  if ($#mtpfile == 0) then
     echo "ERROR: no mtp file specified"
     exit 1
  endif

  if ($#TR == 0) then
     echo "ERROR: no TR specified"
     exit 1
  endif

#  if ($#fillmethod == 0) then
#     set fillmethod = "interp";
#  endif

  if ($#tpxfile == 0) then
     set tpxfile = $outstem.tpexclude
  endif

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

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

############--------------##################
usage_exit:
  echo "USAGE: mtp-repack  repack data with missing timepoints"
  echo "Options:";
  echo "   -i instem      : stem of input volume"
  echo "   -o outstem     : stem of output volume"
  echo "   -mtp filename  : name of file with missing timepoints"
#  echo "   -fill  method  : inter, mean, constant"
  echo "   -TR  TR        : TR in seconds"
  echo "   -tpx filename  : name of tp exclude file (outstem.tpexclude)"
  echo "   -umask umask   : set unix file permission mask"
  echo "   -monly  mfile  : do not run, just create a matlab file"
  echo "   -version       : print version and exit"
exit 1;

