Module:Version 2

Lua
CodeDiscussionLinksLink count SubpagesDocumentationTestsResultsSandboxLive code All modules

Documentation for this module may be created at Module:Version 2/doc

Code

local p = {}
flag_table = {}

l10nDef = require('Module:Version 2/l10n')

if l10nDef.langcode ~= nil then
	langcode = l10nDef.langcode
	lang = mw.language.new( langcode )
else
	lang = mw.language.getContentLanguage()
	langcode = lang:getCode()
end
wiki = langcode

if lang:isRTL() then textalign = 'right' else textalign = 'left' end

WDlink_on = false
if l10nDef.WDlink_on ~= nil then WDlink_on = l10nDef.WDlink_on end

function l10n(x, qid)
	local translation = l10nDef.translations[langcode][x]
	if not translation and qid ~= nil then translation = mw.wikibase.label( qid ) end -- get Wikidata label (can use fallback chain)
	if not translation then translation = l10nDef.translations['en'][x] end -- default
	if not translation then translation = '' end -- default
	return translation
end

function monolingualValue(entity, property)
	if entity.claims ~= nil then
		if entity.claims[property] ~= nil then
			for _,v in pairs(entity.claims[property]) do
				if v.mainsnak.snaktype ~= 'value' then return '' end
				if v.mainsnak.datavalue.value.language == langcode then return v.mainsnak.datavalue.value.text end
			end
			for _,v in pairs(entity.claims[property]) do
				if v.mainsnak.datavalue.value.language == 'en' then return v.mainsnak.datavalue.value.text end
			end
			return entity.claims[property][1].mainsnak.datavalue.value.text
		end
	end
	return ''
end

function p.victories(frame)
	local s = {
		header_1 = "victories", -- translation
		header_2 = {"date", "race", "country", "class", "winner"},-- translations
										-- in the lower part of the table header. The second value 3 in {4, 3} tells where the icon will go.
		data_type = {'date', 'race', 'country', 'class', 'rider'},
		country_column = 3,
		data_sort_type = {'', 'unsortable', '', '', ''}, -- see https://meta.wikimedia.org/wiki/Help:Sorting
		item = frame.args[1],
		property = 'P2522',
		error_message = 0
	}
	return tableA(s, victory_main(s, Qnumber))
end

function victory_main(s, Qnumber)
	local s = s
	local h = {} -- time, raceID, countryID, countryName
	local test

	 _, _, s.item = string.find(s.item, "(%w+)")
	local entity = mw.wikibase.getEntity( s.item )

	pcall(function() test = entity.claims[s.property][1].mainsnak.snaktype end)
	if test == 'somevalue' or test == 'novalue' then s.error_message = 2 return '' end

	if pcall(function() test = entity.claims[s.property][1].mainsnak.datavalue.value['numeric-id'] end)
	then else s.error_message = 1  return ''
	end

	local country = true
	if l10nDef.no_country_in_victories == true then country = false end

	local sortkey, sortkey_class
	local tBody = ''
	local tableBody, sortindex = {}, {}
	local a1, b1, c1
	local timeofrace

	-- Class of a cycling race. Class is: 1.UWT, 2.UWT, 1.HC, ... add new classes, no problem
	local class = { "Q22231106", "Q22231107", "Q22231108", "Q22231109", "Q22231110", "Q22231111", "Q22231112",
		"Q22231113", "Q22231114", "Q22231115", "Q22231116", "Q22231117", "Q22231118", "Q22231119", "Q23015458", "Q23005601", "Q23005603" }
	local class_2x = {"Q22231107", "Q23005603", "Q22231115", "Q22231109", "Q22231112", "Q22231113", "Q22231117"} --multi stage races

	-- 1.UWT, 2.UWT, 1.HC, 2.HC, 1.1, 1.2, 2.1, 2.2, 1.Ncup, 2.Ncup, 1.2U, 2.2U, CC, CN, CDM, 1.WWT, 2.WWT
	-- CC, CDM,
	-- 1.UWT, 2.UWT, 1.WWT, 2.WWT, 2.Ncup, 1.Ncup, 2.HC, 1.HC, 2.1, 1.1, 2.2, 2.2U, 1.2, 1.2U, CN
	-- https://fr.wikipedia.org/wiki/Projet:Cyclisme/Usages#Victoires
	local class_sort={["Q22231106"]='01', ["Q22231107"]='01', ["Q23005601"]='01', ["Q23005603"]='01', ["Q22231115"]='01', -- 1.UWT, 2.UWT, 1.WWT, 2.WWT, 2.Ncup
		["Q22231114"]='02', ["Q22231109"]='03', ["Q22231108"]='04', ["Q22231112"]='05', ["Q22231110"]='06', -- 1.Ncup, 2.HC, 1.HC, 2.1, 1.1
		["Q22231113"]='07', ["Q22231117"]='07', ["Q22231111"]='08', ["Q22231116"]='08', ["Q22231119"]='09', --2.2, 2.2U, 1.2, 1.2U, CN

		["Q22231118"]='13', ["Q23015458"]='15' }

	local stages = {'Q18131152', 'Q20646667', 'Q20646670', 'Q20680270', 'Q20646668', 'Q20679712', 'Q2348250', 'Q2266066', 'Q485321'}

	-- UCI Europe Tour,..., UCI ProTour, UCI World Calendar, UCI WorldTour, UCI Women’s WorldTour, UCI Women's Road World Rankings
	local UCI_Circuits = {'Q1194340', 'Q1063423', 'Q1063430', 'Q268357', 'Q1039648', 'Q1329578', 'Q12270097', 'Q635366', 'Q21075974', 'Q1693153'}

	for l, m in pairs(entity.claims[s.property]) do -- look into all statements
		h['time'] = '' 	h['countryID'] = '' h['countryName'] = ''
		h['raceID'] = 'Q'.. m.mainsnak.datavalue.value['numeric-id']
		h['item1ID'] = h['raceID']	h['item2ID'] = '' h['item3ID'] = ''
		local entity_race = mw.wikibase.getEntity( h['raceID'] )

		local function fn2_country()
			local raceID
			local a, b = timeStartEnd(h['raceID'], "P17", 'numeric-id', timeofrace)
			if a == true then
				h['countryID'] = 'Q'..b
				if country == true then
					h['countryName'] = l10n('Q' .. b, 'Q' .. b)
				end
			else --go from stage item to race item
				a, b = pcall(fooA, 'numeric-id', entity_race, 'P361', 1)
				if a == true then h['item2ID'] = 'Q'..b end
				if a == false then
					a, b = pcall(fooA, 'numeric-id', entity_race, 'P31', 1)
					if a == true then h['item3ID'] = 'Q'..b end
				end
				if a == true then
					local a, b = timeStartEnd('Q'..b, "P17", 'numeric-id', timeofrace)
					if a == true then h['countryID'] = 'Q'..b
						if country == true then
							h['countryName'] = l10n('Q' .. b, 'Q' .. b)
						end
					end
				end
			end
		end -- end function fn2_country

		local function fn_date(h)
			local i
			sortkey=''
			for _,property in ipairs({"P585","P582", "P580"}) do
				-- give time dates, when property 'point in time', 'start time' or 'end time' is used
				a1, b1, c1 = pcall(fooA, 'time', entity_race, property, 1)
				if a1 == true and h['time'] == '' then i = 1
					while a1 == true and c1 == 'deprecated' do
						i = i + 1
						a1, b1, c1 = pcall(fooA, 'time', entity_race, property, i)
					end
					local _, _, y, m, d = string.find(b1, "(%d+)%p(%d+)%p(%d+)")
					if m ~= '00' and d =='00' then sortkey = y..m..'32' h['time'] = lang:formatDate("M", '+'..y.."-"..m.."-31")
					elseif m == '00' and d =='00' then sortkey = y..'12'..'32' h['time'] = ''
					else sortkey = y..m..d  h['time'] = formatDate(b1, 'small')
					end
					timeofrace = b1
					break
				end
	  		end
		return '<td data-sort-value="'..sortkey..  '" style="text-align:right;padding:0 0.5em">'.. h['time'].. '</td>'
		end -- end function fn_dates

		local function fn_race(h)
			local str, a, b, a1, b1, a2, b2, a3, b3
			local label_x = ''
			local entity_x1
			local Sitelink_x, Sitelink_x0, Sitelink_x1, Sitelink_x2 = '', '', ''
			local entity_race = mw.wikibase.getEntity( h['raceID'] )
			local entity_type, entity_num = '', 0
			local level = -1
			local link
			local multi_stage = false
			a, b = pcall(fooA, 'numeric-id', entity_race, 'P31', 1)
			if a == true then
				-- test for stage item
				for i=1,#stages do
					if "Q"..b == stages[i] then entity_type = 'stage item' end -- stage article
				end

				-- test for 'no stage item' - item
				a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P31', 1) -- first value for P31
				a2, b2 = pcall(fooA, 'numeric-id', entity_race, 'P31', 2) -- second value for P31
				if a1 == true and a2 == true then -- for two values
					if "Q"..b1 == "Q22231119" or "Q"..b1 == "Q23015458" then entity_num = 2 entity_type = 'championship' end
					if "Q"..b2 == "Q22231119" or "Q"..b2 == "Q23015458" then entity_num = 1 entity_type = 'championship' end
					if entity_type == '' then
						for i=1,#class do -- #class = number of elements in class
							if "Q"..b1 == class[i] then
								for ii=1,#class_2x do
	   								if "Q"..b1 == class_2x[ii] then multi_stage = "Q"..b1 break end
	   							end
	   							entity_num = 2 entity_type = 'no stage item' break
	   						end
							if "Q"..b2 == class[i] then
								for ii=1,#class_2x do
	   								if "Q"..b2 == class_2x[ii] then multi_stage = "Q"..b2 break end
	   							end
	   							entity_num = 1 entity_type = 'no stage item' break
	   						end
						end
					end
				end

				-- else A
				if entity_type == '' and a1 == true and a2 == false then -- for one value
					entity_type = 'else A'
				end
				-- else B

			end

			if entity_type == 'else A' then
				label_x = monolingualValue(entity_race, 'P1448')
				if label_x == '' then
					a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P31', 1)
					if a1 == true then
						Sitelink_x1 = mw.wikibase.Sitelink( 'Q' .. b1 )
						label_x = mw.wikibase.label( 'Q' .. b1 ) or ''

					end
				end
				if entity_race ~= nil then Sitelink_x0 = entity_race:getSitelink(wiki..'wiki') end
				if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0
				elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
				end
			end

			if entity_type == 'no stage item' then
				a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P31', entity_num)
				if a1 == true then
					Sitelink_x1 = mw.wikibase.sitelink( 'Q' .. b1 )
					label_x = mw.wikibase.label( 'Q' .. b1 )
				end
				if entity_race ~= nil then Sitelink_x0 = entity_race:getSitelink(wiki..'wiki') end
				if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0
				elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
				end
			end

			if entity_type == 'championship' then
				a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P31', entity_num)
				if a1 == true then
					entity_l = mw.wikibase.getEntity( 'Q' .. b1 )
					label_x = monolingualValue(entity_l, 'P1448') -- show the "offical name"
					if label_x == '' then
						label_x = mw.wikibase.label( 'Q' .. b1 )
					end
					Sitelink_x = mw.wikibase.sitelink( 'Q' .. b1 )

					if Sitelink_x == nil or label_x == nil then
						a2, b2 = pcall(fooA, 'numeric-id', entity_l, 'P361', 1)
						if a2 == true then
							if Sitelink_x == nil then Sitelink_x = mw.wikibase.sitelink( 'Q' .. b2 ) end
							if label_x == nil then label_x = mw.wikibase.label( 'Q' .. b2 ) end
						end
					end
					if Sitelink_x ~= nil then
						if label_x ~= nil then
							link = '[[' .. Sitelink_x .. '|' .. label_x .. ']]'
						else
							link = '[[' .. Sitelink_x .. ']]'
						end
					else
						if label_x ~= nil then
							link = label_x
						else
							link = '(label missing)'
						end
					end
				end
			end

			if entity_type == 'stage item' then
				local entity_l
				a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P361', 1)
				if a1 == true then
					entity_x1 = mw.wikibase.getEntity( 'Q'..b1 )
					a2, b2 = pcall(fooA, 'numeric-id', entity_x1, 'P31', 1)
					if a2 == true then
						local is_class = false
						for i=1,#class do
							if "Q"..b2 == class[i] then is_class = true break end
						end
						if is_class == false then
							entity_l = mw.wikibase.getEntity( 'Q' .. b2 )
							label_x = mw.wikibase.label( 'Q' .. b2 )
						else
							a3, b3 = pcall(fooA, 'numeric-id', "Q"..b2, 'P31', 2)
							if a3 == true then
								entity_l = mw.wikibase.getEntity( 'Q' .. b3 )
								label_x = mw.wikibase.label( 'Q' .. b3 )
							end
						end
					end
				end
				entity_stage = mw.wikibase.getEntity( 'Q18131152' )

				local comma = ", "
				if wiki == 'fr' then
					for _,v in ipairs({"^Trois", "^Quatre", "^Boucles"}) do  -- ^ match only at the beginning
						local i, _ = mw.ustring.find(label_x , v)
						if i ~= nil then comma = " des " end
					end
					for _,v in ipairs({"^Triptyque", "^Tour", "^Grand Prix", "^Circuit", "^Mémorial", "^Trophée"}) do
						local i, _ = mw.ustring.find(label_x , v)
						if i ~= nil then comma = " du " end
					end
					for _,v in ipairs({"^Ronde", "^Semaine", "^Classica", "^Flèche", "^Course", "^Classique"}) do
						local i, _ = mw.ustring.find(label_x , v)
						if i ~= nil then comma = " de la " end
					end
					for _,v in ipairs({"^Étoile"}) do
						local i, _ = mw.ustring.find(label_x , v)
						if i ~= nil then comma = " de l'" end
					end
				end

				a, b = pcall(fooA, 'value', entity_race, 'P1545', 1)
				if a == false then b = '?' end
				if b ~= '0' then
					local stage_label = l10n('stage')

					local substage = ' '
					local i,j = string.find(b, "%a+")
					local k,l = string.find(b, "%d+")
					local value1, value2
					value2 = string.sub(b, k, l)
					if i ~= nil then value1 = string.sub(b, i, j) end
					if value1 ~= nil then substage = value1..' ' b = value2 end

					if entity_l~= nil then Sitelink_x2 = entity_l:getSitelink(wiki..'wiki') end
					if entity_x1~=nil then Sitelink_x1 = entity_x1:getSitelink(wiki..'wiki') end
					if entity_race~=nil then Sitelink_x0 = entity_race:getSitelink(wiki..'wiki') end
					if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0
					elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
					elseif Sitelink_x2 ~= nil then Sitelink_x = Sitelink_x2 level = 2
					end

					local number = number(b, 'f')

					if wiki=='de' or wiki=='da' or wiki=='fo' or wiki=='no' then
						if level == 1 or level == 2 then
							link = '[['..Sitelink_x..'|'.. label_x.. ']]' ..', '.. number .. substage.. stage_label
						elseif level == 0 then
							link = '[['..Sitelink_x.. '|'.. label_x.. ', '.. number .. substage.. stage_label.. ']]'
						elseif level == -1 then
							link = label_x.. ', '.. number .. substage.. stage_label
						end
					elseif wiki == 'en' or wiki == 'br' then
						label_x = label_x.. ', '.. stage_label.. ' '.. b
					elseif wiki == 'fr' or wiki == 'lb' then
						if level == 1 or level == 2 then
							if b == '1' then link = number .. substage.. stage_label.. comma.. '[['..Sitelink_x..'#1re.C2.A0.C3.A9tape'..'|'.. label_x.. ']]'
							else link = number .. substage.. stage_label.. comma.. '[['..Sitelink_x..'#'.. b.. 'e.C2.A0.C3.A9tape'..'|'.. label_x..']]'
							end
						end
						if level == 0 then
							link = '[['..Sitelink_x.. '|'.. number .. substage.. stage_label.. comma.. label_x.. ']]'
						end
						if level == -1 then
							link = number .. substage.. stage_label.. comma.. label_x
						end

					elseif wiki=='ca' then label_x = number .. stage_label.. ' del '.. label_x
					elseif wiki=='es' then label_x = number .. stage_label.. ', '.. label_x
					else label_x = stage_label.. ' '.. b..', '.. label_x
					end
				else -- Prolog
					if entity_l~= nil then Sitelink_x2 = entity_l:getSitelink(wiki..'wiki') end
					if entity_x1~=nil then Sitelink_x1 = entity_x1:getSitelink(wiki..'wiki') end
					if entity_race~=nil then Sitelink_x0 = entity_race:getSitelink(wiki..'wiki') end
					if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0
					elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
					elseif Sitelink_x2 ~= nil then Sitelink_x = Sitelink_x2 level = 2
					end

					if wiki=='de' or wiki=='da' or wiki=='fo' or wiki=='no' then
						if level >= 0 then
							link = '[['..Sitelink_x.. '|'.. label_x.. ']]'.. ', '.. l10n('prolog')
						end
					elseif wiki == 'en' then
						label_x = label_x.. ', '.. l10n('prolog')
					elseif wiki == 'fr' or wiki == 'lb' then
						if level > 0 then link = l10n('prolog') .. comma.. '[['..Sitelink_x..'#'.. l10n('prolog') .. '|'.. label_x.. ']]'
						elseif level == 0 then link = '[['..Sitelink_x..'#'.. l10n('prolog') .. '|'.. l10n('prolog') .. comma.. label_x.. ']]'
						elseif level == -1 then link = l10n('prolog') .. comma.. label_x
						end
					else
						label_x = l10n('prolog') .. ', '.. label_x
					end
				end
			end -- end if entity_type == 'stage item'

			if level == -1 and link == nil then
				local Sitelink = ''
				Sitelink = mw.wikibase.sitelink( h['raceID'] )
				if Sitelink ~= '' and Sitelink ~= nil then
					link = '[['..Sitelink..'|'..label_x..']]'
				end
			end

			if level >= 0 and link == nil and Sitelink_x ~= '' then
				if multi_stage ~= false then
					if wiki == 'fr' then
						link = l10n('general_classification').. ', '.. '[['..Sitelink_x..'|'..label_x..']]'
					else
						link = '[['..Sitelink_x..'|'..label_x..']]'.. ', '.. l10n('general_classification')
					end
				else
					link = '[['..Sitelink_x..'|'..label_x..']]'
				end
			end

			if link == nil then link = label_x end

			if country == true then
				str =  '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..link.. '</td>'
			else
				fn2_country()
				if h['countryID'] ~= '' then str = '<td style="text-align:'.. textalign ..';padding:0 0.5em">'.. flag(h['countryID'], timeofrace).. ' '.. link.. '</td>'
				else str = '<td style="text-align:'.. textalign ..';padding:0 2.3em">'..link.. '</td>'
				end
			end
			return str
		end -- end function fn_race

		local function fn_country(h)
			local str
			if country == true then
				fn2_country()
				if h['countryID'] ~= '' and h['countryName'] ~= '' then str = '<td style="text-align:' .. textalign .. ';padding:0 0.5em">'..flag(h['countryID'], timeofrace).. ' '.. h['countryName'].. '</td>'
				elseif h['countryID'] == '' and h['countryName'] ~= '' then str = '<td style="text-align:' .. textalign .. ';padding:0 0.5em">'.. '   '.. h['countryName'].. '</td>'
				elseif h['countryID'] ~= '' and h['countryName'] == '' then str = '<td style="text-align:' .. textalign .. ';padding:0 0.5em">'..flag(h['countryID'], timeofrace).. '</td>'
				elseif h['countryID'] ~= '' and h['countryName'] ~= '' then str = '<td style="text-align:' .. textalign .. ';padding:0 0.5em">'.. '   '.. '</td>'
				end
			else str = ''
			end
			return str
		end -- end function fn_country

		local function fn_class(h)
			local entity_race = mw.wikibase.getEntity( h['raceID'] )
			local entity_type, entity_num = '', 0
			local class_text = ''
			local link = ''
			local Sitelink
			sortkey_class = ''

			a, b = pcall(fooA, 'numeric-id', entity_race, 'P31', 1)
			if a == true then
				-- test for stage item
				for i=1,#stages do
					if "Q"..b == stages[i] then entity_type = 'stage item' end
				end
			end

		if entity_type == 'stage item' then
			local a1, b1
			a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P361', 1)
			if a1 == true then
				local a, b, c, d
				local entity = mw.wikibase.getEntity( 'Q'..b1 )
				a, b = pcall(fooA, 'numeric-id', entity, 'P31', 1) -- first value for P31
				c, d = pcall(fooA, 'numeric-id', entity, 'P31', 2) -- second value for P31
				if a == true and c == true then -- for two values
					for i=1,#class do -- #class = number of elements in class
	   					if "Q"..d == class[i] then class_text = mw.wikibase.label('Q'..d) sortkey_class = class_sort['Q'..d] break end
	   				end -- for i
				end -- if a
			end
			link = class_text
			if link ~= '' then
				a, b = pcall(fooA, 'numeric-id', entity_race, 'P361', 1) -- first value for P361
				if a == true then
					entity_II = mw.wikibase.getEntity('Q'..b)
					c, d = pcall(fooA, 'numeric-id', entity_II, 'P361', 1) -- first value for P361
					if c == true then entity_circuit = mw.wikibase.getEntity('Q'..d) end
				end
			end
		else -- not a stage item
			local a, b, c, d, e, f
			a, b = pcall(fooA, 'numeric-id', entity_race, 'P31', 1) -- first value for P31
			c, d = pcall(fooA, 'numeric-id', entity_race, 'P31', 2) -- second value for P31
			if a == true and c == true then -- for two values
				for i=1,#class do -- #class = number of elements in class
					if "Q"..d == class[i] then class_text = mw.wikibase.label('Q'..d) sortkey_class = class_sort['Q'..d] break end
				end
			end

			link = class_text
			if link ~= '' then
				a, b = pcall(fooA, 'numeric-id', entity_race, 'P361', 1) -- first value for P361
				if a == true then entity_circuit = mw.wikibase.getEntity('Q'..b) end
			end
		end

		if link ~= '' then
			e, f = pcall(fooA, 'numeric-id', entity_circuit, 'P31', 1)
			if e == true then
				for i=1,#UCI_Circuits do -- abcd
					if "Q"..f == UCI_Circuits[i] then
						Sitelink = entity_circuit:getSitelink(wiki..'wiki')
						if Sitelink~=nil then link = '[['..Sitelink..'|'..link..']]' end
						break
					end
				end
			end
		end
		return '<td data-sort-value="'..sortkey_class.. '" style="text-align:center;padding:0 0.5em">'..link.. '</td>'
		end -- end function fn_class

		local function fn_rider(h)
			local qual
			local winner= ''
			local winner_flag=''

			a, b = pcall(fooC, 'numeric-id', entity_race, 'P1346', 1, 'P642', 1)
			if a == true then
				winner = '' winner_flag = ''
				for k, v in ipairs(entity_race.claims["P1346"]) do
					for kk, vv in ipairs(v.qualifiers['P642']) do
						if vv.datavalue.value['numeric-id'] == 20882667 then -- overall winner general classification
							winner = 'Q'.. v.mainsnak.datavalue.value['numeric-id']
						end
						if vv.datavalue.value['numeric-id'] == 20882747 then  -- stagewinner
							if winner == '' then winner = 'Q'.. v.mainsnak.datavalue.value['numeric-id'] end
						end
					end
				end
				winner_flag = ''
				local a, b = timeStartEnd(winner, "P27", 'numeric-id', timeofrace)
				if a == true then
					winner_flag = flag('Q'..b, timeofrace).. ' '
				end
			end -- if a == true

			if winner ~= '' then
				local winner_team = false
				local entity_winner = mw.wikibase.getEntity( winner )
				a, b = pcall(fooA, 'numeric-id', entity_winner, 'P31', 1) -- looking if winner is a person
				if a == true and b ~= 5 then winner_team = true end

				if winner_team == false then return '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..winner_flag.. WPlink(winner).. '</td>'
				else
				winner_flag = ''
				local a, b = timeStartEnd(winner, "P17", 'numeric-id', timeofrace) -- flag of team
				if a == true then
					winner_flag = flag('Q'..b, timeofrace).. ' '
				end
					return '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..winner_flag ..WPlink(winner, 'team', timeofrace).. '</td>'
				end
			else
				return '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..''.. '</td>'
			end
		end -- end function fn_rider

		tBody = '<tr style= "line-height: 1.8em; padding: 5px;">' -- start the table row
		for k,v in ipairs({fn_date(h), fn_race(h), fn_country(h), fn_class(h), fn_rider(h)}) do
			tBody = tBody.. v
		end
		tBody = tBody.. '</tr>' -- end the table row

	 	local number = table.getn(tableBody)
	 	--Insertion sort
	 	if number == 0 then
	 		table.insert(sortindex, sortkey)
			table.insert(tableBody, tBody)
		elseif sortkey >= sortindex[number] then
			table.insert(sortindex, sortkey)
			table.insert(tableBody, tBody)
		else
			for i=number,2,-1 do
				if sortkey >= sortindex[i] then
					table.insert(sortindex, i+1, sortkey)
					table.insert(tableBody, i+1, tBody)
					break
				end
			end
		end
	end
	return table.concat (tableBody)
