#!/bin/csh -f
# this script is run by jsf-halfm telrun after each new raw image has been
# created.
# usage:
#   postprocess fullpath cal scale
#
# 1) if cal > 0, apply image corrections, add wcs and fwhm to file
# 2) if scale > 0 fcompress file, rename to .fth, discard .fts file
# 3) inform camera of new file

if ($#argv != 3) then
    jd -t; echo " Bad args"": " $argv
    jd -t; echo " $0"": " "fullpath corrections scale" 
    exit 1
endif

set node = "datar3";

set file = "$argv[1]"
set filet = "$file:t"":"
set file0 = $file:r"00".$file:e
set file1 = $file:r"01".$file:e
set cal = "$argv[2]"
set scale = "$argv[3]"

echo ""
jd -t; echo " $filet Starting postprocessing"

# 1) if cal > 0, apply image corrections, add wcs and fwhm to file
if ("$cal" > 0) then
    jd -t; echo " $filet Applying image corrections"
    rsh $node calimage -C $file
    jd -t; echo " $filet splitting into" $file0:t $file1:t
    rsh $node crop -p 0 0 2048 4096 -p 2048 0 2048 4096 $file
    jd -t; echo " $filet Adding WCS headers"
    rsh $node wcs -wu .3 $file0
    rsh $node wcs -wu .3 $file1
else
    jd -t; echo " $filet No image corrections requested"
endif

# 2) if scale > 0 fcompress file, rename to .fth, discard .fts file
if ("$scale" > 0) then
    jd -t; echo " $filet Compressing with scale $scale"
    # fcompress -r adds HCOMSTAT and HCOMSCAL fits headers and removes the .fts.
    # it also refuses to overwrite an existing .fth file which can happen for
    # repeats.
    rm -f "$file0:r".fth
    rsh $node fcompress -s $scale -r $file0
    rm -f "$file1:r".fth
    rsh $node fcompress -s $scale -r $file1
    set file = "$file0:r".fth
endif

jd -t; echo " $filet Postprocessing complete"

# 3) inform camera of new file   TODO fifo over NFS??
# if (! $?TELHOME) setenv TELHOME /usr/local/telescope
# set camfifo = $TELHOME/comm/CameraFilename
# if (-w $camfifo && -p $camfifo) then
#    jd -t; echo " $filet Informing Camera (if any)"
#    # N.B. echo hangs if there is no camera running with the fifo open
#    (echo $file >> $camfifo & sleep 5; kill %1) >& /dev/null
#endif

exit 0

# For RCS Only -- Do Not Edit
# @(#) $RCSfile: postprocess,v $ $Date: 2003/04/15 20:48:25 $ $Revision: 1.1.1.1 $ $Name:  $
