-- This module is for 南寧平話 (Nanning Pinghua)
-- Not to be confused with 南寧白話, which is more like Cantonese
-- Representative variety: 亭子
-- Romanisation: Jyutping++ (referred to as jpp below)
-- References:
-- 1. 南宁平话词典 by 覃远雄 et al. (1997)
-- 2. https://leimaau.github.io/book/PHONETICIZE_bingwaa.html
-- 3. 广西通志·汉语方言志 (1998)
-- Also see [[Category:Nanning Pinghua]]

local export = {}

local initials = {
	b = "p",  p = "pʰ",  m = "m",  f = "f",           w = "β",
	d = "t",  t = "tʰ",  n = "n",  l = "l",
	z = "t͡s", c = "t͡sʰ", nj = "ɲ", s = "s", sl = "ɬ", j = "j",
	g = "k",  k = "kʰ",  ng = "ŋ", h = "h",
	gw = "kʷ", kw = "kʰʷ",
	[""] = "", -- glottal stop?
}

-- Notes:
-- iang="iɐŋ", iak="iɐk̚" in the same row as <e>
-- ing="ɪŋ", ik="ɪk̚" in the same row as <i>
-- ung="ʊŋ", uk="ʊk̚" in the same row as <u>
local finals = {
	aa="a", aai="ai", aau="au", aam="am", aan="an", aang="aŋ", aap="ap̚", aat="at̚", aak="ak̚",
	         ai="əi",  au="əu",  am="əm",  an="ən",  ang="əŋ",  ap="əp̚",  at="ət̚",  ak="ək̚",
	 e="e",            eu="eu",  em="em",  en="en", iang="iɐŋ", ep="ep̚",  et="et̚", iak="iɐk̚",
	 o="o",                                on="on",                       ot="ot̚",
	 i="i",            iu="iu",im="im",["in"]="in",  ing="ɪŋ",  ip="ip̚",  it="it̚",  ik="ɪk̚",
	 u="u",  ui="ui",                      un="un",  ung="ʊŋ",            ut="ut̚",  uk="ʊk̚",
	yu="y",                               yun="yn",                      yut="yt̚",
	oe="ø",                                         oeng="øŋ",                     oek="øk̚",
}

local syllabics = {
	ng = "ŋ̍"
}

local tones = {
	["1"] = "⁵³", -- 陰平(詩)
	["2"] = "³³", -- 陰上(屎) / 下陰入(得)
	["3"] = "⁵⁵", -- 陰去(世) / 上陰入(粒)
	["4"] = "²¹", -- 陽平(時)
	["5"] = "²⁴", -- 陽上(市) / 上陽入(劣)
	["6"] = "²²", -- 陽去(是) / 下陽入(絕)
}

function export.jpp_to_ipa(text)
	text = text:gsub(", "," ")
	if text:find("^ ") or text:find(" $") or text:find(" ,") or text:find(",,") or text:find("  ") then
		error("Empty syllable detected.")
	end
	return "/" .. text:gsub("[^ ,]+", function(syllable_tone)
		syl, tone = syllable_tone:match("^(%w+)([1-6])$")
		if not syl then
			error("Invalid syllable: " .. syllable_tone)
		end
		tone = tones[tone]
		if syllabics[syl] then
			return syllabics[syl] .. tone
		end
		initial, final = syl:match("^([bpmfwdtnlzcjsgkh]*)([aeiouy]+[mnptk]?g?)$")
		if not initial then
			error("Invalid syllable: " .. syllable_tone)
		end
		return (initials[initial] or error("Invalid initial: " .. syllable_tone))
			.. (finals[final] or error("Invalid final: " .. syllable_tone))
			.. tone
	end):gsub(",","/, /") .. "/"
end

return export