Documentation for this module may be created at မဝ်ဂျူ:mn-IPA/doc

local export = {}
local gsub = mw.ustring.gsub
local u = mw.ustring.char

local consonants = {
	['б'] = 'p', ['б*'] = 'b', ['в'] = 'w̜', ['г'] = 'ɡ', ['г*'] = 'ɢ',
	['д'] = 't', ['д*'] = 'd', ['ж'] = 't͡ʃ', ['з'] = 't͡s', ['з*'] = 'z', ['й'] = 'j', ['к'] = 'kʰ',
	['л'] = 'ɮ', ['м'] = 'm', ['н'] = 'n', ['н*'] = 'ŋ', ['п'] = 'pʰ',
	['р'] = 'r', ['с'] = 's', ['т'] = 'tʰ', ['ф'] = 'f', ['х'] = 'x',
	['ц'] = 't͡s', ['ч'] = 't͡ʃʰ', ['ш'] = 'ʃ', ['щ'] = 'ʃt͡ʃ', ['ь'] = 'ʲ',
}

local vowels1 = {
	['а'] = 'a', ['е'] = 'e', ['и'] = 'i',
	['о'] = 'ɔ', ['ө'] = 'ɵ', ['ү'] = 'u',
	['у'] = 'ʊ', ['ъ'] = 'i', ['ы'] = 'i',
	['э'] = 'i', ['ю'] = 'jʊ',
	['я'] = 'ja', ['ё'] = 'jɔ', ['ә'] = 'ə',
}

local vowels2 = {
	['аа'] = 'aː', ['ай'] = 'ai', ['ее'] = 'eː',
	['ии'] = 'iː', ['ий'] = 'iː',
	['оо'] = 'ɔː', ['ой'] = 'ɔi', ['өө'] = 'oː',
	['үү'] = 'uː', ['үй'] = 'ui', ['уу'] = 'ʊː', ['уй'] = 'ʊi',
	['ээ'] = 'eː', ['юү'] = 'juː', ['юу'] = 'jʊː',
	['яа'] = 'jaː', ['ёо'] = 'jɔː',
}

function export.to_IPA(text)

	text = mw.ustring.lower(text)

	--primary stress
	-- U+0301 COMBINING ACUTE ACCENT, U+02C8 MODIFIER LETTER VERTICAL LINE

	text = gsub(text, "'", u(0x02C8)) -- can use apostrophe for convenience

	if not mw.ustring.match(text, u(0x02C8)) then
		if not mw.ustring.match(text, u(0x0301)) then
			text = u(0x02C8) .. text
		end
		text = gsub(text, '([аеиоөүуъыэюяёә%s%p%z])([аеиоөүуъыэюяёә])'..u(0x0301), '%1'..u(0x02C8)..'%2')
		text = gsub(text, '([бвгджзйклмнпрстфхцчшщь]%*?)([аеиоөүуъыэюяёә])'..u(0x0301), u(0x02C8)..'%1%2')
	end

	for k, v in pairs(vowels2) do
		text = gsub(text, k, v)
		text = gsub(text, k, v) --twice
	end
	for k, v in pairs(vowels1) do
		text = gsub(text, k, v)
	end

	text = gsub(text, '[бвгджзйклмнпрстфхцчшщь]%*?', consonants)

	text = gsub(text, 'n([%sˈ]*)%f[pbmf]', 'm%1')
	text = gsub(text, 'n%f[ɡɢkxʃ%s%p%z]', 'ŋ')

	text = gsub(text, '([aɔuʊ])i%f[%s%p%z]', '%1ⁱ')
	text = gsub(text, '[aeiɔɵuʊə]%f[%s%p%z]', '')
	text = gsub(text, 'ⁱ', 'i')

	text = gsub(text, 'ʲj', 'j')
	text = gsub(text, 'ʰʲ', 'ʲʰ')

	--put ~ at the end of respelling to prevent vowel cutoff
	text = gsub(text, '~', '')

	return text

end

-- only works with Cyrillic Mongolian
function export.show(frame)

	local args = frame:getParent().args
	local page_title = mw.title.getCurrentTitle().text
	local text = args[1] or page_title
	local qualifier = args['q'] or nil
	
	local transcription = export.to_IPA(text)
	local IPA_text = require('Module:IPA').format_IPA_full(
		require('Module:languages').getByCode('mn'),
		{ { pron = '/' .. transcription .. '/' } })

	return '* ' .. (qualifier and require("Module:qualifier").format_qualifier{qualifier} .. ' ' or '')
		.. IPA_text

end

return export