end

function tableA(s, tableBody)
	local s = s

	local error_message = ''
	if s.error_message == 1 then
		error_message = l10n('error_propmissing')
		error_message = mw.ustring.gsub(error_message, "<1>", s.property)
		error_message = mw.ustring.gsub(error_message, "<2>", mw.wikibase.label( s.item ))
		error_message = mw.ustring.gsub(error_message, "<3>", s.item)
		error_message = ' [[File:Exclam icon.svg|12px|'.. error_message .. ']]'
	end

	local tableHeader2_size = table.getn(s.header_2)
	local tableStart = '<table border="0" cellspacing="0" cellpadding="0" class="sortable"><tr><th colspan="' .. tostring(tableHeader2_size + 1) .. '"' ..
		' style="padding:2px 2px; text-align:center; background-color:#FFDF80; line-height: 1.8em;">'
	local tableHeader1 = '<span style="float:left">[[File:Wikidata-logo S.svg|12px|link=d:'.. s.item.. '#'.. s.property..']]'.. error_message .. '</span>' ..
		l10n(s.header_1) .. '</th></tr>'
	local tableHeader2 = '<tr>'

	local country = true
	if l10nDef.no_country_in_victories == true then country = false end

	for i,k in ipairs(s.header_2) do
		if i == s.country_column then
			if country == true then
				tableHeader2 = tableHeader2.. '<th style="text-align:center;padding:2px 20px 2px 2px;white-space:nowrap">'.. l10n(k) .. '</th>'
			end
		end
		if i ~= s.country_column then
			if s.data_sort_type[i] == 'unsortable' then tableHeader2 = tableHeader2.. '<th class="unsortable" style="text-align:center;padding:2px 20px 2px 2px;white-space:nowrap">' .. l10n(k) .. '</th>'
			else tableHeader2 = tableHeader2.. '<th style="text-align:center;padding:2px 20px 2px 2px;white-space:nowrap">' .. l10n(k) .. '</th>'
			end
		end
	end

	tableHeader2 = tableHeader2 .. '</tr>'

	local tableEnd = '</table>'

	return '<table style="border:1px solid rgb(200,200,200)"><tr><td>' .. tableStart .. tableHeader1 .. tableHeader2 .. tableBody .. tableEnd .. '</td></tr></table>'
end -- end function tableA

function jersey(winner_classification, item, timeofrace)
	local jersey, jersey_name = '', ''
	local jerseyWPID = ''
	local starttime, endtime = '', '+2500'
	local a1, b1

	-- 1. Item of race, e.g. Tour de France = 'Q33881'
	-- 2. type of winner, names are the ones in variable t_s
	-- 3. and 4. start and end time. '+2500' means year 2500. Always beginning with a '+'
	-- 5. item of the jersey
	-- 6. item of the Wikipedia article of that jersey

	local data={{'Q33881', 'montagne', '+1975', '+2500', 'Q25265958', 'Q927157'}, -- Tour de France
				{'Q33881', 'leader', '+1919', '+2500', 'Q24257871', 'Q738903'},
				{'Q33881', 'points', '+1953', '+1967', 'Q24645209', 'Q175399'}, -- Jersey green.svg
				{'Q33881', 'points', '+1968', '+1968', 'Q26919974', 'Q175399'},	-- 	Jersey red.svg
				{'Q33881', 'points', '+1969', '+2500', 'Q24645209', 'Q175399'}, -- Jersey green.svg
				{'Q33881', 'jeune', '+1975', '+2500', 'Q24645383', 'Q2254180'}, -- Jersey white.svg
				{'Q33881', 'winner_fighting', '+2003', '+2500', 'Q27644113', 'Q2094179'}, -- Jersey red number.svg
				{'Q33881', 'winner_fighting2', '+2003', '+2500', 'Q27644113', 'Q2094179'}, -- Jersey red number.svg
				{'Q33881', 'equipe', '+2006', '+2500', 'Q27644112', 'Q1436680'},	-- Jersey yellow number.svg

				{'Q33861', 'leader', '+1931', '+2500', 'Q24257763', 'Q1164275'}, -- Giro d'Italia, Jersey pink.svg
				{'Q33861', 'points', '+1967', '+1968', 'Q26919974', 'Q641083'}, -- Jersey red.svg
				{'Q33861', 'points', '+1969', '+2009', 'Q26945272', 'Q641083'}, -- Jersey violet.svg
				{'Q33861', 'points', '+2010', '+2016', 'Q26919974', 'Q641083'}, -- Jersey red.svg
				{'Q33861', 'points', '+2017', '+2500', 'Q26945272', 'Q641083'}, -- Jersey violet.svg
				{'Q33861', 'montagne', '+1974', '+2011', 'Q24645209', 'Q641060'}, -- Jersey green.svg
				{'Q33861', 'montagne', '+2012', '+2500', 'Q24687409', 'Q641060'}, -- Jersey blue.svg
				{'Q33861', 'jeune', '+1976', '+2500', 'Q24645383', 'Q641662'}, -- Jersey white.svg

				{'Q33937', 'leader', '+1935', '+1936', 'Q24258056', 'Q3278226'}, -- Vuelta a España, Jersey orange.svg
				{'Q33937', 'leader', '+1941', '+1941', 'Q26696171', 'Q640430'}, -- Jersey white.svg
				{'Q33937', 'leader', '+1942', '+1942', 'Q24258056', 'Q3278226'}, -- Jersey orange.svg
				{'Q33937', 'leader', '+1945', '+1945', 'Q24257872', 'Q2534046'}, -- Jersey red.svg
				{'Q33937', 'leader', '+1946', '+1950', 'Q26696171', 'Q640430'}, -- Jersey white.svg
				{'Q33937', 'leader', '+1955', '+1976', 'Q24257871', 'Q738903'}, -- Jersey yellow.svg
				{'Q33937', 'leader', '+1977', '+1977', 'Q24258056', 'Q3278226'}, -- Jersey orange.svg
				{'Q33937', 'leader', '+1978', '+1998', 'Q24257871', 'Q738903'}, -- Jersey yellow.svg
				{'Q33937', 'leader', '+1999', '+2009', 'Q24257991', 'Q27665179'}, -- Jersey gold.svg
				{'Q33937', 'leader', '+2010', '+2500', 'Q24257872', 'Q2534046'}, -- Jersey red.svg
				{'Q33937', 'points', '+1945', '+1986', 'Q24687409', 'Q2746711'}, -- Jersey blue.svg
				{'Q33937', 'points', '+1987', '+1989', 'Q24645209', 'Q11638007'}, -- Jersey green.svg
				{'Q33937', 'points', '+1990', '+2009', 'Q24687409', 'Q2746711'}, -- Jersey blue.svg
				{'Q33937', 'points', '+2010', '+2500', 'Q24645209', 'Q11638007'}, -- Jersey green.svg
				{'Q33937', 'montagne', '+1935', '+1985', 'Q27670182', 'Q11638007'}, -- Jersey green.svg
				{'Q33937', 'montagne', '+1986', '+1986', 'Q27670174', 'Q3278226'}, -- Jersey orange.svg
				{'Q33937', 'montagne', '+1987', '+1987', 'Q27670178', 'Q2534046'}, -- Jersey red.svg
				{'Q33937', 'montagne', '+1988', '+1989', 'Q27670105', 'Q27670115'}, -- Jersey blackdots.png
				{'Q33937', 'montagne', '+1990', '+2005', 'Q27670182', 'Q11638007'}, -- Jersey green.svg
				{'Q33937', 'montagne', '+2006', '+2008', 'Q27670174', 'Q3278226'}, -- Jersey orange.svg
				{'Q33937', 'montagne', '+2009', '+2009', 'Q27670126', 'Q27670163'}, -- Jersey granate.svg
				{'Q33937', 'montagne', '+2010', '+2500', 'Q25265959', 'Q27670167'}, -- Jersey bluedots.svg

				{'Q2091354', 'leader', '+2011', '+2500', 'Q24257871', 'Q30020298'}, -- Tour of Norway, Jersey yellow.svg
				{'Q2091354', 'points', '+2011', '+2500', 'Q24645209', 'Q30020298'}, -- Jersey green.svg
				{'Q2091354', 'montagne', '+2011', '+2015', 'Q25265958', 'Q30020298'}, -- Jersey polkadot.svg
				{'Q2091354', 'montagne', '+2016', '+2500', 'Q27670174', 'Q30020298'}, -- Jersey orange.svg
				{'Q2091354', 'jeune', '+2011', '+2500', 'Q24645383', 'Q30020298'}, -- Jersey white.svg
				{'Q2091354', 'winner_fighting', '+2017', '+2500', 'Q29957114', 'Q30020298'}, -- MaillotCyan.PNG
				{'Q128713', 'leader', '+2013', '+2500', 'Q24257871', 'Q30020299'}, -- Tour des Fjords, Jersey yellow.svg
				{'Q128713', 'points', '+2013', '+2014', 'Q24645209', 'Q30020299'}, -- Jersey green.svg
				{'Q128713', 'points', '+2015', '+2500', 'Q24687409', 'Q30020299'}, -- Jersey blue.svg
				{'Q128713', 'montagne', '+2013', '+2500', 'Q25265958', 'Q30020299'}, -- Jersey polkadot.svg
				{'Q128713', 'jeune', '+2013', '+2500', 'Q24645383', 'Q30020299'}, -- Jersey white.svg
				{'Q128713', 'winner_fighting', '+2015', '+2015', 'Q30035038', 'Q30020299'}, -- Jersey green.svg
				{'Q128713', 'winner_fighting', '+2016', '+2500', 'Q30035039', 'Q30020299'}, -- Jersey orange.svg
				{'Q128961', 'leader', '+2013', '+2500', 'Q24687408', 'Q30020300'}, -- Arctic Race of Norway, Jersey blue.svg
				{'Q128961', 'points', '+2013', '+2500', 'Q24645209', 'Q30020300'}, -- Jersey green.svg
				{'Q128961', 'montagne', '+2013', '+2014', 'Q27670178', 'Q30020300'}, -- Jersey red.svg
				{'Q128961', 'montagne', '+2015', '+2500', 'Q27670174', 'Q30020300'}, -- Jersey orange.svg
				{'Q128961', 'jeune', '+2013', '+2500', 'Q24645383', 'Q30020300'}, -- Jersey white.svg
				{'Q128961', 'winner_fighting', '+2014', '+2500', 'Q27644113', 'Q30020300'}, -- Jersey red number.svg
				{'Q17619325', 'leader', '+2014', '+2014', 'Q24257871', 'Q30020302'}, -- Ladies Tour of Norway, Jersey yellow.svg
				{'Q17619325', 'leader', '+2015', '+2016', 'Q26945272', 'Q30020302'}, -- Jersey violet.svg
				{'Q17619325', 'leader', '+2017', '+2500', 'Q24257871', 'Q30020302'}, -- Jersey yellow.svg
				{'Q17619325', 'points', '+2014', '+2500', 'Q24645209', 'Q30020302'}, -- Jersey green.svg
				{'Q17619325', 'montagne', '+2014', '+2500', 'Q25265958', 'Q30020302'}, -- Jersey polkadot.svg
				{'Q17619325', 'jeune', '+2014', '+2500', 'Q24645383', 'Q30020302'}, -- Jersey white.svg
				{'Q17619325', 'winner_fighting', '+2016', '+2500', 'Q30035039', 'Q30020302'}} -- Jersey orange.svg

	--timeofrace = '+1968-07-01T00:00:00Z'
	timeofrace = string.sub(timeofrace, string.find(timeofrace,  "+%d%d%d%d"))
	for k, v in pairs(item) do
		for key, value in pairs(data) do
			if v == value[1] then
				if winner_classification == value[2] then
					if (timeofrace >= value[3]) and (timeofrace <= value[4]) then
						jersey = value[5]
						jerseyWPID = value[6]
					end
				end
			end
		end
	end

	if jersey ~= '' then --and (timeofrace > starttime) and (timeofrace < endtime) then
		local entity_jersey = mw.wikibase.getEntity(jersey)
		jersey_name = mw.wikibase.label(jersey)
		jersey = entity_jersey.claims['P18'][1].mainsnak.datavalue.value
		if jerseyWPID ~= '' then
			local Sitelink = mw.wikibase.sitelink ( jerseyWPID ) -- link to WParticle
			if Sitelink~= nil then jerseyWPID = Sitelink else jerseyWPID = '' end
		end
		return jersey, jersey_name, jerseyWPID
	else return '', '', ''
	end
end

function p.stageinfobox(frame)
	local vvv= ''
	local tab
	local entityId = frame.args[1]
	local timeofrace
	local a1, b1, c1, a2, b2, a3, b3
	local jerseyWPID, jersey_name
	local t_g = {show=true, name='', icon='', picture='', caption='', course= '', race={}, is_a='', startplace='', endplace='', time='',
		length='', length_unit='', speed='', speed_unit='', nr_participants_start="", nr_participants_end='', country={},
		series_ordinal_previous="", series_ordinal_next="", map='', sectional_view='',previous="", next=""}
	local t_s = {order={'results', 'classement_gen', 'classement_annex'},
		results={show=false, header="stage_results", order = {'first','second','third','winner_fighting','winner_fighting2','cima_coppi','cima_pantani'},
			-- name rider, translate name, gender, jersey, team name, time, time gap, points, speed, rank
			first={"", "winner", "", '', "", "", '', '', '', ''},
			second={"", "second", "", '', '', "", '', '', '', ''},
			third={"", "third", "", '', '', "", '', '', '', ''},
			winner_fighting={"", "combative", "", '', '', '', '', '', '', ''},
			winner_fighting2={"", "combative", "", '', '', '', '', '', '', ''}, -- two winner_fighting possible
			cima_coppi={"", "cima_coppy", "", '', '', '', '', '', '', ''},
			cima_pantani={"", "cima_pantani", "", '', '', '', '', '', '', ''}},

		classement_gen={show=false, header="general_class_stage", order = {"leader", "deuxieme", "troisieme"},
			-- name rider, translate name, gender, jersey, team name, time, time gap, points, speed, rank
			leader={"", "leader", "", '', "", "", '', '', '', ''},
			deuxieme={"", "second", "", '', '', "", '', '', '', ''},
			troisieme={"", "third", "", '', '', "", '', '', '', ''}},

		classement_annex={show=false, header="second_class_stage", order={"points","montagne","sprints","jeune","super_combatif","combine",
			"stage_volantes","regularite","azzurri_ditalia","fuga_pinarello","equipe","equipe_points"},
			-- name rider, translation name, gender, jersey, team name, time, time gap, points, speed, rank
			points={"", "points", "", '', "", '', "", '', '', ''},
			montagne={"", "mountain", "", '', '', '', "", '', '', ''},
			sprints={"", "sprints", "", '', '', '', "", '', '', ''},
			jeune={"", "young", "", '', '', '', '', '', '', ''},
			super_combatif={"", "combativity", "", '', "", "", '', '', '', ''},
			combine={"", "combinated", "", '', '', "", '', '', '', ''},
			stage_volantes={"","metas_volantes",'','','','','','', '', ''},
			regularite={"","regularity",'','','','','','', '', ''},
			azzurri_ditalia={"","azzuri_d_italia",'','','','','','', '', ''},
			fuga_pinarello={"","fuga_pinarello",'','','','','','', '', ''},
			equipe={"", "team", "", '', '', "", '', '', '', ''},
			equipe_points={"", "team_by_points", "", '', '', '', '', '', '', ''}}
		}

	if type( entityId ) ~= 'string' then error( 'parameter must be a string') end
	if not entityId:match( 'Q%d+' ) then error ( 'parameter must be a valid Wikidata item (ex: Q42)' ) end
	local entity = mw.wikibase.getEntity( entityId )

	t_g.name = mw.wikibase.label(entityId) or ''
	if wiki == 'fr' and t_g.name ~= '' then t_g.name= mw.ustring.gsub(t_g.name, "^(%d+)([re]+)", "%1<sup>%2</sup> ") end
	t_g.name= mw.ustring.gsub(t_g.name, "^(%a)",function (x) return mw.ustring.upper(x) end)

	a1, b1 = pcall(fooA, 'numeric-id', entity, 'P31', 1) -- If stage is a "stage" or a timetrial stage
	if a1 == true and b1~=18131152 then t_g.is_a = 'Q'.. b1 end

	if t_g.is_a=='Q2266066' or t_g.is_a=='Q2348250' or t_g.is_a=='Q485321' then t_g.icon = " [[File:Cycling (track) pictogram.svg|35px]]"
	else t_g.icon = " [[File:Cycling (road) pictogram.svg|35px]]" end

	a1, b1 = pcall(fooA, 'value', entity, 'P18', 1) -- picture, legende
	if a1 == true and t_g.picture == "" then
		local v
		t_g.picture = b1
		if pcall(foo3, entity, "P18", 1, "P2096", 1) then
			for _, v in pairs(entity.claims["P18"]) do
				pcall(function()
					for num=1,#v.qualifiers["P2096"] do	-- find right language
						if v.qualifiers["P2096"][num].datavalue.value.language == langcode then
							t_g.caption = v.qualifiers["P2096"][num].datavalue.value.text end
					end
				end)
			end
		end
	end

	-- Function that give the starting place of a race
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', 1)
	if a1 == true and t_g.startplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', i)
		end
		t_g.startplace = "Q" .. b1
	end
	-- Function that give the finishing place of a race
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', 1)
	if a1 == true and t_g.endplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', i)
		end
		t_g.endplace = "Q" .. b1
	end

