local export = {}

local titleObj = mw.title.getCurrentTitle()
local pagename = titleObj.text
local namespace = titleObj.nsText

local find = mw.ustring.find
local length = mw.ustring.len
local trim = mw.text.trim
local split = mw.text.split
local sub, gsub = mw.ustring.sub, mw.ustring.gsub
local match, gmatch = mw.ustring.match, mw.ustring.gmatch
local to_cp, to_char = mw.ustring.codepoint, mw.ustring.char

local m_ja = require("Module:ja")
local Jpan = require("Module:scripts").getByCode("Jpan")
local lang = require("Module:languages").getByCode("ja")

-- note that arrays loaded by mw.loadData cannot be directly used by gsub
local data = mw.loadData("Module:ja/data")

function export.new(frame, _args) -- _args is used when called from other Lua code
	
	local args = _args or frame:getParent().args
	
	local pos_table_convert = {
		["s"] = { "n", "vsuru" },
		["suru"] = { "n", "vsuru" },
		["an"] = { "a", "n" },
		["anoun"] = { "a", "n" },
		["as"] = { "adv", "vsuru" },
	}

	local pos_table = {
		["n/noun/"] = { "คำนาม", "noun" },  
		["v/verb"] = { "คำกริยา", "verb" },  
		["vs/vsuru/verb suru"] = { "คำกริยา", "verb-suru" },
		["vform/verb form"] = { "คำกริยา", "verb form" },
		["a/adj/adjective"] = { "คำคุณศัพท์", "adj" },
		["adv/adverb"] = { "คำกริยาวิเศษณ์", "pos|adverb" },
		["pron/pronoun"] = { "คำสรรพนาม", "pos|pronoun" },
		["pn/propn/proper/proper noun"] = { "คำวิสามานยนาม", "pos|proper" },
		["ph/phrase"] = { "วลี", "phrase" },
		["intj/interjection"] = { "คำอุทาน", "pos|interjection" },
		["conj"] = { "คำสันธาน", "pos|conjunction" },
		["part"] = { "คำอนุภาค", "pos|particle" },
		["prep"] = { "คำบุพบท", "pos|preposition" },
		["suf/suffix"] = { "ปัจจัย", "pos|suffix" },
		["pref/prefix"] = { "อุปสรรค", "pos|prefix" },
		["affix"] = { "หน่วยคำเติม", "pos|affix" },
		["prov"] = { "สุภาษิต", "pos|proverb" },
		["id/idiom"] = { "สำนวน", "pos|idiom" },
		["adn/adnominal"] = { "คำคุณนาม", "pos|adnominal" },
	}
	local _pos_table = pos_table; pos_table = {}
	for k, v in pairs(_pos_table) do for i in mw.text.gsplit(k, "/") do pos_table[i] = v end end
	
	local function waapuro_r_to_kana(text)
		return require("Module:typing-aids").replace{"ja", text}
	end

	local result = args["en"] and ("=== รากศัพท์ " .. args["en"] .. " ===") or "== ภาษาญี่ปุ่น =="
	local hf = args["en"] and "=" or ""

	if args["defs"] then
		result = result .. "\n{{DEFAULTSORT:" .. args["defs"] .. "}}"
	end
	if args["wp"] then
		result = result .. "\n{{wp|lang=ja" .. (args["wp"] ~= "y" and "|" .. args["wp"] or "") .. "}}"
	end
	wp_count = 2
	while args["wp" .. wp_count] do
		result = result .. "\n{{wp|lang=ja|" .. args["wp" .. wp_count] .. "}}"
		wp_count = wp_count + 1
	end

	if args["swp"] then
		result = result .. "\n{{swp|lang=ja" .. (args["swp"] ~= "y" and "|" .. args["swp"] or "") .. "}}"
	end
	swp_count = 2
	while args["swp" .. swp_count] do
		result = result .. "\n{{swp|lang=ja|" .. args["swp" .. swp_count] .. "}}"
		swp_count = swp_count + 1
	end

	text = args[1] ~= "" and args[1] or pagename
	text = gsub(text, "%-", "|")
	text = waapuro_r_to_kana(text)

	local function make_tab(original, yomi)
		output_text = ""
		original = gsub(original, " ", "|")
		original = gsub(original, "%.", "|")
		original = gsub(original, "%^", "")
		if find(original, "<") then
			for word in gmatch(original, "<([^>]+)>") do
				output_text = output_text .. "|" .. word
			end
			yomi = yomi or "k"
		else
			output_text = gsub(original, ">([1-9])", "|k%1=")
			output_text = find(output_text, "|") and "|" .. output_text or false
		end
		yomi = yomi or (find(original, "%|") and "o") or "n"
		return "\n{{ja-kanjitab" ..
			(output_text or "") ..
			(yomi == "n" and "" or "|yomi=" .. yomi) ..
			(args["sork"] and "|sort=" .. args["sork"] or sortkey or "") ..
			(args["r"] and "|r=" .. args["r"] or "") ..
			(args["kyu"] and "|kyu=" .. args["kyu"] or "") ..
			(args["kalt"] and "|alt=" .. args["kalt"] or "") .. "}}", yomi
	end

	if find(pagename, "[一-鿿㐀-䶿﨎﨏﨑﨓﨔﨟﨡﨣﨤﨧-﨩𠀀-𪛟𪜀-𮯯𰀀-𱍏]") or args["kalt"] then
		to_add, yomi = make_tab(text, args["yomi"])
		result = result .. to_add
	end

	if find(text, "<") then
		text = gsub(text, "[<>]", "")
	else
		text = gsub(text, "^[^>|]+>%d+([^>|]+)", "%1")
		text = gsub(text, "|[^>|]+>%d+([^>|]+)", "%1")
		text = gsub(text, "([あかがさざただなはばぱまやらわ])|(あ)", "%1.%2")
		text = gsub(text, "([いきぎしじちぢにひびぴみり])|(い)", "%1.%2")
		text = gsub(text, "([うくぐすずつづぬふむゆる])|(う)", "%1.%2")
		text = gsub(text, "([えけげせぜてでねへめれ])|([えい])", "%1.%2")
		text = gsub(text, "([おこごそぞとどのほぼぽもよろ])|([おう])", "%1.%2")
		text = gsub(text, "|", "")
	end

	if args["wpd"] then
		result = result .. "\n{{swp|lang=ja" .. (args["wpd"] ~= "y" and "|" .. args["wpd"] or "") .. "}}"
	end
	wpd_count = 2
	while args["wpd" .. wpd_count] do
		result = result .. "\n{{swp|lang=ja|" .. args["wpd" .. wpd_count] .. "}}"
		wpd_count = wpd_count + 1
	end

	if args["pic"] then
		result = result .. args["pic"]
	end
	pic_count = 2
	while args["pic" .. pic_count] do
		result = result .. args["pic" .. pic_count]
		swp_count = pic_count + 1
	end

	local function other(class, title, args)
		local code, i = "", 2

		if args[class] then
			code = code .. "\n\n===" .. hf .. title .. hf .. "===\n* {{ja-l|" .. args[class] .. "}}"

			while args[class .. i] do
				code = code .. "\n* {{ja-l|" .. args[class .. i] .. "}}"
				i = i + 1
			end
		end

		code = gsub(code, "{{ja%-l\|([^%|%}]+)[::]", "{{ja-r|%1|") -- change something like "{{ja-l|辞典:じてん}}" to "{{ja-r|辞典|じてん}}"
		code = gsub(code, "{{ja%-l\|([ぁ-ー ^%%.]+)}}", "{{ja-r|%1}}") -- change something like "{{ja-l|じてん}}" to "{{ja-r|じてん}}"

		return code
	end

	result = result .. other("alt", "Alternative forms", args)

	sortkey = m_ja.script(text) == "Kana" and m_ja.sort(text) or false
	if sortkey and sortkey == "|sort=" .. text then
		sortkey = false
	end

	if args["d"] or args["e"] or args["we1"] or args["yo1"] or args["b"] or args["lb"] or args["c"] or args["co1"] or args["bl1"] or args["pr1"] or args["su1"] then
		result = result .. "\n\n"
		if not args["en"] then result = result .. hf .. "=== รากศัพท์ ===" .. hf .. "\n" end
		if args["we1"] then
			result = result .. "{{waei|" .. args["we1"] .. "|" .. args["we2"]
			we_count = 3
			while args["we" .. we_count] do
				result = result .. "|" .. args["we" .. we_count]
				we_count = we_count + 1
			end
			result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			if args["c"] then
				result = result .. ", {{cal|ja|nocap=y|" .. (args["cl"] or "en") .. (args["c"] and "|" .. args["c"] or "") .. (args["tr"] and "|tr=" .. args["tr"] or "") .. (args["t"] and "||" .. args["t"] or "") .. (args["lit"] and "|lit=" .. args["lit"] or "") .. (args["pos"] and "|pos=" .. args["pos"] or "") .. (args["g"] and "|g=" .. args["g"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			end
			if args["pr1"] then
				result = result .. ", equivalent to {{pre|ja|" .. args["pr1"] .. "|" .. args["pr2"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "") .. (args["presort"] and "|sort=" .. args["presort"] or "") .. "}}"
			elseif args["su1"] then
				result = result .. ", equivalent to {{suf|ja|" .. args["su1"] .. "|" .. args["su2"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			elseif args["co1"] then
				result = result .. ", equivalent to {{af|ja|" .. args["co1"] .. (args["alt1"] and "|alt1=" .. args["alt1"] or "") .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. "|" .. args["co2"] .. (args["alt2"] and "|alt2=" .. args["alt2"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "")
				co_count = 3
				while args["co" .. co_count] do
					result = result .. "|" .. args["co" .. co_count] .. (args["alt" .. co_count] and "|alt" .. co_count .. "=" .. args["alt" .. co_count] or "") .. (args["tr" .. co_count] and "|tr" .. co_count .. "=" .. args["tr" .. co_count] or "") .. (args["pos" .. co_count] and "|pos" .. co_count .. "=" .. args["pos" .. co_count] or "") .. (args["t" .. co_count] and "|t" .. co_count .. "=" .. args["t" .. co_count] or "")
					co_count = co_count + 1
				end
				result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			elseif args["bl1"] then
				result = result .. ", equivalent to a {{blend|ja|nocap=y|" .. args["bl1"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. "|" .. args["bl2"] .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "")
				bl_count = 3
				while args["bl" .. bl_count] do
					result = result .. "|" .. args["bl" .. bl_count] .. (args["tr" .. bl_count] and "|tr" .. bl_count .. "=" .. args["tr" .. bl_count] or "") .. (args["pos" .. bl_count] and "|pos" .. bl_count .. "=" .. args["pos" .. bl_count] or "") .. (args["t" .. bl_count] and "|t" .. bl_count .. "=" .. args["t" .. bl_count] or "")
					bl_count = bl_count + 1
				end
				result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			end
		elseif args["yo1"] then
			result = result .. "{{yoji|" .. args["yo1"] .. "|" .. args["yo2"] .. (args["yo3"] and "|" .. args["yo3"] or "") .. (args["yo4"] and "|" .. args["yo4"] or "") .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["tr3"] and "|tr3=" .. args["tr3"] or "") .. (args["tr4"] and "|tr4=" .. args["tr4"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["pos3"] and "|pos3=" .. args["pos3"] or "") .. (args["pos4"] and "|pos4=" .. args["pos4"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "") .. (args["t3"] and "|t3=" .. args["t3"] or "") .. (args["t4"] and "|t4=" .. args["t4"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
		elseif args["c"] then
			result = result .. "{{cal|ja|" .. (args["cl"] or "en") .. (args["c"] and "|" .. args["c"] or "") .. (args["tr"] and "|tr=" .. args["tr"] or "") .. (args["t"] and "||" .. args["t"] or "") .. (args["lit"] and "|lit=" .. args["lit"] or "") .. (args["pos"] and "|pos=" .. args["pos"] or "") .. (args["g"] and "|g=" .. args["g"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			if args["pr1"] then
				result = result .. ", equivalent to {{pre|ja|" .. args["pr1"] .. "|" .. args["pr2"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "") .. (args["presort"] and "|sort=" .. args["presort"] or "") .. "}}"
			elseif args["su1"] then
				result = result .. ", equivalent to {{suf|ja|" .. args["su1"] .. "|" .. args["su2"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			elseif args["co1"] then
				result = result .. ", equivalent to {{af|ja|" .. args["co1"] .. (args["alt1"] and "|alt1=" .. args["alt1"] or "") .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. "|" .. args["co2"] .. (args["alt2"] and "|alt2=" .. args["alt2"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "")
				co_count = 3
				while args["co" .. co_count] do
					result = result .. "|" .. args["co" .. co_count] .. (args["alt" .. co_count] and "|alt" .. co_count .. "=" .. args["alt" .. co_count] or "") .. (args["tr" .. co_count] and "|tr" .. co_count .. "=" .. args["tr" .. co_count] or "") .. (args["pos" .. co_count] and "|pos" .. co_count .. "=" .. args["pos" .. co_count] or "") .. (args["t" .. co_count] and "|t" .. co_count .. "=" .. args["t" .. co_count] or "")
					co_count = co_count + 1
				end
				result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			elseif args["bl1"] then
				result = result .. ", equivalent to a {{blend|ja|nocap=y|" .. args["bl1"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. "|" .. args["bl2"] .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "")
				bl_count = 3
				while args["bl" .. bl_count] do
					result = result .. "|" .. args["bl" .. bl_count] .. (args["tr" .. bl_count] and "|tr" .. bl_count .. "=" .. args["tr" .. bl_count] or "") .. (args["pos" .. bl_count] and "|pos" .. bl_count .. "=" .. args["pos" .. bl_count] or "") .. (args["t" .. bl_count] and "|t" .. bl_count .. "=" .. args["t" .. bl_count] or "")
					bl_count = bl_count + 1
				end
				result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
			end
		elseif args["pr1"] then
			result = result .. "From {{pre|ja|" .. args["pr1"] .. "|" .. args["pr2"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "") .. (args["presort"] and "|sort=" .. args["presort"] or "") .. "}}"
		elseif args["su1"] then
			result = result .. "From {{suf|ja|" .. args["su1"] .. "|" .. args["su2"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
		elseif args["co1"] then
			result = result .. "From {{af|ja|" .. args["co1"] .. (args["alt1"] and "|alt1=" .. args["alt1"] or "") .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. "|" .. args["co2"] .. (args["alt2"] and "|alt2=" .. args["alt2"] or "") .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "")
			co_count = 3
			while args["co" .. co_count] do
				result = result .. "|" .. args["co" .. co_count] .. (args["alt" .. co_count] and "|alt" .. co_count .. "=" .. args["alt" .. co_count] or "") .. (args["tr" .. co_count] and "|tr" .. co_count .. "=" .. args["tr" .. co_count] or "") .. (args["pos" .. co_count] and "|pos" .. co_count .. "=" .. args["pos" .. co_count] or "") .. (args["t" .. co_count] and "|t" .. co_count .. "=" .. args["t" .. co_count] or "")
				co_count = co_count + 1
			end
			result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
		elseif args["bl1"] then
			result = result .. "{{blend|ja|" .. args["bl1"] .. (args["tr1"] and "|tr1=" .. args["tr1"] or "") .. (args["pos1"] and "|pos1=" .. args["pos1"] or "") .. (args["t1"] and "|t1=" .. args["t1"] or "") .. "|" .. args["bl2"] .. (args["tr2"] and "|tr2=" .. args["tr2"] or "") .. (args["pos2"] and "|pos2=" .. args["pos2"] or "") .. (args["t2"] and "|t2=" .. args["t2"] or "")
			bl_count = 3
			while args["bl" .. bl_count] do
				result = result .. "|" .. args["bl" .. bl_count] .. (args["tr" .. bl_count] and "|tr" .. bl_count .. "=" .. args["tr" .. bl_count] or "") .. (args["pos" .. bl_count] and "|pos" .. bl_count .. "=" .. args["pos" .. bl_count] or "") .. (args["t" .. bl_count] and "|t" .. bl_count .. "=" .. args["t" .. bl_count] or "")
				bl_count = bl_count + 1
			end
			result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
		elseif args["b"] then
			result = result .. "From {{bor|ja|" .. (args["bl"] or "en") .. (args["b"] and "|" .. args["b"] or "") .. (args["tr"] and "|tr=" .. args["tr"] or "") .. (args["t"] and "||" .. args["t"] or "") .. (args["lit"] and "|lit=" .. args["lit"] or "") .. (args["pos"] and "|pos=" .. args["pos"] or "") .. (args["g"] and "|g=" .. args["g"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
		elseif args["lb"] then
			result = result .. "{{lbor|ja|" .. (args["lbl"] or "grc") .. (args["lb"] and "|" .. args["lb"] or "") .. (args["tr"] and "|tr=" .. args["tr"] or "") .. (args["t"] and "||" .. args["t"] or "") .. (args["lit"] and "|lit=" .. args["lit"] or "") .. (args["pos"] and "|pos=" .. args["pos"] or "") .. (args["g"] and "|g=" .. args["g"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
		else
			result = result .. (args["e"] or
				("From {{der|ja|" .. (args["dl"] or "en") .. (args["d"] and "|" .. args["d"] or "") .. (args["tr"] and "|tr=" .. args["tr"] or "") .. (args["t"] and "||" .. args["t"] or "") .. (args["lit"] and "|lit=" .. args["lit"] or "") .. (args["pos"] and "|pos=" .. args["pos"] or "") .. (args["g"] and "|g=" .. args["g"] or "") .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"))
		end
		result = result .. (args["e_ref"] and args["e_ref"] or "")
	end

	if not args["nop"] then
		result = result .. "\n\n" .. hf .. "=== การออกเสียง ===" .. hf .. "\n{{ja-pron" .. (args[1] ~= "" and "|" .. gsub(text, '%^', '') or "")
		result = result .. (args["acc"] and "|acc=" .. args["acc"] or "") .. (args["acc_ref"] and "|acc_ref=" .. args["acc_ref"] or "")
		acc_count = 2
		while args["acc" .. acc_count] do
			result = result .. "|acc" .. acc_count .. "=" .. args["acc" .. acc_count] .. (args["acc" .. acc_count .. "_ref"] and "|acc" .. acc_count .. "_ref=" .. args["acc" .. acc_count .. "_ref"] or "")
			acc_count = acc_count + 1
		end
		result = result .. (args["dev"] and "|dev=" .. args["dev"] or "") .. (args["devm"] and "|devm=" .. args["devm"] or "") .. "}}"
		if args["hmp"] then
			if yomi and not (yomi == "n" or y == "n") then
				result = result .. "\n** "
			else
				result = result .. "\n* "
			end
			result = result .. (args["hmp"] and "{{hmp|ja|" .. args["hmp"] or "")
			hmp_count = 2
			while args["hmp" .. hmp_count] do
				result = result .. "|" .. args["hmp" .. hmp_count]
				hmp_count = hmp_count + 1
			end
			result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
		end
	end
	
	if not args["hh"] then args["hh"] = args["hhira"] end
	if not args["hk"] then args["hk"] = args["hkata"] end
	if not args["tran"] then args["tran"] = args["trans"] end
	if not args["cnt"] then args["cnt"] = args["count"] end
	if args["eg"] then
		args[3] = args[3] .. "\n#" .. args["eg"]
	end
	local eg_count = 2
	while args["eg" .. eg_count] do
		args[3] = args[3] .. "\n#" .. args["eg" .. eg_count]
		eg_count = eg_count + 1
	end
	
	-- by this time the unnamed args should be either
	-- {{subst:ja-new|<kana>|<first POS>|<first def>|<second POS>|<second def>|...}} or
	-- {{subst:ja-new|<kana>|<first and second POS>|<first def>|<second def>}}
	-- our task here is to convert the second format to the first
	
	if pos_table_convert[args[2]] then
		if args[5] then error("use the simpler POS codes, for example change \"suru|def1|def2\" to \"n|def1|vsuru|def2\"") end
		args[2], args[3], args[4], args[5] = pos_table_convert[args[2]][1], args[3], pos_table_convert[args[2]][2], args[4]
	end
	
	local function add_pos(header, template_name, def)
		result = result .. "\n\n" .. hf .. "===" .. header .. "===" .. hf .. "\n{{ja-" .. template_name ..
			(args[1] ~= "" and "|" .. text or "") ..
			(args["head"] and "|head=" .. args["head"] or "") ..
			(template_name == "noun" and args["cnt"] and "|count=" .. args["count"] or "") ..
			(args["sin"] and "|shin=" .. args["sin"] or "") ..
			(args["ak"] and "|" .. waapuro_r_to_kana(args["ak"]) or "") ..
			(args["ak2"] and "|" .. waapuro_r_to_kana(args["ak2"]) or "") ..
			(args["ak3"] and "|" .. waapuro_r_to_kana(args["ak3"]) or "") .. -- TODO: ak
			(args["rom"] and "|rom=" .. args["rom"] or "") ..
			(args["hh"] and "|hhira=" .. waapuro_r_to_kana(args["hh"]) or "") ..
			(args["hk"] and "|hkata=" .. waapuro_r_to_kana(args["hk"]) or "")

		if header == "คำคุณศัพท์" then
			result = result .. "|infl=" .. (args["infl"] and args["infl"] or "na")
		end

		if template_name == "verb" then result = result .. (args["type"] and "|type=" .. args["type"] or "") end
		if template_name == "verb" or template_name == "verb-suru" then result = result .. (args["tran"] and "|tr=" .. args["tran"] or "") end
		result = result .. "}}"
		
		result = result .. "\n\n# " .. (def or "{{rfdef|ja}}")

		if header == "คำคุณศัพท์" then
			result = result .. "\n\n" .. hf .. "==== การผันรูป ====" .. hf .. "\n"
			if args["infl"] == "i" or args["infl"] == "い" then
				result = result .. "{{ja-i" .. (args[1] ~= "" and "|" .. sub(text, 1, -2) or "") .. "}}"
			elseif not args["infl"] or args["infl"] == "na" or args["infl"] == "な" then
				result = result .. "{{ja-na" .. (args[1] ~= "" and "|" .. text or "") .. "}}"
			end
		end

		if template_name == "verb" then
			result = result .. "\n\n" .. hf .. "==== การผันรูป ====" .. hf .. "\n{{ja-"
			penul, cons = text, text
			penul, cons = sub(penul, -2, -2), sub(cons, -1, -1)
			penul, cons = m_ja.hira_to_kata(penul), m_ja.hira_to_kata(cons)
			penul, cons = gsub(penul, ".", data.kr), gsub(cons, ".", data.kr)
			penul, cons = sub(penul, -1, -1), sub(cons, 1, 1)
			if cons == "u" then
				cons = ""
			elseif cons == "c" then
				cons = "ts"
			end
			if args["type"] == "2" then
				result = result .. "ichi"
			else
				result = result .. "go-" .. cons .. "u"
			end
	
			result = result .. (args[1] ~= "" and "|" .. sub(text, 1, -2) or "") .. "}}"
		end
		
		if template_name == "verb-suru" then
			result = result .. "\n\n" .. hf .. "==== การผันรูป ====" .. hf .. "\n{{ja-suru" .. (args[1] ~= "" and "|" .. text or "") .. "}}"
		end
	end
	
	if not pos_table[args[2]] then error("The POS code " .. args[2] .. " is not valid. See [[Module:ja-new]] for a list of valid POS.") end
	add_pos(pos_table[args[2]][1], pos_table[args[2]][2], args[3])
	if args["use"] then
		result = result .. "\n\n" .. hf .. "==== การใช้ ====" .. hf .. "\n* " .. args["use"]
	end
	result = result .. other("syn", "= คำพ้องความ =", args)
	result = result .. other("ant", "= คำตรงข้าม =", args)
	result = result .. other("der", "= คำประสม =", args)
	result = result .. other("rel", "= คำเกี่ยวข้อง =", args)
	
	if args[4] then
		if not pos_table[args[4]] then error("The POS code " .. args[4] .. " is not valid. See [[Module:ja-new]] for a list of valid POS.") end
		add_pos(pos_table[args[4]][1], pos_table[args[4]][2], args[5])
		if args["Use"] then
			result = result .. "\n\n" .. hf .. "==== การใช้ ====" .. hf .. "\n* " .. args["Use"]
		end
		result = result .. other("Syn", "= คำพ้องความ =", args)
		result = result .. other("Ant", "= คำตรงข้าม =", args)
		result = result .. other("Der", "= คำประสม =", args)
		result = result .. other("Rel", "= คำเกี่ยวข้อง =", args)
	end
	
	if args[6] then
		if not pos_table[args[6]] then error("The POS code " .. args[6] .. " is not valid. See [[Module:ja-new]] for a list of valid POS.") end
		add_pos(pos_table[args[6]][1], pos_table[args[6]][2], args[7])
		if args["USE"] then
			result = result .. "\n\n" .. hf .. "==== การใช้ ====" .. hf .. "\n* " .. args["Use"]
		end
		result = result .. other("SYN", "= คำพ้องความ =", args)
		result = result .. other("ANT", "= คำตรงข้าม =", args)
		result = result .. other("DER", "= คำประสม =", args)
		result = result .. other("REL", "= คำเกี่ยวข้อง =", args)
	end
	
	if args[8] then error("this template only supports up to three POS, please ask someone to expand me") end

	if args["dzh"] or args["den"] or args["dko"] or args["dvi"] then
		result = result .. "\n\n" .. hf .. "=== คำสืบทอด ===" .. hf .. "\n" .. (args["dzh"] and "* {{desc|zh|" .. args["dzh"] .. (args["dzhb"] and "|bor=y" or "") .. (args["dzhd"] and "|der=y" or "") .. (args["dzhc"] and "|clq=y" or "") .. "}}" or "")
		if args["dzh"] then
			if args["den"] or args["dko"] or args["dvi"] then
				result = result .. "\n"
			end
		end
		result = result .. (args["den"] and "* {{desc|en|" .. args["den"] .. (args["denb"] and "|bor=y" or "") .. (args["dend"] and "|der=y" or "") .. (args["denc"] and "|clq=y" or "") .. "}}" or "")
		if args["den"] then
			if args["dko"] or args["dvi"] then
				result = result .. "\n"
			end
		end
		result = result .. (args["dko"] and "* {{desc|ko|" .. args["dko"] .. (args["dkob"] and "|bor=y" or "") .. (args["dkod"] and "|der=y" or "") .. (args["dkoc"] and "|clq=y" or "") .. "}}" or "")
		if args["dko"] then
			if args["dvi"] then
				result = result .. "\n"
			end
		end
		result = result .. (args["dvi"] and "* {{desc|vi|" .. args["dvi"] .. (args["dvib"] and "|bor=y" or "") .. (args["dvid"] and "|der=y" or "") .. (args["dvic"] and "|clq=y" or "") .. "}}" or "")
	end
	result = result .. other("ana", "คำสลับอักษร", args)
	result = result .. other("also", "ดูเพิ่ม", args)
	
	local ref
	if args["ref"] then
		ref = args["ref"] ~= "n"
	else
		ref = args["acc_ref"] or args["e_ref"]
	end
	if ref then
		result = result .. "\n\n=== อ้างอิง ===\n<references/>"
	end

	if args["cn"] then
		result = result .. "\n\n{{cln|ja|" .. args["cn"]
	cn_count = 2
	while args["cn" .. cn_count] do
		result = result .. "|" .. args["cn" .. cn_count]
		cn_count = cn_count + 1
	end
		result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
	end
	if args["ct"] then
		result = result .. (args["cn"] and "\n" or "\n\n") .. "{{top|ja|" .. args["ct"]
	ct_count = 2
	while args["ct" .. ct_count] do
		result = result .. "|" .. args["ct" .. ct_count]
		ct_count = ct_count + 1
	end
		result = result .. (args["defs"] and "" or args["sort"] and "|sort=" .. args["sort"] or sortkey or "") .. "}}"
	end

	if args["k"] then
		result = result .."\n\n----\n\n== ภาษาเกาหลี ==\n{{ko-hanjatab}}\n\n===" .. pos_table[args["kp"] or "n"][1] ..
			"===\n{{ko-" .. pos_table[args["kp"] or "n"][2] .. "|hangeul=" .. args["k"] .. (args["mr"] and "|mr=" .. args["mr"] or "") .. (args["yl"] and "|y=" .. args["yl"] or "") .. "}}" ..
			"\n\n# {{hanja form of|" .. args["k"] .. "|" .. (args["kd"] or args[3]) .. "}}"
	end

	return result
end

function export.add(frame)
	local args = frame:getParent().args
	
	local page = mw.title.new(pagename):getContent()
	if not find(page, '== ภาษาญี่ปุ่น ==\n') then return export.new(nil, args) end
	page = match(page, '== ภาษาญี่ปุ่น ==\n.-%-%-%-%-') or match(page, '== ภาษาญี่ปุ่น ==\n.*')
	
	-- ensure that there is no whitespace between = and heading title (WT:NORM)
	page = gsub(page, '(\n===*) *([^=\n]-) *(===*\n)', function(a,b,c) return a .. b .. c end)
	
	local kireme = find(page, '\n=== อ้างอิง ===') or find(page, '\n%-%-%-%-$')
	if kireme then kireme = kireme + 1 else
		page = gsub(page, '\n$', '') .. '\n\n'
		kireme = find(page, '$')
	end
	local main_part = sub(page, 1, kireme - 1)
	local ending_part = sub(page, kireme, length(page))
	if find(ending_part, '=== อ้างอิง ===') then args["ref"] = 'n' end
	
	local function ja_new_and_korean(args)
		local ja_new = export.new(nil, args)
		local korean = nil
		if find(ja_new, '\n\n%-%-%-%-\n\n== ภาษาเกาหลี ==') then
			_, _, ja_new, korean = find(ja_new, '(.+)\n\n%-%-%-%-\n\n(== ภาษาเกาหลี ==.+)')
		end
		return ja_new .. '\n\n', korean
	end
	
	local result, new_section, korean_section
	
	-- case 1, the current entry has multiple Etymology sections, and our task is to append a new etymology section at the end
	local largest_etym_number
	for number in gmatch(main_part, '=== รากศัพท์ (%d+) ===') do largest_etym_number = number end
	if largest_etym_number then
		args["en"] = tostring(tonumber(largest_etym_number) + 1)
		new_section, korean_section = ja_new_and_korean(args)
		result = main_part .. new_section .. ending_part
	else
		-- case 2, the current entry has only one word with POS headers on L3, or no word at all (with the sole L3 header being === คันจิ ===)
		local kireme
		for l3_name in gmatch(main_part, '\n===([^=\n]+)') do
			if not find(l3_name, '^คันจิ') and not kireme then
				kireme = find(main_part, '\n===' .. l3_name) + 1
			end
		end
		if kireme then
			-- case 2a, the current entry has only one word, and we should put the existing word under Etymology 1 and add the new word as Etymology 2
			local header_and_kanji_section = sub(main_part, 1, kireme - 1)
			local existing_word = sub(main_part, kireme, length(main_part))
			if not find(existing_word, '=== รากศัพท์ ===\n') then existing_word = '=== รากศัพท์ ===\n\n' .. existing_word end
			existing_word = gsub(existing_word, '^=== รากศัพท์ ===', '=== รากศัพท์ 1 ===')
			existing_word = gsub(existing_word, '(\n===*) *([^=\n]-) *(===*\n)', function(a,b,c) return a .. '=' .. b .. '=' .. c end)
			if find(header_and_kanji_section, '{{ja%-kanjitab') then
				local kanjitab = match(header_and_kanji_section, '{{ja%-kanjitab.-\n')
				header_and_kanji_section = gsub(header_and_kanji_section, '{{ja%-kanjitab.-\n', '')
				existing_word = gsub(existing_word, '^=== รากศัพท์ 1 ===', function (a) return a .. '\n' .. kanjitab end)
			end
			args["en"] = "2"
			new_section, korean_section = ja_new_and_korean(args)
			result = header_and_kanji_section .. existing_word .. new_section .. ending_part
		else
			-- case 2b, the current entry has only a === คันจิ === section
			new_section, korean_section = ja_new_and_korean(args)
			new_section = gsub(new_section, '^== ภาษาญี่ปุ่น ==\n*', '')
			result = main_part .. new_section .. ending_part
		end
	end
	
	if not find(result, '%-%-%-%-$') then
		result = gsub(result, '\n*$', '') .. '\n'
		if korean_section then result = result .. '\n----\n\n' .. korean_section end
	else
		if korean_section then result = result .. '\n\n' .. korean_section .. '\n\n----' end
	end
	result = gsub(result, '\n\n\n', '\n\n')
	return result
end

return export