#!/bin/sh
#
# dt    Shell script to convert a Julian Day number to a date
#
#       Note: Fractions of a day are *not* supported. According
#             to an astronomical tradition, Julian Day numbers are
#             counted from 12 noon of each day. Thus all
#             "integer" Julian Day numbers should end in "nnn.5".
#             Otherwise the script assumes, that the trailing
#             ".5" has already been truncated. So, the day number
#             2436115 strictly corresponds to 3 October 1957 at 
#             12 noon but the script assumes that the input means
#             2436115.5 which is 4 October 1957 at 0 hrs.
#
# Usage:  dt <julian_day_number[.5]>
#         dt  -  (for standard input)
#
declare -i JD
declare -i DOM
declare -i MON
declare -i YR
declare -i ALPHA
declare -i VA
declare -i VB
declare -i VC
declare -i VD
declare -i VE
declare -i VZ


if [ $# -ne 1 ] ; then
   echo 'Usage: dt <jd>' 1>&2
   echo 'or:    dt  -  (for standard input)' 1>&2
   exit 1
fi

if [ "$1" = "-" ] ; then
   JD=`cut -d . -f 1 - | cut -d ' ' -f 1`
else
   JD=`echo $1 | cut -d . -f 1`
fi

let VZ=$[ $JD + 1 ]

if [ $VZ -lt 2299161 ] ; then
   let VA=$VZ
else
   let ALPHA=$[ (($VZ * 100) - 186721625) / 3652425 ]
   let VA=$[ $VZ + 1 + $ALPHA - ($ALPHA / 4) ]
fi
 
let VB=$[ ($VA + 1524) ]
let VC=$[ (($VB * 100) - 12210) / 36525 ]
let VD=$[ (36525 * $VC) / 100 ]
let VE=$[ (($VB - $VD) * 10000) / 306001 ]
let DOM=$[ $VB - $VD - ( 306001 * $VE / 10000 ) ]

if [ $VE -le 13 ] ; then
   let MON=$[ $VE - 1 ]
else
   let MON=$[ $VE - 13 ]
fi
 
if [ $MON -gt 2 ] ; then
   let YR=$[ $VC - 4716 ]
else
   let YR=$[ $VC - 4715 ]
fi

echo "${DOM} ${MON} ${YR}"

exit 0
