#!/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 spec|imag [-tail]
# 
# Arguments:
#       spec  = find last spec image in soutdir
#       imag  = find last imag image in ioutdir
#	-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 = spec or imag mode not specified
#	 2 = 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
#       2010-Sep-21     jlyke   Adapt for OSIRIS
#-----------------------------------------------------------------------

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

# check flags...
switch ($1)
    case "S*":
    case "s*":
	set M = "s"
	set mode = "spec"
	breaksw
    case "I*":
    case "i*":
	set M = "i"
	set mode = "imag"
	breaksw
    default:
	printf "$usage\n"
	exit 1
	breaksw
endsw
shift

if ( $1 == "-tail" ) then
    set tail = 1
    shift
endif


# get the current outdir...
set outdir = `show -s osiris -terse ${M}outdir`
if ( $status ) exit $status

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

# get count of files in $outdir and last file if appropriate
set count = `ls -1t $outdir | awk '/\.fits$/{print}' | wc -l`
switch ($count)
    case 0:
	# no images found
	exit 2
	breaksw
    case 1:
	set file = `ls -1t $outdir | awk '/\.fits$/{print}'`
	if ( -z $outdir/$file ) then
	    # image in progress, none on disk
	    exit 2
	    breaksw
	endif
	breaksw
    default:
	set list = `ls -1t $outdir | awk '/\.fits$/{print}' | head -2`
	if ( -z $outdir/$list[1] ) then
	    # image in progress
	    set file = $list[2]
	else
	    set file = $list[1]
	endif
	breaksw
endsw

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