% if ($canSubmit && !@submitted) {
    <form target="_blank" action="submit_mpc" method="post">
% }

<!-- 
Revision data:
<% Dumper(\%revised_dets) %> 
-->

<table border=1 cellspacing=0 cellpadding=2 width="90%">
<tr>
<th class="darkheader"> Tracklet ID </th>
<th class="darkheader"> Status </th>
<th class="darkheader"> Classification </th>
<th class="darkheader"> Known As </th>
<th class="darkheader"> V<sub>tot</sub> (deg/day) </th>
<th class="darkheader"> Pos Ang (deg) </th>
<th class="darkheader"> Score </th>
<th class="darkheader"> GCR (arcsec) </th>

</tr>
<tr>
% if ($trkId) {
<td align="left" width=25%> 
<span class="L18bold"><% $trk->trackletId %>
% if ($revised) {
<span class="alertbox">REVISED</span>
% }
</span>
<br>
% if (!$revised) {
<a target="_blank" href="?<% qq{$ENV{QUERY_STRING}&revised=1} %>">Show trail-fitted astrometry</a> |
% }
<a target="_blank" href="mpcheckt.html?trkId=<% $trkId%>">MPCheck</a><br>
Detections <a target="_blank" href="mtmpc.txt?id=T<% $trkId%>">MPC</a> | <a target="_blank" href="mtdes.txt?id=T<% $trkId%>">DES</a>

% if (@submitted) {
% my ($disp, $desig, $mpc_desig, $submitter) = @submitted;
<hr>
Submitted as <span class="L14bold"><% sprintf qq{<a href="/czar/$model/manage_neo.html?desig=$desig">$desig</a> by <a target="_blank" href="userreview.html?submitter=$submitter&nn=%d">$submitter</a>}, $field->nn %></span><br>
<% $mpc_desig || '' %>
% } elsif ($canSubmit) {
    <hr>
    <table cellpadding=0 cellspacing=2 width="100%">
    <tr>

    <td align="center" valign="top">
    <input type="hidden" name="tracklet" value="T<% $trkId %>">
    <input type="hidden" name="revised" value="<% $revised_data %>">
    <input type="submit" name="subtype" value="Submit Followup"><br>
    <input type="text" size="10" name="desig" value="<% $known_desig || 'NA' %>">
    </td>

    <td align="center" valign="top">
    <input type="hidden" name="tracklet" value="T<% $trkId %>">
    <input type="submit" name="subtype" value="Submit Incidental">
    </td>

% if ($trk->vTot > 1.5 && !$revised && !$override_revised) {
    <td align="center" valign="top">
    <input type="hidden" name="tracklet" value="T<% $trkId %>">
    <input type="submit" name="subtype" value="Use trail-fitted to submit" disabled="disabled">
    </td>
% } else {
    <td align="center" valign="top">
    <input type="hidden" name="tracklet" value="T<% $trkId %>">
    <input type="submit" name="subtype" value="Submit NEO">
    </td>
% }


    </tr>
    </table>
% } # if ($canSubmit)

</td>
% } else {
<td align="center"> <% $trk->trackletId %> </td>
% }
<td align="center"> <span class="L14"> <% $TRACKLET_STATUS_DESCS{$trk->status} %> </span></td>
<td align="center"> <span class="L14"> <% $MOPS_EFF_DESCS{$trk->classification} %> </span></td>
<td align="center"> 
    <span class="L14bold"><& /mpc_link, desig => $known_desig &></span>
% if ($known_str) {
    <br><br><span class="L12"><% $known_str %></span>
% }
</td>
<td align="center"> <& /lib/motionblock, trk => $trk &> </td>
<td align="center"> 
    <span class="L14"> <% sprintf "%.1f", $trk->posAng %> </span>
</td>
<td align="center"> 
    <div class="L16bold"> <% sprintf "NEO %.1f", $trk->digest %></div><br>
    <div class="L12"> <% sprintf "Prob %.2f", $trk->probability %></span></div>
</td>
<td align="center"> <span class="L14"> <% sprintf "%.2f", ($revised_gcr || $trk->gcr_arcsec) %> </td>

<tr>
<td colspan=8> <& detracklet_table, zip_name => "T$trkId", dets => $dets_ref, resids => $orbitId ? 1 : 0, special => $special &> </td><p>
</tr>
</table>

% if ($canSubmit && !@submitted) {
    </form>
% }

<%args>
$trk => undef
$trkId => undef
$orbitId => undef
$special => undef
$canSubmit => 0
$revised => 0
$override_revised => undef
</%args>

<%init>
use Cwd;
use Data::Dumper;

use PS::MOPS::Constants qw(:all);
use PS::MOPS::Lib qw(:all);
use PS::MOPS::DC::Field;
use PS::MOPS::DC::Orbit;
use PS::MOPS::GCR;
use PS::MOPS::JPLEPH;
use PS::MOPS::DC::Tracklet;
use PS::MOPS::DC::Known;

my $inst = $m->notes('INST');
my $model = $m->notes('MODEL');

