#!/bin/bash

# cone search TNS catalog
# csTNS [-r RADIUS] [-s] [-j]  {-h} RA DEC RA2 DEC2 .. (or pipe)
# RA, DEC in degrees (default) but Sumerian (hms|:) if -s is invoked
# -r RADIUS of cone search in arcseconds, [5]
# -s input RA & DEC given as Sumerian (":" or "hms" but not blank separated) 
# -j if invoked produces JSON structure of the result


# 2021 February 04
#
#-----------------------------------------------------------------------
RADIUS=5; SUMERIAN=; JSON=; HELP=;
#-----------------------------------------------------------------------
JSONFILE="csTNS.json"
TF="OUT_csTN"; TFo=${TF}.out; TFt=${TF}.tmp; :> $TFo; :>$TFt 
trap "rm $TFo $TFt" EXIT
#-----------------------------------------------------------------------

while getopts r:sjh OPTVAL
do
    case $OPTVAL in
        r) RADIUS=$OPTARG;;
	s) SUMERIAN=1;;
	j) JSON=1;;	
        h) HELP=1;;
        *) echo "csTNS -h for help"; exit -1
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
    echo -e "\tcsTNS [-r RADIUS] [-s] [-j]  {-h} RAdeg DECdeg RA2 DEC2 ..(pipe)"
    echo -e "\tRA and DEC in degrees (accept input from pipe)"
    echo -e "\t -r .. cone radius for search in arseconds [5]"
    echo -e "\t -s .. input RA-DEC pair are Sumerian (:,hms)"
    echo -e "\t -j .. output csTNS.json file"
    exit
fi

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

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


#-----------------------------------------------------------------------
# proces seach pair 
#-----------------------------------------------------------------------

while [ $# -ge 2 ]
do
    ra=$1; dec=$2; shift 2

#TNS works in ":"-Sumerian
#covert inputs to degrees and then to ":"Sumerian 

    echo $ra $dec > $TFt
    [ $SUMERIAN ] && coco -d $ra $dec > $TFt
    read RA DEC <$TFt


#-----------------------------------------------------------------------
#the Big Lift
#-----------------------------------------------------------------------
    curl -s -X POST -d "api_key=$TNS_API_KEY&data="'{"ra":"'$RA'","dec":"'$DEC'","radius":"5","units":"arcsec"}' https://www.wis-tns.org/api/get/search > $TFo

#-----------------------------------------------------------------------
#output objectname  & json structure
#-----------------------------------------------------------------------
     jq -r ' . | .data.reply[] | .objname,.prefix,.objid ' $TFo | xargs  

     [ $JSON ] && jq '. |del(.id_code,.id_message)' $TFo | gsed 's/^{/{\n"program":"csTNS",\n"facility":"TNS",/' > $JSONFILE

done