#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;
use Pod::Usage;
use FileHandle;


use subs qw(
);


# Options.
my $inst;
my $instance_name;
my $help = 0;

# Start program here.
GetOptions(
    'instance=s' => \$instance_name,
    'postfit_file=s' => \$postfit_file,
    help => \$help,
) or pod2usage(2);

pod2usage(-message => "--orbits_file not specified.") unless $orbits_file;
pod2usage(-message => "--postfit_file not specified.") unless $postfit_file;
$inst = PS::MOPS::DC::Instance->new(DBNAME => $instance_name);
my $mc = $inst->getConfig();
my $ml = $inst->getLogger();

my $line;
my $track_id;
my $extra;
my @stuff;
my @tids;

my %tracks;

my $postfit_fh = new FileHandle($postfit_file) or $ml->logdie("can't open $postfit_file");
# Read JPL postfit output.  For each set of detections we read in, align them with
# tracklets.
while ($line = <$postfit_fh>) {
    next if $line =~ /^(#|!)/;      # MOPS or DES comment, skip
    ($track_id, $extra) = split /\s+/, $line, 2;
    @tids = split /=/, $track_id;   # tracklet IDs from track ID
    $tracks{$track_id} = [@tids];   # save tracklet IDs for track
}
$orbits_fh->close();

exit;


=head1 NAME

postfit2resids - Program to convert JPL postfit output to useful MOPS postfit residual format

=head1 SYNOPSIS

postfit2resids --orbits-file=FOO.orbits --postfit_file=FOO.postfit > FOO.residuals

=head1 DESCRIPTION

postfit2resids takes a residuals file of the format

182688=247763=250120=254184=324709 55326.28519855 0.011704 0.003813 1 1 0
182688=247763=250120=254184=324709 55326.29339646 -0.013674 -0.000482 1 1 0
182688=247763=250120=254184=324709 55327.28355948 0.034713 -0.021325 1 1 0
182688=247763=250120=254184=324709 55327.28463897 0.012808 0.003320 1 1 0
182688=247763=250120=254184=324709 55327.28642038 0.012845 0.014818 1 1 0
182688=247763=250120=254184=324709 55327.29237421 -0.004318 -0.002200 1 1 0
182688=247763=250120=254184=324709 55327.29349171 -0.051378 -0.003149 1 1 0
182688=247763=250120=254184=324709 55327.29513527 -0.010051 0.001683 1 1 0
182688=247763=250120=254184=324709 55328.28934593 0.013881 -0.021254 1 1 0
182688=247763=250120=254184=324709 55328.29780593 -0.013089 0.025121 1 1 0

and generates a residuals file containing

TRACK_ID TRACKLET_ID DET_ID RA_RESID_DEG DEC_RESID_DEG RA_WEIGHT DEC_WEIGHT AST_REJECT

Essentially we are fetching detection IDs and associating them with tracklet IDs
because the DES format eschews detection IDs.  But we need them to do tracklet
residual analysis.

=cut

