local export = {}

local s = mw.ustring.gsub
local m = mw.ustring.match

local C = "[ʔbdɡχklmnpqrsʃtwjz]"
local V = "[aeiuāēīūâêîû]"
local c = {
	{"ṭ", "tˤ"},
	{"ṣ", "sˤ"},
	{"š", "ʃ"},
	{"y", "j"},
	{"g", "ɡ"},
	{"ḫ", "χ"},
	{"'", "ʔ"},
	{"(" .. V .. C .. "?ˤ?)(" .. C .. "ˤ?)%f" .. V, "%1.%2"}
}
local d = {
	{"[āâ]", "aː"},
	{"[ēê]", "eː"},
	{"[īî]", "iː"},
	{"[ūû]", "uː"}
} 
function export.pronunciation_phonemic(word)
    word = mw.ustring.lower(word)
	for a = 1, #c do
		word = s(word, c[a][1], c[a][2])
	end
	local N = {}
	local i = 0
	for a in string.gmatch(word, "%S+") do
		i = i+1
		N[i] = a
	end
	for a = 1, #N do
		if m(N[a], C .. "?ˤ?[âêîû]$") ~= nil then --last syllable is ultraheavy (circumflex)
			N[a] = s(N[a], "%.?(" .. C .. "?ˤ?[âêîû])$", "ˈ%1") --final stress

		elseif m(N[a], C .. "?ˤ?[āēīūâêîû]" .. C .. "ˤ?$") ~= nil then --again (any long V, + C)
			N[a] = s(N[a], "%.?(" .. C .. "?ˤ?[āēīūâêîû]" .. C .. "ˤ?)$", "ˈ%1") --final stress

		elseif m(s(N[a], C .. "ˤ?" .. V .. C .. "?ˤ?$", ""), C .. "?ˤ?" .. "[āēīūâêîû]%.") ~= nil or m(s(N[a], C .. "ˤ?" .. V .. C .. "?ˤ?$", ""), C .. "?ˤ?" .. "[aeiuāēīū]" .. C .. "ˤ?%.") ~= nil then --otherwise, detects if there is (not where it is) a non-final heavy or ultraheavy syllable (long V, or any non-circumflex + C)
			local n = ""
			for b = 1, 5 do --arbitrary, find how to count syllables
				N[a] = s(N[a], "%.?(" .. C .. "?ˤ?" .. "[āēīūâêîû]%." .. n .. C .. "ˤ?" .. V .. C .. "?ˤ?)$", "ˈ%1") --long V
				N[a] = s(s(N[a], "%.?(" .. C .. "?ˤ?" .. "[aeiuāēīū]" .. C .. "ˤ?%." .. n .. C .. "ˤ?" .. V .. C .. "?ˤ?)$", "ˈ%1"), "ˈˈ", "ˈ") --non-circumflex + C
				n = n .. C .. "ˤ?[aeiu]%." --+1 light syllable
			end

		else --no non-final heavy nor ultraheavy syllable detected, ie. there are only non-final light ones
			N[a] = s(N[a], "^( ?)(" .. C .. "?ˤ?[aeiu]%.)", "%1ˈ%2") --initial stress
		end

	end
	word = table.concat(N, " ")
	for a = 1, #d do
		word = s(word, d[a][1], d[a][2])
	end
	return word
end

function export.show(frame)
	local results = {}
	table.insert(results, {pron = "/" .. export.pronunciation_phonemic(mw.title.getCurrentTitle().text) .. "/"})
	local lang = require("Module:languages").getByCode("akk")
	return "* " .. require("Module:accent_qualifier").format_qualifiers(lang, {'[[w:Tiếng Akkad|Babylon cổ]]'}) .. " " .. require("Module:IPA").format_IPA_full { lang = lang, items = results }
end 
return export