#!/usr/bin/env perl

use warnings;

if(@ARGV < 1)
{
    print "Usage: pcritic <file.par>\n";
    exit;
}

# Get the first DS9 in the xpans list
if( ! $ENV{DS9} )
{
	eval {
		@xpa = `xpaget xpans`;
		@xpa = split(/ /,$xpa[0]);
		$title=$xpa[1];
	} or do {
		$title="ds9";
	}
}
else
{
	$title=$ENV{DS9};
}

if( -w $ENV{PWD} )
{
    $fds9="e.reg";
}
else
{
    $fds9="/tmp/e.reg";
}
open(ds9, ">$fds9") || die "ERROR creating file $fds9\n";


# Open the .par file and parse it
open $in, "$ARGV[0]" or die "Error opening $ARGV[0]\n";

my $ra_ref = 0;
my $dec_ref = 0;
my ($third, $i, $x, $y, $phi, $dl, $z);
my ($x1, $y1, $x2, $y2);
while( <$in> )
{
    if( /reference/ )
    {
        ($third, $i, $ra_ref, $dec_ref) = split;
    }
    if( /critic/ && !/#/ )
    {
        ($third, $i, $x, $y, $phi, $dl, $z) = split;
        $x1 = $x + $dl * cos($phi * 3.1415927 / 180.);
        $x2 = $x - $dl * cos($phi * 3.1415927 / 180.);
        $y1 = $y + $dl * sin($phi * 3.1415927 / 180.);
        $y2 = $y - $dl * sin($phi * 3.1415927 / 180.);
        $x1 = $ra_ref - $x1 / 3600. / cos($dec_ref * 3.1415927 / 180.);
        $x2 = $ra_ref - $x2 / 3600. / cos($dec_ref * 3.1415927 / 180.);
        $y1 = $dec_ref + $y1 / 3600.;
        $y2 = $dec_ref + $y2 / 3600.;
        printf ds9 "fk5; line(%.9f,%.9f,%.9f,%.9f) # line=1 1\n",$x1,$y1,$x2,$y2;
    }
}

close $in;
system("cat $fds9 | xpaset $title regions");



