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

#exit;


$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;


if ($#ARGV<0) {
    print "USE: auto_redu.pl DATE(YYYYMMDD) GLUE[0=NO/1=YES] [DX DY spots] [ARCHIVE CALIB] [CONVOLVE] [FTP]\n";
    exit;
}
$TODAY=$ARGV[0];
$GLUE=$ARGV[1];
$DX=$ARGV[2];
$DY=$ARGV[3];
$CALIB=0;
if ($#ARGV==4) {
    $CALIB=$ARGV[4];
}

if ($#ARGV==5) {
    $CALIB=$ARGV[4];
    $convolve=$ARGV[5];
}

if ($#ARGV==6) {
    $CALIB=$ARGV[4];
    $convolve=$ARGV[5];
    $do_ftp=$ARGV[6];
}




$TOMORROW=$TODAY+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_".$TODAY."/";


if ($TODAY<20110000) {
    $nframes=3;
} else {
    $nframes=2;
}

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


$call="cp ".$DIR_CONF."/emission_lines_V1200.sky .";
mycall($call);
$call="cp ".$DIR_CONF."/elines_ARC_V1200.txt .";
mycall($call);



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

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

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

$call="rm -f *_4358*.ps";
mycall($call);
$call="rm -f *_4358*.sky";
mycall($call);
$call="rm -f *.width.ps";
mycall($call);
$call="rm -f *.obj.ps";
mycall($call);
$call="rm -f *.sobj.ps";
mycall($call);

$call="rm -f mask.junkfits";
mycall($call);




#
# We glue all the CCDs
#
if ($GLUE==1) {
    print "Glueing the CCD data...\n";
    open(DIR,"ls *a.fits |");
    while($file=<DIR>) {
	chop($file);
	$cut="a.fits";
	$file =~ s/$cut//;
	$call="glue_new_pmas.pl ".$file;
	system($call);
    }
    close(DIR);
    print "DONE\n";
}

$call="cp ".$DIR_CONF."/CCDFlat.fits .";
mycall($call);
$call="cp ".$DIR_CONF."/ARC_V1200.dist.id ARC.dist.id";
mycall($call);
$call="cp ".$DIR_CONF."/ARC_V1200.disp.id ARC.disp.id";
mycall($call);
$call="cat /meteo/CAVEX/cavex.dat | grep ".$TODAY." > cavex.dat";
mycall($call);
$call="cat /meteo/CAVEX/cavex.dat | grep ".$TOMORROW." >> cavex.dat";
mycall($call);

#exit;

$nc=0;
open(FH,"<cavex.dat");
while($line=<FH>) {
    chop($line);
    @data=split(" ",$line);
    $date[$nc]=$data[1].$data[2];
    $av[$nc]=$data[5];
    $nc++;
}
close(FH);

#exit;



if ($GLUE==1) {

$call="get_object_V600.pl > object.txt";
mycall($call);



#
# We measure the spots location
#
$call="spots_list.pl object.txt ".$DIR_CONF."/spots_V1200.short ".$DX." ".$DY;
mycall($call);
$call="plot_spots_all.pl spots_".$TODAY.".ps/CPS 200";
mycall($call);



$call="get_object_ext.pl > object_ext.txt";
mycall($call);

}




#
# How many targets are?
#
$i=1;
$n_unc=0;
$n_com=0;
do {
    $OBJ_I="obj_".$i;
    open(FH,"cat object.txt | grep ' $OBJ_I' | wc -l |");
    $nfound=<FH>;
    chop($nfound);
    close(FH);
#    if (($nfound<9)&&($nfound!=0)) {
    if ($nfound>0) {
#    $nframes=2;
	if ($nfound<3*$nframes) {
	    $Jobj[$n_unc]=$i;
	    $n_unc++;
	} else {
	    $n_com++;
	}
    }
#    print "$FFF\n";
#    print "$i $nfound $n_com $n_unc\n";
    $i++;
} while ($nfound!=0);

#exit;




#print "Nunc=$n_unc Ncom=$n_com\n";

#exit;



$call="cat object.txt | grep BIAS > bias.txt";
mycall($call);

open(BIAS,"<bias.txt");
open(OUT,">bias.out");
while($line=<BIAS>) {
    chop($line);
    @data=split(" ",$line);
    $file=$data[0];
    open(IMSTAT,"imstats.pl $file 520 1080 50 50 | ");
    while($imstat=<IMSTAT>) {
	chop($imstat);
	@dat_imstat=split(" ",$imstat);
	$mean=$dat_imstat[0];
	$rms=$dat_imstat[1];
	if ((abs($mean-653)<4)&&($rms<3.7)) {
	    print OUT "$file\n";
	}
    }
    close(IMSTAT);
}
close(OUT);
close(BIAS);

$call="wc -l bias.out > nbias.txt";
mycall($call);

open(BIAS,"<nbias.txt");
$line=<BIAS>;
chop($line);
@data=split(" ",$line);
$nbias=$data[0];
close(BIAS);



if ($nbias>3) {
    $call="imcombine.pl bias.out bias.fits";
    mycall($call);
} else {
    if ($nbias>0) {
	$call="cp ".$file." bias.fits";
	mycall($call);
    }
}
if ($nbias>0) {
    $call="med2df.pl bias.fits mbias.fits 5 5";
    mycall($call);
} else {
#
# If there is no bias, we use a master-one
#
    $call="cp ".$DIR_CONF."/mbias_V1200.fits .";
    mycall($call);
}
#
# We combine the SKYFLATS
#
$call="cat object.txt | grep ' sky_1' > sky_1.txt";
mycall($call);
$call="cat object.txt | grep ' Sky_1' >> sky_1.txt";
mycall($call);
$call="cat object.txt | grep ' sky_2' > sky_2.txt";
mycall($call);
$call="cat object.txt | grep ' Sky_2' >> sky_2.txt";
mycall($call);

open(SKY_1,"<sky_1.txt");
open(OUT,">sky_1.out");
while($line=<SKY_1>) {
    chop($line);
    @data=split(" ",$line);
    $file=$data[0];
    open(IMSTAT,"imstats.pl $file 970 1016 50 10 | ");
    while($imstat=<IMSTAT>) {
	chop($imstat);
	@dat_imstat=split(" ",$imstat);
	$mean=$dat_imstat[0];
	$max=$dat_imstat[4];
#	print "$file $mean $max\n";

	if (($mean>3000)&&($max<40000)) { 
	    $call="rm -f b".$file;
	    mycall($call);
	    $call="cp ".$file." b".$file;
	    mycall($call);
	    print OUT "b$file\n";
	}
    }
    close(IMSTAT);
}
close(OUT);
close(SKY_1);



$call="wc -l sky_1.out > nsky_1.txt";
mycall($call);

open(SKY_1,"<nsky_1.txt");
$line=<SKY_1>;
chop($line);
@data=split(" ",$line);
$n_sky_1=$data[0];
close(SKY_1);

print "nsky_1 = $n_sky_1\n";



if ($n_sky_1>3) {
    $call="imcombine.pl sky_1.out sky_1.fits";
    mycall($call);
} else {
    if ($n_sky_1>0) {
	$call="cp ".$file." sky_1.fits";
	mycall($call);
    }
}


#exit;

