#!/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{FIT3D_PATH}; $F3D=$ENV{FIT3D_PATH}; require("$F3D/scripts/my.pl"); #("$F3D/scripts/my.pl");

$PVERSION="1.2";
#    $convolve=1; # Determine the normalized resolution
   $convolve=0; # No not determine the normalized resolution

#$do_ftp=0; # Do not copy the results to the FTP
 $do_ftp=1;

$DIR_CONF="/disk-b/sanchez/ppak/legacy/";

$DIR_DATA=$DIR_CONF."/DATA/V1200/reduced_v".$PVERSION."/";
$DIR_WEB=$DIR_DATA."/web_".$TODAY."/";

$DIR_FTP="/reduced/V1200/";
$DIR_FTP_DATA=$DIR_FTP."reduced_v".$PVERSION."/";
$DIR_FTP_WEB=$DIR_FTP_DATA."/web_second/";



open(LOG,">second_glue.log");
open(PROD,">second_glue.out");

$call="rm -f *cube.fits";
mycall($call);
$call="rm -f *sobj.fits";
mycall($call);
$call="rm -f *rss.fits";
mycall($call);
$call="rm -f *.V.fits";
mycall($call);
$call="rm -f *.B.fits";
mycall($call);

$call="rm -f SN_*.ps";
mycall($call);
$call="rm -f SN_*.out";
mycall($call);


$call="ls ../pmas*/*.sobj.fits > list.sobj.tmp";
mycall($call);


open(FH,"<list.sobj.tmp");
open(OUT,">list.sobj.txt");
while($line=<FH>) {
    chop($line);
    if (($line !~ "vstar")&&($line !~ "obj_")&&($line !~ "run")&&($line !~ "junk")) {
	print OUT "$line\n";
    }
}
close(OUT);
close(FH);


$nobj=0;
$n=0;
open(FH,"<list.sobj.txt");
while($line=<FH>) {
    chop($line);
    @data=split('/',$line);
    $sec=$data[2];
    @data2=split('_',$sec);
    $obj_now=$data2[0];
    $obj[$nobj]=$obj_now;
    $file[$n]=$line;
    $found=0;
    if ($nobj>0) {
	for ($i=0;$i<$nobj;$i++) {
	    if ($obj_now eq $obj[$i]) {
		$found=1;
	    }
	}
    }
    if ($found==0) {
	$nobj++;
    }
    $n++;
}
close(FH);



print "$n $nobj\n"; 

for ($j=0;$j<$nobj;$j++) {
    print "$j $obj[$j]\n";
}
#    exit;

