#!/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/sda2/code/R3D/my.pl";


if ($#ARGV<3) {
    print "USE: spec_extract_diffuse.pl CUBE.fits Ha_map.fits diffuse.fits OUTPUT.RSS.FITS [LOWER_LIMIT]\n";
    exit;
}

$infile=$ARGV[0];
$Ha_file=$ARGV[1];
$segfile=$ARGV[2];
$out_difuse="seg.".$segfile;
$outfile=$ARGV[3];
$out_spec=$ARGV[3];
$out_spec =~ s/fits/spec/;

$lower_limit=0;
if ($#ARGV==4) {
    $lower_limit=$ARGV[4];
}


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

$Ha_map=rfits($Ha_file);
($NX1,$NY1)=$Ha_map->dims;
$s_in=rfits($segfile);
$seg_s_in=zeroes($NX1,$NY1);
($NX,$NY)=$s_in->dims;
if (($NX!=$NX1)||($NY!=$NY1)) {
    print "Dimensions does not match ($NX1,$NY1) != ($NX,$NY)\n";
    exit;
}

$my_map=$Ha_map*$s_in;

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

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

$my_map->wfits("test.int.fits");

$k=0;
for ($i=0;$i<$nx;$i++) {
    for ($j=0;$j<$ny;$j++) {
	$val=$my_map->at($i,$j);
	if ($val>$lower_limit) {
	    $F[$k]=$val;
	    $k++;
	}
    }
}

$med=mean(@F);
$sig=sigma(@F);

if ($med<$sig) {
    $sig=0.95*$med;
}

my @x,@y,@npt;
for ($i=0;$i<$nx;$i++) {
    for ($j=0;$j<$ny;$j++) {
	$val=$my_map->at($i,$j);
	$is_out=-1;
	if (($val>$lower_limit)&&($val<($med-0.5*$sig))) {
	    $is_out=0;
	    set($seg_s_in,$i,$j,1);
	    $K[0]=$K[0]+1;
	} 
	if (abs($val-$med)<=0.5*$sig) {
	    $is_out=1;
	    set($seg_s_in,$i,$j,2);
	    $K[1]=$K[1]+1;
	}
	if ($val>($med+0.5*$sig)) {
	    $is_out=2;
	    set($seg_s_in,$i,$j,3);
	    $K[2]=$K[2]+1;
	}
#	$is_out=$is-1;
	if ($is_out>=0) {
	    my $t=$a_out->slice(":,($is_out)");
	    my $s=$a_in->slice("($i),($j),:");
	    $s->inplace->badmask(0);
	    my $x=sum($s);
#	    @stats=stats($s);
#	    print "$x @stats\n";
#	    if ($x!=0) {
		$t .= $t+$s;	
		$x[$is_out]=$x[$is_out]+$i;
		$y[$is_out]=$y[$is_out]+$j;
		$npt[$is_out]=$npt[$is_out]+1;
#	    }
	}
    }
}

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

print "$outfile created\n";
print "$k diffuse points \n";
print "med = $med\n";
print "sig = $sig\n";
print "$K[0] F<med-sig\n";
print "$K[1] abs(F-med)<=sig\n";
print "$K[2] F>med-sig\n";

$a_sum=sumover($a_out->xchg(0,1));
#print $a_sum;

#$image->xchg(0,1)
open(OUT,">$out_spec");
for ($i=0;$i<$nz;$i++) {
    $w=$crval+$cdelt*$i;
    $f=$a_sum->at($i);
    $k=$i+1;
    print OUT "$k $w $f\n";
}
close(OUT);

$seg_s_in->wfits($out_difuse);

exit;