if ($n_sky_1>0) {

#
# Now we reduce the skyflats to produce a fiber-flat
#
    
    $call="cat object.txt | grep cont_sky_1 > cont_sky_1.txt";
    mycall($call);
    open(FH,"<cont_sky_1.txt");
    while($line=<FH>) {
	chop($line);
	@data=split(" ",$line);
	$cont_sky_1=$data[0];
    }
    close(FH);
    
    
    $call="cat object.txt | grep arc_sky_1 > arc_sky_1.txt";
    mycall($call);
    open(FH,"<arc_sky_1.txt");
    while($line=<FH>) {
	chop($line);
	@data=split(" ",$line);
	$arc_sky_1=$data[0];
    }
    close(FH);
    
    $call="reduce_all.pl sky_1.fits ".$cont_sky_1." ".$arc_sky_1."  1 ".$DIR_CONF."/reduce.noflat.V1200.config > reduce_junk.log";
    mycall($call);
 #   $call="smooth_ff.pl sky_1.disp_cor.fits 31 1 sky_1.poly.fits";
  #  mycall($call);

    $call="smooth_ff.pl sky_1.disp_cor.fits 5 1 sky_1.poly.fits";
    mycall($call);

#    $call="fiber_flat_ppak_new.pl sky_1.disp_cor.fits pfiberflat.fits 0.6 mask.fiberflat.fits";
    $call="fiber_flat_ppak_new.pl sky_1.poly.fits fiberflat.fits 0.75 mask.fiberflat.fits";
    mycall($call);
#    $call="polyfit.pl pfiberflat.fits 11 fiberflat.fits";
#    $call="cp pfiberflat.fits fiberflat.fits";

    $call="split_ppak.pl mask.fiberflat.fits mask.obj.fits mask.cal.fits mask.sky.fits 0";
    mycall($call);
    $call="Mosaic_rss.pl ".$DIR_CONF."/mos.mask.config mask.rss.fits mask.pt.txt";
    mycall($call);

#    exit;

    $call="cp fiberflat.fits fiberflat.".$TODAY.".fits";
    mycall($call);
    $call="split_ppak.pl fiberflat.fits fiberflat.obj.fits cal.fits sky.fits 0";
    mycall($call);


    $call="imstats.pl fiberflat.obj.fits 500 165 300 164 > imstats.fiberflat";
    mycall($call);
    dumplog("fiberflat","imstats.fiberflat");
    $call="imstats_hist.pl fiberflat.obj.fits 500 165 300 164 fiberflat.".$TODAY.".ps/CPS 100";
    mycall($call);



#    $call="med2df.pl pfiberflat.fits fiberflat.fits 31 1";
#    mycall($call);
#    $call="imarith.pl ppfiberflat.fits '*' mask.fiberflat.fits fiberflat.fits";
#    mycall($call);
    
} else {
#
# If there is no skyflat, we use a master-one
#
    $call="cp ".$DIR_CONF."/fiberflat_V1200.fits fiberflat.fits";
    mycall($call);

    $call="split_ppak.pl mask.fiberflat.fits mask.obj.fits mask.cal.fits mask.sky.fits 0";
    mycall($call);
    $call="Mosaic_rss.pl ".$DIR_CONF."/mos.mask.config mask.rss.fits mask.pt.txt";
    mycall($call);
    
}


#exit;

#
# Now we reduce the calibration stars
#
$call="cat object.txt | grep ' std_1' > std_1.txt";
mycall($call);
$nstd_1=0;
open(STD_1,"<std_1.txt");
while($line=<STD_1>) {
    chop($line);
    @data=split(" ",$line);
    $std_1=$data[0];
    $name_std_1=$data[1];
    $cut="std_1_";
    $name_std_1 =~ s/$cut//;
    $nstd_1++;
}
close(STD_1);




if ($nstd_1>0) {

    $call="cat object.txt | grep ' cont_std_1' > cont_std_1.txt";
    mycall($call);
    open(CONT_STD_1,"<cont_std_1.txt");
    while($line=<CONT_STD_1>) {
	chop($line);
	@data=split(" ",$line);
	$cont_std_1=$data[0];
    }
    close(CONT_STD_1);
    
    $call="cat object.txt | grep ' arc_std_1' > arc_std_1.txt";
    mycall($call);
    open(ARC_STD_1,"<arc_std_1.txt");
    while($line=<ARC_STD_1>) {
	chop($line);
	@data=split(" ",$line);
	$arc_std_1=$data[0];
    }
    close(ARC_STD_1);
    
    $call="reduce_all.pl ".$std_1." ".$cont_std_1." ".$arc_std_1."  1 ".$DIR_CONF."/reduce.flat.V1200.config > reduce_junk.log";
    mycall($call);

    $pre_std_1=$std_1;
    $pre_std_1 =~ s/.fits//;
#($pre_std_1,$post)=split(/\./,$std_1);
    
    $call="radial_sum_rss.pl ".$pre_std_1.".sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 std_1.rss.fits";
    mycall($call);
    $call="img2spec.pl std_1.rss.fits 1 spec_std_1.txt";
    mycall($call);
    
    open(EXPTIME,"read_img_header.pl $std_1 EXPTIME,AIRMASS,DATE-OBS |");
    $line=<EXPTIME>;
    ($file,$exptime,$airmass,$date_obs)=split(" ",$line);
    close(EXPTIME);
#print "$name_std_1 $exptime $airmass\n";
    $factor=1/($exptime); # Filling-factor!
    $date_obs =~ s/T//;
    $date_obs =~ s/\-//g;
    $date_obs =~ s/\://g;
    $extinction=0.15;
    $NC=0;
	while (($date[$NC]<$date_obs)&&($NC<$nc)) {
#    while ($date[$NC]<$date_obs) {
	if ($av[$NC]>$extinction) {
	    $extinction=$av[$NC];
	}
    $NC++;
    }


    $call="calib_det.pl spec_std_1.txt ".$DIR_CONF."/f".$name_std_1.".dat ratio.txt ".$factor." ".$extinction." ".$airmass." 31 15 0 3800 5000";
    mycall($call);

#
# We check if there is a second calibration start, to test the accuracy of the calibration
#

    $n_std2=0;
    $call="cat object.txt | grep ' std_2' > std_2.txt";
    mycall($call);
    open(STD_2,"<std_2.txt");
    while($line=<STD_2>) {
	chop($line);
	@data=split(" ",$line);
	$std_2=$data[0];
	$name_std_2=$data[1];
	$cut="std_2_";
	$name_std_2 =~ s/$cut//;
	$n_std2++;
    }
    close(STD_2);
    
    if ($n_std2>0) {
	$call="cat object.txt | grep ' cont_std_2' > cont_std_2.txt";
	mycall($call);
	open(CONT_STD_2,"<cont_std_2.txt");
	while($line=<CONT_STD_2>) {
	    chop($line);
	    @data=split(" ",$line);
	    $cont_std_2=$data[0];
	}
	close(CONT_STD_2);
	
	$call="cat object.txt | grep ' arc_std_2' > arc_std_2.txt";
	mycall($call);
	open(ARC_STD_2,"<arc_std_2.txt");
	while($line=<ARC_STD_2>) {
	    chop($line);
	    @data=split(" ",$line);
	    $arc_std_2=$data[0];
	}
	close(ARC_STD_2);
	

	open(EXPTIME,"read_img_header.pl $std_2 EXPTIME,AIRMASS,DATE-OBS |");
	$line=<EXPTIME>;
	($file,$exptime,$airmass,$date_obs)=split(" ",$line);
	close(EXPTIME);
#print "$name_std_2 $exptime $airmass\n";    
	$factor=1/$exptime;
	$date_obs =~ s/T//;
	$date_obs =~ s/\-//g;
	$date_obs =~ s/\://g;
	$extinction=0.15;
	$NC=0;
#	print "PASO $std_2\n";


	while (($date[$NC]<$date_obs)&&($NC<$nc)) {
	    if ($av[$NC]>$extinction) {
		$extinction=$av[$NC];
	    }
#	    print "$NC '$date[$NC]'<$date_obs $av[$NC] $extinction\n";
#	    <stdin>;
	    $NC++;
	}
	
#	print "PASO $std_2\n";
	
	
	
	$call="reduce_all.pl ".$std_2." ".$cont_std_2." ".$arc_std_2."  ".$exptime." ".$DIR_CONF."/reduce.V1200.config  ".$airmass." ".$extinction." > reduce_junk.log";
	mycall($call);
    
	$pre_std_2=$std_2;
	$pre_std_2 =~ s/.fits//;
#($pre_std_2,$post)=split(/\./,$std_2);
	
	$call="radial_sum_rss.pl ".$pre_std_2.".sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 std_2.rss.fits";
	mycall($call);
	$call="img2spec.pl std_2.rss.fits 1 spec_std_2.txt";
	mycall($call);
	
	open(CAL,">cal.list");
	$cal_file=$DIR_CONF."/f".$name_std_2.".dat";
	print CAL "$cal_file\n";
	print CAL "$spec_std_2.txt\n";
	close(CAL);
    
	$call="flux_ratio.pl spec_std_2.txt ".$DIR_CONF."/f".$name_std_2.".dat junk_ratio.txt 1 1 0 1 0 10000";
	mycall($call);
	$call="spec_plot.pl junk_ratio.txt calib_test.ps/CPS 0.4 1.6 3500 4800 > calib_test.out";
	mycall($call);
	
	open(FH,"<calib_test.out");
	$line=<FH>;
	close(FH);
	print LOG "# CALIBRATIION ACCURACY $line";
    }


#    $convolve=0;
    if ($convolve==1) {
	$call="get_resolution_map.pl arc.disp_cor.fits ARC.disp.id get_res_map.out /null 1";
	mycall($call);
	$call="get_res_plot.V1200.pl get_res_map.out 3400 0.7 'Wavelength' 'Sigma' /null 3600 4800 0.5 1.5 1980 4 1.25 get_res_plot.fits";
	mycall($call);
	$call="split_ppak.pl get_res_plot.fits obj.fits cal.fits sky.fits 0";
	mycall($call);
#	$call="image_plot.pl get_res_plot.fits get_resplot.ps/CPS 0 5";
	$call="plot_image_cont.pl obj.fits 0 1.2 0.51 0.55 '' 1 get_resplot.".$TODAY.".ps/CPS 49 obj.fits 5 0 10 49 rainbow4 0";
	mycall($call);
    } else {
	$call="cp ".$DIR_CONF."/get_res_plot.V1200.fits get_res_plot.fits";
	mycall($call);
    }


} else {
#
# If there is no calibration star, we use a master-one
#
    $call="cp ".$DIR_CONF."/ratio_V1200.txt ratio.txt";
    mycall($call);
    $call="cp ".$DIR_CONF."/get_res_plot.V1200.fits get_res_plot.fits";
    mycall($call);

}

