#!/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(
    "vebose|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;

# TODO: make this an option
my $stiltsJar = '/home/panstarrs/bills/jars/stilts.jar';

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

my $ofmt = 'fits';

my $extensionList = `ftlist $input h | grep Detection | awk '{print \$2}'`;

my ($listFile, $listName) = tempfile ("/tmp/foo.XXXX", UNLINK => !$save_temps);

# make a list of the detection extension names
print "$listName\n" if $save_temps;
foreach my $n (split "\n", $extensionList) {
    print "$n\n" if $verbose;
    # ftlist HDU number starts with 1, stilts expects zero based index
    $n -= 1;
    print $listFile "$input#$n\n";
}
close $listFile;

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

exit 0;

