#!/usr/bin/env perl

# given a P2 ippToPsps batch file
# concatenate all of the Detection extensions so that all of the Detections for
# an exposure are in a single fits 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 ($save_temps, $verbose);
my $test;

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

die "usage: $0 <p2 batch file> <output>\n" unless scalar @ARGV == 2;

my $input = shift;
my $output = shift;

my $jardir = $ENV{JARDIR};
if (!$jardir) {
    $jardir = '/home/panstarrs/bills/jars';
}
my $stiltsJar = "$jardir/stilts.jar";

my $stilts="java -jar $stiltsJar";

my $ofmt = 'fits';

my $listArg = getExtensionArg($input);

my $cmd = "$stilts tcat in='$listArg' out=$output ofmt=$ofmt";
print STDERR "running $cmd\n";

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

exit 0;

sub getExtensionArg {
    # find the zero offset extension number of each of the detection extensions and build
    # an argument list for them
    my $input = shift;

    my $ftableOutput = `ftable -list $input`;
    die "ftable didn't return any output for $input\n" unless $ftableOutput;

    my @lines = split "\n", $ftableOutput;

    my $listArg = "";
    my $n = -1;
    foreach my $line (@lines) {
        # skip first line which is a list header
        if ($n == -1) {
            $n = 0;
            next;
        }
        if ($line =~ /^Detection/) {
            $listArg .= "$input#$n ";
        }
        $n++;
    }

    return $listArg;
}