if ($CALIB==1) {
    $call="cp ".$DIR_CONF."/ratio_V1200.txt ratio.txt";
    mycall($call);
}




#




#
# Now we reduce the objects
#

# We count the number of complete object observations:
$call="cat object.txt | grep ' obj' | grep 'p3' > complete.txt";
mycall($call);

open(FH,"wc -l complete.txt |");
$line=<FH>;
($nOBJ,$file)=split(" ",$line);
close(FH);
$nobj=int($nOBJ/$nframes);
print "$nobj completed\n";

$k=0;
open(FH,"<complete.txt");
while($line=<FH>) {
    $line=<FH>;
    if ($TODAY<20110000) {
	$line=<FH>;
    }
    chop($line);
    @data=split(" ",$line);
    $name_obj[$k]=$data[1];
    @parts=split(/\_/,$data[1]);
    $cut="obj_".$parts[1]."_p3_";
    $name_obj[$k] =~ s/$cut//;
    $name_obj[$k] =~ s/ //g;
    $J_obj[$k]=$parts[1];
    #
    # We check that there are the other two pointings!
    # 
    $NAME_JUST=$name_obj[$k];
    open(P1,"cat object.txt | grep ' obj' | grep '$NAME_JUST' | grep 'p1' | wc -l |");
    $NP1=<P1>;
    chop($NP1);
    close(P1);
    open(P2,"cat object.txt | grep ' obj' | grep '$NAME_JUST' | grep 'p2' | wc -l |");
    $NP2=<P2>;
    chop($NP2);
    close(P2);
    print "$NAME_JUST $NP1 $NP2\n";
    if (($NP1>0)&&($NP2>0)) {
	$k++;
    }
}
close(FH);

$nobj=$k;

#print "nobj=$nobj, k=$k\n";
#exit;


