#!/usr/bin/env perl

# take a file that describes the conversion beteween ipp smf and cmf columns and psps column and create a 
# stilts filter command that will add a column to a table with the difference between the 
# Detection value and the expected value

use strict;
use warnings;

my $verbose;

my $in = shift;
my $out = shift;
die "usage $0 <input matched detections> <output>\n" unless $in and $out;
my $confdir = '/home/panstarrs/bills/ipp/tools/bills';
my $conversionFile = 'p2columns.txt';
my $stiltsJar =  '/home/panstarrs/bills/jars/stilts.jar';
my $stilts = "java -jar $stiltsJar";

open C, "<$confdir/p2columns.txt" or die "failed to open p2columns.txt\n";

my $cmd="'addcol -after zp zpFactor 3630.78*pow(10,-0.4*zp);";

foreach my $line (<C>) {
    next if $line =~ '^#';
    next if !$line;
    chomp $line;
    my ($data, $comment) = split '#', $line;
    next if !$data;
    my ($p2, $ipp, $conversion) = split ' ', $data;

    next if !$ipp;
    $conversion = "" unless $conversion;
    my $equation = "$ipp$conversion";
    $equation = "$p2-$equation";
    $cmd .=  "addcol -after $p2 d_$p2 $equation;";
}
$cmd .= "'";

my $command = "$stilts tpipe in=$in out=$out cmd=$cmd";

print "$command\n" if $verbose;

system $command;
