#!/bin/bash

# find nearest Gaia star for given RA, DEC
# fnsGaia [-v VERBOSITY] [-d DFS] {-h} RAdeg DECdeg (or pipe)
# -r initial CONERADIUS in integer arcseconds [30]
# -d DFS is the field separator for output file
# -v VERBOSITY, [1],2,3

# 1 February 2021
#-----------------------------------------------------------------------
RADIUS=60; DFS="\t";  VERBOSITY=1;
JSON_FILE="fnsGaia.json" 
JSON_ADD='"program":"fnsGaia", "utility":"Gaia",'
DLM_FILE="fnsGaia.dlm"
#-----------------------------------------------------------------------
TF="OUT_fnsGaia" TFt=${TF}".tmp" TFo=${TF}".out" TFd=${TF}".dat" 
echo "nada">$TFt
trap "rm $TFt $TFo $TFd" EXIT
#-----------------------------------------------------------------------

while getopts r:d:v:h optval
do 
   case $optval in
        r) RADIUS=$OPTARG;;
        d) DFS=$OPTARG;;
        v) VERBOSITY=$OPTARG;;
        h) HELP=1;;
        *) echo "fnsGaia -h for help"; exit -1
   esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
  echo "fnsGaia [-r RADIUS][-d DFS] [-v VERBOSITY] [-g GaiaV] {-h} RAd DECd ..| pipe"
  echo "-r radius of cone search in arcseconds [30]"
  echo '-d DFS, the field separator for output ["\t"]'
  echo "-v VERBOSITY, [1],2,3 for increasing columns"
  exit
fi

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

if [ $# -eq 0 ]; then 
  if [ -p /dev/stdin ]; then
    PIPE=$(cat -)
    set -- $PIPE
  else
    echo "mergeGaia: no inputs from pipe or command line"; exit -1
  fi
fi

if [ $# -lt 2 ];  then
   echo "csGia: need a minimum pair of RA, DEC"
   exit -1
fi

RA=$1; DEC=$2;shift 2 

while grep "^nada" $TFt > /dev/null 
do
   csGaia -r $RADIUS -d $DFS -v $VERBOSITY $RA $DEC > $TFt
   RADIUS=$((2*RADIUS))
done
RADIUS=$((RADIUS/2))

#number of objects (recall, first line is header)

nobj=$(wc -l <$TFt)
NOBJ=$((nobj-1))

awk -F"$DFS" -v RA=$RA -v DEC=$DEC -v nobj=$NOBJ -v radius=$RADIUS\
       'BEGIN{pi=3.141592653589793;thetamin=radius;i=1}
        NR>=2 {++i; ra[i]=$3; dec[i]=$4; 
	       dra=(ra[i]-RA)*cos(dec[i]*pi/180)*3600; ddec=(dec[i]-DEC)*3600
               theta[i]=sqrt(dra*dra+ddec*ddec) 
               if (theta[i]<thetamin){thetamin=theta[i];imin=i}
               printf ("%0.7f %0.7f %0.1f\n",ra[i],dec[i],theta[i])}
        END{printf ("%0.7f %0.7f %0.1f %d\n",ra[imin],dec[imin],theta[imin],imin)}' $TFt > $TFo
tail -1 $TFo > $TFd 
read ra dec offset IND <$TFd

awk -v ind=$IND 'NR==1;NR==ind' $TFt > $DLM_FILE
dlm2json $DLM_FILE | gsed 's/{/{'"$JSON_ADD"'/' > $JSON_FILE

Gmag=$(jq -r '.[] | .phot_g_mean_mag' $JSON_FILE)
echo $ra  $dec  $Gmag  $offset\"