-- This function give a format to dates when P585 (date) is used in a single day race
	a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', 1)
	if a1 == true and t_g.time == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', i)
		end
		t_g.time = formatDate(b1, 'long')
		timeofrace = b1
	end

	-- Function that give the number of cyclists at the beginning and at the finishing of a race
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P1132', 1)
	if a1 == true and t_g.nr_participants_start == "" and t_g.nr_participants_end == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P1132', i)
		end
		local v
		for _, v in pairs(entity.claims["P1132"]) do
			if pcall(function()
		   		if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 529711 then
				t_g.nr_participants_start = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
				end
			) then else t_g.nr_participants_start = "" end
			if pcall(function()
				if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 12769393 then
				t_g.nr_participants_end = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
			end
			) then else t_g.nr_participants_end = "" end
		end
	end

	-- This function permits to display an unity (the kilometer) for a distance, with exceptions for macedionan, russian and japanese
	-- that have other symbols
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P3157', 1)
	if a1 == true and t_g.length == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P3157', i)
		end
		t_g.length = b1
		a1, b1, _ = pcall(fooA, 'unit', entity, 'P3157', 1)
		if b1 == "http://www.wikidata.org/entity/Q828224" then
			t_g.length_unit = l10n('unit_km')
		end
	end

	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2043', 1)
	if a1 == true and t_g.length == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2043', i)
		end
		t_g.length = b1
		a1, b1, _ = pcall(fooA, 'unit', entity, 'P2043', 1)
		if b1 == "http://www.wikidata.org/entity/Q828224" then
			t_g.length_unit = l10n('unit_km')
		end
	end
	-- This function permits to display an unity (the kilometer per hour) for an average speed, with exceptions for macedionan, russian and japanese
	-- that have other symbols
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2052', 1)
	if a1 == true and t_g.speed == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2052', i)
		end
		t_g.speed = b1
		a1, b1 = pcall(fooA, 'unit', entity, 'P2052', 1)
		if b1 == "http://www.wikidata.org/entity/Q180154" then
			t_g.speed_unit = l10n('unit_kmh')
		end
	end	-- if a1

	a1, b1 = pcall(fooA, 'numeric-id', entity, 'P17', 1) -- This function gives countries where the race take place
	if a1 == true then
		for i, v in pairs(entity.claims["P17"]) do
   			t_g.country[i] = "Q" .. v.mainsnak.datavalue.value["numeric-id"]
   		end
 	end

	a1, b1 = pcall(fooA, 'value', entity, 'P242', 1) -- locator map image
	if a1 == true and t_g.map == "" then t_g.map = b1 end
	a1, b1 = pcall(fooA, 'value', entity, 'P2713', 1) -- sectional view
	if a1 == true and t_g.sectional_view == "" then t_g.sectional_view = b1 end

	a1, b1 = pcall(fooA, 'numeric-id', entity, 'P155', 1)
	if a1 == true and t_g.previous == "" then
		t_g.previous = "Q"..b1
		a2, b2 = pcall(fooA, 'value', mw.wikibase.getEntity( t_g.previous ), 'P1545', 1)
		if a2 == true then t_g.series_ordinal_previous = b2 end
	end
	a1, b1 = pcall(fooA, 'numeric-id', entity, 'P156', 1)
	if a1 == true and t_g.next == "" then
		t_g.next = "Q"..b1
		a2, b2 = pcall(fooA, 'value', mw.wikibase.getEntity( t_g.next ), 'P1545', 1)
		if a2 == true then t_g.series_ordinal_next = b2 end
	end

	local t_P642 = {[20882747]={'results', 'first'}, [20882748]={'results', 'second'}, [20882749]={'results', 'third'}, [21686770]={'results', 'winner_fighting'},
			[2250962]={'results', 'cima_coppi'}, [10452933]={'results', 'cima_pantani'},
			[20882763]={'classement_gen', 'leader'}, [20882764]={'classement_gen', 'deuxieme'}, [20882765]={'classement_gen', 'troisieme'},
			[20883213]={'classement_annex', 'montagne'}, [20883140]={'classement_annex', 'jeune'}, [20883008]={'classement_annex', 'points'},
			[20883329]={'classement_annex', 'sprints'}, [20893984]={'classement_annex', 'super_combatif'}, [20965880]={'classement_annex', 'combine'},
			[27104688]={'classement_annex', 'stage_volantes'}, [27104684]={'classement_annex', 'regularite'}, [20882922]={'classement_annex', 'equipe'},
			[27104271]={'classement_annex', 'equipe_points'},
			[20882667]={'classement_gen', 'leader'}, [20882668]={'classement_gen', 'deuxieme'}, [20882669]={'classement_gen', 'troisieme'},
			[20883212]={'classement_annex', 'montagne'}, [20883139]={'classement_annex', 'jeune'}, [20883007]={'classement_annex', 'points'},
			[20883328]={'classement_annex', 'sprints'}, [20893983]={'classement_annex', 'super_combatif'}, [20893979]={'classement_annex', 'combine'},
			[27067359]={'classement_annex', 'stage_volantes'}, [27067170]={'classement_annex', 'regularite'},
			[27907747]={'classement_annex', 'azzurri_ditalia'}, [27907748]={'classement_annex', 'azzurri_ditalia'},
			[27907714]={'classement_annex', 'fuga_pinarello'}, [27907715]={'classement_annex', 'fuga_pinarello'},
			[20882921]={'classement_annex', 'equipe'}, [27104269]={'classement_annex', 'equipe_points'}
			}

	a1, b1 = pcall(fooA, 'numeric-id', entity, "P1346", 1)
	if a1 == true then
		local deprecated, qual, id, id_team, id_time, id_time_gap, id_speed, id_points_a, id_points_b
		for k, v in pairs(entity.claims["P1346"]) do
			id_team, id_speed, id_time, id_time_gap, id_points_a, id_points_b = '', '', '', '', '', ''
			a, b = pcall(fooC, 'numeric-id', entity, 'P1346', k, 'P54', 1)
			if a == true then id_team = 'Q'..b  end

			if pcall(function()
				id=v.mainsnak.datavalue.value['numeric-id'] -- id = rider id
				deprecated = entity.claims["P1346"][k].rank
				end) then
			else id=nil end
			if id ~= nil then
				--timeofrace = "+2016-03-00T00:00:00Z"
				-- function timeStartEnd finds the team of the rider at the time (timeofrace) of the race
				if id_team == '' and timeofrace ~= nil and timeofrace ~= '' then
					a, b = timeStartEnd('Q'..id, 'P54', 'numeric-id', timeofrace)
					if a == true and b ~= nil then id_team = 'Q' .. b end
				end

				-- looks into race item if the winner has a P54 statement for beeng a member of a national team
				pcall(function()
					for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P54']) do
						id_team = national_team('Q'..id, timeofrace, entity, 'P1346', k) -- timeofrace -> startOfSeason ?????
						if id_team == nil then id_team = '' end
					end
				end)

		   		pcall(function() -- for property 'race time'
					for _, v in pairs(entity.claims['P1346'][k].qualifiers['P2781']) do
			   			id_time = tonumber(v.datavalue.value.amount)
					end
				end)

	   			pcall(function() -- for property 'time gap'
					for _, v in pairs(entity.claims['P1346'][k].qualifiers['P2911']) do
	   					id_time_gap = tonumber(v.datavalue.value.amount)
					end
				end)

		   		pcall(function() -- for property 'speed'
					for _, v in pairs(entity.claims['P1346'][k].qualifiers['P2052']) do
			   			id_speed = tonumber(v.datavalue.value.amount)
					end
				end)

				pcall(function() -- for property 'points for'
					for _, v in pairs(entity.claims['P1346'][k].qualifiers['P1358']) do
		   				id_points_a = tonumber(v.datavalue.value.amount)
					end
				end)

				pcall(function() -- for property 'number of points/goals/set scored'
					for _, v in pairs(entity.claims['P1346'][k].qualifiers['P1351']) do
		   				id_points_b = tonumber(v.datavalue.value.amount)
					end
				end)

				-- looks into race item if the winner has a P642 statement for showing the type of winner (points, mountain, ..)
				pcall(function()
					for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P642']) do
						qual=vv.datavalue.value['numeric-id']

						if id~=nil and qual~=nil and v.rank~='deprecated' then
							if qual==21686770 and t_s['results']['winner_fighting'][1] ~= '' then t_P642[qual][2] = 'winner_fighting2' end
							pcall(function() -- inserts WD data into table t_s
								t_s[t_P642[qual][1]][t_P642[qual][2]][1]='Q'..id
								t_s[t_P642[qual][1]][t_P642[qual][2]][5]=id_team
								t_s[t_P642[qual][1]][t_P642[qual][2]][10]=deprecated
								if id_time~='' then t_s[t_P642[qual][1]][t_P642[qual][2]][6]=id_time end
								if id_time_gap~='' then t_s[t_P642[qual][1]][t_P642[qual][2]][7]=id_time_gap end
								if id_points_a~='' then t_s[t_P642[qual][1]][t_P642[qual][2]][8]=id_points_a end
								if id_points_b~='' then t_s[t_P642[qual][1]][t_P642[qual][2]][8]=id_points_b end
								if id_speed~='' then t_s[t_P642[qual][1]][t_P642[qual][2]][9]=id_speed end
							end)
							if qual==27104271 and t_s.classement_annex.equipe_points[1]=='' then t_s.classement_annex.equipe_points[1]='Q'..id end
							if qual==20882922 and t_s.classement_annex.equipe[1]=='' then t_s.classement_annex.equipe[1]='Q'..id end

							a1, b1 = pcall(fooA, 'numeric-id', mw.wikibase.getEntity('Q'..id), 'P21', 1)  -- detect gender
							if a1 == true then
								if b1 == 6581097 then t_s[t_P642[qual][1]][t_P642[qual][2]][3] = 'm' -- men
								elseif b1 == 6581072 then t_s[t_P642[qual][1]][t_P642[qual][2]][3] = 'f' -- female
								end
							else t_s[t_P642[qual][1]][t_P642[qual][2]][3] = 'f' -- female
							end
	 					end
					end
				end)
			end
		end
	end
	local rank, deprecated
	local order = {'first', 'second', 'third'}
	local property = 'P2417'
	a1, b1 = pcall(fooA, 'numeric-id', entity, property, 1)
	if a1 == true then
		for k, _ in pairs(entity.claims[property]) do -- look into P2417, stage classification
			for _, v in pairs(entity.claims[property][k].qualifiers['P1352']) do -- for property 'rank'
				rank = tonumber(v.datavalue.value.amount)
				deprecated = entity.claims[property][k].rank
			end
			if rank == 1 or rank == 2 or rank == 3 then
				t_s.results[order[rank]][10] = deprecated
				if t_s.results[order[rank]][1] == '' or t_s.results[order[rank]][10] == 'normal'  then -- name or rider / team
					t_s.results[order[rank]][1] = 'Q' .. entity.claims[property][k].mainsnak.datavalue.value['numeric-id']
					if t_s.results[order[rank]][7] == '' and t_s.results[order[rank]][6] == '' then
						pcall(function()
							for _, v in pairs(entity.claims[property][k].qualifiers['P2911']) do -- for property 'time gap'
								t_s.results[order[rank]][7] = tonumber(v.datavalue.value.amount)
							end
						end)
					end
					if t_s.results[order[rank]][7] == '' and t_s.results[order[rank]][6] == '' then
						pcall(function()
							for _, v in pairs(entity.claims[property][k].qualifiers['P2781']) do -- for property 'race time'
								t_s.results[order[rank]][6] = tonumber(v.datavalue.value.amount)
							end
						end)
					end
					if t_s.results[order[rank]][9] == '' then
						pcall(function()
							for _, v in pairs(entity.claims[property][k].qualifiers['P2052']) do -- for property 'speed'
								t_s.results[order[rank]][9] = tonumber(v.datavalue.value.amount)
							end
						end)
					end
					a1, b1 = pcall(fooA, 'numeric-id', mw.wikibase.getEntity(t_s.results[order[rank]][1]), 'P21', 1)  -- detect gender
					if a1 == true then
						if b1 == 6581097 then t_s.results[order[rank]][3] = 'm' -- men
						elseif b1 == 6581072 then t_s.results[order[rank]][3] = 'f' -- female
						end
					else t_s.results[order[rank]][3] = 'f' -- female
					end
				end
			end
		end
	end
	order = {'leader', 'deuxieme', 'troisieme'}
	property = 'P2321'
	a1, b1 = pcall(fooA, 'numeric-id', entity, property, 1)
	if a1 == true then
		for k, _ in pairs(entity.claims[property]) do -- look into P2321, stage classification
			for _, v in pairs(entity.claims[property][k].qualifiers['P1352']) do -- for property 'rank'
				rank = tonumber(v.datavalue.value.amount)
				deprecated = entity.claims[property][k].rank
			end
			if rank == 1 or rank == 2 or rank == 3 then
				t_s.classement_gen[order[rank]][10] = deprecated
				if t_s.classement_gen[order[rank]][1] == '' or t_s.classement_gen[order[rank]][10] == 'normal'  then -- name or rider / team
					t_s.classement_gen[order[rank]][1] = 'Q' .. entity.claims[property][k].mainsnak.datavalue.value['numeric-id']
					if t_s.classement_gen[order[rank]][7] == '' and t_s.classement_gen[order[rank]][6] == '' then
						pcall(function()
							for _, v in pairs(entity.claims[property][k].qualifiers['P2911']) do -- for property 'time gap'
								t_s.classement_gen[order[rank]][7] = tonumber(v.datavalue.value.amount)
							end
						end)
					end
					if t_s.classement_gen[order[rank]][7] == '' and t_s.classement_gen[order[rank]][6] == '' then
						pcall(function()
							for _, v in pairs(entity.claims[property][k].qualifiers['P2781']) do -- for property 'race time'
								t_s.classement_gen[order[rank]][6] = tonumber(v.datavalue.value.amount)
							end
						end)
					end
					if t_s.classement_gen[order[rank]][9] == '' then
						pcall(function()
							for _, v in pairs(entity.claims[property][k].qualifiers['P2052']) do -- for property 'speed'
								t_s.classement_gen[order[rank]][9] = tonumber(v.datavalue.value.amount)
							end
						end)
					end
					a1, b1 = pcall(fooA, 'numeric-id', mw.wikibase.getEntity(t_s.classement_gen[order[rank]][1]), 'P21', 1)  -- detect gender
					if a1 == true then
						if b1 == 6581097 then t_s.classement_gen[order[rank]][3] = 'm' -- men
						elseif b1 == 6581072 then t_s.classement_gen[order[rank]][3] = 'f' -- female
						end
					else t_s.classement_gen[order[rank]][3] = 'f' -- female
					end
				end
			end
		end
	end

	if t_g.length ~= "" then
		t_g.length, _ = string.gsub(t_g.length, "[+]", "") -- delets "+" sign
		t_g.length = lang:formatNum(tonumber(t_g.length)) -- formats t_g.length in the way it is done in the local Wiki
		if langcode == 'fo' then t_g.length = string.gsub(t_g.length, "%.", ",") end
	end
	if t_g.speed ~= "" then
		t_g.speed, _ = string.gsub(t_g.speed, "[+]", "")
		t_g.speed = lang:formatNum(tonumber(t_g.speed))
		if langcode == 'fo' then t_g.speed = string.gsub(t_g.speed, "%.", ",") end
	end

   	local span1, span2 = "<span style='color:#3366CC'>&#x25C0; </span>", "<span style='color:#3366CC'> &#x25B6;</span>"

	if t_g.series_ordinal_previous ~= '' then
		local label_previous = stageLink(t_g.series_ordinal_previous)
		if t_g.series_ordinal_previous == "0" then label_previous = i10n('prolog') end
		if mw.wikibase.sitelink( t_g.previous ) ~= nil then
   			local k = transform(t_g.previous,'Q', timeofrace)
			local i, _ = string.find(k, "|")
			local j, _ = string.find(k, "]")
			if i ~= nil and j ~= nil then
				t_g.previous = string.sub(k, 1, i) .. span1 .. label_previous .. string.sub(k, j)
			else t_g.previous = span1 .. label_previous end
		else t_g.previous = span1 .. label_previous end
	else t_g.previous = ''
	end

	if t_g.series_ordinal_next~= '' then
		local label_next = stageLink(t_g.series_ordinal_next)
		if t_g.series_ordinal_next == "0" then label_next = i10n('prolog') end
		if mw.wikibase.sitelink( t_g.next ) ~= nil then
   			local k = transform(t_g.next,'Q', timeofrace)
			local i, _ = string.find(k, "|")
			local j, _ = string.find(k, "]")
			if i ~= nil and j ~= nil then
				t_g.next = string.sub(k, 1, i) .. label_next.. span2 .. string.sub(k, j)
			else t_g.next = label_next.. span2 end
		else t_g.next = label_next.. span2 end
	else t_g.next = ''
	end

	if t_g.course== '' then
		a1, b1 = pcall(fooA, 'value', entity, 'P1545', 1)
		if a1 == true then
			local label = stageLink(b1)
			if b1 == "0" then label = i10n('prolog') end
			t_g.course = label
			a2, b2 = pcall(fooA, 'numeric-id', entity, 'P361', 1)
			if a2 == true then
				t_g.course = t_g.course .. ', '.. WPlink('Q'..b2,'pure')
				--t_g.race = 'Q'..b2

				local entity_race = mw.wikibase.getEntity('Q'..b2)
				a3, b3 = pcall(fooA, 'numeric-id', entity_race, 'P31', 1)
 				if a3 == true then
					for k, v in pairs(entity_race.claims["P31"]) do
						t_g.race[k] = 'Q'..v.mainsnak.datavalue.value["numeric-id"]
					end
				end
			end
		end
	end

	if t_s.results.first[1]~='' or t_s.results.second[1]~='' or t_s.results.third[1]~='' or t_s.results.winner_fighting[1]
		then t_s.results.show = true end
	if t_s.classement_gen.leader[1]~='' or t_s.classement_gen.deuxieme[1]~='' or t_s.classement_gen.troisieme[1]~=''
		then t_s.classement_gen.show = true end
	if t_s.classement_annex.points[1]~='' or t_s.classement_annex.montagne[1]~='' or t_s.classement_annex.sprints[1]~='' or t_s.classement_annex.jeune[1]~='' or
		t_s.classement_annex.super_combatif[1]~='' or t_s.classement_annex.combine[1]~='' or t_s.classement_annex.stage_volantes[1]~='' or
		t_s.classement_annex.regularite[1]~='' or t_s.classement_annex.azzurri_ditalia[1]~='' or t_s.classement_annex.fuga_pinarello[1]~='' or
		t_s.classement_annex.equipe[1]~='' or t_s.classement_annex.equipe_points[1]~='' then t_s.classement_annex.show = true end

	function stage_icon(x)
 		if x=='Q20646667' then return "[[File:Plainstage.svg|20px]] " end
 		if x=='Q20646670' then return "[[File:Hillystage.svg|20px]] " end
  		if x=='Q20680270' then return "[[File:Mediummountainstage.svg|20px]] " end
  		if x=='Q20646668' then return "[[File:Mountainstage.svg|20px]] " end
  		if x=='Q20679712' then return "[[File:Mountain Time Trial Stage.svg|20px]] " end
		if x=='Q2348250' then return "[[File:Team Time Trial Stage.svg|20px]] " end
   		if x=='Q2266066' then return "[[File:Time Trial.svg|20px]] " end
   		if x=='Q485321'  then return "[[File:Time Trial.svg|20px]] " end
   		return ''
	end

	local width= '320px' -- size standard 320px, special 340px
	if l10nDef.width_stageinfobox ~= nil then width = l10nDef.width_stageinfobox end

 	tab = "<table border='0' cellpadding='4' cellspacing='0' style='float:right; max-width:"..width.."; border:1px solid rgb(200,200,200);"
	tab = tab .. "margin:0 0 0.5em 0.5em; background-color:rgb(255, 255, 255); color:black; padding:5px; clear:left; "
	tab = tab .. "text-align:left; font-size:85%; line-height:1.6em;'>"
	tab = tab .. "<tr><td colspan='2' style='border-bottom:5px solid white; font-size:175%; background:#FFE7A0; text-align:center'>"
	tab = tab .. "<table style='width:100%'><tr><td>" .. t_g.name .."</td><td>" .. t_g.icon .. "</td></tr></table></td></tr>"

	if t_g.picture ~= "" then tab = tab .. "<tr><td colspan='2' style='text-align:center'>".." [[File:".. t_g.picture .."|center|300px]]</td></tr>" end
	if t_g.picture ~= "" and t_g.caption ~= "" then tab = tab .. "<tr><td colspan='2' style='text-align:center; font-size:80%'>"..t_g.caption.."</td></tr>" end
	if t_g.course~="" or t_g.is_a~="" or t_g.time~="" or t_g.length~="" or t_g.startplace~="" or t_g.endplace~="" then
		tab=tab.."<tr><td colspan='2' style='background-color:#FFE7A0; text-align:center'>'''" .. l10n('race_details') .. "'''</td></tr>" end
	if t_g.course ~= "" then tab = tab.."<tr><td>'''"..l10n('race').."'''</td><td>" .. t_g.course .. "</td></tr>" end
	if t_g.is_a ~= "" then tab = tab.."<tr><td>'''"..l10n('type').."'''</td><td>" ..stage_icon(t_g.is_a).. WPlink(t_g.is_a,'pure').. "</td></tr>" end
	if t_g.time~="" then tab = tab.."<tr><td>'''"..l10n('date').."'''</td><td>" .. t_g.time.."</td></tr>" end
	if t_g.length ~= "" then tab = tab.."<tr><td>'''"..l10n('distance').."'''</td><td>" .. t_g.length.." "..t_g.length_unit.."</td></tr>" end
	if t_g.startplace ~= "" then tab = tab.."<tr><td>'''"..l10n('journey_origin').."'''</td><td>" .. WPlink(t_g.startplace,'pure').. "</td></tr>" end
	if t_g.endplace ~= "" then tab = tab.."<tr><td>'''"..l10n('journey_destination').."'''</td><td>" .. WPlink(t_g.endplace,'pure').. "</td></tr>" end
	if t_g.country ~= nil then for i=1,#t_g.country do t_g.country[i] = flag(t_g.country[i], timeofrace).." ".. WPlink( t_g.country[i],'pure') end end
	if t_g.country[1] ~= nil then tab = tab.."<tr><td style= 'vertical-align:top'>'''"
		if #t_g.country == 1 then tab = tab..l10n('country').."'''</td><td>" else tab = tab..l10n('countries').."'''</td><td>" end
		for i=1,#t_g.country-1 do tab = tab .. t_g.country[i].."<br>" end tab = tab .. t_g.country[#t_g.country].."</td></tr>" end
	if t_g.nr_participants_start ~= "" then tab = tab.."<tr><td>'''"..l10n('starting_riders').."'''</td><td>" .. t_g.nr_participants_start .. "</td></tr>" end
	if t_g.nr_participants_end ~= "" then tab = tab.."<tr><td>'''"..l10n('arriving_riders').."'''</td><td>" .. t_g.nr_participants_end .. "</td></tr>" end
	if t_g.speed ~= "" then tab = tab.."<tr><td>'''"..l10n('average_speed').."'''</td><td>" .. t_g.speed .. " "..t_g.speed_unit.."</td></tr>" end

	for _, value_order in ipairs(t_s.order) do
		if t_s[value_order].show == true then -- if a section of the stageinfobox should be shown
			tab=tab.."<tr><td colspan='2'>"
			tab=tab.."<table border='0' cellpadding='0' cellspacing='0' style='width:100%'>"
			tab=tab.."<tr><td colspan='3' style='border-bottom:5px solid #fff2cc; background-color:#FFE7A0; text-align:center'>'''"..
				l10n(t_s[value_order].header).."'''</td></tr>"

			for key, value in ipairs(t_s[value_order].order) do
				if t_s[value_order][value][1]~="" then
					a1, jersey_name, jerseyWPID  = jersey(value, t_g.race, timeofrace)
					if a1~='' then t_s[value_order][value][4] = a1 end
					if t_s[value_order][value][9] ~= '' then
						t_s[value_order][value][9] = '('.. lang:formatNum(t_s[value_order][value][9])..l10n('unit_kmh')..')'
						if langcode == 'fo' then t_s[value_order][value][9] = string.gsub(t_s[value_order][value][9], "%.", ",") end
					end
					if t_s[value_order][value][8] ~= '' then
						if t_s[value_order][value][8] > 1 then t_s[value_order][value][8] = t_s[value_order][value][8]..l10n('unit_pts')
						else t_s[value_order][value][8] = t_s[value_order][value][8]..l10n('pt') end end
					local title, k =mw.ustring.gsub(l10n(t_s[value_order][value][2]), " ", "&nbsp;")
					if k > 0 then title=mw.ustring.gsub(title, "&nbsp;", "<br>", 1) end --&#32;
					if t_s[value_order][value][5]=="" and t_s[value_order][value][9] =="" then
						tab=tab.."<tr style='vertical-align:top;'><td style='width:1%;background-color:#fff2cc;text-align:left;padding:0 2px 0 2px;white-space:nowrap'>'''"
					else tab=tab.."<tr style='vertical-align:top;'><td rowspan='2' style='width:1%;background-color:#fff2cc;text-align:left;padding:0 2px 0 2px;white-space:nowrap'>'''"
					end
					if value_order~='classement_annex' and t_s[value_order][value][2]~=40 and t_s[value_order][value][2]~=41 then -- Cima Coppi, Cima Pantani with a line break
						if t_s[value_order][value][4] == "" then
							if (value_order=='results') and (value=='winner_fighting' or value=='winner_fighting2' or value=='cima_coppi' or value=='cima_pantanii') then
								tab=tab..l10n(t_s[value_order][value][2])
							else tab=tab .. number(key, t_s[value_order][value][3]) end
						else
							if jerseyWPID=='' then tab=tab.."[[File:"..t_s[value_order][value][4].."|20px|"..title.."]]"
							else tab=tab.."[[File:"..t_s[value_order][value][4].."|20px|"..title.."|link="..jerseyWPID.."]]" end
						end
					else
						if t_s[value_order][value][4] == "" then tab=tab..title
						else
							if jerseyWPID=='' then
								if jersey_name ~= '' then
									tab=tab.."[[File:"..t_s[value_order][value][4].."|20px|"..jersey_name.."]]" .. title
								else
									tab=tab.."[[File:"..t_s[value_order][value][4].."|20px]]" .. title
								end
							else
								tab=tab.."[[File:"..t_s[value_order][value][4].."|20px|link="..jerseyWPID.."]]" .. title
							end
						end
					end
					if t_s[value_order][value][10] == 'deprecated' then
						tab=tab.."</span>".. "'''</td><td style='padding:0 0.5em 0 0.5em'>".. '<s>' .. transform(t_s[value_order][value][1],'f', timeofrace) .. '</s>'
					else tab=tab.."</span>".. "'''</td><td style='padding:0 0.5em 0 0.5em'>".. transform(t_s[value_order][value][1],'f', timeofrace) end
					tab=tab.."</td><td style='text-align:right;font-size:85%;white-space:nowrap'>"
					if t_s[value_order][value][6]~='' then tab=tab.. calculate_time(t_s[value_order][value][6]) end
					if t_s[value_order][value][7]~='' then tab=tab..'+ '.. calculate_time(t_s[value_order][value][7]) end
					tab= tab.. t_s[value_order][value][8]..  "</td></tr>"
				end

				if t_s[value_order][value][5]~="" and t_s[value_order][value][9] ~="" then -- team row
					tab=tab.."<tr><td colspan='2'>"
					tab = tab.. "<table border='0' cellpadding='0' cellspacing='0' style='width:100%'>"
					tab = tab.. "<tr><td style='width:100%;text-align:left;padding-left:2px'>("..transform(t_s[value_order][value][5],'t', timeofrace)..
						")</td><td style='font-size:85%;vertical-align:top;white-space:nowrap'>"..t_s[value_order][value][9] .. "</td></tr></table>"
				else
					if t_s[value_order][value][5]~="" or t_s[value_order][value][9] ~="" then -- team row
						tab=tab.."<tr><td colspan='2' style='text-align:left;padding-left:2px'>"
						if t_s[value_order][value][5] ~= '' then tab=tab..'('..transform(t_s[value_order][value][5],'t', timeofrace)..')' end
						tab = tab..  '<span style="float:right;font-size:85%;">'.. t_s[value_order][value][9].."</span></td></tr>"
					end
				end
			end
			tab=tab.. "</table></td></tr>"
		end
	end

	if t_g.map ~= "" then tab = tab .. "<tr><td colspan='2' style='text-align:center'>".." [[File:".. t_g.map .."|center|300px]]".."</td></tr>" end
	if t_g.sectional_view ~= "" then tab = tab .. "<tr><td colspan='2' style='text-align:center'>".." [[File:".. t_g.sectional_view .."|center|300px]]".."</td></tr>" end
	tab = tab.."<tr><td>"..t_g.previous.."</td><td style='text-align:right'>" .. t_g.next .. "</td></tr>"
	local s = "d:Wikidata:WikiProject Cycling/Documentation/stageinfobox"
	tab = tab .. "<tr><td colspan='2' style='text-align:right; border-top:3px solid #FFDF80; font-size:75%'>".. --infobox_bottom(1)
		"[[" .. s .. "|" .. l10n('documentation').. "]] [[File:Wikidata-logo S.svg|12px|link=d:".. frame.args[1]  .. "]]"
	tab = tab .. "</span></td></tr>"
	tab= tab.."</table>"
	return tab
end

