#!/bin/csh -f
# given one .fts or .fth file, pull out some fields and print each
# separated by pipes (|) to form a simple database entry. The fields are, in
# order: OBJECT|FILTER|DATE-OBS|TIME-OBS|EXPTIME|RA|DEC|filename
# 22 Jul 96  Begin
# 25 Jul 96  Always print all the |, even if one or more fields are blank.
# 29 Oct 96  Allow for UTC-DATE and UTC-TIME too (only in circa 1994 files)

# exactly one arg is required .. namely, the filename
if ($#argv != 1) then
    set col = \:
    echo "$0$col fits_file"
    exit 1
endif

# store filename in fn
set fn = $argv[1]

# must use a ugly tmp files so we can scan for fields in specific order.
set tmpi = /tmp/$$.fli
set tmpo = /tmp/$$.flo

# can't get an apostrophe directly inside a string
set ap = \'

# remove tmp files if killed early
onintr out

# read the header once into tmpi
# this handles .fts and .fth
fitshdr -p $fn > $tmpi

# extract the desired fields in the desired order into tmpo.
# N.B. add the field separators even if the field does not exist.
awk -F$ap '/^OBJECT  / {printf "%s", $2}' < $tmpi >> $tmpo; echo -n \| >> $tmpo
awk -F$ap '/^FILTER  / {printf "%s", $2}' < $tmpi >> $tmpo; echo -n \| >> $tmpo
awk -F$ap '/^DATE-OBS/ {printf "%s", $2}\
	   /^UTC-DATE/ {m=substr($2,1,2); d=substr($2,4,2); y=substr($2,7,2); \
			printf "%02d/%02d/%02d", d, m, y}' < $tmpi >> $tmpo; echo -n \| >> $tmpo
awk -F$ap '/^TIME-OBS|^UTC-TIME/ {printf "%s", $2}' < $tmpi >> $tmpo; echo -n \| >> $tmpo
awk -F$ap '/^EXPTIME / {printf "%d", substr($1,25,6)+0}' < $tmpi >> $tmpo;
    echo -n \| >> $tmpo
awk -F$ap '/^RA      / {printf "%s", $2}' < $tmpi >> $tmpo; echo -n \| >> $tmpo
awk -F$ap '/^DEC     / {printf "%s", $2}' < $tmpi >> $tmpo; echo -n \| >> $tmpo

echo $fn >> $tmpo

# preen off extra stuff and print
sed -e "s/$ap//g" -e 's/ *|/|/g' < $tmpo

out:
rm -f $tmpi $tmpo
