#!/bin/csh -f
#+
# fcs_tint -- set or show the FCS integration time
#
# Purpose:
#	Change the FCS integration time to the specified value by
#	stopping FCSTRACK, changing the value of the integration time
#	parameter in the FCS reference file, and restarting FCSTRACK
#
# Usage:
#	fcs_tint [tint]
# 
# Arguments:
#	tint = number of seconds to exposure per RFCS integration
# 
# Output:
#	If FCSTRACK is restarted, this window will receive copious 
#	amounts of text from the script.
# 
# Side effects:
#	If FCSTRACK is running, it is stopped and restarted.
# 
# Restrictions:
#	User must have permission to modify the current FCS reference file. 
# 
# Exit values:
#	 0 = normal completion
#	 1 = wrong number of arguments
#
# Example:
#	1) show the current FCS integration time:
#		fcs_tint
#
#	1) set the current FCS integration time to 10 seconds:
#		fcs_tint 10
#
#-
# Modification history:
#	2003-Jan-05	GDW	Original version
#-----------------------------------------------------------------------

set buf = $0
set cmd = $buf:t
set usage = "Usage: $cmd [value]"

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

# parse args...
if ( $#argv >= 1 ) then
    set tint = $1
    shift
endif

# report tint if no value passed to script...
if ( ! $?tint ) then
    show -s deifcs -terse ttime
    exit 0
endif

# locate the file...
set outdir = `show -s deifcs -terse outdir`
if ( ! -e $outdir ) then
    printf "ERROR: couldn't find FCS outdir $outdir\n"
    exit 1
endif

# determine the most recent logfile in the directory...
set logfile = `fcs_logfile`
if ( $status ) then
    printf "ERROR: no FCS logfiles found\n"
    exit 1
endif

# convert logfile into reference file...
set reffile = ${logfile:r}.ref
if ( ! -e $reffile ) then
    printf "ERROR: couldn't find FCS reference file $reffile\n"
    exit 1
endif

# create a backup copy...
@ i=1
while ( 1 )
    set backup = ${reffile}_$i
    if ( ! -e $backup ) then
	break
    endif
    @ i++
end
cp $reffile $backup

# modify the reference file...
set tempfile = /tmp/${reffile:t}_$$
awk 'NR==9{print tint;next}{print}' tint=$tint $reffile > $tempfile

# stop FCSTRACK if it is running...
get_deimos_pid fcstrack > /dev/null
if ( $status == 0 ) then
    stop_fcstrack
    set restart_fcs = 1
endif

# go to the FCS directory...
chdir $outdir

# make 10 attempts to replace the file...
@ i=0
while ( $i <= 10 )
    \mv $tempfile $reffile
    if ( $status == 0 ) then
	break
    endif
    sleep 1
    @ i++
end

# modify the keyword...
modify -s deifcs ttime=$tint

# restart FCS as desired...
if ( $?restart_fcs ) then
    fcstrack > /dev/null &
endif