#$nobj=0;
for ($j=0;$j<$nobj;$j++) {
    #
    # We combine the files!
    # 
#    $J=$j+1;
    $J=$J_obj[$j];
    print "Reducing $J $j $J_obj[$j] $name_obj[$j] data\n\n";
    $call="cat object.txt | grep ' obj_".$J."_p1' > obj_p1.txt";
    mycall($call);
    $call="cat object.txt | grep ' obj_".$J."_p2' > obj_p2.txt";
    mycall($call);
    $call="cat object.txt | grep ' obj_".$J."_p3' > obj_p3.txt";
    mycall($call);
    $call="cat object.txt | grep ' arc_obj_".$J."' > arc_obj.txt";
    mycall($call);

#    exit;

#
# Identify ARC
#
    open(ARC_OBJ,"<arc_obj.txt");
    while($line=<ARC_OBJ>) {
	chop($line);
	@data=split(" ",$line);
	$arc_obj=$data[0];
    }
    close(ARC_OBJ);


#
# COPY HEADER FROM RAW DATA
#
    $call="rm -f HEADER.NOW";
    mycall($call);
    for ($i=1;$i<=3;$i++) {
	$file_now="obj_p".$i.".txt";
	open(LH,"<$file_now");
	$ni=0;
	while($lh=<LH>) {
	    chop($lh);
	    @dlh=split(" ",$lh);
	    $head="PPAK_p".$i."_f".$ni;
	    $call="dump_header.pl ".$dlh[0]." ".$head." >> HEADER.NOW";
	    mycall($call);
	    $call="get_heliocentric_vel_PPAK.pl ".$dlh[0]." > HELIO.NOW";
	    mycall($call);
	    open(HELIO,"<HELIO.NOW");
	    $helio=<HELIO>;
	    chop($helio);
	    close(HELIO);
	    $head_now=$head."_HVEL";
	    open(HELIO,">>HEADER.NOW");
	    print HELIO "$head_now  | $helio\n";
	    close(HELIO);
	    $ni++;
	}
	close(LH);
    }


#
# Check if there is a shift
#



# OFFSET 1
    open(OBJ,"<obj_p1.txt");
    open(OBJ_OUT,">obj_p1.out");
    while($obj_line=<OBJ>) {
	chop($obj_line);
	($obj_in,$junk)=split(" ",$obj_line);
	$obj_spot=$obj_in;
	$obj_spot =~ s/fits/spots/;
	$junk1=$obj_in;
	$junk1 =~ s/fits//;
	$arc_spot=$arc_obj;
	$arc_spot =~ s/fits/spots/;

	$call="comp_spots.pl ".$obj_spot." ".$arc_spot." ".$junk1."_spots.ps/CPS 200 > ".$junk1.".offsets";
	mycall($call);
	$spots_file=$junk1.".offsets";
	open(OFF,"<$spots_file");
	$off_line=<OFF>;
	close(OFF);
	chop($off_line);
	($x_med,$y_med,$x_sig,$y_sig)=split(" ",$off_line);
	$dx=0;
	$dy=0;
	if ((abs($x_med)>0.1)&&(abs($x_med)>$x_sig)) {
	    $dx=$x_med;
	}
	if ((abs($y_med)>0.1)&&(abs($y_med)>$y_sig)) {
	    $dy=$y_med;
	}
	if (($dx>0)||($dy>0)) {
	    $call="imshift.pl ".$obj_in." s_".$obj_in." ".$dx." ".$dy;
	    mycall($call);
	    $out_file="s_".$obj_in;
	    print OBJ_OUT "$out_file\n";
	} else {
	    print OBJ_OUT "$obj_in\n";
	}
    }
    close(OBJ_OUT);
    close(OBJ);
    $call="imcombine_odd.pl obj_p1.out obj_p1.fits";
    mycall($call);

# OFFSET 2
    open(OBJ,"<obj_p2.txt");
    open(OBJ_OUT,">obj_p2.out");
    while($obj_line=<OBJ>) {
	chop($obj_line);
	($obj_in,$junk)=split(" ",$obj_line);
	$obj_spot=$obj_in;
	$obj_spot =~ s/fits/spots/;
	$junk1=$obj_in;
	$junk1 =~ s/fits//;
	$arc_spot=$arc_obj;
	$arc_spot =~ s/fits/spots/;

	$call="comp_spots.pl ".$obj_spot." ".$arc_spot." ".$junk1."_spots.ps/CPS 200 > ".$junk1.".offsets";
	mycall($call);
	$spots_file=$junk1.".offsets";
	open(OFF,"<$spots_file");
	$off_line=<OFF>;
	close(OFF);
	chop($off_line);
	($x_med,$y_med,$x_sig,$y_sig)=split(" ",$off_line);
	$dx=0;
	$dy=0;
	if ((abs($x_med)>0.1)&&(abs($x_med)>$x_sig)) {
	    $dx=$x_med;
	}
	if ((abs($y_med)>0.1)&&(abs($y_med)>$y_sig)) {
	    $dy=$y_med;
	}
	if (($dx>0)||($dy>0)) {
	    $call="imshift.pl ".$obj_in." s_".$obj_in." ".$dx." ".$dy;
	    mycall($call);
	    $out_file="s_".$obj_in;
	    print OBJ_OUT "$out_file\n";
	} else {
	    print OBJ_OUT "$obj_in\n";
	}
    }
    close(OBJ_OUT);
    close(OBJ);
    $call="imcombine_odd.pl obj_p2.out obj_p2.fits";
    mycall($call);

# OFFSET 3
    open(OBJ,"<obj_p3.txt");
    open(OBJ_OUT,">obj_p3.out");
    while($obj_line=<OBJ>) {
	chop($obj_line);
	($obj_in,$junk)=split(" ",$obj_line);
	$obj_spot=$obj_in;
	$obj_spot =~ s/fits/spots/;
	$junk1=$obj_in;
	$junk1 =~ s/fits//;
	$arc_spot=$arc_obj;
	$arc_spot =~ s/fits/spots/;

	$call="comp_spots.pl ".$obj_spot." ".$arc_spot." ".$junk1."_spots.ps/CPS 200 > ".$junk1.".offsets";
	mycall($call);
	$spots_file=$junk1.".offsets";
	open(OFF,"<$spots_file");
	$off_line=<OFF>;
	close(OFF);
	chop($off_line);
	($x_med,$y_med,$x_sig,$y_sig)=split(" ",$off_line);
	$dx=0;
	$dy=0;
	if ((abs($x_med)>0.1)&&(abs($x_med)>$x_sig)) {
	    $dx=$x_med;
	}
	if ((abs($y_med)>0.1)&&(abs($y_med)>$y_sig)) {
	    $dy=$y_med;
	}
	if (($dx>0)||($dy>0)) {
	    $call="imshift.pl ".$obj_in." s_".$obj_in." ".$dx." ".$dy;
	    mycall($call);
	    $out_file="s_".$obj_in;
	    print OBJ_OUT "$out_file\n";
	} else {
	    print OBJ_OUT "$obj_in\n";
	}
    }
    close(OBJ_OUT);
    close(OBJ);
    $call="imcombine_odd.pl obj_p3.out obj_p3.fits";
    mycall($call);




#    $call="imcombine_odd.pl obj_p2.txt obj_p2.fits";
#    mycall($call);
#    $call="imcombine_odd.pl obj_p3.txt obj_p3.fits";
#    mycall($call);

    $call="cat object.txt | grep ' cont_obj_".$J."' > cont_obj.txt";
    mycall($call);
    open(CONT_OBJ,"<cont_obj.txt");
    while($line=<CONT_OBJ>) {
	chop($line);
	@data=split(" ",$line);
	$cont_obj=$data[0];
    }
    close(CONT_OBJ);




    open(EXPTIME,"read_img_header.pl obj_p1.fits EXPTIME,AIRMASS,DATE-OBS |");
    $line=<EXPTIME>;
    ($file,$exptime,$airmass,$date_obs)=split(" ",$line);
    $date_obs =~ s/T//;
    $date_obs =~ s/\-//g;
    $date_obs =~ s/\://g;
    $extinction=0.15;
    $NC=0;
	while (($date[$NC]<$date_obs)&&($NC<$nc)) {
#    while ($date[$NC]<$date_obs) {
	if ($av[$NC]>$extinction) {
	    $extinction=$av[$NC];
	}
	$NC++;
    }

    close(EXPTIME);    
    $exptime=$exptime*5.64;

    $call="reduce_all.pl obj_p1.fits ".$cont_obj." ".$arc_obj." ".$exptime." ".$DIR_CONF."/reduce.V1200.config ".$airmass." ".$extinction." > reduce_junk.log";
    mycall($call);

    $call="cp obj_p1.arc.ps ".$name_obj[$j]."_p1.arc.ps";
    mycall($call);


    $call="check_wavelength_cal.pl junk.sky.fits ".$DIR_CONF."/emission_lines_V1200.sky 3400 0.7 5 1 0";
    mycall($call);
    $call="cp check_wavelength_cal.out check_w.".$name_obj[$j]."_p1.out";
    mycall($call);
    $call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj[$j]."_p1.ps/CPS 10";
    mycall($call);

    $call="check_wavelength_cal.pl arc.disp_cor.fits ".$DIR_CONF."/emission_lines_V1200.arc 3400 0.7 5 1 0";
    mycall($call);
    $call="cp check_wavelength_cal.out check_w.".$name_obj[$j]."_p1.arc.out";
    mycall($call);
    $call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj[$j]."_p1.arc.ps/CPS 10";
    mycall($call);
    $call="table_delta_plot.pl check_wavelength_cal.out 0 1 'V1200 Wavelength (\A) ARC' '\gD \gl \A' check_w_range.".$name_obj[$j]."_p1.arc.ps/CPS 3400 4800 -2 2";
    mycall($call);




    $call="cp obj_p1.width.ps ".$name_obj[$j]."_p1.width.ps";
    mycall($call);
    $call="cp spec_obj_p1.msky.txt spec_".$name_obj[$j]."_p1.msky.txt";
    mycall($call);

    $call="get_flux_width.pl junk.sobj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.sobj.flux";
    mycall($call);
    $call="get_flux_width.pl junk.obj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.obj.flux";
    mycall($call);
    $call="table_hist.pl junk.obj.flux 4 ".$name_obj[$j]."_p1_4358.obj.ps/CPS 50 > ".$name_obj[$j]."_p1_4358.obj.sky";
    mycall($call);
    $call="table_hist.pl junk.sobj.flux 4 ".$name_obj[$j]."_p1_4358.sobj.ps/CPS 50 > ".$name_obj[$j]."_p1_4358.sobj.sky";
    mycall($call);
    $call="cp obj_p1.mean.width ".$name_obj[$j]."_p1.mean.width ";
    mycall($call);
    $call="rm obj_p1.mean.width";
    mycall($call);

    $call="get_flux_stats.pl obj_p1.sobj.fits 4500 30 3400 0.7 ".$name_obj[$j]."_p1.SN.ps/CPS 1 > ".$name_obj[$j]."_p1.out ";
    mycall($call);

    open(WW,"<table_delta_plot.out");
    $www=<WW>;
    chop($www);
    ($w_offset,$w_rms)=split(" ",$www);
    close(WW);

    $add_line="PIPE_p1_extinction | ".$extinction;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p1_cont | ".$cont_obj;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p1_arc | ".$arc_obj;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p1_w_offset | ".$w_offset;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p1_w_rms | ".$w_rms;
    add_to_file("HEADER.NOW",$add_line);




    open(EXPTIME,"read_img_header.pl obj_p2.fits EXPTIME,AIRMASS |");
    $line=<EXPTIME>;
    ($file,$exptime,$airmass,$date_obs)=split(" ",$line);
    $date_obs =~ s/T//;
    $date_obs =~ s/\-//g;
    $date_obs =~ s/\://g;
    $extinction=0.15;
    $NC=0;
	while (($date[$NC]<$date_obs)&&($NC<$nc)) {
#    while ($date[$NC]<$date_obs) {
	if ($av[$NC]>$extinction) {
	    $extinction=$av[$NC];
	}
	$NC++;
    }

    close(EXPTIME);    
    $exptime=$exptime*5.64;
    $call="reduce_all.pl obj_p2.fits ".$cont_obj." ".$arc_obj." ".$exptime." ".$DIR_CONF."/reduce.V1200.config ".$airmass." ".$extinction." > reduce_junk.log";
    mycall($call);

    $call="cp obj_p2.arc.ps ".$name_obj[$j]."_p2.arc.ps";
    mycall($call);

$call="check_wavelength_cal.pl junk.sky.fits ".$DIR_CONF."/emission_lines_V1200.sky 3400 0.7 5 1 0";
    mycall($call);
    $call="cp check_wavelength_cal.out check_w.".$name_obj[$j]."_p2.out";
    mycall($call);
    $call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj[$j]."_p2.ps/CPS 10";
    mycall($call);

    $call="check_wavelength_cal.pl arc.disp_cor.fits ".$DIR_CONF."/emission_lines_V1200.arc 3400 0.7 5 1 0";
    mycall($call);
    $call="cp check_wavelength_cal.out check_w.".$name_obj[$j]."_p2.arc.out";
    mycall($call);
    $call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj[$j]."_p2.arc.ps/CPS 10";
    mycall($call);
    $call="table_delta_plot.pl check_wavelength_cal.out 0 1 'V1200 Wavelength (\A) ARC' '\gD \gl \A' check_w_range.".$name_obj[$j]."_p2.arc.ps/CPS 3400 4800 -2 2";
    mycall($call);

    $call="cp obj_p2.width.ps ".$name_obj[$j]."_p2.width.ps";
    mycall($call);
    $call="cp spec_obj_p2.msky.txt spec_".$name_obj[$j]."_p2.msky.txt";
    mycall($call);


    $call="get_flux_width.pl junk.sobj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.sobj.flux";
    mycall($call);
    $call="get_flux_width.pl junk.obj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.obj.flux";
    mycall($call);
    $call="table_hist.pl junk.obj.flux 4 ".$name_obj[$j]."_p2_4358.obj.ps/CPS 50 > ".$name_obj[$j]."_p2_4358.obj.sky";
    mycall($call);
    $call="table_hist.pl junk.sobj.flux 4 ".$name_obj[$j]."_p2_4358.sobj.ps/CPS 50 > ".$name_obj[$j]."_p2_4358.sobj.sky";
    mycall($call);


    open(WW,"<table_delta_plot.out");
    $www=<WW>;
    chop($www);
    ($w_offset,$w_rms)=split(" ",$www);
    close(WW);
    $add_line="PIPE_p2_extinction | ".$extinction;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p2_cont | ".$cont_obj;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p2_arc | ".$arc_obj;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p2_w_offset | ".$w_offset;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p2_w_rms | ".$w_rms;
    add_to_file("HEADER.NOW",$add_line);


    $call="cp obj_p2.mean.width ".$name_obj[$j]."_p2.mean.width ";
    mycall($call);
    $call="rm obj_p2.mean.width";
    mycall($call);



    open(EXPTIME,"read_img_header.pl obj_p3.fits EXPTIME,AIRMASS |");
    $line=<EXPTIME>;
    ($file,$exptime,$airmass,$date_obs)=split(" ",$line);
    $date_obs =~ s/T//;
    $date_obs =~ s/\-//g;
    $date_obs =~ s/\://g;

    $extinction=0.15;
    $NC=0;
	while (($date[$NC]<$date_obs)&&($NC<$nc)) {
#    while ($date[$NC]<$date_obs) {
	if ($av[$NC]>$extinction) {
	    $extinction=$av[$NC];
	}
	$NC++;
    }

    close(EXPTIME);    
#
# We correct for the fibers aperture
#
    $exptime=$exptime*5.64;

    $call="reduce_all.pl obj_p3.fits ".$cont_obj." ".$arc_obj." ".$exptime." ".$DIR_CONF."/reduce.V1200.config ".$airmass." ".$extinction." > reduce_junk.log";
    mycall($call);

    $call="cp obj_p3.arc.ps ".$name_obj[$j]."_p3.arc.ps";
    mycall($call);
$call="check_wavelength_cal.pl junk.sky.fits ".$DIR_CONF."/emission_lines_V1200.sky 3400 0.7 5 1 0";
    mycall($call);
    $call="cp check_wavelength_cal.out check_w.".$name_obj[$j]."_p3.out";
    mycall($call);
    $call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj[$j]."_p3.ps/CPS 10";
    mycall($call);

    $call="table_delta_plot.pl check_wavelength_cal.out 0 1 'V1200 Wavelength (\A) ARC' '\gD \gl \A' check_w_range.".$name_obj[$j]."_p3.arc.ps/CPS 3400 4800 -2 2";
    mycall($call);

   open(WW,"<table_delta_plot.out");
    $www=<WW>;
    chop($www);
    ($w_offset,$w_rms)=split(" ",$www);
    close(WW);
    $add_line="PIPE_p3_extinction | ".$extinction;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p3_cont | ".$cont_obj;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p3_arc | ".$arc_obj;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p3_w_offset | ".$w_offset;
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_p3_w_rms | ".$w_rms;
    add_to_file("HEADER.NOW",$add_line);


    $call="check_wavelength_cal.pl arc.disp_cor.fits ".$DIR_CONF."/emission_lines_V1200.arc 3400 0.7 5 1 0";
    mycall($call);
    $call="cp check_wavelength_cal.out check_w.".$name_obj[$j]."_p3.arc.out";
    mycall($call);
    $call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj[$j]."_p3.arc.ps/CPS 10";
    mycall($call);


    $call="cp obj_p3.width.ps ".$name_obj[$j]."_p3.width.ps";
    mycall($call);
    $call="cp spec_obj_p3.msky.txt spec_".$name_obj[$j]."_p3.msky.txt";
    mycall($call);



    $call="get_flux_width.pl junk.sobj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.sobj.flux";
    mycall($call);
    $call="get_flux_width.pl junk.obj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.obj.flux";
    mycall($call);
    $call="table_hist.pl junk.obj.flux 4 ".$name_obj[$j]."_p3_4358.obj.ps/CPS 50 > ".$name_obj[$j]."_p3_4358.obj.sky";
    mycall($call);
    $call="table_hist.pl junk.sobj.flux 4 ".$name_obj[$j]."_p3_4358.sobj.ps/CPS 50 > ".$name_obj[$j]."_p3_4358.sobj.sky";
    mycall($call);

    $call="cp obj_p3.mean.width ".$name_obj[$j]."_p3.mean.width ";
    mycall($call);
    $call="rm obj_p3.mean.width";
    mycall($call);


#
# If there is a slight change in the transparence, the pointings need to be rescaled
# 

    if ($TODAY<20110000) {
	$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 3 rad_1.txt";
    mycall($call);
    open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/B_short.txt rad_1.txt 0 |");
    while($L=<FH>) {
	$flux1=$L;
	chop($flux1);
    }
    close(FH);

    if ($TODAY<20110000) {
	$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 -5.22 -4.84 rad_2.rss.fits";
    }
	mycall($call);
    $call="img2spec.pl rad_2.rss.fits 3 rad_2.txt";
    mycall($call);
    open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/B_short.txt rad_2.txt 0 |");
    while($L=<FH>) {
	$flux2=$L;
	chop($flux2);
    }
    close(FH);

    if ($TODAY<20110000) {
	$call="radial_sum_rss.pl obj_p3.sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 rad_3.rss.fits";
    } else {
	$call="radial_sum_rss.pl obj_p3.sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 -5.22 4.84 rad_3.rss.fits";
    }
    mycall($call);
    $call="img2spec.pl rad_3.rss.fits 3 rad_3.txt";
    mycall($call);
    open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/B_short.txt rad_3.txt 0 |");
    while($L=<FH>) {
	$flux3=$L;
	chop($flux3);
    }
    close(FH);

    print "FLUXES = $flux1 $flux2 $flux3\n";
    print LOG "#FLUXES = $flux1 $flux2 $flux3\n";
#    exit;

   $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);
	}
    }





