وحدة:Cycling race/2

من أرابيكا، الموسوعة الحرة
اذهب إلى التنقل اذهب إلى البحث
local p = {} 
flag_table = {}
wiki = string.match(mw.site.server, "%a+")
if wiki == "www" then available, translations = pcall( require, "Module:Cycling race-WD" ) 
else available, translations = pcall( require, "Module:Cycling race/lang" ) 
end 

if available == true and type( translations.list ) == "function" then available_list = true else available_list = false end 
if available == true and type( translations.lang_priority ) == "table" then available_lang_priority = true else available_lang_priority = false end 

local textalign = 'left'
if wiki=="ar" or wiki=="fa" or wiki=="ur" 
	then textalign = 'right'
end

function p.victories(frame)
local s = {
	header_function = victories_translate, -- translations are in function victories_translate
	header_1 = 1, 					-- translation 1 in function victories_translate is printed in the upper part of the table header
	header_2 = {2, 3, 4, 5, 6},-- translations 2, 3, 4, 5, 6 in function victories_translate are printed in this order 
									-- in the lower part of the table header. The second value 3 in {4, 3} tells where the icon will go.
	data_type = {'date', 'race', 'country', 'class', 'rider'},
	country_column = 3,
	flag_column = 2, 
	data_sort_type = {'', 'unsortable', '', '', ''}, -- see https://meta.wikimedia.org/wiki/Help:Sorting
	item = 'Q21769889', --'Q27891882' 'Q22062004' 'Q21769889' --  frame.args[1],
	property = 'P2522',
	no_country = {'www'},
	error_message = 0
}
return tableA(s, victory_main(s, Qnumber))
end

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

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

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

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

local country = true
for _, value in pairs(s.no_country) do -- get data if country should be printed in this wiki
   	if value == wiki then country = false end
end
local sortkey, sortkey_class
local tBody = ''
local tableBody, sortindex = {}, {}
local a1, b1, c1
local timeofrace

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

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

--local class_sort = { ["Q22231106"]='01', ["Q22231107"]='02', ["Q22231108"]='03', ["Q22231109"]='04', ["Q22231110"]='05', ["Q22231111"]='06', 
--	["Q22231112"]='07', ["Q22231113"]='08', ["Q22231114"]='09', ["Q22231115"]='10', ["Q22231116"]='11', ["Q22231117"]='12', ["Q22231118"]='13', 
--	["Q22231119"]='14', ["Q23015458"]='15', ["Q23005601"]='16', ["Q23005603"]='17' } 

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

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

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

	local function fn2_country()
		local raceID
		local a, b = timeStartEnd(h['raceID'], "P17", 'numeric-id', timeofrace)
		if a == true then 
			h['countryID'] = 'Q'..b 
			if available_list == true and country == true then
				if type( translations.list ) == "function" then h['countryName'] = translations.list('Q'..b) h['countryID'] = 'Q'..b end
				if h['countryName'] == '' then
					local country = mw.wikibase.getEntityObject( 'Q'..b )
					h['countryName'] = country:getLabel('ar') or country:getLabel('en') .. ' (en)'
				end
			end
		else --go from stage item to race item
			a, b = pcall(fooA, 'numeric-id', entity_race, 'P361', 1)
			if a == true then h['item2ID'] = 'Q'..b end
			if a == false then 
				a, b = pcall(fooA, 'numeric-id', entity_race, 'P31', 1) 
				if a == true then h['item3ID'] = 'Q'..b end
			end
			if a == true then 
				local a, b = timeStartEnd('Q'..b, "P17", 'numeric-id', timeofrace)
				if a == true then h['countryID'] = 'Q'..b 
					if available_list == true and country == true then
						if type( translations.list ) == "function" then h['countryName'] = translations.list('Q'..b) end
						if h['countryName'] == '' then
							local country = mw.wikibase.getEntityObject( 'Q'..b )
							h['countryName'] = country:getLabel('ar') or country:getLabel('en') .. ' (en)'
						end
					end
				end
			end
		end
	end

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

	local function fn_race(h)
		local str, a, b, a1, b1, a2, b2, a3, b3
		local label_x = ''
		local entity_x1
		local Sitelink_x, Sitelink_x0, Sitelink_x1, Sitelink_x2 = '', '', ''
		local entity_race = mw.wikibase.getEntityObject( h['raceID'] )
		local entity_type, entity_num = '', 0 
		local level = -1
		local link

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

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

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

		end
	------------------------------------------------
		if entity_type == 'else A' then
			local entity_l
			a1, b1 = pcall(fooA, 'text', entity_race, 'P1448', 1) -- show the "official name"
			if a1 == true then	
				local lang_WD, text_WD
				for _,v in pairs(entity_race.claims["P1448"]) do
					lang_WD = v.mainsnak.datavalue.value.language
					text_WD = v.mainsnak.datavalue.value.text
					if lang_WD == wiki or lang_WD == 'en' or lang_WD == 'fr' then label_x =text_WD break end
				end 			
			end		

			if label_x == '' then 
				a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P31', 1)
				if a1 == true then 
					entity_l = mw.wikibase.getEntityObject( 'Q'..b1 )
					label_x = entity_l:getLabel('ar') or
					entity_l:getLabel( 'en' ) or
					entity_l:getLabel( 'de' ) or
					entity_l:getLabel( 'fr' ) or ''	
				
				end
			end
			if entity_l ~= nil then Sitelink_x1 =( entity_l:getSitelink('arwiki') or  entity_l:getSitelink('enwiki')) end
			if entity_race ~= nil then Sitelink_x0 = ( entity_race:getSitelink('arwiki') or  entity_race:getSitelink('enwiki'))  end
			if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0				
			elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
			end
		end