function transform(q_number, command, timeofrace)
	-- transforms Q/q-number into flag / WPlink / WDlink
	local wd = " [[File:Wikidata-logo S.svg|12px|link=d:"
	if not string.find(q_number, "^Q%d+") then return q_number end -- test if q_number is an item
	if command == "Q" then return WPlink( q_number ) end -- find variables with an item as value
	if command == 'q' then -- with WDitem icon
		--look into P27 (country of citizenship) to get the Qnumber of that country
		a, b = timeStartEnd(q_number, "P27", 'numeric-id', timeofrace)
		if a == true then return flag('Q'..b, timeofrace).." "..WPlink( q_number )..wd..q_number.."]]"
		else
			--look into P17 (country) to get the Qnumber of that country
			a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( q_number ), 'P17', 1)
			if a == true then return flag("Q"..b, timeofrace).." "..WPlink( q_number )..wd..q_number.."]]"
			else return WPlink( q_number )..wd..q_number.."]]" end
		end
	end
	if command == "f" then -- no WDitem icon
		--look into P27 (country of citizenship) to get the Qnumber of that country
		a, b = timeStartEnd(q_number, "P27", 'numeric-id', timeofrace)
		if a == true then return flag('Q'..b, timeofrace).." "..WPlink( q_number )
		else
			--look into P17 (country) to get the Qnumber of that country
			a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( q_number ), 'P17', 1)
			if a == true then return flag("Q"..b, timeofrace).." "..WPlink( q_number, 'team', timeofrace )
			else return WPlink( q_number, 'team', timeofrace ) end
		end
	end
	if command == "c" then return WPlink( q_number, "Q22348500" ) end -- find "class"-items
	if command == "t" then return WPlink( q_number, 'team', timeofrace ) end
	if command =="2t" then return q_number end
	return q_number
end

function p.listofteams(frame)
	local entity = mw.wikibase.getEntity( frame.args[1] )
	local mt = {}
	local tempID, k, u, v, v1, w, new, teamcategory, entity2, len, len2

	local startOfSeason = '' --'+2016-01-01T00:00:00Z'
	startOfSeason = getStartOfSeason(entity)

	v = ''
	mt[1] = {}
	mt[1][1], mt[1][2], mt[1][3] = '', 0, ''
	local mu = {}
	local a, b
	local cache = {}

	if pcall(fooA, 'numeric-id', entity, 'P1923', 1) == true then
		for k, v1 in pairs(entity.claims['P1923']) do
			new = true
			teamcategory, tempID, len = '', '', 0
			tempID = 'Q'.. v1.mainsnak.datavalue.value['numeric-id']
			entity2 = mw.wikibase.getEntity( tempID )
			cache[tempID] = entity2
			a, b = pcall(fooA, 'numeric-id', entity2, 'P31', 1)
			if a == true then teamcategory = 'Q'..b	else new = false end

			for w in pairs(mt) do
				len = table.getn(mt[w])
				if mt[w][1] == teamcategory then new=false mt[w][2]=mt[w][2]+1 len=len+1 mt[w][len]=tempID len2=len-2 end
			end
			if new == true then
				local size = table.getn(mt)
				mt[size+1] = {}
				mt[size+1][1] = teamcategory
				mt[size+1][2] = 1
				mt[size+1][3] = tempID
			end
		end
	end -- if pcall(fooA

	local ordering = {
		["Q6154783"] = 1, -- WorldTeam
		["Q20638319"] = 2, -- ProTeam
		["Q382927"] = 3, -- UCI Professional Continental Team
		["Q1756006"] = 4, -- UCI Continental Team
		["Q2466826"] = 5, -- UCI Women’s Team
		["Q23726798"] = 6, -- national cycling team
		["Q20738667"] = 6, -- national cycling team U23
		["Q28492441"] = 6, -- équipe cycliste nationale de marque
		["Q20639848"] = 7, -- club cycling team
		["Q20639847"] = 8, -- professional cycling team
		["Q20652655"] = 9, -- amateur cycling team
		["Q20653563"] = 10, -- Groupe Sportif I
		["Q20653564"] = 11, -- Groupe Sportif II
		["Q20653566"] = 12, -- Groupe Sportif III
		["Q26849121"] = 13 -- Women's amateur cycling team
	}

	local a, b, i, ii, jj
	for i=1, table.getn(mt) do
		mu[i] = {}
		mu[i]['index'] = 100
		mu[i]['val'] = ''
		if mt[i][1] ~= '' then
			if ordering[mt[i][1]] ~= nil then
				mu[i]['index'] = ordering[mt[i][1]]
			end
			if mt[i][2] == 1 then mu[i]['val'] = mu[i]['val'] .. '<span style="font-size:1.2em;font-weight:bold">'.. l10n(mt[i][1], mt[i][1]) ..'</span>'
			else mu[i]['val'] = mu[i]['val'] .. '<span style="font-size:1.2em;font-weight:bold">'.. l10n(mt[i][1] .. '_pl', mt[i][1]) .. '</span>'
			end
			if mt[i][2] > 3 then mu[i]['val'] = mu[i]['val'] .. ' <small>('..mt[i][2]..')</small>' end

			mu[i]['val'] = mu[i]['val'].. '<ol>'
			for w in pairs(mt[i]) do
				if w > 2 then
					mu[i]['val'] = mu[i]['val'] .. '<li style="text-indent:-1.5em;width:20em;display:inline-block;">'
					a, b = pcall(fooA, 'numeric-id', cache[mt[i][w]], 'P17', 1)
					if a == true then mu[i]['val'] = mu[i]['val'].. flag('Q'..b, startOfSeason).. ' ' end
					if mt[i][1] ~= 'Q23726798' and mt[i][1] ~= 'Q20738667' then mu[i]['val'] = mu[i]['val'].. WPlink(mt[i][w], 'team', startOfSeason).. '</li>'
					else
						national_team = cache[mt[i][w]]
						-- calculate s for national team item
						a, b = pcall(fooA, 'numeric-id', national_team, 'P31', 1) -- test if country
						if a == true and b == 20738667 then -- Q20738667 = national cycling team U23
							s = ' ' .. l10n('U23')
						else
							s = ''
						end

						a, b = pcall(fooA, 'numeric-id', national_team, 'P17', 1) -- test if country
						if a == true then
							nationality = l10n( 'Q' .. b, 'Q' .. b )
						else
							nationality = ''
						end

						if national_team:getSitelink() == nil then
							team = nationality .. s
						else
							team = WPlink(mt[i][w], 'team', startOfSeason)
							ii, jj = mw.ustring.find(team, '|')
							if ii ~= nil and jj ~= nil then
			 					jj=jj+1
	  							team = mw.ustring.sub(team, 1, ii) .. nationality .. s .. ']]'
							end
						end
						mu[i]['val'] = mu[i]['val'] ..  team .. '</li>'
					end
				end
			end
			mu[i]['val'] = mu[i]['val'] .. '</ol>'
		end --if mt[i][1] ~= ''
	end

	table.sort(mu, function(a,b) return a.index<b.index end)

	for i=1, table.getn(mu) do
		if mu[i].val ~= nil then v = v .. mu[i].val end
	end

	v = v .. '<table border="0" cellspacing="0" cellpadding="0" style="line-height:0em;width:20em;margin:0.5em 0em;border-top:2px solid #FFDF80;"><th>'..
	'<span style="float:left">[[File:Wikidata-logo S.svg|12px|link=d:'.. frame.args[1].. '#P1923]]</span></th></table>'

	return '<table style="max-width:95%; padding:0.5em; margin-right:1em; border:1px solid rgb(200,200,200)"><tr><td>' .. v .. '</td></tr></table>'
end

function number(number, gender)
	if number == '' then return '' end
	if l10nDef.numeration ~= nil then
		return l10nDef.numeration(number, gender)
	else
		return number .. '. '
	end
end

function calculate_time(t)
	local time = tonumber(t)
	local h, m, s = 0, 0, 0
	local str = ''

	if time == nil then return '' end
	if time < 60 then s = time
	elseif time < 3600 then m = math.modf(time/60) s = time - m*60
	else h = math.modf(time/3600) m = math.modf((time - h*3600)/60)  s = time - h*3600 - m*60
	end

	if h>0 then str = str..mw.ustring.format ('%i'..l10n('unit_h'), h) end
	if m>=0 and h>0 then str = str.. mw.ustring.format('%02i'..l10n('unit_min'), m) end
	if m>0 and h==0 then str = str.. mw.ustring.format('%i'..l10n('unit_min'), m) end
	if s>=0 and (h>0 or m>0) then str = str.. mw.ustring.format('%02i'..l10n('unit_sec'), s) end
	if s>=0 and h==0 and m==0 then str = str.. mw.ustring.format('%i'..l10n('unit_sec'), s) end
	return str --time..': '..h..' '..m..' '..s
end

function p.pointsclassification(frame)
	local s = {
		header_1 = 'points_classification', -- translation
		header_2 = {'rider', 'country', 'team', 'points'}, -- translations
		item = string.gsub(frame.args[1], "%c", ""),
		property = 'P3494', -- property to use for this table
		team_classification = false, -- it is not a team classification table, its a rider classification table
		background = 'color' -- there is a background color for the first row
		}
	return new_classification(frame, s)
end

function p.teamsclassificationbytime(frame)
	local s = {
		header_1 = 'teams_classification', -- translation
		header_2 = {'team', 'country', 'time'}, -- translations
		item = frame.args[1],
		property = 'P3497', -- property to use for this table
		team_classification = true, -- it is a team classification table, its not a rider classification table
		background = 'strong' -- there is no background color for the first row, but the first row is formated strong
		}
	return new_classification(frame, s)
end

function p.teamsclassificationbypoints(frame)
	local s = {
		header_1 = 'points_classification_for_teams', -- translation
		header_2 = {'team', 'country', 'points'}, -- translations
		item = frame.args[1],
		property = 'P3496', -- property to use for this table
		team_classification = true, -- it is a team classification table, its not a rider classification table
		background = 'strong' -- there is no background color for the first row, but the first row is formated strong
		}
	return new_classification(frame, s)
end

function p.stageclassification(frame)
	local s = {
		header_1 = 'stage_classification', -- translation
		header_2 = {'rider', 'country', 'team', 'time'}, -- translations
		item = frame.args[1],
		property = 'P2417', -- property to use for this table
		team_classification = false, -- it is not a team classification table, its a rider classification table
		background = false -- there is no background color for the first row
		}
	return new_classification(frame, s)
end

function p.generalclassification(frame)
	local s = {
		header_1 = 'general_classification', -- translation
		header_2 = {'rider', 'country', 'team', 'time'}, -- translations
		item = frame.args[1],
		property = 'P2321', -- property to use for this table
		team_classification = false, -- it is not a team classification table, its a rider classification table
		background = 'color' -- there is a background color for the first row
		}
	return new_classification(frame, s)
end

function p.teamtimetrialclassification(frame)
	local s = {
		header_1 = 'stage_classification', -- translation
		header_2 = {'team', 'country', 'time', 'time_gap', 'speed'}, -- translations
		item = frame.args[1],
		property = 'P2417', -- property to use for this table
		team_classification = true, -- it is a team classification table, its not a rider classification table
		background = false -- there is no background color for the first row
		}
	return new_classification(frame, s)
end

function new_classification(frame, s)
	local country = true
	if l10nDef.classification_showcountry ~= nil then country = l10nDef.classification_showcountry end

	local s = s
	local h = {
		rider={1, '', '', '', '', ''}, -- rank, rider ID, riderGender, nationality ID, flag ID, team ID
		jersey={''}, -- lots of jerseyID
		value={'', '', '', ''} -- points, time, time_gap, speed
		}
	local entity = mw.wikibase.getEntity( s.item )

	--[=[ It is possible to give the classification tables in the article commands to change the standard behaviour. They could look like this:
	{{Cycling race/teamsclassificationbytime|Q18574623|newline=false|country=true}}
	{{Cycling race/teamsclassificationbytime|Q18574623|country= false|newline=false}}
	{{Cycling race/teamsclassificationbypoints|Q18574623|newline =true|country=true}}
	{{Cycling race/teamsclassificationbypoints|Q18574623|newline= true}}
	{{Cycling race/teamsclassificationbypoints|Q18574623|newline = false|country=false}}
	{{Cycling race/teamsclassificationbytime|Q18574623|newline=true|country=true}}

	One additional parameter is "newline" with the values "true" or "false". "newline" says, if there is a line brake after the table. Standard is
	no line break after the tables stageclassification and teamtimetrialclassification.
	The second parameter is "country" with the values "true" or "false". "country" tells the module to print the country column or not.
	Most wikis have as standard to print the country columns, some wikis prefer as standard not to show the country column. A few lines above,
	the command "if wiki == 'da' then country = false end" tells that daWiki do not want to see the country colums as standard. You can add your wiki
	here in, if you do not want to see them as standard. With the new parameter editors are able to tell the module in the article what to do.
	]=]

	local function jersey(h)
		local jersey
		local jersey_name
		local jersey_string = ' '

		jerseys = {
			['Q24257871'] = 'Jersey yellow.svg',
			['Q24645209'] = 'Jersey green.svg',
			['Q24645383'] = 'Jersey white.svg'
		}

		if type(h) == 'table' and h[1] ~= '' then
			for i,k in ipairs(h) do
				pcall(function()
					if jerseys[h[i]] ~= nil then
						jersey = 'File:' .. jerseys[h[i]]
					else
						local entity_jersey = mw.wikibase.getEntity(h[i])
						jersey = 'File:' .. entity_jersey.claims['P18'][1].mainsnak.datavalue.value
					end
					jersey_name = l10n( h[i], h[i] )
					if jersey_name ~= '' then jersey_string = jersey_string .. '[[' .. jersey .. '|20px|' .. jersey_name .. ']]'
					else jersey_string = jersey_string .. '[[' .. jersey .. '|20px]]'
					end
				end)
			end
			return jersey_string
		else return ''
		end
	end -- end function jersey

	local startOfSeason = '' --'+2016-01-01T00:00:00Z'
	startOfSeason = getStartOfSeason(entity)

	local v = ''
	local plus = ''
	local localFrame
	if string.match(frame:getParent():getTitle(), '%P+') == mw.site.namespaces.Template.name
	then localFrame = frame:getParent() else localFrame = frame end
	if localFrame.args[1] ~= nil then localFrame.args[1] = string.gsub(localFrame.args[1], "%c", "") end

	if localFrame.args.country ~= nil then -- switch country column on or off in the article
		if localFrame.args.country == 'true' then country = true end
		if localFrame.args.country == 'false' then country = false end
	end

	local tableHeader2_size = table.getn(s.header_2)

	local tableStart = '<table border="0" cellspacing="0" cellpadding="0"><tr><th colspan="'.. tostring(tableHeader2_size + 1) .. '"'..
		' style="padding:2px 2px; text-align:center; background-color:#FFDF80">'

	local tableHeader1 = '<span style="float:left">[[File:Wikidata-logo S.svg|12px|link=d:'..
		s.item.. '#'.. s.property..']]</span>'.. l10n(header_1) .. '</th></tr>'

	local tableHeader2 = '<tr>'
	for i,k in ipairs(s.header_2) do
		if i==1 then tableHeader2 = tableHeader2.. '<th colspan="2" style="text-align:center;padding:2px 2px;white-space:nowrap">'.. l10n(k) .. '</th>' end
		if i==2 and country == true then tableHeader2 = tableHeader2.. '<th style="text-align:center;padding:2px 2px;white-space:nowrap">'.. l10n(k) .. '</th>' end
		if i>=3 then
			if i ~= tableHeader2_size then tableHeader2 = tableHeader2.. '<th style="text-align:center;padding:2px 2px;white-space:nowrap">'.. l10n(k).. '</th>'
			else tableHeader2 = tableHeader2..'<th style="text-align:center;padding:2px 2px;white-space:nowrap">'.. l10n(k) .. '</th>'
			end
		end
	end
	tableHeader2 = tableHeader2.. '</tr>'

	local tableBody = ''
	pcall(function()
		local t_Body = {}
		local bg_color=""
		local nr_jersey
		for l, m in pairs(entity.claims[s.property]) do -- look into all statements
			h.rider[1]=''
			local rank
			pcall(function()
				for _, v in pairs(m.qualifiers['P1352']) do -- for property 'rank'
					rank = tonumber(v.datavalue.value.amount) break
				end
				h.rider[1] = rank
				end)
			local riderID = 'Q'.. m.mainsnak.datavalue.value['numeric-id']
			if s.team_classification == false then
				h.rider[2] = WPlink(riderID, 'pure')
				h.rider[6] = national_team(riderID, startOfSeason, entity, s.property, l)
			end

			a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( riderID ), 'P21', 1)
			if a == true then
				if b == 6581097 then h.rider[3] = 'm' end -- men
				if b == 6581072 then h.rider[3] = 'f' end -- female
			else h.rider[3] = 'n' -- for teams
			end

		   	pcall(function() -- for property 'points' P1358
				for _, v in pairs(m.qualifiers['P1358']) do h.value[1] = tonumber(v.datavalue.value.amount)	end
			end)

		   	pcall(function() -- for property 'race time' P2781
				for _, v in pairs(m.qualifiers['P2781']) do	h.value[2] = tonumber(v.datavalue.value.amount)	end
			end)

		   	pcall(function() -- for property 'time gap' P2911
				for _, v in pairs(m.qualifiers['P2911']) do	h.value[3] = tonumber(v.datavalue.value.amount)	end
				plus = '+ '
			end)

		   	pcall(function() -- for property 'speed' P2052
				for _, v in pairs(m.qualifiers['P2052']) do h.value[4] = tonumber(v.datavalue.value.amount) end
			end)

			pcall(function() -- for property 'distinctive jersey'
				h.jersey= {''}
				nr_jersey = 1
				for _, v in pairs(m.qualifiers['P2912']) do
					h.jersey[nr_jersey] = 'Q'..v.datavalue.value['numeric-id']
					nr_jersey = nr_jersey + 1
				end
			end)

			if s.team_classification == true then
				h.rider[6] = transform(riderID, 't', startOfSeason)
			end

			if s.team_classification == false then
				local a, b = timeStartEnd(riderID, "P27", 'numeric-id', startOfSeason)
		   		if a == true then
		   			h.rider[5] = flag('Q'..b, startOfSeason)
					if country == true then
		   				h.rider[4] = l10n('Q' .. b, 'Q' .. b)
					end
	   			end
			end
	   		if s.team_classification == true then
				local a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( riderID ), 'P17', 1)
				if a == true then
					a, b = timeStartEnd(riderID, "P17", 'numeric-id', startOfSeason)
	  				if a == true then
		   				h.rider[5] = flag('Q'..b, startOfSeason)
						if country == true then
		   					h.rider[4] = l10n('Q' .. b, 'Q' .. b)
						end
					end
				end
	 		end

			local tBody = '<tr'
			-- find the right background color if a rider has more then one jersey
			-- see Wikidata:WikiProject Cycling/Kit to translate/Jerseys
			if h.jersey[1] ~= '' then
				local num = 1 -- loop for more then one jersey per rider
				while h.jersey[num] ~= nil and h.jersey[num] ~= '' do
					if h.jersey[num] == "Q24257872" then bg_color="#FF8666" break end -- Jersey red.svg General classification
					if h.jersey[num] == "Q24257763" then bg_color="pink" -- Jersey pink.svg
					if p.jersey_pink_color ~= nil then bg_color=p.jersey_pink_color end
					break end
					if h.jersey[num] == "Q24257871" then bg_color="#FFFF99" break end -- Jersey yellow.svg
					if h.jersey[num] == "Q26696171" then bg_color="#FFFFFF" break end -- Jersey white.svg
					if h.jersey[num] == "Q24687408" then bg_color="#99CBFF" break end -- Jersey blue.svg
					if h.jersey[num] == "Q26945272" then bg_color="#BF80FF" break end -- Jersey violet.svg
					if h.jersey[num] == "Q24257991" then bg_color="#FFD700" break end -- Jersey gold.svg
					if h.jersey[num] == "Q24258056" then bg_color="#FFD030" break end -- Jersey orange.svg
					if h.jersey[num] == "Q24258125" then bg_color="#BFFF80" break end -- Jersey green 2.svg
					if h.jersey[num] == "Q26945271" then bg_color="#90EE90" break end -- MaillotVolta.png
					if h.jersey[num] == "Q24645209" then bg_color="#90EE90" break end -- Jersey green.svg Points classification
					if h.jersey[num] == "Q27114205" then bg_color="#808080" break end -- Jersey black.svg
					if h.jersey[num] == "Q25831179" then bg_color="#FFFFFF" break end -- Jersey white.svg
					if h.jersey[num] == "Q26919974" then bg_color="#FF8666" break end -- Jersey red.svg
					if h.jersey[num] == "Q24687409" then bg_color="#99CBFF" break end -- Jersey blue.svg
					if h.jersey[num] == "Q25265938" then bg_color="#BF80FF" break end -- Jersey violet.svg
					if h.jersey[num] == "Q29594434" then bg_color="#87CEEB" break end -- MaillotCyan.PNG
					if h.jersey[num] == "Q30132459" then bg_color="#FFFF99" break end -- Jersey yellow-bluebar.svg
					num = num + 1
				end
			end

			if l == 1 and s.background == 'color' then
				tBody = tBody ..' style="font-weight:bold;' -- winner is formated bold
				if h.jersey[1] ~= '' and bg_color ~= nil then -- background color of winner depending on jersey
					tBody = tBody ..'background-color:'..bg_color..'"'
				else tBody = tBody ..'"' end
			end

			if l == 1 and s.background == 'strong' then
				tBody = tBody ..' style="font-weight:bold;' -- winner is formated bold
			end

			tBody =  tBody .. '><td style="text-align:center;padding:2px 0.5em 2px 0.5em;white-space:nowrap">'.. number(h.rider[1], h.rider[3]).. '</td><td style="text-align:left;padding:0 0.2em 0 0.2em">'
			if s.team_classification == false then
				if h.rider[6]==nil then h.rider[6]='' end
				if country == true then tBody = tBody.. h.rider[2].. jersey(h.jersey)..'</td><td>'.. h.rider[5]..' '.. h.rider[4].. '</td><td style="text-align:left;padding:0 0.2em 0 0.2em">'.. h.rider[6]
				else tBody = tBody.. h.rider[5].. ' '.. h.rider[2].. jersey(h.jersey)..'</td><td style="text-align:left;padding:0 0.2em 0 0.2em">'.. h.rider[6] end
			else
				if country == true then tBody = tBody.. WPlink(riderID, 'team', startOfSeason).. jersey(h.jersey).. '</td><td>'.. h.rider[5].. ' '.. h.rider[4]
				else tBody = tBody.. h.rider[5].. ' '.. WPlink(riderID, 'team', startOfSeason).. jersey(h.jersey) end
			end
			tBody = tBody.. '</td>'

			if s.header_2[4] == 'time' then -- for table stageclassification, generalclassification, adds time and time gap
				if l == 1 then tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'.. calculate_time(h.value[2]).. '</td>'
				else tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'.. plus.. calculate_time(h.value[3]).. '</td>'
				end
			end

			if s.header_2[4] == 'points' then -- for table pointsclassification, adds points
				tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'.. h.value[1].. '<span style="font-size:80%">'
				if type(h.value[1]) == "number" then if h.value[1] > 1 then tBody = tBody..l10n('unit_pts') else tBody = tBody..l10n('unit_pt') end end
				tBody = tBody.. '</span>' .. '</td>'
			end

			if s.header_2[3] == 'time' then
				if s.property == 'P2417' then -- for table teamtimetrialclassification, adds time
					tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'.. calculate_time(h.value[2]) .. '</td>'
				end
			end

			if s.property == 'P3497' then -- for table teambytimeclassification, adds time and time gap
				if l == 1 then tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'.. calculate_time(h.value[2]) .. '</td>'
				else tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'.. plus.. calculate_time(h.value[3]) .. '</td>'
				end
			end

			if s.property == 'P3496' then -- for table teambypointsclassification, adds points
				tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'.. h.value[1].. '<span style="font-size:80%">'
				if type(h.value[1]) == "number" then if h.value[1] > 1 then tBody = tBody..l10n('unit_pts') else tBody = tBody..l10n('unit_pt') end end
				tBody = tBody.. '</span>' .. '</td>'
			end

			if s.header_2[4] == 'time_gap' then -- for table teamtimetrialclassification, adds time gap
				tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'
				if l > 1 then tBody = tBody.. plus end
				tBody = tBody.. calculate_time(h.value[3]) .. '</td>'
			end

			if s.header_2[5] == 'speed' then -- for table teamtimetrialclassification, adds speed
				tBody = tBody.. '<td style="text-align:right;padding:0 0.2em 0 0.2em">'
				if type(h.value[4]) == "number" then tBody = tBody.. mw.ustring.format('%.3f', h.value[4])..
					'<span style="font-size:80%">'..  l10n('kmh').. '</span>'.. '</td></tr>'
				end
			end

			if rank ~= nil then	t_Body[rank] = tBody.. '</tr>' end -- sort table row into the right row
		end
		for _, m in pairs(t_Body) do tableBody = tableBody..m end
	end)

	local tableEnd = '</table>'

	local tableStyle, tableNewline
	if localFrame.args.newline == 'false' then -- parameter newline in WP article is 'false'
		tableStyle = "float:left; margin-right:0.5em; border:1px solid rgb(200,200,200)"
		tableNewline = ''
	end
	if localFrame.args.newline == 'true' then -- parameter newline in WP article is 'true'
		tableStyle = "border:1px solid rgb(200,200,200)"
		tableNewline = '<br style="clear:left;">'
	end
	if localFrame.args.newline == nil then -- no second parameter, compatible to the old code
		if s.property == 'P2417' then --stageclassification
			tableStyle = "float:left; margin-right:0.5em; border:1px solid rgb(200,200,200)"
			tableNewline = ''
		else
			tableStyle = "border:1px solid rgb(200,200,200)"
			tableNewline = '<br style="clear:left;">' -- everything else
		end
	end

	return '<table style="'.. tableStyle.. '"><tr><td>' .. tableStart .. tableHeader1 .. tableHeader2 .. tableBody .. tableEnd .. '</td></tr></table>' .. tableNewline
