#!/bin/csh -f
#+
# cycle_shutter -- perform an open/close sequence on the DEIMOS CCD shutter
#
# Name:
#	cycle_shutter [n]
# 
# Type:
#	C-shell script
# 
# Purpose:
#	perform a close-open-close sequence on the DEIMOS CCD
#	shutter.  This action is often useful in freeing a stuck
#	shutter, thus recovering from the common error condition in
#	which the datataking system refuses to start an exposare.
# 
# Invocation:
#	cycle_shutter [n]
# 
# Inputs:
#	n = number of times to cycle shutter.  IF n<1 we cycle until
#	the shutter operates successfully or a max of n tries.
# 
# Exit status:
#	0 = normal completion
#	1 = error
#-
# Modification history:
#	1999-Oct-13	GDW	Original version (LRIS)
#	2004-Feb-15	GDW	Adapted for DEIMOS
#	2005-Apr-13	GDW	Added n<0 option
#-----------------------------------------------------------------------

# define usage...
set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd [n]"
set n_sleep = 5

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

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

# initial return state is "good"...
set stat = 0

# process case of n<0...
if ( $n < 0 ) then
    set stop_on_success = 1
    @ n = -1 * $n
endif

# start loop...
@ i = 1
modify -s deiccd cshutter=0	# close
while ( $i <= $n )
    set stat = 0

    sleep 1
    modify -s deiccd cshutter=1	# open
    if ( $status != 0 ) set stat = 1

    sleep 1
    modify -s deiccd cshutter=0	# close
    if ( $status != 0 ) set stat = 1

    # exit on success if requested...
    if ( $stat == 0 && $?stop_on_success ) exit 0

    @ i++

    # if the shutter faield to open/close this time, 
    # wait a moment before trying again in order
    # to allow air pressure to build up...
    if ( $stat ) then
	echo "Pausing $n_sleep seconds before trying shutter again..."
	sleep $n_sleep
    endif
end

# check result...
if ( $stat ) then
    echo "ERROR: last shutter open/close attempt failed"
    exit 1
endif
