#! /bin/csh -f
##########################################################
# Name:    mkmosiac16
# Usage: <csh> mkmosaic16 instem <outdir> <-heq>"
#
# Purpose: Creates a 4x4 mosaic from 16 slice files. If
# the slices files have multiple time points, then the
# mosaic will have multiple time points.  For example,
# if the slices are of dimension 64x64x10, then the mosiac
# will be 256x256x10.
#
# Notes:
##########################################################

set MKMOSAIC16_VER = '\$Id: mkmosaic16,v 1.8 2000/01/20 23:51:05 greve Exp greve $';

if ( $#argv < 1 || $#argv > 7 ) then
  echo "";
  echo "USAGE: <csh> mkmosaic16 instem <-o outstem> <-firstslice n> <-heq>"
  echo "   instem - stem of the 16 input slices"
  echo "   <-o outstem> - stem of mosaic (default is instem)"
  echo "   <-firstslice int> - first slice number of the 16 slices "
  echo "              (default is 0)"
  echo "   <-heq> - implement histogram equalization on each mosaic"
  echo "            (default is no equalization)"
  echo ""
  echo "  The mosaic file will be called outstem_mos.bxxxxx"
  echo "  where xxxxx is either bfloat or bshort depending upon"
  echo "  the extension of the input slices. If outstem is not"
  echo "  specified, it is set to instem."
  echo ""
  echo "  Note: requires matlab 5.x"
  echo ""
  echo "  $MKMOSAIC16_VER";
  echo "  Comments or questions: analysis-bugs@nmr.mgh.harvard.edu";
  echo "";
  exit;
endif

set BStem = `basename $argv[1]`;
set InDir = `dirname  $argv[1]`;
shift;

set HistEQ = 0;
set OutStem = ();
set FirstSlice = 0;
set nMosCols = 4;

# parse the input options
while( $#argv != 0 )
  if( "$argv[1]" == "-heq" ) then
    set HistEQ = 1;
  else if("$argv[1]" == "-o" ) then
    shift;
    set OutStem = `basename $argv[1]`;
    set OutDir  = `dirname  $argv[1]`;
  else if("$argv[1]" == "-firstslice" || "$argv[1]" == "-fs" ) then
    shift;
    set FirstSlice = $argv[1];
  endif

  if( $#argv != 0 )shift;
end

if( $#OutStem == 0 ) then
  set OutStem = $BStem;
  set OutDir  = .;
endif

# Check that the output directory exists #
if( ! -d $OutDir ) then
  echo "INFO: Directory $OutDir does not exist, creating ..." 
  mkdir -p $OutDir;
  if( ! -d $OutDir ) then
    echo "ERROR: Could not create directory $OutDir"
    exit;
  endif
endif

# Specify the log file #
set LogFile = $OutDir/$OutStem"_mos.log"
rm -f $LogFile;
touch $LogFile;

echo "----------------------------------------------------" | tee -a $LogFile;
echo "mkmosaic16 $MKMOSAIC16_VER" | tee -a $LogFile;
echo "Author: Douglas Greve (greve@nmr.mgh.harvard.edu)" | tee -a $LogFile;
date | tee -a $LogFile;
uname -a | tee -a $LogFile;
echo BStem = $BStem >> $LogFile;
echo InDir = $InDir >> $LogFile;
echo OutStem = $OutStem >> $LogFile;
echo OutDir = $OutDir >> $LogFile;
echo HistEQ = $HistEQ >> $LogFile;
if($HistEQ) then
  echo Using Histogram Equalization | tee -a $LogFile;
else
  echo NOT Using Histogram Equalization | tee -a $LogFile;
endif

# Check that the input directory exists #
if( ! -d $InDir ) then
  echo "ERROR: Directory $InDir does not exist" | tee -a $LogFile;
  exit 1;
endif

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

# Make sure that there are files with the given stem #
set FirstSliceStem = $InDir/`printf %s_%03d $BStem $FirstSlice`;
#echo $FirstSliceStem
set d = $FirstSliceStem.bshort
if(! -r $d) then
  set d = $FirstSliceStem.bfloat
  if(! -r $d) then
    echo "ERROR: Cannot find bshort or bfloat files with $FirstSliceStem" | \
            tee -a $LogFile;
    exit 1;
  endif
  set Ext = bfloat;
else
  set Ext = bshort;
endif

## Go thru all 16 slices, make sure files exist, and 
## create a list for matalb.
@ slc =  $FirstSlice;
@ ns  = 16 + $FirstSlice; # last slice
set mSliceFiles = "strvcat(";
set c = ""
set shref = $FirstSliceStem".hdr"

while($slc < $ns)

  # Leading zeros #
  if($slc < 10) then 
      set lz = "_00";
  else if ($slc < 100) then
      set lz = "_0";
  else
      set lz = "_";
  endif

  # construct slice file name
  set sf = $InDir"/"$BStem$lz$slc"."$Ext;
  if( ! -r $sf ) then
    echo ERROR: File $sf does not exist or is unreadable | tee -a $LogFile;
    exit;
  endif

  # construct slice header file name
  set sh = $InDir"/"$BStem$lz$slc".hdr"
  if( ! -r $sh ) then
    echo ERROR: File $sh does not exist or is unreadable | tee -a $LogFile;
    exit;
  endif

  # construct slice dof file name and copy (if it exists) #
  set dofInFile = $InDir"/"$BStem$lz$slc".dof"
  if( -r $dofInFile ) then
    set dofOutFile = $OutDir/$OutStem"_mos.dof"
    cp $dofInFile $dofOutFile;
  endif

  # check that header files are the same
  @ n = `diff -q $sh $shref | wc -l`;
  if( $n != 0 ) then
    echo "ERROR: header files $shref and $sh differ" | tee -a $LogFile;
    exit;
  endif

  # add slice file name to matlab list #
  set mSliceFiles = "$mSliceFiles $c '$sf'";

  set c = ",";
  @ slc =  $slc + 1;
end
set mSliceFiles = "$mSliceFiles );";

set MosaicFile = $OutDir/$OutStem"_mos."$Ext;

# matlab file #
set MLF = "/tmp/$OutStem"$$"_mkmosaic16.m"
echo Matlab file is $MLF
rm -f $MLF

echo "% $MLF " >> $MLF
echo "% This is a matlab script to run mkmosaic16." >> $MLF
echo "% It is a temporary file and may be deleted." >> $MLF
echo "% `date`" >> $MLF

echo "global QuitOnError;" >> $MLF
echo "QuitOnError = 1;" >> $MLF
echo "HistEQ = $HistEQ;" >> $MLF
echo "HistEQThr = .99;" >> $MLF
echo "MosaicCols = 4;" >> $MLF
echo "SliceFile = $mSliceFiles;" >> $MLF
echo "MosaicFile = '$MosaicFile';" >> $MLF
echo "mkmosaic;" >> $MLF
echo "quit;" >> $MLF

cat $MLF >> $LogFile;
cat  $MLF | $MATLAB -display iconic | tee -a $LogFile;

# construct slice dat file name and copy (if it exists) #
set datInFile = $InDir/$BStem".dat"
if( -r $datInFile ) then
  set datOutFile = $OutDir/$OutStem".dat"
  echo "  Copying dat file $datInFile to $datOutFile";
  cp $datInFile $datOutFile;
endif

date | tee -a $LogFile;
echo LogFile is $LogFile;
echo Done | tee -a $LogFile;

# Clean up #
rm -f $MLF

exit 0;
##########################################################