----------------------------------------------
		if entity_type == 'one day race' then 
			a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P31', entity_num)
			if a1 == true then 
				entity_l = mw.wikibase.getEntityObject( 'Q'..b1 )
				label_x = entity_l:getLabel('ar') or
					entity_l:getLabel( 'en' ) or
					entity_l:getLabel( 'de' ) or
					entity_l:getLabel( 'fr' ) or ''	
			end
			if entity_l~= nil then Sitelink_x1 = ( entity_l:getSitelink('arwiki') or  entity_l:getSitelink('enwiki')) 	end		
			if entity_race~= nil then Sitelink_x0 = ( entity_race:getSitelink('arwiki') or  entity_race:getSitelink('enwiki')) 	end		
			if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0				
			elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
			end
		end
------------------------------------------
		if entity_type == 'championship' then 
		mw.log(entity_type)
			a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P31', entity_num)
			if a1 == true then
				entity_l = mw.wikibase.getEntityObject( 'Q'..b1 )
				label_x = entity_l:getLabel('ar') or
					entity_l:getLabel( 'en' ) or
					entity_l:getLabel( 'de' ) or
					entity_l:getLabel( 'fr' ) or ''	
			end
			a1, b1 = pcall(fooA, 'numeric-id', entity_l, 'P361', 1)
			if a1 == true then 
				entity_x = mw.wikibase.getEntityObject( 'Q'..b1 )
				if entity_x ~= nil then 
					if wiki == 'www' then 
						Sitelink_x = entity_x:getSitelink('frwiki')
						link = '[[:fr:'..Sitelink_x..'|'.. label_x.. ']]'
					elseif wiki == 'ar' then 
						Sitelink_x = entity_x:getSitelink('arwiki')
						if Sitelink_x~=nil then link = '[['..Sitelink_x..'|'.. label_x.. ']]' else link = label_x	end		
					else
						Sitelink_x = entity_x:getSitelink(wiki..'wiki')
						if Sitelink_x~=nil then link = '[['..Sitelink_x..'|'.. label_x.. ']]' else link = label_x end						
					end
				end
			end
		end
