#!/bin/bash

# cs_NEOWISE [-r radius] {-s} {-h}  ra(hms) dec(dms)
# 	ouptut: W1 & W2 NEOWISE light curve
# ra ... right ascension (HHhMMmSSs or HH:MM:SS.S)
# dec... declination (+/-DDdMMmSSs or DD:MM:SS.S)
# -r     radius of cone search in arcsconds, [5]
# -s ..  show: all header lines and data
#	 if not, show only one line header followed by data
# -h .. help, show and quit
# Usage:
# cs_NEOWISE        20h43m19.03s +44d38m20.4s   
# cs_NEOWISE        20:43:19.03   44:38:20.4
# cs_NEOWISE -r4 -s 20h43m19.03s +44d38m20.4s 


RADIUS=5; SHOW=0; HELP=0; INVALID=0;

while getopts r:sch optval
do 
   case $optval in
	r) RADIUS=$OPTARG;;
	s) SHOW=1;;
	h) HELP=1;;
	*) INVALID=1; 
   esac
done


if [ $INVALID -eq 1 ]; then
	exit -1
fi

if [ $HELP -eq 1 ]; then
   echo " cs_NEOWISE [-r radius] [-s] [-c] [-h]  ra(hms) dec(dms)"
   echo "-r  .. radius of cone search in arcseconds, default is 5 arcsec"
   echo "-s  .. output to screen: if s set, show all header lines"
   echo "-h  .. help (display)"
   echo "usage: cs_NEOWISE -r 4 -s 20h43m19.03s +44d38m20.4s"
   echo "output: W1 & W2 NEOWISE light curve"
   exit
fi


if ! [ $RADIUS -eq $RADIUS ] 2>/dev/null; then
 	echo "error: cone radius must be an integer" ;exit -1
fi 
shift $((OPTIND-1))

if [ $# -ne 2 ]; then
	echo "RA DEC missing"
	exit -2;
fi

RA=$(echo $1 | sed  's/[a-z:]/&+/g;s/+$//')
DEC=$(echo $2| sed  's/[a-z:]/&+/g;s/+$//;s/^+*/+/')

	 echo $RA $DEC $RADIUS    #debugging line

CATALOG="neowiser_p1bs_psd"	#NEOWISE-Reactivation
TFILE=temp_NEOWISE              #temporary file


URL="https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?"
CAT="catalog=$CATALOG&"
SEARCH="spatial=cone&radius="$RADIUS"&radunits=arcsec&"
OBJSTR="objstr="$RA$DEC
OUTPUT="&size=3000&outfmt=1&selcols=w1mpro,w1sigmpro,w2mpro,w2sigmpro,mjd" 

	#echo ${URL}${CAT}${SEARCH}${OBJSTR}${OUTPUT}   #debugging line

curl -s  ${URL}${CAT}${SEARCH}${OBJSTR}${OUTPUT} | \
sed '1,3d;/^\\ /d;/^|/{p;N;N;N;d;}' > $TFILE

n=$(sed '/\\/d;/|/d' $TFILE | wc -l)


if [ $n -eq 0 ]
then
	echo "no sources found"
else
    if [ $SHOW -eq 0 ]
    then 
	echo "number of sources " $n 
	sed '/^\\/d;s/^|/ /;s/|$/ /' $TFILE | sed 's/^  *//;s/  *$//' | awk '{$1=$2=$3=$4="";print}' | gsed 's/^  *//' 
    else
	cat $TFILE
    fi
fi