if ($trkId) {
    $trk = modct_retrieve($inst, trackletId => $trkId);
}

my $dets_ref = $trk->detections;
my $field = modcf_retrieve($inst, fieldId => $dets_ref->[-1]->fieldId);

# If an orbit ID is specified, get per-detection residuals and stich them into the detections.
if ($orbitId) {
    my $orb = modco_retrieve($inst, orbitId => $orbitId);
    my $resid_stuff = jpleph_calcDetectionResiduals(orbit => $orb, detections_ref => $dets_ref);

    foreach my $det (@{$dets_ref}) {
        $det->{dra} = $resid_stuff->{$det->detId}->{dra};
        $det->{ddec} = $resid_stuff->{$det->detId}->{ddec};
        $det->{dtot} = $resid_stuff->{$det->detId}->{dtot};
    }
}

my $known_desig = 'N/A';
my $known_str = '';
if ($trk->knownId) {
    my $k = modck_lookup($inst, knownId => $trk->knownId);
    $known_desig = $k->{known_name};
    if ($k->{e} > 0) {
        $known_str = sprintf "a=%.3f, e=%.3f, i=%.2f, H<sub>V</sub>=%.2f", $k->{q} / (1 - $k->{e}), $k->{e}, $k->{i}, $k->{h_v};
    }
    else {
        $known_str = sprintf "q=%.3f, e=%.3f, i=%.2f, H<sub>V</sub>=%.2f", $k->{q}, $k->{e}, $k->{i}, $k->{h_v};
    }
}

# If this tracklet has been submitted, set a flag indicating is submission disposition.
my $dbh = $inst->dbh;
my @submitted = $dbh->selectrow_array(<<"SQL", undef, $model, $trkId);
select disposition, desig, mpc_desig, submitter from export.mpc_sub where dbname=? and tracklet_id=? limit 1
SQL

my $revised_str = '';
my $revised_data = '';
if (!@submitted) {
    my ($sub_other) = `lookup_sub --instance=$model T$trkId`;
    if ($sub_other) {
        my ($desig, $id) = split /\s+/, $sub_other;
@submitted = $dbh->selectrow_array(<<"SQL", undef, $desig);
select disposition, desig, mpc_desig, submitter from export.mpc_sub where desig=? limit 1
SQL
    }
}

my %revised_dets;
my $revised_gcr;
my $revised_chi2;

if ($revised) {
    $revised_str = '';
    my @foo;
    my @stamppaths;
    my $can = 1;
    my $det;
    foreach $det (@{$trk->detections}) {
        my $dbname = $inst->dbname;
        my $nn = int($det->epoch) - 1;      # MJD to NN
        my $det_id = $det->detId;
        my ($dir) = $det_id =~ /(\d)$/;     # last digit
        my $stamp_path = "/data/mops13.0/stamp-store/stamps/special-stamps/$dbname-auto/$nn/$dir/D$det_id.fits";
        if (!-e $stamp_path) {
            $can = 0;
            $revised_str = "stamp missing: $stamp_path";
            last;
        }
        else {
            push @stamppaths, $stamp_path;
        }
    }

    if ($can) {
        my $oldwd = getcwd;
        chdir "$ENV{MOPS_HOME}/lib/idl" or die "can't chdir";
        push @foo, `idl -quiet -e trailfit -args @stamppaths 2>/dev/null | column -t`;
        chdir $oldwd or die "can't restore $oldwd";

        # Suss out det info:
        my ($head) = shift @foo;
        if ($head !~ /^DET_ID/) {
            die "weird output: $head";
        }
        my @head = split /\s+/, $head;

        foreach my $line (@foo) {
            my @items = split /\s+/, $line;
            my $det_id = $items[0];
            $det_id =~ s/^D//;
            for my $n (0..$#items) {
                $revised_dets{$det_id}->{$head[$n]} = $items[$n];
            }
        }

        # Make revised detections.
        my $rdet;
        foreach $det (@{$dets_ref}) {
            $rdet = $revised_dets{$det->detId} or die "can't find revised det for " . Dumper($det);
            $det->ra($rdet->{RA_DEG});
            $det->dec($rdet->{DEC_DEG});
            $det->{fit_chi2} = $rdet->{CHI2};       # more yuck, this is how we propagate to lib/morph2text

            # Yuck!
            my ($old_flux) = $dbh->selectrow_array("select psf_inst_flux from det_rawattr_v2 where det_id=?", undef, $det->detId) or die "can't get psf_inst_flux for " . Dumper($det);
            my $new_mag = $det->mag + 2.5 * log($old_flux / $rdet->{FLUX}) / log(10);
            $det->mag($new_mag);
            $rdet->{MAG} = $new_mag;
        }
        $revised_gcr = PS::MOPS::GCR::compute_gcr($dets_ref);

        # Build the revision data for submission.
        $revised_data = join '|', map {
            "$_:ra=$revised_dets{$_}->{RA_DEG}&dec=$revised_dets{$_}->{DEC_DEG}&mag=$revised_dets{$_}->{MAG}"
        } sort keys %revised_dets;
    }
}

</%init>
