#!/bin/csh -f

if($#argv != 1 && $#argv != 2) then
  echo "USAGE: ima-checkseries imadir <outfile>"
  exit 1;
endif

set imadir  = $argv[1];
if( ! -e $imadir ) then
  echo "ERROR: $imadir does not exist"
  exit 1;
endif

if($#argv == 2) then
  set outfile = $argv[2];
  set outdir = `dirname $outfile`;
  mkdir -p $outdir
else
  set outfile = /dev/null
endif

echo "Checking Series for $imadir" |& tee -a $outfile
set StartDate = `date`;
echo "StartDate: $StartDate" |& tee -a $outfile

pushd $imadir > /dev/null

## Get the exam number from the first image ##
set tmp = `ls *.ima | head -n 1`;
if($#tmp == 0) then
  echo "ERROR: there are no ima files" |& tee -a $outfile
  exit 1;
endif
set base = `basename $tmp .ima`;
set tmp2 = `echo $base | sed 's/-/ /g' `;
set exam = $tmp2[1];
echo "Exam number is $exam" |& tee -a $outfile

# Create a tmp file with three columns: seriesno runno imageno 
# for each ima file
set tmpfile = /tmp/ima-checkimgno-$$
rm -f $tmpfile
touch $tmpfile
echo "Parsing files names ... "
ima-parse-name * > $tmpfile
if($status) then
  echo "ERROR: ima-parse-name failed" |& tee -a $outfile
  rm -f $tmpfile
  exit 1;
endif

# Mine the tmp file for a unique list of series numbers #
set serieslist  = `cat $tmpfile | awk '{print $2}' | sort -n | uniq`;
set firstseriesno = $serieslist[1];
set lastseriesno  = $serieslist[$#serieslist];

echo "Found $#serieslist series"        |& tee -a $outfile
echo "First Series No: $firstseriesno"  |& tee -a $outfile
echo "Last  Series No: $lastseriesno"   |& tee -a $outfile

echo "Searching for missing/mis-sized series ... "
set exitstatus = 0;
@ seriesno = 1;
while ( $seriesno <= $lastseriesno )
  echo "Checking series $seriesno ---------------- "
  set imafiles = `ls *-$seriesno-*.ima `;
  if($status || $#imafiles == 0) then
    echo "Series $seriesno is missing"   |& tee -a $outfile
    set exitstatus = 2;
  else
    set ima1 = $imafiles[1];
    set ima1sz = `ls -l $ima1 | awk '{print 5}'`;
    foreach ima ($imafiles)
      set imasz = `ls -l $ima | awk '{print 5}'`;
      if($ima1sz != $imasz) then
        echo "Series $seriesno has inconsistent file sizes" |& tee -a $outfile
        set exitstatus = 3;
        break;
      endif
    end
  endif
  @ seriesno = $seriesno + 1;
end


if($exitstatus) then
  echo "WARNING: missing or inconsistent data" |& tee -a $outfile
else
  echo "Everything appears to be in order"  |& tee -a $outfile
endif

echo "StartDate: $StartDate" |& tee -a $outfile
echo "EndDate:   `date`"     |& tee -a $outfile

rm -f $tmpfile


exit $exitstatus;

#--------------------------------------------------------#