end

function references(entity, property, var1)
	local ref1, ref2, ref2b, ref3, ref4 = "", " ", "", "", ""
	local url, ref
	local a, b

	a, b = pcall(fooB, 'value', entity, property, var1, 1, 'P854', 1) -- url
	if a == true then ref1 = b end
	a, b = pcall(fooB, 'text', entity, property, var1, 1, 'P1476', 1) -- Originaltitel der webpage, "language": "fr"
	if a == true then
		ref2 = b
		ref2b= entity.claims[property][var1].references[1].snaks['P1476'][1].datavalue.value.language or ''
		if ref2b == langcode then ref2b = '' else ref2b = '(' .. ref2b .. ') ' end
	end
	a, b = pcall(fooB, 'time', entity, property, var1, 1, 'P577', 1) -- publication date
	if a == true then
		local _, _, year, m, d = string.find(b,"(%d+)-(%d+)-(%d+)")
		if d ~= '00' and m ~= '00' then
			ref3 = ', ' .. formatDate(b, 'long_inreference')
		elseif d == '00' and m ~= '00' then
			ref3 = ', ' .. formatDate(year..'-'..m..'-01', 'monthyear')
		else ref3 = year
		end
	end
	a, b = pcall(fooB, 'time', entity, property, var1, 1, 'P813', 1) -- Retrieved
	if a == true then
		ref4 = ''
		retrieved = l10n('retrieved')
		if string.sub(retrieved, 0, 1) ~= ',' then ref4 = ref4 .. ' ' end
		ref4 = ref4 .. retrieved .. ' ' .. formatDate(b, 'long_inreference')
		if string.find(retrieved, '(') ~= nil then ref4 = ref4 .. ')' end
	end

	if ref1~='' then --and ref2~='' then
		local _, start = string.find( ref1, '//' )
		local ende, _ = string.find( ref1, '/', start + 1 )
		local s = string.sub(ref1, start + 1, ende - 1)
		local s2 = string.gsub(s, "www.", "")
		if wiki == "fr" then
		-- fr: "(en) « Lloyd Mondory ... EPO », sur velonews.competitor.com (consulté le 30 april 2016), 30 octobre 2015."
			if ref2~=' ' then url= ', sur <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end
			ref = ref2b .. '« ['.. ref1.. ' '.. ref2.. '] »' .. url .. ref4 .. ref3 ..'.'
		elseif wiki == "en" then
		-- en: "Inflation ... recession", Pittsburgh Post-Gazette, October 16, 2009. Retrieved 2010-01-21.
			if ref2~=' ' then url= ', <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end
			ref = '"['.. ref1.. ' '.. ref2.. '"]'.. ref2b .. url .. ref3 .. ref4
		elseif wiki == "de" then
			if ref2~=' ' then url= ' In: <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end
			ref = '<span style="font-style:italic;">['.. ref1.. ' '.. ref2.. '.]</span> '.. url.. ref3 .. ref4 ..'.'
		else
			if ref2~=' ' then url= ' <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end
			ref = ref2b .. '['.. ref1.. ' '.. ref2.. '] ' .. url.. ref3 .. ref4
		end
		return ref or ''
	else return ''
	end
end

function p.infobox(frame)
	local t = {is_a="", class="", stage="", starttime="", endtime="", time="", date="", dates="", length="", length_unit="",
	startplace="", endplace="", nr_teams="", nr_participants_start="", nr_participants_end="", speed="", speed_unit="", cost="", cost_unit="",
	first="", first_team="", second="", second_team="", third="", third_team="", winner_point="", winner_point_team="", winner_mountain="", winner_mountain_team="",
	winner_sprint="", winner_sprint_team="", winner_young="", winner_young_team="", winner_fighting="", winner_fighting_team="", winner_combination="",
	winner_combination_team="", winner_metas_volantes="", winner_metas_volantes_team="", winner_regularity="", winner_regularity_team="",
	winner_fuga_pinarello="", winner_fuga_pinarello_team="", winner_azzurri_ditalia="", winner_azzurri_ditalia_team="", winner_team="",
	winner_team_points="", previous="", next=""}
	local ref = {stage="", starttime="", endtime="", time="", date="", dates="", length="", nr_participants_start="", nr_participants_end="",
	speed="", speed_unit="", cost="", first="", second="", third="", winner_point="", winner_mountain="", winner_sprint="", winner_young="",
	winner_fighting="", winner_metas_volantes="", winner_regularity="", winner_combination="", winner_fuga_pinarello="", winner_azzurri_ditalia="",
	winner_team="", winner_team_points=""}
	local tt = {icon="", picture="", caption="", name="", nr="", map="" }
	local ttt = {tour={}, country={}}
	local tttt = {special_1a="", special_1b="", special_2a="", special_2b=""}

	local entity = ""
	local y, m, d = "", "", ""
	local y2, m2, d2 = "", "", ""
	local a, b, c, k, num, i
	local entityId = frame.args[1]
	local results = false
	local a1, b1, c1, a2, b2, c2
	local timeofrace

	if type( entityId ) ~= 'string' then error( 'parameter must be a string') end
	if not entityId:match( 'Q%d+' ) then error ( 'parameter must be a valid Wikidata item (ex: Q42)' ) end
	local entity = mw.wikibase.getEntity( entityId )

	local localFrame
	if string.match(frame:getParent():getTitle(), '%P+') == mw.site.namespaces.Template.name
	then localFrame = frame:getParent() else localFrame = frame end

	if localFrame.args[l10n('picture')] then tt.picture = localFrame.args[l10n('picture')] end
	if localFrame.args[l10n('caption')] then tt.caption = localFrame.args[l10n('caption')] end
	if localFrame.args[l10n('map')] then tt.map = localFrame.args[l10n('map')] end


	tt.name = mw.wikibase.label( entityId ) or ''

	a, b = pcall(fooA, 'numeric-id', entity, 'P641', 1)
	if a == true then -- icon for road bicycle racing, Q3609 (road bicycle racing)
		if b == 3609 then tt.icon = " [[File:Cycling (road) pictogram.svg|35px]]" end
	end
	a, b = pcall(fooA, 'value', entity, 'P18', 1)
	if a == true and tt.picture == "" then
		local v
		tt.picture = b
		if pcall(foo3, entity, "P18", 1, "P2096", 1) then
			for _, v in pairs(entity.claims["P18"]) do
				for num=1,#v.qualifiers["P2096"] do
					if v.qualifiers["P2096"][num].datavalue.value.language == langcode then
					tt.caption = v.qualifiers["P2096"][num].datavalue.value.text end
				end
			end
		end
	end

	a, b = pcall(fooA, 'value', entity, 'P393', 1)
	if a == true and tt.nr == '' then tt.nr = number(b, 'm')	end
	-- Class of a cycling race. Class is: 1.UWT, 2.UWT, 1.HC, ... add new classes, no problem
	local class = { "Q22231106", "Q22231107", "Q22231108", "Q22231109", "Q22231110", "Q22231111", "Q22231112",
		"Q22231113", "Q22231114", "Q22231115", "Q22231116", "Q22231117", "Q22231118", "Q22231119", "Q23015458", "Q23005601", "Q23005603" }
	a, b = pcall(fooA, 'numeric-id', entity, 'P31', 1) -- first value for P31
	c, d = pcall(fooA, 'numeric-id', entity, 'P31', 2) -- second value for P31
	if a == true and c == true then -- for two values
		for i=1,#class do -- #class = number of elements in class
   			if "Q"..b == class[i] then t.class = "c"..b t.is_a = "Q"..d break end
   			if "Q"..d == class[i] then t.class = "c"..d t.is_a = "Q"..b break end
   		end
 	else -- if there is only one value, assume it is not a class
		if a == true or c == true then t.is_a = "Q"..b end
	end

	a, b = pcall(fooA, 'numeric-id', entity, 'P361', 1) -- Competition of the cycling race : UCI World Tour 2016, UCI Europe Tour 2016...
	if a == true then --ttt.tour = "Q" .. b end
		local i, v
		for i, v in pairs(entity.claims["P361"]) do
			ttt.tour[i] = "T" .. v.mainsnak.datavalue.value["numeric-id"]
		end
	end

	if t.stage == "" then
		if pcall(function() -- This function count the number of value for P527 to determine the number of stages
			t.stage = table.getn(entity.claims["P527"])
		end
		) then else t.stage = "" end
	end

	a1, b1, c1 = pcall(fooA, 'time', entity, 'P580', 1)
	if a1 == true and t.starttime == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'time', entity, 'P580', i)
		end
		--b1 = "+2015-07-04T00:00:00Z"
		_, _, y, m, d = string.find(b1, "(%d+)-(%d+)-(%d+)")
	end
	a2, b2, c2 = pcall(fooA, 'time', entity, 'P582', 1)
	if a2 == true and t.endtime == "" then i = 1
		while a2 == true and c2 == 'deprecated' do
			i = i + 1
			a2, b2, c2 = pcall(fooA, 'time', entity, 'P582', i)
		end
		--b2 = "+2015-07-05T00:00:00Z"
		_, _, y2, m2, d2 = string.find(b2, "(%d+)-(%d+)-(%d+)")
	end
	if a1 == true and t.starttime == "" then
		if y ~= y2 then t.starttime = formatDate(b1, 'long')
		elseif m ~= m2 then t.starttime = formatDate(b1, 'daymonth_long')
		else t.starttime = formatDate(b1, 'day')
		end
	end -- if a1
	if a2 == true and t.endtime == "" then
		t.endtime = formatDate(b2, 'long')
		timeofrace = b2
		if wiki == "ar" then
			if y ~= y2 then
			elseif m ~= m2 then t.endtime = lang:formatDate( "d F Y", b2 )
			else t.endtime = lang:formatDate( "d، Y", b2 )
			end	end
		if wiki == "en" then
			if y == y2 and m == m2 then t.endtime = lang:formatDate( "d, Y", b2 ) end
		end
		if wiki == "ja" then
			if y ~= y2 then
			elseif m ~= m2 then t.endtime = lang:formatDate( "m月d日", b2 )
			else t.endtime = lang:formatDate( "d日", b2 )
			end	end
		if wiki == "lv" then
			if y == y2 then t.endtime = lang:formatDate( "j. F", b2 ) end
		end
	end -- if a2

	-- This function give a format to dates when P585 (date) is used in a single day race
	a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', 1)
	if a1 == true and t.time == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', i)
		end
		t.time = formatDate(b1, 'long')
		timeofrace = b1
	end

	-- This function permits to display an unity (the kilometer) for a distance, with exceptions for macedionan, russian and japanese
	-- that have other symbols
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P3157', 1)
	if a1 == true and t.length == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P3157', i)
		end
		t.length = b1
		a1, b1, _ = pcall(fooA, 'unit', entity, 'P3157', 1)
		if b1 == "http://www.wikidata.org/entity/Q828224" then
			t.length_unit = l10n('unit_km')
		end
	end

	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2043', 1)
	if a1 == true and t.length == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2043', i)
		end
		t.length = b1
		a1, b1, _ = pcall(fooA, 'unit', entity, 'P2043', 1)
		if b1 == "http://www.wikidata.org/entity/Q828224" then
			t.length_unit = l10n('unit_km')
		end
	end

	a, b = pcall(fooA, 'numeric-id', entity, 'P17', 1) -- This function gives countries where the race take place
	if a == true then --and ttt.country == "" then ttt.country = "Q" .. b end
		local i, v
		for i, v in pairs(entity.claims["P17"]) do
   			ttt.country[i] = "C" .. v.mainsnak.datavalue.value["numeric-id"]
   		end
 	end
	-- Function that give the starting place of a race
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', 1)
	if a1 == true and t.startplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', i)
		end
		t.startplace = "Q" .. b1
	end
	-- Function that give the finishing place of a race
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', 1)
	if a1 == true and t.endplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', i)
		end
		t.endplace = "Q" .. b1
	end
	-- This function counts the number of value for P1923 (participating teams) and give the number of team that participate at the race
	if pcall(function()
		 t.nr_teams = table.getn(entity.claims["P1923"])
		 end
	  ) then else t.nr_teams = "" end

	-- Function that give the number of cyclists at the beginning and at the finishing of a race
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P1132', 1)
	if a1 == true and t.nr_participants_start == "" and t.nr_participants_end == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P1132', i)
		end
		local v
		for _, v in pairs(entity.claims["P1132"]) do
			if pcall(function()
		   		if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 529711 then
				t.nr_participants_start = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
				end
			) then else t.nr_participants_start = "" end
			if pcall(function()
				if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 12769393 then
				t.nr_participants_end = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
			end
			) then else t.nr_participants_end = "" end
		end	-- for
	end -- if a1

	-- This function permits to display an unity (the kilometer per hour) for an average speed, with exceptions for macedionan, russian and japanese
	-- that have other symbols
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2052', 1)
	if a1 == true and t.speed == "" then i = 1
		while a1 == true and c1 == 'deprecated' do
			i = i + 1
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2052', i)
		end
		t.speed = b1
		a1, b1 = pcall(fooA, 'unit', entity, 'P2052', 1)
		if b1 == "http://www.wikidata.org/entity/Q180154" then
			t.speed_unit = l10n('unit_kmh')
		end
	end	-- if a1
 	-- This function permits to display an unity for the cost of a cycling race
	a, b = pcall(fooA, 'amount', entity, 'P2130', 1)
	if a == true and t.cost == "" then
		t.cost = b
		a, b = pcall(fooA, 'unit', entity, 'P2130', 1)
		if b == "http://www.wikidata.org/entity/Q4916" then t.cost_unit = '€' end
		if b == "http://www.wikidata.org/entity/Q4917" then t.cost_unit = '$' end
	end

	a, b = pcall(fooA, 'value', entity, 'P242', 1) -- locator map image
	if a == true and tt.map == "" then tt.map = b end
	a, b = pcall(fooA, 'numeric-id', entity, 'P155', 1)
	if a == true and t.previous == "" then t.previous = "Q"..b end
	a, b = pcall(fooA, 'numeric-id', entity, 'P156', 1)
	if a == true and t.next == "" then t.next = "Q"..b end

	local note, qual, id, id_team
	if l10nDef.note ~= nil then note = l10nDef.note else note = 'f' end

	-- By entering a value just below, the Wikipedia added will show the team of the winner
	if pcall(foo3, entity, "P1346", 1, "P642", 1) then
		local k, v, vv
		for k, v in pairs(entity.claims["P1346"]) do
			id_team = ''
			--id_team = 't26973671'
			a, b = pcall(fooC, 'numeric-id', entity, 'P1346', k, 'P54', 1)
			if a == true then id_team = 't'..b end

			if pcall(function() id=v.mainsnak.datavalue.value['numeric-id'] end) then else id=nil end -- id = rider id
			if id ~= nil then
				--timeofrace = "+2016-03-00T00:00:00Z"
				-- function timeStartEnd finds the team of the rider at the time (timeofrace) of the race
				if id_team == '' and timeofrace ~= nil and timeofrace ~= '' then
					a, b = timeStartEnd('Q'..id, 'P54', 'numeric-id', timeofrace)
					if a == true and b ~= nil then id_team = 't' .. b end
				end
			end
			-- pcall(function() id=v.mainsnak.datavalue.value['numeric-id'] end) -- rider ID

			-- looks into race item if the winner has a P54 statement for beeng a member of a national team
			pcall(function()
				for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P54']) do
					id_team = '2t'.. ' ('.. national_team('Q'..id, timeofrace, entity, 'P1346', k).. ')'
				end
			end)

			-- looks into race item if the winner has a P642 statement for showing the type of winner (points, mountain, ..)
			pcall(function()
				for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P642']) do
					qual=vv.datavalue.value['numeric-id']

		if id~=nil and qual~=nil and v.rank~='deprecated' then
			if qual == 20882667 and t.first=="" then t.first=note..id t.first_team=id_team ref.first=references(entity,"P1346",k) results=true end
			if qual == 20882668 and t.second=="" then t.second=note..id t.second_team=id_team ref.second=references(entity,"P1346",k) results=true end
			if qual == 20882669 and t.third=="" then t.third=note..id t.third_team=id_team ref.third=references(entity,"P1346",k) results=true end
			if qual == 20883007 and t.winner_point=="" then t.winner_point=note..id t.winner_point_team=id_team ref.winner_point=references(entity,"P1346",k) results=true end
			if qual == 20883212 and t.winner_mountain=="" then t.winner_mountain=note..id t.winner_mountain_team=id_team ref.winner_mountain=references(entity,"P1346",k) results=true end
  			if qual == 20883328 and t.winner_sprint=="" then t.winner_sprint=note..id t.winner_sprint_team=id_team ref.winner_sprint=references(entity,"P1346",k) results=true end
			if qual == 20883139 and t.winner_young=="" then t.winner_young=note..id t.winner_young_team=id_team ref.winner_young=references(entity,"P1346",k) results=true end
			if qual == 20893983 and t.winner_fighting=="" then t.winner_fighting=note..id t.winner_fighting_team=id_team ref.winner_fighting=references(entity,"P1346",k) results=true end
			if qual == 27067359 and t.winner_metas_volantes=="" then t.winner_metas_volantes=note..id t.winner_metas_volantes_team=id_team ref.winner_metas_volantes=references(entity,"P1346",k) results=true end
			if qual == 27067170 and t.winner_regularity=="" then t.winner_regularity=note..id t.winner_regularity_team=id_team ref.winner_regularity=references(entity,"P1346",k) results=true end
			if qual == 20893979 and t.winner_combination=="" then t.winner_combination=note..id t.winner_combination_team=id_team ref.winner_combination=references(entity,"P1346",k) results=true end
			if qual == 27907715 and t.winner_fuga_pinarello=="" then t.winner_fuga_pinarello=note..id t.winner_fuga_pinarello_team=id_team ref.winner_fuga_pinarello=references(entity,"P1346",k) results=true end
			if qual == 27907747 and t.winner_azzurri_ditalia=="" then t.winner_azzurri_ditalia=note..id t.winner_azzurri_ditalia_team=id_team ref.winner_azzurri_ditalia=references(entity,"P1346",k) results=true end
			if qual == 20882921 and t.winner_team == "" then
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( 'Q'..id ), 'P31', 1)
				if a == true and (b == 20738667 or b == 23726798) then -- test if 'national cycling team U23' or 'national cycling team'
					t.winner_team = '2t' .." "..national_team('Q'..id, timeofrace, entity, 'P1346', k)
				else
					t.winner_team = note .. id ref.winner_team=references(entity,"P1346",k) results = true
				end
			end
			if qual == 27104269 and t.winner_team_points == "" then t.winner_team_points = note .. id ref.winner_team_points=references(entity,"P1346",k) results = true end
 		end
				end
			end)
		end	-- for
	end  -- end if pcall

	-- code for references
	local list = {} -- list[1][1] = value from ref.first, list [1][2] = 'first'
	local k
	for k in pairs(ref) do
		if ref[k]~='' then table.insert(list, {ref[k], k}) end
	end
	local w, ww
	num = #list
	for w=num,1,-1 do
		for ww=1,w do
			if w ~= ww then
				if list[w][1] == list[ww][1] then list[w][1] = frame:extensionTag{name='ref', args={name=entityId..ww}} break end
			else list[w][1] = frame:extensionTag{name='ref', content=list[w][1], args={name=entityId..ww}} end
		end
	end
	for i=1,num do
		ref[ list[i][2] ] = list[i][1] --list[num+1-i][1]
	end

	-- transform Q/q-number into flag / WPlink / WDlink
	local k
	local team = true
	local wd = " [[File:Wikidata-logo S.svg|12px|link=d:"

	for k in pairs(ttt) do -- "^C" ttt.country, "^T" ttt.tour
		if ttt[k][1]~=nil and string.find(ttt[k][1], "^C") then for i=1,#ttt[k] do ttt[k][i] = string.gsub(ttt[k][i], "C", "Q") ttt[k][i] = flag(ttt[k][i], timeofrace).." ".. WPlink( ttt[k][i] ) end end
		if ttt[k][1]~=nil and string.find(ttt[k][1], "^T") then for i=1,#ttt[k] do ttt[k][i] = string.gsub(ttt[k][i], "T", "Q") ttt[k][i] = WPlink( ttt[k][i], 'pure') end end
	end
	for k in pairs(t) do
		if string.find(t[k], "^Q") then --t[k], k = startplace, endplace, ... find variables with an item as value
			if pcall(foo1, t[k]) then t[k] = WPlink( t[k] )	end
		end
		if string.find(t[k], "^q") then -- find variables with an item as value (in section Résultats)
			t[k] = mw.ustring.upper( t[k] )
			--look into P27 (country of citizenship) to get the Qnumber of that country
			a, b = timeStartEnd(t[k], "P27", 'numeric-id', timeofrace)
			if a == true and pcall(foo1, t[k]) then t[k] = flag('Q'..b, timeofrace).." "..WPlink( t[k] )..ref[k]..wd..t[k].."]]"
			else
				--look into P17 (country) to get the Qnumber of that country
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P17', 1)
				if a == true and pcall(foo1, t[k]) then t[k] = flag("Q"..b, timeofrace).." "..WPlink( t[k] )..ref[k]..wd..t[k].."]]" end
			end
		end
		if string.find(t[k], "^f") then -- no WDitem, frWP
			t[k] = string.gsub(t[k], "f", "Q")
			--look into P27 (country of citizenship) to get the Qnumber of that country
			a, b = timeStartEnd(t[k], "P27", 'numeric-id', timeofrace)
			if a == true and pcall(foo1, t[k]) then t[k] = flag('Q'..b, timeofrace).." "..WPlink( t[k] )..ref[k]
			else
				--look into P17 (country) to get the Qnumber of that country
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P17', 1)
				if a == true and pcall(foo1, t[k]) then t[k] = flag("Q"..b, timeofrace).." "..WPlink( t[k], 'team', timeofrace )..ref[k] else t[k] = WPlink( t[k], 'team', timeofrace )..ref[k] end
			end
		end
		if string.find(t[k], "^c") then -- find "class"-items, first asci = "c"
			t[k] = string.gsub(t[k], "c", "Q")
			if pcall(foo1, t[k]) then t[k] = WPlink( t[k], "Q22348500" ) end
		end
		if string.find(t[k], "^t") then
			t[k] = string.gsub(t[k], "t", "Q")
			--timeofrace = "+2008-04-09T00:00:00Z"
			if pcall(foo1, t[k]) then t[k] = " (" .. WPlink( t[k], 'team', timeofrace ) .. ")" end
		end
		if string.find(t[k], "^2t") then t[k] = string.gsub(t[k], "2t", "") end
	end

	--local nl ="&#10;"
	-- local tooltip = infobox_bottom(2) .. nl .. mw.text.encode( property(1) .. ' (P393)' ) .. nl .. mw.text.encode( property(2) ..' (P17)')

	if t.length ~= "" then
		t.length, _ = string.gsub(t.length, "[+]", "") -- delets "+" sign from t.length
		t.length = lang:formatNum(tonumber(t.length)) -- formats t.length in the way it is done in the local Wiki
		if langcode == 'fo' then t.length = string.gsub(t.length, "%.", ",") end
	end
	if t.speed ~= "" then
		t.speed, _ = string.gsub(t.speed, "[+]", "")
		t.speed = lang:formatNum(tonumber(t.speed))
		if langcode == 'fo' then t.speed = string.gsub(t.speed, "%.", ",") end
	end
	if t.cost ~= "" then
		t.cost, _ = string.gsub(t.cost, "[+]", "")
		t.cost = lang:formatNum(tonumber(t.cost))
		if langcode == 'fo' then t.cost = string.gsub(t.cost, "%.", ",") end
	end

   	local span1, span2 = "<span style='color:#3366CC'>&#x25C0; </span>", "<span style='color:#3366CC'> &#x25B6;</span>"
	local k = t.previous
	local i, _ = string.find(k, "|")
	local j, _ = string.find(k, "]")
	if i ~= nil and j ~= nil then
		t.previous = string.sub(k, 1, i) .. span1 .. string.match(string.sub(k, i+1, j-1), "%d%d%d%d") .. string.sub(k, j)
	else
		if string.find(k, "%d%d%d%d") == nil then t.previous = '' else t.previous = string.sub(k, string.find(k, "%d%d%d%d")) end
		if t.previous ~= "" then t.previous = span1 .. t.previous end
	end

	k = t.next
	i, _ = string.find(k, "|")
	j, _ = string.find(k, "]")
	if i ~= nil and j ~= nil then
		t.next = string.sub(k, 1, i) .. string.match(string.sub(k, i+1, j-1), "%d%d%d%d") .. span2 .. string.sub(k,j)
	else
		if string.find(k, "%d%d%d%d") == nil then t.next = "" else t.next = string.sub(k, string.find(k, "%d%d%d%d")) end
		if t.next ~= "" then t.next = t.next .. span2 end
	end

	tt.caption = string.gsub(tt.caption, "{{(%w+)}}", function (n) return frame:expandTemplate{ title = n }  end)
	local z = {'first', 'second', 'third', 'winner_point', 'winner_mountain', 'winner_sprint', 'winner_young', 'winner_fighting', 'winner_combination', 'winner_metas_volantes', 'winner_regularity', 'winner_fuga_pinarello', 'winner_azzurri_ditalia'}

	local i
	for _, i in pairs(z) do
		t[i] = t[i].. t[i..'_team']
	end

	if localFrame.args[l10n('special_1')]~="" and localFrame.args[l10n('special_1')]~=nil then
	i, k = string.find(localFrame.args[l10n('special_1')] , ":")
		tttt.special_1a = string.sub(localFrame.args[l10n('special_1')], 1, i-1)
		tttt.special_1b = string.sub(localFrame.args[l10n('special_1')], k+1)
	end
	if localFrame.args[l10n('special_2')]~="" and localFrame.args[l10n('special_2')]~=nil then
	i, k = string.find(localFrame.args[l10n('special_2')] , ":")
		tttt.special_2a = string.sub(localFrame.args[l10n('special_2')], 1, i-1)
		tttt.special_2b = string.sub(localFrame.args[l10n('special_2')], k+1)
	end

	if wiki == "fi" then
		if t.starttime ~= "" then t.starttime = mw.ustring.gsub(t.starttime, "%a+", "%0ta") end
		if t.endtime ~= "" then t.endtime = mw.ustring.gsub(t.endtime, "%a+", "%0ta") end
		if t.time ~= "" then t.time = mw.ustring.gsub(t.time, "%a+", "%0ta") end
	end

 	tab = "<table cellpadding='4' cellspacing='0' style='float:right; width:300px; border:1px solid rgb(200,200,200);"
	tab = tab .. "margin:0 0 0.5em 0.5em; background-color:rgb(255, 255, 255); color:black; padding:5px; clear:left; "
	tab = tab .. "text-align:left; font-size:85%; line-height:1.6em;'>"
	if wiki == "eo" then tab = "<table style='width:23em; border:1px solid rgb(200,200,200);"
		tab = tab .. "margin:0 0 0.5em 0.5em; background-color:rgb(255, 255, 255); color:black; padding:5px;"
		tab = tab .. "text-align:left; font-size:85%; line-height:1.6em;' class='infobox' >"
	end
	tab = tab .. "<tr><td colspan='2' style='border-bottom:5px solid white; font-size:175%; background:#FFDF80; text-align:center'>"
	tab = tab .. "<table style='width:100%'><tr><td>" .. tt.name .."</td><td>" .. tt.icon .. "</td></tr></table></td></tr>"
	if tt.picture ~= "" then tab = tab .. "<tr><td colspan='2' style='text-align:center'>".." [[File:".. tt.picture .."|center|300px]]</td></tr>" end
	if tt.picture ~= "" and tt.caption ~= "" then tab = tab .. "<tr><td colspan='2' style='text-align:center; font-size:80%'>"..tt.caption.."</td></tr>" end
	tab = tab .. "<tr><td colspan='2' style='background-color:#FFDF80; text-align:center'>'''"..l10n('race_details').."'''</td></tr>"
	if tt.nr ~= "" and t.is_a ~= "" then tab = tab.."<tr><td style='width:40%'>'''"..l10n('course').."'''</td><td>" .. tt.nr .. " " .. t.is_a .. "</td></tr>" end
	if ttt.tour[1] ~= nil then tab = tab.."<tr><td style= 'vertical-align:top'>'''"
		if #ttt.tour == 1 then tab = tab..l10n('competition').."'''</td><td>" else tab = tab..l10n('competitions').."'''</td><td>" end
		for i=1,#ttt.tour do tab = tab .. ttt.tour[i] if i == 1 then tab = tab .. " " ..t.class end tab = tab .. "<br>" end
		tab = tab.."</td></tr>" end
	if t.stage ~= "" then tab = tab.."<tr><td>'''"..l10n('stages').."'''</td><td>" .. t.stage.."</td></tr>" end
	if (t.starttime~="" or t.endtime~="") and t.date=="" and t.dates=="" then tab = tab.."<tr><td>'''"..l10n('dates').."'''</td><td>" .. t.starttime.." – " ..t.endtime .."</td></tr>" end
	--if t.endtime ~= "" then tab = tab.."<tr><td>".. l10n('endtime') .."</td><td>" .. t.endtime .. "</td></tr>" end
	if t.time~="" and t.date=="" and t.dates=="" then tab = tab.."<tr><td>'''"..l10n('date').."'''</td><td>" .. t.time.."</td></tr>" end
	if t.date~="" then tab = tab.."<tr><td>'''"..l10n('date').."'''</td><td>" .. t.date.."</td></tr>" end
	if t.dates~="" then tab = tab.."<tr><td>'''"..l10n('dates').."'''</td><td>" .. t.dates.."</td></tr>" end
	if t.length ~= "" then tab = tab.."<tr><td>'''"..l10n('distance').."'''</td><td>" .. t.length.." "..t.length_unit.."</td></tr>" end
	if ttt.country[1] ~= nil then tab = tab.."<tr><td style= 'vertical-align:top'>'''"
		if #ttt.country == 1 then tab = tab..l10n('country').."'''</td><td>" else tab = tab..l10n('countries').."'''</td><td>" end
		for i=1,#ttt.country-1 do tab = tab .. ttt.country[i].."<br>" end tab = tab .. ttt.country[#ttt.country].."</td></tr>" end
	if t.startplace ~= "" then tab = tab.."<tr><td>'''"..l10n('journey_origin').."'''</td><td>" .. t.startplace .. "</td></tr>" end
	if t.endplace ~= "" then tab = tab.."<tr><td>'''"..l10n('journey_destination').."'''</td><td>" .. t.endplace .. "</td></tr>" end
	if t.nr_teams ~= "" then tab = tab.."<tr><td>'''"..l10n('nr_teams').."'''</td><td>" .. t.nr_teams .. "</td></tr>" end
	if t.nr_participants_start ~= "" then tab = tab.."<tr><td>'''"..l10n('starting_riders').."'''</td><td>" .. t.nr_participants_start .. "</td></tr>" end
	if t.nr_participants_end ~= "" then tab = tab.."<tr><td>'''"..l10n('arriving_riders').."'''</td><td>" .. t.nr_participants_end .. "</td></tr>" end
	if t.speed ~= "" then tab = tab.."<tr><td>'''"..l10n('average_speed').."'''</td><td>" .. t.speed .. " "..t.speed_unit.."</td></tr>" end
	if t.cost ~= "" then tab = tab.."<tr><td>'''"..l10n('cost').."'''</td><td>" .. t.cost .. " "..t.cost_unit.. "</td></tr>" end
	if tttt.special_1a ~= "" then tab = tab.."<tr><td>'''"..tttt.special_1a.."'''</td><td>" .. tttt.special_1b.. "</td></tr>" end
	if tttt.special_2a ~= "" then tab = tab.."<tr><td>'''"..tttt.special_2a.."'''</td><td>" .. tttt.special_2b.. "</td></tr>" end

	if results then tab = tab.."<tr><td colspan='2' style='border-bottom:5px solid white; background-color:#FFDF80; text-align:center'>'''"..l10n('palmares').."'''</td></tr>" end
	if t.first ~= "" then tab = tab.."<tr><td>'''"..l10n('winner').."'''</td><td>" .. t.first .. "</td></tr>" end
	if t.second ~= "" then tab = tab.."<tr><td>'''"..l10n('second').."'''</td><td>" .. t.second .. "</td></tr>" end
	if t.third ~= "" then tab = tab.."<tr><td>'''"..l10n('third').."'''</td><td>" .. t.third .. "</td></tr>" end
	if t.winner_point ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_point').."'''</td><td>" .. t.winner_point .. "</td></tr>" end
	if t.winner_mountain ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_mountain').."'''</td><td>" .. t.winner_mountain .. "</td></tr>" end
	if t.winner_sprint ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_sprint').."'''</td><td>" .. t.winner_sprint .. "</td></tr>" end
	if t.winner_young ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_young').."'''</td><td>" .. t.winner_young .. "</td></tr>" end
	if t.winner_fighting ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_fighting').."'''</td><td>" .. t.winner_fighting .. "</td></tr>" end
	if t.winner_metas_volantes ~= "" then tab = tab.."<tr><td>'''"..l10n('metas_volantes').."'''</td><td>" .. t.winner_metas_volantes .. "</td></tr>" end
	if t.winner_regularity ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_regularity').."'''</td><td>" .. t.winner_regularity .. "</td></tr>" end
	if t.winner_fuga_pinarello ~= "" then tab = tab.."<tr><td>'''"..l10n('fuga_pinarello').."'''</td><td>" .. t.winner_fuga_pinarello .. "</td></tr>" end
	if t.winner_azzurri_ditalia ~= "" then tab = tab.."<tr><td>'''"..l10n('azzuri_d_italia').."'''</td><td>" .. t.winner_azzurri_ditalia .. "</td></tr>" end
	if t.winner_combination ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_combination').."'''</td><td>" .. t.winner_combination .. "</td></tr>" end
	if t.winner_team ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_team').."'''</td><td>" .. t.winner_team .. "</td></tr>" end
	if t.winner_team_points ~= "" then tab = tab.."<tr><td>'''"..l10n('winner_team_points').."'''</td><td>" .. t.winner_team_points .. "</td></tr>" end
	if tt.map ~= "" then tab = tab .. "<tr><td colspan='2' style='text-align:center'>".." [[File:".. tt.map .."|center|300px]]".."</td></tr>" end

	tab = tab.."<tr><td>"..t.previous.."</td><td style='text-align:right'>" .. t.next .. "</td></tr>"
	local s = "d:Wikidata:WikiProject Cycling/Documentation/infobox"
	tab = tab .. "<tr><td colspan='2' style='text-align:right; border-top:3px solid #FFDF80; font-size:75%'>" .. "[[" .. s .. "|" .. l10n('documentation') .. "]] [[File:Wikidata-logo S.svg|12px|link=d:".. frame.args[1]  .. "]]" --infobox_bottom(1)
	--tab = tab .. "<span style='float:right' title='".. tooltip .. "'>[[File:High-contrast-help-browser.svg|10px|right|link=]]"
	tab = tab .. "</span></td></tr>"
	tab= tab.."</table>"
	return tab
