mtable = {"ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני",
	"יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר", }
monthtable = {
	["תשרי"] = 7, ["חשוון"] = 8, ["כסלו"] = 9, ["טבת"] = 10,
	["שבט"] = 11, ["אדר א'"] = 12, ["אדר ב'"] = 13, ["אדר"] = 13,
	["ניסן"] = 1, ["אייר"] = 2, ["סיוון"] = 3, ["תמוז"] = 4,
	["אב"] = 5, ["אלול"] = 6,
	}

function sub1(str, from, to)
	return mw.ustring.sub(str, from, to)
end

function find1(str, what, where)
	local ans = mw.ustring.find(str, what, where, true)
	if (ans == nil) then
		ans = 0 end
	return ans
end

function len1(s)
	if (s == nil) then
		return 0 end
	return mw.ustring.len(s)
end

function hebnum(s)
	numberstable = {
	["א"] = 1, ["ב"] = 2, ["ג"] = 3, ["ד"] = 4, ["ה"] = 5,
	["ו"] = 6, ["ז"] = 7, ["ח"] = 8, ["ט"] = 9, ["י"] = 10, 
	["כ"] = 20, ["ך"] = 20, ["ל"] = 30, ["מ"] = 40, ["ם"] = 40, 
	["נ"] = 50, ["ן"] = 50, ["ס"] = 60, ["ע"] = 70, ["פ"] = 80, 
	["ף"] = 80, ["צ"] = 90, ["ץ"] = 90, ["ק"] = 100, ["ר"] = 200, 
	["ש"] = 300, ["ת"] = 400, ["'"] = 0, ["\""] = 0,}
	local ans = 0
	local str = s
	while len1(str) > 0 do
		ans = ans + numberstable[sub1(str, 1, 1)]
		str = sub1(str, 2, len1(str))
	end
	return ans
end

function mindate(fix)
	local indenttable = {176, 206, 235, 265, 294, 324, 0, 30, 59, 88, 117, 147, 147}
	return same("28-08-" .. frame:callParserFunction("padleft", {hebnum(sub1(fix[3], 3, len1(fix[3]))) + 1000
		* hebnum(sub1((fix[3]), 1, 2)) - 3761, 4}) .. " + " .. (indenttable[monthtable[sub1(fix[2], 2)]]
		+ hebnum(fix[1]) - 1) .. " days")
end

function exacttdate(hdate, mindate)
	local count = 0
	local ans
	local greg
	while (count < 82) do
		ans = mindate .. " + " .. count .. " days"
		if (from(ans) == hdate) then
			greg = same(ans)
			greg = same(greg .. " - ".. diff(greg) .. "days")
			checkcasp(greg)
			return to(greg) end
		count = count + 1
	end
	error("Date not found")
end

function exacttdate1(hyear)
	local wyear = frame:callParserFunction("padleft", {hebnum(sub1(hyear, 3, len1(hyear))) + 1000
		* hebnum(sub1(hyear, 1, 2)) - 3761, 4})
	checkcasp("01-01-" .. wyear)
	return wyear .. "-" .. frame:callParserFunction("padleft", {wyear + 1, 4})
end

function from(gdate)
	return frame:callParserFunction("#זמןמ:xhxjj xjx xhxjY", gdate)
end

function same(gdate)
	return frame:callParserFunction("#זמןמ:d-m-Y", gdate)
end

function to(gdate)
	return frame:callParserFunction("#זמןמ:j בF Y", gdate)
end

function fixdate(hdate)
	local s1 = find1(hdate, " ")
	local s2 = find1(hdate, " ", s1 + 1)
	local s3 = find1(hdate, " ", s2 + 1)
	if (s3 > 0) then
		s2 = s3 end
	h1 = sub1(hdate, 1, s1 - 1)
	h2 = sub1(hdate, s1 + 1, s2 - 1)
	h3 = sub1(hdate, s2 + 1, len1(hdate))
	if (len1(h3) > 1 and sub1(h3, 2, 2) ~= "'") then
		h3 = "ה'" .. h3 end
	return {h1, h2, h3, h1 .. " " .. h2 .. " " .. h3}
