-- This module is for 陽江話 (Yangjiang Yue/Cantonese), a lect of Yue Chinese
-- Romanisation: Jyutping++ (referred to as jpp below)
-- References:
-- 1. 广东阳江话研究 (2016) by 冼文婷
-- Also see [[Category:Yangjiang Yue]]

local export = {}

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

-- Note: "e" and "ie" are not allophones; they are just placed in the same row for convenience
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="ɛ",ei="ei",ieu="iɛu",iem="iɛm",ien="iɛn",ieng="iɛŋ",iep="iɛp̚",iet="iɛt̚",iek="iɛk̚",
	o="ɔ", oi="ɔi", ou="ou",          on="ɔn", ong="ɔŋ",          ot="ɔt̚", ok="ɔk̚",
	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̚",
}

-- "5" merges into "2"
local tones = {
	["1"] = "³³", --陰平
	["2"] = "²¹", --上  /下陰入
	["3"] = "²⁴", --陰去/上陰入
	["4"] = "⁴²", --陽平/下陽入
	["6"] = "⁵⁵", --陽去/上陽入
}

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

function export.jpp_to_ipa(text)
	validate(text)
	text = text:gsub("[^ ,]+",function(syllable)
		local a,b,c = syllable:match("^([bpmfdtnlzcsgknhjw]?[lg]?)([aeiou]%l*)([12346])$")
		if not a then
			error("Yangjiang: Invalid syllable: " .. syllable)
		end
		return (initials[a] or error("Yangjiang: Unrecognised initial: " .. a))
			.. (finals[b] or error("Yangjiang: Unrecognised final: " .. b))
			.. tones[c]
	end)
		:gsub(",", "/, /")
	return "/" .. text .. "/"
end

return export