#! /bin/csh -f

#
# fwhmest -- front end for FSL's smoothest
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: nicks $
#    $Date: 2007/01/09 22:41:17 $
#    $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 inputargs = ($argv);
set VERSION = '$Id'
set PrintHelp = 0;

set InSpec = ();
set PolyOrder = -1;
set xmatfile = ();
set extregstem = ();
set MaskSpec = ();
set tmpdir = ();
set outfile = ();
set monly = 0;
set fmt = ();
set fmtext = ();
set MLF = ();
set cleanup = 1;
set nskip = 0;

if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif
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:

goto check_params;
check_params_return:

## Get path for log-file ##
set LF = $InSpec"_fwhm.log"
echo "Logfile is $LF"
rm -f $LF;
touch $LF;
echo ------------------------------------------ >> $LF
echo "fwhmest $VERSION" >> $LF
uname -a >> $LF
hostname >> $LF
date >> $LF
pwd >> $LF
echo $0 >> $LF
echo $inputargs >> $LF

if($#tmpdir == 0) then
  set indir = `dirname $InSpec`;
  set tmpdir = $indir/fwhmest-tmp
endif

mkdir -p $tmpdir  |& tee -a $LF
if($status) exit 1;

set doffile = $tmpdir/dof.dat
rm -f $doffile

if($PolyOrder < 0 && $#xmatfile == 0 && $#extregstem == 0) goto smoothest;

## Set path for matlab file ##
if(! $monly)  set MLF = "/tmp/fwhmest_$$.m"
rm -f $MLF

set outspec = $tmpdir/f.mgh;

  #-----------------------------------------------------#
tee $MLF > /dev/null <<EOF
  inspec  = '$InSpec';
  outspec = '$outspec';
  order   = [$PolyOrder];
  doffile = '$doffile';
  xmatfile = '$xmatfile';
  extregstem = '$extregstem';
  nskip = $nskip;
  monly  = $monly;

  f = MRIread(inspec);
  if(isempty(f))
    fprintf('ERROR: loading %s\n',inspec);
    if(~monly) quit; end
    return; 
  end
  if(nskip > 0) 
    fprintf('nskip = %d\n',nskip);
    f.vol = f.vol(:,:,:,nskip+1:end); 
  end

  szf = size(f.vol);
  nv = prod(szf(1:3));
  nf = szf(4);
  f.vol = reshape(f.vol,[nv nf])';

  X = [];

  if(~isempty(xmatfile))
    XX = load(xmatfile);
    if(isempty(XX))
      fprintf('ERROR: loading %s\n',xmatfile);
      return; quit;
    end
    X = [X XX.Xfinal];
  end

  if(~isempty(extregstem))
    extreg = fmri_ldbvolume(extregstem);
    if(isempty(extreg))
      fprintf('ERROR: could not load %s\n',extregstem);
      return;
    end
    if(size(extreg,3)~=1) extreg = squeeze(extreg)'; %'
    else                  extreg = squeeze(extreg);
    end
    % normalize
    extreg = extreg - repmat(mean(extreg), [nf 1]);
    extreg = extreg./repmat(std(extreg), [nf 1]);
    X = [X extreg];
  end

  if(order > -1)
    Xp = fast_polytrendmtx(1,nf,1,order);
    X = [X Xp];
  end

  if(~isempty(X))
    R = eye(nf) - X*inv(X'*X)*X';
    f.vol = R*f.vol;
    dof = size(X,1) - size(X,2);
  else
    dof = nf;
  end

  f.vol = reshape(f.vol',szf);

  %fspec = sprintf('%s%s',outstem,fmtext);
  MRIwrite(f,outspec);

  fp = fopen(doffile,'w');
  fprintf(fp,'%g\n',dof);
  fclose(fp);

  return; quit;
EOF
  #-----------------------------------------------------#

cat $MLF | matlab -nospash -display iconic |& tee -a $LF
mri_convert $outspec $tmpdir/f.img

smoothest:

if($PolyOrder < 0 && $#xmatfile == 0 && $#extregstem == 0) then
  #set dof = `getnframes $InStem`;
  set dof = `mri_info --nframes $InSpec$fmtext `;
  echo $dof > $doffile
  mri_convert $InSpec $tmpdir/f.img
endif

mri_convert $MaskSpec $tmpdir/mask.img


set dof = `cat $doffile`;
set cmd = (smoothest -V -d $dof -m $tmpdir/mask.img -r $tmpdir/f.img)
echo $cmd |& tee $LF
$cmd > $outfile

cat $outfile

if($cleanup) rm -r $tmpdir

echo " " | tee -a $LF
echo " " | tee -a $LF
date | tee -a $LF
echo "fwhmest: finished" | 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 InSpec = $argv[1]; shift;
      breaksw

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

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

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

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

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

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

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

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

    case "--nocleanup":
      set cleanup = 0;
      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($#InSpec == 0) then
    echo "ERROR: must specify input";
    exit 1
  endif
  if(! -e $InSpec) then
    set fmt = `stem2fmt $InSpec`;
    if($status) then
      echo "ERROR: cannot find $InSpec"
      exit 1;
    endif
    set InSpec = $InSpec.$fmt
  endif

  if($#MaskSpec == 0) then
     echo "ERROR: must specify mask ";
     exit 1
  endif
  if(! -e $MaskSpec) then
    set fmt = `stem2fmt $MaskSpec`;
    if($status) then
      echo "ERROR: cannot find $MaskSpec"
      exit 1;
    endif
    set MaskSpec = $MaskSpec.$fmt
  endif

  if($#outfile == 0) set outfile = $InSpec.fwhm.dat

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


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

#--------------------------------------------------------------------#
usage_exit:
  echo "fwhmest"
  echo "  --i instem "
  echo "  --mask maskstem"
  echo ""
  echo "  --fmt format : bvolume, mgh, or mgz"
  echo "  --polyfit N : default is 0"
  echo "  --nskip nskip : default is 0"
  echo "  --X xmatfile"
  echo "  --extreg extregstem"
  echo "  --o outfile : default is instem.fwhm.dat"
  echo "   -umask umask          : set unix file permission mask"
  echo "   -version              : print version and exit"
  if($PrintHelp) \
  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

Frontend for FSLs smoothest
