Jump to content

Module:Cycling race

Frá Wikipedia, hin frælsa alfrøðin
Versjón frá 9. mar 2016 kl. 23:29 av EileenSanda (kjak | íkøst) (copied from the Danish Wikipedia, we need to get a fo-line in here also)

Module:Cycling race


local p = {}

function infobox_left(x) -- This function permits to translate fields of the infobox, take the line below, give a Wikipedia (ex : mk), and translate all fields. By default, English values are taken.
	-- l10nDef["//??.wikipedia.org"] = {"RACE DETAILS", "COURSE", "COMPETITION", "COMPETITIONS", "STAGES", "DATE", "DATES", "DISTANCE", "COUNTRY", "COUNTRIES", "JOURNEY ORIGIN", "JOURNEY DESTINATION", "TEAMS", "STARTING RIDERS", "ARRIVING RIDERS", "AVERAGE SPEED", "COST", "PALMARES", "WINNER", "SECOND", "THIRD", "POINTS", "MOUNTAINS", "SPRINTS", "YOUTH", "COMBATIVITY", "COMBINATION", "TEAM"}
 	local l10nDef = { }
	l10nDef["//fr.wikipedia.org"] = {"Généralités", "Course", "Compétition", "Compétitions", "Étapes", "Date", "Dates", "Distance", "Pays", "Pays",
	"Lieu de départ", "Lieu d'arrivée", "Équipes", "Partants", "Arrivants", "Vitesse moyenne", "Coût", "Résultats", "Vainqueur", "Deuxième", "Troisième",
	"Classement par points", "Meilleur grimpeur", "Meilleur sprinteur", "Meilleur jeune", "Super-combatif", "Meilleur au combiné", "Meilleure équipe"}
	l10nDef["//en.wikipedia.org"] = {"Race details", "Course", "Competition", "Competitions", "Stages", "Date", "Dates", "Distance", "Country", "Countries",
	"Journey origin", "Journey destination", "Teams", "Starting riders", "Arriving riders", "Average speed", "Cost", "Palmares", "Winner", "Second", 
	"Third", "Points", "Mountains", "Sprints", "Youth", "Combativity", "Combination", "Team"}
	l10nDef["//br.wikipedia.org"] = {"Hollegezhioù", "Redadeg", "Kevezadeg", "Kevezadegoù", "Tennadoù", "Deiziad", "Deiziadoù", "Hed", "Bro", "Broioù",
	"Lec'h loc'hañ", "Lec'h degouezhout", "Skipailhoù", "Loc'herien", "Erruerien", "Tizh keitat", "Koust", "Disoc'hoù", "Gounezer", "Eil", "Trede",
	"Renkadur a-boentoù", "Kraper gwellañ", "Sprinter gwellañ", "Yaouank gwellañ", "Stourmer meur", "Gwellañ el liesrenkadur", "Skipailh gwellañ"}
	l10nDef["//ca.wikipedia.org"] = {"Detalls de la cursa", "Cursa", "Competició", "Competicions", "Etapes", "Data", "Dates", "Distància", "País", "Països",
	"Sortida", "Arribada", "Equips", "Inscrits", "Finalitzen", "Velocitat mitjana", "Cost", "Palmarès", "Vencedor", "Segon", "Tercer", "Punts", "Muntanya", 
	"Esprints", "Joves", "Combativitat", "Combinada", "Equip"}
	l10nDef["//cs.wikipedia.org"] = {"Přehled", "Závod", "Soutěž", "Soutěže", "Počet etap", "Datum", "Datum", "Celková délka", "Země", "Země", "Start", "Cíl", 
	"Týmy", "Běžci", "Příjezdy", "Rychlostní průměr", "Náklady", "Konečné pořadí", "Celkový vítěz", "2. místo", "3. místo", "Vítěz bodovací soutěže", "Nejlepší vrchař", 
	"Nejlepší sprinter", "Nejlepší mladý jezdec", "Nejaktivnější jezdec", "Nejlepší kombinovaná", "Nejlepší družstvo"}
	l10nDef["//da.wikipedia.org"] = {"Løbsdetaljer", "Rute", "Konkurrence", "Konkurrencer", "Etaper", "Dato", "Datoer", "Distance", "Land", "Lande", "Start på tur", 
	"Destination på tur", "Hold", "Startende ryttere", "Sluttende ryttere", "Gennemsnitlig fart", "Pris", "Palmares", "Vinder", "To'er", "Tre'er", "Point", "Bjerge", 
	"Spurter", "Ungdom", "Kombativitet", "Kombination", "Hold"}
	l10nDef["//de.wikipedia.org"] = {"Einzelheiten", "Ausgabe", "Rennserie", " Wettbewerb", "Etappen", "Datum", "Datum", "Gesamtlänge", "Austragungsland", "Austragungsländer", 
	"Start", "Ziel", "Teams", "Fahrer am Start", "Fahrer im Ziel", "Geschwindigkeit im Durchschnitt", "Kosten", "Sieger", "Gesamtwertung", "Zweiter", 
	"Dritter", "Punktewertung", "Bergwertung", "Sprintwertung", "Nachwuchswertung", "Kämpferischster Fahrer", "Kombinationswertung", "Teamwertung"}
	l10nDef["//eo.wikipedia.org"] = {"Gxeneralajxo", "Bicikla konkurso", "Konkuro", "Konkuroj", "Etapoj", "Dato", "Datoj", "Longo", "Lando", "Landoj",
	"Komencloko", "Alvenloko", "Teamoj", "Startantoj", "Alvenantoj", "Averagxa rapido", "Kosto", "Rezultoj", "Venkinto", "Dua pozicio", "Tria pozicio",
	"Klasifiko laux poentoj", "Plej bona grimpanto", "Plej bona sprinto", "Plej bona juno", "Superbatalema", "Plej bona por kombino", "Plej bona teamo"}
	l10nDef["//es.wikipedia.org"] = {"Detalles", "Carrera", "Válida para", "Válida para", "Etapas", "Fecha", "Fechas", "Distancia total", "País", "Países", 
	"Lugar de inicio", "Lugar de llegada", "Equipos", "Ciclistas que iniciaron", "Ciclistas que finalizaron", "Velocidad media", "Costo", "Clasificación final", 
	"Ganador", "Segundo", "Tercero", "Puntos", "Montaña", "Sprints", "Jóvenes", "Combatividad", "Combinación", "Equipo"}
	l10nDef["//lb.wikipedia.org"] = {"Detailer", "Course", "Kompetitioun", "Kompetitiounen", "Etappen", "Datum", "Datumer", "Distanz", "Land", "Länner", 
	"Depart", "Arrivée", "Equippen", "Um Depart", "Ukomm", "Vitesse-Moyenne", "Käschten", "Palmarès", "Gewënner", "Zweeten", "Drëtten", "Beschte Sprinter", "Biergpräis", 
	"Sprinter", "Beschte Jonken", "Kombativitéit", "Kombinatioun", "Equipe"}
	l10nDef["//mk.wikipedia.org"] = {"Детали за трката", "Издание", "Натпреварување", "Натпреварувања", "Етапи", "Датум", "Датуми", "Растојание", 
	"Држава", "Држави", "Поаѓалиште", "Одредиште", "Екипи", "Возачи на почеток", "Возачи на крај", "Просечна брзина", "Трошоци", "Добитници на наградите", 
	"Победник", "Второпласиран", "Третопласиран", "Бодовен", "Планински", "Спринтерски", "Младински", "Борбеност", "Комбиниран", "Екипен"}
	l10nDef["//nl.wikipedia.org"] = {"Wedstrijddetails", "Koers", "Wedstrijd", "Wedstrijden", "Etappes", "Datum", "Datums", "Afstand", "Land", "Landen", "Startplaats", 
	"Finishplaats", "Teams", "Aantal coureurs aan de start", "Aantal coureurs bij de aankomst", "Gemiddelde snelheid", "Kosten", "Palmares", "Winnaar", "Tweede", 
	"Derde", "Punten", "Bergen", "Sprints", "Jeugd", "Aanvalslust", "Combinatie", "Team"}
	l10nDef["//no.wikipedia.org"] = {"Detaljer", "Ritt", "Turnering", "Turneringer", "Etapper", "Dato", "Datoer", "Distanse", "Land", "Land", 
	"Startby", "Målby", "Lag", "Startende ryttere", "Fullførende ryttere", "Gjennomsnittsfart", "Kostnad", "Resultater", "Vinner", "2. plass", "3. plass", 
	"Poeng", "Klatre", "Sprint", "Ungdom", "Mest offensive", "Kombinasjon", "Lagkonkurranse"}
	l10nDef["//pl.wikipedia.org"] = {"Wyrażenia ogólne", "Wyścig", "Konkurencja", "Konkursy", "Etapów", "Data", "Daty", "Dystans", "Państwo", "Państwy", "Odejście", 
	"Przyjazd", "Zespoły", "Zgłoszenia", "Ukończyło wyścig", "Średnia prędkość", "Koszt", "Podium", "Pierwsze miejsce", "Drugie miejsce", "Trzecie miejsce", "Punktowa", 
	"Górska", "Sprinterska", "Młodzieżowa", "Najaktywniejszych", "Kombinowana", "Drużynowa"}
	l10nDef["//ro.wikipedia.org"] = {"Detalii cursă", "Cursă", "Competiție", "Competiții", "Etape", "Dată", "Date", "Distanță", "Țară", "Țări", "Start", "Sosire", 
	"Echipe", "Cicliști la start", "Cicliști la sosire", "Viteză medie", "Cost", "Palmares", "Câștigător", "Al doilea", "Al treilea", "Clasament pe puncte", 
	"Cel mai bun cățărător", "Cel mai bun sprinter", "Cel mai bun tânăr", "Combativitate", "Combinat", "Echipă"}
	l10nDef["//ru.wikipedia.org"] = {"Детали гонки", "Маршрут", "Соревнование", "Соревнования", "Этапы", "Дата", "Даты", "Дистанция", "Страна", "Страны", 
	"Место старта", "Пункт назначения", "Команды", "Вышло на старт гонщиков", "Финишировало гонщиков", "Средняя скорость", "Призовые", "Призёры", "Победитель", 
	"Второй", "Третий", "Очковая", "Горная", "Спринтерская", "Молодёжная", "Бойцовская", "Комбинированная", "Командная"}
	l10nDef["//www.wikidata.org"] = l10nDef["//en.wikipedia.org"]
	local l10n = l10nDef[mw.site.server]
	if not l10n then l10n = l10nDef["//en.wikipedia.org"] end  -- default
	return l10n[x]
end 

function infobox_bottom(x) -- This function give the bottom of the infobox, with a link to the documentation, and the tooltip
 	local l10nDef = { }
	l10nDef["//fr.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentation]]", "In Wikidata missing:"}
	l10nDef["//en.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentation]]", "In Wikidata missing:"}
	l10nDef["//br.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentation]]", "In Wikidata missing:"}
	l10nDef["//ca.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentació]]", "In Wikidata missing:"}
	l10nDef["//cs.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentace]]", "In Wikidata missing:"}
	l10nDef["//da.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentation]]", "In Wikidata missing:"}
	l10nDef["//de.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentation]]", "In Wikidata missing:"}
	l10nDef["//eo.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentado]]", "In Wikidata missing:"}
	l10nDef["//es.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentación]]", "In Wikidata missing:"}
	l10nDef["//eu.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentazioa]]", "In Wikidata missing:"}
	l10nDef["//lb.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentatioun]]", "In Wikidata missing:"}
	l10nDef["//mk.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Документација]]", "In Wikidata missing:"}
	l10nDef["//nl.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentatie]]", "In Wikidata missing:"}
	l10nDef["//no.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentasjon]]", "In Wikidata missing:"}
	l10nDef["//pl.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Dokumentacja]]", "In Wikidata missing:"}
	l10nDef["//pt.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentação]]", "In Wikidata missing:"}
	l10nDef["//ro.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Documentație]]", "In Wikidata missing:"}
	l10nDef["//ru.wikipedia.org"] = {"[[d:Wikidata:WikiProject Cycling/Documentation/infobox|Документация]]", "In Wikidata missing:"}
	l10nDef["//www.wikidata.org"] = l10nDef["//fr.wikipedia.org"]
	local l10n = l10nDef[mw.site.server]
	if not l10n then l10n = l10nDef["//en.wikipedia.org"] end -- default
	return l10n[x]
