Documentația acestui modul poate fi creată la Modul:InfoboxCountry/doc

local p = {}
local getArgs = require('Modul:Arguments').getArgs
local infobox = require('Modul:Infobox')
local TableTools = require('Modul:TableTools')
local wikidata = require('Modul:Wikidata')
local StringUtils = require('Modul:StringUtils')
local displayImage = require('Modul:InfoboxImage').InfoboxImage
local illWd = require('Modul:Ill-wd').fromArgs
local DateUtils = require('Modul:DateUtils')
local GregorianDate = require('Modul:GregorianDate')
local editAtWd = require('Modul:EditAtWikidata')
local formatNum = require('Modul:Formatnum')._formatNum
local lang = require('Modul:Lang').fromArgs
local getLangLink = require('Modul:InLang').getLangLink
local join = require('Modul:Separated entries')._main

local encloseString = StringUtils._encloseString
local appendToString = StringUtils._appendToString
local prependToString = StringUtils._prependToString
local emptyToNil = StringUtils._emptyToNil
local _br_ = tostring(mw.html.create('br'))

local globalInfoboxElementIndex = 1

local function addHeader(ibArgs, header)
	ibArgs['header' .. tostring(globalInfoboxElementIndex)] = header
	globalInfoboxElementIndex = globalInfoboxElementIndex + 1
end

local function addData(ibArgs, data, wdProp)
	if wdProp then data = data .. ' ' .. editAtWd.displayMessage(wdProp) end
	ibArgs['data' .. tostring(globalInfoboxElementIndex)] = data
	globalInfoboxElementIndex = globalInfoboxElementIndex + 1
end

local function addLabelledData(ibArgs, label, data, wdProp, lblstyle)
	if data and wdProp then data = data .. ' ' .. editAtWd.displayMessage(wdProp) end
	ibArgs['label' .. tostring(globalInfoboxElementIndex)] = label
	ibArgs['lblstyle' .. tostring(globalInfoboxElementIndex)] = lblstyle
	addData(ibArgs, data)
end

local function getFirstValueClaimForProperty(prop)
	local allBestClaims = wikidata.findBestClaimsForProperty(nil, mw.ustring.upper(prop))
	if not allBestClaims then return nil end
	wdClaimId = 1
	while wdClaimId <= #allBestClaims and (allBestClaims[wdClaimId].type ~= 'statement' or allBestClaims[wdClaimId].mainsnak.snaktype ~= 'value') do
		wdClaimId = wdClaimId + 1
	end
	if wdClaimId <= #allBestClaims and allBestClaims[wdClaimId].type == 'statement' and allBestClaims[wdClaimId].mainsnak.snaktype == 'value' then
		return allBestClaims[wdClaimId]
	end
	return nil
end

local function deboldify(str)
	if not str then return nil end
	return mw.ustring.gsub(str, "'''", "")
