#! /usr/bin/perl -w

use Getopt::Std;
use File::Temp qw( tempfile );
getopts('AMDRC',\%opt);

$cmd = 'ds9  -scale mode zscale ';
if (exists($opt{M})) {
    $cmd .= ' -mosaic wcs ';
}
if (exists($opt{A})) {
    $cmd .= " -wcs align yes ";
}

if (exists($opt{C})) {
    $cmd .= " -frame new rgb -rgb system image ";
    @color = ("-red","-blue","-green");
}

foreach $neb (@ARGV) {
    chomp($real_file = `neb-locate --path $neb`);
    unless ($real_file =~ /no instances found/) {
	if (($real_file =~ /ota/)||(exists($opt{M}))) {
	    $cmd .= "-medatacube $real_file ";
	}
	elsif (($real_file =~ /cmf$/)) {
	    my $head_name = $real_file;
	    $head_name =~ s/.*XY(\d\d).*/XY$1.psf/;
	    my ($tempFile, $tempName) = tempfile("/tmp/ds9.$$.XXXX",
						 UNLINK => 1, SUFFIX => '.reg' );
	    
	    if (exists($opt{R})) {
		system("fdump $real_file $head_name | awk '{print(\"FK5;point(\",\$15,\$16,\") # point=boxcircle text = {\",\$8,\"}\"}' > $tempName");
		$cmd .= " -regions format xy -regions $tempName ";
	    }
	    else {
		system("echo '# Region file format: DS9 version 4.1' > $tempName");
		system("echo 'global color=green dashlist=8 3 width=1 font=\"helvetica 10 normal\" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1' >> $tempName");
		
		system("fdump $real_file $head_name | awk '{print(\"image;ellipse(\",\$2,\$3,\$22,\$23,\$24,\") # text = {\",\$8,\"\}\")}' >> $tempName");
		$cmd .= " -regions format ds9 -regions $tempName ";
	    }


	}
	else {
	    if (exists($opt{C})) {
		if ($#color == -1) {
		    next;
		}
		else {
		    $c = shift(@color);
		    $cmd .= " $c ";
		}
	    }
	    $cmd .= " $real_file ";
	}
    }
}
system("$cmd");
