#!/bin/csh -f
#+
# lastfile -- return the FRAMENO for the last saved image
#
# Purpose:
#	Check the OUTDIR directory for the highest numbered
#	*.fits file, and return that value.
#
# Usage:
#	lastfile
# 
# Arguments:
#	none
#
# Output:
#	index number of the last image (leading zeros removed), or
#	0 if no images were found in directory, or
#	-1 if output directory was not found
#
# Exit values:
#	 0 = normal exit
#	 1 = no images found
#	-1 = output directory not found
#
# Example:
#	To get the frame number of the last image taken, type:
#		lastfile
#-
# Modification history:
#	Date unknown	???	Original version
#	2000-Jul-01	GDW	Added commments
#       2002-Jun-06     GDW     Adapted for DEIMOS
#-----------------------------------------------------------------------

set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd"

# verify args...
if ( $#argv > 0 ) then
  printf "$usage\n"
  exit 1
endif

# get the current outfile...
set outfile = `show -s deiccd -terse outfile`
if ( $status ) exit $status

# get the current outdir...
set outdir = `show -s deiccd -terse outdir`
if ( $status ) exit $status

if (-e $outdir) then

  # define pattern...
  set dollar = '$'
  set pattern = "^${outfile}.*\.fits${dollar}"

  # parse the list of all files in the output directory, and let Perl
  # extract the digits in between "$outfile" and ".fits".  The resulting 
  # list of numbers is sorted numerically and the last one 
  # extracted using "tail".
  # Note that using "@" will cause Csh to interpret the result as an
  # integer, hence stripping off leading zeros.  A null value is
  # interpreted as "0"...
  @ x = `\ls -1 $outdir | perl -ne "m/${outfile}"'(\d+).fits$/;print "$1\n"' | sort -n | tail -1`

  echo $x
  exit

else
  # output directory not found...
  echo -1
  exit -1
endif