end
--- compute the text to be displayed, based on a data model
p.fromArgs = function(naming, symbols, geography, demography, politics, history, economy, codes, notes)
	local ibArgs = { antet = 'harta', ['culoare cadru'] = '#ccd2d9', doc = 'Infocaseta Țară', wikidata = 'y' }
	if naming and TableTools.size(naming) > 0 then
		ibArgs.title = naming.name
		local otherNames = {}
		if naming.conventional then table.insert(otherNames, naming.conventional) end
		if naming.native then table.insert(otherNames, tostring(mw.html.create('span'):addClass('fn'):addClass('org'):addClass('country-name'):wikitext(naming.native))) end
		if #otherNames > 0 then
			ibArgs.subheader1 = table.concat(otherNames, _br_)
			ibArgs.subheaderstyle = 'background: linear-gradient( to right, rgba(204, 210, 217, 1), rgba(204, 210, 217, 1), rgba(204, 210, 217, 1), rgba(156, 163, 170, 1)) repeat-y right; font-size: 130%; line-height: 1.2em; padding-top: 0;'
			ibArgs.abovestyle = 'padding-bottom: 0; ' .. (ibArgs.abovestyle or '')
		end
	end

	if symbols then
		local symbolsComprssedArray = TableTools.compressSparseArray({symbols.flag, symbols.coA})
		if #symbolsComprssedArray > 0 then
			local symbolsTable = mw.html.create('table'):attr('align', 'center'):cssText('width:100%; background:none;')
			local symbolsImageRow = symbolsTable:tag('tr')
			local symbolsLinksRow = symbolsTable:tag('tr')
	
			for symIdx,eachSymbol in ipairs(symbolsComprssedArray) do
				local symbolImageTd = symbolsImageRow:tag('td')
				if symIdx == 1 and #symbolsComprssedArray > 1 then symbolImageTd:attr('width', '58%') end
				symbolImageTd:wikitext('[[Fișier:', eachSymbol.image, '|', eachSymbol.size, eachSymbol.border and '|border' or '', '|', eachSymbol.link, ']]')
	
				local symbolLinkTd = symbolsLinksRow:tag('td'):attr('align', 'center')
				symbolLinkTd:tag('small'):wikitext(eachSymbol.link)
			end
			addData(ibArgs, tostring(symbolsTable))
		end
		if symbols.motto then
			addData(ibArgs, prependToString({symbols.motto, "'''[[Deviză]]:&nbsp;'''"}))
		end

		local anthemData = {}
		for anthemKey,anthemValue in pairs(symbols.anthem) do
			if anthemValue.textLines and #(anthemValue.textLines) > 0 or anthemValue.file then
				local anthemLabel = anthemValue.label
				local anthemWdProp = anthemValue.wdProp
				local crtData = "'''" .. deboldify(anthemValue.label or 'Imn') .. "''':"
				
				crtData = table.concat(
					TableTools.compressSparseArray({
						crtData,
						table.concat(anthemValue.textLines, _br_)
					}),
					mw.text.decode('&nbsp;')
				)
				
				table.insert(
					anthemData,
					tostring(
						mw.html.create('div')
							:css('margin-bottom', '20')
							:wikitext(crtData)
						)
					)
				if anthemValue.file then
					table.insert(
						anthemData, 
						tostring(mw.html.create('div')
							:css('margin', 'auto')
							:wikitext('[[Fișier:', anthemValue.file, ']]')
							)
					)
				end
			end
		end
		if #anthemData > 0 then
			addData(ibArgs, tostring(
				mw.html.create('div')
					:css('margin', 'auto')
					:css('text-align', 'center')
					:wikitext(table.concat(anthemData, _br_))
			))
		end
	end

	if #(geography.maps) > 0 then
		for _,eachMap in ipairs(geography.maps) do
			local imgTable = mw.html.create('table')
			imgTable:tag('tr'):tag('td'):wikitext(displayImage{image = eachMap.image, sizedefault = eachMap.width, center = 'yes', title = eachMap.caption}):done():done()
				:tag('tr'):tag('td'):tag('div'):css('position', 'relative'):css('top', '0.3em'):tag('small'):wikitext(eachMap.caption)
			
			addData(ibArgs, tostring(imgTable))
		end
	end

	if #(geography.area) > 0 or geography.highest or geography.deepest or geography.largestCity or geography.timezones.regular then
		addHeader(ibArgs, 'Geografie')
		if #(geography.area) > 0 then
			addLabelledData(ibArgs, mw.text.trim('Suprafață '), '&nbsp;')
			for _,eachArea in ipairs(geography.area) do
				local areaValue = eachArea.value
				if type(areaValue) == 'number' then areaValue = formatNum(eachArea.value) end
				addLabelledData(ibArgs, 
					'&nbsp;-&nbsp;' .. eachArea.label,
					table.concat(TableTools.compressSparseArray({
						areaValue,
						'&nbsp;km²',
						eachArea.notes,
						encloseString({
							eachArea.ranking,
							'&#32;([[Lista țărilor după suprafață|locul&nbsp;',
							']])'
						}),
						eachArea.wdProp and editAtWd.displayMessage(eachArea.wdProp) or nil
					})),
					nil,
					'font-weight: normal;'
				)
				if eachArea.waterPercentage then
					addLabelledData(ibArgs, mw.text.trim('[[Apă]]&nbsp;([[Procentaj|%]])'), eachArea.waterPercentage)
				end
			end
		end
		addLabelledData(ibArgs, mw.text.trim('Cel mai înalt punct'), geography.highest)
		addLabelledData(ibArgs, mw.text.trim('Cel mai jos punct'), geography.deepest)
		addLabelledData(ibArgs, mw.text.trim('Cel mai mare oraș'), geography.largestCity)
		
		if geography.neighbors and 0 < #(geography.neighbors) then
			addLabelledData(ibArgs, 'Vecini', table.concat(geography.neighbors, _br_) .. ' ' .. editAtWd.displayMessage('P47'))
		end
		
		addLabelledData(ibArgs, '[[Fus orar]]', geography.timezones.regular and (geography.timezones.regular .. (geography.timezones.wdProp and (' ' .. editAtWd.displayMessage(geography.timezones.wdProp)) or '')))
		addLabelledData(ibArgs, '[[Oră de vară|Ora de vară]]', geography.timezones.summer)
	end
	if demography.census.population or #(demography.estimates) > 0 or demography.density.value then
		addHeader(ibArgs, 'Populație')
		if demography.census.population then
			addLabelledData(ibArgs, 'Populație', '&nbsp;')
			
			local democensusfull = table.concat(
				TableTools.compressSparseArray({
					type(demography.census.population) == 'number' and formatNum(demography.census.population) or demography.census.population,
					demography.census.ref,
					encloseString({demography.census.ranking, '&#32; ([[Lista țărilor după populație|locul&nbsp;', ']])'})
				})
			)
			addLabelledData(ibArgs, '&nbsp;-&nbsp;Recensământ&nbsp;' .. (demography.census.year or ''), democensusfull, demography.census.wdProp)
		end
		
		if demography.density.value then
			local demodensfull = type(demography.density.value) == 'number' and formatNum(demography.density.value) or demography.density.value .. '&nbsp;loc/km²'
			if demography.density.notes then
				demodensfull = demodensfull .. demography.density.notes
			end
			addLabelledData(ibArgs, 'Densitate', demodensfull)
		end
		for _,eachDemographyEst in ipairs(demography.estimates) do
			local eachDemoEstText = type(eachDemographyEst.population) == 'number' and formatNum(eachDemographyEst.population) or eachDemographyEst.population
			if eachDemographyEst.ranking then
				eachDemoEstText = eachDemoEstText .. ' ([[Lista țărilor după populație|locul&nbsp;' .. tostring(eachDemographyEst.ranking) .. ']])'
			end
			addLabelledData(ibArgs, '&nbsp;-&nbsp;Estimare&nbsp;' .. (eachDemographyEst.year or ''), eachDemoEstText)
		end
		if demography.languages.official then
			addLabelledData(ibArgs, 'Limbi oficiale', demography.languages.official, demography.languages.wdProp)
		end
		if demography.languages.other then
			addLabelledData(ibArgs, 'Limbi regionale/minoritare', demography.languages.other)
		end
		if 0 < #(demography.demonym.data) then
			addLabelledData(ibArgs, 'Etnonim', table.concat(demography.demonym.data, _br_) .. (demography.demonym.wdProp and (' ' .. editAtWd.displayMessage(demography.demonym.wdProp)) or ''))
		end
		if demography.ethnicGroups.list then
			addLabelledData(ibArgs, 'Grupuri etnice' .. (demography.ethnicGroups.date and (' (' .. demography.ethnicGroups.date .. ')') or ''), demography.ethnicGroups.list)
		end
	end

	if politics.system or #(politics.leaders) > 0 or politics.legislature.body or politics.capital then
		addHeader(ibArgs, 'Guvernare')
		
		addLabelledData(ibArgs, 'Sistem politic', politics.system, politics.systemWdProp)
		
		for _,eachLeader in ipairs(politics.leaders) do
			addLabelledData(ibArgs, eachLeader.title, eachLeader.name, eachLeader.wdProp)
		end
		
		if politics.legislature.body then
			addLabelledData(ibArgs, 'Legislativ', politics.legislature.body, politics.legislature.wdProp)
			for _,eachChamber in ipairs(politics.legislature.chambers) do
				addLabelledData(ibArgs, eachChamber.label, eachChamber.name)
			end
		end
		addLabelledData(ibArgs, 'Religie oficială', politics.stateReligion)
		addLabelledData(ibArgs, 'Capitala', politics.capital, politics.capitalWdProp)
	end
	
	if history.formation or #(history.events) > 0 then
		addHeader(ibArgs, 'Istorie' .. (history.wdProp and editAtWd.displayMessage(history.wdProp) or ''))
		if history.formation then
			addData(ibArgs, table.concat(TableTools.compressSparseArray({"'''" .. deboldify(history.formation) .. "'''", history.formationNote}), ' '), history.events.wdProp)
		end
		for _,eachEvt in ipairs(history.events) do
			addLabelledData(ibArgs, eachEvt.description, eachEvt.date)
		end
	end
	
	addHeader(ibArgs, 'Economie')
	if economy.gdp then
		addLabelledData(ibArgs, "'''[[Produs intern brut|PIB]]''' ([[Paritatea puterii de cumpărare|PPC]])", economy.gdp.ppcYear or mw.text.decode('&nbsp;'))
		addLabelledData(ibArgs, 
			"&nbsp;-&nbsp;Total",
			appendToString({
				economy.gdp.netto.ppc,
				encloseString({
					economy.gdp.netto.ppcRanking,
					'&#32;([[Lista țărilor în funcție de PIB (PPC)|locul&nbsp;',
					']])'
				})
			})
		)
		addLabelledData(ibArgs,
			"&nbsp;-&nbsp;Pe cap de locuitor",
			appendToString({
				economy.gdp.capita.ppc,
				encloseString({
					economy.gdp.capita.ppcRanking,
					'&#32;([[Lista țărilor în funcție de PIB (PPC)|locul&nbsp;',
					']])'
				})
			})
		)

		addLabelledData(ibArgs, "'''[[Produs intern brut|PIB]]''' (nominal)", economy.gdp.nominalYear or mw.text.decode('&nbsp;'))
		addLabelledData(ibArgs,
			"&nbsp;-&nbsp;Total",
			appendToString({
				economy.gdp.netto.nominal,
				encloseString({
					economy.gdp.netto.nominalRanking,
					'&#32;([[Lista țărilor în funcție de PIB (nominal)|locul&nbsp;',
					']])'
				})
			})
		)
		addLabelledData(ibArgs,
			"&nbsp;-&nbsp;Pe cap de locuitor",
			encloseString({
				economy.gdp.capita.nominal,
				table.concat(
					TableTools.compressSparseArray({
						encloseString({
							economy.gdp.capita.nominalRanking,
							'&#32;([[Lista țărilor în funcție de PIB (nominal)|locul&nbsp;',
							']])'
						}),
						'' ---here we should put the wd prop
					})
				)
			})
		)
	end
	if economy.gini then
		addLabelledData(ibArgs, 
			table.concat(TableTools.compressSparseArray({'[[Coeficientul lui Gini|Gini]]', encloseString({economy.gini.year, '(', ')'})}), ' '), 
			encloseString({
				table.concat(
					TableTools.compressSparseArray({
						economy.gini.value,
						encloseString({
							economy.gini.category,
							'&#32;(', ')'
							
						}),
						encloseString({
							economy.gini.ranking,
							'&#32;(locul&nbsp;', ')',
							economy.gini.ref
						})
					})
				),
				economy.gini.wdProp and editAtWd.displayMessage(economy.gini.wdProp) or ''
			})
		)
	end
	if economy.idu then
		addLabelledData(ibArgs, 
			table.concat(TableTools.compressSparseArray({'[[Indicele dezvoltării umane|IDU]]', encloseString({economy.idu.year, '(', ')'})}), ' '), 
			encloseString({
				table.concat(TableTools.compressSparseArray({economy.idu.value, encloseString({economy.idu.category, '&#32;(', ')'}), encloseString({economy.idu.ranking, '&#32;([[Lista țărilor după indicele dezvoltării umane|locul&nbsp;', ']])', economy.idu.ref})})),
				economy.idu.wdProp and editAtWd.displayMessage(economy.idu.wdProp) or ''
			})
		)
	end
	if economy.currency.data then
		addLabelledData(ibArgs,
			'[[Valută|Monedă]]',
			appendToString({
				appendToString({
					economy.currency.data,
					appendToString({
						encloseString({
							economy.currency.iso4217,
							'&#32;(<code>[[ISO 4217|',
							']]</code>)'
						}),
						economy.currency.footnote
					})
				}),
				economy.currency.wdProp and editAtWd.displayMessage(economy.currency.wdProp) or nil
			})
		)
	end
	
	addHeader(ibArgs, 'Coduri și identificatori')
	local codePrefixes = {['phonePrefix'] = 'Prefix telefonic', ['mobileCode'] = 'Cod mobil', ['internetTLD'] = '[[Domeniu național de nivel superior|Domeniu Internet]]', ['iso3166_2'] = '[[ISO 3166-2]]', ['iocCode'] = 'Cod [[Comitetul Olimpic Internațional|CIO]]'}
	for eachCodeIdx,eachCodeLabel in pairs(codePrefixes) do
		if codes[eachCodeIdx] and codes[eachCodeIdx].value then
			addLabelledData(
				ibArgs,
				eachCodeLabel,
				table.concat(TableTools.compressSparseArray({
					codes[eachCodeIdx].value,
					codes[eachCodeIdx].notes,
					codes[eachCodeIdx].wdProp and (' ' .. editAtWd.displayMessage(codes[eachCodeIdx].wdProp)) or ''
				}))
			)
		end
	end
	
	if notes then
		addData(ibArgs, tostring(mw.html.create('div'):css('font-size', 'smaller'):css('text-align', 'left'):wikitext(table.concat(notes, _br_))))
	end
	local onlineLinks = wikidata.findOnlineLinks()
	if #onlineLinks > 0 then
		addHeader(ibArgs, 'Prezență online')
		addData(ibArgs, table.concat(onlineLinks, _br_))
	end

	return infobox.infobox(ibArgs)
