local p={}

function p._parse(index, template, frame)
	if not frame then frame = mw.getCurrentFrame() end
	local error = ' when using {{tl|Inflation/' .. template .. '}}.{{main other|[[Category:Pages with errors in inflation template]]}}</span>'
	if index then
		local tempTitle = "Inflation/" .. index .. "/dataset"
		local dataset = mw.title.new(tempTitle, "Template")
		if dataset.exists then
			local datatable = {}
			local data = mw.text.gsplit(mw.ustring.gsub(dataset:getContent(), "\n?%s*|%s*#default%s*", ""), "\n")
			for row in data do
				local year, value = mw.ustring.match(row, "%s*\|%s*(%d%d%d%d)%s*=%s*([%d%.]+)")
				if year and value then
					datatable[tonumber(year)] = tonumber(value)
				else
					year, value = mw.ustring.match(row, "%s*\|%s*(%d%d%d%d)%s*=%s*{{(#expr:.*)}}")
					if year and value then
						datatable[tonumber(year)] = tonumber(frame:callParserFunction( value ))
					end
				end
			end
			if table.maxn(datatable) then
				return datatable
			else
				error = '<span class="error">Error: unable to parse "Template:' .. tempTitle .. '"' .. error
			end
		else
			error = '<span class="error">Error: undefined index "' .. index .. '"' .. error
		end
	else
		error = '<span class="error">Error: no index specified' .. error
	end
	return frame:preprocess(error)
end

function p.year(frame)
	local index = frame.args.index or frame.args[1] or frame:getParent().args.index or frame:getParent().args[1]
	local result = p._parse(index, 'year', frame)
	if type(result) == "table" then
		return table.maxn(result)
	else
		return result
	end
end

return p