local p = {}

local monthsAbbr = {
	'Jan',
	'Feb',
	'Mar',
	'Apr',
	'May',
	'Jun',
	'Jul',
	'Aug',
	'Sep',
	'Oct',
	'Nov',
	'Dec'
}

local months = {
	'January',
	'February',
	'March',
	'April',
	'May',
	'June',
	'July',
	'August',
	'September',
	'October',
	'November',
	'December'
}

local function getMaxDay(month, year)
	local maxDay
	
	if month == 1
		or month == 3
		or month == 5
		or month == 7
		or month == 8
		or month == 10
		or month == 12
	then
		maxDay = 31
	elseif month == 2 then
		if year % 400 == 0 then
			maxDay = 29
		elseif year % 100 == 0 then
			maxDay = 28
		elseif year % 4 == 0 then
			maxDay = 29
		else 
			maxDay = 28
		end
	else
		maxDay = 30
	end
	
	return maxDay
end

local function incrementDate(date)
	date.day = date.day + 1

	if date.day > date.maxDay then
		date.day = 1
		date.month = date.month + 1
		date.maxDay = getMaxDay(date.month, date.year)
		
		if date.month > 12 then
			date.month = 1
			date.year = date.year + 1
		end
	end
end

local function createDate(year, month, day)
	return {
		day = day,
		maxDay = getMaxDay(month, year),
		month = month,
		year = year
	}
end
	
function p.main()
	local currentDate = os.date('!*t')
	local date = createDate(2010, 12, 1)
	local out = '<table>'
	local currentMonth
	local currentYear
	
	while true do
		if date.year > currentDate.year then
			break
		end
		
		if date.year == currentDate.year then
			if date.month > currentDate.month then
				break
			end
			
			if date.month == currentDate.month and date.day > currentDate.day then
				break
			end
		end
		
		if date.year ~= currentYear then
			out = out .. '</td></tr></table><h2>' .. date.year .. '</h2><table>'
			currentYear = date.year
		end
		
		if date.month ~= currentMonth then
			out = out .. '</td></tr><tr><th scope="row" style="text-align:left;">' .. monthsAbbr[date.month] .. '</th><td>'
			currentMonth = date.month
		end
		
		local dateString = date.year .. ' ' .. months[date.month] .. ' ' .. date.day
		
		out = out .. '[[Wikipedia:Main Page history/' .. dateString .. '|' .. date.day .. ']]' .. '/[[Wikipedia:Main Page history/' .. dateString .. 'b|b]] '
		
		incrementDate(date)
	end
	
	return out .. '</td></tr></table>'
end

return p