end

function property(x) -- This function allows you to overwrite wikidata information
 	local l10nDef = { }
	l10nDef["//fr.wikipedia.org"] = {"image", "légende", "numéro d'édition", "carte de localisation", "course cyclist", "classe", "étapes", "date de début", "date de fin", "date",
	"longueur", "point de départ", "destination du parcours", "équipes", "nombre de participants au départ", "nombre de participants à l'arrivée", "vitesse", "coût",
	"vainqueur du classement général", "deuxième du classement général", "troisième du classement général", "vainqueur du classement par points",
	"vainqueur du classement de la montagne", "vainqueur du classement des sprints", "vainqueur du classement du meilleur jeune", "vainqueur du classement de la combativité",
	"vainqueur du classement du combiné", "vainqueur du classement de la meilleure équipe" }
	l10nDef["//en.wikipedia.org"] = {"picture", "caption", "edition number", "locator map image", "cycling race", "class", "stages", "start time", "end time", "time",
	"length", "journey origin", "journey destination", "teams", "number of participants at start", "number of participants at end", "speed", "cost",
	"overall winner", "second overall winner", "third overall winner", "winner of the point classification", "winner of the mountain classification",
	"winner of the sprint classification", "winner of the young rider classification", "winner of the fighting spirit classification", 
	"winner of the combination classification", "winner of the team classification" }
 	l10nDef["//www.wikidata.org"] = l10nDef["//en.wikipedia.org"]
	local l10n = l10nDef[mw.site.server]
	if not l10n then l10n = l10nDef["//en.wikipedia.org"] end  -- default
	return l10n[x]
end 