#    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";
    }
    mycall($call);
    $call="rss2rss_mask_ppak.pl mos.rss.fits mos.pt.txt mask.rss.fits ".$name_obj[$j].".rss.fits 1";
    mycall($call);

    $call="rm -r ".$name_obj[$j].".cube.fits ";
    mycall($call);
#    $call="rss2cube.tcl ".$name_obj[$j].".rss.fits mos.pt.txt ".$name_obj[$j].".cube.fits 3 1e-12 1";
#    $call="rss2cube_int.pl ".$name_obj[$j].".rss.fits mos.pt.txt 1 ".$name_obj[$j].".cube.fits 2 5 1";
    $call="rss2cube_int_mask.pl ".$name_obj[$j].".rss.fits mask.rss.fits mos.pt.txt 1 ".$name_obj[$j].".cube.fits 2 5 1";
    mycall($call);
    $call="cp mos.rss.fits mos_".$name_obj[$j].".rss.fits";
    mycall($call);
    $call="cp mos.pt.txt mos_".$name_obj[$j].".pt.txt";
    mycall($call);


    print PROD "$name_obj[$j].cube.fits\n";
#    $call="cp mos.rss.fits ".$name_obj[$j].".rss.fits \n";
#    mycall($call);


#    exit;

#    exit;

#
# We look for the peak intensity!
#
    $call="get_slice.pl ".$name_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=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_B_3900_4550.fits ".$name_obj[$j].".B.fits";
    mycall($call);

    

    $call="rm -r ".$name_obj[$j].".scube.fits ";
    mycall($call);
    $call="DAR_det_cube.pl ".$name_obj[$j].".cube.fits  ".$Xc." ".$Yc." 3 3 ".$name_obj[$j].".scube.fits 550 1900 3 1 0  0 1";
    mycall($call);

    $add_line="PIPE_DAR_cor_ps | DAR_".$name_obj[$j].".cube.ps";
    add_to_file("HEADER.NOW",$add_line);
    $add_line="PIPE_V_4500_5500 | ".$name_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_".$name_obj[$j].".rss.fits HEADER.NOW";
    mycall($call);
    $call="add_header.pl ".$name_obj[$j].".cube.fits HEADER.NOW";
    mycall($call);
    $call="add_header.pl ".$name_obj[$j].".scube.fits HEADER.NOW";
    mycall($call);


    print PROD "$name_obj[$j].scube.fits\n";

    $call="get_flux_stats_cube.pl ".$name_obj[$j].".cube.fits 4500 40 3400 0.7 SN_".$name_obj[$j].".ps/CPS 1 > SN_".$name_obj[$j].".out";
    mycall($call);


    $call="get_aper_spec_scube.pl ".$name_obj[$j]." B > new_center.txt";
    mycall($call);
    $call="cp ".$name_obj[$j].".spec_20.txt ".$name_obj[$j].".NC.V1200.spec_20.txt";
    mycall($call);

    #
    # We perform the flux recalibration if there is V500 data.
    #




    #
    #
    # 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 ".$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=".$name_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 ".$name_obj[$j].".scube.fits HEADER.COORDS";
    mycall($call);    
    $call="write_img_header.pl ".$name_obj[$j].".scube.fits CRVAL1 ".$RA_now;
    mycall($call);    
    $call="write_img_header.pl ".$name_obj[$j].".scube.fits CRVAL2 ".$DEC_now;
    mycall($call);    
    $call="write_img_header.pl ".$name_obj[$j].".scube.fits CRPIX1 ".$CX;
    mycall($call);    
    $call="write_img_header.pl ".$name_obj[$j].".scube.fits CRPIX2 ".$CY;
    mycall($call);    

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

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


    #
    # We perform the flux recalibration on the basis of the V500 data
    # 
    
