#!/usr/bin/env perl

use strict;
use warnings;

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


my $joinType = '1and2';
my $in;
my $out;
my $jardir = $ENV{JARDIR};

$jardir = '/home/panstarrs/bills/jars' unless $jardir;

my $stiltsJar = "$jardir/stilts.jar";
my $stilts = "java -jar $stiltsJar";

my $testdata;

my ($verbose, $save_temps);

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

die "usage: $0 <stack batch file> <out> [--testdata <location of testdata directory]\n" unless (scalar @ARGV == 2);

$in = shift;
$out = shift;

my $command;

my $base = basename($in);

my @filters = qw(none g r i z y);

# Find the stack_ids for the various filters
$command = "$stilts tpipe in=$in'#StackObjectAttributes' cmd='keepcols \"gstackImageID rStackImageID iStackImageID zstackImageID ystackImageID\";stats Maximum;' ofmt=ascii";

print "$command\n" if $verbose;
my $stackList = `$command`;
die "Failed to find stack_ids from $in\n" unless $stackList;

my @stackIDs = split "\n", $stackList;
# shift off the header row
# shift @stackIDs;

my @cmfs;
if ($testdata) {
    for (my $i=1; $i<=5; $i++) {
        my $stack_id = $stackIDs[$i];
        my $cmf = 'none';
        if ($stack_id > 0) {
            $cmf = sprintf "%s/stack.%02d.cmf", $testdata, $stack_id;
        }
        $cmfs[$i] = $cmf;
        print "$filters[$i] $stack_id $cmf\n" if $verbose;
    }
} else {
    # XXX: look up the cmf for this stack here
    die "this program only works in test mode right now\n";
}

# 
my @joined;
for (my $i=1; $i<=5; $i++) {
    my $cmf = $cmfs[$i];
    next if $cmf eq 'none';

    my $filter = $filters[$i];
    my $ippjoined = $filter . "_joined" . basename($cmf);

    $command = "joinstkcmf $cmf $ippjoined";
    $command .= " --ofmt fits";
    $command .= " --test" if $testdata;

    runcommand($command);

    my $stackColumn = $filter . "stackImageID";
    my $idColumn = $filter . "ippDetectID";
    my $outfile = $filter . "_matched" . basename($cmf);
    $command = "$stilts tmatch2 in1=$in'#StackObjectAttributes' in2=$ippjoined matcher=2d out=$outfile ofmt=fits"
        . " values1='$stackColumn $idColumn' values2='STACK_ID IPP_IDET' params=.01 join=$joinType"
        . " fixcols=all suffix1='' suffix2=_$filter ocmd='tablename StackObjectAttributes'";
    $in = $outfile;
    runcommand($command);
}

exit 0;

my $matched = "m." . basename($out);

# $commmand = "$stilts tmatch2 fixcols=dups suffix1=
my $ippjoined;
runcommand("matchIppToPsps $in $ippjoined $matched");

if (!$save_temps) {
    unlink $ippjoined;
}

# runcommand("adddeltacolumns $matched $out");

exit 0;


sub runcommand {
    my $command = shift;
    print "Running: $command\n" if $verbose;
    my $rc = system $command;
    if ($rc) {
        my $status = $rc >> 8;
        die "$command failed\nrc = $rc status = $status";
    }
}
