#!/usr/bin/env perl

# extract the calibration list from a partial ftlist of an Images.dat file

use strict;
use warnings;

my $outcount = 0;

my $log10 = log(10.);

my $last_exp_id = 0;
my $new_exp_id = 0;

my $bad_flags = 0x62;   # ID_IMAGE_ASTROM_FAIL | ID_IMAGE_ASTROM_POOR | ID_IMAGE_PHOTOM_POOR
                        # do the DVO flags actually add value other than PHOTOM_UBERCAL ?

my @saved_vals;

while (my $line = <STDIN>) {
    chomp $line;
    # skip empty lines
    next if !$line;

    my ($n, $name, $mcal, $dmcal, $secz, $exptime, $tzero, $photcode, $flags, $ubercal_dist) = split " ", $line;

    # skip header lines
    next unless defined $ubercal_dist;

    #skip non gpc1 single frame photcodes (stacks)
    next if ($photcode >= 11000 or $photcode < 10000);

    # skip PHU images
    next if $name =~ "PHU";

    my $fcode = int($photcode / 100);

    my ($filter, $clam, $k);
    if ($fcode == 100) {
        $filter = 'g';
        $clam = 24.563;
        $k = -0.147;
    } elsif ($fcode == 101) {
        $filter = 'r';
        $clam = 24.750;
        $k = -0.085;
    } elsif ($fcode == 102) {
        $filter = 'i';
        $clam = 24.611;
        $k = -0.044;
    } elsif ($fcode == 103) {
        $filter = 'z';
        $clam = 24.250;
        $k = -0.033;
    } elsif ($fcode == 104) {
        $filter = 'y';
        $clam = 23.320;
        $k = -0.073;
    } else {
        die "unexpected photcode: $photcode\n";
    }

    $dmcal = 0 if $dmcal eq 'NULL';

    my $zpt = $clam - $mcal;

    my ($exp_name, $exp_id, undef, $cam_id) = split '\.', $name;

    # we take the values from the first chip
    next if $exp_id eq $last_exp_id;
    
    if ($new_exp_id and $exp_id ne $new_exp_id) {
        # exposure changed without getting a good one for previous exposure
        # print last set of values
        printexp(@saved_vals);
        $new_exp_id = 0;
        @saved_vals = ();
    }

    if ($flags & $bad_flags) {
        $new_exp_id = $exp_id;
        @saved_vals = ($exp_name, $exp_id, $cam_id, $zpt, $dmcal, $mcal, $filter, $flags, $ubercal_dist);
        next;
    }

    $new_exp_id = 0;

    $last_exp_id = $exp_id;
    
    printexp($exp_name, $exp_id, $cam_id, $zpt, $dmcal, $mcal, $filter, $flags, $ubercal_dist);

}

sub printexp {
    if ($outcount % 100 == 0) {
        print "#exp_name     exp_id  cam_id    zpcalib      zpcalerr        mcal     filter     flags   ubercal_dist\n";
    }
    $outcount++;
    printf "%12s %7d %7d %12.8f %12.8f %12.8f %6s    0x%08x %6d\n", @_;
}
