#!/bin/bash

#given RA, DEC display Gaia 5-parameter solutions for DR2,EDR3,.. 
# mdrGaia [-r RADIUS] {-h} RAdeg DECdeg ... | pipe
#

# LAST REVISION: 27 January 2021
#-----------------------------------------------------------------------
HELP=; RADIUS=1
#-----------------------------------------------------------------------
TF="OUT_mdrGaia.tmp" TF1=${TF}1 TF2=${TF}2
:> $TF; :> $TF1; :> $TF2
trap "rm $TF $TF1 $TF2" EXIT
#-----------------------------------------------------------------------
params="ra|dec|parallax|parallax_error|pmra|pmdec|phot_g_mean_mag|astrometric_excess_noise|ZERO"
#-----------------------------------------------------------------------
PARAMS=$(echo $params | sed "s/|/ |/g")

while getopts r:h OPTVAL 
do
    case $OPTVAL in
	r) RADIUS=$OPTARG;;
        h) HELP=1;;
        *) echo "mdrGaia -h for help"; exit -1;;
    esac
done
shift $((OPTIND-1))

if [ $HELP ]; then
  echo "mdreGaia [-r RADIUS] {-h} RAdeg DECdeg ... (or pipe)"
  echo "-r cone radius in arcseconds [1]"
  echo "displays, side-by-side, key parameters from Gaia DR2, EDR3 ..."
  echo "search radius should encompass only one (same) object"
  exit
fi

#-----------------------------------------------------------------------
# check to see if data is being supplied by pipe
#-----------------------------------------------------------------------

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

#-----------------------------------------------------------------------

while [ $# -ge 2 ]
do
  RA=$1; DEC=$2; shift 2
  
  csGaia -gE -v3 -r"$RADIUS" -d":" $RA $DEC | ql_dlm -d":"  -s > $TF
  n1=$(grep "source_id" $TF | wc -l|xargs)    #no sources; deblanking by xargs 
  N1=$n1; [ $n1 -gt 1 ] && N1=2


  case $N1 in
	2) echo "mdrGaia: found $n1 sources, expecting one;  reduce radius"
           exit;;
	1) sed 's/^ *//;s/:/ /' $TF | grep -E "($PARAMS)" | sort  >$TF1;;
  esac

  csGaia -g2 -v3 -r"$RADIUS" -d":" $RA $DEC | ql_dlm -d":" -s > $TF
  n2=$(grep "source_id" $TF | wc -l|xargs)
  N2=$n2; [ $n2 -gt 1 ] && N2=2

  case $N2 in
	2) echo "mdrGaia: found $n2 sources; expecting one;  reduce radius"
	   exit;;
	1) sed 's/^ *//;s/:/ /' $TF | grep -E "($PARAMS)" | sort  >$TF2;;
  esac

 if [ $N1 -eq 0 ] || [ $N2 -eq 0 ]; then 
      echo "mdrGaia: $N1,$N2, nada (one or more data set is null)"; exit
 fi

  echo $params | tr "|" "\n" | sed '$d'| nl | awk '{print $2" "$1}' | sort  > $TF
  echo -e "%item\t\t\t EDR3\t\t\t DR2\t\t" 

  join $TF1 <(gjoin  -a1 -e- -o 0 2.2 1.2 $TF $TF2) | sort -k4n | cut -d" " -f1-3 | column -t 
  echo 

done
