#!/bin/bash

# cone search XMM EPIC catalog
# csEPIC [-r CONERADIUS] [-d DFS] [-s] {-h} RA(deg) DEC(deg) RA2 DEC2 (or pipe)
# -r .. radius of cone search in arcseconds [6]
# -d .. Field separator for the output ["\t"]
# -s .. show header. default no show
# eg. csEPIC 299.903083 +20.804028
#     csEPIC -r 100 -s 299.903083 +20.804028
# but can also accept ra,dec from pipe or sub-process 
#     cut -f2,3 Ilaria.txt | csEPIC  
#     csEPIC $(cut -f2,3 Ilaria.txt|xargs)
 
# OUTPUT: for DFS=","
# RAsource, DECsource, flux (CGS), SourceNumber, SourceID

#Reference: There are 336 columns in the database
#http://xmmssc.irap.omp.eu/Catalogue/4XMM-DR10/4XMM-DR10_Catalogue_User_Guide.html#Catalogue
#BUG: Maximum number of sources artificially throttled to NSOURCE=1000
#FEATURE: set OFORMAT=csv,json, votable, votable-plain for other out formats

# LAST REVISION: 03-February-2020
#-----------------------------------------------------------------------
NSOURCE=1000; RADIUS=6;  DFS="\t";  #default values
SHOW=; HELP=; OFORMAT="json"
#-----------------------------------------------------------------------
TF="OUT_csEPIC.tmp"
#trap "[ -e $TF ] && rm $TF" EXIT 
#-----------------------------------------------------------------------

while getopts r:d:s OPTION
do
    case $OPTION in
	r) RADIUS=$OPTARG;;
	d) DFS=$OPTARG;;
	s) SHOW=1;;
	h) HELP=1;;
	*) echo "csEPIC -h for help";exit -1;;
    esac
done
shift $(($OPTIND-1))


#-----------------------------------------------------------------------
#input from pipe? if so, convert to positional parameters
#-----------------------------------------------------------------------

if [ -p /dev/stdin ]; then
    PIPE=$(cat -)
    set -- $PIPE
fi

#-----------------------------------------------------------------------
#process each pair of positional parameters
#-----------------------------------------------------------------------

while [ $# -ge 2 ]
do

	RA=$1;  DEC=$2;  shift 2
	SR=$(echo "scale=5; $RADIUS/3600" | bc)


curl -s "http://nxsa.esac.esa.int/tap-server/tap/sync?REQUEST=doQuery&LANG=ADQL&FORMAT=$OFORMAT&QUERY=SELECT+top+$NSOURCE+ra,dec,ep_8_flux,src_num,observation_id+FROM+xsa.v_epic_source_cat+WHERE+1=contains(epic_source_cat_equatorial_spoint,circle('ICRS',$RA,$DEC,$SR))+ORDER+BY+ep_8_flux+DESC" >$TF

# display header if SHOW is set
	[ $SHOW ] && head -1 $TF | tr "," "$DFS"

	NSRC=$(wc -l < $TF)
	[ "$NSRC" -eq 1 ] && { echo "nada"; exit;}

#display data
	tr "," "$DFS" < $TF

done