#!/bin/bash

# square postage stamp server for SDSS
# psSDSS [-w pixel] [-O gpi..] {-s} {-h } RA(deg) DEC(deg)
# -w .. width in pixels,  [300]
# -s .. display image on screen
# -O .. csv list of case-insensitive options (no blanks); see below
# e.g. s_SDSS -s 32.1435000  29.2358611
# output file: SDSS_FC_nn.jpg where nn=1,2,..
# can also accept inputs from a pipe
# OPTIONS
#G	Grid
#L	Label
#P	PhotoObjs
#S	SpecObjs
#T	TargetObjs
#O	Outline
#B	BoundingBox
#F	Fields
#M	Masks
#Q	Plates
#I	InvertImage

#------------------------------------------------------------------------
HELP=; SHOW=; WPIX=300; IOPTS="GI"
TFILE=SDSS_FC_0.jpg
#------------------------------------------------------------------------

while getopts w:O:sh OPTVAL
do
    case $OPTVAL in
	w) WPIX=$OPTARG;;
	O) IOPTS=$OPTARG;;
	s) SHOW=1;;
	h) HELP=1;;
	*) echo "psDSS -h for help"; exit -1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
   echo "psSDSS [-w pixel] [-O gpi..] {-s} {-h } RA(deg) DEC(deg)"
   echo " -w .. width in pixels,  [300]"
   echo " -s .. display image on screen"
   echo " -O .. case-insensitive options (csv, optional; no blanks)"
   echo " output file: SDSS_FC_nn.jpg where nn=1,2,.."
   exit 
fi

IOPTS=$(echo $IOPTS | gsed 's/,//;s/[a-z]/\U&/g')

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

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

#-----------------------------------------------------------------------
# Main Loop
#-----------------------------------------------------------------------

IND=1
while [ $# -ge 2 ]
do
    RA=$1; DEC=$2; shift 2
    JFILE=${TFILE/0/$IND}		#output file
    curl -s "http://skyserver.sdss.org/dr14/SkyServerWS/ImgCutout/getjpeg?ra=$RA&dec=$DEC&width=$WPIX&height=$WPIX&opt=$IOPTS" -o $JFILE

    [ $SHOW ] && open $JFILE
    IND=$((IND+1))
done