end

function national_team(riderID, startOfSeason, entity, property, k)
	-- property: statement where the rider is the value
	-- k: loop
	local national_team, team, nationality, teamID
	-- national team for U23 or older riders
	if pcall(function()
		local i,j, s
		for _, v in pairs(entity.claims[property][k].qualifiers['P54']) do -- for property 'member of sports team'
			teamID = 'Q'.. v.datavalue.value['numeric-id'] break
		end

		national_team = mw.wikibase.getEntity( teamID )
		-- calculate s for national team item
		a, b = pcall(fooA, 'numeric-id', national_team, 'P31', 1) -- test if country
		if a == true and b == 20738667 then -- Q20738667 = national cycling team U23
			s = ' ' .. l10n('U23')
		else
			s = ''
		end

		a, b = timeStartEnd(riderID, "P27", 'numeric-id', startOfSeason)
		if a == true then
			nationality = l10n( 'Q' .. b, 'Q' .. b )
			if mw.wikibase.sitelink( teamID ) == nil then
				team = nationality .. s
			else
				team = "[[".. mw.wikibase.sitelink( teamID ) .. "|".. nationality.. s .. "]]"
			end
		end

		a, b = timeStartEnd(riderID, "P17", 'numeric-id', startOfSeason)
		if a == true then --team = 'abc'.. b --riderID
			nationality = l10n( 'Q' .. b, 'Q' .. b )
			if mw.wikibase.sitelink( teamID ) == nil then
				team = nationality .. s
			else
				team = "[[".. mw.wikibase.sitelink( teamID ) .. "|".. nationality.. s.. "]]"
			end
		end
	end) then
	else
		--standard team
		pcall(function()
		a, b = timeStartEnd(riderID, 'P54', 'numeric-id', startOfSeason)
		if a == true then
			team = WPlink('Q' .. b, 'team', startOfSeason)
		end
		-- guest team
		if teamID ~= nil then team = WPlink(teamID, 'team') end
		end)
	end

	return team
end

function formatDate(date, mode)
	--	local date = '+2016-05-20'
	--	local mode = 'small'
	if mode == 'long' then
		if l10nDef.formatDate['full'] ~= nil then
			return lang:formatDate(l10nDef.formatDate['full'], date)
		else
			return lang:formatDate("j F Y", date)
		end
	elseif mode == 'reference' then
		if l10nDef.formatDate['reference'] ~= nil then
			return lang:formatDate(l10nDef.formatDate['reference'], date)
		 else
			return formatDate(date, 'long') .. '.'
		 end
	elseif mode == 'monthyear' then
		if l10nDef.formatDate['monthyear'] ~= nil then
			return lang:formatDate(l10nDef.formatDate['monthyear'], date)
		 else
			return lang:formatDate("F Y", date) .. '.'
		 end
	elseif mode == 'small' then
		if l10nDef.formatDate['daymonth_short'] ~= nil then
			return lang:formatDate(l10nDef.formatDate['daymonth_short'], date)
		else
			return lang:formatDate("j M", date)
		end
	elseif mode == 'daymonth_long' then
		if l10nDef.formatDate['daymonth_long'] ~= nil then
			return lang:formatDate(l10nDef.formatDate['daymonth_long'], date)
		else
			return lang:formatDate("j F", date)
		end
	else
		return ''
	end
end

