#!/usr/bin/perl


$ns=0;
open(SKY,"/disk-b/sanchez/ppak/legacy/emission_lines_V500.sky");
while($line=<SKY>) {
    chop($line);
    if ($line !~ "#") {
	@dat=split(" ",$line);
	$ws[$ns]=$dat[0];
	$ns++;
    }
}
close(SKY);


#open(FH,"<../SEG_GAS_v1.3c/candidates_OII5755.csv");
#ALL_LINES.M12.csv
$NNN=0;
open(FH,"<../SEG_GAS_v1.3c/ALL_LINES.M12.csv");
#open(FH,"<../SEG_GAS_v1.3c/candidates_OII7320_7330.csv");
while($line=<FH>) {
    chop($line);
    if ($line !~ "#") {
	if ($NNN==0) {
	    print "# COLUMN23: Flux_OII7320_7330, float, 10^-16 cgs, [OII]7320/30 flux\n";
	    print "# COLUMN24: e_Flux_OII7320_7330, float, 10^-16 cgs, [OII]7320/30 flux error\n";
	}
	$NNN=1;
	$line =~ s/ //g;
	@dat=split(",",$line);
	$name=$dat[0];
	$OH=$dat[20];
	if ($OH ne "nan") {
	@junk=split(/\-/,$name);
	$nr=$junk[$#junk];
	$obj=$name;
	$cut="-".$nr;
	$obj =~ s/$cut//;
	$n=int(1.0*$nr)-1;
#	print "$nr | $obj\n"; exit;

	$sfile="elines_auto_ssp.".$obj.".cen.HII.out";
	open(SKY,"<$sfile");
	$sline=<SKY>;
	$sline=<SKY>;
	close(SKY);
	chop($sline);
	@sdat=split(" ",$sline);
	$w_oii=7320*(1+$sdat[7]/300000);

	$near_sky=0;
	for ($j=0;$j<$ns;$j++) {
	    if (abs($ws[$j]-$w_oii)<10) {
		$near_sky=1;
	    }	
	}

	open(SN,"grep '$n ' ../SEG_GAS_v1.3c/ELINE.HII.$obj\_7320.0_7330.2.out |");
	$sn_line=<SN>; chop($sn_line); 
	@data=split(" ",$sn_line);
	if (($data[1]>0)&&($data[3]>0)) {
	    $F=$data[1]+$data[3];
	} else {
	    $F=0;
	}
	$eF=$data[2];

#	if ($eF<0.25) {
#	    $eF=0.25;
#	}
	if (($F>0)&&($eF>0)) {
	    $SN=$F/$eF;
	} else {
	    $SN=0;
	}
	close(SN);




	if (($SN>1.0)&&($line !~ "nan")) {
	    $out="FEW_OII/zoom_SN_".$SN."_".$name."_OII7320_7330.ps/CPS";
	    $call="./plot_output_FEW_7325.pl ".$obj." ".$n." ".$out." -1 2 6500 7500 > junk1.out";
	    system($call);
#	print "$call"; exit;
	    $out="FEW_OII/SN_".$SN."_".$name."_OII7320_7330.ps/CPS";
	    $call="./plot_output_FEW_7325.pl ".$obj." ".$n." ".$out." -1 20 6500 7500 > junk2.out";
	    system($call);
#	print "$call\n"; exit;





	    if ($near_sky==0) {
		print "$line,$F,$eF\n";
	    }
	}

	$NNN++;
	}
    } else {
	if ($NNN==0) {
	    print "$line\n";
	}
    }
}
close(FH);

exit;
