local export = {}

local IPA_modifier_apostrophe = mw.ustring.char(0x02BC)
local IPA_primary_stress = mw.ustring.char(0x02C8)
local IPA_secondary_stress = mw.ustring.char(0x02CC)
local IPA_tie_bar_top = mw.ustring.char(0x0361)
local IPA_tie_bar_below = mw.ustring.char(0x035C)
local IPA_modifier_triangular_colon = mw.ustring.char(0x2D0)

	-- List of the combining characters used in Lushootseed
local combining_caron = mw.ustring.char(0x30C) -- (Only used in x wedge)
local small_z = mw.ustring.char(0x1DBB) -- (Only used in d raised z)
local small_w = mw.ustring.char(0x2B7) -- (Used in all 'raised w' letters)
local comma_above = mw.ustring.char(0x313)
local comma_above_right = mw.ustring.char(0x315) -- (Used in glottalized L and glottalized barred lambda)

local small_turned_e = mw.ustring.char(0x01DD) -- schwa lookalike

local lut_to_IPA = {
	['\''] = IPA_primary_stress,
	[','] = IPA_secondary_stress,
	['.'] = '.',
	[':'] = IPA_modifier_triangular_colon,
	[comma_above] = IPA_modifier_apostrophe,
	[comma_above_right] = IPA_modifier_apostrophe,
	[small_w] = small_w,
	['a'] = 'ɑ',
	['ə'] = 'ə',
	[small_turned_e] = 'ə',
	['i'] = 'i',
	['u'] = 'u',
	['ʔ'] = 'ʔ',
	['b'] = 'b',
	['c'] = 't' .. IPA_tie_bar_top .. 's',
	['č'] = 't' .. IPA_tie_bar_top .. 'ʃ',
	['c' .. combining_caron] = 't' .. IPA_tie_bar_top .. 'ʃ',  -- č is preferred
	['d'] = 'd',
	['d' .. small_z] = 'd' .. IPA_tie_bar_top .. 'z',
	['g'] = 'ɡ',
	['h'] = 'h',
	['ǰ'] = 'd' .. IPA_tie_bar_top .. 'ʒ',
	['k'] = 'k',
	['l'] = 'l',
	['ɬ'] = 'ɬ',
	['ƛ'] = 't' .. IPA_tie_bar_top .. 'ɬ',
	['m'] = 'm',
	['n'] = 'n',
	['p'] = 'p',
	['q'] = 'q',
	['s'] = 's',
	['š'] = 'ʃ',
	['s' .. combining_caron] = 'ʃ',  -- š is preferred
	['t'] = 't',
	['w'] = 'w',
	['x'] = 'x',
	['x' .. combining_caron] = 'χ',
	['y'] = 'j'
}

-- Convert Lushootseed string into IPA
-- Also, convert apostrophe and comma into primary and secondary stress markers
local function convert_IPA(lut_string)
	
	local pattern = "[ʔaəiubcdqkcghǰlɬƛpsšcčtwxy',.:" .. comma_above .. 
		small_turned_e .. comma_above_right .. small_w .. 
		"][" .. combining_caron .. small_z .. "]?"
	
	local result = ""
	
	for letter in mw.ustring.gmatch(lut_string, pattern) do
		--result = result .. letter .. ' '
		result = result .. lut_to_IPA[letter]
	end
	return result
end

function export.lut_IPA( frame )
	local params = {
        [1] = {list = true, allow_holes = true}
    }

    local err = nil
    local args = frame:getParent().args
    local term = args[1]
    if not term then
    	term = mw.title.getCurrentTitle().text
    end
	
	local items = {}
	table.insert(items, { pron = '/' .. convert_IPA(term) .. '/'})
	
	local lang = require("Module:languages").getByCode("lut")
	mw.log(items['pron'])
	return require("Module:IPA").format_IPA_full { lang = lang, items = items }
end

return export