#    $call="get_aper_spec_scube.pl ".$name_obj[$j]." B > new_center.txt";
#    mycall($call);
#    $call="cp ".$name_obj[$j].".spec_20.txt ".$name_obj[$j].".NC.V1200.spec_20.txt";
#    mycall($call);

    open(LS,"ls -t ../../V500/*/$name_obj[$j].rscube.fits |");
    $V500_cube=<LS>;
    chop($V500_cube);
    close(LS);
    
    if ($V500_cube eq "") {
	$call="write_img_header.pl ".$name_obj[$j].".scube.fits V500CUBE none";
	mycall($call);    
	$SNfile="SN_".$name_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 ".$name_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 ".$name_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 ".$name_obj[$j].".FC.V500.spec_20.txt";
	mycall($call);
	$call="flux_comp.pl ".$name_obj[$j].".NC.V1200.spec_20.txt ".$name_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 600 1900";
	mycall($call);
	
	$call="recal_cube.pl ".$name_obj[$j].".scube.fits out_rat.FC.txt ".$name_obj[$j].".V1200.rscube.fits";
	mycall($call);
	$call="write_img_header.pl ".$name_obj[$j].".V1200.rscube.fits V500RECAL 1";
	mycall($call);    

	$call="get_flux_stats_cube.pl ".$name_obj[$j].".V1200.rscube.fits 4500 40 3400 0.7 SN_".$name_obj[$j].".ps/CPS 1 > SN_".$name_obj[$j].".out";
	mycall($call);
	
	$SNfile="SN_".$name_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 ".$name_obj[$j].".V1200.rscube.fits HEADER.SN";
	    mycall($call);    
	}
	}
	close(SN);

	$call="get_slice.pl ".$name_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 ".$name_obj[$j].".V1200.B.fits";
	mycall($call);
	$call="get_aper_spec_rscube.pl ".$name_obj[$j].".V1200 B > new_center.txt";
	mycall($call);
	$call="cp ".$name_obj[$j].".V1200.spec_20.txt ".$name_obj[$j].".FC.V1200.spec_20.txt";
	mycall($call);
	$call="ls ".$name_obj[$j].".FC.V500.spec_20.txt > list.comp.spec ";
	mycall($call);
	$call="ls ".$name_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.".$name_obj[$j].".ps/CPS -20 250 3700 5000 '".$name_obj[$j]."'";
	mycall($call);
	$call="write_img_header.pl ".$name_obj[$j].".V1200.rscube.fits FILENAME ".$name_obj[$j].".V1200.rscube.fits ";
	mycall($call);    


    }


    


#    print "PARO AHORA\n";
#    <stdin>;
    
}






#
# We check if there are partial observations!
#
$call="cat object.txt | grep ' obj'  > total.txt";
mycall($call);
open(FH,"wc -l total.txt |");
$line=<FH>;
($nTOT,$file)=split(" ",$line);
close(FH);

#***************************
$ntot=int($nTOT/(3*$nframes));
#$nmore=($nTOT-$ntot*9)/3;


