#!/bin/csh -f
#+
# tvfocloop -- increment TV focus when images are saved
#
# Purpose:
#	Move the TV focus through a series of values, pausing at
#	each focus position until new camera image(s) have been saved.
#
# Usage:
#	tvfocloop [-wait n] <start> [n [incr]]
# 
# Arguments:
#	-wait = wait for <n> camera images to appear before moving (default=1)
#	start = starting tv focus position (units)
#	n     = number of focus positions to test (default=7)
#	incr  = increment in focus [mm] (default=20 units)
# 
# Output:
# 
# Restrictions:
#	The script will not actually *take* the TV guider frames; 
#	this must be done by the OA using Xguide.
# 
# Exit values:
#	0 = normal completion
#	1 = wrong number of arguments
#	3 = start and/or incr are not valid floats
#	4 = n too large
#
# Example:
#
#	1) To acquire TV guider frames in the least painful manner, 
#	ask the OA to save a sequence (perhaps 30) of guider frames,
#	then execute the script, specifying that the script will pause
#	until TWO new images have been written:
#		tvfocloop -wait 2 900 11 20
#-
# Modification history:
#       2002-Jul-02     GDW     Original version
#-----------------------------------------------------------------------

# define defaults...
set nwait = 1
set incr = 20
@ n = 7
@ n_max = 100

set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd start [n [incr]]"

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

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

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

end

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

# grab arguments...
if ( $#argv >= 1 ) then
    set start = $1
    shift
endif
if ( $#argv >= 1 ) then
    set n = $1
    shift
endif
if ( $#argv >= 1 ) then
    set incr = $1
    shift
endif

# validate args...
is_float $start $incr > /dev/null
if ( $status ) then
  echo "ERROR -- start and/or incr are not valid floats"
  exit 3
endif

if ( $n > $n_max ) then
  echo "ERROR --- n too large (max is $n_max)"
  exit 4
endif

# acquire data...
@ i = 0
while ( $i < $n )

    # compute new TV focus position...
    set focus = `calc "$start + $i*$incr"`

    # change tv focus...
    tvfocus $focus > /dev/null

    # wait for the new guider image(s) to appear...
    @ j=0
    while ( $j < $nwait )
	set tvimage = `wftv`
	@ j++
    end

    # report position and corresponding image name...
    printf "%s" `tvfocus`
    printf "\t%s" $tvimage
    printf "\n"

    # increment...
    @ i ++
end
