<%args>
$imgtype => 'png'
$epoch_mjd
$type => 'L'
$hackyhackhack => 0
$autoscale => 0
</%args>

<%init>
use File::Slurp;
use File::Temp;
use PS::MOPS::DC::Efficiency;
use PS::MOPS::DC::Field;
use PS::MOPS::Lib qw/mopslib_nn2mjd/;

my $inst = $m->notes('INST');
my $config = $inst->getConfig();
my $gmt_offset_hours = $config->{site}->{gmt_offset_hours};
if ($nn) {
    $epoch_mjd = mopslib_nn2mjd($nn, $gmt_offset_hours);
}

my %typemap = (
    epsc => 'application/postscript',
    eps => 'application/postscript',
    png => 'image/png',
);
my $model => $m->notes('MODEL');
my $tmp = new File::Temp(UNLINK => 1);
my $title;

my $hacky_str = '';
if ($hackyhackhack) {
    $hacky_str = '--xmin 0 --xmax 80 --ymin 0 --ymax 60';
}

my $autoscale_str = $autoscale ? '--autoscale' : '';

if ($type eq 'L') {     # pct linked
    $title = $inst->{_DBNAME} . ", MJD " . $epoch_mjd . ", Linking Efficiency";
    my $linkdata = modce_retrieve($inst, category => $EFF_DERIVEDOBJECTS, byField => 1, epoch_mjd => $epoch_mjd);
    foreach my $d (sort { $a->{fieldId} <=> $b->{fieldId}} @{$linkdata}) {
        my $f = modcf_retrieve($inst, fieldId => $d->{fieldId});
        print $tmp $f->ra, ' ', $f->dec, ' ', 100 * (1 - $d->{unlinked} / ($d->{avail} || 1)), ' ', $f->fieldId, "\n";
    }
}
elsif ($type eq 'A') {  # available
    $title = $inst->{_DBNAME} . ", MJD " . $epoch_mjd . ", Available Linkages";
    my $linkdata = modce_retrieve($inst, category => $EFF_DERIVEDOBJECTS, byField => 1, epoch_mjd => $epoch_mjd);
    foreach my $d (sort {$a->{fieldId} <=> $b->{fieldId}} @{$linkdata}) {
        my $f = modcf_retrieve($inst, fieldId => $d->{fieldId});
        print $tmp $f->ra, ' ', $f->dec, ' ', $d->{avail} || 0, ' ', $f->fieldId, "\n";
    }
}
else {  # inserted/found/pass OD
    $title = $inst->{_DBNAME} . ", MJD " . $epoch_mjd . ", Total Efficiency";
    my $linkdata = modce_retrieve($inst, category => $EFF_DERIVEDOBJECTS, byField => 1, epoch_mjd => $epoch_mjd);
    foreach my $d (sort {$a->{fieldId} <=> $b->{fieldId}} @{$linkdata}) {
        my $f = modcf_retrieve($inst, fieldId => $d->{fieldId});
        print $tmp $f->ra, ' ', $f->dec, ' ', ($d->{clean} / ($d->{avail} || 1)), ' ', $f->fieldId, "\n";
    }
}


close $tmp;

die "bogus image type: $imgtype" unless exists($typemap{$imgtype});
$r->content_type($typemap{$imgtype});

my $stuff = join '', `radecdplot $autoscale_str --title '$title' --labels --terminal $imgtype $hacky_str < $tmp| gnuplot`;
$m->clear_buffer;
$m->print($stuff);
$m->abort;
</%init>