function p.infobox(frame)
	local t = {is_a="", class="", stage="", starttime="", endtime="", time="", length="", length_unit="", 
	startplace="", endplace="", nr_teams="", nr_participants_start="", nr_participants_end="", speed="", speed_unit="", cost="", cost_unit="", 
	first="", second="", third="", winner_point="", winner_mountain="", winner_sprint="", winner_young="", winner_fighting="", 
	winner_combination="", winner_team="", previous="", next=""}
	local tt = {icon="", picture="", caption="", name="", nr="", map="" }
	local ttt = {tour={}, country={}}
	local entity = ""
	local y, m, d = "", "", ""
	local y2, m2, d2 = "", "", ""
	local snak, snak2, snak3, snak4
	local a, b, c, k, num, i
	local entityId = frame.args[1]
	local lang = mw.language.getContentLanguage()
	local wiki = mw.site.server
	local results = false
	local a1, b1, c1, a2, b2, c2

	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 )

	if frame.args[property(1)] then tt.picture = frame.args[property(1)] end 
	if frame.args[property(2)] then tt.caption = frame.args[property(2)] end 
	if frame.args[property(3)] then tt.nr = frame.args[property(3)] end 
	if frame.args[property(4)] then tt.map = frame.args[property(4)] end 

	local z = {stage=6, starttime=8, endtime=9, time=10, length=11, startplace=12, endplace=13, nr_teams=14, nr_participants_start=15, nr_participants_end=16, 
	speed=17, cost=18, first=19, second=20, third=21, winner_point=22, winner_mountain=23, winner_sprint=24, winner_young=25, winner_fighting=26, winner_combination=27,
	winner_team=28}

	for i,k in pairs(z) do 
		if frame.args[property(k)] then t[i] = frame.args[property(k)] end
	end	

	if  entity:getLabel() ~= nil then tt.name = entity:getLabel()
	else
		if entity:getLabel( 'fr' ) ~= nil then tt.name = entity:getLabel( 'fr' ).. " (fr)"
		else tt.name = "Wikidata doesn´t know" end 
	end

	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 
		tt.picture = b 
		for _, v in pairs(entity.claims["P18"]) do
			for num=1,#v.qualifiers["P2096"] do
  				if v.qualifiers["P2096"][num].datavalue.value.language == lang:getCode() then
  					tt.caption = v.qualifiers["P2096"][num].datavalue.value.text end
  			end
  		end 
  	end
	
	a, b = pcall(fooA, 'amount', entity, 'P1132', 1) -- Function for the number of cyclists participing at the race
	if a == true and t.nr_participants_start == "" and t.nr_participants_end == "" then 
		for _, v in pairs(entity.claims["P1132"]) do
  			if v.mainsnak then
  				if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 529711 then
  					t.nr_participants_start = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
  				if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 15053716 then
  					t.nr_participants_end = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
  			end
 		end		
	end	
	-- For FR Wiki and Wikidata, exception that permit to display 1er, 2e... for the edition number ; 
	-- for RU Wiki, -й is written after the value of P393
	a, b = pcall(fooA, 'value', entity, 'P393', 1)  
	if a == true and tt.nr == "" then 
		tt.nr = b .. ". "
		if wiki == "//fr.wikipedia.org" or wiki == "//www.wikidata.org" then
			if b == 1  then tt.nr = "1<sup>re</sup> " else tt.nr = b .."<sup>e</sup> " end end
		if wiki == "//nl.wikipedia.org" then tt.nr = b .."e " end
		if wiki == "//ru.wikipedia.org" then tt.nr = b .."-й " end 
		if wiki == "//eo.wikipedia.org" then tt.nr = b .."-a " end 		
		if wiki == "//cs.wikipedia.org" then tt.nr = b ..". " end
	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" } 
	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 
		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  
		--b = "+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  
		--d = "+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 = lang:formatDate( "j F Y", b1 ) 
		elseif m ~= m2 then t.starttime = lang:formatDate( "j F", b1 )
		else t.starttime = lang:formatDate( "j", b1 )
		end
		if wiki == "//de.wikipedia.org" or wiki == "//da.wikipedia.org" or wiki == "//no.wikipedia.org" then  
			if y ~= y2 then t.starttime = lang:formatDate( "j. F Y", b1 ) 
			elseif m ~= m2 then t.starttime = lang:formatDate( "j. F", b1 )
			else t.starttime = lang:formatDate( "j.", b1 )
			end	end			
		if wiki == "//ja.wikipedia.org" then 
			if y ~= y2 then t.starttime = lang:formatDate( "Y年m月d日", b1 ) 		
			elseif m ~= m2 then t.starttime = lang:formatDate( "Y年m月d日", b1 )	
			else t.starttime = lang:formatDate( "Y年m月d日", b1 )
			end	end			
		if wiki == "//en.wikipedia.org" then 
			if y ~= y2 then t.starttime = lang:formatDate( "F d, Y", b1 ) 		
			elseif m ~= m2 then t.starttime = lang:formatDate( "F d", b1 )	
			else t.starttime = lang:formatDate( "F d", b1 )
			end	end			
		if wiki == "//lv.wikipedia.org" then 
			if y ~= y2 then t.starttime = lang:formatDate( "Y. j. F", b1 ) 		
			elseif m ~= m2 then t.starttime = lang:formatDate( "Y. j. F", b1 )	
			else t.starttime = lang:formatDate( "Y. j.", b1 )
			end	end	
		if wiki == "//eo.wikipedia.org" then 
			if y ~= y2 then t.starttime = lang:formatDate( "j", b1 ) .."-a de ".. lang:formatDate( "F Y", b1 )		
			elseif m ~= m2 then t.starttime = lang:formatDate( "j", b1 ) .."-a de ".. lang:formatDate( "F", b1 )		
			else t.starttime = lang:formatDate( "j", b1 ) .."-a "	
			end	end	
		if wiki == "//cs.wikipedia.org" then 
			if y ~= y2 then t.starttime = lang:formatDate( "j. xg Y", b1 )
			elseif m ~= m2 then t.starttime = lang:formatDate( "j. xg", b1 )
			else t.starttime = lang:formatDate( "j", b1 )
			end	end			
	end -- if a1
	if a2 == true and t.endtime == "" then 
		t.endtime = lang:formatDate( "j F Y", b2 ) 
		if wiki == "//de.wikipedia.org" or wiki == "//da.wikipedia.org" or wiki == "//no.wikipedia.org" then 
			t.endtime = lang:formatDate( "j. F Y", b2 ) end
		if wiki == "//ja.wikipedia.org" then 
			if y ~= y2 then t.endtime = lang:formatDate( "Y年m月d日", b2 ) 		
			elseif m ~= m2 then t.endtime = lang:formatDate( "m月d日", b2 )	
			else t.endtime = lang:formatDate( "d日", b2 )	
			end	end	
		if wiki == "//en.wikipedia.org" then
			if y ~= y2 then t.endtime = lang:formatDate( "F d, Y", b2 ) 		
			elseif m ~= m2 then t.endtime = lang:formatDate( "F d, Y", b2 )	
			else t.endtime = lang:formatDate( "d, Y", b2 )	
			end	end			
		if wiki == "//lv.wikipedia.org" then 
			if y ~= y2 then t.endtime = lang:formatDate( "Y. j. F", b2 ) 		
			elseif m ~= m2 then t.endtime = lang:formatDate( "j. F", b2 )	
			else t.endtime = lang:formatDate( "j. F", b2 )	
			end	end
		if wiki == "//eo.wikipedia.org" then 
			t.endtime = lang:formatDate( "j", b2 ) .."-a de ".. lang:formatDate( "F Y", b1 ) end		
		if wiki == "//cs.wikipedia.org" then 
			t.endtime = lang:formatDate( "j. xg Y", b2 ) 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 = lang:formatDate( "j F Y", b1 )
		if wiki == "//de.wikipedia.org" or wiki == "//da.wikipedia.org" or wiki == "//no.wikipedia.org" then 
			t.time = lang:formatDate( "j. F Y", b1 ) end
		if wiki == "//ja.wikipedia.org" then 
			t.time = lang:formatDate( "Y年m月d日", b1 ) end
		if wiki == "//en.wikipedia.org" then
			t.time = lang:formatDate( "F d, Y", b1 ) end
		if wiki == "//lv.wikipedia.org" then 
			t.time = lang:formatDate( "Y. j. F", b1 ) end
		if wiki == "//eo.wikipedia.org" then
			t.time = lang:formatDate( "j", b1 ) .."-a de ".. lang:formatDate( "F Y", b1 )	 end		
		if wiki == "//cs.wikipedia.org" then
			t.time = lang:formatDate( "j. xg Y", b1 )	 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, '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 = 'km'
			if  wiki == "//mk.wikipedia.org" then t.length_unit = 'км' end
			if  wiki == "//ru.wikipedia.org" then t.length_unit = 'км' end
			if  wiki == "//ja.wikipedia.org" then t.length_unit = 'キロメートル' end
		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
		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  
		for _, v in pairs(entity.claims["P1132"]) do
 			if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 529711 then
			   if pcall(function() 
					t.nr_participants_start = string.gsub(v.mainsnak.datavalue.value.amount, "+", "")
         			end        	
      			) then else t.nr_participants_start = "" end   					
  			end
 			if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 15053716 then
 			   if pcall(function() 
					t.nr_participants_end = string.gsub(v.mainsnak.datavalue.value.amount, "+", "")
         			end        	
      			) then else t.nr_participants_end = "" 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 = 'km/h'
			if  wiki == "//nl.wikipedia.org" then t.speed_unit = 'km/u' end
			if  wiki == "//mk.wikipedia.org" then t.speed_unit = 'км/ч' end
			if  wiki == "//ru.wikipedia.org" then t.speed_unit = 'км/ч' end
			if  wiki == "//ja.wikipedia.org" then t.speed_unit = 'キロメートル毎時' end			
		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

	-- By entering a value just below, the Wikipedia added will not have Wikidata logos associated with cyclists in the infobox
	local note, qual, id 
	if wiki == "//fr.wikipedia.org" or wiki == "//en.wikipedia.org" or wiki == "//br.wikipedia.org" or wiki == "//ca.wikipedia.org" or wiki == "//cs.wikipedia.org" or wiki == "//da.wikipedia.org" or 
		wiki == "//de.wikipedia.org" or wiki == "//eo.wikipedia.org" or wiki == "//es.wikipedia.org" or wiki == "//eu.wikipedia.org" or wiki == "//lb.wikipedia.org" or wiki == "//nl.wikipedia.org" or wiki == "//no.wikipedia.org" or wiki == "//pl.wikipedia.org" or 
		wiki == "//pt.wikipedia.org" or wiki == "//ro.wikipedia.org" then 
		note = 'f' else note = 'q' end 
	if pcall(foo3, entity, "P1346", 1, "P642", 1) then 	
		for _, v in pairs(entity.claims["P1346"]) do
		    if pcall(function() id=v.mainsnak.datavalue.value['numeric-id'] end) then else id=nil end  		
			if pcall(function() qual=v.qualifiers["P642"][1].datavalue.value["numeric-id"] end) then else qual=nil end  
			if id~=nil and qual~=nil and v.rank~='deprecated' then 
			if qual == 20882667 and t.first == "" then t.first = note .. id results = true end
			if qual == 20882668 and t.second == "" then t.second = note .. id results = true end
			if qual == 20882669 and t.third == "" then t.third = note .. id results = true end
			if qual == 20883007 and t.winner_point == "" then t.winner_point = note .. id results = true end
			if qual == 20883212 and t.winner_mountain == "" then t.winner_mountain = note .. id results = true end   			
  			if qual == 20883328 and t.winner_sprint == "" then t.winner_sprint = note .. id results = true end
			if qual == 20883139 and t.winner_young == "" then t.winner_young = note .. id results = true end  
			if qual == 20893983 and t.winner_fighting == "" then t.winner_fighting = note .. id results = true end
			if qual == 20893979 and t.winner_combination == "" then t.winner_combination = note .. id results = true end
			if qual == 20882921 and t.winner_team == "" then t.winner_team = note .. id results = true end
 			end -- if id
  		end	-- for
	end  -- end if pcall

	-- transform Q/q-number into flag / WPlink / WDlink
	local k
	local team = true
	local d1, datum_stagerace = pcall(fooA, 'time', entity, 'P580', 1) -- stage race
	local d2, datum_singleday = pcall(fooA, 'time', entity, 'P585', 1) -- single day race
	local wd = " [[File:Wikidata-logo S.svg|12px|link=d:"	
	
	if d1 == true then datum = datum_stagerace end
	if d2 == true then datum = datum_singleday end	

	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], datum).." ".. 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] = WPlink( string.gsub(ttt[k][i], "T", "Q") ) 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 = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P27', 1)
			if a == true and pcall(foo1, t[k]) then t[k] = flag( getNationalityOnDate (t[k], datum), datum).." "..WPlink( t[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, datum).." "..WPlink( t[k], team )..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 = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P27', 1)
			if a == true and pcall(foo1, t[k]) then t[k] = flag( getNationalityOnDate (t[k], datum), datum).." "..WPlink( 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, datum).." "..WPlink( t[k], team ) 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	
	end

	-- references, not done
	if pcall(foo12, entity, 'P569', 1, 2, 'P248', 1) then 
		snak2 = entity.claims['P569'][1].references[2].snaks["P248"][1].datavalue.value["numeric-id"] 
	end
	if pcall(foo12, entity, 'P569', 1, 2, 'P345', 1) then 
		snak3 = entity.claims['P569'][1].references[2].snaks["P345"][1].datavalue.value
	end
	if pcall(foo12, entity, 'P569', 1, 2, 'P813', 1) then
		snak4 = entity.claims['P569'][1].references[2].snaks["P813"][1].datavalue.value.time
		_, _, y2, m2, d2 = string.find(snak4, "(%d+)-(%d+)-(%d+)") -- d = day, m = month		"[".."http://www.spiegel.de/".."]" --
	end	
	
	--tab1 = "<table class='wikitable'><tr><td>".."name".."</td><td>".. "Tour de France 2016" .. "</td></tr>" .."<tr><td>".."date de début".."</td><td>"
    --tab1 = tab1 .. d1.."."..m1.."."..y1 --.. frame:extensionTag{name='ref',content="Q"..snak2.." | ".."[http://www.imdb.com/name/"..snak3.."]".." | "..d2.."."..m2.."."..y2,args={name='foo'}} 
    --tab1 = tab1 .. "</td></tr></table>"
    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
    end    
    if t.speed ~= "" then 
    	t.speed, _ = string.gsub(t.speed, "[+]", "")
    	t.speed = lang:formatNum(tonumber(t.speed))
    end
    if t.cost ~= "" then 
    	t.cost, _ = string.gsub(t.cost, "[+]", "")
    	t.cost = lang:formatNum(tonumber(t.cost))
    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.gsub(string.sub(k, i+1, j-1), "%D", "") .. string.sub(k, j) 
  	else t.previous = string.gsub(k, "%D", "") 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.gsub(string.sub(k, i+1, j-1), "%D", "") .. span2 .. string.sub(k,j) 
  	else t.next = string.gsub(k, "%D", "") 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)

 	tab = "<table cellpadding='4' cellspacing='0' style='float:right; width:300px; border:1px solid rgb(200,200,200);"
    tab = tab .. "margin:0 0.5em 0.5em 0; 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.wikipedia.org" then tab = "<table style='width:23em; border:1px solid rgb(200,200,200);"
    	tab = tab .. "margin:0 0.5em 0.5em 0; 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>[[File:Wikidata-logo S.svg|30px|link=d:".. frame.args[1]  .. "]]</td><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'>'''"..infobox_left(1).."'''</td></tr>"
	if tt.nr ~= "" and t.is_a ~= "" then tab = tab.."<tr><td style='width:40%'>'''"..infobox_left(2).."'''</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..infobox_left(3).."'''</td><td>" else tab = tab..infobox_left(4).."'''</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>'''"..infobox_left(5).."'''</td><td>" .. t.stage.."</td></tr>" end	
	if t.starttime ~= "" or t.endtime ~= "" then tab = tab.."<tr><td>'''"..infobox_left(7).."'''</td><td>" .. t.starttime.." – " ..t.endtime .."</td></tr>" end
	--if t.endtime ~= "" then tab = tab.."<tr><td>".."Date de fin".."</td><td>" .. t.endtime .. "</td></tr>" end	
	if t.time ~= "" then tab = tab.."<tr><td>'''"..infobox_left(6).."'''</td><td>" .. t.time.."</td></tr>" end	
	if t.length ~= "" then tab = tab.."<tr><td>'''"..infobox_left(8).."'''</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..infobox_left(9).."'''</td><td>" else tab = tab..infobox_left(10).."'''</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>'''"..infobox_left(11).."'''</td><td>" .. t.startplace .. "</td></tr>" end	
	if t.endplace ~= "" then tab = tab.."<tr><td>'''"..infobox_left(12).."'''</td><td>" .. t.endplace .. "</td></tr>" end
	if t.nr_teams ~= "" then tab = tab.."<tr><td>'''"..infobox_left(13).."'''</td><td>" .. t.nr_teams .. "</td></tr>" end
	if t.nr_participants_start ~= "" then tab = tab.."<tr><td>'''"..infobox_left(14).."'''</td><td>" .. t.nr_participants_start .. "</td></tr>" end
	if t.nr_participants_end ~= "" then tab = tab.."<tr><td>'''"..infobox_left(15).."'''</td><td>" .. t.nr_participants_end .. "</td></tr>" end	
	if t.speed ~= "" then tab = tab.."<tr><td>'''"..infobox_left(16).."'''</td><td>" .. t.speed .. " "..t.speed_unit.."</td></tr>" end		
	if t.cost ~= "" then tab = tab.."<tr><td>'''"..infobox_left(17).."'''</td><td>" .. t.cost .. " "..t.cost_unit.. "</td></tr>" end	
	
	if results then tab = tab.."<tr><td colspan='2' style='border-bottom:5px solid white; background-color:#FFDF80; text-align:center'>'''"..infobox_left(18).."'''</td></tr>" end
	if t.first ~= "" then tab = tab.."<tr><td>'''"..infobox_left(19).."'''</td><td>" .. t.first .. "</td></tr>" end	
	if t.second ~= "" then tab = tab.."<tr><td>'''"..infobox_left(20).."'''</td><td>" .. t.second .. "</td></tr>" end	
	if t.third ~= "" then tab = tab.."<tr><td>'''"..infobox_left(21).."'''</td><td>" .. t.third .. "</td></tr>" end
	if t.winner_point ~= "" then tab = tab.."<tr><td>'''"..infobox_left(22).."'''</td><td>" .. t.winner_point .. "</td></tr>" end
	if t.winner_mountain ~= "" then tab = tab.."<tr><td>'''"..infobox_left(23).."'''</td><td>" .. t.winner_mountain .. "</td></tr>" end
	if t.winner_sprint ~= "" then tab = tab.."<tr><td>'''"..infobox_left(24).."'''</td><td>" .. t.winner_sprint .. "</td></tr>" end
	if t.winner_young ~= "" then tab = tab.."<tr><td>'''"..infobox_left(25).."'''</td><td>" .. t.winner_young .. "</td></tr>" end
	if t.winner_fighting ~= "" then tab = tab.."<tr><td>'''"..infobox_left(26).."'''</td><td>" .. t.winner_fighting .. "</td></tr>" end	
	if t.winner_combination ~= "" then tab = tab.."<tr><td>'''"..infobox_left(27).."'''</td><td>" .. t.winner_combination .. "</td></tr>" end	
	if t.winner_team ~= "" then tab = tab.."<tr><td>'''"..infobox_left(28).."'''</td><td>" .. t.winner_team .. "</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>" 	
	tab = tab .. "<tr><td colspan='2' style='text-align:right; border-top:3px solid #FFDF80; font-size:75%'>" .. 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>" 
	if wiki == "//eo.wikipedia.org" then tab = tab ..changetemplate() end
	tab= tab.."</table>"
	return tab
end

