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


$F3D=$ENV{HIIEXPLORER_PATH};  $F3D=$ENV{HIIEXPLORER_PATH};  require("$F3D/my.pl"); #("$F3D/scripts/my.pl"); # "/home/sanchez/sda1/perl/MY/my.pl";

if ($#ARGV<2) {
    print "USE: get_slice.pl INPUT_CUBE.fits redshift map_Ha.fits\n";
    exit;
}

$input_cube=$ARGV[0];
$redshift=$ARGV[1];
$output_map=$ARGV[2];
$output_cont="cont.".$output_map;
$output_EW="EW.".$output_map;

$start_w[0]=(6562-30)*(1+$redshift);
$end_w[0]=(6562+30)*(1+$redshift);
$start_w[1]=(6562-100-30)*(1+$redshift);
$end_w[1]=(6562-100+30)*(1+$redshift);
$start_w[2]=(6562+100-30)*(1+$redshift);
$end_w[2]=(6562+100+30)*(1+$redshift);
$ns=3;

print "$ns slices to cut\n";
print "Reading cube\n";
$b=rfits("$input_cube");
$h=$b->gethdr;
$crval3=$b->hdr->{CRVAL3};
$cdelt3=$b->hdr->{CDELT3};
($nx,$ny,$nz)=$b->dims;

for ($i=0;$i<$ns;$i++) {
    $start_i=int(($start_w[$i]-$crval3)/$cdelt3);
    $end_i=int(($end_w[$i]-$crval3)/$cdelt3);
    if (($start_i>-1)&&($end_i<$nz)) {
	$npix=$end_i-$start_i+1;
	my $a=$b->slice(",,$start_i:$end_i");
	my $c=average($a->xchg(0,2));
	$c=$c*($end_w[$i]-$start_w[$i]);
	my $d=$c->xchg(0,1);
	$map[$i]=$d;
	my $c=medover($a->xchg(0,2));
	$c=$c*($end_w[$i]-$start_w[$i]);
	my $d=$c->xchg(0,1);
	$map_med[$i]=$d;
    }
}

$map_cont=0.5*($map_med[1]+$map_med[2]);
$map_Ha=$map[0]-$map_cont;
#$map_EW_Ha=$map[0]/($map_cont/($start_w[0]-$end_w[0]));
$map_EW_Ha=$map_Ha/($map_cont/($start_w[0]-$end_w[0]));
$map_Ha->inplace->badmask(0);
$map_cont->inplace->badmask(0);
$map_EW_Ha->inplace->badmask(0);

$$h{NAXIS}=2;
$map_Ha->sethdr($h);
$map_cont->sethdr($h);
$map_EW_Ha->sethdr($h);
$map_Ha->wfits($output_map);
$map_cont->wfits($output_cont);
$map_EW_Ha->wfits($output_EW);


exit;






