#!/bin/csh -f
#+
# post_calib -- acquire calibration data for DEIMOS slitmask image(s)
#
# Purpose:
#	Given a list of DEIMOS images, acquire calibration data 
#	(arcs and/or flats) for each image at the same physical 
#	rotator position.  This should produce calibration data
#	which better match the images.
#
# Usage:
#	post_calib [-nofcs] [-arctime <n>] [-flattime <n>] \
#		[-n_arcs <n>] [-n_flats <n>] [-lamps values] \
#		[<image1> <image2> ... <imageN>]
# 
# Arguments:
#	imageN = name of image to calibrate
# 
# Switches:
#	-nofcs	= do not wait for FCS updates.  This is useful when
#		calibrating in a configuration with no FCS setup defined
#	-arctime = specify an xposure time to use for arcs [integer, default=1]
#	-flattime = specify an exposure time to use for flats 
#		[integer, default=12]
#	-n_arcs = number of arc exposures to take [integer; default=1]
#	-n_flats = number of quartz flat exposures to take [integer; default=3]
#	-lamps	= specify a comma-separated list of arc lamps to use 
#		for arc exposures [default is Ne,Ar,Kr,Xe]
#
# Output:
#	A report on the exposures is written to STDOUT on completion.
# 
# Side Effects:
#	Will close the hatch if required.  And leave it closed.
# 
# Restrictions:
#	The rotator must be unlocked and under observer control.
#
# Exit values:
#	 0 = normal completion
#	 1 = wrong number of arguments
#
# Example:
#	1) Acquire calibrations for a sequence of images at the same 
#	rotator positions at which the imatges were acquired:
#		post_calib d0927_0101.fits d0927_0104.fits d0927_0107.fits
#
#	1) Same, using non-standard flatfield time.
#		post_calib -flattime 6 d0927_0101.fits d0927_0104.fits d0927_0107.fits
#
#-
# Modification history:
#	2003-Sep-26	GDW	Original version
#-----------------------------------------------------------------------

