#!/bin/bash

# cone-search PS1 STRM catalog. 
# return tab-separated ra dec type pGalaxy pStar pQSO zphot err_zphot 
# type=galaxy,star,qso
# p=probability, zphot=photometric redshift
#
# csPS1_STRM [-r CONERADIUS] {-s} {-h} RA(deg) Dec(deg) RA2 DEC2...
# -r CONERADIUS in integer arcseconds  [5]
# -s show header  
# -h help 
#  [ ] .. default action, { } explicit request for action
#  $CAS_WSID  and $CAS_PW must be exported globally
#  which are user id and associated password of registered users of CASJobs@STSCI

# LAST REVISION: 5-February-2021
#-----------------------------------------------------------------------
HELP=; SHOW=; SR=5; 
cols="3,4,5,6,7,8,13,14"
JSONFILE="csPS1_STRM.json"
JSONADD='"program":"csPS1_STRM","utility":"PS1_STRM",' 
#-----------------------------------------------------------------------
TF="OUT_csPS1_STRM." TF1=${TF}1 TF2=${TF}2 TFh=${TF}h TFd=${TF}d
#trap "[ -e $TF1 ] && rm $TF1 $TF2 $TFh; [ -e $TFd ] && rm $TFd" EXIT
#-----------------------------------------------------------------------

while getopts r:sh OPTVAL
do
    case $OPTVAL in
	r) SR=$OPTARG;;
	h) HELP=1;;
	s) SHOW=1;;
	*) exit -1;;
    esac
done
shift $((OPTIND-1))


if [ $HELP ]; then
  echo "csPS1_STRM [-r CONERADIUS] {-s} {-t} {-h} RA(deg) Dec(deg)"
  echo " -r CONERADIUS (in arcseconds) [10]"
  echo " -s show header"
  exit
fi

if [ -z $CAS_PWD ] && [ -z $CAS_WSID ]; then
	echo "global variable CAS_WSID & CAS_PW not defined"
	exit -1
fi

RADIUS=$(echo "scale=4;$SR/60" | bc)   #convert cone radius to arcmin

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

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

while [ $# -ge 2 ] 
do 
    RA=$1; DEC=$2; shift 2
    curl -s -X GET "https://mastweb.stsci.edu/ps1casjobs/services/jobs.asmx/ExecuteQuickJob?qry=select+o.objID%2C+o.uniquePspsOBid%2C+o.raMean%2C+o.decMean%2C+%0Ao.class%2C+o.prob_Galaxy%2C+o.prob_Star%2C+o.prob_QSO%2C%0Ao.extrapolation_Class%2C+o.cellDistance_Class%2C+o.cellID_Class%2C+%0Ao.z_phot%2C+o.z_photErr%2C+o.z_phot0%2C+%0Ao.extrapolation_Photoz%2C+cellDistance_Photoz%2C+o.cellID_Photoz%0Afrom+fGetNearbyObjEq%28$RA%2C$DEC%2C$RADIUS%29+nb%0Ainner+join+catalogRecordRowStore+o+on+o.objID%3Dnb.objID%0A&context=HLSP_PS1_STRM&taskname=quickie&isSystem=False&wsid=$CAS_WSID&pw=$CAS_PW" -o $TF1

#generate json file
    sed 1d $TF1 | head -1 | sed 's/^<[^>]*>//;s/\[//g;s/]:[^,]*//g' > $TFh
    sed '/^</d' $TF1 >$TFd
    csvjson  <(cat $TFh $TFd) | gsed 's/{/{'"$JSONADD"'/' > $JSONFILE

#one-line summary of key parameters: 
# RA,DEC,classificationi (star/galaxy/qso/unsure) ,photz,errphotz,offset(")
    cut -d, -f$cols $TFd > $TF2 
    n=$(wc -l < $TF2)
    if [ $n -gt 0 ]; then
        awk -F"," 'BEGIN{pi=3.141592653589793}
        {dra=($1-RA)*cos(pi/180*DEC)*3600
        ddec=($2-DEC)*3600; doff=sqrt(dra^2+ddec^2)
        printf("%8.5f  %8.5f  %8s  ",$1,$2,$3)
        if ($7<0){$7=-1}; if ($8<0){$8=-1};
        printf("%5.2f %5.2f  %4.1f\"\n",$7,$8,doff)}'\
        RA=$RA DEC="$DEC" $TF2 | sort -k1n
    else
        echo "nada :csPS1_STRM"
    fi
done
