#!/usr/bin/perl

# Routine to read the separate astrometry files and combine the data into a
# single files for each monthly directory.
#
#  Format: % maketab <date_dir>
#
# 21 April 2006, A.C.Raugh
#
#============================================================================
# Constants needed to write the label:

$product_id   = "\"ASTR$ARGV[0].TAB\"";
$product_name = "\"ASTROMETRY TABLE, $ARGV[0]\"";
$product_time = "2006-04-25";
$row_bytes    = 379;

# General Method:
#
#   o  Open the date directory
#   o  Loop through header files in order of file name
#   o  Read from header:
#        DATE-OBS & TIME-OBS and convert to ISO time
#        Latitude and longitude of observatory - convert to decimal
#        FILE-NUM
#        SYSTEM
#   o  Open and read data file
#   o  Output table record
#
#  Save time from first and last file times for label.

if (@ARGV != 1)
  { die "Usage: maketab date_dir\n"; }

$date = $ARGV[0];
opendir(DATE,$date) || die "Could not open $date ($!)";
open (MON,"| fixlen -c -r $row_bytes > astr$date.tab") || 
   die "Could not open output file ($!)";

$rows = 0;

foreach $file (sort (readdir DATE))
  { next if ($file !~ /\.hdr/);

    $rows++;

    # Save the file name without extension:

    $filename = $file;
    $filename =~ s/\.hdr//;
    open (HDR,"$date/$file") || die "Could not open $date/$file ($!)";
    
    # All the FITS headers have exactly the same format, so we can
    # read directly to the values that we need:

    read(HDR,$junk,400);

    # FILE-NUM:

    read(HDR,$line,80);
    $line =~ /.*=\s+([0-9]+) /;
    $file_num = $1;

    # DATE-OBS:

    read(HDR,$line,80);
    $line =~ /.*= '(.*)'/;
    $date_obs = $1;
    ($dd,$mm,$yy) = split(/\//,$date_obs);
    $date_obs = sprintf "%4d-%02d-%02dT",$yy+1900,$mm,$dd;

    # TIME-OBS:

    read(HDR,$line,80);
    $line =~ /.*= *(\S+) /;
    $time_obs = $1;
    $time = 24.0 * $time_obs;
    $hh = int($time);
    $time = ($time - ($hh * 1.0)) * 60.0;
    $mm = int($time);
    $ss = ($time - ($mm * 1.0)) * 60.0;
    $time = sprintf "%02d:%02d:%06.3f", $hh, $mm, $ss;

    $utc_time = $date_obs . $time;

    # If we haven't saved a START_TIME yet, do it:

    if (! $start_time)
      { $start_time = $utc_time; }

    read(HDR,$junk,160);

    # Longitude and latitude of the observatory:

    read (HDR,$line,80);
    $line =~ /^.*'(.+)'/;
    $tmp = $1;
    ($dd,$mm,$ss) = split(/\//,$tmp);
    $tmp = ($dd*1.0) + ($mm/60.0) + ($ss/3600.0);
    $obslong = sprintf "%9.5f", $tmp;

    read (HDR,$line,80);
    $line =~ /^.*'(.{1})(.+)'/;
    $obslat_sign = $1;
    $tmp = $2;
    ($dd,$mm,$ss) = split(/\//,$tmp);
    $tmp = ($dd*1.0) + ($mm/60.0) + ($ss/3600.0);
    $obslat = sprintf "%1s%8.5f", $obslat_sign, $tmp;

    # In some cases, latitudes were calculated from the parallax 
    # constants, resulting in values with degraded precision. This
    # is detectable by a value of zero in the arcseconds field.
    # We'll check for this and set a flag:

    $lat_calc = ($ss = 0)? "C" : "-";

    # SYSTEM

    read(HDR,$line,80);
    $line =~ /^.*'(.+)'/;
    $system = $1;

    close(HDR);

    #*** Now read the data file:

    open(DAT,"$date/$filename.dat") || die "Could not open $filename.dat ($!)";

    read(DAT,$line,80);

    # Julian date:

    $jday = substr($line,0,13);

    # Right Ascension and Declination:

    $hh = substr($line,21,2);
    $mm = substr($line,23,2);
    $ss = substr($line,25,5);
    $ra = sprintf "%8.5f", (($hh*1.0) + ($mm/60.0) + ($ss/3600.00)) * 15.0;


    $sg = (substr($line,30,1) eq "-")? -1.0 : +1.0;
    $dd = substr($line,31,2);
    $mm = substr($line,33,2);
    $ss = substr($line,35,5);
    $dec = sprintf "%9.5f", (($dd*1.0)+($mm/60.0)+($ss/3600.0)) * $sg;

    ## -> Next Record

    read(DAT,$line,80);

    # Acceptance and quality codes:

    $accept = substr($line,0,1);
    $quality = substr($line,1,1);
    $quality = ($quality eq " ")? "-" : $quality;

    # ET-UTC

    $et_utc  = sprintf "%4.1f", (substr($line,17,3)/10.0);

    # Adjusted RA and Dec:

    $hh = substr($line,21,2);
    $mm = substr($line,23,2);
    $ss = substr($line,25,5);
    $ra_corr = sprintf "%8.5f", (($hh*1.0)+($mm/60.0)+($ss/3600.00)) * 15.0;


    $sg = (substr($line,30,1) eq "-")? -1.0 : +1.0;
    $dd = substr($line,31,2);
    $mm = substr($line,33,2);
    $ss = substr($line,35,5);
    $dec_corr = sprintf "%9.5f", (($dd*1.0)+($mm/60.0)+($ss/3600.0)) * $sg;

    # Observatory Code and Parralax Factors:

    $obscode = substr($line,40,3);
    $dxy = substr($line,50,4);
    $dz  = substr($line,54,4);

    # Coordinate RMS:

    $ra_rms  = substr($line,59,6);
    $dec_rms = substr($line,66,6);
    
    ## -> Next Record

    read(DAT,$line,80);

    # Observer and observatory:

    $observer = substr($line,2,24);
    $observatory = substr($line,27,36);

    # Magnitude estimates:

    $totmag = substr($line,64,5);
    $nucmag = substr($line,70,4);

    ## -> Next Record

    # Now read the next two records and collect comments into a single
    # field:

    $comment = "";
    read(DAT,$line,80);
    if ($line !~ /^\s+$/)
      { $line =~ s/^\s+//;
        $line =~ s/\s+$//;
        $comment = $line;

        read(DAT,$line,80);

        if ($line !~ /^\s+$/)
          { $line =~ s/^\s+//; 
            $line =~ s/\s+$//;
            $comment = "$comment $line";
          }
      }

    # Print the output record:

    printf MON "$utc_time $jday $ra $dec ";
    printf MON "$ra_corr $dec_corr $accept $quality $ra_rms $dec_rms ";
    printf MON "$et_utc $obslong $obslat $lat_calc $dxy $dz ";
    printf MON "$totmag $nucmag $file_num $system $obscode ";
    printf MON "$observer $observatory ";
    printf MON "$comment\n";

    close(DAT);

    # Next set of files:
  }

close(MON);
closedir(DATE);

# Save the last utc_time as out STOP_TIME:

$stop_time = $utc_time;
$filename = "astr$date.tab";

# Now we're ready to write the label.  We'll read in a template and 
# substitute actual values as needed:

open(TPL,"label.tpl") || die "Could not open template file ($!)";
open(LBL,">astr$date.lbl") || die "Could not open label file ($!)";

while ($line=<TPL>)
  { chop $line;

    $line =~ s/__row_bytes/$row_bytes/;
    $line =~ s/__rows/$rows/;
    $line =~ s/__filename/$filename/;
    $line =~ s/__product_id/$product_id/;
    $line =~ s/__product_name/$product_name/;
    $line =~ s/__product_time/$product_time/;
    $line =~ s/__start_time/$start_time/;
    $line =~ s/__stop_time/$stop_time/;

    printf LBL "%-78.78s\r\n",$line;
  }

# Done:

close(TPL);
close(LBL);