#!/bin/csh -f
#+
# wfi -- wait for new DEIMOS FCS image to be written to disk
#
# Purpose:
#	With no argument, wait for a new FCS image to be written to disk 
#	in the FCS output directory, and print the name of the image to STDOUT.
#	With an argument, loop until the given number of images is written.
#
# Usage:
#	wfi [-nowait] [-silent] [n]
# 
# Arguments:
#	-nowait = do not wait if image not in progress; return immediately
#	-silent = do not print image name
#	n = number of images to wait for [default=1]
# 
# Output:
#	Full image name is written to stdout.
# 
# Restrictions:
#	- If started during image readout, will not return the current image
# 
# Exit values:
#	0 = normal completion
#	1 = wrong number of arguments
#
# Example:
#	1) Wait until next FCS image has been written to disk:
#		wfifcs
# 
#	2) Wait until 5 FCS images have been written to disk:
#		wfifcs 5
# 
# 	3) Wait only if an image is being taken...
#		wfifcs -n
#
#-
# Modification history:
#	2005-Dec-18	GDW	Original version; adapted from wfi
#-----------------------------------------------------------------------

set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd [-silent] image"
set verb = 1
set image = default
@ n = 1

# parse flags...
while ( $#argv > 0 )

  # check for -nowait flag...
  if ( "$1" =~ \-n* ) then
    set nowait=1
    shift
    continue
  endif

  # check for silent flag...
  if ( "$1" =~ \-s* ) then
    set verb = 0
    shift
    continue
  endif

  # exit flag check if no flags remain...
  break

end

# verify args...
if ( $#argv > 1 ) then
    echo "$usage"
    exit 1
endif

# parse args...
if ( $#argv >= 1 ) then
    @ n = $1
    shift
endif

# in no-wait mode we return immediately if no image is in progress...
if ( $?nowait ) then
    set buf = ( `show -terse -s deifcs eraseip exposip pauseip wcrate wdisk` )
    if ( "$buf" !~ *true* ) exit 0
endif

# loop until (a) the specified number of images is written,
# or (b) a new image is written... 
@ i = 0
while ($i < $n)
    @ i++
    waitfor -s deifcs wcrate = t
    waitfor -s deifcs wcrate = f
    waitfor -s deifcs wdisk = t
    waitfor -s deifcs wdisk = f
end

# echo name if desired...
if ( $verb ) then
    lastfcsimage
endif
exit
