#! /bin/csh -f
#A simple script to determine whether emission line sources are isolated. These decisions 
#should probably be reviewed by a human where other information can be folded in. The basic
#rule for this code is that the chosen source is the nearest and that there are no other 
#possibilities within dist_sep plus the chosen source separation of the centroid.
set scname=$0
if($#argv != 0) then
   echo Usage: $scname:t
   exit(1)
endif

set dist_sep = "0.5"
set class_flag = `cat classify_j1.out | awk '$1!="#"{split($0,a," "); print a[8]}'`
set counter_val = `cat classify_j1.out | awk '$1!="#"{split($0,a," "); print a[11]}'`
set dist1_val = `cat classify_j1.out | awk '$1!="#"{split($0,a," "); print a[13]}'`
set cnt_n = 0
set ndat_j = $#class_flag
rm -f isolated_mk.out
while ($cnt_n < $ndat_j)
   @ cnt_n = $cnt_n + 1
   if ($class_flag[$cnt_n] != "-1") then
      if ($counter_val[$cnt_n] != "-99") then
         set min_dist = "100."
         if ($cnt_n < 10) then
            set spn_fl_name = "SEDs/EWspawn_000"$cnt_n".cat"
            set spn_fl_name2 = "SEDs/nspawn_000"$cnt_n".cat"
         else if ($cnt_n < 100) then
            set spn_fl_name = "SEDs/EWspawn_00"$cnt_n".cat"
            set spn_fl_name2 = "SEDs/nspawn_00"$cnt_n".cat"
         else if ($cnt_n < 1000) then
            set spn_fl_name = "SEDs/EWspawn_0"$cnt_n".cat"
            set spn_fl_name2 = "SEDs/nspawn_0"$cnt_n".cat"
         else
            set spn_fl_name = "SEDs/EWspawn_"$cnt_n".cat"
            set spn_fl_name2 = "SEDs/nspawn_"$cnt_n".cat"
         endif
         set spawn_n = `wc -l < $spn_fl_name`
         if ($spawn_n > 0) then
            set cnt_in = 0
            while ($cnt_in < $spawn_n)
               @ cnt_in = $cnt_in + 1
               set indx_now = `cat $spn_fl_name2 | awk 'NR==var1{printf $1}' var1=$cnt_in`
               set dist_now = `cat $spn_fl_name | awk 'NR==var1{printf("%7.3f",$10)}' var1=$cnt_in`
               set tru_test = `echo "$dist_now < $min_dist" | bc -l`
               if ($indx_now != $counter_val[$cnt_n] && $tru_test == 1) then
                  set min_dist = $dist_now
               endif
            end
         endif
         set tru_test = `echo "$dist1_val[$cnt_n] + $dist_sep < $min_dist" | bc -l`
         if ($tru_test == 1) then
            echo "Y" >> isolated_mk.out
         else
            echo "N" >> isolated_mk.out
         endif
      else
         echo "N" >> isolated_mk.out
      endif
   else
      echo "NA" >> isolated_mk.out
   endif
end
exit(0)
