#! /bin/tcsh -f

set ctrl_n_M1 = 0
set ctrl_n_M2 = 0
set ctrl_n_PN = 0
if ( -e $list_eml) then
    set n_M1 = `ls $dir0/pps/*M1*MIEVL* | wc -l`
    set n_M2 = `ls $dir0/pps/*M2*MIEVL* | wc -l`
    set n_PN = `ls $dir0/pps/*PN*PIEVL* | wc -l`
    if ($n_M1 != 0) then
     set ctrl_n_M1 = 1
    endif
    if ($n_M2 != 0) then
     set ctrl_n_M2 = 1
    endif
    if ($n_PN != 0) then
     set ctrl_n_PN = 1
    endif
    set ctrl_n_INST = `echo $ctrl_n_M1 $ctrl_n_M2 $ctrl_n_PN | awk '{print $1+$2+$3}'`
    if ($ctrl_n_INST == 1) then
     set n_DIV = 7
    endif
    if ($ctrl_n_INST == 2) then
     set n_DIV = 13
    endif
    if ($ctrl_n_INST == 3) then
     set n_DIV = 19
    endif
    fkeypar $list_eml+1  NAXIS2 
    set n_eml = `pget fkeypar.par value`
    echo "Catalogue rows: $n_eml"
    set n_src_eml=`echo "$n_eml" "$n_DIV" | awk '{printf("%i",($1/$2))}'`
    echo "N. of sources: $n_src_eml"

    set n = 1
    while($n <= $n_eml)       
        ftabpar $list_eml+1 column=RA row=$n
        set ra2 = `pget ftabpar.par value`
        ftabpar $list_eml+1 column=DEC row=$n
        set dec2 = `pget ftabpar.par value`
        ftabpar $list_eml+1 column=BOX_ID_SRC row=$n
        set  box_id = `pget ftabpar.par value`        
        ftabpar $list_eml+1 column=ML_ID_SRC row=$n
        set  ml_id = `pget ftabpar.par value`        
        ftabpar $list_eml+1 column=RADEC_ERR row=$n
        set radec_err = `pget ftabpar.par value`

        set dist=`echo "$target_RA" "$target_DEC" "$ra2" "$dec2" | awk -f $progr_dir/angsep.awk`
        set dist1=`echo "$dist" | awk '{printf("%i",($1*1000))}'`
        set max_dist_int=`echo "$max_dist" | awk '{printf("%i",($1*1000))}'`
        echo "Target: $target_RA $target_DEC"
        echo "Catalogue src: $ra2 $dec2"
        if ($dist1 <= $max_dist_int) then
          set ctrl_max_dist = 1
          echo "OK: the src "$ml_id" (box id: "$box_id") at the row "$n" is to a distance of $dist arcsec from the target $target_name"
          echo "fselect infile=$list_eml+1 outfile=$list_eml_dir/$cat3xmm3 expr="ML_ID_SRC.ne."$ml_id"" clobber=yes" > $list_eml_dir/fselect.csh
          source $list_eml_dir/fselect.csh
          rm $list_eml_dir/fselect.csh
          set box_id_reg = $box_id
        else
          echo "the src "$ml_id" is too far from target $target_name at the row n. "$n" : $dist arcsec"
        endif
    set n = `expr $n + $n_DIV`
    end
else
  echo "ERROR: there are not the src lists"
endif
