#	Calculate the Julian day number for the specified date.
#	Based on algorithms published in Computer Language magazine,
#	December, 1990.  Used with permission.

proc julian(month, day, year)
	# The Julian day number is the number of days between noon GMT
	# Jan 1, 4713 BC and that date.  (Years B.C. are negative.)
	local a, b, year_corr, Month, i
	set Month = January February March April May June ^
		July August September October November December
	if (year == '') then
		local dt
		set dt = `dt`
		@ year = $dt:3
		if (day == '') then
			@ day = month == '' ? $dt:2 : month
			@ month = $dt:1
		end
	end
	if (month !~ '[0-9]*') then
		@ month = "$lower(month)*"
		for i = 0 to 11 do
			if (lower(Month[i]) =~ month) break
		end
		@ month = i + 1
	end
	if (month < 1 || month > 12 || year < -4713 || year > 2900) then
		echo -2 julian: Invalid Date
		return -1
	end
	# Correct for negative year.
	if (year < 0) then
		@ year++
		@ year_corr = 1
		@ b = 1
	else
		@ year_corr = b = 0
	end
	if (month <= 2) then
		@ year--
		@ month += 12
	end
	# Cope with the Gregorian calendar reform
	if (year * 10000 + month * 100 + day > 15821015) then
		@ a = year//100
		@ b = 2 - a + a//4
	end
	@ a = floor(365.25 * year - year_corr) + ^
		floor(30.6001 * (month + 1)) + day + 1720994 + b
	# 4713 BC was not a leap year.
	if (a < 59) @ a++
	return a
end

julian $argv
