এই মডিউলের জন্য মডিউল:Institution/নথি-এ নথিপত্র তৈরি করা হয়ে থাকতে পারে

--[[  
  __  __           _       _        ___           _   _ _         _   _             
 |  \/  | ___   __| |_   _| | ___ _|_ _|_ __  ___| |_(_) |_ _   _| |_(_) ___  _ __  
 | |\/| |/ _ \ / _` | | | | |/ _ (_)| || '_ \/ __| __| | __| | | | __| |/ _ \| '_ \ 
 | |  | | (_) | (_| | |_| | |  __/_ | || | | \__ \ |_| | |_| |_| | |_| | (_) | | | |
 |_|  |_|\___/ \__,_|\__,_|_|\___(_)___|_| |_|___/\__|_|\__|\__,_|\__|_|\___/|_| |_|
                                                                                    

This module is intended to be the engine behind "Template:Institution".

Please do not modify this code without applying the changes first at 
"Module:Institution/sandbox" and testing at "Module:Institution/testcases".

Authors and maintainers:
* User:Jarekt - original version 

]]
require('strict') -- used for debugging purposes as it detects cases of unintended global variables
local getLabel         = require("Module:Wikidata label")._getLabel            -- used for creation of name based on wikidata
local getDate          = require("Module:Wikidata date")._date                 -- used for processing of date properties
local authorityControl = require("Module:কর্তৃপক্ষ নিয়ন্ত্রণ (নতুন)")._authorityControl -- used for formatting of Authority control row
local City             = require("Module:City")._city                          -- used to add wikidata bases links to names of places
local Coordinates      = require("Module:Coordinates")
local labels           = {
	native_name = {
		ar = 'الاسم الأصلي',
		ast = 'Nome local',
		['be-tarask'] = 'Уласная назва',
		bn = 'স্থানীয় নাম',
		ca = 'Nom oficial',
		cs = 'Nativní název',
		da = 'Officielt navn',
		de = 'Eigenname',
		el = 'Τοπική ονομασία',
		en = 'Native name',
		es = 'Nombre local',
		et = 'Kohalik nimetus',
		eu = 'Bertako izena',
		fa = 'نام محلی',
		fi = 'Omakielinen nimi',
		fr = 'Nom local',
		gl = 'Nome oficial',
		he = 'שם בשפת המקור',
		hi = 'मुल नाम',
		hu = 'Helyi név',
		hy = 'Բնօրինակ անունը',
		id = 'Nama asli',
		it = 'Nome in lingua locale',
		ja = '原語名',
		ko = '원어 이름',
		mk = 'Изворен назив',
		ml = 'പ്രാദേശിക നാമം',
		ms = 'Nama asli',
		nds = 'Offiziellen Naam',
		nl = 'Lokale naam',
		nn = 'Namn på lokalt språk',
		pl = 'Oficjalna nazwa',
		pt = 'Nome nativo',
		ro = 'Denumire oficială',
		ru = 'Оригинальное название',
		scn = 'Nomu n lingua lucali',
		sl = 'Domače ime',
		sr = 'Изворно име',
		sv = 'Officiellt namn',
		th = 'ชื่อในภาษาต้นฉบับ',
		tr = 'Yerel adı',
		uk = 'Власна назва',
		vi = 'Tên bản ngữ',
		zh = '原名',
	},
	parent = {
		ar = 'المؤسسة الأم',
		['be-tarask'] = 'Мацярынская ўстанова',
		bn = 'মূল প্রতিষ্ঠান',
		ca = 'Institució matriu',
		cs = 'Nadřazená instituce',
		da = 'Moderinstitution',
		de = 'Muttergesellschaft',
		el = 'Μητρικός οργανισμός',
		en = 'Parent institution',
		es = 'Institución matriz',
		et = 'Emaasutus',
		fa = 'نهاد مادر',
		fi = 'Emojärjestö',
		fr = 'Institution mère',
		gl = 'Institución pai',
		he = 'מוסד אב',
		hi = 'जनक संस्था',
		hu = 'Üzemeltető',
		hy = 'Ծնողների հաստատություն',
		id = 'Institusi induk',
		it = 'Ente principale',
		ja = '上部機関',
		ko = '상위 기관',
		mk = 'Матична установа',
		ml = 'മാതൃസ്ഥാപനം',
		ms = 'Institusi induk',
		nds = 'Moderinstitutschoon',
		nl = 'Overkoepelende instantie',
		pl = 'Instytucja nadrzędna',
		pt = 'Instituição de origem',
		ro = 'Instituție-mamă',
		ru = 'Родительская организация',
		scn = 'Enti principali',
		sl = 'Matična ustanova',
		sr = 'Матична установа',
		sv = 'Moderinstitut',
		th = 'หน่วยงานแม่',
		tr = 'Ait olduğu kurum',
		vi = 'Thuộc về viện',
		['zh-hans'] = '父机构',
		['zh-hant'] = '父機構',
	},
	location = {
		ar = 'الموقع',
		ast = 'Allugamientu',
		['be-tarask'] = 'Месца',
		bn = 'অবস্থান',
		ca = 'Emplaçament',
		cs = 'Poloha',
		da = 'Sted',
		de = 'Ort',
		el = 'Τοποθεσία',
		en = 'Location',
		es = 'Ubicación',
		et = 'Asukoht',
		eu = 'Kokapena',
		fa = 'مکان',
		fi = 'Sijainti',
		fr = 'Emplacement',
		gl = 'Localización',
		he = 'מיקום',
		hi = 'स्थान',
		hu = 'Elhelyezkedés',
		hy = 'Տեղագրություն՝',
		id = 'Lokasi',
		it = 'Localizzazione',
		ja = '所在地',
		ko = '위치',
		mk = 'Место',
		ml = 'സ്ഥാനം',
		ms = 'Lokasi',
		nds = 'Oort',
		nl = 'Locatie(s)',
		nn = 'Stad',
		pl = 'Miejsce',
		pt = 'Localização',
		ro = 'Amplasament',
		ru = 'Местонахождение',
		scn = 'Lucalizzazzioni',
		sl = 'Kraj',
		sr = 'Седиште',
		sv = 'Plats',
		th = 'ที่ตั้ง',
		tr = 'Konum',
		uk = 'Місце',
		vi = 'Vị trí',
		zh = '地址'
	},
	established = {
		ar = 'تاريخ الإنشاء',
		['be-tarask'] = 'Заснаваны',
		bn = 'প্রতিষ্ঠিত',
		ca = 'Fundació',
		cs = 'Založeno',
		da = 'Grundlagt',
		de = 'Gegründet',
		el = 'Ιδρύθηκε',
		en = 'Established',
		es = 'Fundación',
		et = 'Asutatud',
		eu = 'Sorrera',
		fa = 'تأسیس',
		fi = 'Perustettu',
		fr = 'Fondation',
		gl = 'Fundación',
		he = 'נוסד',
		hi = 'स्थापित',
		hu = 'Alapítás',
		hy = 'հաստատված է՝',
		id = 'Didirikan',
		it = 'Istituito',
		ja = '設立',
		ko = '설립',
		mk = 'Основана',
		ml = 'നിലവിൽ വന്നത്',
		ms = 'Ditubuhkan',
		nds = 'Grünnt',
		nl = 'Opgericht',
		nn = 'Skipa',
		pl = 'Data powstania',
		pt = 'Estabelecido',
		ro = 'Înființare',
		ru = 'Дата основания',
		scn = 'Istituitu',
		sl = 'Ustanovitev',
		sr = 'Основана',
		sv = 'Inrättad',
		th = 'จัดตั้งขึ้นเมื่อ',
		tr = 'Kuruluşu',
		uk = 'Заснований',
		vi = 'Thành lập',
		zh = '成立',
	},
	coordinates = {
		ar = 'الإحداثيات',
		ast = 'Coordenaes',
		['be-tarask'] = 'Каардынаты',
		bn = 'স্থানাঙ্ক',
		ca = 'Coordenades',
		cs = 'Souřadnice',
		da = 'Koordinater',
		de = 'Koordinaten',
		el = 'Συντεταγμένες',
		en = 'Coordinates',
		es = 'Coordenadas',
		et = 'Koordinaadid',
		eu = 'Koordenatuak',
		fa = 'مختصات',
		fi = 'Koordinaatit',
		fr = 'Coordonnées',
		gl = 'Coordenadas',
		he = 'קואורדינטות',
		hi = 'निर्देशांक',
		hu = 'Koordináták',
		hy = 'Կորդինատները',
		id = 'Koordinat',
		it = 'Coordinate',
		ja = '経緯度',
		ko = '좌표',
		mk = 'Координати',
		ml = 'നിർദ്ദേശാങ്കങ്ങൾ',
		ms = 'Koordinat',
		nds = 'Laag',
		nl = 'Coördinaten',
		nn = 'Koordinatar',
		pl = 'Współrzędne',
		pt = 'Coordenadas',
		ro = 'Coordonate',
		ru = 'Координаты',
		scn = 'Coordinati',
		sl = 'Koordinate',
		sr = 'Координате',
		sv = 'Koordinater',
		th = 'พิกัด',
		tr = 'Koordinatları',
		uk = 'Координати',
		vi = 'Tọa độ',
		['zh-hans'] = '坐标',
		['zh-hant'] = '坐標',
	},
	inventory = {
		ar = 'قائمة الفهارس',
		ast = 'Inventariu',
		['be-tarask'] = 'Інвэнтар',
		bn = 'তালিকাভুক্ত জিনিসপত্র',
		ca = 'Inventari',
		cs = 'Inventář',
		da = 'Inventarliste',
		de = 'Bestandsverzeichnis',
		el = 'Συλλογή',
		en = 'Inventory',
		es = 'Inventario',
		et = 'Kogud',
		eu = 'Inbentarioa',
		fa = 'فهرست موجودی‌ها',
		fi = 'Inventorio',
		fr = 'Inventaire',
		gl = 'Inventario',
		he = 'Inventory',
		hi = 'वस्तु सूची',
		hu = 'Leltár',
		hy = 'Գույքացուցակ',
		id = 'Inventaris',
		it = 'Collezione',
		ja = '収蔵品目録',
		ko = '소장품 목록',
		mk = 'Попис',
		ml = 'വസ്തുക്കൾ',
		ms = 'Inventori',
		nds = 'Inventarlist',
		nl = 'Collectie',
		pl = 'Inwentarz',
		pt = 'Inventário',
		ro = 'inventar',
		ru = 'реестр',
		scn = 'Cullizzioni',
		sl = 'popis',
		sr = 'Инвентар',
		sv = 'Inventarielista',
		th = 'ภาพของพื้นที่',
		tr = 'Envanter',
		uk = 'Список праць',
		vi = 'Kiểm kê',
		['zh-hans'] = '藏品目录',
		['zh-hant'] = '藏品目錄',
	},
	linkback = {
		ar = 'وصلة إلى قالب صندوق معلومات المؤسسة',
		['be-tarask'] = 'Адваротная спасылка да карткі ўстановы',
		bn = 'প্রতিষ্ঠান তথ্যছক টেমপ্লেটে ফেরত যাওয়ার লিঙ্ক',
		ca = 'Enllaç a la plantilla d’informació de la institució',
		cs = 'Zpětný odkaz na šablonu infoboxu instituce',
		da = 'Link tilbage til institutionen faktaskabelon',
		de = 'Link zurück zur Museums Infobox-Vorlage',
		el = 'Σύνδεσμος προς το πλαίσιο πληροφοριών οργανισμού',
		en = 'Link back to Institution infobox template',
		et = 'Link selle malli leheküljele',
		fa = 'پیوند به الگوی جعبهٔ اطلاعات مؤسسه',
		fi = 'Linkki takaisin mallineeseen Institution infobox',
		fr = 'Lien vers le modèle de boîte d’information pour l’institution',
		gl = 'Ligazón de volta ao modelo',
		he = 'Link back to Institution infobox template',
		hi = 'संस्था के ज्ञानसन्दूक साँचा की वापस कड़ी',
		hy = 'Link back to Institution infobox template',
		id = 'Tautkan kembali ke templat kotak info institusional',
		it = 'Link a questo modello di museo',
		ja = 'Institution infoboxテンプレートへ戻る',
		ko = '기관 정보 틀로 돌아가는 링크',
		mk = 'Врска кон инфокутијата за установата',
		ml = 'സ്ഥാപന ഇൻഫോബോക്സ് ഫലകത്തിലേക്ക് തിരിച്ച് കണ്ണി ചേർക്കുക',
		ms = 'Pautkan kembali ke templat kotak info institusi',
		nl = 'link naar dit museum-sjabloon',
		pl = 'Link do szablonu instytucji',
		pt = 'Regressar à predefinição',
		ru = 'Ссылка на шаблон музея',
		scn = 'Link a stu mudellu di museu',
		sl = 'Povezava nazaj na predlogo',
		sr = 'Назад на шаблон институције',
		sv = 'Länk tillbaka till institutionsfaktamallen',
		th = 'ลิงก์กลับไปยังหน้ากล่องข้อมูลหน่วยงาน',
		tr = 'Kurum bilgi kutusu şablonuna geri dön',
		uk = 'Зворотне посилання до картки установи',
		vi = 'Liên kết quay lại bản mẫu thông tin Institution',
		['zh-hans'] = '查看机构信息模板',
		['zh-hant'] = '查看機構資訊模板',
	},
	missing_linkback = {
		ar = 'قالب <em>المؤسسة</em> هذا يعتمد على عنصر في ويكي بيانات، وهذا العنصر يفتقد خاصية [[d:Property:P1612|منشئ صفحة كومنز (P1612)]]. رجاءً اضغط على أيقونة [[File:Commons to Wikidata QuickStatements.svg|25 بكسل]] الموجودة في الأعلى لإضافته.',
		['be-tarask'] = 'Гэты шаблён <em>Установа</em> заснаваны на старонцы Вікізьвестак, якой бракуе ўласьцівасьці [[d:Property:P1612|старонка інстытуцыі ў Вікісховішчы (P1612)]]. Каб дадаць яе, націсьніце, калі ласка, [[File:Commons to Wikidata QuickStatements.svg|25px]] іконку ўверсе.',
		en = 'This <em>Institution</em> template is relying on Wikidata page, which is missing [[d:Property:P1612|Commons Institution page (P1612)]] property. Please click [[File:Commons to Wikidata QuickStatements.svg|25px]] icon above to add it.',
		fr = 'Ce modèle <em>Institution</em> dépend d’une page Wikidata, où il manque une propriété [[d:Property:P1612|Commons Institution page (P1612)]]. Veuillez cliquer l’icone [[File:Commons to Wikidata QuickStatements.svg|25px]] ci-dessus pour l’ajouter.',
		ja = 'この<em>Institution</em>テンプレートはウィキデータのページに依存していますが、当該ページは[[d:Property:P1612|コモンズの施設ページ(P1612)]]プロパティが欠けています。上の[[File:Commons to Wikidata QuickStatements.svg|25px]]アイコンをクリックして追加してください。',
		mk = 'Ова предлошка <em>Установа</em> зависи од страница на Википодатоците на која ѝ недостасува својството [[d:Property:P1612|страница за установа на Ризницата (P1612)]]. Стиснете на иконката [[File:Commons to Wikidata QuickStatements.svg|25px]] погоре за да го додадете.',
		pl = 'Ten szablon <em>Instytucja</em> opiera się na stronie Wikidata, której brakuje deklaracji [[d:Property:P1612|Commons Institution page (P1612)]]. Kliknij powyższą ikonę [[File:Commons to Wikidata QuickStatements.svg|25px]], aby dodać tą deklaracje. ',
		ru = 'Этот шаблон <em>Учреждения</em> полагается на страницу в Викиданных, в которой отсутствует [[d:Property:P1612|страница учреждения на Викискладе (P1612)]] из пространства имён «Собственность» (property). Нажмите, пожалуйста, на следующую иконку [[File:Commons to Wikidata QuickStatements.svg|25px]] выше, чтобы добавить страницу.',
		sl = 'Ta predloga <em>Institution</em> je odvisna od strani v Wikipodatkih, ki ji manjka lastnost [[d:Property:P1612|Commons Institution page (P1612)]]. Prosimo, kliknite zgornjo ikono [[File:Commons to Wikidata QuickStatements.svg|25px]] in jo dodajte.',
		th = 'แม่แบบ<em>หน่วยงาน</em>นี้ มีข้อมูลบนวิกิสนเทศที่ล้าหลังกว่าเล็กน้อย เนื่องจากขาดข้อมูล [[d:Property:P1612|Commons Institution page (P1612)]] กรุณากดที่ไอคอน [[File:Commons to Wikidata QuickStatements.svg|25px]] ด้านบนเพื่อเพิ่ม',
		['zh-hans'] = '此“<em>Institution</em>”模板依靠维基数据页面,其缺少[[d:Property:P1612|共享资源机构页面(P1612)]]属性。请勾选上方的[[File:Commons to Wikidata QuickStatements.svg|25px]]图标添加它。',
		['zh-hant'] = '此「<em>Institution</em>」模板依靠維基數據頁面,其缺少[[d:Property:P1612|共享資源機構頁面(P1612)]]屬性。請勾選上方的[[File:Commons to Wikidata QuickStatements.svg|25px]]圖標添加它。',
	},
	missing_homecat = {
		ar = 'قالب <em>المؤسسة</em> هذا يعتمد على عنصر في ويكي بيانات، وهذا العنصر يفتقد خاصية [[d:Property:P373|تصنيف كومنز (P373)]] التي تربطه مع تصنيف موجود في كومنز. الرجاء إنشاء هذا التصنيف و/أو الضغط على أيقونة [[File:Commons to Wikidata QuickStatements.svg|25 بكسل]] أعلاه، وإضافته إلى ويكي بيانات بالشكل المناسب.',
		['be-tarask'] = 'Гэты шаблён <em>Установа</em> заснаваны на старонцы Вікізьвестак, якой бракуе ўласьцівасьці [[d:Property:P1612|катэгорыя ў Вікісховішчы (P373)]] з спасылкай на існую катэгорыю Вікісховішча. Калі ласка, стварыце такую катэгорыю і/або націсьніце [[File:Commons to Wikidata QuickStatements.svg|25px]] іконку ўверсе, каб дадаць яе ў Вікізьвесткі.',
		en = 'This <em>Institution</em> template is relying on Wikidata page, which is missing [[d:Property:P373|Commons category (P373)]] property linking it to an existing category on Commons. Please create such category and/or click [[File:Commons to Wikidata QuickStatements.svg|25px]] icon above to add it to Wikidata.',
		fr = 'Ce modèle <em>Institution</em> dépend d’une page Wikidata, où il manque une propriété [[d:Property:P373|Commons category (P373)]] la liant à une catégorie existante sur Commons. Veuillez créer une telle catégorie ou cliquer l’icone [[File:Commons to Wikidata QuickStatements.svg|25px]] ci-dessus  pour l’ajouter sur Wikidata.',
		ja = 'この<em>Institution</em>テンプレートはウィキデータのページに依存していますが、当該ページをコモンズ上の既存のカテゴリにリンクさせる[[d:Property:P373|コモンズのカテゴリ(P373)]]プロパティが欠けています。カテゴリを作成するか、上の[[File:Commons to Wikidata QuickStatements.svg|25px]]アイコンをクリックしてウィキデータに追加してください。',
		mk = 'Оаа предлошка <em>Установа</em> зависи од страница на Википодатоците на која ѝ недостасува својството [[d:Property:P373|категорија на Ризницата (P373)]] кое би ја поврзало со овдешна постоечка категорија. Направете таква категорија и/или појдете на Википодатоците за да ја додадете.',
		ru = 'Этот шаблон <em>Учреждения</em> полагается на страницу в Викиданных, в которой отсутствует [[d:Property:P373|категория на Викискладе (P373)]] из пространства имён Собственность (property), связанная с существующей категорией на Викискладе. Создайте, пожалуйста, такую категорию и/или нажмите на следующую иконку [[File:Commons to Wikidata QuickStatements.svg|25px]] выше, чтобы добавить категорию.',
		sl = 'Ta predloga <em>Institution</em> je odvisna od strani v Wikipodatkih, ki ji manjka lastnost [[d:Property:P373|Commons category (P373)]] za povezavo z obstoječo kategorijo v Zbirki. Prosimo, ustvarite tako kategorijo in/ali kliknite zgornjo ikono [[File:Commons to Wikidata QuickStatements.svg|25px]] in jo dodajte v Wikipodatke.',
		th = 'แม่แบบ<em>หน่วยงาน</em>นี้มีข้อมูลขาดหายเล็กน้อย เนื่องจากขาดการลิงก์คุณลักษณะ [[d:Property:P373|หมวดหมู่คอมมอนส์ (P373)]] มายังหมวดหมู่ที่มีอยู่บนคอมมอนส์ กรุณาสร้างหมวดหมู่แล้วลิงก์ด้วยปุ่ม [[File:Commons to Wikidata QuickStatements.svg|25px]] เพื่อเพิ่มไปยังวิกิสนเทศ',
		['zh-hans'] = '此“<em>Institution</em>”模板依靠维基数据页面,其缺少链接至现有共享资源分类的[[d:Property:P373|共享资源分类(P373)]]属性。请创建这个分类(如果没有),并前往维基数据添加它。',
		['zh-hant'] = '此「<em>Institution</em>」模板依靠維基數據頁面,其缺少連結至現有共享資源分類的[[d:Property:P373|共享資源分類(P373)]]屬性。請創建這個分類(如果沒有),並前往維基數據添加它。',
	},
	website = 'Q35127',
	authority = 'Q36524',
}
local ISOdate          = require("Module:ISOdate")._ISOdate                    -- used for internationalization of dates
local LanguageCodes    = {
	Q197936   = "abe",           -- Abenaki
	Q5111     = "ab",            -- Abkhaz
	Q27683    = "ace",           -- Acehnese
	Q27776    = "ady",           -- Adyghe
	Q27811    = "aa",            -- Afar
	Q14196    = "af",            -- Afrikaans
	Q34737    = "agq",           -- Aghem
	Q28026    = "ak",            -- Akan
	Q8773     = "akl",           -- Aklan language
	Q1815020  = "akz",           -- Alabama
	Q8748     = "sq",            -- Albanian
	Q131339   = "als",           -- Alemannic German
	Q131339   = "gsw",           -- Alemannic German
	Q56499    = "arq",           -- Algerian Arabic
	Q7976     = "en-us",         -- American English
	Q28244    = "am",            -- Amharic
	Q35497    = "grc",           -- Ancient Greek
	Q28378    = "anp",           -- Angika
	Q13955    = "ar",            -- Arabic
	Q8765     = "an",            -- Aragonese
	Q28602    = "arc",           -- Aramaic
	Q8785     = "hy",            -- Armenian
	Q29316    = "rup",           -- Aromanian
	Q29316    = "roa-rup",       -- Aromanian
	Q29401    = "as",            -- Assamese
	Q29507    = "ast",           -- Asturian
	Q715766   = "tay",           -- Atayal
	Q56590    = "atj",           -- Atikamekw
	Q306626   = "de-at",         -- Austrian German
	Q29561    = "av",            -- Avar
	Q4627     = "ay",            -- Aymara
	Q9292     = "az",            -- Azerbaijani
	Q33205    = "bfq",           -- Badaga
	Q257829   = "bqi",           -- Bakhtiari
	Q33243    = "bm",            -- Bambara
	Q33151    = "bjn",           -- Banjar
	Q33219    = "jv-x-bms",      -- Banyumasan
	Q33219    = "map-bms",       -- Banyumasan
	Q13389    = "ba",            -- Bashkir language
	Q29540    = "bar",           -- Bavarian language
	Q33025    = "bej",           -- Beja
	Q9091     = "be",            -- Belarusian
	Q9610     = "bn",            -- Bengali
	Q33268    = "bh",            -- Bhojpuri
	Q33268    = "bho",           -- Bhojpuri
	Q37059    = "bpy",           -- Bishnupriya Manipuri
	Q35452    = "bi",            -- Bislama
	Q25167    = "nb",            -- Bokmål
	Q9303     = "bs",            -- Bosnian
	Q33202    = "brh",           -- Brahui
	Q750553   = "pt-br",         -- Brazilian Portuguese
	Q12107    = "br",            -- Breton
	Q7979     = "en-gb",         -- British English
	Q33190    = "bug",           -- Buginese
	Q7918     = "bg",            -- Bulgarian
	Q9228     = "my",            -- Burmese
	Q33120    = "bxr",           -- Buryat
	Q880301   = "frc",           -- Cajun French
	Q44676    = "en-ca",         -- Canadian English
	Q9186     = "yue",           -- Cantonese
	Q9186     = "zh-yue",        -- Cantonese
	Q2937525  = "cps",           -- Capiznon
	Q7026     = "ca",            -- Catalan
	Q33239    = "ceb",           -- Cebuano
	Q21117    = "esu",           -- Central Alaskan Yup'ik
	Q33284    = "bcl",           -- Central Bikol
	Q36811    = "ckb",           -- Central Kurdish
	Q33262    = "ch",            -- Chamorro
	Q33281    = "cbk-zam",       -- Chavacano
	Q33350    = "ce",            -- Chechen
	Q33388    = "chr",           -- Cherokee
	Q33273    = "ny",            -- Chewa
	Q33265    = "chy",           -- Cheyenne
	Q7850     = "zh",            -- Chinese
	Q32979    = "cho",           -- Choctaw
	Q33170    = "ckt",           -- Chukchi
	Q33251    = "chu",           -- Church Slavonic
	Q33348    = "cv",            -- Chuvash
	Q37041    = "lzh",           -- Classical Chinese
	Q37041    = "zh-classical",  -- Classical Chinese
	Q25289    = "kw",            -- Cornish
	Q33111    = "co",            -- Corsican
	Q33390    = "cr",            -- Cree
	Q33357    = "crh",           -- Crimean Tatar
	Q39132363 = "crh-cyrl",      -- Crimean Tatar in Cyrillic script
	Q38893333 = "crh-Latn",      -- Crimean Tatar in Latin script
	Q6654     = "hr",            -- Croatian
	Q9056     = "cs",            -- Czech
	Q9035     = "da",            -- Danish
	Q56466    = "din",           -- Dinka
	Q18415595 = "dty",           -- Doteli language
	Q7411     = "nl",            -- Dutch
	Q516137   = "nds-NL",        -- Dutch Low Saxon
	Q33081    = "dz",            -- Dzongkha
	Q689894   = "pa",            -- Punjabi Gurmukhi
	Q29919    = "arz",           -- Egyptian Arabic
	Q242648   = "eml",           -- Emilian-Romagnol
	Q1860     = "en",            -- English
	Q29952    = "myv",           -- Erzya
	Q9072     = "et",            -- Estonian
	Q30005    = "ee",            -- Ewe
	Q30007    = "ext",           -- Extremaduran
	Q25258    = "fo",            -- Faroese
	Q46728    = "hif",           -- Fiji Hindi
	Q33295    = "fj",            -- Fijian
	Q1412     = "fi",            -- Finnish
	Q33291    = "fon",           -- Fon
	Q15087    = "frp",           -- Franco-Provençal
	Q150      = "fr",            -- French
	Q33441    = "fur",           -- Friulian
	Q33454    = "ff",            -- Fula
	Q33287    = "gaa",           -- Ga
	Q33457    = "gag",           -- Gagauz
	Q9307     = "gl",            -- Galician
	Q33475    = "gan",           -- Gan
	Q8108     = "ka",            -- Georgian
	Q188      = "de",            -- German
	Q181037   = "aln",           -- Gheg Albanian
	Q33587    = "ki",            -- Gikuyu
	Q33657    = "glk",           -- Gilaki
	Q5575236  = "gom",           -- Goan Konkani
	Q2501174  = "gor",           -- Gorontalo
	Q35722    = "got",           -- Gothic
	Q9129     = "el",            -- Greek
	Q25355    = "kl",            -- Greenlandic
	Q35876    = "gn",            -- Guarani
	Q1363072  = "gcr",           -- Guianan Creole
	Q5137     = "gu",            -- Gujarati
	Q33491    = "ht",            -- Haitian Creole
	Q33375    = "hak",           -- Hakka
	Q56475    = "ha",            -- Hausa
	Q33569    = "haw",           -- Hawaiian
	Q9288     = "he",            -- Hebrew
	Q33315    = "hz",            -- Herero
	Q35978    = "hil",           -- Hiligaynon
	Q1776032  = "mrj",           -- Hill Mari language
	Q1568     = "hi",            -- Hindi
	Q33617    = "ho",            -- Hiri Motu
	Q9067     = "hu",            -- Hungarian
	Q294      = "is",            -- Icelandic
	Q35224    = "io",            -- Ido
	Q33578    = "ig",            -- Igbo
	Q35936    = "ilo",           -- Ilocano
	Q9240     = "id",            -- Indonesian
	Q33509    = "inh",           -- Ingush
	Q13351    = "moe",           -- Innu-aimun
	Q29921    = "iu",            -- Inuktitut
	Q27183    = "ik",            -- Inupiat
	Q9142     = "ga",            -- Irish
	Q652      = "it",            -- Italian
	item      = "code",          -- itemLabel
	Q35939    = "jam",           -- Jamaican Patois
	Q5287     = "ja",            -- Japanese
	Q33549    = "jv",            -- Javanese
	Q1340322  = "jut",           -- Jutlandic dialect
	Q33522    = "kbd",           -- Kabardian
	Q35475    = "kbp",           -- Kabiye
	Q35853    = "kab",           -- Kabyle
	Q33634    = "xal",           -- Kalmyk Oirat
	Q33673    = "kn",            -- Kannada
	Q36094    = "kr",            -- Kanuri
	Q36121    = "pam",           -- Kapampangan
	Q33714    = "krc",           -- Karachay-Balkar
	Q33541    = "kaa",           -- Karakalpak
	Q33552    = "ks",            -- Kashmiri
	Q33690    = "csb",           -- Kashubian
	Q9252     = "kk",            -- Kazakh
	Q33584    = "kha",           -- Khasi
	Q9205     = "km",            -- Khmer
	Q938216   = "khw",           -- Khowar
	Q33720    = "krj",           -- Kinaray-a language
	Q33573    = "rw",            -- Kinyarwanda
	Q33583    = "rn",            -- Kirundi
	Q36126    = "kv",            -- Komi
	Q56318    = "koi",           -- Komi-Permyak
	Q33702    = "kg",            -- Kongo
	Q9176     = "ko",            -- Korean
	Q34806    = "bss",           -- Kose language
	Q35744    = "kri",           -- Krio
	Q36368    = "ku",            -- Kurdish
	Q165795   = "fkv",           -- Kven
	Q1405077  = "kj",            -- Kwanyama
	Q9255     = "ky",            -- Kyrgyz
	Q36196    = "lad",           -- Ladino
	Q36206    = "lbe",           -- Lak
	Q56483    = "lki",           -- Laki
	Q22283016 = "mis",           -- language without language code
	Q9211     = "lo",            -- Lao
	Q36212    = "ltg",           -- Latgalian
	Q397      = "la",            -- Latin
	Q9078     = "lv",            -- Latvian
	Q31746    = "lez",           -- Lezgian
	Q36106    = "lij",           -- Ligurian
	Q102172   = "li",            -- Limburgish
	Q36217    = "ln",            -- Lingala
	Q9083     = "lt",            -- Lithuanian
	Q33698    = "liv",           -- Livonian
	Q36584    = "olo",           -- Livvi-Karelian
	Q33754    = "lmo",           -- Lombard
	Q25433    = "nds",           -- Low German
	Q13286    = "dsb",           -- Lower Sorbian
	Q33368    = "lg",            -- Luganda
	Q9051     = "lb",            -- Luxembourgish
	Q36451    = "mi",            -- Māori
	Q9296     = "mk",            -- Macedonian
	Q497345   = "vmf",           -- Main-Franconian
	Q36109    = "mai",           -- Maithili
	Q7930     = "mg",            -- Malagasy
	Q9237     = "ms",            -- Malay
	Q36236    = "ml",            -- Malayalam
	Q32656    = "dv",            -- Maldivian
	Q9166     = "mt",            -- Maltese
	Q12175    = "gv",            -- Manx
	Q33730    = "arn",           -- Mapudungun
	Q1571     = "mr",            -- Marathi
	Q36280    = "mh",            -- Marshallese
	Q33661    = "mfe",           -- Mauritian Creole
	Q13356    = "mzn",           -- Mazanderani
	Q13357    = "fit",           -- Meänkieli
	Q3906614  = "mhr",           -- Meadow Mari
	Q13358    = "ruq",           -- Megleno-Romanian
	Q13365    = "mwv",           -- Mentawai
	Q505674   = "gml",           -- Middle Low German
	Q36455    = "cdo",           -- Min Dong
	Q13324    = "min",           -- Minangkabau
	Q13359    = "xmf",           -- Mingrelian
	Q13330    = "mwl",           -- Mirandese
	Q36510    = "el",            -- Modern Greek
	Q13343    = "mdf",           -- Moksha
	Q36392    = "mo",            -- Moldovan
	Q9246     = "mn",            -- Mongolian
	Q56426    = "ary",           -- Moroccan Arabic
	Q523014   = "mus",           -- Muscogee
	Q615660   = "mui",           -- Musi
	Q13300    = "nah",           -- Nahuatl
	Q13307    = "na",            -- Nauruan
	Q13310    = "nv",            -- Navajo
	Q33900    = "ng",            -- Ndonga
	Q33845    = "nap",           -- Neapolitan
	Q36452    = "yrk",           -- Nenets
	Q33979    = "new",           -- Nepal Bhasa
	Q33823    = "ne",            -- Nepali
	Q34333    = "yrl",           -- Nheengatu
	Q33850    = "nrm",           -- Norman
	Q33850    = "fr-x-nrm",      -- Norman
	Q28224    = "frr",           -- North Frisian
	Q19933293 = "lrc",           -- Northern Luri
	Q33947    = "se",            -- Northern Sami
	Q33890    = "nso",           -- Northern Sotho
	Q9043     = "no",            -- Norwegian
	Q36738    = "nov",           -- Novial
	Q34235    = "ii",            -- Nuosu language
	Q25164    = "nn",            -- Nynorsk
	Q14185    = "oc",            -- Occitan
	Q33810    = "or",            -- Odia
	Q34233    = "ryu",           -- Okinawan
	Q35499    = "cu",            -- Old Church Slavonic
	Q42365    = "ang",           -- Old English
	Q35225    = "peo",           -- Old Persian
	Q35501    = "prg",           -- Old Prussian
	Q33864    = "om",            -- Oromo
	Q33968    = "os",            -- Ossetian
	Q36730    = "ota",           -- Ottoman Turkish
	Q36323    = "pko",           -- Pökoot
	Q23014    = "pfl",           -- Palatinate German
	Q36727    = "pi",            -- Pali
	Q33879    = "pag",           -- Pangasinan
	Q33856    = "pap",           -- Papiamento
	Q12473446 = "pmy",           -- Papua Malay language
	Q58680    = "ps",            -- Pashto
	Q10729616 = "aoc",           -- Pemon
	Q22711    = "pdc",           -- Pennsylvania German
	Q9168     = "fa",            -- Persian
	Q34024    = "pcd",           -- Picard
	Q15085    = "pms",           -- Piedmontese
	Q36699    = "pis",           -- Pijin
	Q20537530 = "pih",           -- Pitcairn-Norfolk
	Q36554    = "pih",           -- Pitkern
	Q1751432  = "pdt",           -- Plautdietsch
	Q809      = "pl",            -- Polish
	Q36748    = "pnt",           -- Pontic Greek
	Q5146     = "pt",            -- Portuguese
	Q37178    = "ine",           -- Proto-Indo-European
	Q58635    = "pa",            -- Punjabi
	Q5218     = "qu",            -- Quechua
	Q13198    = "rcf",           -- Réunion Creole
	Q32145    = "ksh",           -- Ripuarian language
	Q1641543  = "rgn",           -- Romagnol
	Q13201    = "rmy",           -- Romani
	Q7913     = "ro",            -- Romanian
	Q13199    = "rm",            -- Romansh
	Q7737     = "ru",            -- Russian
	Q26245    = "rue",           -- Rusyn
	Q3006285  = "acf",           -- Saint Lucian Creole French
	Q34299    = "sah",           -- Sakha
	Q718269   = "ais",           -- Sakizaya language
	Q34011    = "sm",            -- Samoan
	Q213434   = "sgs",           -- Samogitian
	Q213434   = "bat-smg",       -- Samogitian
	Q33954    = "sg",            -- Sango
	Q11059    = "sa",            -- Sanskrit
	Q33965    = "sat",           -- Santali
	Q33902    = "skr",           -- Saraiki
	Q33976    = "sc",            -- Sardinian
	Q27154    = "stq",           -- Saterland Frisian
	Q14549    = "sco",           -- Scots
	Q9314     = "gd",            -- Scottish Gaelic
	Q9299     = "sr",            -- Serbian
	Q9301     = "sh",            -- Serbo-Croatian
	Q34015    = "crs",           -- Seychellois Creole
	Q56482    = "shn",           -- Shan
	Q33274    = "shy",           -- Shawiya language
	Q34004    = "sn",            -- Shona
	Q33973    = "scn",           -- Sicilian
	Q33786    = "sid",           -- Sidamo
	Q30319    = "szl",           -- Silesian
	Q21480034 = "en-simple",     -- Simple English
	Q21480034 = "simple",        -- Simple English
	Q21480034 = "en-x-simple",   -- Simple English
	Q13414913 = "zh-hans",       -- Simplified Chinese
	Q33997    = "sd",            -- Sindhi
	Q13267    = "si",            -- Sinhala
	Q9058     = "sk",            -- Slovak
	Q9063     = "sl",            -- Slovene
	Q13275    = "so",            -- Somali
	Q34340    = "st",            -- Sotho
	Q3449805  = "azb",           -- South Azerbaijani
	Q12634001 = "bcc",           -- Southern Balochi
	Q12952748 = "luz",           -- Southern Luri
	Q36495    = "nan",           -- Southern Min
	Q36495    = "zh-min-nan",    -- Southern Min
	Q13293    = "sma",           -- Southern Sami
	Q56508    = "sou",           -- Southern Thai
	Q1321     = "es",            -- Spanish
	Q33989    = "srn",           -- Sranan tongo
	Q34002    = "su",            -- Sundanese
	Q7838     = "sw",            -- Swahili
	Q34014    = "ss",            -- Swazi
	Q9027     = "sv",            -- Swedish
	Q1366643  = "de-ch",         -- Swiss Standard German
	Q34057    = "tl",            -- Tagalog
	Q34128    = "ty",            -- Tahitian
	Q9260     = "tg",            -- Tajik
	Q1063911  = "tzl",           -- Talossan
	Q34318    = "tly",           -- Talysh
	Q5885     = "ta",            -- Tamil
	Q2087886  = "be-tarask",     -- Taraškievica
	Q2087886  = "be-x-old",      -- Taraškievica
	Q695526   = "it-x-tara",     -- Tarantino
	Q695526   = "roa-tara",      -- Tarantino
	Q25285    = "tt",            -- Tatar
	Q39132549 = "tt-cyrl",       -- Tatar in Cyrillic script
	Q39134544 = "tt-latn",       -- Tatar in Latin script
	Q34142    = "tsg",           -- Tausug
	Q8097     = "te",            -- Telugu
	Q34125    = "tet",           -- Tetum
	Q9217     = "th",            -- Thai
	Q34271    = "bo",            -- Tibetan
	Q34124    = "ti",            -- Tigrinya
	Q34159    = "tpi",           -- Tok Pisin
	Q34094    = "to",            -- Tongan
	Q18130932 = "zh-hant",       -- Traditional Chinese
	Q34327    = "ts",            -- Tsonga
	Q34137    = "tn",            -- Tswana
	Q34251    = "tcy",           -- Tulu
	Q34138    = "tum",           -- Tumbuka
	Q56240    = "aeb",           -- Tunisian Arabic
	Q56240    = "aeb-arab",      -- Tunisian Arabic
	Q256      = "tr",            -- Turkish
	Q9267     = "tk",            -- Turkmen
	Q34040    = "tru",           -- Turoyo
	Q34055    = "tvl",           -- Tuvaluan language
	Q34119    = "tyv",           -- Tuvan
	Q36850    = "tw",            -- Twi
	Q13238    = "udm",           -- Udmurt
	Q8798     = "uk",            -- Ukrainian
	Q22282914 = "und",           -- undetermined language
	Q13248    = "hsb",           -- Upper Sorbian
	Q1617     = "ur",            -- Urdu
	Q13263    = "ug",            -- Uyghur
	Q9264     = "uz",            -- Uzbek
	Q32762    = "vro",           -- Võro
	Q32762    = "fiu-vro",       -- Võro
	Q32704    = "ve",            -- Venda
	Q32724    = "vec",           -- Venetian
	Q32747    = "vep",           -- Veps
	Q9199     = "vi",            -- Vietnamese
	Q56485    = "wym",           -- Vilamovian
	Q32858    = "vot",           -- Votic
	Q37560    = "lat-vul",       -- Vulgar Latin
	Q34208    = "wbl",           -- Wakhi
	Q34219    = "wa",            -- Walloon
	Q34279    = "war",           -- Waray language
	Q9309     = "cy",            -- Welsh
	Q27175    = "fy",            -- West Frisian
	Q133800   = "pnb",           -- Punjabi Shahmukhi
	Q36943    = "wal",           -- Wolaytta
	Q34257    = "wo",            -- Wolof
	Q34290    = "wuu",           -- Wu Chinese
	Q13218    = "xh",            -- Xhosa
	Q34247    = "yai",           -- Yaghnobi
	Q12953315 = "yav",           -- Yangben
	Q8641     = "yi",            -- Yiddish
	Q34179    = "ydg",           -- Yidgha
	Q34311    = "yo",            -- Yoruba
	Q7033959  = "zh-yue",        -- Yue Chinese
	Q10199    = "diq",           -- Zazaki
	Q237409   = "zea",           -- Zeelandic
	Q13216    = "za",            -- Zhuang
	Q10179    = "zu",            -- Zulu
}
local core             = require("Module:core")

-- ==================================================
-- === Internal functions ===========================
-- ==================================================

local function info_box(text, lang, qCode)
	return string.format('<table class="messagebox plainlinks layouttemplate" dir="ltr" style="border-collapse:collapse; border-width:2px; border-style:solid; width:100%%; clear: both; '..
		'border-color:#f28500; background:#ffe; border-left-width: 8px; ">'..
		'<tr>'..
		'<td class="mbox-image" style="padding-left:.9em;">'..
		' [[File:Commons-emblem-issue.svg|class=noviewer|45px]]</td>'..
		'<td class="mbox-text" style="">%s</td>'..
		'</tr></table>', string.format(core.langSwitch(labels[text],lang), qCode))
end

-- ====================================================================
-- This function is responsible for producing HTML of a single row of the template
-- At this stage all the fields are already filed. There is either one or two fields
-- INPUTS:
-- * param - structures for 2 fields containing fields:
--    - field    - field name
--    - wrapper  - some fields need a <span class=...> wrapper around the field content 
-- * args - table with all the parameters
-- ====================================================================
local function Build_html_row(param, args)
	local field = args[param.field]
	if field=='' then field=nul; end
	if not (field or args.demo) then 
		return nil
	end
	local tag = labels[param.field]
	if type(tag)=='string' and string.match(tag, "^Q%d+$") then
		tag = getLabel(tag, args.lang, "-", "ucfirst")
	else
		tag = core.langSwitch(tag, args.lang)
	end
	local cell1 = string.format('<td style="%s">%s</td>\n', args.style2, tag)
	local cell2 = string.format('<td colspan="2" style="word-break:break-word;%s">'.. param.wrapper ..'</td>', args.style1, field or '')
	return string.format('<tr valign="top">\n%s%s</tr>\n', cell1, cell2)
end

-- ====================================================================
-- === This function is just responsible for producing HTML of the  ===
-- === template. At this stage all the fields are already filed     ===
-- ====================================================================
local function Build_html(args, cats)
	local field
	args.style1 = 'border:1px solid #aaa;'
	args.style2 = 'background-color:#e0e0ee; font-weight:bold; ' .. args.style1
	args.style3 = 'min-width:130px; ' .. args.style1
	
	-- get text direction
	local dir, text_align, odir
	if mw.language.new( args.lang ):isRTL() then
		dir, text_align, odir = 'rtl', 'right', 'left'
	else
		dir, text_align, odir = 'ltr', 'left', 'right'
	end 
	
	-- Top line with Creator name, lifespan and link icons -
	local top = {}
	table.insert(top, string.format('<span class="fn" id="creator"><bdi>%s\n</bdi></span>', args.name or 'missing name') )
	if args.linkback then 
	    table.insert(top, string.format('[[File:Blue pencil.svg|15px|link=Institution:%s]]', args.linkback) )
	end
	if args.wikidata then -- Wikidata Link
		table.insert(top, string.format('[[File:Wikidata-logo.svg|20px|wikidata:%s|link=wikidata:%s]]', args.wikidata, args.wikidata) )
	end
	if args.QS then -- quick_statement link to upload missing info to wikidata
		table.insert(top, string.format('%s', args.QS) )
	end
	if args.inventory then
		local formatStr = "<span style='float:%s; font-size:80%%; margin-%s:20px;'> ([[%s|%s]])</span>"
		table.insert(top, string.format(formatStr, odir, odir, args.inventory, core.langSwitch(labels.inventory, args.lang)  ))
	end
	
	local line = string.format('<th colspan="4" style="%s">%s</th>', args.style2, table.concat(top, '&nbsp;')) 
	local results = {}
	table.insert(results, string.format('<tr valign="top">\n%s\n</tr>\n', line))
	
	-- add other fields
	local param = {
		{field='native_name' 	, wrapper='%s'},
		{field='parent'         , wrapper='%s'},
		{field='location' 		, wrapper='<div class="locality">%s</div>'},
		{field='coordinates'	, wrapper='%s'},
		{field='established' 	, wrapper='%s'},
		{field='website'        , wrapper='%s'},
		{field='authority'		, wrapper='%s'},
	}
	for i=1,#param do
		table.insert(results, Build_html_row(param[i], args))
	end

	-- Image on the Left
	if not args.image and args.demo then
		args.image = 'MarksburgSilhouette.svg'
	end
	if args.image then --Wikiquote link
		field = string.format('[[File:%s|200x140px|alt=%s|class=photo]]', args.image, args.name or '') 
		local n = #results -- number of rows below 
		line  = string.format('<td rowspan="%i" style="width:120px" id="fileinfotpl_creator_image"><span class="wpImageAnnotatorControl wpImageAnnotatorOff">%s</span></td>', n, field) 
		table.insert(results, 2, string.format('<tr valign="top">\n%s\n</tr>\n', line)	)
	end
	results = table.concat(results)

	-- build table
	local collapsed = ''
	if args.collapse or args.namespace == 6 then
		collapsed = 'collapsed'
	end
	local style = string.format('class="toccolours collapsible %s" cellpadding="2" cellspacing="0" dir="%s" style="text-align:%s; border-collapse:collapse; background:#f0f0ff; border:1px solid #aaa;" lang="%s"',
		collapsed, dir, text_align, args.lang)
	results = string.format('<table %s>\n%s\n</table>\n', style, results)
	results = string.format('<div class="vcard">\n%s\n</div>\n', results)
	
	-- add references and documentation which are only visible in creator namespace
	if args.namespace==106 then
		local box =''
		if args.wikidata and string.match(cats,'missing linkback') then
			box = info_box('missing_linkback', args.lang, args.wikidata)
		elseif args.wikidata and string.match(cats,'without home category') then
			box = info_box('missing_homecat', args.lang, args.wikidata)
		end
		local doc = mw.getCurrentFrame():expandTemplate{ title ='documentation', args = { 'Template:Institution/documentation' } }
		results = results .. box .. doc -- add documentation to pages in creator namespace
	end
	return results
end

-- ===========================================================================
-- === Create coordinate link                                              ===
-- === INPUTS:                                                             ===
-- ===  * lat - latitude of the institution                                ===
-- ===  * lon - longitude of the institution                               ===
-- ===  * osm - "waypoint" ID gives better www.openstreetmap.org link      ===
-- ===  * geopoly - not woring at the moment                               ===
-- ===  * lang  - language id of the desired language                      ===
-- ===  * namespace - namespace number of the page calling the module      ===
-- ===========================================================================
local function coords(lat, lon, osm, geopoly, namespace, lang)
	if not lat or not lon then
		return nil
	end

	-- add OSM polygon, title etc.
	local str, prec
	if namespace == 6 then -- in files
		str = Coordinates._lat_lon(lat, lon, prec, lang)
	else
		local args = { lat=lat, lon=lon, lang=lang, prec="50", mode="institution"}
		str = Coordinates._GeoHack_link(args)
	end
	-- OSM link
	local osmlink = string.format('//www.openstreetmap.org/index.html?mlat=%s&mlon=%s&zoom=17', lat, lon)
	if osm then
		osmlink = string.format('//www.openstreetmap.org/?way=%s', osm)
	end
	osmlink = string.format('<span class="wpImageAnnotatorControl wpImageAnnotatorOff">[[File:Openstreetmap logo.svg|20px|Link to OpenStreetMap|link=%s]]</span>', osmlink)
	-- Google maps link
	local gmaplink = string.format('//maps.google.com/maps?hl=%s&q=%s,%s&tab=wl', lang, lat, lon)
	if geopoly then
		--gmaplink = string.format('//tools.wmflabs.org/dschwenbot/geo_poly/?t=unnamed&p=%s', mw.text.encode(geopoly)) -- not working at the moment
	end
	gmaplink = string.format('<span class="wpImageAnnotatorControl wpImageAnnotatorOff">[[File:Google Maps icon (2020).svg|20px|Link to Google Maps|link=%s]]</span>', gmaplink)
	return str .. ' ' .. osmlink .. ' ' .. gmaplink
end

-- ===========================================================================
-- === This function is responsible for adding maintenance categories      ===
-- === which are not related to wikidata                                   ===
-- === INPUTS:                                                             ===
-- ===  * args  - merged data from the local arguments and Wikidata        ===
-- ===========================================================================
local function add_maintenance_categories(args)
	local cats = '' -- categories 
	
	-- if home category than
	if args.namespace==14 and args.homecat and mw.title.new('Category:' .. args.homecat):localUrl() == mw.title.getCurrentTitle():localUrl() then
	
		cats = cats .. '\n[[Category:Institution template home categories]]'
		--cats = cats .. string.format('\n[[Category:namespace %i]]',args.namespace)
		-- check for wikidata q-code
		if not args.wikidata then
			cats = cats .. '\n[[Category:Institution template home categories without Wikidata link]]'
		end
	end
		
	-- ===============================================================
	-- === automatic categorization of pages in Institution: namespace === 
	-- ===============================================================
	if args.namespace~=106 then
		return cats
	end
	
	-- add [[Category:Institution templates]] category
	cats = cats .. string.format('\n[[Category:Institution templates]]')
	
	-- check for key information
	if not args.linkback and not args.wikidata then
		cats = cats .. '\n[[Category:Institution templates without linkback]]'
	end	
	if not args.name then
		cats = cats .. '\n[[Category:Institution templates without name]]'
	end	
	
	-- add homecat category
	if args.homecat then
		cats = cats .. string.format('\n[[Category:%s]]',args.homecat)
	end
	
	-- check for image
	if not args.image then
		cats = cats .. '\n[[Category:Institution templates without images]]'
	end
	-- check for wikidata q-code
	if not args.wikidata then
		cats = cats .. '\n[[Category:Institution templates without Wikidata link]]'
	end
	-- check for homecat
	if not args.homecat then
		cats = cats .. '\n[[Category:Institution templates without home category]]'
	else
		local hc = mw.title.new('Category:'..args.homecat)
		if not hc or not hc.exists then
			cats = cats .. '\n[[Category:Institution templates without home category]]'
		end 
	end

	return cats
end

-- ===========================================================================
-- === This function is responsible for adding maintenance categories      ===
-- === to pages in Institution namespace which are related to wikidata     ===
-- === INPUTS:                                                             ===
-- ===  * args0 - local inputs from the Institution template page          ===
-- ===  * args1 - merge of local and wikidata metadata                     ===
-- ===  * data  - data pulled from Wikidata                                ===
-- ===========================================================================
local function add_categories_to_institution_namespace(args0, args1, data)
	local cats = ''     -- categories 
	local qsTable = {}  -- table to store QuickStatements 
	local comp    = {}  -- outcome of argument vs. wikidata comparison
	-- two forms of QuickStatements command with and without quotes
	local qsCommand = {'%s|%s|%s', '%s|%s|"%s"'}

	-- compare Linkback to the actual page name. Many "Linkbacks" are created with 
	-- tool which produces &#38; and &#39;  instead of "&" and "'"
	if args0.linkback then
		local linkback = args0.linkback
		linkback = mw.ustring.gsub(linkback, '&#39;', "'")
		linkback = mw.ustring.gsub(linkback, '&#38;', "&")
		if linkback~=args0.pagename then
			cats = cats .. '\n[[Category:Institution templates with mismatching linkback]]'
		end
	end
	
	-- add [[Category:Institution templates with unknown parameter]] category, if some parameter not on the following list is used
	local fields = {'name', 'native_name', 'inventory', 'parent', 'location', 'latitude', 'longitude', 'osm', 'geopoly', 
									'image', 'homecat', 'established', 'website', 'authority', 'stub', 'demo',
									'namespace', 'linkback', 'wikidata', 'lang', 'pagename', 'option', 'collapse' }
	local set = {}
	for _, field in ipairs(fields) do set[field] = true end
	for field, _ in pairs( args0 ) do 
		if not set[field] then
			cats = string.format('%s\n[[Category:Institution templates with unknown parameter|%s]]', cats, field)
		end
	end
	
	-- skip the rest if no q-code
	if not args0.wikidata then
		return cats, args1
	end	
	
	-- add [[Category:Wikidata based Institution templates]] and [[Category:Institution templates with Wikidata link: local linkback]]
	local val = {wikidata=1, linkback=0, lang=0, namespace=0, pagename=0 }
	local hash = 0;
	for field, _ in pairs( args0 ) do 
		hash = hash + (val[field] or 10)
	end
	if hash==1 then
		cats = string.format('%s\n[[Category:Institution templates based only on Wikidata]]', cats)
	end
	
	-- mark parameters as "local" if they are present in Institution template
	local fields = {'name', 'native_name', 'parent', 'location', 'image', 'homecat', 'established', 'website', 'authority', 'linkback'}
	for _, field in ipairs( fields ) do
		if args0[field] then
			comp[field] = 'local'
		end
	end
	
	-- redundant if commons Institution template and wikidata have those fields and they are the same
	local fields = {'established', 'native name‎'}
	for _, field in ipairs( fields ) do
		if args0[field] and data[field] and args0[field]==data[field] then
			comp[field] = 'redundant'
		end
	end

	-- redundant name if wikidata has at least English label
	if args0.name and data.name_ and not string.match(data.name_, "^%[%[d:Q%d+%|.+%]%]")  then
		comp.name = 'redundant'
	end
	
	-- redundant if commons Institution template and wikidata have those fields, without checking values
	if args0.location and data.location then
		--comp.location = 'redundant'
	end
	
	-- ==================================================
	-- === coordinates  ================================= 
	-- ==================================================
	-- calculate distance
	local lat1, lat2, lon1, lon2 = args0.latitude, data.latitude, args0.longitude, data.longitude
	if lat1 and lat2 then
		comp.coordinates = 'local'
	end
	if lat1 and lat2 and lon1 and lon2 then
		local dLat = math.rad(lat1-lat2)
		local dLon = math.rad(lon1-lon2)
		local d = math.pow(math.sin(dLat/2),2) + math.pow(math.sin(dLon/2),2) * math.cos(math.rad(lat1)) * math.cos(math.rad(lat2))
		d = 2 * math.atan2(math.sqrt(d), math.sqrt(1-d))  -- angular distance in radians
		d = 6371000 * d       -- radians to meters conversion
		if d<100 then
			comp.coordinates = 'redundant'
		else
			comp.coordinates = 'mismatching'
		end
	elseif lat1 and not lat2 and lon1 and not lon2 then
		comp.coordinates = 'item missing'
		table.insert( qsTable, string.format(qsCommand[1], args0.wikidata, 'P625', string.format('@%09.5f/%09.5f', lat1, lon1)) )
	end

  -- ==================================================
	-- === website  ===================================== 
	-- ==================================================	
	args0.website_ = args0.website
	if args0.website then
		local str = string.match(args0.website, "%[([^ %]]+)[ %]]")
		if str then -- strip off [] brackets if detected
		  args0.website_ = str
		end
	end
	local a1 = args0.website_    -- creator template value  
	local d1 = data.website      -- wikidata q-code
	if a1 and d1 and a1==d1 then 
		comp.website = 'redundant'	
	elseif a1 and not d1 then
		comp.website = 'item missing'
		table.insert( qsTable, string.format(qsCommand[2], args0.wikidata, 'P856', a1) )
	end	
	
	-- ==================================================
	-- === odds and ends  =============================== 
	-- ==================================================	
	if args0.image then 
		args0.image_ = mw.uri.decode( args0.image, "WIKI" )
	end
	args0.linkback_ = args0.pagename;
	args0.homecat_  = args0.homecat;	
	
	local fields = {image='P18', linkback='P1612', homecat='P373'}
	for field, prop in pairs( fields ) do
		a1 = args0[field..'_'] -- creator template value  
		d1 = data[field]       -- wikidata q-code
		if a1 and d1 and a1~=d1 then 
			comp[field] = 'mismatching'
		elseif a1 and d1 and a1==d1 then 
			comp[field] = 'redundant'	
		elseif a1 and not d1 then
			comp[field] = 'item missing'
			table.insert( qsTable, string.format(qsCommand[2], args0.wikidata, prop, a1) )
		end	
	end
	if comp.linkback == 'redundant' and (hash~=1 or not args0.linkback) then
		comp.linkback = nil
	end

	-- ==================================================
	-- === Create categories and QuickStatement codes === 
	-- ==================================================
	-- create categories based on comp structure
	for field, outcome in pairs( comp ) do
		cats = string.format('%s\n[[Category:Institution templates with Wikidata link: %s %s]]', cats, outcome, field)
	end
	
	-- convert QS table to a string
	local QS   = ''     -- quick_statements final string
	if #qsTable>0 then
		local today = '+' .. os.date('!%F') .. 'T00:00:00Z/11' -- today's date in QS format
	    local url   = mw.title.getCurrentTitle():canonicalUrl()
	    local source = '|S143|Q24731821|S813|' .. today .. '|S4656|"' .. url .. '"'
		local qsWrapper = '&nbsp;[[File:Commons_to_Wikidata_QuickStatements.svg|15px|link=%s]]'
		QS = table.concat( qsTable, source..'||') .. source    -- combine multiple statements into a single command separated by ||
		QS = mw.ustring.gsub(QS, ' ', "%%20")
		QS = mw.ustring.gsub (mw.uri.encode(QS),'%%2520','%%20')
		QS = 'https://quickstatements.toolforge.org/#/v1=' .. QS    -- create full URL link
		QS = string.format(qsWrapper, QS)
		cats = cats .. '\n[[Category:Institution templates with Wikidata link: quick statements]]'
	end
	args1.QS = QS;
	return cats, args1
end

-- ===========================================================================
-- === Harvest wikidata properties matching creator template fields        ===
-- === INPUTS:                                                             ===
-- ===  * qCode - item id or a q-code                                      ===
-- ===  * lang  - language id of the desired language                      ===
-- ===  * namespace - namespace number of the page calling the module      ===
-- ===========================================================================
local function harvest_wikidata(qCode, lang, namespace)
-- INPUTS:
-- * qCode - item id or a q-code
-- * lang  - language id of the desired language
-- * namespace - namespace number of the page calling the module
	local str, d, v
	local data = {} -- structure similar to "args" but filled with wikidata data
	local cats = ''
	local entity = nil
	if mw.wikibase and qCode then
		entity = mw.wikibase.getEntity(qCode)
		if not entity then
			 cats = '[[Category:Institution templates with bad Wikidata link|invalid]]' 
		elseif entity.id~=qCode then
			 cats = '[[Category:Institution templates with redirected Wikidata link]]'
		end
	end
	if not entity then
		return data, cats
	end

	-- ===========================================================================
	-- === Step 1: time properties
	-- ===========================================================================	
	-- harvest time properties: translated date and year number
	local prop = 'P1619'
	local d = getDate(entity, prop , lang)  -- date of official opening
	if not d.str or d.str=='' then
		prop = 'P571'
		d = getDate(entity, prop, lang) -- inception date
	end
	if d.str then
		data.established_ = d.iso
		data.established  = d.str .. core.editAtWikidata(entity.id, prop, lang)
	end
	
	-- ===========================================================================
	-- === Step 1a: website
	-- ===========================================================================	
	-- look for multiple values each with a language code
	local website = {}
	local url
	for _, statement in pairs( entity:getBestStatements( 'P856' )) do
		if (statement.mainsnak.snaktype == "value") then 
			url = statement.mainsnak.datavalue.value
			local lng = nil
			if statement.qualifiers and statement.qualifiers.P407 then
				lng = statement.qualifiers.P407[1].datavalue.value.id
				lng = LanguageCodes[lng]
		  end
			website[lng or 'en'] = url
		end
	end
	data.website = core.langSwitch(website, lang)
	if data.website and url then
		local label   = mw.ustring.gsub(url , '^https?\:\/\/', "")   -- remove "http://" or "https://" at the beginning
		label         = mw.ustring.gsub(label , '\/$', "")         -- "/" at the end
		data.website  = string.format("[%s %s]", data.website, label) 
	end
	if data.website then
		data.website = data.website .. core.editAtWikidata(entity.id, 'P856', lang)
	end

		
	-- ===========================================================================
	-- === Step 2: simple string and Q-code properties
	-- ===========================================================================	
	-- harvest string and Q-code properties
	local property = {P18='image', P154='logo_image', P373='homecat', P1612='linkback', P1448='official_name', 
					P1705='native_name', P131='city', P276='location', P159='HQ_location', P749='parent', P361='partOf', P17='country'}
	local addIcon = {P1448=1, P1705=1, P131=1, P276=1, P159=1, P749=1, P361=1}
	for prop, field in pairs( property ) do
		if entity.claims and entity.claims[prop] then -- if we have wikidata item and item has the property
			-- capture single "best" Wikidata value
			for _, statement in pairs( entity:getBestStatements( prop )) do
				if (statement.mainsnak.snaktype == "value") then 
					local v = statement.mainsnak.datavalue.value
					if v.id then 
						v = core.getLabel(v.id, lang)
					elseif v.text then
						v = v.text
					end
					if addIcon[prop] then
						v = v .. core.editAtWikidata(entity.id, prop, lang)
					end
					data[field] = v 
				end
			end
		end
	end
	data.native_name = data.official_name or data.native_name
	data.image       = data.logo_image or data.image
	data.location    = data.city or data.HQ_location or data.location
	data.parent      = data.parent or data.partOf
	if data.location and data.country then
		data.location = mw.text.listToText( {data.location, data.country}, ', ', ', ')
	end
	
	-- ===========================================================================
	-- === Step 3: geographic coordinates
	-- ===========================================================================	
	local P625 = entity:getBestStatements( 'P625' ) --  coordinate location
	v = nil
	if P625[1] and P625[1].mainsnak.datavalue.value.latitude then 
		v = P625[1].mainsnak.datavalue.value
	end
	if not v then -- check for location of  headquarters location (P159) 
		local P159 = entity:getBestStatements( 'P159' ) 
		if P159[1] and P159[1].qualifiers and P159[1].qualifiers.P625 then
			v = P159[1].qualifiers.P625[1].datavalue.value
		end
	end
	if v and v.globe == 'http://www.wikidata.org/entity/Q2' then
		data.latitude, data.longitude = v.latitude, v.longitude
	end

	-- =================================================================================
	-- === Step 4: name and authority control
	-- =================================================================================	
	-- get name field
	data.name  = getLabel(entity, lang) -- create name based on wikidata label
	data.name_ = getLabel(entity, 'en') -- try english label label

	-- get authority control template		
	local AC_cats
	data.authority, AC_cats = authorityControl(entity, {wikidata = qCode}, lang, 5) 
	if not (namespace == 2 or namespace == 6 or namespace == 828 or math.fmod(namespace,2)==1) then
		cats = cats .. AC_cats -- lets not add authorityControl categories to user pages, files, modules or talk pages and concentrate on templates and categories instead
	end
	
	return data, cats
end

-- ==================================================
-- === External functions ===========================
-- ==================================================
local p = {}

-- ===========================================================================
-- === Version of the function to be called from other LUA codes
-- ===========================================================================
function p._institution(args0)
	local lang = args0.lang  -- user's language
	local cats = ''         -- categories 
	local str, data
	
	-- look up title info
	args0.namespace  = mw.title.getCurrentTitle().namespace   -- get page namespace
	args0.pagename   = mw.title.getCurrentTitle().text        -- get {{PAGENAME}}

	-- ===========================================================================
	-- === Step 1: clean up of template arguments "args0"
	-- ===========================================================================
	if args0.linkback then
		args0.linkback = string.sub(args0.linkback,13)
	end
	if args0.established then
		args0.established = ISOdate(args0.established, lang)
	end
	if not tonumber(args0.latitude) or not tonumber(args0.longitude) then
		args0.longitude = nil
		args0.latitude  = nil
	end
	
	-- ===========================================================================
	-- === Step 2: one by one merge wikidata and creator data
	-- ===========================================================================
	data, cats = harvest_wikidata(args0.wikidata, lang, args0.namespace)
	
	-- mass merge (prioritize local values)
	local args = {}
	local fields = {'native_name', 'inventory', 'parent', 'location', 'latitude', 'longitude', 'demo', 'image', 'homecat', 
					'established', 'website', 'authority', 'linkback', 'wikidata', 'lang', 'namespace', 'collapse' }
	for _, field in ipairs( fields ) do 
		args[field] = args0[field] or data[field]
	end
	args.name = data.name
	if not args.name or string.match(args.name or '', "^%[%[d:Q%d+%|Q.+%]%]") then 
		args.name = args0.name -- no name on Wikidata
	end
	--args.name = data.name or args0.name

	args.location = City(args.location, lang) 
	args.coordinates = coords(args.latitude, args.longitude, args0.osm, args0.geopoly, args0.namespace, lang)
	if not args0.latitude and data.latitude then
		args.coordinates = args.coordinates .. core.editAtWikidata(args0.wikidata, 'P625', args.lang)
	end

	-- convert all empty strings to nils
	for _, field in ipairs( fields ) do 
		if args[field] == '' then 
			args[field] = nil; 
		end
	end
	
	-- ===========================================================================
	-- === Step 3: create maintenance categories and render html of the table
	-- ===========================================================================
	cats = cats .. add_maintenance_categories(args)
	-- If institution namespace than add maintenance categories
	args.QS = nil;
	if args.namespace==106  then
		str, args = add_categories_to_institution_namespace(args0, args, data)
		cats = cats .. str
	end
	local results = Build_html(args, cats)
	return results, cats
end

-- ===========================================================================
-- === Version of the function to be called from template namespace
-- ===========================================================================
function p.institution(frame)
	-- switch to lowercase parameters to make them case independent
	local args = core.getArgs(frame)

	if args.option == 'collapse' then
		args.collapse = 1 -- some "options" are to modify the name and some are commands to do things
		args.option  = nil
	end
	local QS = ''
	if args.wikidata and string.match(args.wikidata or '', "^Q%d+$") then -- invisible language independent marking
		QS = string.format('<div style="display: none;">institution QS:P195,%s</div>\n', args.wikidata)
	end
	
	-- call the inner "core" function
	local results, cats = p._institution(args)	
	return results .. QS .. cats
end

return p