-- This module is for 南寧白話 (Nanning Yue/Cantonese), a lect of Yue Chinese
-- Not to be confused with 南寧平話 [[Module:csp-pron]]
-- Romanisation: Jyutping++ (referred to as jpp below)
-- References:
-- 1. 广西南宁白话研究 (2008) by 林亦, 覃凤余

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",
	gw = "kʷ", kw = "kʰʷ",
	j = "j",  w = "w",
	[""] = "", -- glottal stop?
}

-- 老派>新派: ɿ>i, yn>ɐn, yt>ɐt
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="ɛ",           eu="ɛu", em="ɛm", en="ɛn", eng="ɛŋ", ep="ɛp̚", et="ɛt̚", ek="ɛk̚",
	oe="œ",                                    oeng="œŋ",         oet="œt̚",oek="œk̚",
	o="ɔ",  oi="ɔi",                   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̚",
	yu="y",                           yun="yn",                    yt="yt̚",
	m="m̩",
	ng="ŋ̍",
}

local tones = {
	["1"] = "⁵⁵", --陰平
	["2"] = "³⁵", --陰上
	["3"] = "³³", --陰去
	["4"] = "²¹", --陽平
	["5"] = "²⁴", --陽上
	["6"] = "²²", --陽去
	-- internal use:
	["7"] = "⁵", --上陰入
	["8"] = "³", --下陰入
	["9"] = "²", --陽入
}

local entering_tones = {
	["1"] = "7", ["3"] = "8", ["6"] = "9"
}

local function validate(text)
	text = text:gsub(","," ")
	if text:sub(1,1) == " " or text:sub(-1,-1) == " " or text:match("  ") then
		error("Nanning: 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]?[lgw]?)([aeioumn]%l*)([123456])$")
		if not a then
			error("Nanning: Invalid syllable: " .. syllable)
		end
		if b:sub(-1,-1):match("^[ptk]") then
			c = entering_tones[c] or c
		end
		return (initials[a] or error("Nanning: Unrecognised initial: " .. a))
			.. (finals[b] or error("Nanning: Unrecognised final: " .. b))
			.. tones[c]
	end)
		:gsub(",", "/, /")
	return "/" .. text .. "/"
end

return export