#!/usr/bin/env perl

# given an smf file create a file with a single fits table containing all of the detections
# A column giving the imageID (exp_id * 100 + ccdnum) is added for use in matching to
# PSPS detections and to distingush detections with the same IPP_IDET from different
# OTAs
#
# Optionally just extract from a selected OTA's 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 ($stack_id, $skycal_id);
my $test;
my ($save_temps, $verbose);
my $ofmt;

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

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

my $cmf = 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 $infilename = basename($cmf);

my $path;
if ($cmf =~ /^neb:/) {
    $path = `neb-locate -p $cmf`;
    if (!$path) {
        die "ailed to find location of $cmf\n";
    }
    print $path if $verbose;
    chomp $path;
} else {
    $path = $cmf;
}

my ($proj, $cell, $skycell_id);
if (!$test) {
    (undef, undef, undef, $proj, $cell, undef, $stack_id, undef, $skycal_id) = split '\.', $infilename;

    $skycell_id = sprintf "skycell.%04d.%03d", $proj, $cell;
} else {
    (undef, $stack_id) = split '\.', $infilename;
    $stack_id += 0;
    $skycal_id = $stack_id;
    my $results = `echo $path | fields SKYCELL`;
    chomp $results;
    print "$results\n" if $verbose;
    # (undef, undef, $skycell_id) = split " ", $results;
    (undef, $skycell_id) = split " ", $results;
    (undef, $proj, $cell) = split '\.', $skycell_id;
    $cell += 0;
    $proj += 0;
}

print "$stack_id $skycal_id $skycell_id\n" if $verbose;

my $extension = "";

my $extname = $infilename;
my $exthead = 'SkyChip';

my $cmd = "$stilts tmatchn nin=5 matcher=exact values1=IPP_IDET values2=IPP_IDET values3=IPP_IDET"
    . " values4=IPP_IDET values5=IPP_IDET"
    . " fixcols=all suffix1='' suffix2=_exp suffix3=_dev suffix4=_ser suffix5='_xsrc'"
    . " out=$output"
    . " in1=$path#$exthead.psf  join1=always"
    . " icmd1='"
    .         "addcol -after IPP_IDET STACK_ID $stack_id;"
    .         "addcol -after STACK_ID SKYCAL_ID $skycal_id;"
    .         "addcol -after SKYCAL_ID PROJ_ID $proj;"
    .         "addcol -after PROJ_ID CELL_ID $cell;"
    . "'"

    . " in2=$path#$exthead.xfit"
    . " icmd2='" . 'select "equals(MODEL_TYPE, \"PS_MODEL_EXP\" )";' . "'"

    . " in3=$path#$exthead.xfit"
    . " icmd3='" . 'select "equals(MODEL_TYPE, \"PS_MODEL_DEV\" )";' . "'"

    . " in4=$path#$exthead.xfit"
    . " icmd4='" . 'select "equals(MODEL_TYPE, \"PS_MODEL_SERSIC\" )";' ."'"

    . " in5=$path#$exthead.xsrc"
    . " progress=none"
    ;

$cmd .= " ofmt=$ofmt" if $ofmt;

print "$cmd\n" if $verbose;

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

exit 0;

