#!/bin/csh -f
#+
# lastfcsimage -- return full disk name of the most recent FCS image
#
# Purpose:
#	Seeks the newest image in the current FCS output
#	directory, and returns its full disk name.
#
# Usage:
#	lastfcsimage [-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:
#		lastfcsimage
#	returns:
#		
#
#	2) Return the tail of the latest image:
#		lastfcsimage -tail
#	returns 
#		
#-
# Modification history:
#	2003-Feb-05	GDW	Original version
#	2005-Oct-26	GDW	Rewrote to fix bug with huge directories 
#-----------------------------------------------------------------------

# 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 deifcs -terse outdir`
if ( $status ) exit $status

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

# 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