function p.teamroster(frame)
	local columns = tonumber(frame.args.columns) == 1 and tonumber(frame.args.columns) or 2 --defaults to two columns
	local squadSeason = mw.wikibase.getEntityObject( frame.args[1] )
	local flags = {}
	local riderIds = {}
	local riderNames = {}
	local riderBirthdays = {}
	local labelMissing = false
	local wiki = mw.site.server	
	local WDlink_off = false	

	-- WDlink_off is used to decide if a Wikidata flag will be shown
	if wiki == "//www.wikidata.org" or wiki == "//fr.wikipedia.org" or wiki == "//en.wikipedia.org" or wiki == "//br.wikipedia.org" or wiki == "//ca.wikipedia.org" or wiki == "//cs.wikipedia.org" or 
	wiki == "//da.wikipedia.org" or wiki == "//de.wikipedia.org" or wiki == "//eo.wikipedia.org" or wiki == "//es.wikipedia.org" or wiki == "//eu.wikipedia.org" or wiki == "//lb.wikipedia.org" or 
	wiki == "//nl.wikipedia.org" or wiki == "//no.wikipedia.org" or wiki == "//pl.wikipedia.org" or wiki == "//pt.wikipedia.org" or 
	wiki == "//ro.wikipedia.org" then WDlink_off = true end	

	local startOfSeason = squadSeason.claims["P580"][1].mainsnak.datavalue.value.time

	local i = 1
 	while squadSeason.claims["P527"][i]  do
 		riderIds[i] = 'Q' .. squadSeason.claims["P527"][i].mainsnak.datavalue.value['numeric-id']
 		local rider = mw.wikibase.getEntityObject(riderIds[i])
 		
 		local label = rider:getLabel()
 		local link = rider:getSitelink()
 		
 		if label == null then
 			label = '\'\'' .. rider:getLabel('en') .. '&nbsp;(en)\'\''
 			labelMissing = true
 		end
 		
 		if link == null then
 			riderNames[i] = label
 		elseif label == link then
 			riderNames[i] = '[[' .. label .. ']]'
 		else
 			riderNames[i] = '[[' .. link .. '|' .. label .. ']]'
 		end
 		
 		if pcall(function()
       		riderBirthdays[i] = rider.claims["P569"][1].mainsnak.datavalue.value.time 
        	end       	
    	) then else riderBirthdays[i] = '' end

 		if pcall(function()
        	flags[i] = flag(getNationalityOnDate (riderIds[i], startOfSeason), startOfSeason)
  			end
		) then else flags[i] = '' end

 	    i = i + 1 
    end

    local tableBody = ''
    local tableHeader = '<table border="0" cellspacing="0" cellpadding="2" width="100%">'
    	.. '<tr style="background-color:#FFDF80;"><th width="35%" style="text-align:left;">' 
    if WDlink_off == true then tableHeader = tableHeader .. '[[File:Wikidata-logo S.svg|12px|link=d:'.. frame.args[1].. '#P527]]&nbsp;&nbsp;' end
    tableHeader = tableHeader .. getSquadTableColumn(1) .. '</th><th width="42%" style="text-align:left;">' .. getSquadTableColumn(2) .. '</th></tr>'
    local tableFoot = '</table>' 
    i = 1  
    
    local tableSize = table.getn(riderNames)
    
    while riderNames[i] do
    	tableBody = tableBody ..'<tr><td nowrap >'..flags[i] .. ' '.. riderNames[i] .. ' '
    	if WDlink_off == false then tableBody = tableBody  .. wdLink(riderIds[i])  end
    	tableBody = tableBody..	'</td><td nowrap >' ..getDateAndAgeOnDate(frame, startOfSeason, riderBirthdays[i]).. '</td></tr>'

    	if columns == 2 and math.floor((tableSize + 1)/2) == i then
    		tableBody = tableBody .. tableFoot ..'</td><td width="1%"></td><td style="vertical-align:top;" width="44%">' .. tableHeader
    	end
    	i = i + 1	
    end	
    
    local tableStart = '<table border="0"><tr><td style="vertical-align:top;" width="44%">'
    local tableEnd = '</td></tr></table>'
    
    if labelMissing then
    	tableEnd = tableEnd .. getMissingLabelTrackingCategory()
    end

	return '<table style="border:1px solid rgb(200,200,200)"><tr><td>'.. 
		tableStart.. tableHeader.. tableBody.. tableFoot.. tableEnd.. '</td></tr></table>'
end

function getDateAndAgeOnDate (frame, onDate, date)
	local lang = mw.language.getContentLanguage()
	local wiki = mw.site.server

	time = lang:formatDate( "j F Y", date )
	if wiki == "//de.wikipedia.org" or wiki == "//da.wikipedia.org" or wiki == "//no.wikipedia.org" then 
		time = lang:formatDate( "j. F Y", date ) end
	if wiki == "//ja.wikipedia.org" then 
		time = lang:formatDate( "Y年m月d日", date ) end
	if wiki == "//en.wikipedia.org" then
		time = lang:formatDate( "F d, Y", date ) end
	if wiki == "//lv.wikipedia.org" then
		local _, _, y1, m1, d1 = string.find(onDate, "(%d+)-(%d+)-0*(%d+)")
		local _, _, y2, m2, d2 = string.find(date, "(%d+)-(%d+)-0*(%d+)")
		time = frame:expandTemplate{ title = 'Template:Birth date and age2', args = { y1, m1, d1, y2, m2, d2 } } end
	if wiki == "//eo.wikipedia.org" then 
		time = lang:formatDate( "j", date ) .."-a de ".. lang:formatDate( "F Y", date ) end

	return time
end

function getNationalityOnDate (rider, date) -- rider Qnumber, date = e.g. "+1985-05-20T00:00:00Z" 
	local entity = mw.wikibase.getEntity( rider ) 
	local nationalities = entity.claims["P27"]
	local possibleNationalities = {}

	local num = 1
	for _, v in pairs(nationalities) 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
 				possibleNationalities[num] = "Q" .. v.mainsnak.datavalue.value['numeric-id']
 				num = num + 1
 			end
 		else
 			possibleNationalities[num] = "Q" .. v.mainsnak.datavalue.value['numeric-id']
 			num = num + 1
 		end
 	end		
	return possibleNationalities[1]
end

function WPlink(Qnumber, ...) 
local link
local entity = mw.wikibase.getEntity( Qnumber )
local Sitelink = entity:getSitelink() -- link to WParticle
local Label = entity:getLabel()
local Label_fr = entity:getLabel( 'fr' )
local Sitelink_claas = mw.wikibase.getEntity( 'Q22348500' ):getSitelink() 
local a, b
local official_name = ""

if pcall(foo1, Qnumber) then -- "[[" .. sitelinks1[num] .. "|" .. string.gsub(sitelinks1[num], "%b()", "") .. "]]"
	if Sitelink ~= nil then link = "[[" .. Sitelink .. "|" .. string.gsub(Sitelink, "%b()", "") .. "]]"	else link = Label end
else return "unknown ID in function WPlink" end
if link == nil then 
	link = Label_fr 
	if link == nil then link = "(label missing)" else link = string.gsub(link, "%b()", "") .. " (fr)" end -- if no fr:label else fr.label plus ...
end
if arg[1] == true then -- Qnumber of a team
	a, b = pcall(fooA, 'text', entity, 'P1448', 1) 
	if a == true then official_name = b end	
	if pcall(foo1, Qnumber) then 
		if Sitelink ~= nil and official_name == b then link = "[[" .. Sitelink .. "|" .. official_name .. "]]"	else link = official_name end
	else return "unknown ID in function WPlink" end
	if link == nil then 
		link = Label_fr 
		if link == nil then link = "(label missing)" else link = link .. " (fr)" end -- if no fr:label else fr.label plus ...
	end
end -- end arg[1] 
if arg[1] == "Q22348500" then -- add weblink from item "Q22348500" if available
	if pcall(foo1, Qnumber) then --Sitelink_claas
		if Sitelink == nil then 
			if Sitelink_claas ~= nil then link = "[[" .. Sitelink_claas .. "|" .. Label .. "]]" else link = Label end 
		end
	end
end
return link
end

function getMissingLabelTrackingCategory()
	local l10nDef = { }
	l10nDef["//lv.wikipedia.org"] = '[[Category:Vikidatos trūkst nosaukuma latviešu valodā]]'

	local l10n = l10nDef[mw.site.server]
	if not l10n then
    	l10n = ''
	end
	return l10n
end 

function getSquadTableColumn(x)
	local l10nDef = { }
	l10nDef["//fr.wikipedia.org"] = {"Cycliste", "Date de naissance"}
	l10nDef["//en.wikipedia.org"] = {"Rider", "Date of birth"}
	l10nDef["//ca.wikipedia.org"] = {"Ciclista", "Data de naixement"}
	l10nDef["//cs.wikipedia.org"] = {"Cyklista", "Datum narození"}
	l10nDef["//da.wikipedia.org"] = {"Rytter", "Fødselsdag"}
	l10nDef["//de.wikipedia.org"] = {"Name", "Geburtsdatum"}
	l10nDef["//es.wikipedia.org"] = {"Corredor", "Fecha de nacimiento"}
	l10nDef["//eu.wikipedia.org"] = {"Izena", "Jaiotze-data"}
	l10nDef["//it.wikipedia.org"] = {"Ciclista", "Data di nascita"}
	l10nDef["//ja.wikipedia.org"] = {"選手名", "生年月日"}
	l10nDef["//lb.wikipedia.org"] = {"Coureur", "Gebuertsdatum"}
	l10nDef["//lv.wikipedia.org"] = {"Braucējs", "Dzimšanas datums"}
	l10nDef["//mk.wikipedia.org"] = {"Велосипедист", "Датум на раѓање"}
	l10nDef["//nl.wikipedia.org"] = {"Naam", "Geboortedatum"}
	l10nDef["//no.wikipedia.org"] = {"Rytter", "Fødselsdato"}
	l10nDef["//pl.wikipedia.org"] = {"Imię i nazwisko", "Data urodzenia"}
	l10nDef["//pt.wikipedia.org"] = {"Ciclista", "Data de Nascimento"}
	l10nDef["//ro.wikipedia.org"] = {"Biciclist", "Data nașterii"}
	l10nDef["//ru.wikipedia.org"] = {"Гонщик", "Дата рождения"}
	l10nDef["//sv.wikipedia.org"] = {"Namn", "Födelsedatum"}
	l10nDef["//www.wikidata.org"] = l10nDef["//en.wikipedia.org"]

	local l10n = l10nDef[mw.site.server]
	if not l10n then
    	l10n = l10nDef["//en.wikipedia.org"]
	end
	return l10n[x]
end 

function changetemplate () -- for eoWiki
	local frame = mw.getCurrentFrame()
	local n = frame:expandTemplate {title="sxangxu sxablonon2", args = {["sxablono"] = "Cycling race/infobox"}}
return n			
end

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 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 foo12 (entity_var, property, var1, var2, ref, var3)
local snak = entity_var.claims[property][var1].references[var2].snaks[ref][var3].datavalue
end