function p.teamroster(frame)
	if frame.args[1] ~= nil then frame.args[1] =	string.gsub(frame.args[1], "%c", "") end
	local squadSeason = mw.wikibase.getEntity( frame.args[1] )
	local flags, pays = {}, {}
	local riderIds, riderNames, riderBirthdays, givenname, familyname, riderTeam, time = {}, {}, {}, {}, {}, {}, {}
	local riderStart, riderEnd, riderPosition, riderReason, riderRef = {}, {}, {}, {}, {}
	local index, riderNames_transl, riderNames_notransl = {}, {}, {}
	local labelMissing = false
	local team, rider, startOfSeason
	local v = ''

	local function trans(date, month, day)
		if date ~= '' then
			local _, _, y, m, d = string.find(date, "(%d+)-(%d+)-(%d+)")
			if m == '00' then m = month end
			if d == '00' then d = day end
			date = '+'..y..'-'..m..'-'..d..'T00:00:00Z'
			return date
		else return '' end
	end
	local function name(i, names, givenname, familyname)
		if names == '' then return names end
		-- transform name "A B ..." into "B ... A"
		local name_parts = {'da', 'de', 'di', 'De', 'la', 'Le', 'ten', 'van', 'Van', 'да', 'ди', 'де', 'Де', 'ла', 'Ле', 'тен', 'ван', 'Ван'}
		local _, count = mw.ustring.gsub(names, " ", " ")
		local a,b,c,d = '', '', '', ''
		local done = false
		if count ~= nil then count = count + 1 else count = 1 end

		if count == 2 then
			_, _, a, b =  mw.ustring.find(names, "(%S+)%s+(%S+)")
			names = b .. ' ' .. a .. ":" .. i
		elseif count == 3 then
			local v
			_, _, a, b, c =  mw.ustring.find(names, "(%S+)%s+(%S+)%s+(%S+)")
			for _,v in ipairs(name_parts) do if b == v then names = b..' '..c..' '..a..":"..i done = true break end end
			if not done and familyname==2 then names = b..' '..c..' '..a..":"..i done = true
			elseif not done then names = c..' '..a..' '..b..":"..i done = true end
		elseif count > 3 then
			local v
			_, _, a, b, c, d =  mw.ustring.find(names, "(%S+)%s+(%S+)%s+(%S+)%s+(%S+)")
			for _,v in ipairs(name_parts) do if c == v then names = c..' '..d..' '..a..' '..b..":"..i done = true break end end
			if not done then names = b..' '..c..' '..d..' '..a..":"..i end
		end
		return names
	end

	local localFrame
	local sort
	--[[
	 The word 'sort' is used to sort the riders after the surname. It could look like this in the Wikipedia article
	{{Cycling race/teamroster|Q21769847
	| sort
	}}
	A rider called 'Laurens De Vreese' is sorted after 'De Vreese Laurens'. If you want to sort after 'Vreese Laurens De'
	change that in the code.
	]]
	if string.match(frame:getParent():getTitle(), '%P+') == mw.site.namespaces.Template.name
	then localFrame = frame:getParent() else localFrame = frame end
	if localFrame.args[2] ~= nil then
		if mw.ustring.find(mw.ustring.lower(localFrame.args[2]), "sort") then sort = true else sort = false end
	end
	if wiki == "lv" or wiki == "mk" or wiki == "ru" then sort = true end

	pcall(function() team = squadSeason.claims["P361"][1].mainsnak.datavalue.value['numeric-id'] end)

	startOfSeason = getStartOfSeason(squadSeason)

	local i = 1
	pcall(function()
	while squadSeason.claims["P527"][i]  do
		riderIds[i] = 'Q' .. squadSeason.claims["P527"][i].mainsnak.datavalue.value['numeric-id']
		riderNames[i] = WPlink(riderIds[i])

		rider = mw.wikibase.getEntity(riderIds[i])
		if pcall(function() riderBirthdays[i] = rider.claims["P569"][1].mainsnak.datavalue.value.time end
	   	) then else riderBirthdays[i] = '' end
	 	if pcall(function() local k	for k, _ in pairs(rider.claims["P735"]) do givenname[i] = k end end
	   	) then else givenname[i] = 0 end
	 	if pcall(function() local k for k, _ in pairs(rider.claims["P734"]) do familyname[i] = k end end
	   	) then else familyname[i] = 0 end

		riderNames_transl = mw.wikibase.label( riderIds[i] ) or ''

		if sort == true then
		riderNames_transl[i] = name(i, riderNames_transl[i], givenname[i], familyname[i])
		else index[i] = i
		end

		if pcall(function()
			local date = squadSeason.claims["P527"][i].qualifiers["P580"][1].datavalue.value.time or ''
			riderStart[i] = formatDate(trans(date,'01', '01'), 'small')
		end
		) then else riderStart[i] = '' end

		if pcall(function()
			local date = squadSeason.claims["P527"][i].qualifiers["P582"][1].datavalue.value.time
			riderEnd[i] = formatDate(trans(date,'12', '31'), 'small')
		end
		) then else riderEnd[i] = '' end

		if pcall(function()
		riderPosition[i] =  'Q' .. squadSeason.claims["P527"][i].qualifiers["P39"][1].datavalue.value['numeric-id']
		local label = string.gsub(mw.wikibase.label( riderPosition[i] ), "%b()", "") or ''
		riderPosition[i] = ', ' .. label end
		) then else riderPosition[i] = '' end

		riderReason[i] = ''
		pcall(function() riderReason[i] = 'Q'.. squadSeason.claims["P527"][i].qualifiers["P1643"][1].datavalue.value['numeric-id'] end)
		if riderReason[i] == '' then pcall(function() riderReason[i] = 'Q'.. squadSeason.claims["P527"][i].qualifiers["P1642"][1].datavalue.value['numeric-id'] end) end
		if riderReason[i] == '' then pcall(function() riderReason[i] = 'Q'.. squadSeason.claims["P527"][i].qualifiers["P1534"][1].datavalue.value['numeric-id'] end) end
		if riderReason[i] ~= '' then
			local label = string.gsub(mw.wikibase.label( riderReason[i] ), "%b()", "") or ''
			riderRef[i] = references(squadSeason, 'P527', i)
			riderReason[i] = ', ' .. label
		 end

		local a, b
		local timeofrace
		local changedTime = '+0000-00-00'
		local changedTeam = ''
		local label
		local stagiaire
		time[i]='' riderTeam[i] = ''
		if pcall(function() timeofrace = squadSeason.claims["P527"][i].qualifiers["P580"][1].datavalue.value.time end)
		then else timeofrace = startOfSeason end
		if team ~= nil then a = true b = team -- if team known, don´t search for team
			else a, b = timeStartEnd(riderIds[i], 'P54', 'numeric-id', timeofrace) team = b
		end
		if a == true and b ~= nil then
			pcall(function()
				local v
				for _, v in pairs(rider.claims["P54"]) do -- look into all P54 teams
					pcall(function() -- get trainee data from rider item
						if v.mainsnak.datavalue.value['numeric-id'] == b  then -- print riderStart[i], riderEnd[i], riderPosition[i], riderReason[i]
							if riderReason[i] == '' then pcall(function() riderReason[i] = 'Q'.. v.qualifiers["P1643"][1].datavalue.value['numeric-id'] end) end
							if riderReason[i] == '' then pcall(function() riderReason[i] = 'Q'.. v.qualifiers["P1642"][1].datavalue.value['numeric-id'] end) end
							if riderReason[i] == '' then pcall(function() riderReason[i] = 'Q'.. v.qualifiers["P1534"][1].datavalue.value['numeric-id'] end) end
							if string.sub(riderReason[i],1,1)=='Q' then -- only for these pcall-functions, not for those at line 970
								local label = string.gsub(mw.wikibase.label( riderReason[i] ), "%b()", "") or ''
								if pcall(function()	riderRef[i] = references(squadSeason, 'P527', i) end) then else riderRef[i]='' end
								--		riderRef[i] = references(squadSeason, 'P527', i)
								riderReason[i] = ', ' .. label
							end

							local date1 = v.qualifiers["P580"][1].datavalue.value.time
							date1 = trans(date1,'01','01')
							local _, _, y1, m1, d1 = string.find(date1, "(%d+)-(%d+)-(%d+)")
							local date2
							if pcall(function() date2 = v.qualifiers["P582"][1].datavalue.value.time end) then else date2='+'..y1..'-12-31T00:00:00Z' end
							date2 = trans(date2,'12','31')
							local _, _, y2, m2, d2 = string.find(date2, "(%d+)-(%d+)-(%d+)")
							local _, _, y3, m3, d3 = string.find(startOfSeason, "(%d+)-(%d+)-(%d+)")

							if  (y1 == y3 or y2 == y3) and ((y1 == y3 and (m1 ~= '01' or d1 ~= '01')) or (y2 == y3 and (m2 ~= '12' or d2 ~= '31'))) then
								-- riders who start after 1 January or end earlier then 31 December in the season
								riderStart[i] = formatDate(date1, 'small')
								if pcall(function()
									local date = v.qualifiers["P582"][1].datavalue.value.time
									riderEnd[i] = formatDate(date2, 'small')
									end
								) then else riderEnd[i] = formatDate('+'..y1..'-12-31T00:00:00Z', 'small') end

								if riderPosition[i] == '' then -- find the 'position' (P39) of a rider
									pcall(function() riderPosition[i] ='Q' ..v.qualifiers["P39"][1].datavalue.value['numeric-id']
										local label = string.gsub(mw.wikibase.label( riderPosition[i] ), "%b()", "") or ''
										riderPosition[i] = ', ' .. label
									end)
								end
							end
						end
					end)

					stagiaire = ''
					pcall(function() stagiaire = v.qualifiers["P39"][1].datavalue.value['numeric-id'] end)
					if v.mainsnak.datavalue.value['numeric-id'] ~= b and stagiaire == '' then -- find previous team and end time for the rider at that team
						local date1 = v.qualifiers["P580"][1].datavalue.value.time
						date1 = trans(date1,'01','01')
						local _, _, y1, m1, d1 = string.find(date1, "(%d+)-(%d+)-(%d+)")
						local date2
						if pcall(function() date2 = v.qualifiers["P582"][1].datavalue.value.time end) then else date2='+'..y1..'-12-31T00:00:00Z' end
						date2 = trans(date2,'12','31')
						local _, _, y2, m2, d2 = string.find(date2, "(%d+)-(%d+)-(%d+)")
						local _, _, y3, m3, d3 = string.find(startOfSeason, "(%d+)-(%d+)-(%d+)")
						if y1 <= y3 then -- start time < season time
							pcall(function()
								local timeP582 = v.qualifiers["P582"][1].datavalue.value.time
								timeP582 = trans(timeP582,'12', '31')
								if timeP582 >= changedTime then -- find maximum end time
									-- Case Pierre-Roger Latour: Chambéry CF (2012 - 2014), time season at 2013
									-- Task: changedTime should be after start time, but before startOfSeason
									local _, _, y4, m4, d4 = string.find(timeP582, "(%d+)-(%d+)-(%d+)")
									if y4 > y3 then changedTime = '+'..y3..'-12-31T00:00:00Z' else changedTime = timeP582 end
									changedTeam = v.mainsnak.datavalue.value['numeric-id']
	 							end -- end if
							end) -- end function
							-- print riderTeam[i], time[i]
							if changedTime ~= '+0000-00-00' then
								pcall(function() riderTeam[i] = WPlink( 'Q'..changedTeam , 'team', changedTime ) end)
								local _, _, y1, _, _ = string.find(changedTime, "(%d+)-(%d+)-(%d+)")
								time[i] = ' ('..y1..')'
							end
						end
					end -- end if
				end -- end for
			end) -- end function
		end -- end if

		local a, b = timeStartEnd( riderIds[i], 'P27', 'numeric-id', startOfSeason )
		if a then
			flags[i] = flag( 'Q' .. b, startOfSeason )
			pays[i] = l10n( 'Q' .. b, 'Q' .. b)
		else
			flags[i] = ''
			pays[i] = ''
		end

		i = i + 1
	end
	end)

	-- sorting names after surname
	if sort == true then
		if language~='ja' then
			table.sort(riderNames_transl, function(a,b) return a<b end)
		end
		local ii, v1, v2, name1, name2, number
		i = 1
		-- sorting riders
		for ii,name1 in ipairs(riderNames_transl) do
			if name1 ~= '' then
				v1, v2 = mw.ustring.find(name1, ":")
				number = mw.ustring.sub(name1, v2+1)
				name2, _ = mw.ustring.gsub(name1, ":%d+", "")
				index[i] = tonumber(number)
				i = i + 1
			end
		end
	end

	local tableBody= ''
	local tableHeader = '<table border="0" cellspacing="0" cellpadding="2">'
	   	.. '<tr style="background-color:#FFDF80;line-height:1.8em;"><th style="text-align:left;white-space:nowrap">'
	if WDlink_on == false then tableHeader = tableHeader .. '[[File:Wikidata-logo S.svg|12px|link=d:' .. frame.args[1] .. '#P527]]&nbsp;&nbsp;&nbsp;' end
	tableHeader = tableHeader .. l10n('rider_name')..'</th><th style="text-align:right;white-space:nowrap">' .. l10n('date_of_birth')
	tableHeader = tableHeader .. '</th><th style="text-align:left;padding:0 0.5em;white-space:nowrap">'.. l10n('nationality') .. '&nbsp;'
	tableHeader = tableHeader ..	'&nbsp;</th><th style="text-align:left;padding:0 0.5em;white-space:nowrap">' .. l10n('previous_team') .. '&nbsp;</th></tr>'
	local tableFoot = '</table>'
	local tableEndText = ''
	local tableSize = table.getn(riderNames)
	local iii = 1
	i = 1
	while index[i] do
		tableBody = tableBody .. '<tr style="line-height:1.8em"><td style="padding:0 1em 0 0;white-space:nowrap">' .. riderNames[index[i]]
	  	if WDlink_on == true then tableBody = tableBody.. ' '.. wdLink(riderIds[index[i]]) end
	   	if riderStart[index[i]]~='' or riderEnd[index[i]]~='' then
	   		tableBody=tableBody..'<span style="font-size:80%; color:#686868"> ('..riderStart[index[i]]..'–'..riderEnd[index[i]].. riderPosition[index[i]]
	   		if riderReason[index[i]] ~= '' then tableBody=tableBody.. ', [[#tr_'..i..frame.args[1]..'|'..l10n('note_short')..']]' end
	   		tableBody=tableBody .. ')</span>'
	   	elseif riderReason[index[i]]~='' then
	   		tableBody=tableBody.. '<span style="font-size:80%; color:#686868"> ([[#tr_'..i..frame.args[1]..'|'..l10n('note_short')..']]'.. ')</span>'
	   	end
	   	tableBody = tableBody.. '</td><td style="text-align:right;white-space:nowrap">'
		if wiki == 'lv' then
			local _, _, y1, m1, d1 = string.find(startOfSeason,"(%d+)-(%d+)-0*(%d+)")
			local _, _, y2, m2, d2 = string.find(riderBirthdays[index[i]],"(%d+)-(%d+)-0*(%d+)")
			tableBody = tableBody.. frame:expandTemplate{ title = 'Template:Birth date and age2', args = { y1, m1, d1, y2, m2, d2 } }.. '</td>'
		else
			tableBody = tableBody .. formatDate(riderBirthdays[index[i]], 'long') .. '</td><td>'.. flags[index[i]].. ' '..pays[i].. '</td>'
		end
		tableBody = tableBody .. '<td style="padding:0 0.5em; text-align:left">'
		if riderTeam[index[i]] ~= nil then tableBody = tableBody .. riderTeam[index[i]].. time[index[i]] end
		tableBody = tableBody ..'</td></tr>'

		if riderReason[index[i]] ~= '' then
			if iii == 1 then tableEndText = tableEndText.. l10n('note_long')..': '.. riderNames[index[i]].. riderReason[index[i]]
			else tableEndText = tableEndText.. '<span style="color:white">'.. l10n('note_long')..': </span>'.. riderNames[index[i]].. riderReason[index[i]] end
			iii = iii + 1
			if riderRef[index[i]] ~= '' then tableEndText = tableEndText..
				frame:extensionTag{name='ref', content=riderRef[index[i]], args = {name='tr_'..i..frame.args[1]}} end
			tableEndText = tableEndText.. '<br>'
		end
		i = i + 1
	end

	--if tableEndText ~= '' then tableEndText = l10n('note_long)..': <span style="font-size:80%; color:#686868">'.. tableEndText .. '</span>' end

	local borderStyle = 'border:1px solid rgb(200,200,200); padding: 4px'
	if wiki == 'lv' then
		borderStyle = 'border:0'
	end
	local tableStart = '<table style="' .. borderStyle .. '"><tr><td style="vertical-align:top;">'
	local tableEnd = '</td></tr></table>'

	if labelMissing then tableEnd = tableEnd .. getMissingLabelTrackingCategory() end

	return tableStart .. tableHeader .. tableBody .. tableFoot .. tableEnd .. tableEndText
end

function timeStartEnd(Qid, property, mode, timeofrace)
	-- mode = 'numeric-id', property = 'P54', Qid = 'Q123'
	local entity = 	mw.wikibase.getEntity(Qid)
	local starttime, endtime
	local a, b = pcall(fooA, mode, entity, property, 1)
	if a == true then
		local timeStartEnd = nil
		local timeStartEnd2 = nil
		local v
		for _, v in pairs(entity.claims[property]) do
			if pcall(function () local test = v.mainsnak.datavalue.value[mode] end) then -- test if not 'unknown value'
				if pcall(function () starttime = v.qualifiers["P580"][1].datavalue.value.time end) then
	   				starttime = v.qualifiers["P580"][1].datavalue.value.time
					local _,_,year,m,d = string.find(starttime,"(%d+)-(%d+)-(%d+)")
					if m == '00' and d == '00' then starttime = '+'..year..'-01-01T00:00:00Z' end
				end
				if pcall(function () endtime = v.qualifiers["P582"][1].datavalue.value.time end) then
					endtime = v.qualifiers["P582"][1].datavalue.value.time
					local _,_,year,m,d = string.find(endtime,"(%d+)-(%d+)-(%d+)")
					if m == '00' and d == '00' then endtime = '+'..year..'-12-31T00:00:00Z' end
					if m == '01' and d == '01' then endtime = '+'..year..'-12-31T00:00:00Z' end
				end
	  			if v.qualifiers then
	 				if (not v.qualifiers["P580"] or starttime <= timeofrace)
	 					and
	 					(not v.qualifiers["P582"] or endtime >= timeofrace)
	 				then
	 					if mode == 'text' then -- monolingual data type
							if v.mainsnak.datavalue.value.language == langcode then return a, v.mainsnak.datavalue.value.text end
							if v.mainsnak.datavalue.value.language == 'en' then timeStartEnd = v.mainsnak.datavalue.value.text
							else timeStartEnd2 = v.mainsnak.datavalue.value.text end
						else
							timeStartEnd = v.mainsnak.datavalue.value[mode]
						end
	 				end
	 			else
	 				timeStartEnd = v.mainsnak.datavalue.value[mode]
	 			end -- end if v.qualifiers
			end --end if unknown
	 	end --end for
		if timeStartEnd == nil and timeStartEnd2 ~= nil then timeStartEnd = timeStartEnd2 end
		return a, timeStartEnd
	else
		return false, ''
	end -- end if a == true
end

function black_list(label)
	-- List of Wikipedia articles with the same lemma as the non existing rider article. Those lemmas are printed as text "black" in the tables,
	-- not "blue" or "red". This way there will be no false wikilinks at the WhatLinksHere entry. List should be updated maybe once a year.
	if l10nDef.black_list ~= nil then
		for _, value in pairs(l10nDef.black_list) do
			if value == label then
				return true
			end
		end
	end
	return false
end

function WPlink(Qnumber, ...)
	if pcall(foo1, Qnumber) then
	else return 'unknown ID in function WPlink' end

	local link = ''
	local Sitelink = mw.wikibase.sitelink( Qnumber ) -- link to WParticle
	local Sitelink2 = Sitelink
	local Label = mw.wikibase.label( Qnumber ) or ''
	local a, b
	local official_name = ''

	if arg[1] == nil then
		if Sitelink ~= nil then
			if Label ~= '' then
				link = '[[' .. Sitelink .. '|' .. Label .. ']]'
			else
				link = '[[' .. Sitelink .. '|' .. mw.text.trim(mw.ustring.gsub(Sitelink2, '%b()', '')) .. ']]'
			end
		elseif Label ~= '' then
			if wiki == 'ar' then
				local title = mw.title.new(Label)
				if title.exists then
					link = Label
				else
					link = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {id=Qnumber,en='true'} }--"[[" .. Label.. "]]"
				end
			else
				if black_list(Label) == true then
					link = Label -- function black_list: articles that are printed as text, not wikilinks
				else -- detect if there is a different local article with the same name
					local title = mw.title.new(Label)
					if title.exists then
						link = Label
					else
						link = '[[' .. Label .. ']]'
					end
				end
			end
		end
	end -- if arg[1] == nil

	if arg[1] == 'pure' then
		Label = mw.ustring.gsub(Label, "^(%a)", function (x) return mw.ustring.upper(x) end) -- capitalize
		if Sitelink ~= nil then
			if Label ~= '' then
				link = '[[' .. Sitelink .. '|' .. Label .. ']]'
			else
				link = '[[' .. Sitelink .. '|' .. mw.text.trim(mw.ustring.gsub(Sitelink, '%b()', '')..' ') .. ']]'
			end
		elseif wiki == 'ar' then
			local title = mw.title.new(Label)
			if title.exists
				then link = Label
				else link = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {id=Qnumber,en='true'} }--"[[" .. Label.. "]]"
			end
		else
			link = Label
		end
	end -- end arg[1] == 'pure'

	if arg[1] == 'team' then -- add '(team of the winner)'
		a, b = timeStartEnd(Qnumber, 'P1448', 'text', arg[2]) --officialName(entity)
		local entity = mw.wikibase.getEntity( Qnumber )
		local a1, b1 = pcall(fooA, 'numeric-id', entity, 'P361', 1)
		if a1 == true then
			local a2, b2 = timeStartEnd('Q'..b1, 'P1448', 'text', arg[2])
			if a2 == true then
				a = a2
				b = b2
			end
			Sitelink2 = mw.wikibase.sitelink( 'Q' .. b1 ) -- link to WParticle
		end
		if a == true then official_name = b end

		if Sitelink ~= nil then
			if official_name == nil then
				link = '[[' .. Sitelink.. '|' .. mw.text.trim(mw.ustring.gsub(Sitelink, '%b()', '').. ' ') .. ']]'
			else
				link = link .. '[['.. Sitelink.. '|'.. official_name.. ']]'
			end
		end
		if link == '' and Sitelink2 ~= nil then -- code goes from season item to team item
			if official_name == nil or official_name == '' then
				link = '[[' .. Sitelink2.. '|'.. mw.text.trim(mw.ustring.gsub(Sitelink2, '%b()', '').. ' ') .. ']]'
			else
				link = link .. '[['.. Sitelink2..'|'.. official_name.. ']]'
			end
		end

		if Sitelink == nil and Sitelink2 == nil then
			if official_name ~= '' then
				link = official_name
			else
				link = Label
			end
		end
	end -- end arg[1] == 'team'

	if arg[1] == 'Q22348500' then -- add weblink from item "Q22348500" if available
		if Sitelink ~= nil then
			if Label ~= '' then
				link = '[[' .. Sitelink .. '|' .. Label .. ']]'
			else
				link = '[[' .. Sitelink .. ']]'
			end
		else
			local Sitelink_class = mw.wikibase.sitelink( 'Q22348500' )
			if Sitelink_class ~= nil then
				if Label ~= '' then
					link = '[[' .. Sitelink_class .. '|' .. Label .. ']]'
				else
					link = ''
				end
			else
				link = Label
			end
		end
	end -- end arg[1] == 'Q22348500'

	if link == '' then
		link =  '(label missing)'
	end

	return link
end -- end function WPlink

function getMissingLabelTrackingCategory()
	if l10nDef.missingLabelTrackingCategory ~= nil then
		return l10nDef.missingLabelTrackingCategory
	else
		return ''
	end
end -- end function getMissingLabelTrackingCategory

function fooA (mode,entity,property,var)
	local snak
	if mode=="value" then snak=entity.claims[property][var].mainsnak.datavalue.value
	else snak=entity.claims[property][var].mainsnak.datavalue.value[mode]
	end
	return snak, entity.claims[property][var].rank
end

function fooB (mode, entity_var, property, var1, var2, ref, var3)
	local snak
	if mode == 'value' then snak = entity_var.claims[property][var1].references[var2].snaks[ref][var3].datavalue.value
	else snak = entity_var.claims[property][var1].references[var2].snaks[ref][var3].datavalue.value[mode]
	end
	return snak
end

function fooC (mode, entity_var, property, var1, quali, var2)
	local snak
	if mode == 'value' then snak = entity_var.claims[property][var1].references[var2].snaks[ref][var3].datavalue.value
	else snak = entity_var.claims[property][var1].qualifiers[quali][var2].datavalue.value[mode]
	end
	return snak
end

function foo1 (arg)
	local entity = mw.wikibase.getEntity( arg )
end

function foo2 (entity_var, property, var)
	local snak = entity_var.claims[property][var].mainsnak.datavalue.value.amount
end

function foo3 (entity_var, property, var1, quali, var2)
	local snak = entity_var.claims[property][var1].qualifiers[quali][var2].datavalue.value.amount
end

function winner(t, winner_id)
	local number = t.number
	local winner_id = winner_id
	local tt = {}
	for num=1,number do table.insert(tt, "") end

	for num=1,number do
		local entity_race = mw.wikibase.getEntity(t.race[num][1])
		if pcall(fooA, 'numeric-id', entity_race, 'P1346', 1) == true then
		for k, v1 in pairs(entity_race.claims['P1346']) do
			if pcall(fooC, 'numeric-id', entity_race, 'P1346', k, 'P642', 1) == true and v1.qualifiers.P642[1].datavalue.value['numeric-id'] == winner_id then
				local time_var, a, b
				local winner = "Q"..v1.mainsnak.datavalue.value['numeric-id']

				-- get date of the race, e.g. "+2016-01-01T00:00:00Z"
				-- P585 (point in time for a single day race) or P580 (start time for a stage race)
				a, b = pcall(fooA, 'time', entity_race, 'P585', 1)
				if a == true then time_var = b
				else
					a, b = pcall(fooA, 'time', entity_race, 'P580', 1)
					if a == true then time_var = b end
				end

				-- get nationality of the winner, nationality could have changed, therefore look for qualifiers p580 and p582
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( winner ), 'P27', 1) -- standard: only one nationality
				if a == true then
					tt[num] = flag("Q"..b, time_var) .. " " .. WPlink(winner) .. " "
					if WDlink_on == true then tt[num] = tt[num].. wdLink(winner) end
				else if WDlink_on == true then tt[num] = "  " .. wdLink(winner) else tt[num] = "" end
				end

				-- if person has more than one nationality calculate tt[num] again
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( winner ), 'P27', 2)
				if a == true then
					local _, bb = timeStartEnd(winner, "P27", 'numeric-id', time_var)
					tt[num] = flag('Q'..bb, time_var) .. " " .. WPlink(winner) .. " "
					if WDlink_on == true then tt[num] = tt[num].. wdLink(winner) end
				end
			end -- if v1.
		end -- for k, v1
		end -- if
	end -- for num=
	return tt
end

function p.listofwinners(frame)
	local t = {number, race={}, year={}, vainqueur, second, troisieme}
	frame.args[1] =	string.gsub(frame.args[1], "%c", "")
	local entity = mw.wikibase.getEntity( frame.args[1] )
	local WPcontent = {}

	local localFrame
	if string.match(frame:getParent():getTitle(), '%P+') == mw.site.namespaces.Template.name
	then localFrame = frame:getParent() else localFrame = frame end
	if localFrame.args[1] ~= nil then localFrame.args[1] = string.gsub(localFrame.args[1], "%c", "") end
--[=[
It is possible to give the table listofwinners in the article commands. It could look like this:
{{Cycling race/listofwinners|Q18574623
| above row 1: '''[[aaa bbb ccc]]''' xxx
}}
"above row x" inserts a new row above row x into the table. Content is what is behind the ":".
]=]
	if localFrame.args[2] ~= nil then
		for num,var in pairs(localFrame.args) do
			if num > 1 and mw.ustring.find(mw.ustring.lower(localFrame.args[num]), 'row') then
				local _, _, key1, val = mw.ustring.find(localFrame.args[num], "([^:]+)%s*:%s*(%C+)")
				local _, _, key01, key11, key12 = mw.ustring.find(key1, "(%a+)%s*(%a+)%s*(%d+)")
				key12 = tonumber(key12) key11 = mw.ustring.lower(key01..key11)
				if key11 == 'aboverow' then WPcontent[key12] = val end
			end
		end
	end

	local num = 0
	if pcall(fooA, 'numeric-id', entity, 'P527', 1) == true then
		for k, v1 in pairs(entity.claims['P527']) do
			local year, race, entity_race, a, b
			race = 'Q'..v1.mainsnak.datavalue.value['numeric-id'] -- Qnumbers of the parts of a tour
			entity_race = mw.wikibase.getEntity(race)

			-- P585(point in time for a single day race) or P580(start time for a stage race)
			a, b = pcall(fooA, 'time', entity_race, 'P585', 1)
			if a == true then year = b
			else
				a, b = pcall(fooA, 'time', entity_race, 'P580', 1)
				if a == true then year = b end
			end

			if year ~= nil then _, _, year, _, _ = string.find(year, "(%d+)-(%d+)-(%d+)") end
			table.insert(t.race, { race, year} )
			table.sort(t.race, function(a,b) return a[2] < b[2] end) -- t.race is sorted after year
			num = num + 1
		end
	end -- for k, v1
	t.number = num

	for num=1, t.number do -- build year column with link to wikipedia article and to wikidata item
		local sitelink = mw.wikibase.sitelink( t.race[num][1] )
		if sitelink == nil then sitelink = t.race[num][2] else sitelink = "[[" .. sitelink .. "|" .. t.race[num][2] .. "]]"	end
		if WDlink_on == false then table.insert(t.year, sitelink) else table.insert(t.year, sitelink.. " " .. wdLink(t.race[num][1]) ) end
	end

	t.vainqueur = winner(t, 20882667) -- build vainqueur column
	t.second = winner(t, 20882668) -- build second column
	t.troisieme = winner(t, 20882669) -- build troisiem column

	local table_first = "<table cellpadding='4' cellspacing='0' style='border:1px solid rgb(200,200,200); color:black;"..
		"margin:0 0 0.5em 0; background-color:rgb(255, 255, 255); padding:5px; clear:left; "..
		"text-align:left; vertical-align:top; font-size:85%; line-height:1.6em;'>"
	local table_proto = "<tr style='background:#FFDF80; text-align:center'><th>"
	if WDlink_on == false then table_proto = table_proto .. '<span style="float:left">[[File:Wikidata-logo S.svg|12px|link=d:'.. frame.args[1].. '#P527]]</span>' end
	table_proto = table_proto.. l10n('year').. "</th><th>".. l10n('winner').. "</th><th>".. l10n('second').. "</th><th>".. l10n('third').. "</th></tr>"
	local table_center, table_last = "", "</table>"

	for var=1, t.number do
		if type(WPcontent) == 'table' and WPcontent[var] ~= nil then table_center = table_center..
			"<tr><td colspan='4' style='text-align:center'>".. WPcontent[var].. "</td></tr>" end

		table_center = table_center .. "<tr><td style='text-align:center'>".. t.year[var].."</td>"
		table_center = table_center .. "<td>"..t.vainqueur[var].."</td>"
		table_center = table_center .. "<td>"..t.second[var].."</td>"
		table_center = table_center .. "<td>"..t.troisieme[var].."</td></tr>"
	end
	return table_first .. table_proto .. table_center .. table_last
end

function p.listofstages(frame)
	if frame.args[1] ~= nil then frame.args[1] = string.gsub(frame.args[1], "%c", "") end
	local i, k, v, uu, ii, nationality
	local entity, etape, stage = {}, {}, {}
	local series_ordinal, point_of_time, length = {}, {}, {}
	local sitelinks_etape, sitelinks1, sitelinks2, sitelinks3, sitelinks4 = {}, {}, {}, {}, {}
	local flag1, flag2 = {}, {}
	local number0, number1, number2 = {}, {}, {}
	local level = false
	local a, b, num, var
	local entity0 = mw.wikibase.getEntity( frame.args[1] )
	local _, _, key1, key01, key11, key12, key2, key21, key22, val
	local WPcontent = {}

	local localFrame
	if string.match(frame:getParent():getTitle(), '%P+') == mw.site.namespaces.Template.name
	then localFrame = frame:getParent() else localFrame = frame end
	if localFrame.args[1] ~= nil then localFrame.args[1] = string.gsub(localFrame.args[1], "%c", "") end
