#!/bin/csh -f
#
# ima-getfirstimg - gets the first image number given 
#    the ima series and run number.
#
# The script gets the first image in the alphabetically sorted
# list of all images in the series/run.  The image number is extracted
# from this image.  This image number is decremented and used to 
# create a new file name.  If this file exists, the image number is
# decremented again.  Decremation continues until the file does not 
# exist indicating that the first image in the run has been reached.
# It was necessary to do it this way so as to avoid reading in 1000's
# of file names.
#

set VERSION = '$Id';

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:

set imadir = `dirname $imastem`;
if(! -d $imadir ) then
  echo "ERROR: cannot find $imadir"
  exit 1;
endif

pushd $imadir > /dev/null;

set imarunstem = $imastem-$imarun;

## get the first in the alphabetically sorted list ##
set tmp0 = `ls $imarunstem-* | head -n 1`;
if($#tmp0 == 0) then
  echo "ERROR: no images found"
  exit 1;
endif

## extract the series, run, and imageno ##
set sri = `ima-parse-name $tmp0`;
set imgno = $sri[3];

## count imgno backwards until does not exist ##
while( -e $tmp0 )
  @ imgno = $imgno - 1;
  set tmp0 = $sri[1]-$sri[2]-$imgno.ima
  # echo $tmp0
end

@ imgno = $imgno + 1;
echo $imgno;

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 imastem = $argv[1]; shift;
      breaksw

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

    case "-umask":
      if ( $#argv == 0) goto arg1err;
      umask $argv[1]; shift;
      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($?imastem == 0) then
    echo "ERROR: must spec a stem"
    exit 1;
  endif

  if($?imarun == 0) then
    echo "ERROR: must spec a run"
    exit 1;
  endif

goto check_params_return;

############--------------##################
usage_exit:
  echo "USAGE: ima-getfirstimg -i imastem -r imarun"
exit 1;