end

function fixerror(message)
	if message == "---"
		then return "" end
	return message
end

function aserror(message)
	error(message .. "[[קטגוריה:דפים עם שגיאות בתאריך]]")
end

function takenumbers(wdate)
	local s1 = find1(wdate, " ")
	local s2 = find1(wdate, " ", s1 + 1)
	local h1 = sub1(wdate, 1, s1 - 1)
	local h2 = sub1(wdate, s1 + 1, s2 - 1)
	local h3 = sub1(wdate, s2 + 1, len1(wdate))
	for f, ff in pairs(mtable) do
		if "ב" .. ff == h2 then
			return h1 .. "-" .. f .. "-" .. frame:callParserFunction("padleft", {h3, 4}) end
	end
	return wdate
end

function numtonums(wdate)
	local s1 = find1(wdate, "-")
	local s2 = find1(wdate, "-", s1 + 1)
	return {tonumber(sub1(wdate, 1, s1 - 1)),
			tonumber(sub1(wdate, s1 + 1, s2 - 1)),
		    tonumber(sub1(wdate, s2 + 1, len1(wdate)))}
end

function diff(gdate)
	local ans
	local wdate = numtonums(gdate)
	local wday = wdate[1]
	local wmonth = wdate[2]
	local wyear = wdate[3]
	if wyear > 1582 or (wyear == 1582 and (wmonth > 10 or (wmonth == 10 and wday > 14)))
		then ans = 0
		else local ytable = {200, 300, 500, 600, 700, 900, 1000, 1100, 1300, 1400, 1500}
			ans = 10
			if wmonth < 3
				then wyear = wyear - 1 end
			for y, yy in pairs(ytable) do
				if yy > wyear
					then ans = ans - 1 end
			end end
	return ans
end

function remove(dateStr) -- Thanks to Eran
	dateStr = mw.ustring.gsub( dateStr, "[%[%]]", "" )
	dateStr = mw.ustring.gsub(dateStr, "(\127UNIQ[^\127]+QINU\127)", "")
	dateStr = mw.ustring.gsub(dateStr, "&rlm;","")
	dateStr = mw.ustring.gsub(dateStr, "&lrm;","")
	return dateStr
end

function checkcasp(wdate)
	local wnumbers = numtonums(wdate)
	if wnumbers[3] < 360 or wnumbers[3] > 4357 or
			(wnumbers[3] == 1582 and wnumbers[2] == 10 and wnumbers[1] > 4 and wnumbers[1] < 15)
		then error("The date is not in the allowed casp") end
end

function fromhebrew1()
	local fix = fixdate(remove(frame.args[1]))
	return exacttdate(fix[4], mindate(fix))
end

function fromhebrew(f)
	frame = f
	local success, res = pcall(fromhebrew1)
	if success
		then return res end
	for m, mm in pairs(monthtable) do
		if find1(frame.args[1], m) == 1 then
			error("month not implemented yet") end
	end
	if find1(frame.args[1], " ") == 0 then
		error("year not implemented yet") end
	if frame.args["error"] == nil
		then return aserror(res) end
	return fixerror(frame.args["error"])
end

function tohebrew1()
	local rem = mw.text.trim(remove(frame.args[1]))
	local take = takenumbers(rem)
	if to(take) ~= rem
		then error("wrong date") end
	checkcasp(take)
	take = same(take .. " + " .. diff(take) .. " days")
	return from(take)
end

function tohebrew(f)
	frame = f
	local success, res1 = pcall(tohebrew1, frame)
	if success
		then return res1 end
	for m, mm in pairs(mtable) do
		if find1(frame.args[1], mm) == 1 then
			error("month not implemented yet") end
	end
	if find1(frame.args[1], " ") == 0 then
		error("year not implemented yet") end
	if frame.args["error"] == nil
		then return aserror(res) end
	return fixerror(frame.args["error"])
end

return {fromhebrew = fromhebrew, tohebrew = tohebrew}