--[=[ It is possible to give the table listofstages in the article commands which overwrites data from Wikidata. It could look like this:
{{Cycling race/listofstages|Q18574623
| RoW  1: locaTION Ab : [[1a1b]]
| after row 1 : date : 99 août
| after row 1 : icon : [[File:Stage rest day.svg|vbght frthzt fdgtr]]
| after row 1: text : rest day at [[aaa bbb ccc]]
|row 4:  location A : [[4a4a]]abc
| row 3 : winner a : <sup>tzhgt<sup/>
| row 4 : winner b : kjuzhgt<br />bbjje
| row 4 : icon : [[File:Mediummountainstage.svg|xcvbbgf fgtr]]
| row 4 : distance : <s>141.8</s> 122<ref>test</ref>
}}
The first paramer is "row x" or "after row x". "after row" adds a new row after row x into the table to print e.g. a rest day. The second parameters are
"location [a/b/ab]", "date", "icon", "text", "winner [a/b]" and "distance". "a" and "b" means the first and the second location or winner. "ab" could be used if
start location and end location are the same. The file data for the icon looks this way: [[File:Stage rest day.svg|any text]]
]=]
	if localFrame.args[2] ~= nil then
		local WProw, WPnew_row, WPcourse, WPtext, WPdate, WPwinner, WPicon, WPdistance = 'row', 'afterrow', 'location', 'text', 'date', 'winner', 'icon', 'distance'
		for num,var in pairs(localFrame.args) do
			if num > 1 and mw.ustring.find(mw.ustring.lower(localFrame.args[num]), WProw) then
				_, _, key1, key2, val = mw.ustring.find(localFrame.args[num], "([^:]+)%s*:?%s*([^:]*)%s*:%s*(%C+)")
				_, _, key01, key11, key12 = mw.ustring.find(key1, "(%a+)%s*(%a+)%s*(%d+)")
				key12 = tonumber(key12) key11 = mw.ustring.lower(key01..key11)
				key2 = mw.ustring.lower(mw.text.trim(key2))
				_, _, key21, key22 = mw.ustring.find(key2, "(%a+)%s*(%a*)")
				key21 = mw.ustring.lower(key21) key22 = mw.ustring.lower(key22)

				if type(WPcontent[key12]) ~= 'table' then WPcontent[key12] = {} end
				if key11 == WProw and key21 == WPcourse then WPcontent[key12][key22] = val end
				if key11 == WPnew_row and key2 == WPdate then
					WPcontent[key12]['date'] = val
					WPcontent[key12]['text'] = WPcontent[key12]['text'] or ''
					WPcontent[key12]['icon (new row)'] = WPcontent[key12]['icon (new row)'] or ''
				end
				if key11 == WPnew_row and key2 == WPtext then
					WPcontent[key12]['text'] = 	val
					WPcontent[key12]['date'] = 	WPcontent[key12]['date'] or ''
					WPcontent[key12]['icon (new row)'] = WPcontent[key12]['icon (new row)'] or ''
				end
				if key11 == WPnew_row and key2 == WPicon then
					val = mw.ustring.gsub(val, "|", "|border|right|20px|", 1)
					WPcontent[key12]['icon (new row)'] = val
					WPcontent[key12]['date'] = 	WPcontent[key12]['date'] or ''
					WPcontent[key12]['text'] = WPcontent[key12]['text'] or ''
				end
				if key11 == WProw and key21 == WPwinner and key22 == 'a' then WPcontent[key12]['stage winner'] = val end
				if key11 == WProw and key21 == WPwinner and key22 == 'b' then WPcontent[key12]['general winner'] = val end
				if key11 == WProw and key21 == WPicon then
					val = mw.ustring.gsub(val, "|", "|border|right|20px|", 1) WPcontent[key12]['icon'] = val end
				if key11 == WProw and key21 == WPdistance then WPcontent[key12]['distance'] = val end
			end
		end
	end
	-- if there is one 'P527' then level = true
	a, b = pcall(fooA, 'numeric-id', entity0, 'P527', 1)
	if a == true then level = true end

	-- read series_ordinal and the Qnumber and sort them after series_ordinal, eg: 1 2a 2b 3 4 5
	local parts = {}
	for num, v in pairs(entity0.claims["P527"]) do
		etape[num] = 'Q'..v.mainsnak.datavalue.value['numeric-id']
		entity[num] = mw.wikibase.getEntity( etape[num] )
		a, b = pcall(fooA, 'value', entity[num], 'P1545', 1)
		if a == true then series_ordinal[num] = b else series_ordinal[num] = " " end
		table.insert(parts, num, {nr = series_ordinal[num], Qnum = etape[num]})
	end

	-- sort parts after nr = series_ordinal[num], not Qnum
	table.sort(parts, function(a, b)
		local num1 = string.sub(a.nr, string.find(a.nr, "%d+"))
		local num2 = string.sub(b.nr, string.find(b.nr, "%d+"))
		local char1, char2
		if string.find(a.nr, "%a") then char1 = string.sub(a.nr, string.find(a.nr, "%a")) else char1 = "" end
		if string.find(b.nr, "%a") then char2 = string.sub(b.nr, string.find(b.nr, "%a")) else char2 = "" end

		local comp
		if char1 == "" and char2 == "" then comp = tonumber(num1) < tonumber(num2) end
		if char1 ~= "" or char2 ~= "" then comp = tonumber(num1) < tonumber(num2) end
		if char1 ~= "" and char2 ~= "" then
			if num1 == num2 then comp = char1 < char2
			else comp = tonumber(num1) < tonumber(num2)
			end
		end
		return comp end)

	for num=1,#entity0.claims["P527"] do
		-- collect data from Wikidata in tables
		entity[num] = mw.wikibase.getEntity( parts[num].Qnum )
		if WDlink_on == false then number0[num]= " " else number0[num] = "&nbsp;" .. wdLink(parts[num].Qnum) end
		sitelinks_etape[num] = entity[num]:getSitelink()

		a, b = pcall(fooA, 'value', entity[num], 'P1545', 1)
		if a == true then series_ordinal[num] =  b else series_ordinal[num] = " " end
		a, b = pcall(fooA, 'time', entity[num], 'P585', 1)
		if a == true then point_of_time[num] =  b else point_of_time[num] = " " end
		a, b = pcall(fooA, 'numeric-id', entity[num], 'P1427', 1)
		if a == true then sitelinks1[num] =  WPlink( 'Q'..b, 'pure' ) else sitelinks1[num] = " " end
		a, b = pcall(fooA, 'numeric-id', entity[num], 'P1444', 1)
		if a == true then sitelinks2[num] =  WPlink( 'Q'..b, 'pure' ) else sitelinks2[num] = " " end
		a, b = pcall(fooA, 'amount', entity[num], 'P3157', 1)
		if a == true then length[num] =  b else length[num] = " " end
		a, b = pcall(fooA, 'amount', entity[num], 'P2043', 1)
		if a == true then length[num] =  b else if length[num] ~= ' ' then length[num] = " " end end

		flag1[num] = ' '
		sitelinks3[num] = ' '
		number1[num]  = ' '
		local id, qual
		-- find the vainqueur d'étape, Q20882747
		if pcall(foo3, entity[num], "P1346", 1, "P642", 1) then
			local v
			for _, v in pairs(entity[num].claims["P1346"]) do
				if pcall(function() id = v.mainsnak.datavalue.value['numeric-id'] end) then else id = nil end
				qual = v.qualifiers["P642"][1].datavalue.value["numeric-id"]
				if id ~= nil and v.rank ~= 'deprecated' then
					if qual == 20882747 then
						number1[num]  = 'Q' .. id
						a, b = timeStartEnd(number1[num], "P27", 'numeric-id', point_of_time[num])
						if a == true then
							flag1[num] = flag('Q'..b, point_of_time[num])
							sitelinks3[num] = WPlink( number1[num] )
						else
							a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity(number1[num]), 'P17', 1)
							if a == true then
								flag1[num] = flag('Q'..b, point_of_time[num])
								sitelinks3[num] = WPlink( number1[num], 'team', point_of_time[num] )
							end
						end
						if WDlink_on == false then number1[num]="" else number1[num] =
							"<span style='white-space:nowrap'>&nbsp;[[File:Wikidata-logo S.svg|12px|link=d:".. number1[num] .. ']]</span>' end
					end
				end -- if id
			end	-- for
		end  -- end if pcall

		flag2[num] = ' '
		sitelinks4[num] = ' '
		number2[num]  = ' '
		local id, qual
		-- find the leader du classement général à l'issue de l'étape, Q20882763
		if pcall(foo3, entity[num], "P1346", 1, "P642", 1) then
			local v
			for _, v in pairs(entity[num].claims["P1346"]) do
				if pcall(function() id = v.mainsnak.datavalue.value['numeric-id'] end) then else id = nil end
				qual = v.qualifiers["P642"][1].datavalue.value["numeric-id"]
				if id ~= nil and v.rank ~= 'deprecated' then
					if qual == 20882763 or qual == 20882667 then
						number2[num]  = 'Q' .. id
						a, b = timeStartEnd(number2[num], "P27", 'numeric-id', point_of_time[num])
						if a == true then
							flag2[num] = flag( 'Q'..b, point_of_time[num])
							sitelinks4[num] = WPlink( number2[num] )
						else
							a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity(number2[num]), 'P17', 1)
							if a == true then
								flag2[num] = flag( 'Q'..b, point_of_time[num])
								sitelinks4[num] = WPlink( number2[num], 'team' )
							end
						end
						if WDlink_on == false then number2[num]="" else number2[num] =
							"<span style='white-space:nowrap'>&nbsp;[[File:Wikidata-logo S.svg|12px|link=d:"..number2[num] .. ']]</span>' end
					end
				end -- if id
			end	-- for
		end  -- end if pcall

		if pcall(function()
			-- find the type of stages
			i = 1
			stage[num] = ""
			uu = entity[num].claims["P31"][i].mainsnak.datavalue.value['numeric-id']
			while entity[num].claims["P31"][i] do
				if uu == 20646667 then stage[num] = typeofstage('plain stage') break end
				if uu == 20646670 then stage[num] = typeofstage('hilly stage') break end
				if uu == 20680270 then stage[num] = typeofstage('intermediate stage') break end
				if uu == 20646668 then stage[num] = typeofstage('mountain stage') break end
				if uu == 485321 then stage[num] = typeofstage('time trial stage', 485321) break end -- prologue
				if uu == 2266066 then stage[num] = typeofstage('time trial stage', 2266066) break end -- individual time trial
				if uu == 2348250 then stage[num] = typeofstage('time trial stage', 2348250) break end -- team time trial
				if uu == 20679712 then stage[num] = typeofstage('uphill time trial stage') break end
				i = i + 1
			end
			end)
		then else stage[num] = " " end

	end -- end for num=1,var do

	local table_first, table_proto, table_last
	table_first = "<table border='0' cellpadding='4' cellspacing='0' style='border:1px solid rgb(200,200,200); color:black; "
	table_first = table_first .. "margin:0 0 0.5em 0; background-color:rgb(255, 255, 255); padding:5px; clear:left; "
	table_first = table_first .. "text-align:left; font-size:85%; line-height:1.6em;'>"
	table_proto = "<tr style='background:#FFDF80; text-align:center;'><th style='white-space:nowrap'>"
	if WDlink_on == false then table_proto = table_proto .. "[[File:Wikidata-logo S.svg|12px|link=d:".. localFrame.args[1].. "#P527]]" end
	table_proto = table_proto.. l10n('stage') .."</th><th>" ..	l10n('date') .."</th><th>".. l10n('stopover')..
	"</th>".. "<th style='color:#FFDF80'>type</th>" .."<th>".. l10n('distance_km').. "</th><th>".. l10n('stage_winner').."</th><th>".. l10n('overall_leader').. "</th></tr>"
	table_last = "</table>"

	 -- build table for output
	local table_center = ""
	for num=1, #entity0.claims["P527"] do
		local ee = stageLink(series_ordinal[num])
		if series_ordinal[num] == "0" then
			ee = i10n('prolog')
		end
		local stageNr -- if there is a wikipedia article of that stage show it
		if sitelinks_etape[num] == nil then stageNr = ee else stageNr = '[[' .. sitelinks_etape[num] .. '|' .. ee .. ']]' end
		if wiki == 'lv' then stageNr = series_ordinal[num] end

		date = formatDate(point_of_time[num], 'daymonth_short')
		if wiki == 'fr' then date = string.gsub(date, '(1 )', '1<sup>er</sup> ') end

		if pcall(function()
			length[num] = lang:formatNum(tonumber(length[num]))
			end
		) then else length[num] = " " end

		if type(WPcontent[num]) == 'table' and WPcontent[num]['a'] ~= nil then sitelinks1[num] = WPcontent[num]['a'] end
		if type(WPcontent[num]) == 'table' and WPcontent[num]['b'] ~= nil then sitelinks2[num] = WPcontent[num]['b'] end
		if type(WPcontent[num]) == 'table' and WPcontent[num]['ab'] ~= nil then sitelinks1[num] = WPcontent[num]['ab'] sitelinks2[num] = '' end
		if type(WPcontent[num]) == 'table' and WPcontent[num]['icon'] ~= nil then stage[num] = WPcontent[num]['icon'] end
		if type(WPcontent[num]) == 'table' and WPcontent[num]['distance'] ~= nil then length[num] = WPcontent[num]['distance'] end
		if type(WPcontent[num]) == 'table' and WPcontent[num]['stage winner'] ~= nil then
			flag1[num] = '' sitelinks3[num] = WPcontent[num]['stage winner'] number1[num]= '' end
		if type(WPcontent[num]) == 'table' and WPcontent[num]['general winner'] ~= nil then
			flag2[num] = '' sitelinks4[num] = WPcontent[num]['general winner'] number2[num]= '' end

		table_center = table_center.. "<tr><td style='text-align:center; white-space:nowrap'>".. stageNr .. "<span style='white-space:nowrap'>&nbsp;".. number0[num].."</span>"..
		"</td><td style='white-space:nowrap; text-align:right; padding-right:0px'>"..date.. "</td><td style='padding-right:0px'>".. sitelinks1[num]
		if sitelinks2[num] ~= '' then table_center = table_center.. " – " end
		table_center = table_center.. sitelinks2[num].."</td><td style='padding-top:10px'>".. stage[num].. "</td><td style='text-align:center'>".. length[num].. "</td>"
		if type(WPcontent[num]) == 'table' and WPcontent[num]['stage winner'] ~= nil then
			table_center = table_center.. "<td style='text-align:center'>".. flag1[num].. ' '.. sitelinks3[num].. number1[num] .. "</td>"
		else table_center = table_center.. "<td>".. flag1[num].. ' '.. sitelinks3[num].. number1[num] .. "</td>" end
		if type(WPcontent[num]) == 'table' and WPcontent[num]['general winner'] ~= nil then
			table_center = table_center.. "<td style='text-align:center'>".. flag2[num].. ' '.. sitelinks4[num].. number2[num].. "</td></tr>"
		else table_center = table_center.. "<td>".. flag2[num].. ' '.. sitelinks4[num].. number2[num].. "</td></tr>" end

		if type(WPcontent[num]) == 'table' and (WPcontent[num]['date'] ~= nil or WPcontent[num]['text'] ~= nil or WPcontent[num]['icon (new row)'] ~= nil)
		then table_center = table_center.. "<tr><td></td>"
			if WPcontent[num]['icon (new row)'] == '' then table_center = table_center.."<td style='text-align:right; padding:3px 0px 10px 0px;white-space:nowrap'>".. WPcontent[num]['date']
			else table_center = table_center.."<td style='text-align:right; padding-right:0px'>".. WPcontent[num]['date'] end
			if WPcontent[num]['icon (new row)'] == '' then table_center = table_center.."</td><td style='text-align:left; padding:3px 4px 10px'>"..WPcontent[num]['text']
			else table_center = table_center.."</td><td style='text-align:left'>"..WPcontent[num]['text'] end
			table_center = table_center.."</td><td style='padding-top:10px'>".. WPcontent[num]['icon (new row)'].. "</td><td colspan='3' ></td></tr>"
		end
	end

	local tabl = table_first.. table_proto
	if level == true then tabl = tabl.. table_center.. table_last else tabl = tabl.. table_last end
	return tabl
end -- end function p.listofstages

function stageLink(x) -- x= 10a or x = 5
	a, _ = string.gsub(x, '%a', '') -- 20, not 20a
	if string.find(x, '%a') then b = string.sub(x, string.find(x, '%a')) else b = '' end
	local number = number(a, 'f')
	if b == '' then
		return number .. l10n('stage')
	else
		return number .. b .. ' ' .. l10n('stage')
	end
end -- end function stageLink

function typeofstage(x, typ)
 	if x=='plain stage' then return "[[File:Plainstage.svg|border|right|20px|"..l10n('plain').."]]" end
 	if x=='hilly stage' then return "[[File:Hillystage.svg|border|right|20px|"..l10n('hilly').."]]" end
  	if x=='intermediate stage' then return "[[File:Mediummountainstage.svg|right|border|20px|"..l10n('inter').."]]" end
  	if x=='mountain stage' then return "[[File:Mountainstage.svg|border|right|20px|"..l10n('mount').."]]" end
  	if x=='uphill time trial stage' then return "[[File:Mountain Time Trial Stage.svg|border|right|20px|"..l10n('uphill').."]]" end
   	if x=='rest day' then return "[[File:Stage rest day.svg|border|right|20px|"..l10n('rest').."]]" end
   	if x=='time trial stage' then
   		if typ==2348250 then return "[[File:Team Time Trial Stage.svg|right|20px|"..l10n('time_team').."]]" end
   		if typ==2266066 then return "[[File:Time Trial.svg|right|20px|"..l10n('time_indiv').."]]" end
   		if typ==485321  then return "[[File:Time Trial.svg|right|20px|"..l10n('time_prologue').."]]" end
	end
end -- end function typeofstage

function wdLink(id)
	return "[[File:Wikidata-logo S.svg|12px|link=d:" .. id .. "]]"
end -- end function wdLink

function flag(x, date)
	local year,m,d
	if date==nil then date = '+'..os.date('%Y-%m-%d') end
	local flag1 = { -- Q..a current flag, Q..b, Q..c older flag. date: "+2016", "+2016-01-30", ..
	Q29a={"[[File:Flag of Spain.svg|border|20px|ESP]]","+1982",""},
	Q29b={"[[File:Flag of Spain (1977 - 1981).svg|border|20px|ESP]]","+1977","+1981"},
	Q30= "[[File:Flag of the United States (Pantone).svg|border|20px|USA]]",
	Q31= "[[File:Flag of Belgium (civil).svg|border|20px|BEL]]",
	Q38a={"[[File:Flag of Italy.svg|border|20px|ITA]]","+1947",""},
	Q38b={"[[File:Flag of Italy (1861-1946) crowned.svg|border|20px|ITA]]","+1861","+1946"},
	Q39="[[File:Flag of Switzerland.svg|border|15px|SUI]]",
	Q55= "[[File:Flag of the Netherlands.svg|border|20px|NED]]",
	Q142="[[File:Flag of France.svg|border|20px|FRA]]",
	Q145="[[File:Flag of the United Kingdom.svg|border|20px|GBR]]",
	Q183a={"[[File:Flag of Germany.svg|border|20px|GER]]","+1949-05-23",""},
	Q183b={"[[File:Flag of German Reich (1935–1945).svg|border|20px|GER]]","+1935","+1945"},
	Q183c={"[[File:Flag of the NSDAP (1920–1945).svg|border|20px|GER]]","+1933","+1935"},
	Q183d={"[[File:Flag of Germany (3-2 aspect ratio).svg|border|20px|GER]]","+1919","+1933"},
	Q183e={"[[File:Flag of the German Empire.svg|border|20px|GER]]","+1866","+1918"},
	Q218a={"[[File:Flag of Romania.svg|border|20px|ROU]]","+1989-12-27",""},
	Q218b={"[[File:Flag of Romania (1965-1989).svg|border|20px|ROU]]","+1965","+1989-12-26"},
	Q218c={"[[File:Flag of Romania (1952-1965).svg|border|20px|ROU]]","+1952","+1965"},
	Q218d={"[[File:Flag of Romania (1948-1952).svg|border|20px|ROU]]","+1948","+1952"},
	Q218e={"[[File:Flag of Romania.svg|border|20px|ROU]]","+1867-07-01","+1948"},
	Q224a={"[[File:Flag of Croatia.svg|border|20px|CRO]]","+1990-12-21",""},
	Q224b={"[[File:Flag of Croatia (white chequy).svg|border|20px|CRO]]","+1990-06-27","+1990-12-21"}
	}

	if flag1[x..'a']~=nil and date>=flag1[x..'a'][2] and flag1[x..'a'][3]=='' then return flag1[x..'a'][1] end
	if flag1[x..'b']~=nil and date>=flag1[x..'b'][2] and date<=flag1[x..'b'][3] then return flag1[x..'b'][1] end
	if flag1[x..'c']~=nil and date>=flag1[x..'c'][2] and date<=flag1[x..'c'][3] then return flag1[x..'c'][1] end
	if flag1[x..'d']~=nil and date>=flag1[x..'d'][2] and date<=flag1[x..'d'][3] then return flag1[x..'d'][1] end
	if flag1[x..'e']~=nil and date>=flag1[x..'e'][2] and date<=flag1[x..'e'][3] then return flag1[x..'e'][1] end
	if flag1[x]~=nil then return flag1[x] end

	local flag2 = { Q16={'Q80110','CAN'}, Q17={'Q43175','JPN'}, Q20={'Q83149','NOR'}, Q27={'Q82205','IRL'}, Q32={'Q133022','LUX'}, Q33={'Q47891','FIN'},
	Q34={'Q81286','SWE'}, Q35={'Q60149','DEN'}, Q36={'Q42436','POL'}, Q37={'Q81477','LTU'}, Q39={'Q124020','SUI'}, Q77={'Q171103','URU'},
	Q96={'Q122462','MEX'}, Q145={'Q83278','GBR'}, Q159={'Q16611','RUS'}, Q191={'Q81471','EST'}, Q211={'Q130449','LAT'}, Q212={'Q127974','UKR'},
	Q213={'Q127155','CZE'}, Q214={'Q160861','SVK'}, Q232={'Q131650','KAZ'}, Q262={'Q83392','DZA'}, Q408={'Q81676','AUS'}, Q414={'Q130774','ARG'},
	Q664={'Q160260','NZL'}, Q717={'Q165538','VEN'}, Q739={'Q160425','COL'} }

	local xx
	if flag_table[x] ~= nil then return flag_table[x] end

	if flag2[x]~=nil then xx = x x = flag2[x] end -- transform x to new x
	if type(x)=='table' and pcall(foo1,x[1]) then -- for transformed x
		local entity=mw.wikibase.getEntity(x[1])
		local a,b=pcall(fooA,'value',entity,'P18',1) -- P18 (image)
		if a==true then
			flag_table[xx] = "[[File:"..b.."|border|20px|"..x[2].."]]"
			return "[[File:"..b.."|border|20px|"..x[2].."]]"
		end
	end
	if type(x)=='string' and pcall(foo1,x) then -- reading the flag data from untransformed items, e.g. Q29
		local entity = mw.wikibase.getEntity( x )
		local flags = entity.claims["P41"]
		local possible_flag = {}
		local num = 1
		if pcall(fooA, 'numeric-id', entity, 'P41', 1) then
			local v
			for _, v in pairs(flags) do
				if v.qualifiers then
					if (not v.qualifiers["P580"] or v.qualifiers["P580"][1].datavalue.value.time <= date)
						and (not v.qualifiers["P582"] or v.qualifiers["P582"][1].datavalue.value.time >= date)
					then possible_flag[num]=v.mainsnak.datavalue.value num=num+1 end
				else possible_flag[num]=v.mainsnak.datavalue.value num=num+1 end
			end
			local file="[[File:"..possible_flag[1].."|border|20px"
			local a2,b2=pcall(fooA,'value',entity,'P984',1) -- P984 (country code by the International Olympic Committee)
			if a2 == true then file=file.."|"..b2.."]]" else file=file.."]]" end
			flag_table[x] = file
			return file
		end
	end
	return " "
end -- end function flag

function getStartOfSeason(entity)
	-- 1st from P580, 2nd from P585, 3rd from en, fr or de label
	local startOfSeason = ''
	pcall(function() startOfSeason = entity.claims["P580"][1].mainsnak.datavalue.value.time end)
	if startOfSeason == '' then
		pcall(function() startOfSeason = entity.claims["P585"][1].mainsnak.datavalue.value.time end)
		if startOfSeason == '' then
			local Sitelink = entity:getSitelink('enwiki') or entity:getSitelink('frwiki') or entity:getSitelink('dewiki') or ''
			if string.match(Sitelink, '%d%d%d%d' ) ~= nil then
				startOfSeason = '+'..string.match(Sitelink, '%d%d%d%d' ) ..'-01-01T00:00:00Z'
			end
		end
	end
	if startOfSeason ~= '' then
		return startOfSeason
	else
		return '> Wikidata is missing data about the start time (P580) and end time (P582) of the season'
	end
end -- end function startOfSeason

return p