local export = {}
local gsub = mw.ustring.gsub
local lower = mw.ustring.lower

local tab = {
	["a"]="ั", ["b"]="บ", ["c"]="ท͜ส", ["ĉ"]="ช", ["d"]="ด", ["e"]="↶เ",
	["f"]="ฟ", ["g"]="ก", ["ĝ"]="จ", ["h"]="ฮ", ["ĥ"]="ฅ", ["i"]="ิ",
	["j"]="ย", ["ĵ"]="ฌ", ["k"]="ค", ["l"]="ล", ["m"]="ม", ["n"]="น",
	["o"]="↶โ", ["p"]="พ", ["r"]="ร", ["s"]="ส", ["ŝ"]="ศ", ["t"]="ท",
	["u"]="ุ", ["ŭ"]="ว", ["v"]="ฝ", ["z"]="ซ", ["dz"]="ด͜ซ",
}

-- fix some diphthongs
local tab2 = {
	["ea"]="↶เอั", ["ei"]="↶เอิ", ["eo"]="↶เอ↶โ",
	["oa"]="↶โอั", ["oe"]="↶โอ↶เ", ["oi"]="↶โอิ",
}

function export.tr(text, lang, sc, debug_mode)

	if type(text) == "table" then -- called directly from a template
		text = text.args[1]
	end

	text = lower(text)
	text = gsub(text, "e[aio]", tab2)
	text = gsub(text, "o[aei]", tab2)
	text = gsub(text, "dz", tab)
	text = gsub(text, ".", tab)

	text = gsub(text, "^([ัิุ↶])", "อ%1")
	text = gsub(text, "([%s%p])([ัิุ↶])", "%1อ%2")
	text = gsub(text, "([ัิุ])([ัิุ↶])", "%1อ%2")

	--text = gsub(text, "ัว", "↶เา")
	text = gsub(text, "([ก-ฮ])↶([เโ])", "%2%1")

	text = gsub(text, "ั".."ั", "า")
	text = gsub(text, "ั$", "า")
	text = gsub(text, "ั([%s%p])", "า%1")

	text = gsub(text, "ิ".."ิ", "ี")
	text = gsub(text, "ิ$", "ี")
	text = gsub(text, "ิ([%s%p])", "ี%1")

	text = gsub(text, "ุ".."ุ", "ู")
	text = gsub(text, "ุ$", "ู")
	text = gsub(text, "ุ([%s%p])", "ู%1")

	text = gsub(text, "ั([ก-ฮ])([ัาิีุู])", "า%1%2")
	text = gsub(text, "ิ([ก-ฮ])([ัาิีุู])", "ี%1%2")
	text = gsub(text, "ุ([ก-ฮ])([ัาิีุู])", "ู%1%2")

	text = gsub(text, "ั([ก-ฮ])([ัาิีุู])", "า%1%2") --twice
	text = gsub(text, "ิ([ก-ฮ])([ัาิีุู])", "ี%1%2")
	text = gsub(text, "ุ([ก-ฮ])([ัาิีุู])", "ู%1%2")

	text = gsub(text, "ั([เโ])", "า%1")
	text = gsub(text, "ิ([เโ])", "ี%1")
	text = gsub(text, "ุ([เโ])", "ู%1")

	return text

end

return export