#! /usr/local/bin/perl -w

use Getopt::Std;

getopts('hvxC',\%opt);

if (exists($opt{h})) {
    print STDERR "./ghostbuster.pl <inlist>\n";
    print STDERR "   inlist format: exp_name RA DEC\n";
    print STDERR "   options:       -h    This help.\n";
    print STDERR "                  -v    Be more verbose.\n";
    print STDERR "                  -x    Don't bother with images.\n";

    exit(1);
}

open (L,">>ghostbuster.log");

while (<>) {
    chomp;
    ($exp_name,$ra,$dec) = split /\s+/;
    if (exists($opt{v})) {
	print "Working on $exp_name at position $ra $dec\n";
    }
    
    $smf = (split /\n/, `find_images.pl -EVFD -n $exp_name`)[-1];
    if (exists($opt{v})) {
	print "  Found SMF: $smf\n";
    }

    open(C,">./${exp_name}.coord");
    print C "$ra $dec\n";
    close(C);
    
    $coords = (split /\n/, `ppCoord -astrom $smf -radec ${exp_name}.coord`)[-1];
    @results = split /\s+/,$coords;

    if (exists($opt{v})) {
	print "  Obtained coordinate transform: $coords\n";
    }
    
    unless (defined($results[5])&&
	    (abs($results[0] - $ra) < 1e-3)&&
	    (abs($results[1] - $dec) < 1e-3)) {
	warn "$exp_name $ra $dec: failed to do astrometry: $coords\n";
    }
    $x_pos = $results[3];
    $y_pos = $results[4];
    $chip  = $results[5];
    $ota   = $chip;
    $ota =~ s/XY/ota/;

    $raw_file = '';
    unless(exists($opt{x})) {
	chomp($raw_file = `find_images.pl -RY -n $exp_name -O $ota`);
	if ($opt{C}) {
	    system("ppImage -file neb:///${raw_file} ./${exp_name} -recipe PPIMAGE CHIP  -Db CHIP.FITS TRUE ");
	}
	else {
	    system("ppImage -file neb:///${raw_file} ./${exp_name} -recipe PPIMAGE QUICKMOSAIC -Db CHIP.FITS TRUE -Db BACKGROUND FALSE");
	    print("ppImage -file neb:///${raw_file} ./${exp_name} -recipe PPIMAGE QUICKMOSAIC -Db CHIP.FITS TRUE -Db BACKGROUND FALSE\n");
	}
	open(R,">./${exp_name}.reg");
	print R "$x_pos $y_pos\n";
	close(R);
	push @ds9s, "./${exp_name}.${chip}.ch.fits -regions format xy -regions system image -regions ./${exp_name}.reg -pan to $x_pos $y_pos image ";	
    }
    if (exists($opt{v})) {
	print "  Summary: $exp_name $ra $dec $x_pos $y_pos $chip $ota $smf $raw_file\n";
    }
    # Determine if cross talk and extract magnitudes
    $cell_x = -1;
    $cell_y = -1;
    
    $limit = 590;
    $cell = 0;
    while ($cell_x == -1) {
	if ($x_pos <= $limit) {
	    $cell_x = $cell;
	}
	$cell++;
	$limit += 18;
	$limit += 590;
    }
    $limit = 598;
    $cell = 0;
    while ($cell_y == -1) {
	if ($y_pos <= $limit) {
	    $cell_y = $cell;
	}
	$cell++;
	$limit += 12;
	$limit += 598;
    }
    
    $ota_x = $ota;
    $ota_y = $ota;
    $ota_x =~ s/ota(.)./$1/;
    $ota_y =~ s/ota.(.)/$1/;

    $can_cross_talk = 0;
    $ct_ota_x = -1;
    $ct_ota_y = -1;
    $ct_cell_x = -1;
    $ct_cell_y = -1;
    #rule 1
    
    if ($opt{v}) {
	print ">> $ota_x $ota_y $cell_x $cell_y\n";
    }

    if (($ota_x == 2)&&($cell_x == 3)) {
	$can_cross_talk = 1;
	$ct_ota_x = 3;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 3;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos;
	$ct_y = $y_pos;
    }
    if (($ota_x == 3)&&($cell_x == 3)) {
	$can_cross_talk = 1;
	$ct_ota_x = 2;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 3;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos;
	$ct_y = $y_pos;
    }
    #rule 2
    if (($ota_x == 4)&&($cell_x == 3)) {
	$can_cross_talk = 1;
	$ct_ota_x = 5;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 3;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos;
	$ct_y = $y_pos;
    }
    if (($ota_x == 5)&&($cell_x == 3)) {
	$can_cross_talk = 1;
	$ct_ota_x = 4;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 3;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos;
	$ct_y = $y_pos;
    }
    #rule 3
    if (($ota_x == 2)&&($cell_x == 5)) {
	$can_cross_talk = 1;
	$ct_ota_x = 2;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 6;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos + 590 + 18;
	$ct_y = $y_pos;
    }
    if (($ota_x == 2)&&($cell_x == 6)) {
	$can_cross_talk = 1;
	$ct_ota_x = 2;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 5;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos - 590 - 18;
	$ct_y = $y_pos;
    }
    #rule 4
    if (($ota_x == 5)&&($cell_x == 5)) {
	$can_cross_talk = 1;
	$ct_ota_x = 5;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 6;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos + 590 + 18;
	$ct_y = $y_pos;
    }
    if (($ota_x == 5)&&($cell_x == 6)) {
	$can_cross_talk = 1;
	$ct_ota_x = 5;
	$ct_ota_y = $ota_y;
	$ct_cell_x = 6;
	$ct_cell_y = $cell_y;
	$ct_x = $x_pos - 590 - 18;
	$ct_y = $y_pos;
    }
    
    $ct_rule = "NO_CT";
    if ($can_cross_talk) {
	$ct_rule = "OTA${ota_x}${ota_y}xy${cell_x}${cell_y}<->OTA${ct_ota_x}${ct_ota_y}xy${ct_cell_x}${ct_cell_y}";
	$ct_chip  = "XY${ct_ota_x}${ct_ota_y}";
    }
    if ($opt{L}) {
	print "$ct_rule $ct_chip\n";
    }

    # Find magnitudes
    if ($smf) {
	$RR = 5;
	
	$mag_det = 'NAN';
	$mag_ct  = 'NAN';

	open(FD,"fdump $smf ${chip}.psf |");
	while (<FD>) {
	    chomp;
	    if ($_ =~ /IDET/) { next; }
	    @data = split /\s+/;
	    if ((abs($x_pos - $data[1]))&&(abs($y_pos - $data[2]))) {
		$RR_test = sqrt( ($x_pos - $data[1])**2 + 
				 ($y_pos - $data[2])**2);
		if ($RR_test < $RR) {
		    $RR = $RR_test;
		    $mag_det = $data[7];
		    $xx_det  = $data[31];
		    $xy_det  = $data[32];
		    $yy_det  = $data[33];
		}
	    }
	}
	close(FD);
	$r_det = $RR;
	$r_ct  = 'NAN';
	$RR = 5;
	if ($can_cross_talk) {
	    open(FD,"fdump $smf ${ct_chip}.psf |");
	    while (<FD>) {
		chomp;
		if ($_ =~ /IDET/) { next; }
		@data = split /\s+/;
		if ((abs($ct_x - $data[1]))&&(abs($ct_y - $data[2]))) {
		    $RR_test = sqrt( ($ct_x - $data[1])**2 + 
				     ($ct_y - $data[2])**2);
		    if ($RR_test < $RR) {
			$RR = $RR_test;
			$mag_ct = $data[7];
			$xx_ct  = $data[31];
			$xy_ct  = $data[32];
			$yy_ct  = $data[33];
		    }
		}
	    }
	    close(FD);
	    $r_ct = $RR;
	}
    }		    

    print L "$exp_name $ra $dec $x_pos $y_pos $chip $mag_det $xx_det $yy_det $xy_det $r_det $ct_rule $ct_x $ct_y $mag_ct $xx_ct $yy_ct $xy_ct $r_ct\n";

#    system("ds9 ./${exp_name}.${chip}.ch.fits -regions format xy -regions system image -regions ./${exp_name}.reg");
}
close(L);

unless(exists($opt{x})) {
    $options = join " ", @ds9s;
    system("ds9 $options");
}
