#!/bin/csh -f

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

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

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

echo "Checking $imadir" |& tee -a $outfile
date                    |& tee -a $outfile

## 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

## Get the total number of iamge files
set nimas = `ls *.ima | wc -l`;
echo "Number of image files is $nimas"  |& tee -a $outfile

## Get the number of the last image file ##
#set tmp = `ls *.ima | tail -n 1`;
#set base = `basename $tmp .ima`;
#set tmp2 = `echo $base | sed 's/-/ /g' `;
#set lastimgno = $tmp2[3];
#echo "Last image number is $lastimgno" |& tee -a $outfile

set newseries = 1;
@ series   = 1;
@ imgno    = 1;
@ nmissing = 0;
while($imgno <= $nimas) 
  set imafile = $exam-$series-$imgno
  
  
  #if( $newseries ) then

end

exit



set tmpfile = /tmp/ima-checkimgno-$$
rm -f $tmpfile
touch $tmpfile

echo "Parsing files names ... "
ima-parse-name * > $tmpfile
if($status) then
  echo "ERROR: ima-parsename failed" |& tee -a $outfile
  rm -f $tmpfile
  exit 1;
endif

set imgnolist  = `cat $tmpfile | awk '{print $3}' | sort -n`;
set firstimgno = $imgnolist[1];
set lastimgno  = $imgnolist[$#imgnolist];

echo "Found $#imgnolist images"     |& tee -a $outfile
echo "First Image No: $firstimgno"  |& tee -a $outfile
echo "Last  Image No: $lastimgno"   |& tee -a $outfile

echo "Searching for missing image numbers ... "
set missing = ();
@ imgno = 1;
while ( $imgno <= $lastimgno )
  set match = `cat $tmpfile | awk '{print $3}'  | grep -x $imgno | wc -l`;
  if($match < 1) set missing = ($missing $imgno);
  @ imgno = $imgno + 1;
end

if($#missing == 0) then
  echo "No missing images found" |& tee -a $outfile
else
  foreach imgno ($missing)
    echo "$imgno" |& tee -a $outfile
  end
endif

date |& tee -a $outfile

rm -f $tmpfile


exit 0;