for ($i=0;$i<$n_unc;$i++) {
    
#    $J=$nobj+1;
    $J=$Jobj[$i];

    $N_POINTS=0;
    open(FH,"<total.txt");
    while($line=<FH>) {
	chop($line);
	$OBJ_J="obj_".$J;
	if ($line =~ $OBJ_J) {
	    @data=split(" ",$line);
	    $name_obj_now=$data[1];
	    $cut="obj_".$J."_p1_";
	    $name_obj_now =~ s/$cut//;
	    $cut="obj_".$J."_p2_";
	    $name_obj_now =~ s/$cut//;
	    $cut="obj_".$J."_p3_";
	    $name_obj_now =~ s/$cut//;
	    $name_obj_now =~ s/ //g;
	    $N_POINTS++;
	}
    }
    close(FH);
    $nmore=int($N_POINTS/$nframes);
    if ($N_POINTS != $nframes*$nmore) {
	$nmore++;
    }



    $call="cat object.txt | grep ' cont_obj_".$J."' > cont_obj.txt";
    mycall($call);
    open(CONT_OBJ,"<cont_obj.txt");
    while($line=<CONT_OBJ>) {
	chop($line);
	@data=split(" ",$line);
	$cont_obj=$data[0];
    }
    close(CONT_OBJ);

    $call="cat object.txt | grep ' arc_obj_".$J."' > arc_obj.txt";
    mycall($call);
    open(ARC_OBJ,"<arc_obj.txt");
    while($line=<ARC_OBJ>) {
	chop($line);
	@data=split(" ",$line);
	$arc_obj=$data[0];
    }
    close(ARC_OBJ);    


    print "Reducing $name_obj_now data $nmore\n\n";




    for ($j=0;$j<$nmore;$j++) {
	$n_p_now=0;
	for ($JJ=1;$JJ<4;$JJ++) {
	    $check="p".$JJ."_".$name_obj_now;
	    open(POINT,"cat total.txt | grep '$check' | wc -l |");
	    $point=<POINT>;
	    chop($point);
	    close(POINT);
	    if ($point>0) {
		$p_now[$n_p_now]=$JJ;
		$n_p_now++;
	    }
	}

#	$K=$j+1;
	$K=$p_now[$j];
	$call="cat object.txt | grep ' obj_".$J."_p".$K."' > obj_p".$K.".txt";
	mycall($call);




# OFFSET 1
	$obj_file_in="obj_p".$K.".txt";
	$obj_file_out="obj_p".$K.".out";
	open(OBJ,"<$obj_file_in");
	open(OBJ_OUT,">$obj_file_out");
	$ni=0;
	$call="rm -f HEADER.NOW";
	mycall($call);

	while($obj_line=<OBJ>) {
	    chop($obj_line);
	    ($obj_in,$junk)=split(" ",$obj_line);
	    $obj_spot=$obj_in;
	    $obj_spot =~ s/fits/spots/;
	    $junk1=$obj_in;
	    $junk1 =~ s/fits//;
	    $arc_spot=$arc_obj;
	    $arc_spot =~ s/fits/spots/;

#
# We extract the header information
#
	    $head="PPAK_p".$K."_f".$ni;
	    $call="dump_header.pl ".$obj_in." ".$head." >> HEADER.NOW";
	    mycall($call);
	    $call="get_heliocentric_vel_PPAK.pl ".$obj_in." > HELIO.NOW";
	    mycall($call);
	    open(HELIO,"<HELIO.NOW");
	    $helio=<HELIO>;
	    chop($helio);
	    close(HELIO);
	    $head_now=$head."_HVEL";
	    open(HELIO,">>HEADER.NOW");
	    print HELIO "$head_now  | $helio\n";
	    close(HELIO);
	    $ni++;
#
#
#


	    
	    $call="comp_spots.pl ".$obj_spot." ".$arc_spot." ".$junk1."_spots.ps/CPS 200 > ".$junk1.".offsets";
	    mycall($call);
	    $spots_file=$junk1.".offsets";
	    open(OFF,"<$spots_file");
	    $off_line=<OFF>;
	    close(OFF);
	    chop($off_line);
	    ($x_med,$y_med,$x_sig,$y_sig)=split(" ",$off_line);
	    $dx=0;
	    $dy=0;
	    if ((abs($x_med)>0.1)&&(abs($x_med)>$x_sig)) {
		$dx=$x_med;
	    }
	    if ((abs($y_med)>0.1)&&(abs($y_med)>$y_sig)) {
		$dy=$y_med;
	    }
	    if (($dx>0)||($dy>0)) {
		$call="imshift.pl ".$obj_in." s_".$obj_in." ".$dx." ".$dy;
		mycall($call);
		$out_file="s_".$obj_in;
		print OBJ_OUT "$out_file\n";
	    } else {
		print OBJ_OUT "$obj_in\n";
	    }
	}
	close(OBJ_OUT);
	close(OBJ);

#	$call="imcombine_odd.pl obj_p".$K.".txt obj_p".$K.".fits";
	$call="imcombine_odd.pl obj_p".$K.".out obj_p".$K.".fits";
	mycall($call);

	open(EXPTIME,"read_img_header.pl obj_p$K.fits EXPTIME,AIRMASS |");
	$line=<EXPTIME>;
	($file,$exptime,$airmass,$date_obs)=split(" ",$line);
	$date_obs =~ s/T//;
	$date_obs =~ s/\-//g;
	$date_obs =~ s/\://g;

	$extinction=0.15;
	$NC=0;
	while (($date[$NC]<$date_obs)&&($NC<$nc)) {
#	while ($date[$NC]<$date_obs) {
	    if ($av[$NC]>$extinction) {
		$extinction=$av[$NC];
	    }
	    $NC++;
	}

	close(EXPTIME);    
	$call="reduce_all.pl obj_p".$K.".fits ".$cont_obj." ".$arc_obj." ".$exptime." ".$DIR_CONF."/reduce.V1200.config ".$airmass." ".$extinction." > reduce_junk.log";
	mycall($call);
	$call="cp obj_p".$K.".sobj.fits ".$name_obj_now."_p".$K.".sobj.fits";
	mycall($call);
	$name_out=$name_obj_now."_p".$K.".sobj.fits";
	#print PROD "$name_obj_now_p$K.sobj.fits\n";
	print PROD "$name_out\n";

	$call="cp obj_p".$K.".arc.ps ".$name_obj_now."_p".$K.".arc.ps";
	mycall($call);
	$call="check_wavelength_cal.pl junk.sky.fits ".$DIR_CONF."/emission_lines_V1200.sky 3400 0.7 5 1 0";
	mycall($call);
	$call="cp check_wavelength_cal.out check_w.".$name_obj_now."_p".$K.".out";
	mycall($call);
	$call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj_now."_p".$K.".ps/CPS 10";
	mycall($call);
	$call="cp obj_p".$K.".width.ps ".$name_obj_now."_p".$K.".width.ps";
	mycall($call);
	$call="cp spec_obj_p".$K.".msky.txt spec_".$name_obj_now."_p".$K.".msky.txt";
	mycall($call);



	$call="get_flux_width.pl junk.sobj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.sobj.flux";
	mycall($call);
	$call="get_flux_width.pl junk.obj.fits ".$DIR_CONF."/emission_lines_V1200.sky 20 3400 0.7 /null > junk.obj.flux";
	mycall($call);
	$call="table_hist.pl junk.obj.flux 4 ".$name_obj_now."_p".$K."_4358.obj.ps/CPS 50 > ".$name_obj_now."_p".$K."_4358.obj.sky";
	mycall($call);
	$call="table_hist.pl junk.sobj.flux 4 ".$name_obj_now."_p".$K."_4358.sobj.ps/CPS 50 > ".$name_obj_now."_p".$K."_4358.sobj.sky";
	mycall($call);
	
	$call="cp obj_p".$K.".mean.width ".$name_obj_now."_p".$K.".mean.width ";
	mycall($call);


	$call="check_wavelength_cal.pl arc.disp_cor.fits ".$DIR_CONF."/emission_lines_V1200.arc 3400 0.7 5 1 0";
	mycall($call);
	$call="cp check_wavelength_cal.out check_w.".$name_obj_now."_p".$K.".arc.out";
	mycall($call);
	$call="table_hist.pl check_wavelength_cal.all 0 check_w.".$name_obj_now."_p".$K.".arc.ps/CPS 10";
	mycall($call);
	$call="table_delta_plot.pl check_wavelength_cal.out 0 1 'V1200 Wavelength (\A) ARC' '\gD \gl \A' check_w_range.".$name_obj_now."_p".$K.".arc.ps/CPS 3400 4800 -2 2";
	mycall($call);
	
	open(WW,"<table_delta_plot.out");
	$www=<WW>;
	chop($www);
	($w_offset,$w_rms)=split(" ",$www);
	close(WW);
	
	$add_line="PIPE_p".$K."_extinction | ".$extinction;
	add_to_file("HEADER.NOW",$add_line);
	$add_line="PIPE_p".$K."_cont | ".$cont_obj;
	add_to_file("HEADER.NOW",$add_line);
	$add_line="PIPE_p".$K."_arc | ".$arc_obj;
	add_to_file("HEADER.NOW",$add_line);
	$add_line="PIPE_p".$K."_w_offset | ".$w_offset;
	add_to_file("HEADER.NOW",$add_line);
	$add_line="PIPE_p".$K."_w_rms | ".$w_rms;
	add_to_file("HEADER.NOW",$add_line);






    }

    if ($nmore==1) {
	$call="rm -r ".$name_obj_now.".cube.fits ";
	mycall($call);
     
#	$call="rss2cube.tcl ".$name_obj_now."_p".$p_now[0].".sobj.fits /disk-b/sanchez/ppak/legacy/ppak_pt_arc.txt ".$name_obj_now.".1P.cube.fits 3 1e-12 1";
#    $call="rss2cube_int.pl ".$name_obj[$j].".rss.fits mos.pt.txt 1 ".$name_obj[$j].".cube.fits 2 5 1";
	$call="rss2cube_int.pl ".$name_obj_now."_p".$p_now[0].".sobj.fits /disk-b/sanchez/ppak/legacy/ppak_pt_arc.txt 1 ".$name_obj_now.".1P.cube.fits 2 5 1";
	mycall($call);
	print PROD "$name_obj_now.1P.cube.fits\n";
	$call="get_slice.pl ".$name_obj_now.".1P.cube.fits img /disk-b/sanchez/ppak/legacy/slice_B.conf";
	mycall($call);
	$call="cp img_B_3900_4550.fits ".$name_obj_now.".1P.B.fits";
	mycall($call);

	$call="get_flux_stats_cube.pl ".$name_obj_now.".1P.cube.fits 4500 40 3400 0.7 SN_".$name_obj_now.".1P.ps/CPS 1 > SN_".$name_obj_now.".1P.out";
	mycall($call);


	$call="add_header.pl ".$name_obj_now."_p".$p_now[0].".sobj.fits HEADER.NOW";
	mycall($call);

	
    } else {


#	exit;


	$call="cp ".$name_obj_now."_p".$p_now[0].".sobj.fits obj_p".$p_now[0].".sobj.fits";
	mycall($call);
	$call="cp ".$name_obj_now."_p".$p_now[1].".sobj.fits obj_p".$p_now[1].".sobj.fits";
	mycall($call);

	$call="add_header.pl ".$name_obj_now."_p".$p_now[0].".sobj.fits HEADER.NOW";
	mycall($call);
	$call="add_header.pl ".$name_obj_now."_p".$p_now[1].".sobj.fits HEADER.NOW";
	mycall($call);


	$call="radial_sum_rss.pl obj_p".$p_now[0].".sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 rad_1.rss.fits";
	mycall($call);
	$call="img2spec.pl rad_1.rss.fits 2 rad_1.txt";
	mycall($call);
	open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/B_short.txt rad_1.txt 0 |");

    while($L=<FH>) {
	$flux1=$L;
	chop($flux1);
    }
    close(FH);

	
	$call="radial_sum_rss.pl obj_p".$p_now[1].".sobj.fits ".$DIR_CONF."/ppak_pt_arc.txt 5 0 0 rad_2.rss.fits";
	mycall($call);
	$call="img2spec.pl rad_2.rss.fits 2 rad_2.txt";
	mycall($call);
	open(FH,"flux_filter.pl /disk-b/sanchez/ppak/legacy/B_short.txt rad_2.txt 0 |");

    while($L=<FH>) {
	$flux2=$L;
	chop($flux2);
    }
    close(FH);


	print "FLUXES = $flux1 $flux2 \n";
	print LOG "#FLUXES = $flux1 $flux2 \n";    


	$rat12=$flux2/$flux1;
	if (($rat12<0.95)||($rat12>1.05)) {
	    $call="imarith.pl obj_p".$p_now[1].".sobj.fits / ".$rat12." obj_p".$p_now[1].".sobj.fits";
	    mycall($call);
	}

	$PPP=$p_now[0].$p_now[1];
	if ($TODAY<20110000) {
	    $call="Mosaic_rss.pl ".$DIR_CONF."/mos_new_".$PPP."p.config ".$name_obj_now."_2P.rss.fits mos_".$PPP."p.pt.txt";
	} else {
	    $call="Mosaic_rss.pl ".$DIR_CONF."/mos_new_2_".$PPP."p.config ".$name_obj_now."_2P.rss.fits mos_".$PPP."p.pt.txt";
	}
	mycall($call);
	$call=$name_obj_now."_2P.rss.fits";
	print PROD "$call\n";
	$call="cp mos_".$PPP."p.pt.txt mos_".$name_obj_now."_2P.pt.txt";
	mycall($call);
	$call="rm -r ".$name_obj_now.".cube.fits ";
	mycall($call);
#	$call="rss2cube.tcl ".$name_obj_now."_2P.rss.fits mos_".$PPP."p.pt.txt ".$name_obj_now.".2P.cube.fits 3 1e-12 1";
	$call="rss2cube_int.pl ".$name_obj_now."_2P.rss.fits mos_".$PPP."p.pt.txt 1 ".$name_obj_now.".2P.cube.fits 2 5 1";
	mycall($call);
	print PROD "$name_obj_now.2P.cube.fits\n";
	$call="get_slice.pl ".$name_obj_now.".2P.cube.fits img /disk-b/sanchez/ppak/legacy/slice_B.conf";
	mycall($call);
	$call="cp img_B_3900_4550.fits ".$name_obj_now.".2P.B.fits";
	mycall($call);

	$call="get_flux_stats_cube.pl ".$name_obj_now.".2P.cube.fits 4500 40 3400 0.7 SN_".$name_obj_now.".2P.ps/CPS 1 > SN_".$name_obj_now.".2P.out";
	mycall($call);


    }

}

