#!/bin/sh
# jd  Shell script to calculate the Julian Day number (JD).
#
#     The JD is a consecutive count of days from the beginning
#     of the year -4712 onwards. Following an astronomical tradition
#     Julian Day numbers are counted from noon of each day,
#     thus ending in 'nnnn.5' at midnight. The Gregorian
#     calendar reform during October 1582 is taken into account.
#     The method is valid for negative years but not for
#     negative JD numbers.
#
#     usage:  'jd  <dd> <mm> <yyyy>'
#     or      'jd - '                (use standard input)
#     where:                  yyyy = Year
#                        mm        = Month
#                   dd             = Day
#
#     The shell script takes 3 arguments for day, month and year
#     from the command line arguments or from the standard input.
#     The year has four digits in our days and the separator
#     between arguments is a blank.
#
# Method from: Jean Meeus, Astronomical Formulae for Calculators,
#              3rd Edition, 1985, Willmann-Bell, Inc., Richmond
#              ISBN 0-943396-09-3
#

declare -i DAY
declare -i MONTH
declare -i YEAR
declare -i VY
declare -i VM
declare -i VA
declare -i VB
declare -i DSTRING
declare -i JD

if [ "$1" = "-" ] ; then
   STDINP="`cat -`"
   DAY=`echo $STDINP | cut -d ' ' -f 1`
   MONTH=`echo $STDINP | cut -d ' ' -f 2`
   YEAR=`echo $STDINP | cut -d ' ' -f 3`
else
   if [ $# -lt 3 ] ; then
      echo 'Usage: jd <dd> <mm> <yyyy>' 1>&2
      echo '       jd -  (use standard input)' 1>&2
      exit 1
   else
      DAY=$[$1]
      MONTH=$[$2]
      YEAR=$[$3]
   fi
fi

if [ $DAY -lt 1 -o $DAY -gt 31 ] ; then
   echo "jd: parameter #1 for day out of range" 1>&2
   exit 1
fi

if [ $MONTH -lt 1 -o $MONTH -gt 12 ] ; then
   echo "jd: parameter #2 for month out of range" 1>&2
   exit 1
fi

if [ $YEAR -eq 1582 -a $MONTH -eq 10 ] ; then
   if [ $DAY -gt 4 -a $DAY -lt 15 ] ; then
      echo "jd: Warning: Date ${DAY} ${MONTH} ${YEAR} does not \
exist in Gregorian calendar" 1>&2
   fi
fi

# This is the start of the calculation

if [ $MONTH -gt 2 ] ; then
   VY=$YEAR
   VM=$MONTH
else
   VY=$[ $YEAR - 1 ]
   VM=$[ $MONTH + 12 ]
fi

DSTRING=$[ ($YEAR * 10000) + ($MONTH * 100) + $DAY ]
if [ $DSTRING -ge 15821015 ] ; then
   VA=$[ $VY / 100 ]
   VB=$[ ($VA / 4) + 2 - $VA ]
else
   VA=0
   VB=0
fi

VM=$[ $VM + 1 ]
if [ $VY -lt 0 ] ; then
   JD=$[ (36525 * $VY - 75) / 100 ]
else
   JD=$[ 36525 * $VY / 100 ]
fi
let JD+=$[ 306001 * $VM / 10000 ]
let JD+=$[ $DAY + $VB + 1720994 ]

echo "${JD}.5"
exit 0

