local p = {}

local errorcats = ''

local function isnotempty(s)
	return s and s:match( '^%s*(.-)%s*$' ) ~= ''
end

local function mysplit(s)
	-- Change  tags to slashes
	s = mw.ustring.gsub
	s = mw.ustring.gsub
	s = mw.ustring.gsub
	-- Split into a table
	s = mw.text.split
	-- Remove empty rows
	local t = {}
	for k=1,#s do
		if isnotempty(s[k]) then
			table.insert
		end
	end
	return t
end

local function scoringtable
	local root = ''
	-- If there is no progression then do a very simple format
	if (not isnotempty(p)) and (isnotempty(g1) or isnotempty(g2)) then
		root = mw.html.create('table')
			root
		local row = root:tag('tr'):css
		row:tag('td')
		row:tag('td')
		row:tag('td')
		return tostring(root)
	end
	
	-- Split into tables
	local gt1 = mysplit(g1)
	local gt2 = mysplit(g2)
	local pt = mysplit(p)
	-- Align goals with scores in progression
	local score1, score2 = 0, 0
	for k = 1,#pt do
		local s1 = tonumber(mw.ustring.gsub(pt[k] or '', '^[%s]*([0-9][0-9]*)[^0-9][^0-9]*([0-9][0-9]*)[%s]*$', '%1') or '-1') or -1
		local s2 = tonumber(mw.ustring.gsub(pt[k] or '', '^[%s]*([0-9][0-9]*)[^0-9][^0-9]*([0-9][0-9]*)[%s]*$', '%2') or '-1') or -1
		if s1 == (score1 + 1) and s2 == score2 then
			score1 = s1
			table.insert
		elseif s2 == (score2 + 1) and s1 == score1 then
			score2 = s2
			table.insert
		else
			errorcats = errorcats .. ''
			errorcats = errorcats .. 'Error: Goals/Progression mismatch: S1 = ' .. s1 .. ' S2 = ' .. s2 .. ' GT1 = ' .. (gt1[k] or '') .. ' GT2 = ' .. (gt2[k] or '') .. ''
		end
	end
	if not (#gt1 == #pt) or not(#gt2 == #pt) then
		errorcats = errorcats .. ''
		errorcats = errorcats .. 'Error: Goals/Progression mismatch: N1 = ' .. #gt1 .. ' N2 = ' .. #gt2 .. ' PN = ' .. #pt .. ''
	end
	-- Now build the score table
	for k=1,#pt do
		if k == 1 then
			root = mw.html.create('table')
			root
		end
		local row = root:tag('tr'):css
		row:tag('td')
		row:tag('td')
		row:tag('td')
	end
	
	return tostring(root)
end

function p.box( frame )
	local args = frame:getParent.args
	local res = ''
	local id = args['id'] or ''
	
	id = mw.ustring.gsub(id,'^"(.-)"$', '%1')
	
	local root = mw.html.create('table')
	root
	local row = root:tag('tr'):addClass('summary')
	-- Date and time
	local cell = row:tag('td')
	cell:wikitext(args['date'] or '')
	cell:wikitext(isnotempty(args['time']) and '' .. args['time'] or '')
	-- Team 1
	cell = row:tag('td')
	cell:tag('span'):addClass('fn org'):wikitext(args['team1'] or '')
	-- Score
	cell = row:tag('td')
	if isnotempty(args['score']) then
		cell:tag('b'):wikitext(args['score'])
	else
		cell:tag('abbr'):attr:css:wikitext('v')	
	end
	if isnotempty(args['periods']) then
		cell:wikitext('')
		cell:tag('small'):wikitext(args['periods'])
	end
	-- Team 2
	cell = row:tag('td')
	cell:tag('span'):addClass('fn org'):wikitext(args['team2'] or '')
	-- Stadium and attendance
	cell = row:tag('td')
	if isnotempty(args['stadium']) then
		cell:tag('span'):addClass('location'):wikitext(args['stadium'])
	end
	if isnotempty(args['attendance']) then
		cell:wikitext('')
		cell:tag('i'):wikitext('관중 수:')
		cell:wikitext(' ' .. args['attendance'])
	end
	res = res .. tostring(root)

	if isnotempty(args['score']) then
		root = mw.html.create('table')
		root
		cell = root:tag('tr'):tag('th')
		cell:attr
		if isnotempty(args['reference']) then
			cell:tag('b'):wikitext('[' .. args['reference'] .. ' 경기 참조]')
		end
		-- Empty spacing
		row = root:tag('tr'):css
		cell = row:tag('td')

		-- Goalies
		cell = row:tag('td')
		cell = row:tag('td')
		if isnotempty(args['goalie1']) or isnotempty(args['goalie2']) then
			cell:tag('i'):wikitext('골키퍼')
		end
		cell = row:tag('td')

		-- Officials and linesmen
		cell = row:tag('td')
		if isnotempty(args['official']) then
			if isnotempty(args['official2']) then
				cell:tag('i'):wikitext('심판:')
				cell:wikitext('' .. args['official2'])
			else
				cell:tag('i'):wikitext('심판:')
				cell:wikitext('' .. args['official'])
			end
		end
		if isnotempty(args['linesman']) then
			cell:wikitext('')
			if isnotempty(args['linesman2']) then
				cell:tag('i'):wikitext('Linesmen:')
				cell:wikitext('' .. args['linesman2'])
			else
				cell:tag('i'):wikitext('Linesman:')
				cell:wikitext('' .. args['linesman'])
			end
		end
		-- Goals and progression
		row = root:tag('tr'):css
		cell = row:tag('td')
				scoringtable
					)
		if isnotempty(args['pnote']) then
			row = root:tag('tr'):css
			row:tag('td')
		end
		-- Shoot out
		if isnotempty(args['soshots1']) or isnotempty(args['soshots2']) then
			soshots1 = table.concat(mysplit(args['soshots1'] or ''), '')
			soshots2 = table.concat(mysplit(args['soshots2'] or ''), '')
			row = root:tag('tr'):css
			row:tag('td')
			row:tag('td')
			row:tag('td')
		end
		if isnotempty(args['sonote']) then
			row = root:tag('tr'):css
			row:tag('td')
		end
		-- Second leg overtime
		if isnotempty(args['otgoals1']) or isnotempty(args['otgoals2']) 
						or isnotempty(args['otprogression']) then
			row = root:tag('tr'):css
			cell = row:tag('td')
					scoringtable
					)
		end
		if isnotempty(args['otnote']) then
			row = root:tag('tr'):css
			row:tag('td')
		end
		-- Penalties
		row = root:tag('tr'):css
		cell = row:tag('td')
		if isnotempty(args['penalties1']) then
			cell:tag('i'):wikitext(args['penalties1'] .. ' 분')
		end
		cell = row:tag('td')
		if isnotempty(args['penalties1']) or isnotempty(args['penalties2']) then
			cell:tag('i'):wikitext('페널티')
		end
		cell = row:tag('td')
		if isnotempty(args['penalties2']) then
			cell:tag('i'):wikitext(args['penalties2'] .. ' 분')
		end
		-- Shots
		row = root:tag('tr'):css
		cell = row:tag('td')
		if isnotempty(args['shots1']) then
			cell:tag('i'):wikitext(args['shots1'])
		end
		cell = row:tag('td')
		if isnotempty(args['shots1']) or isnotempty(args['shots2']) then
			cell:tag('i'):wikitext('슛')
		end
		cell = row:tag('td')
		if isnotempty(args['shots2']) then
			cell:tag('i'):wikitext(args['shots2'])
		end
		res = res .. tostring(root)
	end
	if isnotempty(args['note']) then
		root = mw.html.create('table')
		root
		cell = root:tag('tr'):tag('td')
		cell
		res = res .. tostring(root) .. ''
	end
	-- tracking
	if (args['sogoals1'] or args['sogoals2']) then
		errorcats = errorcats .. ''
	end
	-- make errors visible in preview mode
	if errorcats ~= '' then
		if frame:preprocess( "" ) == "" then
			errorcats = ''
		else
			errorcats = ''
		end
	end
	return errorcats .. res
end