#!/bin/csh -f
#+
# lastimage -- return full disk name of the most recently acquired image
#
# Purpose:
#	Seeks the newest image in the current output
#	directory, and returns its full disk name.
#
# Usage:
#	lastimage [-tail]
# 
# Arguments:
#	-tail = print only the tail of the filename
# 
# Output:
#	The full or tail of the disk name is echoed to stdout
# 
# Exit values:
#	 0 = normal exit
#	 1 = no images found
#	-1 = output directory not found
#
# Example:
#	1) Return the full name of the latest image:
#		lastimage
#	returns:
#		/dsk/iraid1/kics/2002jun06/d0606_0045.fits
#
#	2) Return the tail of the latest image:
#		lastimage -tail
#	returns 
#		d0606_0045.fits
#-
# Modification history:
#	2000-Nov-15	GDW	Original version
#	2001-May-07	GDW	Added "-tail" option
#	2002-Jun-06	GDW	Adapted for DEIMOS
#	2002-Oct-04	GDW	Removed OUTFILE check to pickup backup.fits
#	2005-Oct-26	GDW	Fix bug with long directory names
#	2013-Aug-31	GDW	Prepend /s
#-----------------------------------------------------------------------

# define usage...
set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd [-tail]"
set tail = 0

# check flags...
if ( $1 == "-tail" ) then
    set tail = 1
    shift
endif

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

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

# abort if output directory not existing...
if (! -e $outdir) exit -1

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

# get disk name of latest file...
set buf = `\ls -1t $outdir | awk '/\.fits$/{print;exit 1}'`
if ( $status != 1 ) exit 1

# return only tail if requested...
if ( $tail ) then
    echo $buf
else
    echo $outdir/$buf
endif