#!/usr/bin/perl

#$[ = 0;			# set array base to 1
$, = ' ';		# set output field separator
$\ = "\n";		# set output record separator

if (@ARGV<1) {
	print "Usage: pelli <file> [color] [clean] [coltext] [shape]";
	print "Catalog format : id xc(deg) yc(deg) a(deg) b(deg) theta z mag";
	exit;
}

print ">Usage: pelli <file> [color] [clean] [coltext] [shape]# $ARGV[0] $ARGV[1] $ARGV[2] $ARGV[3] $ARGV[4]";

sub sex2deg
{
    my ($ra, $dec) = @_;
	my ($hh,$mm,$ss)=split(':',$ra);
	my ($dd,$nn,$tt)=split(':',$dec);
	my $sign=1;
	if (substr($dec,0,1) eq '-')
        {
	        $sign=-1;
        	$dd=abs($dd);
	}

	$ra=($hh+$mm/60+$ss/3600)*15;
	$dec=$sign*($dd+$nn/60+$tt/3600);

    return ($ra, $dec);
}

# 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};
}

$color=$ARGV[1];
if ($color eq '') 
{
	$color="red";
}
if ($ARGV[2] eq "clean")
{
	system("xpaset -p $title regions deleteall");
}
if ($ARGV[3]) 
{
	$col=$ARGV[3];
}
else
{
	$col=1;
}

$shape=$ARGV[4];
if($shape eq '')
{
	$shape='ellipse';
}

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


#----------------------------------------------
# Read the input file
if( $ARGV[0] ne "STDIN" )
{
	open $in, "$ARGV[0]" or die "ERROR opening $ARGV[0]\n";
}
else
{
	$in = *STDIN;
}
local $\; # établit le mode slurp en local
@file=<$in>;
close $in;

#---------------------------------------------
#Set default WCS coordinates values
$iref = 0;
$ra = 0;
$dec = 0;
# Check if there exists the frames.pl file for compatibility
do 'frames.pl';
$iref = 1 if( $type eq 'fk5' );

# Check if the first line contains a WCS reference
if( $file[0] =~ /#REFERENCE/i )
{
	chop $file[0];
	($null,$iref,$ra,$dec) = split /\s+/,$file[0];
	print "$null $iref $ra $dec\n";
}

#If we have the reference coordinates in sexagesimal form
#convert them to degrees
if ($iref == 4)
{
    ($ra, $dec) = sex2deg($ra, $dec);
	$pixel=3600;
	$pixelx=-3600*cos($dec/180*3.1415926);
	$ds9type = 'fk5';
}
elsif( $iref == 2 )
{
	$ds9type = 'image';
	$pixel=$pixelx=1;
}
else #( $iref == 3 or $iref == 0 ) default case
{
	$pixel=3600;
	$pixelx=-3600*cos($dec/180*3.1415926);
	$ds9type = 'fk5';
}

#---------------------------------------------------
# Try to not print the ellipse Id 2 times
$oldId = "";

for( $i = 0; $i < scalar @file; $i++ ) 
{
	$_ = $file[$i];
	chop;	# strip record separator
	next if( /#.*/ );

	($id,$xc,$yc,$a,$b,$theta,$z,$mag) = split;
	@fld=split;
	# Convert the coordinates to absolute coordinates
	# iref == 0 means that it's already in WCS coordinates (default)
    if( $iref == 1 ) # Sexagesimal to degrees absolute coordinates
    {
        ($xc, $yc) = sex2deg($xc, $yc);
    }

	if( $iref == 3 or $iref == 4 ) # relative to absolute
	{
		$xc = $ra + $xc/$pixelx;
		$yc = $dec + $yc/$pixel;
	}
	elsif( $iref == 2 )
	{
		$xc += $ra;
		$yc += $dec;
	}

	# initialise text
	if( $col != 0 )
	{
		$text = $fld[$col-1];
	}
	else
	{
		$text = $i;
	}

	if ($shape eq 'ellipse' && $a != 0 && $b != 0) 
	{
		# Print the ellipse
		printf ds9 "$ds9type;ellipse(%.7f,%.7f,",$xc,$yc;
		printf ds9 "%.5e,%.5e,",$a/$pixel,$b/$pixel;
		printf ds9 "%.2f) # color=$color ",$theta;
		
		# Plot the arc ID but not the ID of the 2nd potfile ellipse
		if( $oldId ne $id or $oldxc != $xc or $oldyc != $yc )
		{
			print ds9 "text={$text} font=\"helvetica 14 normal\" ";
		} 

		# If it's the 2nd ellipse of a potfile clump ie sigma
		if ( $oldId eq $id and $oldxc == $xc and $oldyc == $yc )
		{
			printf ds9 "background";
		}	
		printf ds9 "\n";
		$oldId = $id;
		$oldxc = $xc; $oldyc = $yc;
	}
	elsif( $shape eq 'line' )
	{
		$aa=$col*($a+$b);
		$aa /=3600;
		$theta += 90;
		$theta += 90 if( $a == 0 && $b != 0);
		
		$tr=$theta/180.*3.1415926;
	       	$xbeg=($xc-10*$aa*cos($tr)/cos($yc*3.1415926/180.));
	       	$xfin=($xc+10*$aa*cos($tr)/cos($yc*3.1415926/180.));
	        $ybeg=($yc+10*$aa*sin($tr));
	        $yfin=($yc-10*$aa*sin($tr));

		print ds9 "$ds9type;line($xbeg,$ybeg,$xfin,$yfin) # color=$color text={$text}\n";	
	}
	elsif( $shape eq 'point' )
	{
		print ds9 "$ds9type;point($xc,$yc) # point=cross color=$color text={$text}\n";
	}
}
close(ds9);

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


