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



system("rm -f spec_*_int*");
system("rm -f spec_*_clean*");
system("rm -f auto_ssp*.ps");
system("rm -f auto_ssp*.out");
system("rm -f elines_*.out");
system("rm -f indeces_*.out");
system("rm -f indeces_*.ps");
system("rm -f fit_auto_*.ps");
$call="rm -f indeces_*.out";
system($call);

#$templates="back_temp.txt.fits";
#$templates="miles_6.fits";
$templates="miles_2.fits";

$DIR_CONF="/disk-b/sanchez/ppak/legacy/";
open(LOG,">ana_int.log");


open(RED,"<redshift.list");
while($red=<RED>) {
    chop($red);
    @data=split(" ",$red);
    $guess{$data[0]}=$data[1];
}
close(RED);

open(FH,"</disk-a/sanchez/legacy/sample/NED_0.015_0.025_K_15.txt.out");
while($line=<FH>) {
    chop($line);
    if ($line !~ "#") {
	@data=split(/\|/,$line);
	$name=$data[0];
	$name =~ s/ //g;
	$redshift_SDSS{$name}=$data[3];
    }
}
close(FH);


$call="ls r_*.scube.fits > list.cube.txt";
mycall($call);


$n=0;
open(OBJ,"<list.cube.txt");
while($line=<OBJ>) {
    chop($line);
#    if (($line !~ "mod")&&($line !~ "res")&&($line !~ "r_")) {
    if (($line !~ "mod")&&($line !~ "res")) {
	@data=split('/',$line);    
	$obj_now=$data[0];
	if (($obj_now !~ "1P")&&($obj_now !~ "2P")) {
	    
	    $obj_now =~ s/\.//g;
	    $obj_now =~ s/scubefits//g;
	    $cut="r_";
	    $obj_now =~ s/$cut//g;
	    $obj[$n]=$obj_now;
	    $file[$n]=$line;    

#	    print "$n $obj[$n]\n"; exit;
	$in_pdl=rfits($file[$n]);
	$h=$in_pdl->gethdr;
	$pix=$h->{CDELT1};
	$crpix1=$h->{CRPIX1};
	$crval1=$h->{CRVAL1};
	$cdelt1=$h->{CDELT1};
	$crpix2=$h->{CRPIX2};
	$crval2=$h->{CRVAL2};
	$cdelt2=$h->{CDELT2};
	$crpix3=$h->{CRPIX3};
	$crval3=$h->{CRVAL3};
	$cdelt3=$h->{CDELT3};
	($nx,$ny,$nz)=$in_pdl->dims;
	$out_pdl=zeroes($nz);

	    if ($cdelt3>2) {
		$grat=0;
	    } else {
		$grat=1;
	    }
	    
	    print "$obj_now\n";
	    #$nz_new=$nz-50;
	    #$in_sec=$in_pdl->slice(",,50:$nz_new");
	    $mask=ones($nx,$ny);
	    for ($i=0;$i<$nz;$i++) {
		$mask_now=$in_pdl->slice(",,($i)");
		$mask=$mask*$mask_now;
	    }
#	    $mask->wfits("test.fits");
	    


	
	$V_img=$file[$n];
	$V_img =~ s/scube/V/g;


	    $call="get_slice_filter.pl ".$file[$n]." /home/sanchez/filters/V_Johnson.txt ".$V_img;
	    mycall($call);	    
	    $V_pdl=rfits($V_img);
	    @dims=$V_pdl->dims;


	    $nadd=0;
	    
	    $XC=0;
	    $YC=0;
	    $NC=0;
	    for ($j=0;$j<$ny;$j++) {
		for ($i=0;$i<$nx;$i++) {
		    $t=$in_pdl->slice("($i),($j),:");
		    $val=$V_pdl->at($i,$j);
		    $mask_now=$mask->at($i,$j);
		    if ($mask_now eq "nan") {
			$mask_val=0;
		    } else {
			$mask_val=1;		   
		    }
		    $val=$val*$mask_val;
		    if ($val>0.01) {
			$out_pdl=$out_pdl+$t;
			$nadd++;
		    }
		    if ($val>0.1) {
			$XC=$XC+$val*$i;
			$YC=$YC+$val*$j;
			$NC=$NC+$val;
		    }
		}
	    }
	    $XC=$XC/$NC;
	    $YC=$YC/$NC;
	    $YC=$ny-$YC;
	    print "$file[$n] $V_img $XC $YC\n";
	    print LOG "CENTROID $file[$n] $V_img $XC $YC\n";
	    $call="radial_sum_cube.pl ".$file[$n]." 3 ".$XC." ".$YC." radial.rss.fits 2";
	    mycall($call);
	    $out_cen="spec_".$obj[$n]."_cen.txt";
	    $out_cen_cor="spec_".$obj[$n]."_cen_cor.txt";
	    $out_cen_ps="radial_".$obj[$n]."_cen.ps";
	    $cube_name="r_".$obj[$n].".scube.fits";
	    $call="cp radial_sum_cube_0.ps ".$out_cen.ps;
	    mycall($call);
	    $call="img2spec.pl radial.rss.fits 0 ".$out_cen;
	    mycall($call);
	    print LOG "$obj[$n] added $nadd spaxels\n";
	    $input_redshift=$redshift_SDSS{$obj[$n]};
	    if ($input_redshift==0) {
		$input_redshift=0.009;
		$input_d_redshift=0.002;
		$input_min_redshift=0.005;
		$input_max_redshift=0.05;
	    } else {
		$input_redshift=$input_redshift-0.0005;
		$input_d_redshift=0.001;
		$input_min_redshift=$input_redshift-0.003;
		$input_max_redshift=$input_redshift+0.003;
	    }
	
	$out_int="spec_".$obj[$n]."_int.txt";
	open(OUT,">$out_int");
	for ($k=0;$k<$nz;$k++) {
	    $wave[$k]=$crval3+$cdelt3*(($crpix3-1)+$k);
	    $id=$k+1;
	    $val=$out_pdl->at($k);
	    print OUT "$id $wave[$k] $val\n";
	}
	close(OUT);
	
	$call="spec_plot.pl ".$out_int." /null -0.1 200 4500 5500 > spec_plot.out";
	mycall($call);
	open(OUT,"<spec_plot.out");
	$OUT=<OUT>;
	chop($OUT);
	@data=split(" ",$OUT);
	close(OUT);
	if ($data[0]>0) {
	    $Fmax=3*$data[0];#+11.5*$data[2];
	    $Fmin=-0.2*$data[0];
	} else {
	    $Fmax=400;
	    $Fmin=-10;
	}

#	    $Fmax=500;
	    $ps_out=$out_int;
	    $ps_out =~ s/txt/ps/;
	    $call="spec_plot.pl ".$out_int." ".$ps_out."/CPS -0.1 ".$Fmax." 3700 6900 > spec_plot.out";
	mycall($call);
	

#
# We find the redshift
#
	    
	    $redshift_guess=$guess{$out_int};
	    if ($redshift_guess>0) {
		$redshift_min=$redshift_guess-0.003;
		$redshift_max=$redshift_guess+0.003;
	    } else {
		$redshift_guess=0.01;
		$redshift_min=0.001;
		$redshift_max=0.06;
	    }
		

	    $plot=0;
	    $call="auto_ssp_elines_several.pl ".$out_int." /disk-b/sanchez/ppak/legacy/miles_2.fits out.txt /disk-b/sanchez/ppak/legacy/mask_elines_SDSS.txt /disk-b/sanchez/ppak/legacy/auto_ssp_SDSS_redshift.config ".$plot." ".$Fmin." ".$Fmax." 3800 4600 ".$DIR_CONF."/emission_lines_STRONG.txt ".$redshift_guess." 0.0003 ".$redshift_min." ".$redshift_max." > REDSHIFT.txt";
	    mycall($call);
	    open(RED,"<out.txt");
	    $lin=<RED>;
	    $lin=<RED>;
	    chop($lin);
	    @a_lin=split(" ",$lin);
	    
	    $redshift=$a_lin[4];
	    close(RED);
	    $vel=$redshift*300000;
	    print "$out_int $redshift ($redshift_guess) $vel | Now we FIT the SSP+GAS\n";
#	    exit;
	    print LOG "# $out_int $redshift $vel $redshift_guess | Now we FIT the SSP+GAS\n";
	    $input_redshift=$redshift;
	    $input_min_redshift=0.99*$redshift;
	    $input_max_redshift=1.01*$redshift;
	    $input_d_redshift=0.000;


	    if ($grat==0) {
		$call="auto_ssp_elines_several_log.pl ".$out_int." ".$DIR_CONF.$templates." auto_ssp.".$obj[$n].".out ".$DIR_CONF."/mask_elines.txt ".$DIR_CONF."/auto_ssp_V300_several.config  ".$plot." ".$Fmin." ".$Fmax." 3800 5800 ".$DIR_CONF."/emission_lines.txt ".$input_redshift." ".$input_d_redshift." ".$input_min_redshift." ".$input_max_redshift;
	    } else {
		$call="auto_ssp_elines_several_log.pl ".$out_int." ".$DIR_CONF.$templates." auto_ssp.".$obj[$n].".out ".$DIR_CONF."/mask_elines.txt ".$DIR_CONF."/auto_ssp_V600_several.config  ".$plot." ".$Fmin." ".$Fmax." 3870 5800 ".$DIR_CONF."/emission_lines.txt ".$input_redshift." ".$input_d_redshift." ".$input_min_redshift." ".$input_max_redshift;

	    }
	    mycall($call);
#	    print "Press Enter"; <stdin>;
	    $call="cp out.fit_spectra ".$obj[$n].".elines.out";
	    mycall($call);
	    $call="legacy_plot.pl ".$DIR_CONF."auto_ssp_elines.list auto_ssp.".$obj[$n].".ps/CPS ".$Fmin."  ".$Fmax." 3700 5800 ".$obj[$n]." ";
	    mycall($call);

#	    print "Press Enter\n"; <stdin>;
	    
	    $out_dir="OUTFIT_".$obj[$n];
	    $call="mkdir ".$out_dir;
	    mycall($call);
	    $call="cp org_spec.txt ".$out_dir."/";
	    mycall($call);
	    $call="cp mod_joint_spec.txt ".$out_dir."/";
	    mycall($call);
	    $call="cp model_spec.txt ".$out_dir."/";
	    mycall($call);
	    $call="cp res_joint_spec.txt ".$out_dir."/";
	    mycall($call);
	    $out_index="indeces_".$obj[$n].".out";
	    $out_index_ps="indeces_".$obj[$n].".ps";
	    $call="get_index.pl no_gas_spec.txt ".$redshift." ".$out_index_ps."/CPS > ".$out_index;
	    mycall($call);


#
# We analyze the central spectrum
#

#***************************************************************

	$call="spec_plot.pl ".$out_cen_cor." /null -0.1 200 4500 5500 > spec_plot.out";
	mycall($call);
	open(OUT,"<spec_plot.out");
	$OUT=<OUT>;
	chop($OUT);
	@data=split(" ",$OUT);
	close(OUT);
	if ($data[0]>0) {
	    $Fmax=3*$data[0];#+11.5*$data[2];
	    $Fmin=-0.2*$data[0];
	} else {
	    $Fmax=400;
	    $Fmin=-10;
	}

#	    $Fmax=500;
	    $ps_out=$out_cen;
	    $ps_out =~ s/txt/ps/;
	    $call="spec_plot.pl ".$out_cen_cor." ".$ps_out."/CPS -0.1 ".$Fmax." 3700 6900 > spec_plot.out";
	mycall($call);
	

#
# We founnd the redshift
#
#	    $redshift=$guess{$out_int};
	    $vel=$redshift*300000;
	    print "$out_cen $redshift $vel | Now we FIT the SSP+GAS\n";
	    print LOG "# $out_cen $redshift $vel | Now we FIT the SSP+GAS\n";
	    $input_redshift=$redshift;
	    $input_min_redshift=0.99*$redshift;
	    $input_max_redshift=1.01*$redshift;
	    $input_d_redshift=0.000;

	    if ($grat==0) {
		$call="auto_ssp_elines_several_log.pl ".$out_cen_cor." ".$DIR_CONF.$templates." auto_ssp.".$obj[$n]."_cen.out ".$DIR_CONF."/mask_elines.txt ".$DIR_CONF."/auto_ssp_V300_several.config  ".$plot." ".$Fmin." ".$Fmax." 3800 5800 ".$DIR_CONF."/emission_lines.txt ".$input_redshift." ".$input_d_redshift." ".$input_min_redshift." ".$input_max_redshift;
	    } else {
		$call="auto_ssp_elines_several_log.pl ".$out_cen_cor." ".$DIR_CONF.$templates." auto_ssp.".$obj[$n]."_cen.out ".$DIR_CONF."/mask_elines.txt ".$DIR_CONF."/auto_ssp_V600_several.config  ".$plot." ".$Fmin." ".$Fmax." 3870 5800 ".$DIR_CONF."/emission_lines.txt ".$input_redshift." ".$input_d_redshift." ".$input_min_redshift." ".$input_max_redshift;

	    }
	    mycall($call);
	    $call="cp out.fit_spectra ".$obj[$n]."_cen.elines.out";
	    mycall($call);
	    $call="legacy_plot.pl ".$DIR_CONF."auto_ssp_elines.list auto_ssp.".$obj[$n]."_cen.ps/CPS ".$Fmin."  ".$Fmax." 3700 6900 ".$obj[$n]." ";
	    mycall($call);

#	    print "Press Enter\n"; <stdin>;
	    
	    $out_dir="OUTFIT_".$obj[$n]."_cen";
	    $call="mkdir ".$out_dir;
	    mycall($call);
	    $call="cp org_spec.txt ".$out_dir."/";
	    mycall($call);
	    $call="cp mod_joint_spec.txt ".$out_dir."/";
	    mycall($call);
	    $call="cp model_spec.txt ".$out_dir."/";
	    mycall($call);
	    $call="cp res_joint_spec.txt ".$out_dir."/";
	    mycall($call);
	    $out_index="indeces_".$obj[$n].".out";
	    $out_index_ps="indeces_".$obj[$n]."_cen.ps";
	    $call="get_index.pl no_gas_spec.txt ".$redshift." ".$out_index_ps."/CPS > ".$out_index;
	    mycall($call);


#***************************************************************

# WE analyze the cube

	    $input_d_redshift=0.001;
	    $input_min_redshift=$input_redshift-0.00065;
	    $input_max_redshift=$input_redshift+0.00065;

	    if ($grat==0) {
		$call="auto_ssp_elines_several_cube.pl r_".$obj[$n].".scube.fits ".$DIR_CONF.$templates." auto_ssp.".$obj[$n].".cube.out ".$DIR_CONF."/mask_elines.txt ".$DIR_CONF."/auto_ssp_V300_several_cube.config  ".$plot." ".$Fmin." ".$Fmax." 3900 5800 ".$DIR_CONF."/emission_lines.txt ".$input_redshift." ".$input_d_redshift." ".$input_min_redshift." ".$input_max_redshift." 0.002 0.002";
	    } else {
		$call="auto_ssp_elines_several_cube.pl r_".$obj[$n].".scube.fits ".$DIR_CONF.$templates." auto_ssp.".$obj[$n].".cube.out ".$DIR_CONF."/mask_elines.txt ".$DIR_CONF."/auto_ssp_V600_several_cube.config  ".$plot." ".$Fmin." ".$Fmax." 3900 5800 ".$DIR_CONF."/emission_lines.txt ".$input_redshift." ".$input_d_redshift." ".$input_min_redshift." ".$input_max_redshift." 0.002 0.002";

	    }
	    mycall($call);

	    $call="map_auto_ssp.pl elines_auto_ssp.".$obj[$n].".cube.out maps.".$obj[$n];
	    mycall($call);

	    $call="get_index_cube.pl NG_auto_ssp.".$obj[$n].".cube.out.fits ".$input_redshift." /null";
	    mycall($call);


#	print "Press Enter\n"; <stdin>;
#	 exit;

	$n++;

    }

    }
}
close(OBJ);

print "$n completed targets\n";



close(LOG);
exit;

sub mycall {
    my $call=$_[0];
    print "$call | ";
    system($call);
    print LOG "$call\n";
    print "DONE\n";
}

