モジュール:GengoConvert

出典: 謎の百科事典もどき『エンペディア(Enpedia)』
ナビゲーションに移動 検索に移動

※ここに呼び出す説明文 『 モジュール:GengoConvert/doc 』 が作成されていません。

local p = {}
local getArgs = require('Module:Arguments').getArgs

local pi = math.pi
local sin = math.sin
local floor = math.floor
local abs = math.abs
local huge = math.huge

--------------------------------------------------------------------------------
-- 概要
-- 日本の旧暦(太陰太陽暦)を暦法ごとに復元して、西暦の日付から旧暦の年月日と元号年を返す。
-- 旧暦年は正月朔日から数え、元号の年数もこれに従う。西暦は1582年10月4日までユリウス暦、
-- 同年10月15日以降グレゴリオ暦。紀元前は天文学的年表記に換算して計算する
-- (紀元前N年 = 1−N年)。1年〜3桁の年にも対応する。
--   ~603年    暦法導入以前:現代天文計算(定朔・定気)
--   604~696年 元嘉暦   定朔・平気(定数は元嘉暦、基準は参照表で較正)
--   697~763年 儀鳳暦   定朔・平気(定数は儀鳳暦、基準は参照表で較正)
--   764~861年 大衍暦   定朔・進朔(定数は大衍暦、進朔限は年代別)
--   862~1684年 宣明暦  定朔・進朔(統法8400・章歳3068055・章月248057・積年7070138)
--   1685~1754 貞享暦   現代天文計算による定朔(JST)・平気
--   1755~1797 宝暦暦   同上
--   1798~1843 寛政暦   同上
--   1844~1872 天保暦   現代天文計算による定朔(JST)・定気
--   1873年1月1日(明治6年1月1日)以降は新暦。1872年12月31日までは旧暦(明治5年12月2日)。
-- 暦法の切替は、新暦法の最初の正月朔日で行う。
-- 精度(日本暦日原典に基づく645~1872年の各年の「閏月」と「西暦元日の旧暦日付」2454件との照合)
--   元嘉暦期 90%/儀鳳暦期 96%/大衍暦期 97%/宣明暦期 94%/貞享暦期 99%/
--   宝暦暦期 95%/寛政暦期 97%/天保暦期 100%(全体で約95%)。
--   さらに各改元日の旧暦日付(約250件)との照合で、大化元年を7月29日から7月17日に訂正した。
--  ・元嘉暦・儀鳳暦・大衍暦は暦元の定数を持たず、参照表に合わせて較正した近似値。
--  ・宣明暦は章歳・章月・積年を暦書どおりに用いるが、朓朒表の代わりに現代の月・太陽の
--    不均等補正を(太陽項の振幅・位相を較正して)用いている。朔日が±1日ずれる月がある
--    (参照表との不一致は月初で約6%)。閏月の位置が1か月ずれる年もある。
--  ・貞享暦・宝暦暦・寛政暦は、各暦の独自計算ではなく現代天文計算で代用している。
--  ・天保暦は現代計算だが、実際の暦(嘉永5年閏2月)と食い違う年を例外表で補正した。
--  ・紀元前・暦法導入以前は現代天文計算の値であり、史実の暦日ではない(日本書紀の
--    暦日とも一致しない)。
--  ・元号表は推古~舒明など天皇の治世年を含む(「推古天皇元年」の形式で表示する)。
--------------------------------------------------------------------------------

local function to_rad(d) return d * pi / 180 end
local function fix_angle(a) a = a % 360 if a < 0 then a = a + 360 end return a end
local function norm180(a) a = (a + 180) % 360 - 180 return a end

--------------------------------------------------------------------------------
-- 暦日→ユリウス通日(1582年10月15日以降はグレゴリオ暦、それ以前はユリウス暦)
-- 紀元前は天文学的年表記(1年=紀元前1年の翌年=0年)で扱う。
--------------------------------------------------------------------------------
local function jd_from_date(y,m,d)
	if m <= 2 then y = y - 1 m = m + 12 end
	local B
	if (y > 1582) or (y == 1582 and m > 10) or (y == 1582 and m == 10 and d >= 15) then
		local A = floor(y / 100)
		B = 2 - A + floor(A / 4)
	else
		B = 0
	end
	return floor(365.25 * (y + 4716)) + floor(30.6001 * (m + 1)) + d + B - 1524.5
end

local function date_from_jd(jd)
	local Z = floor(jd + 0.5)
	local F = (jd + 0.5) - Z
	local A = Z
	if Z >= 2299161 then
		local alpha = floor((Z - 1867216.25) / 36524.25)
		A = Z + 1 + alpha - floor(alpha / 4)
	end
	local B = A + 1524
	local C = floor((B - 122.1) / 365.25)
	local D = floor(365.25 * C)
	local E = floor((B - D) / 30.6001)
	local day = B - D - floor(30.6001 * E) + F
	local month = (E < 14) and (E - 1) or (E - 13)
	local year = (month > 2) and (C - 4716) or (C - 4715)
	return year, month, floor(day + 1e-9)
end

-- 日番号(暦日を表す整数=その日の正午のユリウス通日)
local function day_number_from_date(y, m, d)
	return floor(jd_from_date(y, m, d) + 0.5)
end

local function date_from_day_number(dn)
	return date_from_jd(dn - 0.5)
end

