local export = {}

local lang = require("Module:languages").getByCode("new")
local sc = require("Module:scripts").getByCode("Deva")
local m_IPA = require("Module:IPA")

local gsub = mw.ustring.gsub
local gmatch = mw.ustring.gmatch
local find = mw.ustring.find

local correspondences = {
	["ṅ"] = "ŋ", ["g"] = "ɡ", 
    ["c"] = "t͡ɕ", ["j"] = "d͡ʑ", ["ċ"] = "t͡ɕ", ["ñ"] = "n",
	["ṭ"] = "ʈ", ["ḍ"] = "ɖ", ["ṇ"] = "n",
	["t"] = "t", ["d"] = "d",
	["y"] = "j", ["v"] = "w",  ["l"] = "l",
	["ś"] = "s", ["ṣ"] = "s", ["h"] = "h",
	["n"] = "n", ["r̥"] = "ri", ["ṃ"] = "̃", ["m̐"] = "̃", ["ॽ"] = "", [","] = ",", ["r"] = "ɾ", ["r̥̄"] = "ɾiː", ["l̥"] = "lri",
 ["l̥̄"] = "lriː",
	["a"] = "ə", ["ā"] = "a", ["i"] = "i",
	["ī"] = "iː", ["o"] = "o", ["e"] = "e",
	["u"] = "u", ["ū"] = "uː", ["ai"] = "əi", ["au"] = "əu", ["ô"] = "ɔ", ["ê"] = "ɛː", ["ã"] = "ə̃",["ā̃"] = "ã", ["ĩ"] = "ĩ",
	["ī̃"] = "ĩː", ["õ"] = "õ", ["ẽ"] = "ẽ",
	["ũ"] = "ũ", ["ū̃"] = "ũː", ["ỗ"] = "ɔ̃", ["ễ"] = "ɛ̃ː", ["â"] = "æː", ["ẫ"] = "æ̃ː", ["æ"] = "æː", ["æ̃"] = "æ̃ː",  ["ɛ"] = "ɛː", ["ɛ̃"] = "ɛ̃ː",

	["ː"] = "ː", [":"] = "ː", [" "] = " ", ["ऽ"] = " ", ["ḥ"] = "ː", 
}

local vowels = "aāā̃ẽõiīuūeī̃ū̃:ḥĩoə̃ːəãũɛêâæŏĕ̤"
local weak_h_c = "gjdḍdṇɽblmɾnṛvrṝḹḷṟwy"
local primary_stress = "ˈ"
local secondary_stress = "ˌ"
local weak_h = "([" .. weak_h_c .. "])h"
local aspirate = "([kctṭtp])"
local syllabify_pattern = "([" .. vowels .. "]+)([^" .. vowels .. "%.]+)([" .. vowels .."]+)"

local function find_consonants(text)
	local current = ""
	local cons = {}
	for cc in mw.ustring.gcodepoint(text .. " ") do
		local ch = mw.ustring.char(cc)
		if find(current .. ch, "^[kgṅcjñṭḍṇɽtdnpbmɽ̃yrlɳwvɾjwśṣshqxġzžḻṛṟfθðṉ]$") or find(current .. ch, "^[kgcjṭḍṇtɽdɽ̃pbṛṟ]h$") then
			current = current .. ch
		else
			table.insert(cons, current)
			current = ch
		end
	end
	return cons
end

local function syllabify(text)
	for count = 1, 2 do
		text = gsub(text, syllabify_pattern, function(a, b, c)
			b_set = find_consonants(b)
			table.insert(b_set, #b_set > 1 and 2 or 1, "")
			return a .. table.concat(b_set) .. c
			end)
end
return text
end


local identical = "knlsfzθð"
for character in gmatch(identical, ".") do
	correspondences[character] = character
end

local function transliterate(text)
	--return (lang:transliterate(text))
	return lang:transliterate(text, nil, "new-translit-Latn")
end

function export.link(term)
	return require("Module:links").full_link{ term = term, lang = lang, sc = sc }
end

function export.toIPA(text, phonetic)
	local translit = transliterate(text)
	if not translit then
		error('The term "' .. Newar .. '" could not be transliterated.')
	end

	if phonetic then
	end
	local result = gsub(translit, ".", correspondences)
		
	
	translit = gsub(translit, "͠", "̃")
	translit = gsub(translit, "m̐", "̃")
    translit = gsub(translit, "([aāiu])ṃ", "%1̃ː")
	translit = gsub(translit, "oṃ", "oːm")
	translit = gsub(translit, "%-", ".")
    translit = gsub(translit, "r̥", "ɾi")
    translit = gsub(translit, '([aäāeēoôêæiīuūr̥])kṣ', '%1k̚t͡ɕʰy')
    translit = gsub(translit, '()kṣ', 't͡ɕʰ') 
    --translit = gsub(translit, "āy([grbtṭdmncjvwṇṅśṣɳslkp]?)", "æː%1")
--translit = gsub(translit, "ay([grbtṭdmncjvwṇṅśṣɳslkp]?)", "ɛː%1")
--translit = gsub(translit, "ā̃y([grbtṭdmncjvwṇṅśṣɳslkp]?)", "æ̃ː%1")
--translit = gsub(translit, "ãy([grbtṭdmncjvwṇṅśṣɳslkp]?)", "ɛ̃ː%1")
translit = gsub(translit, "([grbtṭdmncjvwṇṅśṣɳslkp]?)wa", "%1wɔ")
translit = gsub(translit, "([grbtṭdmncjvwṇṅśṣɳslkp]?)wã", "%1wɔ̃")
	translit = syllabify(translit)
	
	
	-- aspiration rules
	translit = gsub(translit, aspirate .. "h", '%1ʰ')
	translit = gsub(translit, weak_h, '%1ʱ')
	translit = gsub(translit, '([' .. weak_h_c .. '])%.h', '.%1ʱ')
	translit = gsub(translit, aspirate .. '%.h', '.%1ʰ')
        translit = gsub(translit, "%.ː", "ː.")

	local result = gsub(translit, ".", correspondences)
	
	-- formatting
	result = gsub(result, "ː̃", "̃ː")
	result = gsub(result, "ː.̃", "̃ː.")
    result = gsub(result, "ːː", "ː")
	result = gsub(result, "%. ", " ")
    result = gsub(result, "%.$", " ")
    result = gsub(result, "%.?%-", ".")
	result = gsub(result, "ː%.̃", "̃ː.")

	return result
end

function export.make(frame)
	local args = frame:getParent().args
	local pagetitle = mw.title.getCurrentTitle().text
	
	local p, results = {}, {}
	
	if args[1] then
		for index, item in ipairs(args) do
			table.insert(p, (item ~= "") and item or nil)
		end
	else
		p = { pagetitle }
	end
	
	for _, Newar in ipairs(p) do
		table.insert(results, { pron = "[" .. export.toIPA(Newar) .. "]" })
		if export.toIPA(Newar, true) ~= export.toIPA(Newar) then
			table.insert(results, { pron = "[" .. export.toIPA(Newar, true) .. "]" })
		end
	end
	
	return m_IPA.format_IPA_full { lang = lang, items = results }
end

return export