#
# We reduce the velocity stars
# *****************************

$i=1;
$n_vstars=0;
do {
    $OBJ_I="vstar_".$i;
    open(FH,"cat object.txt | grep ' $OBJ_I' | wc -l |");
    $nfound=<FH>;
    chop($nfound);
    close(FH);
    if ($nfound>0) {
	$n_vstars++;
    }
    $i++;
} while ($nfound!=0);

print "$nfound V-stars found|n";
print LOG "# $nfound V-stars found|n";


for ($i=0;$i<$n_vstars;$i++) {
    $J=$i+1;


    $call="cat object.txt | grep ' cont_vstar_".$J."' > cont_vstar.txt";
    mycall($call);
    open(CONT_VSTAR,"<cont_vstar.txt");
    while($line=<CONT_VSTAR>) {
	chop($line);
	@data=split(" ",$line);
	$cont_vstar=$data[0];
    }
    close(CONT_VSTAR);

    $call="cat object.txt | grep ' arc_vstar_".$J."' > arc_vstar.txt";
    mycall($call);
    open(ARC_VSTAR,"<arc_vstar.txt");
    while($line=<ARC_VSTAR>) {
	chop($line);
	@data=split(" ",$line);
	$arc_vstar=$data[0];
    }
    close(ARC_VSTAR);    


    $call="cat object.txt | grep ' vstar_".$J."' > vstar.txt";
    mycall($call);
    open(NAME,"<vstar.txt");
    $line=<NAME>;
    chop($line);
    close(NAME);
    ($junk,$name_vstar)=split(" ",$line);


    $call="imcombine.pl vstar.txt vstar.fits";
    mycall($call);

    open(EXPTIME,"read_img_header.pl vstar.fits EXPTIME,AIRMASS |");
    $line=<EXPTIME>;
    ($file,$exptime,$airmass,$date_obs)=split(" ",$line);
    $date_obs =~ s/T//;
    $date_obs =~ s/\-//g;
    $date_obs =~ s/\://g;
    
    $extinction=0.15;
    $NC=0;
    while (($date[$NC]<$date_obs)&&($NC<$nc)) {
	if ($av[$NC]>$extinction) {
	    $extinction=$av[$NC];
	}
	$NC++;
    }
    
    close(EXPTIME);    
    $call="reduce_all.pl vstar.fits ".$cont_vstar." ".$arc_vstar." ".$exptime." ".$DIR_CONF."/reduce.V1200.config ".$airmass." ".$extinction." > reduce_junk.log";
    mycall($call);

    $call="cp vstar.sobj.fits ".$name_vstar."_".$J.".sobj.fits";
    mycall($call);
    $name_out=$name_vstar."_".$J.".sobj.fits";
    print PROD "$name_out\n";

}


#####################################################





#
# We clean the directory
#
$call="rm -f junk*.fits";
mycall($call);
$call="rm -f arc*.fits";
mycall($call);
#$call="rm -f sky**.fits";
#mycall($call);
$call="rm -f obj_p1.sobj.fits";
mycall($call);
$call="rm -f obj_p2.sobj.fits";
mycall($call);
$call="rm -f obj_p3.sobj.fits";
mycall($call);
$call="rm -f run*b.sobj.fits";
mycall($call);



$nno=0;
open(FH,"<object_ext.txt");
while($line=<FH>) {
    chop($line);
    $a_line[$nno]=$line;
    $nno++;
}
close(FH);

#
# SKYs
#
open(SKY,"ls -ltra spec_*msky.txt |");
open(OUTSKY,">auto_redu_V1200.sky_list");
open(OUTMAG,">auto_redu_V1200.sky_mag");
print OUTMAG "# sky_file V_mag_sky\n";
while($line=<SKY>) {
    chop($line);
    @data=split(" ",$line);
    $file=$data[7];
    $nam=$file;
    $cut="spec_";
    $nam =~ s/$cut//;
    $cut=".msky.txt";
    $nam =~ s/$cut//;
    ($pre,$point)=split(/\_/,$nam);


    $NAME=$point."_".$pre;
    if (($file !~ "run")&&($file !~ "obj")) {
	print OUTSKY "$file\n";
	$call="mag_filter.pl ".$DIR_CONF."/filters/B_short.txt 19.47 ".$file." 0 > mag_filter.out";
	mycall($call);
	open(MAG,"<mag_filter.out");
	$a_mag=<MAG>;	
	chop($a_mag);
	$line_now="";
	for ($i=0;$i<$nno;$i++) {
	    @DATA=split(" ",$a_line[$i]);
	    $NAM=$DATA[1];
	    $NAME =~ s/\+//;
	    $NAM =~ s/\+//;
	    if ($NAM =~ $NAME) {
		$line_now=$a_line[$i];
	    }
	}

	$point =~ s/p//;
	$call="dump_header.pl ".$nam.".V1200.rscube.fits | grep AIRMASS | grep P".$point." > AIRMASS.NOW";
	mycall($call);
	$call="dump_header.pl ".$nam.".V1200.rscube.fits | grep JUL_DATE | grep P".$point." > JUL_DATE.NOW";
	mycall($call);
	open(AIRMASS,"<AIRMASS.NOW");
	$AIRMASS=<AIRMASS>;
	@air_dat=split(/\|/,$AIRMASS);
	close(AIRMASS);
	$air_mass_now=$air_dat[1];

	open(AIRMASS,"<JUL_DATE.NOW");
	$AIRMASS=<JUL_DATE>;
	@air_dat=split(/\|/,$AIRMASS);
	close(AIRMASS);
	$jul_date_now=$air_dat[1];


	print OUTMAG "$a_mag $line_now  $jul_date_now $air_mass_now\n";
    }
}
close(OUTMAG);
close(OUTSKY);
close(SKY);

open(SKY_MAG,"<auto_redu_V1200.sky_mag");
while($line=<SKY_MAG>) {
    chop($line);
    if ($line !~ "#") {
	@data=split(" ",$line);
	$name=$data[0];
	$cut="spec_";
	$name =~ s/$cut//;
	$cut=".msky.txt";
	$name =~ s/$cut//;
	($namecube,$point)=split(/\_/,$name);
	$mag=$data[1];
	$call="write_img_header.pl ".$namecube.".V1200.rscube.fits VMAGSKY".$point." ".$mag;
	mycall($call);    		
    }
}
close(SKY_MAG);

$call="spectra_plot.pl auto_redu_V1200.sky_list skys_plot.ps/CPS -1 10";
mycall($call);

$label1="Julian DATE";
$label2="Night-sky B-band (mag/arcsec\u2\d)";
$call="table_plot.pl auto_redu_V1200.sky_mag 13 1 '".$label1."' '".$label2."' sky_mag_date.ps/CPS";
mycall($call);

$label1="Airmass";
$label2="Night-sky B-band (mag/arcsec\u2\d)";
$call="table_plot.pl auto_redu_V1200.sky_mag 12 1 '".$label1."' '".$label2."' sky_mag_airmass.ps/CPS";
mycall($call);



$call="cat *.mean.width > all.mean.width";
mycall($call);
$call="table_hist.pl all.mean.width 3 all.mean.width.ps/CPS 8";
mycall($call);


open(FH,"<auto_redu_V1200.sky_list");
while($file=<FH>) {
    chop($file);
    $psfile=$file;
    $psfile =~ s/txt/ps/;
    $call="spec_plot.pl ".$file." ".$psfile."/CPS -1 10 3700 4800";
    mycall($call);
}
close(FH);




$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);

open(VSTAR,"ls vstar_*.sobj.fits |");
while($vstar=<VSTAR>) {
    chop($vstar);
    $cut="vstar_";
    $new="vstar_".$TODAY."_";
    $vstar_new=$vstar;
    $vstar_new =~ s/$cut/$new/;
    $call="mv ".$vstar." ".$vstar_new;
    mycall($call);    
}

$call="create_web.pl ".$TODAY." 1 3 ".$PVERSION;
mycall($call);
$call="mkdir ".$DIR_WEB;
mycall($call);
$call="cp web/* ".$DIR_WEB."/";
mycall($call);




if ($do_ftp==1) {
    
    open(ORDERS,">input.ftp");
    print ORDERS "open ftp://mycalifa\@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 "binary\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);
}




close(PROD);
close(LOG);


exit;


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

sub dumplog {
    my $name=$_[0];
    my $file=$_[1];
    open(DUMP,"<$file");
    my $dd;
    while($dd=<DUMP>) {
	print LOG "# $name | $dd\n";
    }
    close(DUMP);
}

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