function winner (t, winner_id)
	tt = {}
	for num=1,t.main.number do
		table.insert(tt, "")
	end
	local wiki = mw.site.server	
	local winner, time_var, sitelink, nationality 
	local go
	local WDlink_off = false	

	-- WDlink_off is used to decide if a Wikidata flag will be shown
	if wiki == "//fr.wikipedia.org" or wiki == "//en.wikipedia.org" or wiki == "//br.wikipedia.org" or wiki == "//ca.wikipedia.org" or wiki == "//cs.wikipedia.org" or wiki == "//da.wikipedia.org" or 
	wiki == "//de.wikipedia.org" or wiki == "//eo.wikipedia.org" or wiki == "//es.wikipedia.org" or wiki == "//eu.wikipedia.org" or wiki == "//lb.wikipedia.org" or 
	wiki == "//nl.wikipedia.org" or wiki == "//no.wikipedia.org" or wiki == "//pl.wikipedia.org" or wiki == "//pt.wikipedia.org" or 
	wiki == "//ro.wikipedia.org" then WDlink_off = true end	
	for num=1,t.main.number do
	-- winner: Qnumber of vainqueur du classement général
	i = 1
   	if pcall(foo2, t.main.race[num][2], "P1346", i) then 
   		while t.main.race[num][2].claims["P1346"][i] do	-- suche nach "Gewinner der Gesamtwertung"
   			if pcall(foo3, t.main.race[num][2], "P1346", i, "P642", 1) then go = true else go = false end
            if go == true and t.main.race[num][2].claims["P1346"][i].qualifiers.P642[1].datavalue.value['numeric-id'] == winner_id then 
	    		winner = "Q"..t.main.race[num][2].claims["P1346"][i].mainsnak.datavalue.value['numeric-id'] 
				if wiki == "//www.wikidata.org" then sitelink = mw.wikibase.getEntity( winner ):getSitelink( 'frwiki' )
				else sitelink = mw.wikibase.sitelink( winner ) 
				end 
 				if sitelink == nil then 
 					if mw.wikibase.getEntity( winner ):getLabel() == nil then sitelink = "—" 
 					else sitelink = mw.wikibase.getEntity( winner ):getLabel() 
 					end 
					if wiki == "//lv.wikipedia.org" and mw.wikibase.getEntity( winner ):getLabel() == nil then 
						sitelink = mw.wikibase.getEntity( winner ):getLabel('en') .. " (en)" end  	 
					if wiki == "//mk.wikipedia.org" and mw.wikibase.getEntity( winner ):getLabel() == nil then 
						sitelink = mw.wikibase.getEntity( winner ):getLabel('en') .. " (en)" end  
					if wiki == "//ja.wikipedia.org" and mw.wikibase.getEntity( winner ):getLabel() == nil then 
						sitelink = mw.wikibase.getEntity( winner ):getLabel('en') .. " (en)" end  	 					
				else sitelink = "[[" .. sitelink .. "|" .. string.gsub(sitelink, "%b()", "") .. "]]" 
				end	
			
				-- 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)
				if pcall(foo2, t.main.race[num][2], "P585", 1) then 
				time_var = t.main.race[num][2].claims["P585"][1].mainsnak.datavalue.value.time 
				elseif pcall(foo2, t.main.race[num][2], "P580", 1) then 
				time_var = t.main.race[num][2].claims["P580"][1].mainsnak.datavalue.value.time 
				else end
			
				-- get nationality of the winner, nationality could have changed, therefore look for qualifiers p580 and p582
				if pcall(foo2, mw.wikibase.getEntity( winner ), "P27", 1) then -- standard: only one nationality
					nationality = "Q"..mw.wikibase.getEntity( winner ).claims["P27"][1].mainsnak.datavalue.value['numeric-id']
					tt[num] = flag(nationality, time_var) .. " " .. sitelink .. " " 
					if WDlink_off == false then tt[num] = tt[num].. wdLink(winner) end
				else tt[num] = "  " .. sitelink .. " " .. wdLink(winner) end
				if pcall(foo2, mw.wikibase.getEntity( winner ), "P27", 2) then 	-- if person has more than one nationality calculate tt[num] again
					tt[num] = flag( getNationalityOnDate (winner, time_var), time_var) .. " " .. sitelink .. " " 
					if WDlink_off == false then tt[num] = tt[num].. wdLink(winner) end
				end
			end -- end if
			i = i + 1	
		end -- end while	
	else  end  -- end if pcall
	end -- end for
return tt
end

function p.listofwinners(frame)
	local t = {main={entity0="", race={}}, year={}, vainqueur={}, second={}, troisieme={}}

	if pcall(foo1, frame.args[1]) then t.main.entity0 = mw.wikibase.getEntity( frame.args[1] ) end
    local tt, k, sitelink
	local num = 1 
	local go
	local wiki = mw.site.server
	local WDlink_off = false
	
	-- WDlink_off is used to decide if a Wikidata flag will be shown
	if wiki == "//fr.wikipedia.org" or wiki == "//en.wikipedia.org" or wiki == "//br.wikipedia.org" or wiki == "//ca.wikipedia.org" or wiki == "//cs.wikipedia.org" or wiki == "//da.wikipedia.org" or 
	wiki == "//de.wikipedia.org" or wiki == "//eo.wikipedia.org" or wiki == "//es.wikipedia.org" or wiki == "//eu.wikipedia.org" or wiki == "//lb.wikipedia.org" or 
	wiki == "//nl.wikipedia.org" or wiki == "//no.wikipedia.org" or wiki == "//pl.wikipedia.org" or wiki == "//pt.wikipedia.org" or 
	wiki == "//ro.wikipedia.org" then WDlink_off = true end

	if pcall(foo2, t.main.entity0, "P527", num) then go = true else go = false end
 	while go == true and t.main.entity0.claims["P527"][num] do
 		race = 'Q'..t.main.entity0.claims["P527"][num].mainsnak.datavalue.value['numeric-id'] -- Qnumbers of the parts of a tour
		tt = {}
		table.insert(tt, race) 
		table.insert(tt, mw.wikibase.getEntityObject(race))
		if pcall(foo2, tt[2], "P585", 1) then -- P585(point in time for a single day race) or P580(start time for a stage race)
			k = tt[2].claims["P585"][1].mainsnak.datavalue.value.time
		elseif pcall(foo2, tt[2], "P580", 1) then 
			k = tt[2].claims["P580"][1].mainsnak.datavalue.value.time
		else return "! not enoght data on Wikidata available" end
        local _, _, year, _, _ = string.find(k, "(%d+)-(%d+)-(%d+)") 
		table.insert(tt, year)
		table.insert(t.main.race, tt)
		table.sort(t.main.race, function(a,b) return a[3] < b[3] end) -- t.main.race is sorted after year 
   	    num = num + 1 
    end -- end while	
	t.main.number = num - 1

	tt = {}
	for num=1,t.main.number do -- build first column with link to wikipedia article and to wikidata item
		if wiki == "//www.wikidata.org" then sitelink = t.main.race[num][2]:getSitelink( 'frwiki' )
		else sitelink = mw.wikibase.sitelink( t.main.race[num][1] ) 
		end 
 		if sitelink == nil then sitelink = t.main.race[num][3] 
		else sitelink = "[[" .. sitelink .. "|" .. t.main.race[num][3] .. "]]" 
		end
    if WDlink_off == true then table.insert(tt, sitelink) else table.insert(tt, sitelink.. " " .. wdLink(t.main.race[num][1]) ) end 
	end 
	table.insert(t.year, tt)
 
	table.insert(t.vainqueur, winner(t, 20882667))
	table.insert(t.second,  winner(t, 20882668))
	table.insert(t.troisieme, winner(t, 20882669))

    local table_first, table_proto, table_last, table_center
    table_first = "<table 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; vertical-align:top; font-size:85%; line-height:1.6em;'>" 

    table_proto = "<tr style='background:#FFDF80; text-align:center;'><th>"
    if WDlink_off == true then table_proto = table_proto .. "[[File:Wikidata-logo S.svg|12px|link=d:".. frame.args[1].. "#P527]]" end    
    table_proto = table_proto.. headoftableIV(1).. "</th><th>".. 
	headoftableIV(2).. "</th><th>".. headoftableIV(3).. "</th><th>".. headoftableIV(4).. "</th></tr>"
    table_center = ""		      
    table_last = "</table>"
    
    local table_center = ""
    for var=1, t.main.number do -- t.main.race[var][3]
    table_center = table_center .. "<tr><td style='text-align:center'>".. t.year[table.getn(t.year)][var].."</td>"
    table_center = table_center .. "<td>"..t.vainqueur[table.getn(t.vainqueur)][var].."</td>"
    table_center = table_center .. "<td>"..t.second[table.getn(t.second)][var].."</td>"
    table_center = table_center .. "<td>"..t.troisieme[table.getn(t.troisieme)][var].."</td></tr>" 
	end
    return table_first .. table_proto .. table_center .. table_last 
end

function p.listofstages(frame)
 	local i, v, uu, ii, nationality
 	local entity, etape, stage = {}, {}, {}
 	local series_ordinal, point_of_time, length = {}, {}, {}
    local sitelinks_etape, sitelinks1, sitelinks2, sitelinks3, sitelinks4 = {}, {}, {}, {}, {}
    local y, m, d = {}, {}, {}
    local flag1, flag2 = {}, {}
    local number0, number1, number2 = {}, {}, {}
    local level = false  
	local a, b
	local num, var
	local wiki = mw.site.server	
 	local entity0 = mw.wikibase.getEntityObject( frame.args[1] ) -- Q18589873 (Quatre jours de Dunkerque 2015)
	local WDlink_off = false
	local team = true
	-- if there is one 'P527' then level = 2  
 	a, b = pcall(fooA, 'numeric-id', entity0, 'P527', 1) 
	if a == true then level = true end	
 	-- only for level: 2
 	-- 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.getEntityObject( 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 ~= "" and char2 == "" then comp =  tonumber(num1) < tonumber(num2) end
 	 	if char1 == "" and char2 ~= "" then comp =  tonumber(num1) < tonumber(num2) end
 	 	if char1 ~= "" and char2 ~= "" then comp =  char1 < char2 end
        return comp end)
 		--return a.nr < b.nr end) 

	-- WDlink_off is used to decide if a Wikidata flag will be shown
	if wiki == "//fr.wikipedia.org" or wiki == "//en.wikipedia.org" or wiki == "//br.wikipedia.org" or wiki == "//ca.wikipedia.org" or wiki == "//cs.wikipedia.org" or wiki == "//da.wikipedia.org" or 
	wiki == "//de.wikipedia.org" or wiki == "//eo.wikipedia.org" or wiki == "//es.wikipedia.org" or wiki == "//eu.wikipedia.org" or wiki == "//lb.wikipedia.org" or 
	wiki == "//nl.wikipedia.org" or wiki == "//no.wikipedia.org" or wiki == "//pl.wikipedia.org" or wiki == "//pt.wikipedia.org" or 
	wiki == "//ro.wikipedia.org" then WDlink_off = true end
 	
 	var = #entity0.claims["P527"] 
 	for num=1,var do  
		-- collect data from Wikidata in tables 
		entity[num] = mw.wikibase.getEntityObject( parts[num].Qnum )
		if WDlink_off == true then number0[num]= " " else number0[num] = " " .. 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 ) else sitelinks1[num] = " " end
		a, b = pcall(fooA, 'numeric-id', entity[num], 'P1444', 1) 
		if a == true then sitelinks2[num] =  WPlink( 'Q'..b ) else sitelinks2[num] = " " end     
		a, b = pcall(fooA, 'amount', entity[num], 'P2043', 1) 
		if a == true then length[num] =  formatNumber( b ) else length[num] = " " 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 	
		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 
--					flag1[num] = flag(getNationalityOnDate(number1[num], point_of_time[num]), point_of_time[num])					
					a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntityObject(number1[num]), 'P27', 1) 
					if a == true then 
						flag1[num] = flag( getNationalityOnDate (number1[num], point_of_time[num]), point_of_time[num])
						sitelinks3[num] = WPlink( number1[num] )						
					else 
						a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntityObject(number1[num]), 'P17', 1) 
						if a == true then 
							flag1[num] = flag( 'Q'..b, point_of_time[num]) 
							sitelinks3[num] = WPlink( number1[num], team )						
						end
					end
					if WDlink_off == true then number1[num]="" else number1[num]= " [[File:Wikidata-logo S.svg|12px|link=d:"..number1[num] .. ']]' 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 	
		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 
