#!/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<2) {
    print "USE: rss_seg2cube.pl INPUT.RSS.fits SEGMENTATION.fits OUTPUT.CUBE.FITS\n";
    exit;
}

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

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

($nz,$N)=$a_in->dims;
$crval=$a_in->hdr->{CRVAL1};
$cdelt=$a_in->hdr->{CDELT1};
$crpix=$a_in->hdr->{CRPIX1};

$s_in=rfits($segfile);
($nx,$ny)=$s_in->dims;


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


for ($i=0;$i<$nx;$i++) {
    for ($j=0;$j<$ny;$j++) {
	$is=$s_in->at($i,$j);
	if ($is>0) {
	    $is_out=$is-1;
	    my $t=$out_cube->slice("($i),($j),:");
	    $s=$a_in->slice(":,($is_out)");
	    $t .= $s;
	}
    }
}

$out_cube->wfits($outfile);

print "$outfile created\n";


exit;
