#!/usr/bin/env perl

# given an smf file create a file with a single fits table containing all of the detections
# A column giving the imageID (exp_id * 100 + ccdnum) is added for use in matching to
# PSPS detections and to distingush detections with the same IPP_IDET from different
# OTAs
#
# Optionally just extract from a selected OTA's extension

use strict;
use warnings;

use File::Basename;
use File::Temp qw( tempdir  tempfile );

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

# It wouldn't be too hard to make ota an array and do a list of chips.
# for now just all or one

my ($ota, $save_temps, $verbose);

GetOptions(
    "ota|o=s"           =>  \$ota,
    "vebose|v"          =>  \$verbose,
    "save-temps"        =>  \$save_temps,
) or pod2usage( 2 );

die "usage: $0 <smf file> <output> [--ota <ota name>]\n" unless scalar @ARGV == 2;

my $smf = shift;
my $output = shift;

my $stilts="java -jar $ENV{HOME}/tools/stilts.jar";

my $ofmt = 'fits';

my $infilename = basename($smf);
my ($exp_name, $exp_id, $cam_id);
($exp_name, $exp_id, undef, $cam_id) = split '\.', $infilename;

print "$exp_name $exp_id $cam_id\n";
my $extension = "";

if ($ota) {
    $ota = uc($ota);
    if ($ota =~ /^XY/) {
        $ota = substr $ota, 2, 2;
    }
    $extension = sprintf "XY%02d.psf", $ota;
    extract_chip($smf, $output, $exp_id, $ota, $extension);
    exit 0;
}


# create temporary directory and temporary list of files for tcat
my $dir = tempdir( CLEANUP => !$save_temps);
my ($listfile, $listname) = tempfile( "$dir/filelist.XXXX", UNLINK => !$save_temps);

for (my $y = 0; $y <= 7; $y++) {
    for (my $x = 0; $x <= 7; $x++) {
        # skip non existent corner chips.
        next if (($x == 0 || $x == 7) && ($y == 0 || $y == 7));

        $ota = sprintf "%d%d", $y, $x;

        $extension = sprintf "XY%02d.psf", $ota;
        my ($ofile, $out) = tempfile ("$dir/$ota.XXXX", SUFFIX => '.cmf', UNLINK => !$save_temps);
        print $listfile "$out\n";
        extract_chip($smf, $out, $exp_id, $ota, $extension);
    }
}

close $listfile;

# now run stilts tcat to combine the files into one big table
my $extname = $infilename;

my $cmd = "$stilts tcat in=\@$listname out=$output ofmt=$ofmt ocmd='tablename $extname;'";
my $rc = system $cmd;
if ($rc) {
    my $status = $rc >> 8;
    die "stilts failed with $status $rc\n";
}

exit 0;


sub extract_chip {
    my ($in, $out, $frameID, $ota, $extension) = @_;

    my $imageID = $frameID*100 + $ota;

    # Add a column IMAGE_ID which we can match with the imageID in the Detection table.
    my $cmd = "$stilts tpipe in=$in'#'$extension out=$out ofmt=$ofmt cmd='addcol -after IPP_IDET IMAGE_ID $imageID;' join=1or2";

    print "$cmd\n" if $verbose;

    my $rc = system $cmd;
    if ($rc) {
        my $status = $rc >> 8;
        die "stilts failed with $status $rc\n";
    }
}