------------------------------------------
		if entity_type == 'stage' then
			local entity_l
			a1, b1 = pcall(fooA, 'numeric-id', entity_race, 'P361', 1)
			if a1 == true then 
				entity_x1 = mw.wikibase.getEntityObject( 'Q'..b1 )
				a2, b2 = pcall(fooA, 'numeric-id', entity_x1, 'P31', 1)
					if a2 == true then
						local is_class = false
						for i=1,#class do
   							if "Q"..b2 == class[i] then is_class = true break end
   						end
						if is_class == false then entity_l = mw.wikibase.getEntityObject( 'Q'..b2 )
						else
							a3, b3 = pcall(fooA, 'numeric-id', "Q"..b2, 'P31', 2)
							if a3 == true then entity_l = mw.wikibase.getEntityObject( 'Q'..b3 ) end
						end
					end	
					label_x = entity_l:getLabel('ar') or
						entity_l:getLabel( 'en' ) or
						entity_l:getLabel( 'de' ) or
						entity_l:getLabel( 'fr' ) or ''			
			end
			entity_stage = mw.wikibase.getEntityObject( 'Q18131152' )
			entity_prolog = mw.wikibase.getEntityObject( 'Q485321' )			

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


			a, b = pcall(fooA, 'value', entity_race, 'P1545', 1)		
			if a == false then b = '?' end
			if b ~= '0' then
				local l10nDef = {["fr"]="étape", ["en"]="stage", ["ar"]="مرحلة", ["br"]="Tennad", ["ca"]="etapa", ["cs"]="etapa", ["de"]="Etappe", ["da"]="etape", ["eo"]="Etapo",
				["es"]="etapa", ["eu"]="Etapa", ["fi"]="Etappi", ["fo"]="teinur", ["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 stage_label = l10nDef[wiki]
				if stage_label == nil then stage_label = entity_stage:getLabel(wiki) or entity_stage:getLabel('en') or entity_stage:getLabel('fr') end

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

				if wiki=="de" or wiki=="da" or wiki=="fo" or wiki=="no" then
				label_x = label_x.. ', '.. b.. '. '.. stage_label
				elseif wiki=='en' or wiki=='br' then label_x = label_x.. ', '.. stage_label.. ' '.. b

				elseif wiki=='ar' then 
					label_x = label_x  .. '، ' .. stage_label .. ' '.. b
					if entity_l~= nil then Sitelink_x2 = (entity_l:getSitelink('arwiki') or entity_l:getSitelink('enwiki')) end
					if entity_x1~=nil then Sitelink_x1 = (entity_x1:getSitelink('arwiki') or entity_x1:getSitelink('enwiki')) end
					if entity_race~=nil then Sitelink_x0 = (entity_race:getSitelink('arwiki') or entity_race:getSitelink('enwiki'))  end
					if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0				
					elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
					elseif Sitelink_x2 ~= nil then Sitelink_x = Sitelink_x2 level = 2
					end

				elseif wiki == 'www' or wiki == 'fr' or wiki=="lb"  then
					if entity_l~= nil then Sitelink_x2 = entity_l:getSitelink('frwiki') end
					if entity_x1~=nil then Sitelink_x1 = entity_x1:getSitelink('frwiki') end
					if entity_race~=nil then Sitelink_x0 = entity_race:getSitelink('frwiki') end
					if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0				
					elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
					elseif Sitelink_x2 ~= nil then Sitelink_x = Sitelink_x2 level = 2
					end

					--local _, _, y, m, d = string.find(timeofrace, "(%d+)%p(%d+)%p(%d+)")
					if level == 1 or level == 2 then  
						if b == '1' then link = b.. '<sup>re</sup>'.. substage.. stage_label.. comma.. '[[:fr:'..Sitelink_x..'#1re.C2.A0.C3.A9tape'..'|'.. label_x.. ']]' 
						else link = b.. '<sup>e</sup>'.. substage.. stage_label.. comma.. '[[:fr:'..Sitelink_x..'#'.. b.. 'e.C2.A0.C3.A9tape'..'|'.. label_x..']]' 
						end
					end
					if level == 0 then 
						if b == '1' then link = '[[:fr:'..Sitelink_x.. '|'.. b.. '<sup>re</sup>'.. substage.. stage_label.. comma.. label_x.. ']]' 
						else link = '[[:fr:'..Sitelink_x.. '|'.. b.. '<sup>e</sup>'.. substage.. stage_label.. comma.. label_x..']]' 
						end						
					end
				
				elseif wiki=="ca" then label_x = b.. 'a '.. stage_label.. ' del '.. label_x
				elseif wiki=="es" then label_x = b.. "<sup>a</sup> ".. stage_label.. ', '.. label_x
				else label_x = stage_label.. ' '.. b..', '.. label_x 
				end
			else -- Prolog
				if entity_l~= nil then Sitelink_x2 = (entity_l:getSitelink('arwiki') or entity_l:getSitelink('enwiki')) end
				if entity_x1~=nil then Sitelink_x1 = (entity_x1:getSitelink('arwiki') or entity_x1:getSitelink('enwiki')) end
				if entity_race~=nil then Sitelink_x0 = (entity_race:getSitelink('arwiki') or entity_race:getSitelink('enwiki')) end
				if Sitelink_x0 ~= nil then Sitelink_x = Sitelink_x0	level = 0				
				elseif Sitelink_x1 ~= nil then Sitelink_x = Sitelink_x1 level = 1
				elseif Sitelink_x2 ~= nil then Sitelink_x = Sitelink_x2 level = 2
				end	
				
				local l10nDef = { ["fr"]="Prologue", ["ar"]="المقدمة", ["en"]="Prologue", ["br"]="Prolog", ["ca"]="Pròleg", ["cs"]="Prolog", ["de"]="Prolog", ["da"]="Prolog", ["eo"]="Prologo",
				["es"]="Prólogo", ["eu"]="Aitzinetapa", ["fi"]="Prologi", ["fo"]="Forteinur", ["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 prolog_label 
				if wiki == 'www' then prolog_label = l10nDef['fr'] else prolog_label = l10nDef[wiki] end
				if prolog_label == nil then
					prolog_label = entity_prolog:getLabel('ar') or entity_prolog:getLabel('en') or entity_prolog:getLabel('fr') or
					entity_prolog:getLabel('de')
					prolog_label = mw.ustring.gsub(prolog_label, "^(%a)",function (x) return mw.ustring.upper(x) end)
				end

				if wiki=="de" or wiki=="da" or wiki=="fo" or wiki=="no" then label_x = label_x.. ', '.. prolog_label
				elseif wiki == 'en' then label_x = label_x.. ', '.. prolog_label
				elseif wiki == 'ar' then label_x = label_x.. '، '.. prolog_label
				elseif wiki == 'www' or wiki == 'fr' or wiki=="lb" then 
					if level > 0 then link = prolog_label.. comma.. '[[:fr:'..Sitelink_x..'#'..prolog_label.. '|'.. label_x.. ']]' end
					if level == 0 then link = '[[:fr:'..Sitelink_x..'#'..prolog_label.. '|'.. prolog_label.. comma.. label_x.. ']]' end
				else label_x = prolog_label.. ', '.. label_x 
				end
			end
		end

		if level == -1 then
			local Sitelink = ''
			local entity_k = mw.wikibase.getEntityObject( h['raceID'] )
			if wiki == 'www' then Sitelink = entity_k:getSitelink('frwiki') else Sitelink = entity_k:getSitelink(wiki..'wiki') end
			if Sitelink ~= '' and Sitelink ~= nil then				
				if wiki == 'www' then link = '[[:fr:'..Sitelink..'|'..label_x..']]' else link = '[['..Sitelink..'|'..label_x..']]' end
			end
		end
		if level >= 0 and link == nil and Sitelink_x ~= '' then
			if wiki == 'www' then link = '[[:fr:'..Sitelink_x..'|'..label_x..']]'
			else link = '[['..Sitelink_x..'|'..label_x..']]'
			end
		end
		if link == nil then link = label_x end
	
		if available_list==true and country == true then str =  '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..link.. '</td>'
		else
			fn2_country()
			if h['countryID'] ~= '' then str = '<td style="text-align:'.. textalign ..';padding:0 0.5em">'.. flag(h['countryID'], timeofrace).. ' '.. link.. '</td>'
			else str = '<td style="text-align:'.. textalign ..';padding:0 2.3em">'..link.. '</td>'
			end
		end		
	return str
	end	

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

	local function fn_class(h)
		local entity_race = mw.wikibase.getEntityObject( h['raceID'] )
		local entity_type, entity_num = '', 0 
		local class_text = ''
		local link = ''
		local Sitelink
		sortkey_class = ''
		
		a, b = pcall(fooA, 'numeric-id', entity_race, 'P31', 1)
		if a == true then
			-- test for stage item
			for i=1,#stages do
				if "Q"..b == stages[i] then entity_type = 'stage' end
			end
		end		

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

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

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

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

	if winner ~= '' then 
		local winner_team = false
		local entity_winner = mw.wikibase.getEntityObject( winner )
		a, b = pcall(fooA, 'numeric-id', entity_winner, 'P31', 1) -- looking if winner is a person
		if a == true and b ~= 5 then winner_team = true end			
		
		if winner_team == false then return '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..winner_flag.. WPlink(winner).. '</td>'
		else 
		winner_flag = ''
		local a, b = timeStartEnd(winner, "P17", 'numeric-id', timeofrace) -- flag of team
	   	if a == true then 
	   		winner_flag = flag('Q'..b, timeofrace).. ' '		
		end			
			return '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..winner_flag.. WPlink(winner, 'team', timeofrace).. '</td>' 
		end
	else return '<td style="text-align:'.. textalign ..';padding:0 0.5em">'..''.. '</td>'
	end
	end

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

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

function WPlink_entity(entity, ...) 
local link=''
local Sitelink = entity:getSitelink() -- link to WParticle
local Sitelink2 = Sitelink
local Label = entity:getLabel('ar') or ''
local Label_fr = entity:getLabel( 'fr' ) or ''
local a, b
local official_name = ""
local wiki = string.match(mw.site.server, "%a+")

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

		Sitelink2 = entity:getSitelink() -- link to WParticle		
	end
	if a == true then official_name = b end
	
	if available_lang_priority == false then
		a, b = pcall(fooA, 'text', entity, 'P1448', 2) -- test if more then two official names
		if a == true then
			a, b = timeStartEnd_entity(entity, 'P1448', 'text', arg[2]) --officialName(entity) 
			if a == true then official_name = b end
		else
			a, b = pcall(fooA, 'text', entity, 'P1448', 1) 
			if a == true then official_name = b end	
		end
	end
			
	if Sitelink ~= nil then 
		if official_name == nil then 
			link = "[[".. Sitelink.. "|".. mw.text.trim(mw.ustring.gsub(Sitelink,"%b()","").. ' ').. "]]" 
		else
			if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
				local i, _ = mw.ustring.find(Sitelink, ",")
				if i ~= nil then Sitelink = mw.ustring.sub(Sitelink, 1, i-1) end
			end
			link = link .. '[['.. Sitelink.. "|".. official_name.. ']]'
		end
	end
	if link == '' and Sitelink2 ~= nil then -- code goes from season item to team item
		if official_name == nil then
			link = "[[".. Sitelink2.. "|".. mw.text.trim(mw.ustring.gsub(Sitelink2,"%b()","").. ' ').. "]]" 	
		else
			if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
				local i, _ = mw.ustring.find(Sitelink2, ",")
				if i ~= nil then Sitelink2 = mw.ustring.sub(Sitelink2, 1, i-1) end
			end		
			link = link .. '[['.. Sitelink2.."|".. official_name.. ']]' 
		end		
	end

	if Sitelink == nil and Sitelink2 == nil then 
		if official_name ~='' then link = official_name else link = entity:getLabel('ar') end
		if link == nil then link = "(label missing)" end
	end	

end -- end arg[1]
return link
end

function timeStartEnd_entity(entity, property, mode, timeofrace)
-- mode = 'numeric-id', property = 'P54', Qid = 'Q123'
--local entity = 	mw.wikibase.getEntity(Qid)
local a, b = pcall(fooA, mode, entity, property, 1)
local starttime, endtime
local available_lang_priority = available_lang_priority

if a == true then
	local timeStartEnd = {}
	local num = 1
	local v
	for _, v in pairs(entity.claims[property]) do
		if pcall(function () local test = v.mainsnak.datavalue.value[mode] end) then -- test if not 'unnown value' 
			if pcall(function () starttime = v.qualifiers["P580"][1].datavalue.value.time end) then
   				starttime = v.qualifiers["P580"][1].datavalue.value.time
				local _,_,year,m,d = string.find(starttime,"(%d+)-(%d+)-(%d+)")
				if m == '00' and d == '00' then starttime = '+'..year..'-01-01T00:00:00Z' end
			end
			if pcall(function () endtime = v.qualifiers["P582"][1].datavalue.value.time end) then
				endtime = v.qualifiers["P582"][1].datavalue.value.time
				local _,_,year,m,d = string.find(endtime,"(%d+)-(%d+)-(%d+)")
				if m == '00' and d == '00' then endtime = '+'..year..'-12-31T00:00:00Z' end
				if m == '01' and d == '01' then endtime = '+'..year..'-12-31T00:00:00Z' end
			end
  			if v.qualifiers then
 				if (not v.qualifiers["P580"] or starttime <= timeofrace)
 					and
 					(not v.qualifiers["P582"] or endtime >= timeofrace)
 				then
 					if available_lang_priority == true and property == "P1448" then
 						local test = false
						pcall(function () if type( v.qualifiers["P1448"])=='table' then test=true end end)
						if test == false then
							timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
						else
							local lang_module, lang_WD
							local language= ''
							local zaehler
							for i,j in ipairs(translations.lang_priority) do
									lang_module = j
									for number in pairs(v.qualifiers["P1448"]) do
										lang_WD = v.qualifiers["P1448"][number].datavalue.value.language
										if lang_WD == lang_module then zaehler = number break end
									end -- for number in pairs
								if lang_WD == lang_module then language = lang_WD   break end
								end -- for i,j
							if language~='' then -- a WD translation matching translations.lang_priority exist
									local t = v.qualifiers["P1448"][zaehler].datavalue.value.text
									timeStartEnd[num] = t
	 							else timeStartEnd[num] = v.mainsnak.datavalue.value[mode]--  no matching between lang module and "official name" qualifier
								end -- if language~=''
						end --  test if official name qualifier exist
 					else timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
					end -- if property == "P1448"
  					num = num + 1
 				end
 			else
 				timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
 				num = num + 1
 			end
		end
 	end
	return a, timeStartEnd[1]
else return false, '' end
end

function func_error_message(wiki,x) 
local l10nDef = { }	
l10nDef["en"] = {'Property <1> is missing in item "<2>" (<3>)'}
local l10n = l10nDef[wiki]
if not l10n then l10n = l10nDef["en"] end  -- default
return l10n[x]	
end 

function tableA(s, tableBody)
local s = s
local tableBody = tableBody
local available_list = available_list
local entity = mw.wikibase.getEntityObject( s.item )

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

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

local country = true
 for _, value in pairs(s.no_country) do -- get data if country should be printed in this wiki
    if value == wiki then country = false end
end

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

		if k ~= s.country_column then tableHeader2 = tableHeader2..s.header_function (wiki, k)
		else tableHeader2 = tableHeader2..s.header_function (wiki, k)
		end
	end
end

tableHeader2 = tableHeader2.. '</th></tr>'

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

function victories_translate(wiki,x) 
local l10nDef = { }	
l10nDef["ar"] = {"سجل الفوز", "التاريخ", "السباق", "البلد", "الصنف", "الفائز"}
l10nDef["fr"] = {"Victories", "Date", "Course", "Pays", "Classe", "Vainqueur"}
l10nDef["en"] = {"Victories", "Date", "Race", "Country", "Class", "Winner"}
l10nDef["da"] = {"Victories", "Dato", "Løb", "Land", "Klasse", "Vinder"}
l10nDef["es"] = {"Victories", "Fecha", "Carrera", "País", "Clase", "Ganador"}
l10nDef["ja"] = {"Victories", "開催日", "レース", "国", "国", "勝者"}
l10nDef["mk"] = {"Victories", "Датум", "Трка", "Земја", "Класа", "Победник"}
l10nDef["no"] = {"Victories", "Dato", "Løp", "Land", "Klasse", "Vinner"}
l10nDef["ru"] = {"Victories", "Дата", "Гонка", "Страна", "Класс", "Победитель"}
	
local l10n = l10nDef[wiki]
if not l10n then l10n = l10nDef["fr"] end  -- default
return l10n[x]	
end 

function func_date (date, wiki, mode)
--	local wiki = 'cs'
--	local mode = 'small'
--	local date = '+2016-05-20'
	local function standard(datum) 
		if mode=='long' then return mw.language.getContentLanguage():formatDate("j F Y", datum) end 
		if mode=='small' then return mw.language.getContentLanguage():formatDate("j M", datum) end 		
	end
	local function ar(datum) 
		local lang = mw.getLanguage('ar') 
		if mode=='long' then return mw.getLanguage('ar'):formatDate("j F Y", datum) end 
		if mode=='small' then return mw.getLanguage('ar'):formatDate("j F Y", datum) end 	
		end
	local function br(datum) 
		local lang = mw.getLanguage('br') 
		if mode=='long' then return lang:formatDate("j", datum ) .." a viz ".. lang:formatDate("F Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum ) .." a viz ".. lang:formatDate("M", datum) end 		
	end	
	local function ca(datum, language) 
		local lang = mw.getLanguage(language) 
		if mode=='long' then return lang:formatDate("j", datum) .." de ".. lang:formatDate("F", datum) .." de ".. lang:formatDate("Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum) .." de ".. lang:formatDate("M", datum) end 		
	end
	local function cs(datum)
		local lang = mw.getLanguage('cs') 		
		if mode=='long' then return lang:formatDate("j. xg Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum)  ..". xg ".. lang:formatDate("M", datum) end 		
	end
	local function de(datum, language) 
		if mode=='long' then return mw.getLanguage(language):formatDate("j. F Y", datum) end 
		if mode=='small' then return mw.getLanguage(language):formatDate("j. M", datum) end 	
	end		
	local function eo(datum) 
		local lang = mw.getLanguage('eo') 
		if mode=='long' then return lang:formatDate("j", datum) .."-a de ".. lang:formatDate("F Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum) .."-a de ".. lang:formatDate("M", datum) end 		
	end	
	local function en(datum) 
		if mode=='long' then return mw.getLanguage('en'):formatDate("F d, Y", datum) end 
		if mode=='small' then return mw.getLanguage('en'):formatDate("M d", datum) end 	
		end
	local function eu(datum) 
		local lang = mw.getLanguage('eu') 
		if mode=='long' then return lang:formatDate( "Y", datum) ..".eko ".. lang:formatDate("F", datum) .."k ".. lang:formatDate("j", datum) end 
		if mode=='small' then return lang:formatDate( "M", datum) .."k ".. lang:formatDate("j", datum) end 		
	end
	local function fi(datum) -- may be different
		if mode=='long' then return mw.ustring.gsub(mw.getLanguage('fi'):formatDate("j. F Y", date), "%a+", "%0ta") end 
		if mode=='small' then return mw.getLanguage('fi'):formatDate("j. M", date) end 		
	end 
	local function hu(datum) 
		local lang = mw.getLanguage('hu') 
		if mode=='long' then return lang:formatDate( "Y", datum) ..". ".. lang:formatDate("F", datum) .." ".. lang:formatDate("j", datum)..". " end
		if mode=='small' then return lang:formatDate( "M", datum) ..". ".. lang:formatDate("j", datum) end 		
	end
	local function ja(datum) 
		if mode=='long' then return mw.getLanguage('ja'):formatDate("Y年m月d日", datum) end 
		if mode=='small' then return mw.getLanguage('ja'):formatDate("m月d日", datum) end	
	end	
	local function lv(datum)
		local lang = mw.getLanguage('lv') 
		if mode=='long' then return lang:formatDate("Y.", datum)  .." gada ".. lang:formatDate("j. F", datum) end 
		if mode=='small' then return lang:formatDate("Y. M", datum) end 		
	end 	
	local function pl(datum) 
		local lang = mw.getLanguage('pl') 
		local date_pl = {"stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca", "lipca", "sierpnia", "września", "października", "listopada", "grudnia"}
		if mode=='long' then return lang:formatDate("j ", datum) .. date_pl[tonumber(lang:formatDate("n", datum))] .. lang:formatDate(" Y", datum) end 
		if mode=='small' then return lang:formatDate("j M", datum) end 		
	end		

	local x = {['']=standard(date), ['ar']=ar(date), ['br']=br(date), ['ca']=ca(date,'ca'), ['cs']=cs(date), ['da']=de(date,'da'), ['de']=de(date,'de'), ['en']=en(date), ['eo']=eo(date), 
		['es']=ca(date,'es'), ['eu']=eu(date), ['fi']=fi(date), ['fo']=de(date,'fo'), ['hu']=hu(date), ['ja']=ja(date), ['lv']=lv(date), ['no']=de(date,'no'), ['pl']=pl(date)}

	return x[wiki] or x['']
end

function WPlink(Qnumber, ...) 
local link=''
local entity = mw.wikibase.getEntity( Qnumber )
local Sitelink = entity:getSitelink() -- link to WParticle
local Sitelink2 = Sitelink
local Label = entity:getLabel('ar') or ''
local Label_fr = entity:getLabel( 'fr' ) or ''
local a, b
local official_name = ""
local wiki = string.match(mw.site.server, "%a+")

if arg[1] == nil then 	
	if pcall(foo1, Qnumber) then 
		if Sitelink ~= nil then 
			if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
				if Sitelink~=nil then
					local i, _ = mw.ustring.find(Sitelink, ",")
					if i ~= nil then Sitelink2 = mw.ustring.sub(Sitelink, 1, i-1) end
				end
			end
			link = "[[" .. Sitelink .. "|" .. mw.text.trim(mw.ustring.gsub(Sitelink2, "%b()", "")..' ') .. "]]"	
			if wiki == "de" then -- ru riders get label as alias, to shorten the name
				local a, b = pcall(fooA, 'numeric-id', entity, 'P27', 1) 
				if a == true and (b==159 or b==184 or b==212 or b==232) then link = "[[" .. Sitelink .. "|" .. Label .. "]]" end
			end
		elseif Label ~= '' then 
			if wiki ~= 'www' then
				--if black_list(wiki, Label) == true then 
					link = Label -- function black_list: articles that are printed as text, not wikilinks
				--else -- detect if there is a different local article with the same name
					--local title = mw.title.new(Label)
					--if title.exists then link = Label else link = "[[" .. Label.. "]]" end
				--end
			else link = Label end
		else link = Label end 
	else return "unknown ID in function WPlink" end
	if link == '' then 
		link = entity:getLabel('ar') or entity:getLabel('en') or entity:getLabel('fr') or entity:getLabel('de') or ''
		if link ~= '' then link = mw.ustring.gsub(link, "%b()", "")
		else link =  "(label missing)" end  
	end
end -- if arg[1] == nil
if arg[1] == 'team' then -- add '(team of the winner)'
	a, b = timeStartEnd(Qnumber, 'P1448', 'text', arg[2]) --officialName(entity) 
	local a1, b1 = pcall(fooA, 'numeric-id', entity, 'P361', 1)
	if a1== true then 
		local a2, b2 = timeStartEnd('Q'..b1, 'P1448', 'text', arg[2]) 
		if a2== true then a = a2 b = b2	end
		entity = mw.wikibase.getEntity( 'Q'..b1 ) 
		Sitelink2 = entity:getSitelink() -- link to WParticle		
	end
	if a == true then official_name = b end
	
	if available_lang_priority == false then
		a, b = pcall(fooA, 'text', entity, 'P1448', 2) -- test if more then two official names
		if a == true then
			a, b = timeStartEnd(Qnumber, 'P1448', 'text', arg[2]) --officialName(entity) 
			if a == true then official_name = b end
		else
			a, b = pcall(fooA, 'text', entity, 'P1448', 1) 
			if a == true then official_name = b end	
		end
	end
			
	if Sitelink ~= nil then 
		if official_name == nil then 
			link = "[[".. Sitelink.. "|".. mw.text.trim(mw.ustring.gsub(Sitelink,"%b()","").. ' ').. "]]" 
		else
			if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
				local i, _ = mw.ustring.find(Sitelink, ",")
				if i ~= nil then Sitelink = mw.ustring.sub(Sitelink, 1, i-1) end
			end
			link = link .. '[['.. Sitelink.. "|".. official_name.. ']]'
		end
	end
	if link == '' and Sitelink2 ~= nil then -- code goes from season item to team item
		if official_name == nil then
			link = "[[".. Sitelink2.. "|".. mw.text.trim(mw.ustring.gsub(Sitelink2,"%b()","").. ' ').. "]]" 	
		else
			if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
				local i, _ = mw.ustring.find(Sitelink2, ",")
				if i ~= nil then Sitelink2 = mw.ustring.sub(Sitelink2, 1, i-1) end
			end		
			link = link .. '[['.. Sitelink2.."|".. official_name.. ']]' 
		end		
	end

	if Sitelink == nil and Sitelink2 == nil then 
		if official_name ~='' then link = official_name else link = entity:getLabel('ar') end
		if link == nil then link = "(label missing)" end
	end	

end -- end arg[1]
if arg[1] == 'pure' then
	if pcall(foo1, Qnumber) then
		if wiki=="en" or wiki=="www" then --delete string ", ..." from e.g. "Unley, South Australia"
			if Sitelink~=nil then
				local i, _ = mw.ustring.find(Sitelink, ",")
				if i ~= nil then Sitelink2 = mw.ustring.sub(Sitelink, 1, i-1) end
			end
		end		
		if Sitelink ~= nil then link = "[[" .. Sitelink .. "|" .. mw.text.trim(mw.ustring.gsub(Sitelink2, "%b()", "")..' ') .. "]]"	
		else link = mw.ustring.gsub(Label, "^(%a)", function (x) return mw.ustring.upper(x) end)
		end 
	end
end
if arg[1] == 'race' then -- for infobox "Competitions"
	local a, b = pcall(fooA, 'numeric-id', entity, 'P31', 1)
	if a == true  and b == 1137352 then
		local entity_race = mw.wikibase.getEntity( 'Q'..b )
		local Label_race = entity_race:getLabel('ar') or ''
		local Sitelink_race = entity_race:getSitelink() or ''
		if Label_race ~= '' and Sitelink ~= nil  then link = '[['..Sitelink..'|'..Label_race..']]'
		elseif Sitelink ~= nil  then link = "[[".. Sitelink.. "]]"
		else if Sitelink_race ~= '' then link = '[['..Sitelink_race.."|".. mw.text.trim(mw.ustring.gsub(Sitelink_race,"%b()","").. ' ').. "]]" 
			else link = Label_race or Label end
		end
		if wiki == 'www' then link = '[['..entity:getSitelink( 'frwiki')..'|'..entity_race:getLabel('fr')..']]' end

	else if Sitelink ~= nil then link = "[[".. Sitelink.. "]]" else link = Label end
	end
end
if arg[1] == "Q22348500" then -- add weblink from item "Q22348500" if available
	local Sitelink_claas = mw.wikibase.getEntity( 'Q22348500' ):getSitelink() 	
	if pcall(foo1, Qnumber) then --Sitelink_claas
		if Sitelink == nil then 
			if Sitelink_claas ~= nil then link = "[[" .. Sitelink_claas .. "|" .. Label .. "]]" 
			elseif entity:getLabel( 'ar' )~=nil then link = entity:getLabel( 'ar' )
			elseif entity:getLabel( 'fr' )~=nil then link = entity:getLabel( 'fr' )
			elseif entity:getLabel( 'en' )~=nil then link = entity:getLabel( 'en' )
			elseif entity:getLabel( 'de' )~=nil then link = entity:getLabel( 'de' )				
			else link = Label 
			end 
		end
	end
end
return link
end

function timeStartEnd(Qid, property, mode, timeofrace)
-- mode = 'numeric-id', property = 'P54', Qid = 'Q123'
local entity = 	mw.wikibase.getEntity(Qid)
local a, b = pcall(fooA, mode, entity, property, 1)
local starttime, endtime
local available_lang_priority = available_lang_priority

if a == true then
	local timeStartEnd = {}
	local num = 1
	local v
	for _, v in pairs(entity.claims[property]) do
		if pcall(function () local test = v.mainsnak.datavalue.value[mode] end) then -- test if not 'unnown value' 
			if pcall(function () starttime = v.qualifiers["P580"][1].datavalue.value.time end) then
   				starttime = v.qualifiers["P580"][1].datavalue.value.time
				local _,_,year,m,d = string.find(starttime,"(%d+)-(%d+)-(%d+)")
				if m == '00' and d == '00' then starttime = '+'..year..'-01-01T00:00:00Z' end
			end
			if pcall(function () endtime = v.qualifiers["P582"][1].datavalue.value.time end) then
				endtime = v.qualifiers["P582"][1].datavalue.value.time
				local _,_,year,m,d = string.find(endtime,"(%d+)-(%d+)-(%d+)")
				if m == '00' and d == '00' then endtime = '+'..year..'-12-31T00:00:00Z' end
				if m == '01' and d == '01' then endtime = '+'..year..'-12-31T00:00:00Z' end
			end
  			if v.qualifiers then
 				if (not v.qualifiers["P580"] or starttime <= timeofrace)
 					and
 					(not v.qualifiers["P582"] or endtime >= timeofrace)
 				then
 					if available_lang_priority == true and property == "P1448" then
 						local test = false
						pcall(function () if type( v.qualifiers["P1448"])=='table' then test=true end end)
						if test == false then
							timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
						else
							local lang_module, lang_WD
							local language= ''
							local zaehler
							for i,j in ipairs(translations.lang_priority) do
									lang_module = j
									for number in pairs(v.qualifiers["P1448"]) do
										lang_WD = v.qualifiers["P1448"][number].datavalue.value.language
										if lang_WD == lang_module then zaehler = number break end
									end -- for number in pairs
								if lang_WD == lang_module then language = lang_WD   break end
								end -- for i,j
							if language~='' then -- a WD translation matching translations.lang_priority exist
									local t = v.qualifiers["P1448"][zaehler].datavalue.value.text
									timeStartEnd[num] = t
	 							else timeStartEnd[num] = v.mainsnak.datavalue.value[mode]--  no matching between lang module and "official name" qualifier
								end -- if language~=''
						end --  test if official name qualifier exist
 					else timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
					end -- if property == "P1448"
  					num = num + 1
 				end
 			else
 				timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
 				num = num + 1
 			end
		end
 	end
	return a, timeStartEnd[1]
else return false, '' end
end

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

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

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

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

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

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

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

function 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 p.test(frame)
local conf = frame.args.conf
local background_color1 = "#FFFFFF"
local parameter = frame.args.parameter
local p1, p2, p3 = {}, {}, {}

local num = 1 -- configuration section
for k, v in mw.ustring.gmatch(conf, "([%w%s_]+)%s*=%s*([#%w%s]+)") do
	local _, _, str1 = string.find(k, "(%w+_%w+)")
	local _, _, str2 = string.find(v, "(#%w+)")	
	if str1 == 'background_color1' then background_color1=str2 end
	num = num + 1
end

local num = 1 -- parameter section
for k, v in mw.ustring.gmatch(parameter, "([%w%s]+)%s*=%s*([%w%s]+)") do
	p1[num] = k p2[num] = v p3[num] = '' 
	num = num + 1
end

for k in pairs(p3) do -- value section
	local _, _, str = string.find(p1[k], "(%a+)")
	local val = frame.args[str]
	if val ~= nil then p3[k] = val end
end

local tab = "<table cellpadding='4' cellspacing='1' style='float:right; width:300px; border:1px solid rgb(200,200,200);"
tab = tab .. "margin:0 0 0.5em 0.5em; background-color:rgb(255, 255, 255); color:black; padding:5px; clear:left; "
tab = tab .. "text-align:" .. textalign .. "; font-size:85%; line-height:1.6em;'>"

tab = tab .. "<tr><td colspan='2' style='background-color:"..background_color1.."; text-align:center'>".."Infobox".."</td></tr>"

for k in pairs(p1) do 
	tab = tab.. "<tr><td>'''" .. p2[k] .."'''</td><td>" .. p3[k] .. "</td></tr>"
end

tab = tab.. "</table>"

return tab 
end 


return p