#! /bin/csh -f
#A simple script from 3/7/10 to make a final, 17 line catalog. It has to 
#grab things from Gui_form.cat and classify_j1.out and even 
#diagnose.out
#1 Field
#2 Index1
#3 Index2
#4 Photo_index
#5 Classification_flag (0=UNK;1=LAE;2=[OII];3=H-beta;4=[OIII]4959;5=[OIII]5007;6=[CIV];7=H-gamma;8=H-delta;9=[NeIII]3869;10=[NeV]3426)
#6 S/N
#7 Number fibers
#8 z
#9 Wavelength (Ang)
#10 Flux(E-17 erg/s/cm^2)
#11 VP Position RA (deg)
#12 VP Position dec (deg)
#13 EW (Ang)
#14 Counterpart mag_r
#15 Counterpart RA (deg)
#16 Counterpart dec (deg)
#17 Counterpart ID (0=cleanly isolated and certain;1=uncertain or blended)

set cnt_off = 215
set fld_name = "HDFN"
set n_go = `wc -l < fin_Gui_form.cat`
set n_go2 = `wc -l < classify_j1.out`

set nmat_gui = `cat Gui_form.cat | awk '{print $1}'`
set nmat_j1 = `cat classify_j1.out | awk '{print $1}'`
set inx_orig = `cat Gui_form.cat | awk '{print $2}'`
set inx_phot = `cat Gui_form.cat | awk '{print $3}'`
set inx_clas = `cat Gui_form.cat | awk '{print $4}'`
set num_aper = `cat Gui_form.cat | awk '{print $4}'`
set SN_meas = `cat classify_j1.out | awk '{print $5}'`
set cnt_SN = 0
while ($cnt_SN < $n_go)
   @ cnt_SN = $cnt_SN + 1
   set fibers_now = `cat detections/diagnose.out | awk 'NR==var1{print $2}' var1=$inx_orig[$cnt_SN]`
   set num_aper[$cnt_SN] = `echo $fibers_now | awk -F"," '{print NF}'`
end
set z_in = `cat Gui_form.cat | awk '{print $5}'`
set wave_in = `cat Gui_form.cat | awk '{print $6}'`
set flux_meas = `cat classify_j1.out | awk '{print $6}'`
set VP_RA = `cat Gui_form.cat | awk '{print $7}'`
set VP_dec = `cat Gui_form.cat | awk '{print $8}'`
set EW = `cat classify_j1.out | awk '{print $8}'`
set mag1 = `cat classify_j1.out | awk '{print $12}'`
set ph_RA = `cat Gui_form.cat | awk '{print $9}'`
set ph_dec = `cat Gui_form.cat | awk '{print $10}'`
set iso_flag = `cat Gui_form.cat | awk '{print $11}'`

#Put EW into true rest frame, don't assume LyA like the input
set cnt_SN = 0
while ($cnt_SN < $n_go)
   @ cnt_SN = $cnt_SN + 1
   set tmp_pass = $EW[$cnt_SN]
   set EW[$cnt_SN] = `echo "$tmp_pass*($wave_in[$cnt_SN]/1215.67)/(1.+$z_in[$cnt_SN])" | bc -l`
end
rm -f mk_cat_1.out
set cnt_SN = 0
while ($cnt_SN < $n_go)
   @ cnt_SN = $cnt_SN + 1
   @ n_now = $cnt_SN + $cnt_off
   set cnt_SN2 = 0
   while ($cnt_SN2 < $n_go2)
      @ cnt_SN2 = $cnt_SN2 + 1
      if ($nmat_gui[$cnt_SN] == $nmat_j1[$cnt_SN2]) then
         echo "$fld_name $n_now $inx_orig[$cnt_SN] $inx_phot[$cnt_SN] $inx_clas[$cnt_SN] $SN_meas[$cnt_SN2] $num_aper[$cnt_SN] $z_in[$cnt_SN] $wave_in[$cnt_SN] $flux_meas[$cnt_SN2] $VP_RA[$cnt_SN] $VP_dec[$cnt_SN] $EW[$cnt_SN2] $mag1[$cnt_SN2] $ph_RA[$cnt_SN] $ph_dec[$cnt_SN] $iso_flag[$cnt_SN]" >> mk_cat_1.out
         set cnt_SN2 = $n_go2
      endif
   end
end
