#!/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 $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 <p2 batch file> [<out>]\n" unless (scalar @ARGV == 2);

$in = shift;
$out = shift;

my $jardir = $ENV{JARDIR};
unless ($jardir) {
    $jardir = '/home/panstarrs/bills/jars' unless $jardir;
    print STDERR "JARDIR envrionment variable not found. Using $jardir\n" if $verbose;
    # add it to the enviorment so that the other programs can use it
    $ENV{JARDIR} = $jardir;
}
my $stiltsJar = "$jardir/stilts.jar";
my $stilts = "java -jar $stiltsJar";

# file name for concatenated detection extensions
my $detcat = "cat." . basename($in);

runcommand( "concatp2batch $in $detcat");

# find exp_id. XXX: I think that we could use file batch name for this or require user to supply it as an argument
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 ($testdata) {
#    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 $testdata;

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