#! /bin/tcsh -f

echo "******************************"
echo "*  start check_t_target.csh  *"
echo "******************************"
date

set type_stringa_new = "$1"

set start_dir = /Users/Gio/Work/EXTRAS/EXTRAS_analysis3XMM  
set progr_dir = $start_dir/WP4scripts
set result_dir = $start_dir/results.v11
set bin_dir = $result_dir/BIN
set obs_list = obs_list.txt

#TARGET SRC
set target_name = "PSRB0943+10"
set target_RA = 146.530458
set target_DEC = 9.865917
set max_dist = 20

echo "read ser 1 2" > $result_dir/lc_"$target_name".qdp
set O = 1
foreach dir0 (`cat $start_dir/$obs_list`)
echo "*************************************"
echo "  START ANALYSIS: OBS $dir0          "
echo "*************************************"
 set out_dir = $bin_dir/$dir0/3XMM

 cd $out_dir/
 set N_out=`grep "sorgente" *.out | wc -l | awk '{print $1}'`
 set ctrl_out = 1
 while($ctrl_out <= $N_out)
  set out=`grep "sorgente" *.out | awk -v nr=$ctrl_out '{ if (NR==nr) print $0}'`
  if ($type_stringa_new == "binfixed") then
    set outT=`echo $out | awk '{print $1}' | cut -d'.' -f1 | cut -d'_' -f3`
  endif
  if ($type_stringa_new == "bayesian") then
    set outT=`echo $out | awk '{print $1}' | cut -d'_' -f3 | cut -d'.' -f-3`
  endif
  set ra2=`echo $out | awk '{print $7}'`
  set dec2=`echo $out | awk '{print $8}'`
  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))}'`
  if ($dist1 <= $max_dist_int) then
    echo "Found $target_name target: $outT"
    echo "Dist (arcsec): $dist"
    set outTstart=`echo $outT | sed -e "s/-/ /g"| awk '{print $1}'`
    set outTstop=`echo $outT | sed -e "s/-/ /g"| awk '{print $2}'`
    echo "$outTstart $outTstop"
    set Terr=`echo $outTstop $outTstart | awk '{printf("%.f \n",($1-$2)/2)}'`
    set Tmedio=`echo $outTstop $outTstart | awk '{printf("%.f \n",(($1+$2)/2)-436772832)}'`
    echo "$Tmedio $Terr"
    set rate2=`echo $out | awk '{print $10}'`
    set rate_err2=`echo $out | awk '{print $11}'`
    echo "$Tmedio $Terr $rate2 $rate_err2" >> $result_dir/lc_"$target_name".qdp
  endif
 set ctrl_out = `expr $ctrl_out + 1`
 end
cd $start_dir/

set O = ` expr $O + 1`
end
cd $start_dir/
date
echo "stop check_t_target.csh"
