local export = {}
local pos_functions = {}
local piqdstyle = "font-family: pIqaD, Constructium, 'Klingon pIqaD HaSta', Code2000, Horta, 'Unifont CSUR', 'Kurinto Text Aux', 'Kurinto Book Aux', 'Kurinto Sans Aux'"

-- If Not Empty
local function ine(arg)
	if arg == "" then
		return nil
	else
		return arg
	end
end

local function handle_infl(args, data, argpref, label)
	if args[argpref] and args[argpref..'2'] then
		local forms = {}
		local form = argpref
		local i = 1
		while args[form] do
			table.insert (forms, args[form])
			i = i + 1
			form = argpref..i
		end
		forms.label = mw.ustring.gsub(label, 'form', 'forms')
		table.insert(data.inflections, forms )
	elseif args[argpref] then
		table.insert(data.inflections, { label = label, args[argpref]})
	end
end

local lang = require("Module:languages").getByCode("tlh")
local script = require('Module:scripts').getByCode("Latn")
local PAGENAME = mw.ustring.gsub(mw.title.getCurrentTitle().text, '[^/]+/', '')
local piqdconv = require("Module:tlh-pIqaD")

function export.show(frame)

	local args = frame:getParent().args
	local poscat = frame.args[1] or error("Part of speech has not been specified. Please pass parameter 1 to the module invocation.")
	poscat = string.gsub(poscat, 'form', 'forms')
	local data = {lang = lang, sc = script, pos_category = poscat, categories = {}, heads = {args["head"] or PAGENAME}, inflections = {}, sort_key = args["sort"]}
	
	if poscat == 'nouns' and #frame.args[2] > 0 then
		local plur = frame.args[2]
		if plur == "pu'" or plur == "Du'" or plur == 'mey' then
			args['pl'] = data.heads[1] .. plur
			table.insert(data.categories, 'Klingon -' .. plur .. ' nouns')
		else
			args['pl'] = plur
			table.insert(data.categories, 'Klingon nouns with irregular plurals')
		end
	end
	
	if args["cat2"] then
		table.insert(data.categories, "Klingon " .. args["cat2"])
	end
	if args["cat3"] then
		table.insert(data.categories, "Klingon " .. args["cat3"])
	end
	
	handle_infl(args, data, "stem", "stem")
	
	if pos_functions[poscat] then
		pos_functions[poscat](args, data)
	end
	
	local phon = args["head"] or PAGENAME -- detects only first one
	local piqd = piqdconv.convert(phon)
	data.heads[1] =  data.heads[1]..' • <span style="'..piqdstyle..'">'..piqd..'</span>'
	
	return require("Module:headword").full_headword(data)
end

pos_functions["adjectives"] = function(args, data)
	handle_infl(args, data, "pl", "plural")
end

pos_functions["nouns"] = function(args, data)
	handle_infl(args, data, "pl", "plural")
end

pos_functions["verbs"] = function(args, data)
	handle_infl(args, data, "past", "past tense")
end

pos_functions["proper nouns"] = pos_functions["nouns"]

return export