#!/bin/bash

# cs_WISE -r radius -s ra dec 
# returns 4-band WISE photometry
# -r radius ... sets the radius of cone search in integer arcsec [5]
# -s ... shows (displays) output. if set, verbose; default, otherwise
# ra dec ... hms&dms and colon format (see usage)
# -h ... help (display and quit)

# usage: 
# cs_WISE         20h43m19.03s +44d38m20.4s
# cs_WISE         20:43:19.03   44:38:20.4
# cs_WISE -s      20h43m19.03s +44:38:20.4s
# cs_WISE -r10 -s 20:43:19.03  +44d38m20.4s
# bug/feature: "temp_photWISE" has all the output

HELP=0; SHOW=0; INVALID=0;
RADIUS=5;	#default cone radius in arcseonds

CATALOG="allwise_p3as_psd"      #ALLWISE
TFILE=temp_photWISE          #temporary file

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

[ $INVALID -eq 1 ] &&  exit -1
[ $# -eq 0 ] && HELP=1;

if [ $HELP -eq 1 ]; then
	echo "cs_WISE -r radius -s ra dec"
	echo "-r radius ... search radius in integer arcsec [5]"
	echo "-s ... if set verbose , terse otherwise "
	echo "-h ... help (display & quit)"
	exit; fi

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

shift $((OPTIND-1))

if [ $# -ne 2 ]; then
	echo "error: need RA & DEC"; exit -1; 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


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=ra,dec,w1mpro,w1snr,w2mpro,w2snr,w3mpro,w3snr,w4mpro,w4snr"

#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 1 ]; then
	cat $TFILE
    else
	echo "number of sources " $n 
	sed '/^\\/d' $TFILE
    fi
fi