#!/usr/bin/env perl

if (@ARGV != 2) { die "USAGE: megacoords (mode) (filename)\n"; }
$ENV{'PATH'} = "$ENV{'PATH'}:/apps/elixir/bin";

# currently we keep things hardwired:

$mode = $ARGV[0];
$input = $ARGV[1];

if ($mode eq "chip") { $ccd   = "ccd22"; }
if ($mode eq "amp")  { $ccd   = "amp44"; }
$Xref  = 973;
$Yref  = 4560;

if ($ccd eq "") { die "ERROR: camera $camera not found\n"; }

$temp = `mktemp /tmp/center.XXXXXX`; chop ($temp);

# mana processing of image
open (MANA, "|mana --norc >& /dev/null");

print MANA "\$CCDKEYWORD = EXTNAME\n";
print MANA "macro go\n";
print MANA " rd a $input -n $ccd\n";
print MANA " wd a $temp.fits\n";
print MANA " exec gosexphot $temp.fits $temp.sx >& /dev/null\n";
print MANA " exec imclean -sex $temp.fits $temp.sx $temp.smp >& /dev/null\n";
print MANA " exec gastro $temp.smp >& /dev/null\n";
print MANA " header a -w $temp.smp\n";
print MANA " coords a -p $Xref $Yref\n";
print MANA " exec echo \$RA \$DEC > $temp.coords\n";
print MANA " exit 0\n";
print MANA "end\n";

print MANA "go\n";
print MANA "exit 1\n";
close (MANA);

($Robs, $Dobs) = split (" ", `cat $temp.coords`);
($tmp, $Rreq, $Dreq) = split (" ", `echo $input | fields RA_DEG DEC_DEG`);

($tmp, $obsid, $Nastro, $Cerror) = split (" ", `echo $temp.smp | fields OBSID NASTRO CERROR`);

if ($Robs < 0.0)   { $Robs += 360.0 }
if ($Robs > 360.0) { $Robs -= 360.0 }

if ($Rreq < 0.0)   { $Rreq += 360.0 }
if ($Rreq > 360.0) { $Rreq -= 360.0 }

$dR = 3600.0 * ($Rreq - $Robs) * cos ($Dobs*3.141592643589/180.0);
$dD = 3600.0 * ($Dreq - $Dobs);

printf "$obsid %10.6f %10.6f  %10.6f %10.6f  %6.1f %6.1f  %3d %4.2f\n", $Rreq, $Dreq, $Robs, $Dobs, $dR, $dD, $Nastro, $Cerror;

escape:
system ("rm -f $temp $temp.fits $temp.sx $temp.smp $temp.coords");
exit 0;