for ($j=0;$j<$nobj;$j++) {
    $n_p_now=0;
    for ($JJ=1;$JJ<4;$JJ++) {
	$check=$obj[$j]."_p".$JJ;
	open(POINT,"cat list.sobj.txt | grep '$check' | wc -l |");
	$point=<POINT>;
	chop($point);
	close(POINT);
	if ($point>0) {
	    $p_now[$n_p_now]=$JJ;
	    $n_p_now++;
	}
    }
    print "$obj[$j] $n_p_now $n\n"; #exit;

    if ($n_p_now==3) {
	$call="rm -f HEADER.NOW";
	mycall($call);
	for ($i=0;$i<$n;$i++) {
	    @data=split('/',$file[$i]);
	    $dir=$data[1];
	    $sec=$data[2];
	    @data2=split('_',$sec);
	    $TODAY=$dir;
	    $cut="pmas_";
	    $TODAY =~ s/$cut//;
	    $cut="-";
	    $TODAY =~ s/$cut//g;

	    $obj_now=$data2[0];
	    if ($obj_now eq $obj[$j]) {
		if ($file[$i] =~ "p1") {
		    $call="cp ".$file[$i]." obj_p1.sobj.fits";
		    mycall($call);
		    $call="dump_header.pl obj_p1.sobj.fits DATE_".$TODAY." >> HEADER.NOW";
		    mycall($call);
		}
		if ($file[$i] =~ "p2") {
		    $call="cp ".$file[$i]." obj_p2.sobj.fits";
		    mycall($call);
		    $call="dump_header.pl obj_p2.sobj.fits  DATE_".$TODAY." >> HEADER.NOW";
		    mycall($call);
		}
		if ($file[$i] =~ "p3") {
		    $call="cp ".$file[$i]." obj_p3.sobj.fits";
		    mycall($call);
		    $call="dump_header.pl obj_p3.sobj.fits  DATE_".$TODAY." >> HEADER.NOW";
		    mycall($call);
		}
	    }
	}



	if (($cdelt==0.7)||($cdelt==2.0)) {
	    $call="radial_sum_rss.pl obj_p1.sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 -5 3 rad_1.rss.fits";
	} else {
	    $call="radial_sum_rss.pl obj_p1.sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 rad_1.rss.fits";
	}
	mycall($call);
	$call="img2spec.pl rad_1.rss.fits 4 rad_1.txt";
	mycall($call);
	open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/V_Johnson.txt rad_1.txt 0 |");
	while($LINE=<FH>) { 
	    $flux1=$LINE;
	}	chop($flux1);
	chop($flux1);
	close(FH);
	
	if (($cdelt==0.7)||($cdelt==2.0)) {
	    $call="radial_sum_rss.pl obj_p2.sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 2 9 rad_2.rss.fits";
	} else {
	$call="radial_sum_rss.pl obj_p2.sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 rad_2.rss.fits";
	}
	mycall($call);
	$call="img2spec.pl rad_2.rss.fits 4 rad_2.txt";
	mycall($call);
	open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/V_Johnson.txt rad_2.txt 0 |");
	while($LINE=<FH>) { 
	    $flux2=$LINE;
	}
#	$flux2=<FH>;
	chop($flux2);
	close(FH);
	
	$call="radial_sum_rss.pl obj_p3.sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 rad_3.rss.fits";
	mycall($call);
	$call="img2spec.pl rad_3.rss.fits 4 rad_3.txt";
	mycall($call);
	open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/V_Johnson.txt rad_3.txt 0 |");
	while($LINE=<FH>) { 
	    $flux3=$LINE;
	}
#	$flux3=<FH>;
	chop($flux3);
	close(FH);
	
	print "FLUXES = $flux1 $flux2 $flux3\n";
	print LOG "FLUXES = $flux1 $flux2 $flux3\n";

	$add_line="PIPE_flux_ratio1 | ".$flux1;
	add_to_file("HEADER.NOW",$add_line);
	$add_line="PIPE_flux_ratio2 | ".$flux2;
	add_to_file("HEADER.NOW",$add_line);
	$add_line="PIPE_flux_ratio3 | ".$flux3;
	add_to_file("HEADER.NOW",$add_line);

	 @fluxes=($flux1,$flux2,$flux3);
	($min_flux,$max_flux)=minmax(@fluxes);
	$mean_flux=mean(@fluxes);
	if ($mean_flux!=0) {
	    $range_fluxes=($max_flux-$min_flux)/$mean_flux;
	} else {
	    $range_fluxes=($max_flux-$min_flux);
	}
	$add_line="PIPE_range_flux | ".$range_fluxes;
	add_to_file("HEADER.NOW",$add_line);
	
	
	$F=0.05;
	$call="comp_spec.pl rad_2.txt rad_1.txt rad.txt 4000 4500 101";
	mycall($call);
	open(COMP,"<comp_spec.out");
	$comp=<COMP>;
	chop($comp);
	close(COMP);
	@d_comp=split(" ",$comp);
	$rat12=$d_comp[0];
	if (($flux1>0)&&($flux2>0)) {
#	$rat12=$flux2/$flux1;
	    if (($rat12<(1-$F))||($rat12>(1+$F))) {
#	    $call="imarith.pl obj_p2.sobj.fits / ".$rat12." obj_p2.sobj.fits";
		$call="polyfit_spec.pl rad.txt 2 new_rad.txt 300 1900 /null";
		mycall($call);
		$call="spec2img.pl new_rad.txt rad.fits 331";
		mycall($call);
		$call="imarith.pl obj_p2.sobj.fits '*' rad.fits obj_p2.sobj.fits";
		mycall($call);
	    }
	}
	$call="comp_spec.pl rad_3.txt rad_1.txt rad.txt 4000 4500 101";
	mycall($call);
	open(COMP,"<comp_spec.out");
	$comp=<COMP>;
	chop($comp);
	close(COMP);
	@d_comp=split(" ",$comp);
	$rat13=$d_comp[0];
	if (($flux1>0)&&($flux3>0)) {
#	$rat13=$flux3/$flux1;
	    if (($rat13<(1-$F))||($rat13>(1+$F))) {
#	    $call="imarith.pl obj_p3.sobj.fits / ".$rat13." obj_p3.sobj.fits";
		$call="polyfit_spec.pl rad.txt 2 new_rad.txt 300 1900 /null";
		mycall($call);
		$call="spec2img.pl new_rad.txt rad.fits 331";
#	    $call="spec2img.pl rad.txt rad.fits 331";
	    mycall($call);
	    $call="imarith.pl obj_p3.sobj.fits '*' rad.fits obj_p3.sobj.fits";
	    mycall($call);
#	    mycall($call);
	}
    }


#	$rat21=$flux2/$flux1;
#	if (($rat21<0.95)||($rat21>1.05)) {
#	    $call="imarith.pl obj_p2.sobj.fits / ".$rat21." obj_p2.sobj.fits";
#	    mycall($call);
#	}
	
#	$rat31=$flux3/$flux1;
#	if (($rat31<0.95)||($rat31>1.05)) {
#	    $call="imarith.pl obj_p3.sobj.fits / ".$rat31." obj_p3.sobj.fits";
#	    mycall($call);
#	}
	
	
#    exit;

#	print "TODAY = $TODAY"; exit;

	if ($TODAY<20110000) {
	    $call="Mosaic_rss.pl ".$DIR_CONF."/mos_new.config mos.rss.fits mos.pt.txt";
	} else {
	    $call="Mosaic_rss.pl ".$DIR_CONF."/mos_new_2.config mos.rss.fits mos.pt.txt";
	}
	
	
#	$call="Mosaic_rss.pl ".$DIR_CONF."/mos_new.config mos.rss.fits mos.pt.txt";
	mycall($call);
	$pdl=rfits("mos.rss.fits");
	$cdelt=$pdl->hdr->{CDELT1};
	if ($cdelt==0.7) {
	    if ($TODAY<20110000) {
		$call="rss2rss_mask_ppak.pl mos.rss.fits ".$DIR_CONF."/mos_new.pt.txt ".$DIR_CONF."/mask_V1200.rss.fits mmos.rss.fits 1";
	    } else {
		$call="rss2rss_mask_ppak.pl mos.rss.fits ".$DIR_CONF."/mos_new_2.pt.txt ".$DIR_CONF."/mask_V1200.rss.fits mmos.rss.fits 1";
	    }
	} 
	if ($cdelt==2) {
	    if ($TODAY<20110000) {
		$call="rss2rss_mask_ppak.pl mos.rss.fits ".$DIR_CONF."/mos_new.pt.txt ".$DIR_CONF."/mask_V500.rss.fits mmos.rss.fits 3";
	    } else {
		$call="rss2rss_mask_ppak.pl mos.rss.fits ".$DIR_CONF."/mos_new_2.pt.txt ".$DIR_CONF."/mask_V500.rss.fits mmos.rss.fits 3";
	    }
	} 
	if ($cdelt==1.5) {
	    $call="rss2rss_mask_ppak.pl mos.rss.fits ".$DIR_CONF."/mos.pt.txt ".$DIR_CONF."/mask.rss.fits mmos.rss.fits";
	} 
	if ($cdelt==3.2) {
	    $call="cp mos.rss.fits mmos.rss.fits";
	}
	


	mycall($call);
	$call="cp mmos.rss.fits ".$obj[$j].".rss.fits";
	mycall($call);


#	$call="cp mos.rss.fits mos_".$obj[$j].".rss.fits";
#	mycall($call);
#	$call="cp mos.ps.txt mos_".$obj[$j].".pt.txt";
#	mycall($call);
	
#	exit;


	$call="rm -f ".$obj[$j].".cube.fits ";
	mycall($call);
#	$call="rss2cube.tcl mmos.rss.fits mos.pt.txt ".$obj[$j].".cube.fits 3 1e-12 1";
#	$call="rss2cube_int.pl mmos.rss.fits mos.pt.txt 1 ".$obj[$j].".cube.fits 2 5 1";

	$call="rss2cube_int.pl mmos.rss.fits mos.pt.txt 1 ".$obj[$j].".cube.fits 2 5 1";
	if ($cdelt==0.7) {
	    $call="rss2cube_int_mask.pl mmos.rss.fits ".$DIR_CONF."/mask_V1200.rss.fits mos.pt.txt 1 ".$obj[$j].".cube.fits 2 5 1";
	}
	if ($cdelt==2) {
	    $call="rss2cube_int_mask.pl mmos.rss.fits ".$DIR_CONF."/mask_V500.rss.fits mos.pt.txt 1 ".$obj[$j].".cube.fits 2 5 1";
	}
	mycall($call);

	if ($cdelt==2) {
	    $call="get_flux_stats_cube.pl ".$obj[$j].".cube.fits 5800 40 3745 2.0 SN_".$obj[$j].".ps/CPS 1 > SN_".$obj[$j].".out";
	}
	if ($cdelt==0.7) {
	    $call="get_flux_stats_cube.pl ".$obj[$j].".cube.fits 4500 40 3400 0.7 SN_".$obj[$j].".ps/CPS 1 > SN_".$obj[$j].".out";
	}

	if ($cdelt==3.2) {
	    $call="get_flux_stats_cube.pl ".$obj[$j].".cube.fits 5800 40 3620 3.2 SN_".$obj[$j].".ps/CPS 1 > SN_".$obj[$j].".out";
	}

	if ($cdelt==1.5) {
	    $call="get_flux_stats_cube.pl ".$obj[$j].".cube.fits 5800 40 3845 1.5 SN_".$obj[$j].".ps/CPS 1 > SN_".$obj[$j].".out";
	}

	mycall($call);


	print PROD "$obj[$j].cube.fits $cdelt\n";

	$call="cp mmos.rss.fits mos_".$obj[$j].".rss.fits";
	mycall($call);
	$call="cp mos.pt.txt mos_".$obj[$j].".pt.txt";
	mycall($call);




	
#    exit;
	
#
# We look for the peak intensity!
#

	if ($cdelt!=0.7) {

	    $call="get_slice.pl ".$obj[$j].".cube.fits img /disk-b/sanchez/ppak/legacy/slice_V.conf";
	    mycall($call);
	    $img=rfits("img_V_4500_5500.fits");
	    ($nx,$ny)=$img->dims;
	    $val_max=-1e12;
	    $XC=37;
	    $YC=37;
	    for ($ii=30;$ii<45;$ii++) {
		for ($jj=30;$jj<45;$jj++) {
		    $val=$img->at($ii,$jj);
		    if ($val>$val_max) {
			$val_max=$val;
			$XC=$ii;
			$YC=$jj;
	    }
		}
	    }
	    
	    $call="cp img_V_4500_5500.fits ".$obj[$j].".V.fits";
	    mycall($call);
	    
	    $call="rm -r ".$obj[$j].".scube.fits ";
	    mycall($call);
	    $call="DAR_det_cube.pl ".$obj[$j].".cube.fits  ".$XC." ".$YC." 3 3 ".$obj[$j].".scube.fits 400 1900 3 1 0  0 1";
	    mycall($call);
	    
# $call="DAR_det_cube.pl ".$name_obj[$j].".cube.fits  ".$XC." ".$YC." 3 3 ".$name_obj[$j].".scube.fits 400 1900 3 1 0  0 1";
#    mycall($call);
	    
	    $add_line="PIPE_DAR_cor_ps | DAR_".$obj[$j].".cube.ps";
	    add_to_file("HEADER.NOW",$add_line);
	    $add_line="PIPE_V_4500_5500 | ".$obj[$j].".V.fits";
	    add_to_file("HEADER.NOW",$add_line);
	    
	    $call="add_header.pl mos_".$obj[$j].".rss.fits HEADER.NOW";
	    mycall($call);
	    $call="add_header.pl ".$obj[$j].".cube.fits HEADER.NOW";
	    mycall($call);
	    $call="add_header.pl ".$obj[$j].".scube.fits HEADER.NOW";
	    mycall($call);
	    
	    $call="get_aper_spec_scube.pl ".$obj[$j]." V > new_center.txt";
	    mycall($call);
	    $out_SDSS=$obj[$j].".comp_SDSS.out"; 
	    $call=$DIR_CONF."/spec_comp_SDSS.pl ".$obj[$j].".spec_30.txt none ".$obj[$j].".comp_SDSS.ps/CPS 5000 -1 400 3400 8000 > ".$out_SDSS;
	    mycall($call);
	    open(CSDSS,"<$out_SDSS");
	    $csdss=<CSDSS>;
	    close(CSDSS);
	    chop($csdss);
	    ($name_junk,$fact_sdss,$fact_sdss_g,$fact_sdss_r)=split(" ",$csdss);
	    if ($fact_sdss>0) {
		$rat=1/$fact_sdss;
		$call="recal_cube_const.pl ".$obj[$j].".scube.fits ".$rat." ".$obj[$j].".V1200.rscube.fits";
		mycall($call);
	    }
	    

	    
	    print PROD "$obj[$j].rscube.fits\n";
	    $add_line="PIPE_flux_recal | ".$fact_sdss;
	    add_to_file("HEADER.NOW",$add_line);
	    $add_line="PIPE_flux_recal_g | ".$fact_sdss_g;
	    add_to_file("HEADER.NOW",$add_line);
	    $add_line="PIPE_flux_recal_r | ".$fact_sdss_r;
	    add_to_file("HEADER.NOW",$add_line);
	    $add_line="PIPE_VERSION | ".$PVERSION;
	    add_to_file("HEADER.NOW",$add_line);
	    
	    
	    $call="add_header.pl ".$obj[$j].".V1200.rscube.fits HEADER.NOW";
	    mycall($call);    
	    
    $RA_now=0;
    $DEC_now=0;
    $call=$DIR_CONF."/get_coords.pl ".$DIR_CONF."/CALIFA-parentsample.csv.2mass.galex.IRAS.NAME ".$obj[$j]." > coords.txt";
    mycall($call);
    open(TMP,"<coords.txt");
    $tmp=<TMP>; chop($tmp);
    close(TMP);
    @dat_tmp=split(" ",$tmp);
    $RA_now=$dat_tmp[1];
    $DEC_now=$dat_tmp[2];

    if (($RA_now==0)&&($DEC_now==0)) {
	$call="rm -f coords.txt";
	mycall($call);
	$call="wget -nd 'http://nedwww.ipac.caltech.edu/cgi-bin/nph-objsearch?objname=".$obj[$j]."&extend=no&hconst=73&omegam=0.27&omegav=0.73&corr_z=1&out_csys=Equatorial&out_equinox=J2000.0&obj_sort=RA+or+Longitude&of=pre_text&zv_breaker=30000.0&list_limit=5&img_stamp=YES&of=ascii_bar' -O coords.txt";
	mycall($call);

	open(TMP,"<coords.txt");
	while($tmp=<TMP>) {
	    chop($tmp);   
	    @dat_tmp=split(/\|/,$tmp);
	    $RA_now=$dat_tmp[2];
	    $DEC_now=$dat_tmp[3];	    
	}	
	close(TMP);

    }
    open(TMP,"<new_center.txt");
    $tmp=<TMP>; chop($tmp);
    close(TMP);
    ($junk,$CX,$CY)=split(" ",$tmp);
    $CX=$CX+0.5;
    $CY=$CY+0.5;
	       $call="rm -r HEADER.COORDS";
    mycall($call);
    
    $add_line="WCSAXES |                       2 ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="WCSNAME |    TELESCOPE                                                         ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="RADESYS |    ICRS                                                              ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CTYPE1  |    RA---TAN                                                          ";
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRPIX1  |             ".$CX;
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRVAL1  |             ".$RA_now;
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CUNIT1  |    deg                                                               ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CTYPE2  |    DEC--TAN                                                          ";
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRPIX2  |               ".$CY;
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRVAL2  |               ".$DEC_now;

    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CUNIT2  |    deg                                                               ";

    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CD1_1   |           -0.0002777777                                              ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CD1_2   |            0.00000                                                   ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CD2_1   |            0.00000                                                   ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CD2_2   |           -0.0002777777     ";
    add_to_file("HEADER.COORDS",$add_line);

	    
	    $call="add_header.pl ".$obj[$j].".V1200.rscube.fits HEADER.COORDS";
    mycall($call);    
    $call="write_img_header.pl ".$obj[$j].".V1200.rscube.fits CRVAL1 ".$RA_now;
    mycall($call);    
    $call="write_img_header.pl ".$obj[$j].".V1200.rscube.fits CRVAL2 ".$DEC_now;
    mycall($call);    
    $call="write_img_header.pl ".$obj[$j].".V1200.rscube.fits CRPIX1 ".$CX;
    mycall($call);    
    $call="write_img_header.pl ".$obj[$j].".V1200.rscube.fits CRPIX2 ".$CY;
    mycall($call);    

    $call="write_img_header.pl ".$obj[$j].".V1200.rscube.fits FILENAME ".$obj[$j].".V1200.rscube.fits";
    mycall($call);    

    $call="write_img_header.pl ".$obj[$j].".V.fits CRVAL1 ".$RA_now;
    mycall($call);    
    $call="write_img_header.pl ".$obj[$j].".V.fits CRVAL2 ".$DEC_now;
    mycall($call);    
    $call="write_img_header.pl ".$obj[$j].".V.fits CRPIX1 ".$CX;
    mycall($call);    
    $call="write_img_header.pl ".$obj[$j].".V.fits CRPIX2 ".$CY;
    mycall($call);    

    $call="add_header.pl ".$obj[$j].".V.fits HEADER.COORDS";
    mycall($call);    

    $call="get_flux_stats_cube.pl ".$obj[$j].".V1200.rscube.fits 5800 40 3745 2.0 SN_".$obj[$j].".ps/CPS 1 > SN_".$obj[$j].".out";
    mycall($call);
    $SNfile="SN_".$obj[$j].".out";
    open(SN,"<$SNfile");
    while($SN=<SN>) {
	chop($SN);
	if ($SN !~ "#") {
	    @SN_data=split(" ",$SN);
	    $call="rm -r HEADER.SN";
	    mycall($call);    
	    $add_line="PIPE_VMAG3SIGMA | ".$SN_data[5];
	    add_to_file("HEADER.SN",$add_line);	    
	    $add_line="PIPE_VMAG5SIGMA | ".$SN_data[8];
	    add_to_file("HEADER.SN",$add_line);	    
	    if ($SN_data[1]!=0) {
		$area=$SN_data[6]/$SN_data[1];
	    }
	    $add_line="PIPE_AREA3SIGMA | ".$area;
	    add_to_file("HEADER.SN",$add_line);	    
	    $call="add_header.pl ".$obj[$j].".V1200.rscube.fits HEADER.SN";
	    mycall($call);    
	}
    }
    close(SN);
	    
	
	    print PROD "$obj[$j].scube.fits\n";
	} else {

	    $call="get_slice.pl ".$obj[$j].".cube.fits img /disk-b/sanchez/ppak/legacy/slice_B.conf";
	    mycall($call);
	    $img=rfits("img_B_3900_4550.fits");
	    ($nx,$ny)=$img->dims;
	    $val_max=-1e12;
	    $XC=37;
	    $YC=37;
	    for ($ii=30;$ii<45;$ii++) {
		for ($jj=30;$jj<45;$jj++) {
		$val=$img->at($ii,$jj);
		if ($val>$val_max) {
		    $val_max=$val;
		    $XC=$ii;
		    $YC=$jj;
		}
		}
	    }

	    $Xc=37;
	    $Yc=37;
	    for ($ii=15;$ii<60;$ii++) {
		for ($jj=15;$jj<60;$jj++) {
		$val=$img->at($ii,$jj);
		if ($val>$val_max) {
		    $val_max=$val;
		    $Xc=$ii;
		    $Yc=$jj;
		}
		}
	    }
	    
	    $call="cp img_B_3900_4550.fits ".$obj[$j].".B.fits";
	    mycall($call);
	    
	    $call="rm -r ".$obj[$j].".scube.fits ";
	    mycall($call);
#	    $call="DAR_det_cube.pl ".$obj[$j].".cube.fits  ".$XC." ".$YC." 4 4 ".$obj[$j].".scube.fits 20 2050 3 1 0  0 1";
#	    mycall($call);

	    $call="DAR_det_cube.pl ".$obj[$j].".cube.fits  ".$Xc." ".$Yc." 2 2 ".$obj[$j].".scube.fits 550 1900 3 1 0  0 1";
	    mycall($call);
	    
	    $add_line="PIPE_DAR_cor_ps | DAR_".$obj[$j].".cube.ps";
	    add_to_file("HEADER.NOW",$add_line);
	    $add_line="PIPE_V_4500_5500 | ".$obj[$j].".B.fits";
	    add_to_file("HEADER.NOW",$add_line);
	    
	    $add_line="PIPE_VERSION | ".$PVERSION;
	    add_to_file("HEADER.NOW",$add_line);
	    
	    $call="add_header.pl mos_".$obj[$j].".rss.fits HEADER.NOW";
	    mycall($call);


	    $call="get_flux_stats_cube.pl ".$obj[$j].".cube.fits 4500 40 3400 0.7 SN_".$obj[$j].".ps/CPS 1 > SN_".$obj[$j].".out";
	    mycall($call);
	    
	    
	    $call="get_aper_spec_scube.pl ".$obj[$j]." B > new_center.txt";
	    mycall($call);
	    $call="cp ".$obj[$j].".spec_20.txt ".$obj[$j].".NC.V1200.spec_20.txt";
	    mycall($call);
	    
	    #
	    # We get the astrometric solution
	    #
	    $RA_now=0;
	    $DEC_now=0;
	    $call=$DIR_CONF."/get_coords.pl ".$DIR_CONF."/CALIFA-parentsample.csv.2mass.galex.IRAS.NAME ".$obj[$j]." > coords.txt";
	    mycall($call);
	    open(TMP,"<coords.txt");
	    $tmp=<TMP>; chop($tmp);
	    close(TMP);
	    @dat_tmp=split(" ",$tmp);
	    $RA_now=$dat_tmp[1];
	    $DEC_now=$dat_tmp[2];
	    
	    if (($RA_now==0)&&($DEC_now==0)) {
		$call="rm -f coords.txt";
		mycall($call);
		$call="wget -nd 'http://nedwww.ipac.caltech.edu/cgi-bin/nph-objsearch?objname=".$obj[$j]."&extend=no&hconst=73&omegam=0.27&omegav=0.73&corr_z=1&out_csys=Equatorial&out_equinox=J2000.0&obj_sort=RA+or+Longitude&of=pre_text&zv_breaker=30000.0&list_limit=5&img_stamp=YES&of=ascii_bar' -O coords.txt";
		mycall($call);
		
		open(TMP,"<coords.txt");
		while($tmp=<TMP>) {
		    chop($tmp);   
		    @dat_tmp=split(/\|/,$tmp);
		    $RA_now=$dat_tmp[2];
		    $DEC_now=$dat_tmp[3];	    
		}	
		close(TMP);
		
	    }
	    open(TMP,"<new_center.txt");
	    $tmp=<TMP>; chop($tmp);
	    close(TMP);
	    ($junk,$CX,$CY)=split(" ",$tmp);
	    $CX=$CX+0.5;
	    $CY=$CY+0.5;




	    $call="add_header.pl ".$obj[$j].".cube.fits HEADER.NOW";
	    mycall($call);
	    $call="add_header.pl ".$obj[$j].".scube.fits HEADER.NOW";
	    mycall($call);


    $call="rm -r HEADER.COORDS";
    mycall($call);
    
    $add_line="WCSAXES |                       2 ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="WCSNAME |    TELESCOPE                                                         ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="RADESYS |    ICRS                                                              ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CTYPE1  |    RA---TAN                                                          ";
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRPIX1  |             ".$CX;
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRVAL1  |             ".$RA_now;
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CUNIT1  |    deg                                                               ";
    add_to_file("HEADER.COORDS",$add_line);
    $add_line="CTYPE2  |    DEC--TAN                                                          ";
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRPIX2  |               ".$CY;
#    add_to_file("HEADER.COORDS",$add_line);
#    $add_line="CRVAL2  |               ".$DEC_now;

	    add_to_file("HEADER.COORDS",$add_line);
	    $add_line="CUNIT2  |    deg                                                               ";
	    
	    add_to_file("HEADER.COORDS",$add_line);
	    $add_line="CD1_1   |           -0.0002777777                                              ";
	    add_to_file("HEADER.COORDS",$add_line);
	    $add_line="CD1_2   |            0.00000                                                   ";
	    add_to_file("HEADER.COORDS",$add_line);
	    $add_line="CD2_1   |            0.00000                                                   ";
	    add_to_file("HEADER.COORDS",$add_line);
	    $add_line="CD2_2   |           -0.0002777777     ";
	    add_to_file("HEADER.COORDS",$add_line);
	    
	    $call="add_header.pl ".$obj[$j].".scube.fits HEADER.COORDS";
	    mycall($call);    
	    $call="write_img_header.pl ".$obj[$j].".scube.fits CRVAL1 ".$RA_now;
	    mycall($call);    
	    $call="write_img_header.pl ".$obj[$j].".scube.fits CRVAL2 ".$DEC_now;
	    mycall($call);    
	    $call="write_img_header.pl ".$obj[$j].".scube.fits CRPIX1 ".$CX;
	    mycall($call);    
	    $call="write_img_header.pl ".$obj[$j].".scube.fits CRPIX2 ".$CY;
	    mycall($call);    
	    
	    $call="write_img_header.pl ".$obj[$j].".B.fits CRVAL1 ".$RA_now;
	    mycall($call);    
	    $call="write_img_header.pl ".$obj[$j].".B.fits CRVAL2 ".$DEC_now;
	    mycall($call);    
	    $call="write_img_header.pl ".$obj[$j].".B.fits CRPIX1 ".$CX;
	    mycall($call);    
	    $call="write_img_header.pl ".$obj[$j].".B.fits CRPIX2 ".$CY;
	    mycall($call);    
	    
	    $call="add_header.pl ".$obj[$j].".B.fits HEADER.COORDS";
	    mycall($call);    
	    

    open(LS,"ls -t ../../V500/*/$obj[$j].rscube.fits |");
    $V500_cube=<LS>;
    chop($V500_cube);
    close(LS);
    
    if ($V500_cube eq "") {
	$call="write_img_header.pl ".$obj[$j].".scube.fits V500CUBE none";
	mycall($call);    
	$SNfile="SN_".$obj[$j].".out";
	open(SN,"<$SNfile");
	while($SN=<SN>) {
	    chop($SN);
	    if ($SN !~ "#") {
		@SN_data=split(" ",$SN);
		$call="rm -r HEADER.SN";
		mycall($call);    
		$add_line="PIPE_VMAG3SIGMA | ".$SN_data[5];
		add_to_file("HEADER.SN",$add_line);	    
		$add_line="PIPE_VMAG5SIGMA | ".$SN_data[8];
		add_to_file("HEADER.SN",$add_line);	    
		if ($SN_data[1]!=0) {
		    $area=$SN_data[6]/$SN_data[1];
		}
		$add_line="PIPE_AREA3SIGMA | ".$area;
		add_to_file("HEADER.SN",$add_line);	    
		$call="add_header.pl ".$obj[$j].".scube.fits HEADER.SN";
		mycall($call);    
	    }
	}
	close(SN);
	


    } else {
	@DAT_CUBE=split(/\//,$V500_cube);
	$name_V500=$DAT_CUBE[$#DAT_CUBE];
	$call="write_img_header.pl ".$obj[$j].".scube.fits V500CUBE '$name_V500'";
	mycall($call);    
	$V=$V500_cube;
	$V =~ s/rscube/V/;
	$img=rfits($V);
	($nx,$ny)=$img->dims;
	$val_max=-1e12;
	$XC=38;
	$YC=42;
	for ($ii=35;$ii<45;$ii++) {
	    for ($jj=35;$jj<45;$jj++) {
		$val=$img->at($ii,$jj);
		if ($val>$val_max) {
		    $val_max=$val;
		    $XC=$ii;
		    $YC=$jj;
		}
	    }
	}

#	print "PASO\n";
	$call="radial_sum_cube.pl ".$V500_cube." 2.5 ".$XC." ".$YC." rad.V500.rss.fits 2";
	mycall($call);
	$call="img2spec.pl rad.V500.rss.fits 3 ".$obj[$j].".FC.V500.spec_20.txt";
	mycall($call);
	$call="flux_comp.pl ".$obj[$j].".NC.V1200.spec_20.txt ".$obj[$j].".FC.V500.spec_20.txt rat.FC.txt 1 5 0 2 3745 4800";
	mycall($call);
#	print "$call\n";
	

	$call="polyfit_spec.pl rat.FC.txt 4 out_rat.FC.txt 500 2000";
	mycall($call);
	
	$call="recal_cube.pl ".$obj[$j].".scube.fits out_rat.FC.txt ".$obj[$j].".V1200.rscube.fits";
	mycall($call);
	$call="add_header.pl ".$obj[$j].".V1200.rscube.fits HEADER.NOW";
	mycall($call);    
	$call="add_header.pl ".$obj[$j].".V1200.rscube.fits HEADER.COORDS";
	mycall($call);    

	$call="write_img_header.pl ".$obj[$j].".V1200.rscube.fits V500RECAL 1";
	mycall($call);    

	$call="get_flux_stats_cube.pl ".$obj[$j].".V1200.rscube.fits 4500 40 3400 0.7 SN_".$obj[$j].".ps/CPS 1 > SN_".$obj[$j].".out";
	mycall($call);
	
	$SNfile="SN_".$obj[$j].".out";
	open(SN,"<$SNfile");
	while($SN=<SN>) {
	chop($SN);
	if ($SN !~ "#") {
	    @SN_data=split(" ",$SN);
	    $call="rm -r HEADER.SN";
	    mycall($call);    
	    $add_line="PIPE_VMAG3SIGMA | ".$SN_data[5];
	    add_to_file("HEADER.SN",$add_line);	    
	    $add_line="PIPE_VMAG5SIGMA | ".$SN_data[8];
	    add_to_file("HEADER.SN",$add_line);	    
	    if ($SN_data[1]!=0) {
		$area=$SN_data[6]/$SN_data[1];
	    }
	    $add_line="PIPE_AREA3SIGMA | ".$area;
	    add_to_file("HEADER.SN",$add_line);	    
	    $call="add_header.pl ".$obj[$j].".V1200.rscube.fits HEADER.SN";
	    mycall($call);    
	}
	}
	close(SN);

	$call="get_slice.pl ".$obj[$j].".V1200.rscube.fits img.V1200 /disk-b/sanchez/ppak/legacy/slice_B.conf";
	mycall($call);
	$call="cp img.V1200_B_3900_4550.fits ".$obj[$j].".V1200.B.fits";
	mycall($call);
	$call="get_aper_spec_rscube.pl ".$obj[$j].".V1200.rscube.fits B > new_center.txt";
	mycall($call);
	$call="cp ".$obj[$j].".V1200.spec_20.txt ".$obj[$j].".FC.V1200.spec_20.txt";
	mycall($call);
	$call="ls ".$obj[$j].".FC.V500.spec_20.txt > list.comp.spec ";
	mycall($call);
	$call="ls ".$obj[$j].".FC.V1200.spec_20.txt >> list.comp.spec ";
	mycall($call);
	$call=$DIR_CONF."/spectra_plot_V500_V1200.pl list.comp.spec spec_comp_V500_V1200.".$obj[$j].".ps/CPS -20 250 3700 5000 '".$obj[$j]."'";
	mycall($call);

    }





	}
	
	
    }
    
# print "OBJ=$j\n"; <stdin>;
   
}

$call="get_aper_spec_dir_rscube.pl B";
mycall($call);

#
# Last check on the wavelength calibration
#
$call=$DIR_CONF."/ana_cal_vel.V1200.pl 0";
mycall($call);
$call=$DIR_CONF."/vel_plot_all.V1200.pl > vel_plot_all.out";
mycall($call);
$call="grep ABSORP vel_plot_all.out > vel_plot_all.ABS";
mycall($call);

open(ABS,"<vel_plot_all.ABS");
while($line=<ABS>) {
    chop($line);
    @ABS=split(" ",$line);
    $call="write_img_header.pl ".$ABS[1].".V1200.rscube.fits PIPE_SYSVEL_MEDIAN ".$ABS[2];
    mycall($call);    
    $call="write_img_header.pl ".$ABS[1].".V1200.rscube.fits PIPE_SYSVEL_RMS ".$ABS[3];
    mycall($call);    
}
close(ABS);



$call="mkdir ".$DIR_DATA;
mycall($call);
$call="cp *cube.fits ".$DIR_DATA;
mycall($call);
$call="cp mos_*rss.fits ".$DIR_DATA;
mycall($call);
$call="cp mos_*.pt.txt ".$DIR_DATA;
mycall($call);
$call="cp *.spec_*.txt ".$DIR_DATA;
mycall($call);

$call="create_web_second.pl 1 3 ".$PVERSION;
mycall($call);

if ($do_ftp==1) {
    
    open(ORDERS,">input.ftp");
    print ORDERS "open ftp://mycalifa:myafi07lAc\@ftp.caha.es\n";
    print ORDERS "mkdir $DIR_FTP_DATA\n";
    print ORDERS "mkdir $DIR_FTP_WEB\n";
    print ORDERS "cd $DIR_FTP_DATA\n";
    print ORDERS "bin\n";
    print ORDERS "mput -f *cube.fits\n";
    print ORDERS "mput -f mos_*rss.fits\n";
    print ORDERS "mput -f mos_*pt.txt\n";
    print ORDERS "mput -f *.spec_*.fits\n";
    print ORDERS "mput -f vstar_$TODAY_*.fits\n";
    print ORDERS "cd $DIR_FTP_WEB\n";
    print ORDERS "lcd web\n";
    print ORDERS "mput -f *\n";
    print ORDERS "quit\n";
    close(ORDERS);
    $call="ncftp < input.ftp > output.ftp";
    mycall($call);
}




$call="rm -f *sobj.fits";
mycall($call);
$call="rm -f rad*rss.fits";
mycall($call);
$call="rm -f mos.*";
mycall($call);
$call="rm -f mmos.*";
mycall($call);
$call="rm -f rad*txt";
mycall($call);






exit;

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


sub add_to_file {
    my $file=$_[0];
    my $line=$_[1];
    open(DUMP,">>$file");
    print DUMP "$line\n";
    close(DUMP);
}


