#! /bin/tcsh -f

echo "*************************"
echo "*  start match_bin.csh  *"
echo "*************************"
date

cd $result_dir/
set det=$result_dir/$dir0/detection
set prod_dir=$result_dir/$dir0/WP4products
echo "OBS $an_dir"
cp $progr_dir/match_plus.csh $an_dir 
cp $progr_dir/MATCH_PLUS $an_dir 
cd $an_dir/

set refsrc=`echo $det/emllist_singsrc_"$b_tot".txt`
if ( -e $refsrc ) then
 set list="$dir0"_"$b_tot"_"$start"-"$stop".list
 set out="$dir0"_"$b_tot"_"$start"-"$stop".out
 set ntotsrc=`wc -l $refsrc | awk '{print $1}'`
 set newdir = $an_dir
 if ( -e $list ) then
  set ctrl_list=`cat $list | wc -l | awk '{print $1}'`
  if ( $ctrl_list != 0) then
   echo "Start the match of $list with $refsrc catalog"
   source match_plus.csh $list $refsrc $out $ntotsrc $newdir $sist_err $sig
   rm $an_dir/eboxlist_local_"$start"-"$stop".fits
   rm $an_dir/eboxlist_map_"$start"-"$stop".fits
  else
   echo "$list exists but is empty"
   echo "$out does not build"
   rm $list
   rm "$dir0"_"$b_tot"_"$start"-"$stop".bkgimg
   rm "$dir0"_"$b_tot"_"$start"-"$stop".expimg
   rm "$dir0"_"$b_tot"_"$start"-"$stop".img
   rm "$dir0"_"$b_tot"_"$start"-"$stop".reg
   rm $an_dir/eboxlist_local_"$start"-"$stop".fits
   rm $an_dir/eboxlist_map_"$start"-"$stop".fits
  endif
 else
  echo "$list does not exist"
  echo "$out does not build"
  rm "$dir0"_"$b_tot"_"$start"-"$stop".bkgimg
  rm "$dir0"_"$b_tot"_"$start"-"$stop".expimg
  rm "$dir0"_"$b_tot"_"$start"-"$stop".img
  rm "$dir0"_"$b_tot"_"$start"-"$stop".reg
  rm $an_dir/eboxlist_local_"$start"-"$stop".fits
  rm $an_dir/eboxlist_map_"$start"-"$stop".fits
 endif
else
  echo "ERROR: $result_dir/$dir0/$refsrc does not exist"
  echo "ERROR: $result_dir/$dir0/$refsrc does not exist" >> $log_dir/messages.log
endif
rm -rf $an_dir/ExpDetectPrep
rm $an_dir/"$dir0"_*.fits
cd $start_dir/

date
echo "stop match_bin.csh"
