#!/bin/csh

# File zmachcatlist
# By Jessica Mink, Harvard-Smithsonian Center for Astrophysics
# May 23, 2019

if ($#argv == 0) then
    echo "ZMACHCATLIST: Catalog archived Z-Machine data from list of spectrum files"
    echo "           Version 1.0 by Jessica Mink, SAO-TDC, May 23, 2019"
    echo "           Usage: zmachcatlist [-h][file containing a list of file paths]"
    echo "                  -h: Do not print 2-line header"
    exit
    endif

if ( $1 == "-h" ) then
    shift

# Print tab-separated file header
else
    cat zmachcatlist.head
endif

# Create internal list of files from file list file
set filelist=$1
#echo "ZMACHCATLIST: Cataloging Z-Machine spectrum files in $1"

# Catalog spectrum data files
foreach file (`cat $filelist`)
#    echo "File is $file"

# Extract parameters from spectrum FITS file header
    set catline0=`gethead -tub $file object ra dec hjdn exposure rfn`
#    echo $catline0
    set object=`echo $catline0 | getcol stdin 1`
    set ra=`echo $catline0 | getcol stdin 2`
    set dec=`echo $catline0 | getcol stdin 3`
    set hjd=`echo $catline0 | getcol -d 5 stdin 4`
    set exp=`echo $catline0 | getcol stdin 5`
    set rfn=`echo $catline0 | getcol stdin 6`

# Compute wavelength limits from first and last pixel of spectrum
    set wls=`listspec $file printlim+ columns="w"`
    set nwl=`echo $wls | wc -l`
    if ( $nwl == "0" ) then
	set wl1="___"
	set wl2="___"
    else
	set wl=`echo $wls | tr "\\n" " "`
	set wl1=`echo $wl | getcol -d 3 stdin 1` 
	set wl2=`echo $wl | getcol -d 3 stdin 2` 
    endif
#    echo $rfn $wl : $wl1 $wl2

# Read cross-correlated radial velocity, error, and quality from file header
    set vel=`gethead -utbn 3 $file velocity`
    set velr=`gethead -utbn 3 $file czxcr`
    set qcstat=`gethead -utbn 3 $file qcstat`

# Build catalog line
#    echo "$object\t$ra\t$dec\t$hjd\t$wl1\t$wl2\t$vel\t$velr\t$qcstat\t$exp\t$rfn\t$file"
    set catline="$object\t$ra\t$dec\t$hjd\t$wl1\t$wl2\t$vel\t$velr\t$qcstat\t$exp\t$rfn\t$file"
    echo "$catline"
    end

exit 0

# May 23 2019	New program based on FASTCATLIST