--------------------------------------------------------------------------------
-- ΔT(Espenak & Meeus)
--------------------------------------------------------------------------------
local function delta_t_seconds(year, month)
	local y = year + (((month or 6) - 0.5) / 12)
	if y < -500 then
		local u = (y - 1820) / 100
		return -20 + 32 * (u * u)
	end
	if y < 500 then
		local u = y / 100
		return 10583.6 - 1014.41 * u + 33.78311 * u^2 - 5.952053 * u^3 - 0.1798452 * u^4 + 0.022174192 * u^5 + 0.0090316521 * u^6
	end
	if y < 1600 then
		local u = (y - 1000) / 100
		return 1574.2 - 556.01 * u + 71.23472 * u^2 + 0.319781 * u^3 - 0.8503463 * u^4 - 0.005050998 * u^5 + 0.0083572073 * u^6
	end
	if y < 1700 then
		local t = y - 1600
		return 120 - 0.9808 * t - 0.01532 * t^2 + t^3 / 7129
	end
	if y < 1800 then
		local t = y - 1700
		return 8.83 + 0.1603 * t - 0.0059285 * t^2 + 0.00013336 * t^3 - t^4 / 1174000
	end
	if y < 1860 then
		local t = y - 1800
		return 13.72 - 0.332447 * t + 0.0068612 * t^2 + 0.0041116 * t^3 - 0.00037436 * t^4 + 0.0000121272 * t^5 - 0.0000001699 * t^6 + 0.000000000875 * t^7
	end
	if y < 1900 then
		local t = y - 1860
		return 7.62 + 0.5737 * t - 0.251754 * t^2 + 0.01680668 * t^3 - 0.0004473624 * t^4 + t^5 / 233174
	end
	if y < 1920 then
		local t = y - 1900
		return -2.79 + 1.494119 * t - 0.0598939 * t^2 + 0.0061966 * t^3 - 0.000197 * t^4
	end
	if y < 1941 then
		local t = y - 1920
		return 21.20 + 0.84493 * t - 0.076100 * t^2 + 0.0020936 * t^3
	end
	if y < 1961 then
		local t = y - 1950
		return 29.07 + 0.407 * t - t^2 / 233 + t^3 / 2547
	end
	if y < 1986 then
		local t = y - 1975
		return 45.45 + 1.067 * t - t^2 / 260 - t^3 / 718
	end
	if y < 2005 then
		local t = y - 2000
		return 63.86 + 0.3345 * t - 0.060374 * t^2 + 0.0017275 * t^3 + 0.000651814 * t^4 + 0.00002373599 * t^5
	end
	if y < 2050 then
		local t = y - 2000
		return 62.92 + 0.32217 * t + 0.005589 * t^2
	end
	if y < 2150 then
		return -20 + 32 * (((y - 1820) / 100)^2) - 0.5628 * (2150 - y)
	end
	local u = (y - 1820) / 100
	return -20 + 32 * (u * u)
end

local function jde_tt_to_jd_ut(jde_tt)
	local y, m = date_from_jd(jde_tt)
	local jd_ut = jde_tt - delta_t_seconds(y, m) / 86400
	local y2, m2 = date_from_jd(jd_ut)
	return jde_tt - delta_t_seconds(y2, m2) / 86400
end

--------------------------------------------------------------------------------
-- 太陽の視黄経(章動・光行差込み)。二十四節気は視黄経で定義される。
--------------------------------------------------------------------------------
local function sun_ecliptic_longitude_tt(jde_tt)
	local T = (jde_tt - 2451545.0) / 36525
	local T2 = T * T
	local L0 = 280.46646 + 36000.76983 * T + 0.0003032 * T2
	local M = 357.52911 + 35999.05029 * T - 0.0001537 * T2 - 0.00000048 * T2 * T
	local Mr = to_rad(M)
	local C = (1.914602 - 0.004817 * T - 0.000014 * T2) * sin(Mr) + (0.019993 - 0.000101 * T) * sin(2 * Mr) + 0.000289 * sin(3 * Mr)
	local true_lon = L0 + C
	local omega = 125.04 - 1934.136 * T
	local apparent_lon = true_lon - 0.00569 - 0.00478 * sin(to_rad(omega))
	return fix_angle(apparent_lon)
end

-- 太陽黄経が lon 度になる時刻(TTのユリウス日)。guess は近傍の推定値。
local function solar_crossing_tt(lon, guess_tt)
	lon = fix_angle(lon)
	local t = guess_tt
	for _ = 1, 30 do
		local diff = norm180(lon - sun_ecliptic_longitude_tt(t))
		t = t + diff / 0.9856
		if abs(diff) < 1e-9 then break end
	end
	return t
end

--------------------------------------------------------------------------------
-- 朔(新月):Meeus第49章(第2版)。平均朔と周期項(月・太陽の不均等+惑星摂動)に分けて返す。
--------------------------------------------------------------------------------
local function new_moon_parts(k)
	local T = k / 1236.85
	local T2 = T * T
	local T3 = T2 * T
	local T4 = T3 * T
	local mean = 2451550.09766 + 29.530588861 * k + 0.00015437 * T2 - 0.000000150 * T3 + 0.00000000073 * T4
	local M = 2.5534 + 29.10535670 * k - 0.0000014 * T2 - 0.00000011 * T3
	local Mprime = 201.5643 + 385.81693528 * k + 0.0107582 * T2 + 0.00001238 * T3 - 0.000000058 * T4
	local F = 160.7108 + 390.67050284 * k - 0.0016118 * T2 - 0.00000227 * T3 + 0.000000011 * T4
	local Omega = 124.7746 - 1.56375588 * k + 0.0020672 * T2 + 0.00000215 * T3
	local Mr = to_rad(M)
	local Mpr = to_rad(Mprime)
	local Fr = to_rad(F)
	local Or = to_rad(Omega)
	local E = 1 - 0.002516 * T - 0.0000074 * T2
	local delta = -0.40720 * sin(Mpr) + 0.17241 * E * sin(Mr) + 0.01608 * sin(2 * Mpr) + 0.01039 * sin(2 * Fr)
		+ 0.00739 * E * sin(Mpr - Mr) - 0.00514 * E * sin(Mpr + Mr) + 0.00208 * E * E * sin(2 * Mr)
		- 0.00111 * sin(Mpr - 2 * Fr) - 0.00057 * sin(Mpr + 2 * Fr) + 0.00056 * E * sin(2 * Mpr + Mr)
		- 0.00042 * sin(3 * Mpr) + 0.00042 * E * sin(Mr + 2 * Fr) + 0.00038 * E * sin(Mr - 2 * Fr)
		- 0.00024 * E * sin(2 * Mpr - Mr) - 0.00017 * sin(Or) - 0.00007 * sin(Mpr + 2 * Mr)
		+ 0.00004 * sin(2 * Mpr - 2 * Fr) + 0.00004 * sin(3 * Mr) + 0.00003 * sin(Mpr + Mr - 2 * Fr)
		+ 0.00003 * sin(2 * Mr + 2 * Fr) - 0.00003 * sin(Mpr + Mr + 2 * Fr) + 0.00003 * sin(Mpr - Mr + 2 * Fr)
		- 0.00002 * sin(Mpr - Mr - 2 * Fr) - 0.00002 * sin(3 * Mpr + Mr) + 0.00002 * sin(4 * Mpr)
	local A1 = fix_angle(299.77 + 0.107408 * k - 0.009173 * T2)
	local A2 = fix_angle(251.88 + 0.016321 * k)
	local A3 = fix_angle(251.83 + 26.651886 * k)
	local A4 = fix_angle(349.42 + 36.412478 * k)
	local A5 = fix_angle(84.66 + 18.206239 * k)
	local A6 = fix_angle(141.74 + 53.303771 * k)
	local A7 = fix_angle(207.14 + 2.453732 * k)
	local A8 = fix_angle(154.84 + 7.306860 * k)
	local A9 = fix_angle(34.52 + 27.261239 * k)
	local A10 = fix_angle(207.19 + 0.121824 * k)
	local A11 = fix_angle(291.34 + 1.844379 * k)
	local A12 = fix_angle(161.72 + 24.198154 * k)
	local A13 = fix_angle(239.56 + 25.513099 * k)
	local A14 = fix_angle(331.55 + 3.592518 * k)
	local planetary =
		  0.000325 * sin(to_rad(A1)) + 0.000165 * sin(to_rad(A2)) + 0.000164 * sin(to_rad(A3))
		+ 0.000126 * sin(to_rad(A4)) + 0.000110 * sin(to_rad(A5)) + 0.000062 * sin(to_rad(A6))
		+ 0.000060 * sin(to_rad(A7)) + 0.000056 * sin(to_rad(A8)) + 0.000047 * sin(to_rad(A9))
		+ 0.000042 * sin(to_rad(A10)) + 0.000040 * sin(to_rad(A11)) + 0.000037 * sin(to_rad(A12))
		+ 0.000035 * sin(to_rad(A13)) + 0.000023 * sin(to_rad(A14))
	return mean, delta + planetary
