local export = {}
local m_IPA = require("Module:IPA")

local IPA_mapping = {
	["a"] = "a", ["ã"] = "ɜ̃", ["à"] = "ɜ", ["b"] = "b", ["c"] = "k",
	["e"] = "ɛ", ["ê"] = "e", ["ẽ"] = "ẽ", ["g"] = "ŋg", ["h"] = "h",
	["i"] = "i", ["ĩ"] = "ĩ", ["j"] = "j", ["k"] = "kʰ", ["m"] = "m",
	["n"] = "n", ["o"] = "ɔ", ["ô"] = "o", ["õ"] = "õ", ["p"] = "p",
	["qu"] = "k", ["r"] = "ɺ", ["t"] = "t", ["u"] = "u", ["ũ"] = "ũ",
	["w"] = "ʋ", ["x"] = "t͡ɕ", ["y"] = "ɨ", ["ỳ"] = "ɘ", ["ỹ"] = "ɨ"
}

function export.IPA_transcribe(text)
	return "/" .. mw.ustring.gsub(text, '.', IPA_mapping) .. "/"
end

function export.translate(text)
	if type(text) == "table" then
		text = text.args[1]
	end
	local pron = export.IPA_transcribe(text)
	
	lang = require("Module:languages").getByCode("ram")
	local items = {}
	table.insert(items, {pron = pron, note = nil})
	return m_IPA.format_IPA_full(lang, items)
end

function export.IPA(frame)
	local args = type(frame) == 'string' and { frame } or frame:getParent().args
	local result = {}
	
	if args['phon'] and args['phon'] ~= '' then
		args = { args['phon'] }
	end
	args = (not args[1]) and { mw.title.getCurrentTitle().text } or args

	for _, text in ipairs(args) do
		text = mw.ustring.lower(text)
	
		-- h before consonants
		text = gsub(text, 'h([khjmntɺʋ])', 'ʔ%1')
		
		-- r before consonants
		text = gsub(text, 'ɺ([khjmntɺʋ%s])', 'ɹ%1')
		
		-- nasalization after consonants
		text = gsub(text,"([mn][aeiouy])",{
		["a"] = "ã",
		["e"] = "ẽ",
		["i"] = "ĩ",
		["o"] = "õ",
		["u"] = "ũ",
		["y"] = "ɨ̃",
		})

		table.insert(result, '[' .. text .. ']')
	end
	
	table.insert(result, 1, "ram")
	if (type(frame) == 'string') then
		return mw.ustring.sub(result[1], 2, mw.ustring.len(result[1]) - 1)
	else
		return frame:expandTemplate{ title = "IPA", args = result}
	end

end

return export