#!/bin/sh
#
# From sla@umbra.UCSC.EDU Fri Aug  6 22:42:01 1993
# From: sla@umbra.UCSC.EDU (Steve Allen)
# Newsgroups: sci.astro.fits
# Subject: shell tools for FITS files, part III
# Date: 6 Aug 1993 05:46:49 GMT
# Organization: UCO/Lick Observatory
# NNTP-Posting-Host: umbra.ucsc.edu
# Summary: print value of a single keyword
# Keywords: Bourne shell, Un*x, awk, sed
# 
# Here is yet one more little shell tool for FITS files.  Given
# a keyword on the command line, it picks out the value of that
# keyword and prints it.  There is lots of room for improvement
# of this script, but it works.
# 
#                       fitskey
#       A little bourne shell script which acts like fgrep for FITS keywords.
#       It only looks in the primary header; extensions are ignored.
#       Author: Steve Allen (sla@lick.ucsc.edu) 1993
#       It takes as input a FITS file, and prints out the FITS key
#       values associated with the given FITS keyword.
#       Could be enhanced to look at XTENSIONs, and to optionally print
#       the keyword itself and/or the comment field.  It also produces
#       stupid output if there is more than one identical keyword.
#
if [ $# -lt 1 ]; then
    echo "Usage: $0 FITSkeyword [FITSfile ...]" >&2
    exit 1
fi

# a legal FITS key must be 8 characters long with explicit trailing spaces
# the awk script here ensures that arrangement
# find a quoted string (but not one which contains quotes!)
seds=`echo $1 | awk '{printf("s&^%-8.8s= *\(%c[^%c]%c\)&\1&p",$1,39,39,39)}'`
# echo seds is $seds
# find a value followed by a comment
sedc=`echo $1 | awk '{printf("s&^%-8.8s= *\(.*\)/.*&\1&p",$1)}'`
# echo sedc is $sedc
# find a value not followed by a comment
sedv=`echo $1 | awk '{printf("s&^%-8.8s= *\(.*\)&\1&p",$1)}'`
# echo sedv is $sedv
shift                   # throw away the FITS keyword in the first argument
sedq='/^END */q'        # detect end of primary fits header (even if from Lick)

if [ -z "$*" ] ; then
    # act like a pipeline element
    ( dd conv=unblock cbs=80  | sed -n -e "$sedq" -e "$seds" -e t -e "$sedc" -e t -e "$sedv" ) 2>/dev/null
else
    for file in $* ; do
	keyval=`dd cbs=80 conv=unblock if=$file 2>/dev/null | \
	sed -n -e "$sedq" -e "$seds" -e t -e "$sedc" -e t -e "$sedv"`
	if [ ! -z "$keyval" ]; then
	    if [ $# -gt 1 ]; then
		echo $file": "$keyval
	    else
		echo $keyval
	    fi
	fi
    done
fi
# ______________________________________________________________________________
# Steve Allen          | That was the equation!         |   sla@lick.ucsc.edu
# UCO/Lick Observatory | Existence!...Survival must     |If the UC were opining,
# Santa Cruz, CA 95064 | cancel out programming! -- Ruk | it wouldn't use me.