end

--- create the data model for the module based on the argument array
p.fromArray = function(args)
	
	local naming = {}
	local countryName = StringUtils._emptyToNil({args['name'] or args['nume'] or wikidata.findLabel()})
	if countryName then naming.name = countryName end
	if args['nume_convențional'] then naming.conventional = args['nume_convențional'] end
	if args['nume_nativ'] then naming.native = args['nume_nativ'] end
	if args['nume_genitiv'] then naming.genitive = args['nume_genitiv'] end
	if args['nume_legătură'] then naming.link = args['nume_legătură'] end
	if not naming.native then
		local officialLangsWdClaims = wikidata.findBestClaimsForProperty(nil, 'P37')
		local officialLangCodes = {ro = {code='ro'}}
		local nativeNames = {}
		
		--find out official languages
		if officialLangsWdClaims then
			for _,eachOfficialLangClaim in ipairs(officialLangsWdClaims) do
				if eachOfficialLangClaim.type == 'statement' and eachOfficialLangClaim.mainsnak.snaktype == 'value' then
					local langId = eachOfficialLangClaim.mainsnak.datavalue.value.id
					local langISOcode = wikidata.findOneValueNoRef('P218', langId) or wikidata.findOneValueNoRef('P219', langId) or wikidata.findOneValueNoRef('P305', langId)
					if langISOcode then
						local aLang = {code=langISOcode, id=langId}
						aLang.langLink = getLangLink(langId)
						officialLangCodes[langISOcode] = aLang
					end
				end
			end
		end

		local officialNameClaims = wikidata.findClaimsForProperty(nil, 'P1448')
		local nativeLabelClaims = wikidata.findClaimsForProperty(nil, 'P1705')
		local officialNamesTexts = {}
		local nameLanguages = {}
		
		-- map official names to languages
		if officialNameClaims or nativeLabelClaims then
			local nameClaims = {}
			if officialNameClaims then for _,v in ipairs(officialNameClaims) do table.insert(nameClaims, v) end end
			if nativeLabelClaims then for _,v in ipairs(nativeLabelClaims) do table.insert(nameClaims, v) end end
			for _,eachOfficialNameClaim in ipairs(nameClaims) do
				if eachOfficialNameClaim.type == 'statement'
					and eachOfficialNameClaim.mainsnak.snaktype == 'value'
					and (not eachOfficialNameClaim.qualifiers or not eachOfficialNameClaim.qualifiers['P582'])
					and (officialLangCodes[eachOfficialNameClaim.mainsnak.datavalue.value.language]
						or 'ro' == eachOfficialNameClaim.mainsnak.datavalue.value.language) then
					
					local thisNameLanguage = eachOfficialNameClaim.mainsnak.datavalue.value.language
					local thisNameText = eachOfficialNameClaim.mainsnak.datavalue.value.text
					officialNamesTexts[thisNameLanguage] = thisNameText
					if not nameLanguages[thisNameText] then nameLanguages[thisNameText] = {} end
					table.insert(nameLanguages[thisNameText], thisNameLanguage)
				end
			end
		end

		-- get common name for all official languages except ro
		for _,eachLangData in pairs(officialLangCodes) do
			local crtEntity = mw.wikibase.getEntity()
			if crtEntity then
				local mainName = mw.wikibase.getEntity():getLabelWithLang(eachLangData.code)
				if mainName and 'ro' ~= eachLangData.code then
					if not nameLanguages[mainName] or (#(nameLanguages[mainName]) == 1 and nameLanguages[mainName][1] == 'ro') then nameLanguages[mainName] = {} end
					table.insert(nameLanguages[mainName], eachLangData.code)
				end
			end
		end

		-- produce a list of all native names
		for eachNativeName,nativeLangs in pairs(nameLanguages) do
			local langsEnumeration = {separator = ', ', conjunction = ' și '}
			for _,eachLangForThisName in ipairs(TableTools.removeDuplicates(nativeLangs)) do
				table.insert(langsEnumeration, officialLangCodes[eachLangForThisName].langLink)
			end
			
			-- + any ro name that is not the same as the main name (native.name)
			if 1 == #nativeLangs and 'ro' == nativeLangs[1] then
				if eachNativeName ~= naming.name then
					table.insert(nativeNames, eachNativeName)
				end
			else
				table.insert(
					nativeNames,
					appendToString({
							lang(officialLangCodes[nativeLangs[1]].code, nil, eachNativeName, true),
							prependToString({
								encloseString({
									join(langsEnumeration),
									'(', ')'
								}),
								' '
							})
						})
					)
			end
		end
		naming.native = table.concat(nativeNames, _br_)
	end

	local symbols = {}
	local countryFlagImg = StringUtils._emptyToNil({args['imagine_drapel'] or wikidata.findOneValueNoRef('P41')})
	local countryCOAImg = StringUtils._emptyToNil({args['imagine_stemă'] or args['imagine_simbol'] or wikidata.findOneValueNoRef('P94')})
	local countryFlagClaim = getFirstValueClaimForProperty('P163')
	local countryCOAClaim = getFirstValueClaimForProperty('P237')
	if countryFlagImg then 
		if not symbols.flag then symbols.flag = {} end
		symbols.flag.image = countryFlagImg
		symbols.flag.size = '125px'
		symbols.flag.border = true
	end
	if countryFlagClaim then
		if not symbols.flag then symbols.flag = {} end
		symbols.flag.link = wikidata.findLinkToItemWithCallback(countryFlagClaim.mainsnak.datavalue.value.id, true, function(object) return 'Drapel' .. (naming.genitive and ('ul ' .. naming.genitive) or '') end)
	elseif symbols.flag then
		symbols.flag.link = 'Drapel' .. (naming.genitive and ('ul ' .. naming.genitive) or '')
	end
	if countryCOAImg then
		if not symbols.coA then symbols.coA = {} end
		symbols.coA.image = countryCOAImg
		symbols.coA.size = args['simbol_lat'] or '85px'
	end
	if countryCOAClaim then
		if not symbols.coA then symbols.coA = {} end
		symbols.coA.link = wikidata.findLinkToItemWithCallback(countryCOAClaim.mainsnak.datavalue.value.id, true, function(object) return 'Stem' .. (naming.genitive and ('a ' .. naming.genitive) or 'ă') end)
	elseif symbols.coA then
		symbols.coA.link = 'Stem' .. (naming.genitive and ('a ' .. naming.genitive) or 'ă')
	end
	
	local function extractAnthemFromArgs(arg, label)
		if not arg then return nil end
		local buildingAnthem = {}
		buildingAnthem.label = label
		buildingAnthem.textLines = {}
		
		local anthemLines = mw.text.split(arg, '<br%s/?>')
		local imageNamespaces = {'Imagine', 'Image', 'File', 'Fișier' }
		for _,eachAnthemLine in ipairs(anthemLines) do
			local isTextLine = true
			for _,eachImgNs in ipairs(imageNamespaces) do
				local imageRegex = encloseString({eachImgNs, '%[%[', ':(.*)%]%]'})
				local imageMatch = mw.ustring.match(eachAnthemLine, imageRegex)
				if imageMatch then
					buildingAnthem.file = imageMatch
					isTextLine = false
					break
				end
			end
			if isTextLine then
				table.insert(buildingAnthem.textLines, eachAnthemLine)
			end
		end
		return buildingAnthem
	end
	
	symbols.anthem = {}
	symbols.anthem.main = extractAnthemFromArgs(args['imn'], "'''[[Imn]]'''")
	symbols.anthem.royal = extractAnthemFromArgs(args['imn_regal'], "'''[[Imn regal|Imnul Regal]]'''")
	symbols.anthem.national = extractAnthemFromArgs(args['imn_național'], "'''[[Imn național|Imnul național]]'''")
	if not symbols.anthem.main and not symbols.anthem.royal and not symbols.anthem.national then
		local anthemClaim = getFirstValueClaimForProperty('P85')
		if anthemClaim then
			local anthemWdId = anthemClaim.mainsnak.datavalue.value.id
			local anthemSong = wikidata.findOneValueNoRef('P51', anthemWdId)
			symbols.anthem.main = {}
			symbols.anthem.main.wdProp = 'P85'
			symbols.anthem.main.label = "'''[[Imn]]'''"
			symbols.anthem.main.textLines = {}
			table.insert(symbols.anthem.main.textLines,
				tostring(mw.html.create('div'):css('font-style', 'italic'):wikitext(
					wikidata.findLinkToItemWithCallback(anthemWdId, true, function(object) 
						local lang
						if object.claims and object.claims['P364'] and object.claims['P364'][1] and object.claims['P364'][1].type == 'statement' and object.claims['P364'][1].mainsnak.snaktype == 'value' then
							local langEntityId = object.claims['P364'][1].mainsnak.datavalue.value.id
							lang = wikidata.findOneValueNoRef('P218') or wikidata.findOneValueNoRef('P424')
						end
						lang = lang or 'ro'
						local labelInLang = object.labels[lang] and object.labels[lang].value or wikidata.findLabel(object.id)
					end)
				))
			)
			symbols.anthem.main.file = anthemSong
		end
	end
	symbols.motto = emptyToNil({
		args['deviză_națională'] 
		or args['deviză']
		or args['motto']
		or appendToString({
			emptyToNil({
				wikidata.findOneValue('P1546') or wikidata.findOneValue('P1451')
			}),
			prependToString({editAtWd.displayMessage('P1546'), ' '})
		})
	})
	local geography = {}
	geography.maps = {}
	if args['imagine_hartă'] then
		local mainMap = {}
		mainMap.image = args['imagine_hartă']
		mainMap.caption = args['descriere_hartă']
		mainMap.width = args['lăţime_hartă'] or args['lățime_hartă'] or '290px'
		table.insert(geography.maps, mainMap)
	end
	for _,mapIdx in pairs(TableTools.affixNums(args, 'imagine_hartă')) do
		local otherMap = {}
		otherMap.image = args['imagine_hartă' .. tostring(mapIdx)]
		otherMap.caption = args['descriere_hartă' .. tostring(mapIdx)]
		otherMap.width = args['lăţime_hartă' .. tostring(mapIdx)] or args['lățime_hartă' .. tostring(mapIdx)] or '290px'
		table.insert(geography.maps, otherMap)
	end
	geography.area = {}
	if args['suprafață_km2'] or args['suprafață_km²'] or args['suprafață'] then
		local area = {}
		area.value = args['suprafață_km2'] or args['suprafață_km²'] or args['suprafață']
		if area.value and mw.ustring.match(area.value, '[0-9,]+%.?%d*') == area.value then area.value = mw.language.new('en'):parseFormattedNumber(area.value) end
		area.waterPercentage = args['procentaj_apa']
		area.label = args['suprafață_etichetă'] or 'totală'
		area.notes = args['suprafață_notă']
		area.ranking = args['suprafață_loc']
		table.insert(geography.area, area)
	end
	for _,areaIdx in pairs(TableTools.affixNums(args, 'suprafață_date')) do
		local area = {}
		area.label = args['suprafață_etichetă' .. areaIdx]
		area.value = args['suprafață_date' .. areaIdx]
		table.insert(geography.area, area)
	end
	if #(geography.maps) == 0 then
		local wdMapClaims = wikidata.findBestClaimsForProperty(nil, 'P242') or {} -- locator map image
		for _,eachWdMapClaim in ipairs(wdMapClaims) do
			if eachWdMapClaim.type == 'statement' and eachWdMapClaim.mainsnak.snaktype == 'value' and eachWdMapClaim.mainsnak.datavalue then
				local map = {}
				map.image = eachWdMapClaim.mainsnak.datavalue.value
				if eachWdMapClaim.qualifiers and eachWdMapClaim.qualifiers['P2096'] then
					for _,eachLegendQualifier in ipairs(eachWdMapClaim.qualifiers['P2096']) do
						if eachLegendQualifier.snaktype == 'value' and eachLegendQualifier.datavalue.value.language == 'ro' then
							map.caption = eachLegendQualifier.datavalue.value.text
						end
					end
				end
				map.width = '290px'
				table.insert(geography.maps, map)
			end
		end
	end
	if #(geography.area) == 0 then
		local areaClaim = getFirstValueClaimForProperty('P2046') --area
		if areaClaim then
			local area = {}
			area.value = tonumber(areaClaim.mainsnak.datavalue.value.amount)
			area.notes = wikidata.outputReferences(areaClaim)
			area.label = 'Total'
			area.waterPercentage = wikidata.findOneValue('P2927')
			area.wdProp = 'P2046'
			table.insert(geography.area, area)
		end
	end
	for peakProperty, peakSignificance in pairs({p610 = 'highest', p1589 = 'deepest'}) do
		local wdPeakClaim = getFirstValueClaimForProperty(peakProperty)
		local peakInfo = {}
		if wdPeakClaim then
			table.insert(peakInfo, wikidata.printSnak(wdPeakClaim.mainsnak))
			table.insert(peakInfo, wikidata.outputReferences(wdPeakClaim))
			local peakHeight = nil
			if wdPeakClaim.qualifiers and wdPeakClaim.qualifiers['P2044'] and wdPeakClaim.qualifiers['P2044'][1] and wdPeakClaim.qualifiers['P2044'][1].snaktype == 'value' then
				peakHeight = wikidata.printSnak(wdPeakClaim.qualifiers['P2044'][1])
			else
				peakHeight = wikidata.findOneValueNoRef('P2044', wdPeakClaim.mainsnak.datavalue.value.id)
			end
			table.insert(peakInfo, encloseString({peakHeight, '&#32;(', ')'}))
			table.insert(peakInfo, editAtWd.displayMessage(mw.ustring.upper(peakProperty)))
			geography[peakSignificance] = table.concat(peakInfo)
		end
	end
	geography.largestCity = args['cel_mai_mare_oraș'] or args['cea_mai_mare_așezare']
	
	geography.timezones = {}
	geography.timezones.regular = emptyToNil({appendToString({args['fus_orar'], encloseString({args['utc'], '&#32;([[UTC', ']])'})})})
	geography.timezones.summer = emptyToNil({appendToString({args['fus_orar_ODV'] or args['fus_vară'], encloseString({args['utc_ODV'], '&#32;([[UTC', ']])'})})})
	if not geography.timezones.regular then
		local tzClaims = wikidata.findBestClaimsForProperty(nil, 'P421')
		local summerAccumulator = {}
		local regularAccumulator = {}
		if tzClaims then for _,eachTzClaim in ipairs(tzClaims) do
			local utcOffsetText
			if eachTzClaim.type == 'statement' and eachTzClaim.mainsnak.snaktype == 'value' then
				local utcOffsetClaims = wikidata.findBestClaimsForProperty(eachTzClaim.mainsnak.datavalue.value.id, 'P2907')
				for __,eachOffsetClaim in ipairs(utcOffsetClaims) do
					if eachOffsetClaim.type == 'statement' and eachOffsetClaim.mainsnak.snaktype == 'value' then
						utcOffsetText = tostring(eachOffsetClaim.mainsnak.datavalue.value.amount)
						utcOffsetText = mw.ustring.gsub(utcOffsetText, '%.5', ':30')
						utcOffsetText = mw.ustring.gsub(utcOffsetText, '%.75', ':45')
					end
				end
			end
			local accumulator = regularAccumulator
			if eachTzClaim.qualifiers and eachTzClaim.qualifiers['P1264'] then
				for __,eachPeriodQualifier in ipairs(eachTzClaim.qualifiers['P1264']) do
					if eachPeriodQualifier.snaktype == 'value' and eachPeriodQualifier.datavalue.value.id == 'Q36669' then
						accumulator = summerAccumulator
					end
				end
			end
			
			table.insert(
				accumulator, 
				appendToString({
					appendToString({
						wikidata.printSnak(eachTzClaim.mainsnak),
						wikidata.outputReferences(eachTzClaim)
					}),
					encloseString({
						utcOffsetText,
						'&#32;([[UTC',
						']])'
					})
				})
			)
		end end
		if #regularAccumulator > 0 then
			geography.timezones.regular = emptyToNil({table.concat(regularAccumulator, _br_)})
			geography.timezones.summer = emptyToNil({table.concat(summerAccumulator, _br_)})
			geography.timezones.wdProp = 'P421'
		end
	end
	geography.neighbors = wikidata.findBestValues('P47')
	
	local demography = {}
	demography.census = {}
	demography.census.year = args['populație_recensământ_an']
	demography.census.population = args['populație'] or args['populație_recensământ']
	demography.census.ref = args['populație_note_subsol']
	demography.census.ranking = args['populație_recensământ_loc'] or args['loc_populație']
	demography.estimates = {}
	if args['populație_estimare'] then
		local demo = {}
		demo.year = args['populație_estimare_an']
		demo.population = args['populație_estimare']
		demo.ranking = args['populație_estimare_loc']
		table.insert(demography.estimates, demo)
	end
	for _,eachPopEstIdx in ipairs(TableTools.affixNums(args, 'populație_estimare')) do
		local demo = {}
		demo.year = args['populație_estimare_an' .. tostring(eachPopEstIdx)]
		demo.population = args['populație_estimare' .. tostring(eachPopEstIdx)]
		demo.ranking = args['populație_estimare_loc' .. tostring(eachPopEstIdx)]
		table.insert(demography.estimates, demo)
	end
	demography.density = {}
	demography.density.value = args['densitate_populație_km2'] or args['densitate_populație_km²'] or args['densitate']
	if demography.density.value then
		demography.density.notes = args['dens_pop_notă']
		demography.density.ranking = args['densitate_populație_loc']
	end
	if demography.census.population then
		local popNumberMatch = mw.ustring.match(demography.census.population, '[0-9,%.]+')
		if popNumberMatch then demography.census.population = formatNum(popNumberMatch) end
	else
		local wdPopulationClaim = getFirstValueClaimForProperty('P1082')
		if wdPopulationClaim then
			local demo = {}
			
			demo.population = tonumber(wdPopulationClaim.mainsnak.datavalue.value.amount)
			demo.ref = wikidata.outputReferences(wdPopulationClaim)
			demo.wdProp = 'P1082'
			if wdPopulationClaim.qualifiers and wdPopulationClaim.qualifiers['P585'] and wdPopulationClaim.qualifiers['P585'][1].snaktype == 'value' then
				local censusDate = wikidata.extractDateFromClaim(wdPopulationClaim.qualifiers['P585'][1])
				demo.year = censusDate and censusDate.year or nil
			end
			local determinationMethodId = nil
			if wdPopulationClaim.qualifiers and wdPopulationClaim.qualifiers['P459'] and wdPopulationClaim.qualifiers['P585'][1].snaktype == 'value' then
				determinationMethodId = wdPopulationClaim.qualifiers['P585'][1].datavalue.value['numeric-id']
			end
			if determinationMethodId == 39825 then
				demography.census = demo
			else
				table.insert(demography.estimates, demo)
			end
		end
	end
	demography.languages = {}
	demography.languages.official = args['limbi_oficiale'] or args['limbă_oficială']
	if not demography.languages.official then
		local officialLangsWdClaims = wikidata.findBestClaimsForProperty(nil, 'P37')
		local officialLangs = {}
		if officialLangsWdClaims then for _,eachOfficialLangClaim in ipairs(officialLangsWdClaims) do
			if eachOfficialLangClaim.type == 'statement' and eachOfficialLangClaim.mainsnak.snaktype == 'value' then
				local langLabel, langLabelLang = mw.wikibase.getLabelWithLang(eachOfficialLangClaim.mainsnak.datavalue.value.id)
				if langLabelLang == 'ro' and StringUtils._startsWithAny({langLabel, 'Limba ', 'limba '}) then
					langLabel = mw.ustring.sub(langLabel, mw.ustring.len('Limba ') + 1, mw.ustring.len(langLabel))
				end
			end
			table.insert(officialLangs, illWd(eachOfficialLangClaim.mainsnak.datavalue.value.id, langLabel))
			demography.languages.wdProp = 'P37'
		end end
		if #officialLangs > 0 then demography.languages.official = table.concat(officialLangs, _br_) end
	end
	demography.languages.other = args['limbi'] or args['limbi_regionale']
	demography.ethnicGroups = {}
	demography.ethnicGroups.list = args['grupări_etnice'] or args['grupuri_etnice'] or args['ethnic_groups']
	demography.ethnicGroups.date = args['grupuri_etnice_an'] or args['ethnic_groups_year']
	
	demography.demonym = {}
	demography.demonym.data = {}
	if args['etnonim'] then table.insert(demography.demonym.data, args['etnonim']) end
	if 0 == #(demography.demonym.data) then
		local demonymClaims = wikidata.findBestClaimsForProperty(nil, 'P1549')
		if demonymClaims then for _,eachDemonymClaim in ipairs(demonymClaims) do
			if eachDemonymClaim.type == 'statement' and eachDemonymClaim.mainsnak.snaktype == 'value' and eachDemonymClaim.mainsnak.datavalue.value.language == 'ro' then
				local crtDemonym = eachDemonymClaim.mainsnak.datavalue.value.text
				local extras = {}
				if eachDemonymClaim.qualifiers and eachDemonymClaim.qualifiers['P518'] then
					for _,eachQual in ipairs(eachDemonymClaim.qualifiers['P518']) do
						if eachQual and eachQual.snaktype == 'value' then
							if eachQual.datavalue.value.id == 'Q499327' then
								table.insert(extras, 'masc.')
							elseif eachQual.datavalue.value.id == 'Q1775415' then
								table.insert(extras, 'fem.')
							elseif eachQual.datavalue.value.id == 'Q146786' then
								table.insert(extras, 'pl.')
							elseif eachQual.datavalue.value.id == 'Q110786' then
								table.insert(extras, 'sing.')
							end
						end
					end
				end
				local extra
				if 0 < #extras then
					extra = tostring(mw.html.create('small'):wikitext(encloseString({table.concat(extras, ' '), '(', ')'})))
				end
				table.insert(demography.demonym.data, join({crtDemonym, extra, separator = ' '}))
			end
		end end
		if 0 < #(demography.demonym.data) then
			demography.demonym.wdProp = 'P1549'
		end
	end
	local politics = {}
	politics.system = args['sistem_politic']
	if not politics.system then
		politics.system, politics.systemWdProp = wikidata.findOneValue('P122'), 'P122'
	end
	politics.leaders = {}
	for _,leaderIdx in ipairs(TableTools.affixNums(args, 'titlu_conducător')) do
		local leader = {}
		leader.title = args['titlu_conducător' .. tostring(leaderIdx)]
		leader.name = args['nume_conducător' .. tostring(leaderIdx)]
		if leader.name then
			table.insert(politics.leaders, leader)
		end
	end
	if #(politics.leaders) < 1 then
		local headOfStatePosnWdId = nil
		local headOfState = {}
		headOfState.name = wikidata.findOneValue('P35')
		headOfState.wdProp = 'P35'
		if headOfState.name then
			local headOfStatePosnWd = getFirstValueClaimForProperty('P1906')
			if headOfStatePosnWd then
				headOfStatePosnWdId = headOfStatePosnWd.mainsnak.datavalue.value.id
				local headOfStatePosnLabel = mw.wikibase.getLabel(headOfStatePosnWdId)
				if naming.genitive and headOfStatePosnLabel then
					headOfStatePosnLabel = StringUtils._removeEnd({headOfStatePosnLabel, ' al ' .. naming.genitive})
					headOfStatePosnLabel = StringUtils._removeEnd({headOfStatePosnLabel, ' a ' .. naming.genitive})
				end
				headOfStatePosnLabel = StringUtils._capitalize({headOfStatePosnLabel})
				headOfState.title = illWd(headOfStatePosnWdId, headOfStatePosnLabel, nil, true)
			else
				headOfState.title = 'Șef de stat'
			end
		end
		if headOfStatePosnWdId then
			table.insert(politics.leaders, headOfState)
		end
		
		local headOfGovernment = {}
		local headOfGovernmentPosnWdId
		headOfGovernment.name = wikidata.findOneValue('P6')
		headOfGovernment.wdProp = 'P6'
		if headOfGovernment.name then
			local headOfGovernmentPosnWd = getFirstValueClaimForProperty('P1313')
			if headOfGovernmentPosnWd then
				headOfGovernmentPosnWdId = headOfGovernmentPosnWd.mainsnak.datavalue.value.id
				local headOfGovernmentPosnLabel = mw.wikibase.getLabel(headOfGovernmentPosnWdId)
				if naming.genitive and headOfGovernmentPosnLabel then
					headOfGovernmentPosnLabel = StringUtils._removeEnd({headOfGovernmentPosnLabel, ' al ' .. naming.genitive})
					headOfGovernmentPosnLabel = StringUtils._removeEnd({headOfGovernmentPosnLabel, ' a ' .. naming.genitive})
				end
				headOfGovernmentPosnLabel = StringUtils._capitalize({headOfGovernmentPosnLabel})
				headOfGovernment.title = illWd(headOfGovernmentPosnWdId, headOfGovernmentPosnLabel, nil, true)
			else
				headOfGovernment.title = 'Șef de guvern'
			end
		end
		if headOfGovernmentPosnWdId and headOfGovernmentPosnWdId ~= headOfStatePosnWdId then
			table.insert(politics.leaders, headOfGovernment)
		end
	end
	politics.legislature = {}
	politics.legislature.body = args['legislatură']
	politics.legislature.chambers = {}
	for _,chamberType in ipairs({'superioară', 'inferioară'}) do
		local chamber = {}
		chamber.name = args['camera_' .. chamberType]
		chamber.label = 'Camera ' .. chamberType
		if chamber.name then table.insert(politics.legislature.chambers, chamber) end
	end
	if not politics.legislature.body and #(politics.legislature.chambers) == 0 then
		local legislatureWdClaim = getFirstValueClaimForProperty('P194')
		if legislatureWdClaim then
			politics.legislature.body = illWd(legislatureWdClaim.mainsnak.datavalue.value.id)
			if legislatureWdClaim and legislatureWdClaim.qualifiers and legislatureWdClaim.qualifiers['P527'] then --has as part
				local chamberNames = {}
				for _,eachLegislaturePartSnak in ipairs(legislatureWdClaim.qualifiers['P527']) do
					if eachLegislaturePartSnak.snaktype == 'value' then
						table.insert(chamberNames, illWd(eachLegislaturePartSnak.datavalue.value.id))
					end
				end
				if #chamberNames > 0 then
					table.insert(politics.legislature.chambers, {label = 'Camere', name = table.concat(chamberNames, _br_)})
				end
			end
			politics.legislature.wdProp = 'P194'
		end
	end
	politics.capital = args['capitală']
	if not politics.capital then
		politics.capital = wikidata.findOneValue('P36')
		politics.capital = StringUtils._appendToString({politics.capital, 
			StringUtils._encloseString({
				join({
					StringUtils._emptyToNil({wikidata.loadOneValueInChain({'P36', '_P459'})}),
					StringUtils._emptyToNil({StringUtils._prependToString({ wikidata.loadOneValueInChain({'P36', '_P580'}), 'din '})}),
					StringUtils._emptyToNil({StringUtils._prependToString({ wikidata.loadOneValueInChain({'P36', '_P1310'}), 'contestată de '})}),
					['separator'] = '; '
				}), 
				' (', ')'
			})
		})
		politics.capitalWdProp = 'P36'
	end
	politics.stateReligion = args['religie'] or args['religion']
	
	local history = {}
	history.events = {}
	if args['tip_suveranitate'] then
		history.formation = args['tip_suveranitate']
		history.formationNote = args['notă_suveranitate']
	elseif args['fondare'] then
		history.formation = 'Formare'
		history.formationNote = args['fondare']
	end
	for _,sigEventIdx in ipairs(TableTools.affixNums(args, 'eveniment_fondare')) do
		local sigEvent = {}
		sigEvent.description = args['eveniment_fondare' .. tostring(sigEventIdx)]
		sigEvent.date = args['dată_fondare' .. tostring(sigEventIdx)]
		table.insert(history.events, sigEvent)
	end
	if args['aderareUEdată'] then
		local sigEvent = {}
		sigEvent.description = 'Aderare la [[Uniunea Europeană|UE]]'
		sigEvent.date = args['aderareUEdată']
		table.insert(history.events, sigEvent)
	end
	if #(history.events) == 0 then
		history.wdProp = 'P793'
		local sigEventWdClaims = wikidata.findBestClaimsForProperty(nil, history.wdProp)
		
		local function getAnyQualifier(claim, props)
			if not claim.qualifiers then return nil end
			for _,prop in ipairs(props) do
				if claim.qualifiers[prop] and claim.qualifiers[prop][1] and claim.qualifiers[prop][1].snaktype == 'value' then
					return claim.qualifiers[prop][1]
				end
			end
			return nil
		end
		if sigEventWdClaims then for _,eachSigEventWdClaim in ipairs(sigEventWdClaims) do
			if eachSigEventWdClaim.type == 'statement' and eachSigEventWdClaim.mainsnak.snaktype == 'value' and eachSigEventWdClaim.qualifiers 
					and getAnyQualifier(eachSigEventWdClaim, {'P585', 'P580'}) then
				local sigEvent = {}
				sigEvent.description = wikidata.printSnak(eachSigEventWdClaim.mainsnak)
				sigEvent.dateRaw = DateUtils.extractDateFromWikidataSnak(getAnyQualifier(eachSigEventWdClaim, {'P585', 'P580'}))
				sigEvent.date = GregorianDate.displayDualDateIfInInterval(sigEvent.dateRaw, true)
				table.insert(history.events, sigEvent)
			end
		end end	
		table.sort(history.events, function(e1, e2)
			if not e1 then return false end
			if not e2 then return true end
			if not e1.dateRaw then return false end
			if not e2.dateRaw then return true end
			return DateUtils.compare(e1.dateRaw, e2.dateRaw) < 0
		end)
		history.events.wdProp = 'P793'
	end
	
	local economy = {}
	economy.gdp = { netto = {}, capita = {} }
	economy.gdp.netto.nominal = args['PIB_nominal'] or appendToString({wikidata.findOneValue('P2131'), editAtWd.displayMessage('P2131')})
	economy.gdp.netto.ppc = args['PIB_PPC'] or appendToString({wikidata.findOneValue('P4010'), editAtWd.displayMessage('P4010')})
	economy.gdp.netto.ppcRanking = args['PIB_PPC_loc']
	economy.gdp.netto.nominalRanking = args['PIB_nominal_loc']
	economy.gdp.capita.nominal = args['PIB_nominal_pe_locuitor'] or appendToString({wikidata.findOneValue('P2132'), editAtWd.displayMessage('P2132')})
	economy.gdp.capita.ppc = args['PIB_PPC_pe_locuitor'] or args['PIB_per_capita'] or appendToString({wikidata.findOneValue('P2299'), editAtWd.displayMessage('P2299')})
	economy.gdp.capita.ppcRanking = args['PIB_PPC_pe_locuitor_loc']
	economy.gdp.capita.nominalRanking = args['PIB_nominal_pe_locuitor_loc']
	economy.gdp.nominalYear = args['PIB_an'] or args['PIB_nominal_an'] or wikidata.loadOneValueInChain({'P2131', '_P585'})
	economy.gdp.ppcYear = args['PIB_an'] or args['PIB_PPC_an'] or wikidata.loadOneValueInChain({'P2299', '_P585'})
	
	local function extractEconomicalIndexData(args, indexName, indexWdProp)
		local index = {}
	
		index.value = args[indexName]
		index.ranking = args[indexName .. '_loc']
		index.year = args[indexName .. '_an']
		index.category = args[indexName .. '_categorie']
		index.ref = args[indexName .. '_ref']
		if not index.value then
			local indexClaim = getFirstValueClaimForProperty(indexWdProp)
			if indexClaim then
				index.value = formatNum(indexClaim.mainsnak.datavalue.value.amount)
				if indexClaim.qualifiers and indexClaim.qualifiers['P585'] and indexClaim.qualifiers['P585'][1] and indexClaim.qualifiers['P585'].snaktype == 'value' then
					local indexDate = wikidata.extractDateFromClaim(indexClaim.qualifiers['P585'][1])
					if indexDate and indexDate.year then index.year = tostring(indexDate.year) end
				end
				index.ref = wikidata.outputReferences(indexClaim)
				index.wdProp = indexWdProp
			end
		end
		return index
	end
	
	economy.gini = extractEconomicalIndexData(args, 'Gini', 'P1125')
	economy.idu = extractEconomicalIndexData(args, 'IDU', 'P1081')
	
	economy.currency = {}
	economy.currency.data = args['monedă']
	economy.currency.iso4217 = args['monedă_iso']
	economy.currency.footnote = args['monedă_notă']
	if not economy.currency.data then
		local currencyClaim = getFirstValueClaimForProperty('P38')
		if currencyClaim then
			economy.currency.data = illWd(currencyClaim.mainsnak.datavalue.value.id)
			economy.currency.iso4217 = wikidata.findOneValue('P498', currencyClaim.mainsnak.datavalue.value.id)
			economy.currency.wdProp = 'P38'
		end
	end

	local codes = {}

	local function extractCode(arg, argNames, wdProperty, sep)
		sep = sep or _br_
		local code = {}
		for _,eachArg in ipairs(argNames) do
			if code.value then break end
			code.value = arg[eachArg]
			code.notes = arg['notă_' .. eachArg]
			if code.value then return code end
		end
		if not code.value then
			
			local wdClaims = wikidata.findBestClaimsForProperty(nil, mw.ustring.upper(wdProperty))
			local valueAccumulator = {}
			local noteAccumulator = {}
			if wdClaims then
				for __,eachWdClaim in ipairs(wdClaims) do
					if eachWdClaim.type == 'statement' and eachWdClaim.mainsnak.snaktype == 'value' then
						table.insert(valueAccumulator, wikidata.printSnak(eachWdClaim.mainsnak))
						table.insert(noteAccumulator, wikidata.outputReferences(eachWdClaim))
					end
				end
			end
			
			if #valueAccumulator > 0 then
				code.value = table.concat(valueAccumulator, sep)
				code.notes = table.concat(noteAccumulator)
				code.wdProp = wdProperty
				return code
			end
		end
		return nil
	end
	codes.phonePrefix = extractCode(args, {'prefix_telefonic'}, 'P474')
	codes.mobileCode = extractCode(args, {}, 'P2258')
	codes.internetTLD = extractCode(args, {'domeniu_internet', 'cctld'}, 'P78', ' ')
	codes.iso3166_2 = extractCode(args, {'iso3166-2'}, 'P297')
	codes.iocCode = extractCode(args, {}, 'P984')
	
	local notes = {}
	if args['note'] then table.insert(notes, args['note']) end
	for _,eachNoteIdx in ipairs(TableTools.affixNums(args, 'nota')) do
		table.insert(notes, args['nota' .. tostring(eachNoteIdx)])
	end
	
	return p.fromArgs(naming, symbols, geography, demography, politics, history, economy, codes, notes)
end

--- extract the args array from frame
p.fromFrame = function(frame)
	local args = getArgs(frame)
	return p.fromArray(args)
end

return p