end

--------------------------------------------------------------------------------
-- 日本標準時(東経135度、UTC+9)を日の境界とする「真の天文計算」
--------------------------------------------------------------------------------
local JST_OFF = 9 / 24
local function dn_of_jd_ut(jd_ut) return floor(jd_ut + JST_OFF + 0.5) end

local ws_cache = {}
-- 西暦(ユリウス暦/グレゴリオ暦)g年12月の冬至(UT)
local function winter_solstice_ut(g)
	local v = ws_cache[g]
	if v then return v end
	local tt = solar_crossing_tt(270, 2451900.07 + 365.2422 * (g - 2000))
	v = jde_tt_to_jd_ut(tt)
	ws_cache[g] = v
	return v
end

local zq_cache = {}
-- g年12月の冬至から数えて i 番目の中気(定気、UT)。i=0が冬至。
local function zq_ut_true(g, i)
	if i == 0 then return winter_solstice_ut(g) end
	local key = g * 16 + i
	local v = zq_cache[key]
	if v then return v end
	local tt = solar_crossing_tt(270 + 30 * i, winter_solstice_ut(g) + i * 30.4369)
	v = jde_tt_to_jd_ut(tt)
	zq_cache[key] = v
	return v
end

local nm_cache = {}
local function nm_day_number_true(k)
	local v = nm_cache[k]
	if v then return v end
	local mean, per = new_moon_parts(k)
	v = dn_of_jd_ut(jde_tt_to_jd_ut(mean + per))
	nm_cache[k] = v
	return v
end

--------------------------------------------------------------------------------
-- 暦法(regime)
--   from_e : その暦法が最初に適用される旧暦年
--   shuo_dn(k) : 第k朔の日番号 / ws_dn(g) : g年12月の冬至の日番号
--   zq_dn(g,i) : 中気の日番号 / k_est(dn) : dnを含む朔月の概算番号
--------------------------------------------------------------------------------
local function make_true_regime(name, from_e, qmode, leap_force)
	local R = {name = name, from_e = from_e, leap_force = leap_force}
	R.shuo_dn = nm_day_number_true
	-- qmode: false=定気(太陽の実黄経)/true=平気(真の冬至から1年/12ずつ)
	--        table{Y=1年の日数, off=補正日数}=平気(暦の1年の長さによる線形モデル)
	local lin
	if type(qmode) == "table" then
		lin = function(g) return 2451900.07 + (g - 2000) * qmode.Y + qmode.off end
	end
	function R.ws_dn(g)
		if lin then return dn_of_jd_ut(lin(g)) end
		return dn_of_jd_ut(winter_solstice_ut(g))
	end
	function R.zq_dn(g, i)
		if lin then return dn_of_jd_ut(lin(g) + i * (qmode.Y / 12)) end
		if qmode then
			return dn_of_jd_ut(winter_solstice_ut(g) + i * (365.2422 / 12))
		end
		return dn_of_jd_ut(zq_ut_true(g, i))
	end
	function R.k_est(dn) return floor((dn - 0.5 - 2451550.09766) / 29.530588861) end
	return R
end

-- 旧暦法の定朔:平朔に、月の不均等(近点離角)と太陽の不均等(平均近点離角)の補正を加える。
-- 暦書の朓朒表の代用として、Meeus第49章の主要項を使い、太陽項の振幅(×1.4)と位相(-0.45rad)を
-- 参照表(日本暦日原典)との照合で較正した。
local function new_moon_xm(k)
	local T = k / 1236.85
	local M = to_rad(2.5534 + 29.10535670 * k)
	local Mp = to_rad(201.5643 + 385.81693528 * k + 0.0107582 * T * T)
	local E = 1 - 0.002516 * T
	local _, per = new_moon_parts(k)
	local base = -0.40720 * sin(Mp) + 0.01608 * sin(2 * Mp) + 0.17241 * E * sin(M)
	return -0.40720 * sin(Mp) + 0.01608 * sin(2 * Mp) + 1.4 * 0.17241 * E * sin(M - 0.45) + (per - base)
end