--					flag2[num] = flag( getNationalityOnDate (number2[num], point_of_time[num]), point_of_time[num])
					a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntityObject(number2[num]), 'P27', 1) 
					if a == true then 
						flag2[num] = flag( getNationalityOnDate(number2[num], point_of_time[num]), point_of_time[num]) 
						sitelinks4[num] = WPlink( number2[num] )						
					else 
						a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntityObject(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_off == true then number2[num]="" else number2[num]= " [[File:Wikidata-logo S.svg|12px|link=d:"..number2[num] .. ']]' 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') end
           if uu == 20646670 then stage[num] = typeofstage('hilly stage') end
           if uu == 20680270 then stage[num] = typeofstage('intermediate stage') end
           if uu == 20646668 then stage[num] = typeofstage('mountain stage') end
           if uu == 485321 then stage[num] = typeofstage('time trial stage', 485321) end -- prologue
           if uu == 2266066 then stage[num] = typeofstage('time trial stage', 2266066) end -- individual time trial
           if uu == 2348250 then stage[num] = typeofstage('time trial stage', 2348250) end -- team time trial
           if uu == 20679712 then stage[num] = typeofstage('uphill time trial stage') end
         i = i + 1	
         end 
         end      	
      ) then else stage[num] = " " end     

     _, _, y[num], m[num], d[num] = string.find(point_of_time[num], "(%d+)-(%d+)-(%d+)") -- d = day, m = month

	end -- end for num=1,var do

	local table_first, table_proto, table_last
	table_first = "<table 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; vertical-align:top; font-size:85%; line-height:1.6em;'>" 
	table_proto = "<tr style='background:#FFDF80; text-align:center;'><th>"
	if WDlink_off == true then table_proto = table_proto .. "[[File:Wikidata-logo S.svg|12px|link=d:".. frame.args[1].. "#P527]]" end
	table_proto = table_proto.. headoftable(1) .."</th><th>" ..	headoftable(2) .."</th><th>".. headoftable(3)..
	"</th><th>".. headoftable(4).. "</th><th>".. headoftable(5).."</th><th>".. headoftable(6).. "</th></tr>"
	table_last = "</table>"	

     -- build table for output
	local table_center = ""
	var = #entity0.claims["P527"]
	for num=1, var do    	
		local a, b 
		a, _ = string.gsub(series_ordinal[num], "%a", "") -- 20, not 20a
		if string.find(series_ordinal[num], "%a") then b = string.sub(series_ordinal[num], string.find(series_ordinal[num], "%a")) 
		else b = "" end
		local ee, er = stageLink(series_ordinal[num], a, b)
		if series_ordinal[num] == "0" then 
			er = "#"..func_prologue() 
			ee = func_prologue()
		end	
		local stageNr -- if there is a wikipedia article of that stage show it or show the section
		if sitelinks_etape[num] == nil then stageNr = "[["..er.."|"..ee.."]]" else stageNr = "[["..sitelinks_etape[num].."|"..ee.."]]" end

		local day = tostring(tonumber(d[num]))
		if day == "1" and (wiki == "//fr.wikipedia.org") then day = "1<sup>er</sup>" 
		else if wiki ~= "//fr.wikipedia.org" and wiki ~= "//eo.wikipedia.org" then day = day .. "." end end
		if wiki == "//lv.wikipedia.org" then stageNr = series_ordinal[num] end
		local month = func_month(m[num])
		local date = day..' ' .. month
		if wiki == "//ja.wikipedia.org" then date = month .. day .. "日" end
		if wiki == "//eo.wikipedia.org" then date = day .. "-a de ".. month  end

		if pcall(function()
			length[num] = mw.language.getContentLanguage():formatNum(tonumber(length[num])) 
			end        	
		) then else length[num] = " " end     

		table_center = table_center.. "<tr style='vertical-align:top'><td nowrap style='text-align:right'>".. stageNr .. number0[num].. 
		"</td><td nowrap style='text-align:right; padding-right:0px'>"..date.. "</td><td>".. sitelinks1[num].." – "..sitelinks2[num]..stage[num].. 
		"</td><td style='text-align:center'>".. length[num].. " </td><td nowrap>".. flag1[num].. ' '.. sitelinks3[num].. number1[num].. "</td><td nowrap>".. 
		flag2[num]..' ' ..sitelinks4[num].. number2[num].. "</td></tr>"
    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

function func_prologue() -- returns the word "Prologue"
 	local l10nDef = { ["fr"]="Prologue", ["en"]="Prologue", ["br"]="Prolog", ["ca"]="Pròleg", ["cs"]="Prolog", ["de"]="P", ["da"]="Prolog", ["eo"]="Prologo",
 	["es"]="Prólogo", ["fi"]="Prologi", ["hu"]="Prolog", ["it"]="Prologo", ["ja"]="プロローグ", ["la"]="Incipit prologus", ["lb"]="Prolog", ["lv"]="Prologs",
 	["mk"]="Пролог",  ["nl"]="Proloog", ["no"]="Prolog", ["pl"]="Prologu", ["pt"]="Prólogo", ["ro"]="Prolog", ["ru"]="Пролог", ["sk"]="Prológ", ["sv"]="Prolog" }
 
	local wiki,word=mw.site.server 
	if wiki=='//www.wikidata.org' then return l10nDef["fr"]
	else return l10nDef[string.sub(wiki,string.find(wiki,"%a+"))] end
  end	

function stageLink(x, a, b) -- x= 10a: a = 10, b = a. x = 5: a = 5, b = "" 
 	local l10nDef = {["fr"]="étape", ["en"]="Stage", ["br"]="Tennad", ["ca"]="Etapa", ["cs"]="Etapa", ["de"]="Etappe", ["da"]="Etape", ["eo"]="Etapo",
 	["es"]="Etapa", ["eu"]="Etapa", ["fi"]="Etappi", ["hu"]="Szakasz", ["it"]="Tappa", ["ja"]="ステージ", ["la"]="Statio", ["lb"]="Etapp", ["lv"]="Posms", ["mk"]="Етапа",
 	["nl"]="Etappe", ["no"]="Etappe", ["pl"]="Etap", ["pt"]="Etapa", ["ro"]="Etapa", ["ru"]="Этап", ["sk"]="Etapa", ["sv"]="Etapp" }		                

	local wiki,l10n=mw.site.server
	local word1, word2	
	if wiki=='//www.wikidata.org' then word2=l10nDef["fr"]
	else word2=l10nDef[string.sub(wiki,string.find(wiki,"%a+"))] end
	local word = word2

-- fr: {{1re}} étape, {{2e}} étape
	if mw.site.server == "//www.wikidata.org" or mw.site.server == "//fr.wikipedia.org" then 
  	 if b == "" then -- series_ordinal without character		
	   if a == "1" then word1 = "1<sup>re</sup> "..word else word1 = a.."<sup>e</sup> "..word end -- table text = {{1re}} étape, {{2ae}} étape,
	   if a == "1" then word2 = "#1re "..word else word2 = "#"..a.."e  "..word end --text of section header = #1re étape, #2e étape
   	   return word1, word2
   	 end
     if b ~= "" then -- series_ordinal with character: instead of eg "1a re" it is "1re a"	
 	   if a == "1" then word1 = "1<sup>re</sup> "..b.." "..word else word1 = a.."<sup>e</sup> "..b.." "..word end -- table text = {{1re}} étape, {{2ae}} étape,
	   if a == "1" then word2 = "#1re "..b.." "..word else word2 = "#"..a.."e"..b.." "..word end --text of section header = #1re étape, #2e étape
   	   return word1, word2	
     end  	
  end
  -- default
  word1 = x                  -- table text = 1, 2a, 3
  word2 = "#"..word.." ".. x -- text of section header = #Etappe 2a, #Stage 4
 	
  --return table text, text of section header
  return word1, word2 
  end

