#!/usr/bin/perl
#
use Statistics::OLS;
use Math::FFT;
use Math::Stat;
use Math::Spline qw(spline linsearch binsearch);
use Math::Derivative qw(Derivative2);
use Math::Approx;
use Astro::FITS::CFITSIO qw( :longnames :constants );
use PDL;
use PDL::Fit::Polynomial; 
use PDL::Filter::Linear;
use PGPLOT;  # Load PGPLOT module
use PDL::Fit::Gaussian;
use PDL::Slatec;
use PDL::Image2D;
#use PDL::Matrix;

#$F3D=$ENV{HIIEXPLORER_PATH};  $F3D=$ENV{HIIEXPLORER_PATH};  require("$F3D/my.pl"); #("$F3D/scripts/my.pl"); # "/work1/ssa/perl/MY/my.pl";
#$F3D=$ENV{HIIEXPLORER_PATH};  $F3D=$ENV{HIIEXPLORER_PATH};  require("$F3D/my.pl"); #("$F3D/scripts/my.pl"); # "/home/sanchez/3DSoft_Ubuntu/R3D/my.pl";
$F3D=$ENV{HIIEXPLORER_PATH};  $F3D=$ENV{HIIEXPLORER_PATH};  require("$F3D/my.pl"); #("$F3D/scripts/my.pl"); # "/home/sanchez/sda2/code/R3D/my.pl";

if ($#ARGV<2) {
    print "USE: spec_extract_cube_error.pl INPUT.CUBE.fits SEGMENTATION.fits OUTPUT.RSS.FITS\n";
    exit;
}

$infile=$ARGV[0]."[1]";
$segfile=$ARGV[1];
$outfile=$ARGV[2];
$pt=$outfile;
$pt =~ s/fits/pt.txt/;

$a_in=rfits($infile);
$h=$a_in->gethdr;

($nx,$ny,$nz)=$a_in->dims;
$crval=$a_in->hdr->{CRVAL3};
$cdelt=$a_in->hdr->{CDELT3};
$crpix=$a_in->hdr->{CRPIX3};

$s_in=rfits($segfile);

($NX,$NY)=$s_in->dims;

$inverse_s=zeroes($NX,$NY);

if (($nx!=$NX)||($ny!=$NY)) {
    print "Dimensions does not match ($nx,$ny) != ($NX,$NY)\n";
    exit;
}

@DATA=stats($s_in);
$ns=$DATA[4];
#print "$ns sources detected\n"; exit;
$a_out=zeroes($nz,$ns);

@stats=stats($a_in);

#print "@stats\n"; exit;

my @x,@y,@npt;

$h_lim=10*($stats[2]);
$l_lim=0.001*($stats[2]);
$a_in=$a_in->clip($l_lim,$h_lim);
#hclip($a_in,$val_lim);
#inplace($a_in->hclip($val_lim,$val_lim));

#	for ($k=0;$k<$nz;$k++) {

#	    if ($val_now>$val_lim) {
#		set($a_in,$val_lim,($i,$j,$k));
#	    }
#	}


$nd=0;
for ($i=0;$i<$nx;$i++) {
    for ($j=0;$j<$ny;$j++) {

	$is=$s_in->at($i,$j);
	if ($is==0) {
	    set($inverse_s,$i,$j,1);
	}
	$is_out=$is-1;
	my $t=$a_out->slice(":,($is_out)");
	my $s=$a_in->slice("($i),($j),:");
	$s->inplace->badmask(0);
	$t .= $t+$s;	
	if ($is_out>=0) {
	    $x[$is_out]=$x[$is_out]+$i;
	    $y[$is_out]=$y[$is_out]+$j;
	    $npt[$is_out]=$npt[$is_out]+1;
	} else {
	    $nd++;
	}
    }
}

for ($j=0;$j<$ns;$j++) {    
    my $t=$a_out->slice(":,($j)");
    print "$j $npt[$j]\n";
    $t .= $t/$npt[$j];	
    
}

$a_out->hdr->{CRPIX1}=$crpix;
$a_out->hdr->{CRVAL1}=$crval;
$a_out->hdr->{CDELT1}=$cdelt;
$a_out->wfits($outfile);

$inverse_s->wfits("diffuse.fits");

$size=sqrt($nx**2+$ny**2)/(2*$ns);
open(OUT,">$pt");
print OUT "C $size $size 0\n";
for ($i=0;$i<$ns;$i++) {
    $x[$i]=$x[$i]/$npt[$i];
    $y[$i]=$y[$i]/$npt[$i];
    print OUT "$i $x[$i] $y[$i] 1\n";
}
close(OUT);

print "$outfile and $pt created\n";


exit;