# define defaults...
set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd [-nofcs] [-arctime <n>] [-flattime <n>] [-n_arcs <n>]\n[-n_flats <n>] [-lamps <values>]\n\t[image1 image2 ... imageN]"
set arctime = 1
set flattime = 12
@ n_arcs = 1
@ n_flats = 3
set lamps = ( Ne Ar Kr Xe )
set good_lamps = (Ar Kr	Xe Cd Ne Zn Hg )
set lamps_needing_warmup = (Cd Zn Hg)
set logfile = ${cmd}.log.$$
set usefcs = 1
set nsleep = 5	# default is to let lamps warm up for 5 sec
set image1 = NONE
set image2 = NONE
set image3 = NONE

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

    # check for nofcs flag...
    if ( "$1" == "-nofcs" ) then
	set usefcs = 0
	shift
	printf "Ignoring FCS\n"
	continue
    endif

    # check for arctime flag...
    if ( "$1" == "-arctime" ) then
	shift
	set arctime = $1
	shift
	printf "Using requested arctime of $arctime\n"
	continue
    endif

    # check for flattime flag...
    if ( "$1" == "-flattime" ) then
	shift
	set flattime = $1
	shift
	printf "Using requested flattime of $flattime\n"
	continue
    endif

    # check for n_arcs flag...
    if ( "$1" == "-n_arcs" ) then
	shift
	@ n_arcs = $1
	shift
	printf "Acquiring $n_arcs arc exposures\n"
	continue
    endif

    # check for n_flats flag...
    if ( "$1" == "-n_flats" ) then
	shift
	@ n_flats = $1
	shift
	printf "Acquiring $n_flats flat exposures\n"
	continue
    endif

    # check for lamp list...
    if ( "$1" == "-lamps" ) then
	if ( $#argv < 2 ) then
	    printf "$usage\n"
	    exit 1
	endif
	set list = `echo $2 | sed "s/,/ /g"`
	set lamps = ( $list )
	shift
	shift
	continue
    endif

    # no flags found; so quit processing flags...
    break
end

# parse args...
if ( $#argv >= 1 ) then
    set images = ( $* )
else
    printf "$usage\n"
    exit 1
endif

set slider = `slider`

# validate images...
foreach image ( $images )

    # complain if a purported image name begins with "-"
    # (probably a syntax error)
    if ( "$image" =~ \-* ) then
	printf "$usage\n"
	exit 1
    endif

    # complain if image is unreadable...
    if ( ! -e $image ) then
	printf "ERROR: cannot access image $image -- aborting\n"
	exit 1
    endif

    # complain if image is not a slitmask image...
    set buf = ( `fitshead $image slmsknam` )
    set slmsknam = $buf[$#buf]
    if ( "$slmsknam" == "None" ) then
	printf "ERROR: image $image is not a slitmask image -- aborting\n"
	exit 1
    endif

    # complain if we are on the wrong slider...
    set buf = ( `fitshead $image gratepos` )
    set gratepos = $buf[$#buf]
    if ( "$gratepos" != "$slider" ) then
	printf "ERROR: wrong slider for image $image; want $gratepos, but got $slider -- aborting\n"
	exit 1
    endif

end

# validate lamp request...
set lampstring = ""
foreach lamp ( $lamps )
    set lampstring = ${lampstring}$lamp
    set bad = 1
    foreach good_lamp ( $good_lamps )
	if ( "$lamp" == "$good_lamp" ) then
	    set bad = 0
	endif
    end

    if ( $bad == 1 ) then
	printf "ERROR -- $lamp is not a valid choice for an arc lamp\n"
	printf "\tValid selections are:"
	foreach good_lamp ( $good_lamps )
	    printf " %s" $good_lamp
	end
	printf "\n"
	exit 1
    endif

    # check whether warmup required...
    foreach test ( $lamps_needing_warmup )
	if ( "$lamp" == "$test" ) then
	    set nsleep = 180
	endif
    end
end

# verify logfile...
touch $logfile >& /dev/null
if ( $status != 0 ) then
    set logfile = /tmp/$logfile
    touch $logfile >& /dev/null
    if ( $status != 0 ) then
	printf "ERROR -- cannot open logfile $logfile\n"
	beep 3
	exit 1
    endif
endif
printf "%-12s %-12s %-16s %s\n" "Mask" "RotAng" "Arc" "Flats" >> $logfile
printf "%-12s %-12s %-16s %s\n" "------------" "------------" "----------------" "-----------------------------------" >> $logfile

# close hatch if required...
set hatch = `show -s deimot -terse hatchpos`
if ( "$hatch" != "closed" ) then
    printf "WARNING -- hatch is open, so I'm going to close it...\n"
    modify -s deimot hatchpos=closed
    if ( $status ) then
	printf "ERROR while attempting to close hatch -- abort"
	exit 1
    endif
endif

# loop over masks...
onintr abort

# save the todisk state...
set todisk_old = `show -s deiccd -terse todisk`
modify -s deiccd todisk=t

# initialize variables...
set bad_masks = ()
set good_masks = ()
set current_lamps = ""
foreach image ( $images )

    # close main shutter to protect CCD while slitmask changes...
    modify -s deiccd cshutter=f	

    # determine PA to use...
    set buf = ( `fitshead $image rotatval` )
    set rotatval = $buf[$#buf]

    # move the rotator...
    rotang $rotatval
    if ( $status != 0 ) then
	printf "ERROR: rotator move failed --- aborting\n"
	exit 1
    endif

    # determine mask to use...
    set buf = ( `fitshead $image slmsknam` )
    set mask = $buf[$#buf]

    # select the specified mask...
    slitmask $mask
    if ( $status != 0 ) then
	printf "ERROR selecting mask $mask --- skipping\n"
	beep 3
	set bad_masks = ( $bad_masks $mask)
	continue
    endif

    # wait for FCS to track...
    if ( $usefcs == 1 ) then
	lamps off
	set current_lamps = off
	modify -s deiccd cshutter=t	# open shutter for FCS
	printf "Waiting for FCS to track..."
	waitfor -s deifcs fcssta = Tracking
    endif
    modify -s deiccd cshutter=f	# close main shutter to allow lamps to turn on
    if ( $status != 0 ) then
	printf "ERROR closing shutter -- you may need to interrupt FCS in order to continue\n"
	beep 3
	exit 1
    endif

    # turn on arc lamps...
    if ( $n_arcs > 0 && "$current_lamps" != "arcs" ) then
	modify -s deimot lamps="$lamps"
	if ( $status != 0 ) then
	    printf "ERROR turning arc lamps on --- skipping\n"
	    beep 3
	    set bad_masks = ( $bad_masks $mask)
	    continue
	endif
	set current_lamps = arcs

	printf "Waiting $nsleep seconds for lamps to warm up"
	sleepdots $nsleep
    endif

    # acquire arc images...
    if ( $n_arcs > 0 ) then
	tint $arctime
	set description = "$lampstring arc $mask"
	object $description
	spectral
	modify -s deiccd obstype="Line"
	set image1 = `nextimage -tail`
	goi $n_arcs
    endif

    # acquire flats...
    if ( $n_flats > 0 ) then
	modify -s deimot lamps="Qz"
	if ( $status != 0 ) then
	    printf "ERROR turning Qz lamp on --- skipping\n"
	    beep 3
	    continue
	endif
	set current_lamps = qz
	tint $flattime
	sleep 5
	set description = "IntFlat $mask"
	object $description
	spectral
	modify -s deiccd obstype="IntFlat"
	set image2 = `nextimage -tail`
	goi $n_flats
	waitfor -s deiccd wdisk=f
	set image3 = `lastimage -tail`
    endif

    # log results...
    printf "%-12s %12.1f %-16s %s\n" "$mask" "$rotatval" "$image1" "$image2 - $image3" >> $logfile

    # add to list of good masks...
    set good_masks = ( $good_masks $mask)
end

abort:

# restore state...
modify -s deiccd todisk=$todisk_old
lamps off

# print report...
printf "Log of observations:\n\n"
cat $logfile
printf "\n"
\rm $logfile

printf "The following masks were completed successfully:\n"
if ( $#good_masks > 0 ) then
    foreach mask ( $good_masks )
	printf "\t%s" $mask
    end
else
    printf "\t%s" NONE
endif
printf "\n"

if ( $#bad_masks > 0 ) then
    printf "The following masks were NOT completed due to errors:\n"
    foreach mask ( $bad_masks )
	printf "\t%s" $mask
    end
    printf "\n"
else
    printf "There were no errors reported --- all masks completed OK.\n"
endif
    
# script_done
exit