function func_month(x) 
	local l10nDef = { }
	l10nDef["fr"] = {"janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."}
	l10nDef["en"] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
	l10nDef["be"] = {"studz.", "liut.", "sak.", "kras.", "mai.", "cherv.", "lip.", "zhniven'", "veras", "kastr.", "list.", "snezh."}
	l10nDef["bg"] = {"ian.", "fevr.", "mart", "april", "mai", "iuni", "iuli", "avg.", "sept.", "okt.", "noem.", "dek."}
	l10nDef["br"] = {"Genver", "C'hwevrer", "Meurzh", "Ebrel", "Mae", "Mezheven", "Gouere", "Eost", "Gwengolo", "Here", "Du", "Kerzu"}
	l10nDef["ca"] = {"gener", "febrer", "març", "abril", "maig", "juny", "juliol", "agost", "setembre", "octubre", "novembre", "desembre"}
	l10nDef["cs"] = {"led.", "ún.", "bře.", "dub.", "kvě.", "čvn.", "čvc.", "srp.", "září.", "říj.", "list.", "pros."}
	l10nDef["da"] = {"jan.", "febr.", "marts", "april", "maj", "juni", "juli", "aug.", "sept.", "okt.", "nov.", "dec."}
	l10nDef["de"] = {"Jan.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.", "Nov.", "Dez."}
	l10nDef["eo"] = {"janu.", "febr.", "marto", "apr.", "majo", "jun.", "jul.", "auxg.", "sept.", "okt.", "nov.", "dec."}
	l10nDef["es"] = {"enero", "feb.", "marzo", "abr.", "mayo", "jun.", "jul.", "agosto", "sept.", "oct.", "nov.", "dic."}
	l10nDef["et"] = {"jaan.", "veebr.", "märts", "apr.", "mai", "juuni", "juuli", "aug.", "sept.", "okt.", "nov.", "dets."}
	l10nDef["eu"] = {"urtarrilaren", "otsailaren", "martxoaren", "apirilaren", "maiatzaren", "ekainaren", "uztail", "abuztuaren", "irailaren", "urri", "azaroaren", "abenduaren"}
	l10nDef["hu"] = {"jan.", "feb.", "márc.", "ápr.", "máj.", "jun.", "jul.", "aug.", "szept.", "okt.", "nov.", "dec."}
	l10nDef["id"] = {"Djan.", "Peb.", "Mrt.", "Apr.", "Mai", "Djuni", "Djuli", "Ag.", "Sept.", "Okt.", "Nop.", "Des."}
	l10nDef["it"] = {"genn.", "febbr.", "mar.", "apr.", "magg.", "giugno", "luglio", "ag.", "sett.", "ott.", "nov.", "dic."}
	l10nDef["ja"] = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"}
	l10nDef["la"] = {"Ian.", "Febr.", "Mart.", "Apr.", "Mai.", "Iun.", "Iul.", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."}
	l10nDef["lb"] = {"Januar", "Februar", "Mäerz", "Abrëll", "Mee", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}
	l10nDef["lt"] = {"saus.", "vas.", "kovas", "bal.", "geg.", "birz", "liepa", "rugp.", "rugs.", "spalis", "lapkr.", "gr."}
	l10nDef["lv"] = {"janvāris", "februāris", "marts", "aprīlis", "maijs", "jūnijs", "jūlijs", "augusts", "septembris", "oktobris", "novembris", "decembris"}
	l10nDef["mk"] = {"јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"}
	l10nDef["ms"] = {"Jan.", "Feb.", "Mac", "Apr.", "Mei", "Jun", "Julai", "Og", "Sept.", "Okt.", "Nov.", "Dis."}
	l10nDef["no"] = {"jan.", "feb.", "mar.", "apr.", "mai", "jun.", "jul.", "aug.", "sep.", "okt.", "nov.", "des."}
	l10nDef["nl"] = {"jan.", "feb.", "maart", "apr.", "mei", "juni", "juli", "aug.", "sept.", "okt.", "nov.", "dec."}
	l10nDef["pl"] = {"stycz.", "luty", "mar.", "kwiec.", "maj", "czerw.", "lip.", "sierp.", "wrzes.", "pazdz.", "listop.", "grudz."}
	l10nDef["pt"] = {"jan.", "fev.", "março", "abril", "maio", "junho", "julho", "agosto", "set.", "out.", "nov.", "dez."}
	l10nDef["ro"] = {"Ian.", "Feb.", "Mar.", "Apr.", "Mai", "Iun.", "Iul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."}
	l10nDef["ru"] = {"Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августа", "Сентября", "Октября", "Ноября", "Декабря"}
	l10nDef["sh"] = {"sijec.", "velj.", "ozuj.", "trav.", "svib.", "lip.", "srp.", "kol.", "ruj.", "list.", "stud.", "pros."}
	l10nDef["sk"] = {"l'ad.", "ún.", "brez.", "dub.", "kvet", "cerv.", "cerven.", "srp.", "zári.", "ruj.", "list.", "pros."}
	l10nDef["sl"] = {"jan.", "feb.", "mar.", "apr.", "maj", "jun.", "jul.", "avg.", "sept.", "okt.", "nov.", "dec."}
	l10nDef["sv"] = {"jan.", "febr.", "mars", "april", "maj", "juni", "juli", "aug.", "sept.", "okt.", "nov.", "dec."}

	local wiki,l10n=mw.site.server 
	if wiki=='//www.wikidata.org' then return l10nDef["fr"][tonumber(x)]
	else return l10nDef[string.sub(wiki,string.find(wiki,"%a+"))][tonumber(x)] end
end

function headoftable(x) -- En-tête du tableau listant les étapes
	local l10nDef={ }
	l10nDef["fr"]={"Étape", "Date", "Villes étapes", "Distance (km)", "Vainqueur d'étape", "Leader du classement général"}
	l10nDef["en"]={"Stage", "Date", "Course", "Distance (km)", "Stage winner", "Overall leader"}
	l10nDef["br"]={"Tennad", "Deiziad", "Kêr loc'hañ ha kêr degouezhout", "Hed (km)", "Trec'hour", "E penn ar renkamant hollek"}
	l10nDef["ca"]={"Etapa", "Data", "Ciutats d'etapa", "Distància (km)", "Vencedor de l'etapa", "Líder de la general"}
	l10nDef["cs"]={"Etapa", "Datum", "Trasa", "Vzdálenost (km)", "Vítěz", "Průběžný lídr"}
	l10nDef["da"]={"Etape", "Dato", "Start – Mål", "Afstand (km)", "Etapevinder", "Den gule trøje"}
	l10nDef["de"]={"Etappe", "Datum", "Etappenorte", "Länge (km)", "Etappensieger", "Gesamtführender"}
	l10nDef["eo"]={"Etapo", "Dato", "Etapa urbo", "Longo (km)", "Venkinto de la etapo", "Estro de la gxeneralo klasado"}
	l10nDef["es"]={"Etapa", "Fecha", "Recorrido", "Distancia (km)", "Ganador", "Líder"}
	l10nDef["fi"]={"Etappi", "Päivä", "Reitti", "Pituus (km)", "Voittaja", "Yleinen johtaja"}
	l10nDef["hu"]={"Szakasz", "Időpont", "Végpontok", "Hossz (km)", "Szakaszgyőztes", "Általános vezető"}
	l10nDef["it"]={"Tappa", "Data", "Percorso", "Distanza (km)", "Vincitore di tappa", "Leader cl. generale"}
	l10nDef["ja"]={"ステージ", "開催日", "コース", "距離 (km)", "ステージ勝者", "全体リーダー"}
	l10nDef["la"]={"Statio", "Dies", "Iter", "Distantia (km)", "Victor", "Altiore princeps"}
	l10nDef["lb"]={"Etapp", "Datum", "Etappestied", "Längt (km)", "Gewënner", "Generalklassement"}
	l10nDef["lv"]={"Posms", "Datums", "Maršruts", "Posma garums (km)", "Uzvarētājs", "Kopvērtējuma līderis"}
	l10nDef["mk"]={"Етапа", "Датум", "Тек", "Растојание (км)", "Победник", "Cевкупен лидер"}
	l10nDef["nl"]={"Etappe", "Datum", "Start – Finish", "Afstand (km)", "Winnaar", "Klassementsleider"}
	l10nDef["no"]={"Etappe", "Dato", "Start – Målgang", "Lengde (km)", "Etappevinner", "Sammenlagtleder"}
	l10nDef["pl"]={"Etap", "Data", "Start – Meta", "Dystans (km)", "Zwycięzca etapu", "Lider"}
	l10nDef["pt"]={"Etapa", "Data", "Percurso", "Distância (km)", "Vencedor", "Líder geral"}
	l10nDef["ro"]={"Etapa", "Dată", "Start – Sosire", "Distanță (km)", "Câștigător", "Liderul global"}
	l10nDef["ru"]={"Этап", "Дата", "Маршрут", "Длина (км)", "Победитель", "Лидер генеральной классификации"}
	l10nDef["sk"]={"Etapa", "Dátum", "Trasa", "Vzdialenosť (km)", "Víťaz", "Priebežný líder"}
	l10nDef["sv"]={"Etapp", "Datum", "Start – mål", "Distans (km)", "Skede vinnare", "Övergripande ledare"}
	l10nDef["als"]=l10nDef["de"]

	local wiki,l10n=mw.site.server 
	if wiki=='//www.wikidata.org' then l10n=l10nDef["fr"]
	else l10n=l10nDef[string.sub(wiki,string.find(wiki,"%a+"))] end

--	local l10n = l10nDef[mw.site.server]
--	if not l10n then l10n = l10nDef["//fr.wikipedia.org"] end  -- default
	return l10n[x]
end 

function headoftableII(x) -- En-têtes des tableaux générant les classements
	local l10nDef = { }
	l10nDef["//fr.wikipedia.org"] = {"Coureur", "Pays", "Équipe", "Temps", "Points", "Classement de l'étape", "Classement général", "Classement par points", "Classement de la montagne", "Classement des sprints", "Classement du meilleur jeune", "Classement par équipes"}
	l10nDef["//br.wikipedia.org"] = {"Reder", "Bro", "Skipailh", "Amzer", "Poentoù", "Renkadur an tennad", "Renkadur hollek", "Renkadur a-boentoù", "Renkadur ar menez", "Renkadur ar sprintoù", "Renkadur ar yaouank gwellañ", "Renkadur a-skipailh"}
	l10nDef["//ca.wikipedia.org"] = {"Corredor", "País", "Equip", "Temps", "Punts", "Classificació de l'etapa", "Classificació general", "Classificació per punts", "Classificació de la muntanya", "Classificació dels esprints", "Classificació del millor jove", "Classificació per equips"}
	l10nDef["//eo.wikipedia.org"] = {"Kuranto", "Lando", "Teamo", "Tempo", "Poentoj", "Etapa klasifiko", "Gxenerala klasifiko", "Klasifiko laux poentoj", "Klasifiko por la montaro", "Klasifiko por la sprintoj", "Klasifiko de la plej bona juno", "Klasifiko po teamo"}
	l10nDef["//lb.wikipedia.org"] = {"Coureur", "Land", "Equipe", "Zäit", "Punkten", "Etappeklassement", "Generalklassement", "Klassement no Punkten", "Biergpräis", "Sprintklassement", "Beschte Jonken", "Equippeklassement"}
	l10nDef["//ro.wikipedia.org"] = {"Ciclist", "Țară", "Echipă", "Timp", "Puncte", "Clasamentul etapei", "Clasament general", "Clasament pe puncte", "Clasament cățărători", "Clasament sprinteri", "Clasamentul celui mai bun tânăr", "Clasament pe echipe"}
	l10nDef["//www.wikidata.org"] = l10nDef["//fr.wikipedia.org"]
	local l10n = l10nDef[mw.site.server]
	if not l10n then l10n = l10nDef["//fr.wikipedia.org"] end  -- default
	return l10n[x]
end 

function headoftableIII(x) -- En-tête du tableau listant les équipes participantes (P1923)
	local l10nDef = { }
	l10nDef["//fr.wikipedia.org"] = {"Nom de l'équipe", "Pays", "Code", "WorldTeam", "WorldTeams", "ProTeam", "ProTeams", "Équipe continentale professionnelle", "Équipes continentales professionnelles", "Équipe continentale", "Équipes continentales", "Équipe nationale", "Équipes nationales", "Équipe régionale et de club", "Équipes régionales et de clubs", "Équipe cycliste professionnelle", "Équipes cyclistes professionnelles", "Équipe cycliste amateur", "Équipes cyclistes amateurs", "Groupe sportif I", "Groupes sportifs I", "Groupe sportif II", "Groupes sportifs II", "Groupe sportif III", "Groupes sportifs III", "Équipe mixte", "Équipes mixtes", "Équipe féminine", "Équipes féminines"}
	l10nDef["//br.wikipedia.org"] = {"Anv skipailh", "Bro", "Kod", "WorldTeam", "WorldTeams", "ProTeam", "ProTeams", "Skipailh kevandir a-vicher", "Skipailhoù kevandir a-vicher", "Skipailh kevandir", "Skipailhoù kevandir", "Skipailh bro", "Skipailhoù bro", "Skipailh rannvro ha klub", "Skipailhoù rannvro ha club", "Skipailh marc'h-houarn a-vicher", "Skipailhoù marc'h-houarn a-vicher", "Skipailh marc'h-houarn amatour", "Skipailhoù marc'h-houarn amatour", "Strollad sport I", "Strolladoù sport I", "Strollad sport II", "Strolladoù sport II", "Strollad sport III", "Strolladoù sport III", "Skipailh kemmesk", "Skipailhoù kemmesk", "Skipailh merc'hed", "Skipailhoù merc'hed"}
	l10nDef["//ca.wikipedia.org"] = {"Nom de l'equip", "País", "Codi", "WorldTeam", "WorldTeams", "ProTeam", "ProTeams", "Equip continental professional", "Equips continentals professionals", "Equip continental", "Equips continentals", "Equip nacional", "Equips nacionals", "Equip regional i de club", "Equips regionals i de clubs", "Equip ciclista professional", "Equips ciclistes professionals", "Equip ciclista amateur", "Equips ciclistes amateurs", "Grup esportiu I", "Grups esportius I", "Grup esportiu II", "Grups esportius II", "Grup esportiu III", "Grups esportius III", "Equip mixt", "Equips mixtos", "Equip femení", "Equips femenins"}
	l10nDef["//eo.wikipedia.org"] = {"Nomo de la teamo", "Lando", "Kodo", "Monda teamo", "Mondaj teamoj", "ProTeamo", "ProTeamoj", "Profesiista kontinenta teamo", "Profesiistaj kontinentaj teamoj", "Kontinenta teamo", "Kontinentaj teamoj", "Nacia teamo", "Naciaj teamoj", "Regiona aux kluba teamo", "Regionaj aux klubaj teamoj", "Profesiista bicikla teamo", "Profesiistaj biciklaj teamoj", "Amatora bicikla teamo", "Amatoraj biciklaj teamoj", "Sporta grupo 1", "Sportaj grupoj 1", "Sporta grupo 2", "Sportaj grupoj 2", "Sporta grupo 3", "Sportaj grupoj 3", "Miksa teamo", "Miksaj teamoj", "Ina teamo", "Inaj teamoj"}
	l10nDef["//lb.wikipedia.org"] = {"Equippennumm", "Land", "Code", "WorldTeam", "WorldTeams", "ProTeam", "ProTeams", "Professionell Kontinentalequipe", "Professionell Kontinentalequippen", "Kontinentalequipe", "Kontinentalequippen", "Nationalequipe", "Nationalequippen", "Regional- a Klubequipe", "Regional- a Klubequippen", "Professionell Vëlosequipe", "Professionell Vëlosequippen", "Amateursequipe", "Amateursequippen", "Sportsgrupp I", "Sportsgruppen I", "Sportsgrupp II", "Sportsgruppen II", "Sportsgrupp III", "Sportsgruppen III", "Gemëscht Equipe", "Gemëscht Equippen", "Dammenequipe", "Dammenequippen"}
	l10nDef["//ro.wikipedia.org"] = {"Numele echipei", "Țară", "Cod", "WorldTeam", "WorldTeams", "ProTeam", "ProTeams", "Echipă continentală profesionistă", "Echipe continentale profesioniste", "Echipă continentală", "Echipe continentale", "Echipă națională", "Echipe naționale", "Echipă regională și de club", "Echipe regionale și de club", "Echipă ciclistă profesionistă", "Echipe cicliste profesioniste", "Echipă ciclistă de amatori", "Echipe cicliste de amatori", "Grup sportiv I", "Grupuri sportive I", "Grup sportiv II", "Grupuri sportive II", "Grup sportiv III", "Grupuri sportive III", "Echipă mixtă", "Echipe mixte", "Echipă feminină", "Echipe feminine"}
	l10nDef["//www.wikidata.org"] = l10nDef["//fr.wikipedia.org"]
	local l10n = l10nDef[mw.site.server]
	if not l10n then l10n = l10nDef["//fr.wikipedia.org"] end  -- default
	return l10n[x]
end 

function headoftableIV(x) -- En-tête du tableau du palmarès d'une course cycliste
	local l10nDef = { }
	l10nDef["//fr.wikipedia.org"] = {"Année", "Vainqueur", "Deuxième", "Troisième"}
	l10nDef["//en.wikipedia.org"] = {"Year", "Winner", "Second", "Third"}
	l10nDef["//br.wikipedia.org"] = {"Bloavezh", "1añ", "2l", "3de"}
	l10nDef["//ca.wikipedia.org"] = {"Any", "Vencedor", "Segon", "Tercer"}
	l10nDef["//cs.wikipedia.org"] = {"Ročník", "Vítěz", "Druhý", "Třetí"}
	l10nDef["//da.wikipedia.org"] = {"År", "Vinder", "Toer", "Treer"}
	l10nDef["//de.wikipedia.org"] = {"Jahr", "Sieger", "Zweiter", "Dritter"}
	l10nDef["//eo.wikipedia.org"] = {"Jaro", "Venkinto", "Dua pozicio", "Tria pozicio"}
	l10nDef["//es.wikipedia.org"] = {"Año", "Ganador", "Segundo", "Tercero"}
	l10nDef["//eu.wikipedia.org"] = {"Urtea", "Irabazlea", "Bigarrena", "Hirugarrena"}
	l10nDef["//hu.wikipedia.org"] = {"Év", "Versenyző", "Második", "Harmadik"}
	l10nDef["//it.wikipedia.org"] = {"Anno", "Vincitore", "Secondo", "Terzo"}
	l10nDef["//ja.wikipedia.org"] = {"年", "優勝", "準優勝", "3位"}
	l10nDef["//lb.wikipedia.org"] = {"Joer", "Gewënner", "Zweeten", "Drëtten"}
	l10nDef["//lv.wikipedia.org"] = {"Gads", "Uzvarētājs", "Otrais", "Trešais"}
	l10nDef["//mk.wikipedia.org"] = {"Година", "Победник", "Второпласиран", "Третопласиран"}
	l10nDef["//nl.wikipedia.org"] = {"Jaar", "Winnaar", "Tweede", "Derde"}
	l10nDef["//no.wikipedia.org"] = {"År", "Vinner", "Andreplass", "Tredjeplass"}
	l10nDef["//pl.wikipedia.org"] = {"Rok", "Pierwsze", "Drugie", "Trzecie"}
	l10nDef["//pt.wikipedia.org"] = {"Ano", "Vencedor", "Segundo", "Terceiro"}
	l10nDef["//ro.wikipedia.org"] = {"An", "Câștigător", "Locul doi", "Locul trei"}
	l10nDef["//ru.wikipedia.org"] = {"Год", "Победитель", "Второй", "Третий"}
	l10nDef["//sr.wikipedia.org"] = {"Година", "Победник", "Други", "Трећи"}
	l10nDef["//www.wikidata.org"] = {"Année", "Vainqueur", "Deuxième", "Troisième"}
	local l10n = l10nDef[mw.site.server]
	if not l10n then l10n = l10nDef["//fr.wikipedia.org"] end  -- default
	return l10n[x]
end 

function typeofstage(x, typ)
 	--  plain, hilly, inter, ... must be "" or "any text"
 	--  l10nDef[""] = {plain = "", hilly="", inter='', mount='', time_prologue='', time_team='', time_indiv='', uphill='', rest=''}
	local l10nDef = { }
	l10nDef["fr"] = {plain = "étape de plaine", hilly="étape vallonnée", inter='étape de moyenne montagne', mount='étape de montagne', time_prologue='prologue', time_team='contre-la-montre par équipes', time_indiv='contre-la-montre individuel', uphill='contre-la-montre en côte', rest='étape de repos'}	
	l10nDef["en"] = {plain = "plain stage", hilly="hilly stage", inter='intermediate stage', mount='mountain stage', time_prologue='time trial stage', time_team='team time trial stage', time_indiv='individual time trial stage', uphill='uphill time trial stage', rest='rest day'}
	l10nDef["es"] = {plain = "etapa llana", hilly="etapa escarpada", inter='etapa de media montaña', mount='etapa de montaña', time_prologue='prólogo', time_team='contrarreloj por equipos', time_indiv='contrarreloj individual', uphill='cronoescalada', rest='jornada de descanso'}
	l10nDef["br"] = {plain = "tennad plaen", hilly="tennad digompez", inter='tennad damveneziek', mount='tennad meneziek', time_prologue='', time_team='ABEU a-skipailhoù', time_indiv='ABEU', uphill='', rest='devezh diskuizh'}
	l10nDef["ca"] = {plain = "etapa plana", hilly="etapa accidentada", inter='etapa de mitja muntanya', mount='etapa de muntanya', time_prologue='pròleg', time_team='contrarellotge per equips', time_indiv='contrarellotge individual', uphill='', rest='etapa de descans'}
	l10nDef["cs"] = {plain = "rovinatá etapa", hilly="", inter='kopcovitá etapa', mount='horská etapa', time_prologue='prolog', time_team='týmová časovka', time_indiv='individuální časovka', uphill='', rest=''}
	l10nDef["da"] = {plain = "Flad", hilly="Flad med brosten", inter='Kuperet', mount='Bjergetape', time_prologue='', time_team='Holdkørsel', time_indiv='Enkeltstart', uphill='', rest=''}
	l10nDef["eo"] = {plain = "ebena etapo", hilly="malebena etapo", inter='mezgranda montaro etapo', mount='montara etapo', time_prologue='prologo', time_team='teama kontraux-la-kronometro', time_indiv='individua kontraux-la-kronometro', uphill='malebena kontraux-la-kronometro', rest='ripoza etapo'}
	l10nDef["de"] = {plain = "Flachetappe", hilly="Hügelige Etappe", inter='Mittelschwere Etappe', mount='Hochgebiergsetappe', time_prologue='Prolog', time_team='Teamzeitfahren', time_indiv='Einzelzeitfahren', uphill='Bergzeitfahren', rest='Ruhetag'}
	l10nDef["ja"] = {plain = "平坦ステージ", hilly="丘陵ステージ", inter='中間ステージ', mount='山岳ステージ', time_prologue='タイムトライアルステージ', time_team='チームタイムトライアルステージ', time_indiv='個人タイムトライアルステージ', uphill='アップヒルタイムトライアルステージ', rest='休養日'}
	l10nDef["lb"] = {plain = "Flaach Etapp", hilly="Hiwweleg Etapp", inter='Mëttelschwéier Etapp', mount='Biergetapp', time_prologue='Prolog', time_team='Contre-la-montre (Equipe)', time_indiv='Contre-la-montre (Eenzel)', uphill='Biergcourse', rest='Roudag'}
	l10nDef["lv"] = {plain = "līdzenuma posms", hilly="paugurains posms", inter='vidēju kalnu posms', mount='kalnu posms', time_prologue='individuālais brauciens', time_team='komandu brauciens', time_indiv='individuālais brauciens', uphill='individuālais brauciens kalnā', rest='atpūtas diena'}	
	l10nDef["mk"] = {plain = "рамна етапа", hilly="ридеста етапа", inter='среднопланинска етапа', mount='планинска етапа', time_prologue='пролог', time_team='екипен хронометар', time_indiv='индивидуален хронометар', uphill='', rest='ден за одмор'}	
	l10nDef["nl"] = {plain = "vlakke rit", hilly="heuvelrit", inter='heuvelrit', mount='bergrit', time_prologue='proloog', time_team='ploegentijdrit', time_indiv='individuele tijdrit', uphill='klimtijdrit', rest='rustdag'}
	l10nDef["no"] = {plain = "flat etappe", hilly="kupert etappe", inter='middels klatreetappe', mount='klatreetappe', time_prologue='prolog', time_team='lagtempo', time_indiv='temporitt', uphill='klatretempoetappe', rest='hviledag'}
	l10nDef["pl"] = {plain = "płaski", hilly="", inter='pagórkowaty', mount='górski', time_prologue='prologu', time_team='jazda drużynowa na czas', time_indiv='jazda indywidualna na czas', uphill='', rest=''}
	l10nDef["ro"] = {plain = "etapă de plat", hilly="etapă valonată", inter='etapă intermediară', mount='etapă de munte', time_prologue='prolog', time_team='contratimp pe echipe', time_indiv='contratimp individual', uphill='', rest='zi de repaus'}
	l10nDef["ru"] = {plain = "равнинный", hilly="холмистый", inter='горный', mount='высокогорный', time_prologue='пролог', time_team='командная разделка', time_indiv='индивидуальная разделка', uphill='горная разделка', rest='день отдыха'}

	local wiki,l10n=mw.site.server 
	if wiki=='//www.wikidata.org' then l10n=l10nDef["fr"]
	else l10n=l10nDef[string.sub(wiki,string.find(wiki,"%a+"))] end

 	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:Mountainstage.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:Time Trial.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

function formatNumber (number)
	-- cut off the first character, a plus sign
	number = number:sub(2, -1)
	if mw.site.server == "//lv.wikipedia.org" then 
		number = number:gsub("%.", ",")
	end
	return number;
end

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

function flag (x,date)
	local year,m,d
	if date==nil then date = '+'..os.date('%Y-%m-%d') end 	
--	_,_,year,m,d = string.find(date,"(%d+)-(%d+)-(%d+)") -- year, m = month, d = day 
 	--year="1940" 
    --x = "Q145"
	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 (Pantone).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]]",
	Q183="[[File:Flag of Germany.svg|border|20px|GER]]",
	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"}
	}

	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'}, Q35={'Q60149','DEN'}, Q36={'Q42436','POL'}, 
	Q37={'Q81477','LTU'}, Q39={'Q124020','SUI'}, Q77={'Q171103','URU'},  Q145={'Q83278','GBR'}, Q159={'Q16611','RUS'}, Q191={'Q81471','EST'}, Q211={'Q130449','LAT'},
	Q212={'Q127974','UKR'}, Q214={'Q160861','SVK'}, Q232={'Q131650','KAZ'}, Q408={'Q81676','AUS'}, Q739={'Q160425','COL'} }  	

	if flag2[x]~=nil then 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 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
		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 
		return file
	end 
	return " "
end 	
	

return p