This module is embedded in our various event infobox templates, and serves to provide auto-categorization by parsing the date fields of the infobox and extracting the ABY and BBY dates. It has some exception values that stop categorization, such as "c." and "before" or "after", and will place the article in either "Category:Events in <Year>" or "Category:Battles in <Year>".


local p = {}

local function splitDelimiter(str, d)
	if str:find(d) then
		return str:sub(1, str:find(d) - 1)
	end
	return str
end

local function splitPieces(str, sep)
	if sep == nil then
		sep = "%s"
	end
	local t = {}
	for s in string.gmatch(str, "([^" .. sep .. "]+)") do
		table.insert(t, s)
	end
	return t
end


function p.main(frame)
    if mw.title.getCurrentTitle().namespace ~= 0 then
        return ''
    end
	local date = ''
    for k, v in pairs(frame:getParent().args) do
    	if k == "date" and v and string.len(v) > 0 then
    		date = v
    	end
    end
	
	if not date then
		return ''
	end
	
	local catName = "Events"
	if frame.args.type then
		catName = frame.args.type
	end
	
	if date:find("<ref") then
		date = date:sub(1, date:find('<ref') - 1)
	end
	local st = splitDelimiter(string.lower(date), '%('):gsub("'", "")
	if st:find('prior') or st:find('before') or st:find('after') or st:find('between') or st:find(' by') or st:find('^by ') then
		return ''
	end
	local sortKey = ''
	if st:find('c%.') or st:find('circa') then
		sortKey = "|*" .. mw.title.getCurrentTitle().text
	end
	
	local cats = {}
	for _, x in ipairs(splitPieces(date, "[")) do
		local link = splitDelimiter(splitDelimiter(splitDelimiter(x, "|"), "]"), "/")
		if link:find(" ABY") or link:find(" BBY") then
			cats[#cats + 1] = "[[Category:" .. catName .. " in " .. link .. sortKey .. "]]"
		end
	end
    return table.concat(cats)
end

return p