-- This module is for 開平話 (Kaiping Yue), a lect of Yue Chinese
-- Representative locality: 赤坎
-- Romanisation: Jyutping++ (referred to as jpp below)
-- References:
-- 1. 开平方言 (2000) by 邓钧

local export = {}

local initials = {
	b = "p",  p = "pʰ",  m = "m",  f = "f",
	d = "t",  t = "tʰ",  n = "n",  sl = "ɬ", l = "l",
	z = "t͡s", c = "t͡sʰ", s = "s",
	g = "k",  k = "kʰ",  ng = "ŋ", h = "h",
	j = "j",  w = "v",
	[""] = "",
}

local finals = {
	a="a",ai="ai",au="au",am="am",an="an",ang="aŋ",ap="ap̚",at="at̚",ak="ak̚",
	e="e",ei="ei",eu="eu",em="em",en="en",         ep="ep̚",et="et̚",
	ie="iɛ",                            ieng="iɛŋ",               iek="iɛk̚",
	o="ɔ",oi="ɔi",                on="ɔn",ong="ɔŋ",        ot="ɔt̚",ok="ɔk̚",
	uo="uɔ",
	i="i",        iu="iu",im="im",["in"]="in",     ip="ip̚",it="it̚",
	u="u", ui="ui",               un="un", ung="ʊŋ",       ut="ut̚", uk="ʊk̚",
	m="m̩",
	ng="ŋ̍",
}

-- "3" merges into "1"
local tones = {
	["1"] = "33", --陰平/陰去/下陰入
	["2"] = "55", --陰上/上陰入
	["4"] = "22", --陽平
	["5"] = "21", --陽上
	["6"] = "32", --陽去/陽入
}

local sandhi = {
	["1*"]="35", ["4*"]="15", ["5*"]="215", ["6*"]="325",
	["1-2"]="55", ["4-2"]="55", ["5-2"]="55", ["6-2"]="55",
	["1-5"]="21", ["2-5"]="21", ["4-5"]="21", ["6-5"]="21",
	["1-5*"]="215", ["2-5*"]="215", ["4-5*"]="215", ["6-5*"]="215",
}

local function tone_superscript(text)
	return text:gsub("[1235]",{["1"]="¹",["2"]="²",["3"]="³",["5"]="⁵"})
end

local function validate(text)
	text = text:gsub(","," ")
	if text:sub(1,1) == " " or text:sub(-1,-1) == " " or text:match("  ") then
		error("Kaiping: Empty syllable detected.")
	end
end

function export.jpp_to_ipa(text)
	validate(text)
	text = text:gsub("[^ ,]+",function(syllable)
		local a,b,c,d = syllable:match("^([bpmfdtnlzcsgknhjw]?[lg]?)([aeioumn]%l*)([12456])(%-?[25]?%*?)$")
		if not a then
			error("Kaiping: Invalid syllable: " .. syllable)
		end
		return (initials[a] or error("Kaiping: Unrecognised initial: " .. a))
			.. (finals[b] or error("Kaiping: Unrecognised final: " .. b))
			.. tones[c]
			.. (d~="" and ("⁻"..(sandhi[c..d] or error("Kaiping: Unrecognised tone sandhi: " .. (c..d)))) or "")
	end)
		:gsub(",", "/, /")
	return "/" .. tone_superscript(text) .. "/"
end

return export