-- 暦書の定数に基づく平均値方式(abstract日付:日の境界は暦の0時)
--   q.lunar : 1朔望月(日) q.solar : 1年(日)
--   q.ws0   : e=q.e_ref の天正冬至(ユリウス通日、暦の0時=x.5)
--   q.shuo0 : k=0の平朔(同上)
--   q.km0   : 定朔にするとき、Meeus番号 = k + km0(nilなら平朔)
--   q.shin  : 進朔限(日の小数部がこれ以上なら翌日を朔日とする)の関数 (year)->値|nil
local function make_mean_regime(name, from_e, q)
	local R = {name = name, from_e = from_e}
	local cache = {}
	local function shuo_t(k)
		local t = q.shuo0 + k * q.lunar + (q.dt or 0)
		if q.km0 then
			if q.xm then
				t = t + new_moon_xm(k + q.km0)
			else
				local _, per = new_moon_parts(k + q.km0)
				t = t + per
			end
		end
		return t
	end
	function R.shuo_dn(k)
		local v = cache[k]
		if v then return v end
		local t = shuo_t(k)
		local day = floor(t + 0.5)
		local lim = q.shin and q.shin((date_from_jd(t)))
		if lim and (t + 0.5 - day) >= lim then day = day + 1 end
		cache[k] = day
		return day
	end
	local function ws_t(g) return q.ws0 + (g + 1 - q.e_ref) * q.solar end
	function R.ws_dn(g) return floor(ws_t(g) + 0.5) end
	function R.zq_dn(g, i) return floor(ws_t(g) + i * q.solar / 12 + 0.5) end
	function R.k_est(dn) return floor((dn - 0.5 - q.shuo0) / q.lunar) end
	return R
end

-- 暦元を採用時点の天文計算値に合わせた平均値方式(元嘉暦・儀鳳暦・大衍暦用)
local CHANGAN = 7.26 / 24
local function make_calibrated_regime(name, from_e, e_ref, lunar, solar, dingshuo, shin, ws_adj, sh_adj, ds)
	local g = e_ref - 1
	local ws_ut = winter_solstice_ut(g)
	local km = floor((ws_ut - 2451550.09766) / 29.530588861)
	local mean = new_moon_parts(km)
	return make_mean_regime(name, from_e, {
		lunar = lunar, solar = solar + (ds or 0), e_ref = e_ref,
		ws0 = ws_ut + CHANGAN + (ws_adj or 0),
		shuo0 = jde_tt_to_jd_ut(mean) + CHANGAN + (sh_adj or 0),
		km0 = dingshuo and km or nil,
		shin = shin,
	})
end

-- 宣明暦(862~1684):統法8400、章歳3068055、章月248057、
-- 長慶2年(822)の天正冬至=大余48・小余6390、閏余160264
local XM_SOLAR = 365 + 137 / 560
local XM_LUNAR = 248057 / 8400
local XM_WS0 = 1721047.5 + 93 / 140
local XM_SHUO0 = XM_WS0 + 822 * XM_SOLAR - 160264 / 8400

local REGIMES
local function get_regimes()
	if REGIMES then return REGIMES end
	REGIMES = {
		-- 暦法導入以前(現代天文計算)
		make_true_regime("astro", -9999, false, nil),
		-- 元嘉暦(何承天・445):19年7閏、日法752、月法22207。日本では推古12年(604)頃から
		-- 儀鳳暦の採用(697)まで。参照表(日本暦日原典)との照合で冬至・朔の基準を較正
		(function()
			local lunar = 29 + 399 / 752
			return make_calibrated_regime("genka", 604, 443, lunar, 235 * lunar / 19, true, nil, -0.327, 0.135, -1.73e-4)
		end)(),
		-- 儀鳳暦(麟徳暦・665):総法1340、定朔
		make_calibrated_regime("giho", 697, 665, 29 + 711 / 1340, 365 + 328 / 1340, true, nil, 0.009, 0.095, -2.9e-5),
		-- 大衍暦(729):統法3040、進朔限は年代別
		make_calibrated_regime("taien", 764, 729, 29 + 1613 / 3040, 365 + 743 / 3040, true, function(y)
			if y < 766 then return nil end
			if y <= 767 then return 2660 / 3040 end
			if y <= 792 then return 2534 / 3040 end
			if y <= 836 then return 2787 / 3040 end
			return 2660 / 3040
		end, 0.026, -0.020, -1.06e-4),
		make_mean_regime("senmyo", 862, {
			lunar = XM_LUNAR, solar = XM_SOLAR, e_ref = 0, ws0 = XM_WS0, shuo0 = XM_SHUO0,
			km0 = -14571, xm = true, dt = 0.0857, shin = function() return 0.933 end,
		}),
		make_true_regime("jokyo", 1685, {Y = 365.2422, off = -0.5}, nil),
		make_true_regime("horeki", 1755, {Y = 365.2422, off = -0.5}, nil),
		make_true_regime("kansei", 1798, {Y = 365.2422, off = -0.375}, nil),
		-- 天保暦:嘉永5年閏2月(冬至1851年12月の年)は実暦に合わせて例外とする
		make_true_regime("tenpo", 1844, false, {[1851] = 2}),
	}
	return REGIMES
end

