#! /usr/bin/env bash

#
# Convert a date given as YYYY-MM-DD into a Julian day number.
# The formula used comes from:
# http://adsabs.harvard.edu/full/1983IAPPP..13...16F
# The algorithm is valid for any date after March 1900.
#
# Time-stamp: <2011-01-17 10:39:43 chl>
#

to_julian()
{
    y=`echo $DATE | awk ' { print substr($0,1,4) } '`
    m=`echo $DATE | awk ' { print substr($0,6,2) } ' | sed ' s/^0*// '`
    d=`echo $DATE | awk ' { print substr($0,9,2) } ' | sed ' s/^0*// '`
    # Note that we need to fix possible problems with octal numbers, hence
    # the call to sed to remove the first 0 if any.
    out=$((367*$y-7*($y+($m+9)/12)/4+(275*$m)/9+$d+1721014))
    echo $out
}

DATE=$1
to_julian $1

exit 0
