#!/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 $ofmt;
my $stiltsJar = '/home/panstarrs/bills/jars/stilts.jar';
my $stilts = "java -jar $stiltsJar";

my $test = 1;

my ($verbose, $save_temps);

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

die "usage: $0 [--ofmt <ofmt>] <p2 batch file> [<out>]\n" unless (scalar @ARGV == 1) or (scalar @ARGV == 2);

$in = shift;
$out = shift;

my $detcat = "cat." . basename($in);

runcommand( "concatp2batch $in $detcat");

# find exp_id. XXX: we could use batch name for this or require user to find this
my $command = "$stilts tcat in=$detcat icmd='head 1;keepcols imageID;' ofmt=ascii | grep -v '#'";
my $imageID = `$command`;
# XXX TODO: check for success
chomp $imageID;
my $exp_id = $imageID / 100;
print "exp_id is $exp_id\n" if $verbose;

my $smf;
if ($test) {
    # XXX: make an option
    my $testdata = "/data/ippc19.0/home/bills/ipp/ippToPsps/test/testdata";
    $smf = sprintf "%s/test.%02d.smf", $testdata, $exp_id;
} else {
    # XXX: look up the smf for the exposure here
    die "only test mode works right now\n";
}

my $ippcat = "cat." . basename($smf);

$command = "concatsmf $smf $ippcat";
$command .= " --test" if $test;

runcommand($command);

my $matched = "m." . basename($out);
runcommand("matchIppToPsps $detcat $ippcat $matched");

if (!$save_temps) {
    unlink $detcat;
    unlink $ippcat;
}

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";
    }
}
