#!/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";


if ($#ARGV<3) {
    print "USE: SE2CUBE OUTFIT_INPUT.RSS.fits NOUT SEGMENTATION.fits OUTPUT.CUBE.FITS\n";
    exit;
}

$infile=$ARGV[0];
$nout=$ARGV[1];
$segfile=$ARGV[2];
$outfile=$ARGV[3];

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

($nx,$ns,$NMOD)=$a_in->dims;
$crval=$a_in->hdr->{CRVAL1};
$cdelt=$a_in->hdr->{CDELT1};
$crpix=$a_in->hdr->{CRPIX1};

$a_in_sec=$a_in->slice(":,:,($nout)");

$s_in=rfits($segfile);

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

$a_out=zeroes($NX,$NY,$nx);

for ($i=0;$i<$NX;$i++) {
    for ($j=0;$j<$NY;$j++) {
	$is=$s_in->at($i,$j);
	$is_out=$is-1;
	if ($is_out>=0) {
	    my $t=$a_out->slice("($i),($j),:");
	    my $s=$a_in_sec->slice(":,($is_out)");
	    $t .= $t+$s;	
	}
    }
}

$a_out->hdr->{CRPIX3}=$crpix;
$a_out->hdr->{CRVAL3}=$crval;
$a_out->hdr->{CDELT3}=$cdelt;
$a_out->wfits($outfile);


exit;
