#!/bin/sh
# easter
#     Shell script to calculate the date of easter
#     in the Gregorian Calendar.
#
# usage:
#     easter [-dy] <year>
#     easter  -     (use standard input)
# where
#              d     = output format <day> <month> <year>
#              y     = add year to output
#                      (standard output: <day> <name of month> )
#
# Method by:   Spencer Jones, General Astronomy, 1922, pp 73-74;
#
#              Jean Meeus, Astronomical Formulae for Calculators,
#              3rd Edition, 1985, Willmann-Bell, Inc., Richmond
#              ISBN 0-943396-09-3
#

declare -i VA
declare -i VA
declare -i VB
declare -i VC
declare -i VD
declare -i VE
declare -i VF
declare -i VG
declare -i VI
declare -i VK
declare -i VL
declare -i VM
declare -i VN
declare -i VP


if [ "$1" = "-" -o $# -eq 0 ] ; then
   STDINP="`cat -`"
else
   STDINP="$*"
fi

OPTLTR="d"
DOPT=`echo "$STDINP" | sed \
 -e "s/[^-${OPTLTR}]//g" \
 -e "s/--*/-/g"  \
 -e "s/${OPTLTR}${OPTLTR}*/${OPTLTR}/g"  \
 -e "s/-${OPTLTR}/${OPTLTR}/g"   \
 -e "s/${OPTLTR}${OPTLTR}*/${OPTLTR}/"   \
 -e "s/${OPTLTR}/-${OPTLTR}/"`

OPTLTR="y"
YOPT=`echo "$STDINP" | sed \
 -e "s/[^-${OPTLTR}]//g" \
 -e "s/--*/-/g"  \
 -e "s/${OPTLTR}${OPTLTR}*/${OPTLTR}/g"  \
 -e "s/-${OPTLTR}/${OPTLTR}/g"   \
 -e "s/${OPTLTR}${OPTLTR}*/${OPTLTR}/"   \
 -e "s/${OPTLTR}/-${OPTLTR}/"`

NOW=`echo "$STDINP" | sed -e "s/[^0-9]//g"`

#echo "$NOW"
#echo "$DOPT"

YEAR=`echo "$NOW" | sed -e "/[^0-9]/d"`
if [ -z "$YEAR" ] ; then
   echo "Strange Argument $NOW"
   exit 1
fi

if [ $YEAR -lt 1583 ] ; then
   echo 'Usage: easter [-dy] <yyyy>  where yyyy >= 1583' 1>&2
   echo '       easter  -           (use standard input)' 1>&2
   exit 1
fi


# This is the start of the calculation

VA=$[ $YEAR % 19 ]
VB=$[ $YEAR / 100 ]
VC=$[ $YEAR % 100 ]
VD=$[ $VB / 4 ]
VE=$[ $VB % 4 ]
VF=$[ ( $VB + 8 ) / 25 ]
VG=$[ ( $VB - VF + 1 ) / 3 ]
VH=$[ ( (19 * $VA) + $VB - VD - $VG + 15 ) % 30 ]
VI=$[ $VC / 4 ]
VK=$[ $VC % 4 ]
VL=$[ (32 + (2*$VE) + (2*$VI) - $VH - $VK) % 7 ]
VM=$[ ($VA + (11 * $VH) + (22 * $VL)) / 451 ]
VN=$[ ($VH + $VL - (7 * $VM) + 114) / 31 ]
VP=$[ ($VH + $VL - (7 * $VM) + 114) % 31 ]

# output date format <day> <month> <year>
if [ "$DOPT" = "-d" ] ; then
   echo -n $[ $VP + 1 ]
   echo -n " "
   echo -n $[ $VN ]
   echo " $YEAR"
   exit 0
fi

# output day of month
echo -n $[ $VP + 1 ] 

if [ $VN -eq 3 ] ; then
   echo -n " March"
elif [ $VN -eq 4 ] ; then
   echo -n " April"
else
   echo " unknown ERROR"
fi

if [ "$YOPT" = "-y" ] ; then
   echo " $YEAR"
else
   echo
fi

exit 0
