#!/usr/bin/perl
#
# $Id: sxpar 17973 2012-02-10 19:06:45Z weaver $
#
# Parse FITS header
# D. Finkbeiner 2001 Dec 20
#
# Example:
# sxpar /u/dfink/idR-001331-z1-0278.fit TAI
#
# If the COMMENT keyword is selected, prints ALL comments.
#
use warnings;
use strict;

my $fname = $ARGV[0];
my $card  = uc $ARGV[1];
die "No card name specified!" unless $card;
if ($fname ne '-') {
    die "File not found: $fname" unless -e $fname;
}
open RLUN, $fname or die "Cannot read file: $fname\n";
my $atend = 0;
my $fits = 0;
my $buf;
while (! $atend) {
    for my $i (1 .. 36) {
        read RLUN, $buf, 80;
        my ($key, $val) = split("=| " , $buf);
        $fits = 1 if $key eq 'SIMPLE';
        $atend = 1 if $key eq 'END';
        if ($key eq $card) {
            if ($key eq "COMMENT") {
                printf "%s\n", $buf
            } else {
                my ($key, $val, $comment) = split("=|/" , $buf);
                $val =~ s/^[\s|\']+//;
                $val =~ s/[\s|\']+$//;
                printf "%s\n", $val;
                close RLUN;
                exit;
            }
        }
    }
    if (! $fits) {
        print STDERR "Corrupted FITS file?  No SIMPLE keyword in header!\n";
        exit 1;
    }
}
close RLUN;
