#!/bin/bash

# given a series of bibcodes print titles of MAXPAPERS  top papers
#
# bc2top bibcode1 bibcode2 ... | pipe
#
# LAST REVISION: 25-January-2020
#-----------------------------------------------------------------------
MAXNPAPERS=15
Authorize="Authorization: Bearer:"$ADS_TOKEN
BaseURL="https://api.adsabs.harvard.edu/v1"
#-----------------------------------------------------------------------

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

if [ $HELP ]; then
  echo "given BibCode(s) return ADS information"
  echo "bibcode_ADS {-h} bibcode1, bibcode2, ... | pipe"
  exit
fi

if [ -z $ADS_TOKEN ]; then
    echo "bc2top: ADS_TOKEN is not set"; exit -1
fi

#-----------------------------------------------------------------------
# No positional parameters?
# So input must be from pipe
#-----------------------------------------------------------------------
if [ $# -eq 0 ]; then 
  if [ -p /dev/stdin ]; then
    PIPE=$(cat -)
    set -- $PIPE
  else
    echo "bibcode_ADS: no parametes given"; exit -1
 fi
fi


BIBCODE=$(echo $* | xargs | sed 's/ /%20OR%20/g;s/&/%26/g')

echo "displaying up to top 15 papers"
curl -s -H "$Authorize" "${BaseURL}/search/query?q=bibcode:($BIBCODE)&fl=title,citation_count&rows=$MAXNPAPERS" | \
jq '.response.docs | .[] | .title | .[]' | nl -s " " -w2 