--------------------------------------------------------------------------------
-- 冬至月(11月)から次の冬至月の直前までの各月(span)
--------------------------------------------------------------------------------
local span_cache = {}
local function build_span(R, g)
	local key = R.name .. "|" .. g
	local c = span_cache[key]
	if c then return c end

	local function find_k(dn)
		local k = R.k_est(dn)
		for _ = 1, 12 do
			if R.shuo_dn(k) > dn then
				k = k - 1
			elseif R.shuo_dn(k + 1) <= dn then
				k = k + 1
			else
				return k
			end
		end
		return k
	end

	local k0 = find_k(R.ws_dn(g))
	local k1 = find_k(R.ws_dn(g + 1))
	local zq = {}
	for i = 0, 11 do zq[i] = R.zq_dn(g, i) end

	local months = {}
	for k = k0, k1 - 1 do
		local s, e = R.shuo_dn(k), R.shuo_dn(k + 1)
		local has = false
		for i = 0, 11 do
			if zq[i] >= s and zq[i] < e then has = true break end
		end
		months[#months + 1] = {start_dn = s, end_dn = e, major = has}
	end
	local n = #months

	-- 13か月なら最初の中気のない月が閏月(例外指定があればそれに従う)
	local leap_idx = nil
	if R.leap_force and R.leap_force[g] then
		local j = ((R.leap_force[g] - 11) % 12) + 1
		if j + 1 <= n then leap_idx = j + 1 end
	elseif n >= 13 then
		for i = 2, n do
			if not months[i].major then leap_idx = i break end
		end
		if not leap_idx then leap_idx = n end
	end

	local mnum = 11
	local ly = g
	for i = 1, n do
		local mo = months[i]
		if i == 1 then
			mo.month, mo.leap = 11, false
		elseif i == leap_idx then
			mo.month, mo.leap = mnum, true
		else
			mnum = (mnum % 12) + 1
			mo.month, mo.leap = mnum, false
		end
		if i > 1 and mo.month == 1 and not mo.leap then ly = g + 1 end
		mo.lyear = ly
	end

	c = {months = months, first = months[1].start_dn, last_end = months[n].end_dn}
	span_cache[key] = c
	return c
end

-- 暦法が最初に適用される日(その暦法の最初の正月朔日)
local function regime_start_dn(R)
	if R.start_dn ~= nil then return R.start_dn end
	if R.from_e <= -9000 then
		R.start_dn = -huge
	else
		local sp = build_span(R, R.from_e - 1)
		for _, mo in ipairs(sp.months) do
			if mo.month == 1 and not mo.leap then
				R.start_dn = mo.start_dn
				break
			end
		end
		R.start_dn = R.start_dn or -huge
	end
	return R.start_dn
end

local function regime_index_for_dn(dn)
	local rs = get_regimes()
	local ri = #rs
	while ri > 1 and dn < regime_start_dn(rs[ri]) do ri = ri - 1 end
	return ri, rs
end

-- 新暦(グレゴリオ暦)の施行日:1873年1月1日(明治6年1月1日)
local function is_new_calendar(y)
	return y >= 1873
end

-- 指定日(ユリウス暦/グレゴリオ暦)の旧暦。新暦の日付では nil を返す。
local function convert_to_lunar(gy, gm, gd)
	if is_new_calendar(gy) then return nil, "new calendar" end
	local dn = day_number_from_date(gy, gm, gd)
	local ri, rs = regime_index_for_dn(dn)
	local R, nxt = rs[ri], rs[ri + 1]
	for _, g in ipairs({gy - 1, gy, gy - 2, gy + 1}) do
		local sp = build_span(R, g)
		if dn >= sp.first and dn < sp.last_end then
			for i, mo in ipairs(sp.months) do
				if dn >= mo.start_dn and dn < mo.end_dn then
					-- 次の暦法の施行前なのに旧暦法が新暦年の正月に入っている場合は、前月の延長とみなす
					if nxt and i > 1 and mo.lyear >= nxt.from_e then
						mo = sp.months[i - 1]
					end
					return {
						lyear = mo.lyear, lmonth = mo.month, lday = dn - mo.start_dn + 1,
						isLeap = mo.leap, regime = R.name,
					}
				end
			end
		end
	end
	return nil, "cannot map lunar"
end

-- 旧暦年 y の正月朔日(日番号)。新暦の年は1月1日。
local function new_year_dn(y)
	if is_new_calendar(y) then return day_number_from_date(y, 1, 1) end
	local dn_mid = day_number_from_date(y, 3, 1)
	local ri, rs = regime_index_for_dn(dn_mid)
	local R = rs[ri]
	local sp = build_span(R, y - 1)
	for _, mo in ipairs(sp.months) do
		if mo.month == 1 and not mo.leap and mo.lyear == y then return mo.start_dn end
	end
	return nil
end


local eras = {
	{name="推古", start=5921212},{name="舒明", start=6280415},{name="皇極", start=6411117},{name="大化", start=6450717},
	{name="白雉", start=6500322},{name="斉明", start=6550211},{name="天智", start=6610824},{name="弘文", start=6720107},
	{name="天武", start=6720821},{name="朱鳥", start=6860814},{name="持統", start=6870217},{name="文武", start=6970822},
	{name="大宝", start=7010503},{name="慶雲", start=7040616},{name="和銅", start=7080207},{name="霊亀", start=7151003},
	{name="養老", start=7171224},{name="神亀", start=7240303},{name="天平", start=7290902},{name="天平感宝", start=7490504},
	{name="天平勝宝", start=7490819},{name="天平宝字", start=7570906},{name="天平神護", start=7650201},{name="神護景雲", start=7670913},
	{name="宝亀", start=7701023},{name="天応", start=7810130},{name="延暦", start=7820930},{name="大同", start=8060608},
	{name="弘仁", start=8101020},{name="天長", start=8240208},{name="承和", start=8340214},{name="嘉祥", start=8480716},
	{name="仁寿", start=8510601},{name="斉衡", start=8541223},{name="天安", start=8570320},{name="貞観", start=8590520},
	{name="元慶", start=8770601},{name="仁和", start=8850311},{name="寛平", start=8890530},{name="昌泰", start=8980520},
	{name="延喜", start=9010831},{name="延長", start=9230529},{name="承平", start=9310516},{name="天慶", start=9380622},
	{name="天暦", start=9470515},{name="天徳", start=9571121},{name="応和", start=9610305},{name="康保", start=9640819},
	{name="安和", start=9680908},{name="天禄", start=9700503},{name="天延", start=9740116},{name="貞元", start=9760811},
	{name="天元", start=9781231},{name="永観", start=9830529},{name="寛和", start=9850519},{name="永延", start=9870505},
	{name="永祚", start=9890910},{name="正暦", start=9901126},{name="長徳", start=9950325},{name="長保", start=9990201},
	{name="寛弘", start=10040808},{name="長和", start=10130208},{name="寛仁", start=10170521},{name="治安", start=10210317},
	{name="万寿", start=10240819},{name="長元", start=10280818},{name="長暦", start=10370509},{name="長久", start=10401216},
	{name="寛徳", start=10441216},{name="永承", start=10460522},{name="天喜", start=10530202},{name="康平", start=10580919},
	{name="治暦", start=10650904},{name="延久", start=10690506},{name="承保", start=10740916},{name="承暦", start=10771205},
	{name="永保", start=10810322},{name="応徳", start=10840315},{name="寛治", start=10870511},{name="嘉保", start=10950123},
	{name="永長", start=10970103},{name="承徳", start=10971227},{name="康和", start=10990915},{name="長治", start=11040308},
	{name="嘉承", start=11060513},{name="天仁", start=11080909},{name="天永", start=11100731},{name="永久", start=11130825},
	{name="元永", start=11180425},{name="保安", start=11200509},{name="天治", start=11240518},{name="大治", start=11260215},
	{name="天承", start=11310228},{name="長承", start=11320921},{name="保延", start=11350610},{name="永治", start=11410813},
	{name="康治", start=11420525},{name="天養", start=11440328},{name="久安", start=11450812},{name="仁平", start=11510214},
	{name="久寿", start=11541204},{name="保元", start=11560518},{name="平治", start=11590509},{name="永暦", start=11600218},
	{name="応保", start=11610924},{name="長寛", start=11630504},{name="永万", start=11650714},{name="仁安", start=11660923},
	{name="嘉応", start=11690506},{name="承安", start=11710527},{name="安元", start=11750816},{name="治承", start=11770829},
	{name="養和", start=11810825},{name="寿永", start=11820629},{name="元暦", start=11840527},{name="文治", start=11850909},
	{name="建久", start=11900516},{name="正治", start=11990523},{name="建仁", start=12010319},{name="元久", start=12040323},
	{name="建永", start=12060605},{name="承元", start=12071116},{name="建暦", start=12110423},{name="建保", start=12140118},
	{name="承久", start=12190527},{name="貞応", start=12220525},{name="元仁", start=12241231},{name="嘉禄", start=12250528},
	{name="安貞", start=12280118},{name="寛喜", start=12290331},{name="貞永", start=12320423},{name="天福", start=12330525},
	{name="文暦", start=12341127},{name="嘉禎", start=12351101},{name="暦仁", start=12381230},{name="延応", start=12390313},
	{name="仁治", start=12400805},{name="寛元", start=12430318},{name="宝治", start=12470405},{name="建長", start=12490502},
	{name="康元", start=12561024},{name="正嘉", start=12570331},{name="正元", start=12590420},{name="文応", start=12600524},
	{name="弘長", start=12610322},{name="文永", start=12640327},{name="建治", start=12750522},{name="弘安", start=12780323},
	{name="正応", start=12880529},{name="永仁", start=12930906},{name="正安", start=12990525},{name="乾元", start=13021210},
	{name="嘉元", start=13030916},{name="徳治", start=13070118},{name="延慶", start=13081122},{name="応長", start=13110517},
	{name="正和", start=13120427},{name="文保", start=13170316},{name="元応", start=13190518},{name="元亨", start=13210322},
	{name="正中", start=13241225},{name="嘉暦", start=13260528},{name="元徳", start=13290922},{name="元弘", start=13310911},
	{name="正慶", start=13320523},{name="建武", start=13340305, court="north"},
	{name="延元", start=13360411, court="south"},{name="暦応", start=13381011, court="north"},
	{name="興国", start=13400525, court="south"},{name="康永", start=13420601, court="north"},
	{name="貞和", start=13451115, court="north"},{name="正平", start=13470120, court="south"},
	{name="観応", start=13500404, court="north"},{name="文和", start=13521104, court="north"},
	{name="延文", start=13560429, court="north"},{name="康安", start=13610504, court="north"},
	{name="貞治", start=13621011, court="north"},{name="応安", start=13680307, court="north"},
	{name="建徳", start=13700816, court="south"},
	{name="文中", start=13720504, court="south"},
	{name="永和", start=13750329, court="north"},
	{name="天授", start=13750626, court="south"},
	{name="康暦", start=13790409, court="north"},
	{name="永徳", start=13810320, court="north"},
	{name="弘和", start=13810306, court="south"},
	{name="至徳", start=13840319, court="north"},{name="元中", start=13840518, court="south"},
	{name="嘉慶", start=13871005, court="north"},{name="康応", start=13890307, court="north"},
	{name="明徳", start=13900412, court="north"}, -- 1392年閏10月5日の南北朝合一以後は唯一の元号として継続
	{name="応永", start=13940802},
	{name="正長", start=14280610},
	{name="永享", start=14291003},{name="嘉吉", start=14410310},{name="文安", start=14440223},{name="宝徳", start=14490816},
	{name="享徳", start=14520810},{name="康正", start=14550906},{name="長禄", start=14571016},{name="寛正", start=14610201},
	{name="文正", start=14660314},{name="応仁", start=14670409},{name="文明", start=14690608},{name="長享", start=14870809},
	{name="延徳", start=14890916},{name="明応", start=14920812},{name="文亀", start=15010318},{name="永正", start=15040316},
	{name="大永", start=15210923},{name="享禄", start=15280903},{name="天文", start=15320829},{name="弘治", start=15551107},
	{name="永禄", start=15580318},{name="元亀", start=15700527},{name="天正", start=15730825},{name="文禄", start=15930110},
	{name="慶長", start=15961216},{name="元和", start=16150905},{name="寛永", start=16240417},{name="正保", start=16450113},
	{name="慶安", start=16480407},{name="承応", start=16521020},{name="明暦", start=16550518},{name="万治", start=16580821},
	{name="寛文", start=16610523},{name="延宝", start=16731030},{name="天和", start=16811109},{name="貞享", start=16840405},
	{name="元禄", start=16881023},{name="宝永", start=17040416},{name="正徳", start=17110611},{name="享保", start=17160809},
	{name="元文", start=17360607},{name="寛保", start=17410412},{name="延享", start=17440403},{name="寛延", start=17480805},
	{name="宝暦", start=17511214},{name="明和", start=17640630},{name="安永", start=17721210},{name="天明", start=17810425},
	{name="寛政", start=17890219},{name="享和", start=18010319},{name="文化", start=18040322},{name="文政", start=18180526},
	{name="天保", start=18310123},{name="弘化", start=18450109},{name="嘉永", start=18480401},{name="安政", start=18550115},
	{name="万延", start=18600408},{name="文久", start=18610329},{name="元治", start=18640327},{name="慶応", start=18650501},
	{name="明治", start=18680125},{name="大正", start=19120730},{name="昭和", start=19261225},{name="平成", start=19890108},
	{name="令和", start=20190501},
}

--   開始=延元改元(南朝方の分立開始、1336年)
--   終了=明徳の和約による南北朝合一(ユリウス暦1392年11月19日)
local NANBOKUCHO_START = 13360411
local NANBOKUCHO_END   = 13921119 -- この日付「以降」は eras(明徳)側に一本化
-- 南朝/北朝それぞれの元号だけを抽出した副次テーブル
local eras_south, eras_north = {}, {}
for _, e in ipairs(eras) do
	if e.court == "south" then eras_south[#eras_south + 1] = e end
	if e.court == "north" then eras_north[#eras_north + 1] = e end
end

--------------------------------------------------------------------------------
-- 日情報(日番号 → 旧暦/新暦の年月日と元号)
--------------------------------------------------------------------------------
local REIGN = {["推古"]=true,["舒明"]=true,["皇極"]=true,["斉明"]=true,["天智"]=true,["弘文"]=true,["天武"]=true,["持統"]=true,["文武"]=true}

local function ymd_int(y, m, d)
	return y * 10000 + (m or 1) * 100 + (d or 1)
end

local era_lyear_cache = {}
local function era_start_lyear(e)
	local v = era_lyear_cache[e]
	if v then return v end
	local sy = floor(e.start / 10000)
	local sm = floor(e.start / 100) % 100
	local sd = e.start % 100
	if is_new_calendar(sy) then
		v = sy
	else
		local l = convert_to_lunar(sy, sm, sd)
		v = l and l.lyear or sy
	end
	era_lyear_cache[e] = v
	return v
end

-- 元号の表示形(返り値:{text=, name=, ey=})
local function scan_era_list(list, yi, lyear)
	for i = #list, 1, -1 do
		local e = list[i]
		if yi >= e.start then
			local ey = lyear - era_start_lyear(e) + 1
			if ey < 1 then ey = 1 end
			local name = e.name .. (REIGN[e.name] and "天皇" or "")
			local es = (ey == 1) and "元" or tostring(ey)
			return {text = name .. es, name = name, ey = es}
		end
	end
	return nil
end

local function wareki(y, m, d, lyear)
	local yi = ymd_int(y, m, d)
	if yi >= NANBOKUCHO_START and yi < NANBOKUCHO_END then
		local s = scan_era_list(eras_south, yi, lyear)
		local n = scan_era_list(eras_north, yi, lyear)
		if s and n then
			return {text = string.format("南朝: %s年・北朝: %s年", s.text, n.text), nb = true}
		end
	end
	return scan_era_list(eras, yi, lyear) or {text = ""}
end

-- 日番号 dn の情報
local function info_of_dn(dn)
	local y, m, d = date_from_day_number(dn)
	local info = {y = y, m = m, d = d, dn = dn}
	if is_new_calendar(y) then
		info.isNew, info.lyear, info.lmonth, info.lday, info.isLeap = true, y, m, d, false
	else
		local l = convert_to_lunar(y, m, d)
		if not l then return nil end
		info.isNew, info.lyear, info.lmonth, info.lday, info.isLeap = false, l.lyear, l.lmonth, l.lday, l.isLeap
	end
	info.wk = wareki(y, m, d, info.lyear)
	return info
end

local function ylabel(y)
	if y <= 0 then return "紀元前" .. (1 - y) end
	return tostring(y)
end

local function era_year_text(info)
	if info.wk.nb then return info.wk.text end
	if info.wk.text ~= "" then return info.wk.text .. "年" end
	return "旧暦" .. ylabel(info.lyear) .. "年"
end

local function md_text(info, level)
	local s = (info.isLeap and "閏" or "") .. info.lmonth .. "月"
	if level == "day" then s = s .. info.lday .. "日" end
	return s
end

local function full_text(info, level)
	return era_year_text(info) .. md_text(info, level)
end

-- 範囲の終端表記:同じ元号年なら年を省略、同じ元号なら年数のみ
local function end_text(a, b, level)
	if a.wk.text ~= "" and a.wk.text == b.wk.text then
		return md_text(b, level)
	elseif a.wk.text == "" and b.wk.text == "" and a.lyear == b.lyear then
		return md_text(b, level)
	elseif a.wk.name and a.wk.name == b.wk.name then
		return b.wk.ey .. "年" .. md_text(b, level)
	end
	return full_text(b, level)
end

local function span_text(a, b, level, sep)
	if a.wk.text == b.wk.text and a.lyear == b.lyear and a.lmonth == b.lmonth and a.isLeap == b.isLeap and a.lday == b.lday and level == "day" then
		return full_text(a, level)
	end
	if level == "month" and a.lyear == b.lyear and a.lmonth == b.lmonth and a.isLeap == b.isLeap then
		return full_text(a, level)
	end
	return full_text(a, level) .. sep .. end_text(a, b, level)
end

--------------------------------------------------------------------------------
-- 入力の解析
--------------------------------------------------------------------------------
local function trim(s)
	s = tostring(s or "")
	s = s:gsub("^%s+", "")
	s = s:gsub("%s+$", "")
	return s
end

local function clean(s)
	s = s:gsub("%[%[([^%]|]*)|[^%]]*%]%]", "%1")
	s = s:gsub("%[%[([^%]]*)%]%]", "%1")
	s = s:gsub("%s+", "")
	return s
end

local function mkdate(y, m, d, bc)
	if bc then y = 1 - y end
	return {year = y, month = m, day = d}
end

local function parse_part(raw)
	local c = clean(raw)
	if c == "" then return nil end
	local a, b, d = c:match("^(%d+)%-(%d%d?)%-(%d%d?)$")
	if a then return mkdate(tonumber(a), tonumber(b), tonumber(d)) end
	a, b, d = c:match("^(%d+)/(%d%d?)/(%d%d?)$")
	if a then return mkdate(tonumber(a), tonumber(b), tonumber(d)) end
	a, b = c:match("^(%d+)/(%d%d?)$")
	if a then return mkdate(tonumber(a), tonumber(b), nil) end
	if c:match("^%d%d?%d?%d?$") then return mkdate(tonumber(c), nil, nil) end

	local bc = false
	local yy = c:match("紀元前(%d+)年")
	if yy then bc = true else yy = c:match("(%d+)年") end
	local mm, dd = c:match("(%d+)月(%d+)日")
	if not mm then
		mm = c:match("(%d+)月")
		if not mm then dd = c:match("(%d+)日") end
	end
	if not yy and not mm and not dd then return nil end
	local t = mkdate(yy and tonumber(yy) or nil, mm and tonumber(mm) or nil, dd and tonumber(dd) or nil, bc and yy)
	if bc then t.year = 1 - tonumber(yy) end
	return t
end

local function days_in_month(y, m)
	local first = day_number_from_date(y, m, 1)
	local ny, nm = y, m + 1
	if nm > 12 then ny, nm = y + 1, 1 end
	return day_number_from_date(ny, nm, 1) - first
end

local function valid_ymd(y, m, d)
	if not (y and m and d) then return false end
	if m < 1 or m > 12 or d < 1 or d > 31 then return false end
	local yy, mm, dd = date_from_day_number(day_number_from_date(y, m, d))
	return yy == y and mm == m and dd == d
end

-- 日付片(年・月・日の欠けを許す)から [開始日番号, 終了日番号, 精度] を返す
local function bounds(t)
	if t.year and t.month and t.day then
		if not valid_ymd(t.year, t.month, t.day) then return nil end
		local dn = day_number_from_date(t.year, t.month, t.day)
		return dn, dn, "day"
	elseif t.year and t.month then
		if t.month < 1 or t.month > 12 then return nil end
		local s = day_number_from_date(t.year, t.month, 1)
		return s, s + days_in_month(t.year, t.month) - 1, "month"
	elseif t.year then
		local s = new_year_dn(t.year)
		local e = new_year_dn(t.year + 1)
		if not (s and e) then return nil end
		return s, e - 1, "year"
	end
	return nil
end

--------------------------------------------------------------------------------
-- 出力
--------------------------------------------------------------------------------
-- 年の表記(リンク込み)の直後に元号年を挿入する(新暦用)
local function insert_after_year(raw, ins)
	local s, e = raw:find("%[%[[^%[%]|]-%d+年[^%[%]]-%]%]")
	if s then
		local seg = raw:sub(s, e)
		if not seg:find("月") then
			return raw:sub(1, e) .. ins .. raw:sub(e + 1)
		end
	end
	s, e = raw:find("紀元前%d+年")
	if not s then s, e = raw:find("%d+年") end
	if s then return raw:sub(1, e) .. ins .. raw:sub(e + 1) end
	return raw .. ins
end

local function decorate(raw_a, raw_b, sep, ta, tb)
	local sa, ea, la = bounds(ta)
	if not sa then return nil end
	local sb, eb, lb
	if tb then
		sb, eb, lb = bounds(tb)
		if not sb then return nil end
	end

	-- 精度:日付が両端とも「日」なら日、月だけなら月、年だけなら年
	local level
	if tb then
		if la == "day" and lb == "day" then level = "day"
		elseif la == "year" and lb == "year" then level = "year"
		elseif la == "year" or lb == "year" then level = "day"
		elseif la == "month" and lb == "month" then level = "month"
		else level = "day" end
		-- 片方だけ「日」を持つ場合、省略側は初日/末日で補う(sa, eb)
	else
		level = la
	end

	-- 始点は初日、終点は末日(日精度で片側だけ月・年の場合も同様に補う)
	local first = sa
	local last = tb and eb or ea
	local ia, ib = info_of_dn(first), info_of_dn(last)
	if not (ia and ib) then return nil end

	local note
	if level == "year" then
		if ia.wk.text == "" and ib.wk.text == "" then return nil end
		local at = era_year_text(ia)
		if not tb then
			local bt = era_year_text(ib)
			note = (bt ~= at) and (at .. "・" .. bt) or at
		else
			note = at .. "から" .. ((ib.wk.name and ib.wk.name == ia.wk.name) and (ib.wk.ey .. "年") or era_year_text(ib))
		end
	else
		note = span_text(ia, ib, level, "から")
		if not tb and level == "day" then note = full_text(ia, level) end
	end

	local raw = tb and (raw_a .. sep .. raw_b) or raw_a
	if ia.isNew and ib.isNew then
		-- 新暦:年表記の直後に元号年を挿入(従来の表示形式)
		if level == "year" then return raw .. "(" .. note .. ")" end
		local wa = era_year_text(ia)
		local ins = "(" .. wa .. ")"
		if tb and ib.wk.text ~= ia.wk.text then
			ins = "(" .. wa .. "から" .. era_year_text(ib) .. ")"
		end
		return insert_after_year(raw_a, ins) .. (tb and (sep .. raw_b) or "")
	end
	return raw .. "(" .. note .. ")"
end

--------------------------------------------------------------------------------
-- 脚注の除去
--------------------------------------------------------------------------------
local function strip_ignored(s)
	s = tostring(s or "")
	s = s:gsub("\127'\"`UNIQ%-%-ref%-%x+%-QINU`\"'\127", "")
	s = s:gsub("\127'\"`UNIQ%-%-[^%s]+%-QINU`\"'\127", "")
	s = mw.ustring.gsub(s, "<ref[^/>]*/>", "")
	s = mw.ustring.gsub(s, "<ref[^>]*>.-</ref>", "")
	s = mw.ustring.gsub(s, "{{%s*[Ss]fn.-}}", "")
	s = mw.ustring.gsub(s, "{{%s*[Ee]fn.-}}", "")
	s = mw.ustring.gsub(s, "{{%s*[Rr]efnest.-}}", "")
	s = mw.ustring.gsub(s, "{{%s*[Rr]%s*[|}].-}}", "")
	s = mw.ustring.gsub(s, "{{%s*要出典.-}}", "")
	return s
end

local SEPS = {"から", "〜", "~", "–", "—", "−", "/"}

local function split_range(s)
	for _, sep in ipairs(SEPS) do
		local i, j = s:find(sep, 1, true)
		if i then return s:sub(1, i - 1), s:sub(j + 1), sep end
	end
	return nil
end

local function convert_impl(frame)
	local args = getArgs(frame)
	local input = args[1] or args.date or args["1"]
	if not input then return "" end
	input = trim(strip_ignored(input))
	if input == "" then return "" end

	-- 単一の日付(YYYY/M/D・YYYY-M-D)を先に判定
	local single = parse_part(input)
	local c = clean(input)
	if single and (c:match("^%d+/%d%d?/%d%d?$") or c:match("^%d+/%d%d?$") or c:match("^%d+%-%d%d?%-%d%d?$")) then
		return decorate(input, nil, nil, single, nil) or input
	end

	local ra, rb, sep = split_range(input)
	if ra then
		ra, rb = trim(ra), trim(rb)
		local a, b = parse_part(ra), parse_part(rb)
		if a and b then
			-- 欠けた年・月を補う
			if not a.year and b.year then a.year = b.year end
			if not b.year and a.year then b.year = a.year end
			if not a.month and a.day and b.month then a.month = b.month end
			if not b.month and b.day and a.month then b.month = a.month end
			if b.year == a.year and a.month and b.month and not (rb:find("年") or rb:find("/")) then
				if b.month < a.month or (b.month == a.month and b.day and a.day and b.day < a.day) then
					b.year = a.year + 1
				end
			end
			return decorate(ra, rb, sep, a, b) or input
		end
	end

	if single then return decorate(input, nil, nil, single, nil) or input end
	return input
end

function p.convert(frame)
	local ok, res = pcall(convert_impl, frame)
	if ok then return res end
	local args = getArgs(frame)
	return tostring(args[1] or args.date or "")
end

return p