local p = {}

-- Converts "Flag of" in a variable in order to accept images that don't follow this name schema
 flagOf = "Flag_of_"

-- Loading the flag translations module --
local translations = mw.loadData("Module:Flags/LocaleData")
local master = mw.loadData("Module:Flags/MasterData")

-- Assigning the parameter to a flag and a link
function p.flag(territory)
 
-- Searching in the master table only.
-- 2 letter code search
    if #territory.args[1] == 2 then
        for flagParameter,commonsFile in pairs(master.twoLetter) do 
            if flagParameter == territory.args[1]  then 
                commonsName = commonsFile 
                tempLink = commonsFile
            end
        end
        for flagParameter,commonsFile in pairs(translations.fullName) do
            if commonsFile == tempLink then
                link = flagParameter
            end
        end
        if link == nil then link = commonsName
        end
    end

-- 3 letter code search
    if #territory.args[1] == 3 then
        for flagParameter,commonsFile in pairs(master.threeLetter) do 
            if flagParameter == territory.args[1]  then 
                commonsName = commonsFile 
                 tempLink = commonsFile
            end
        end
        for flagParameter,commonsFile in pairs(translations.fullName) do
            if commonsFile == tempLink then
                link = flagParameter
            end
        end 
        if link == nil then link = commonsName
        end
    end

-- Searching in FlagTranslations, then in FlagMaster
-- Full name search
    if commonsName == nil then
        flagTables = { translations.fullName, master.fullName, }
        for k,v in ipairs(flagTables) do
            for flagParameter,commonsFile in pairs(v) do 
                if flagParameter == territory.args[1]  then 
                    commonsName = commonsFile 
                    link = flagParameter
                elseif commonsFile == territory.args[1]  then 
                    commonsName = commonsFile 
                    link = flagParameter
                end
            end
        end
    end 

-- Fallback to Commons when the parameter doesn't have an entry in the table.    
    if commonsName == nil then 
        commonsName = territory.args[1] 
        link = territory.args[1] 
    end

-- Variant check for historical flags --
    if territory.args[3] ~= "" then 
        variant = territory.args[3]
        commonsName = master.variant[commonsName .. "|" .. variant] 
        flagOf=""
    end

-- Label check --
    if territory.args[2] ~= "{{{2}}}" then
        variant = territory.args[2]
        commonsName = master.variant[commonsName .. "|" .. variant]
        flagOf = ""
    end  

-- Digesting Commons flag files not following the format "Flag of "
-- These filenamess must be preceded by "File:" in the table values.

    if commonsName ~= nil and string.find( commonsName, "File:", 1 ) == 1 then
        commonsName = string.sub( commonsName, 6)
        flagOf = ""
    end

-- Fallback for non-identified variant/label flags --
    if commonsName == nil then
        commonsName = "Flag of None"
    end

-- Border for everybody except Nepal and Ohio
    if commonsName == "Nepal" or commonsName == "Ohio" then 
        border = "" 
    else 
        border = "border|" 
    end


-- Size of flag -- 
-- Function to define the default size for the flag if needed
    function defaultSize()
        sizeExceptions = { "Nepal", "Switzerland", "the Vatican City", }
        for some,exceptions in pairs(sizeExceptions) do 
            if commonsName == exceptions then 
                size = "20x17px" 
            end 
        end
        if size == nil then 
            size = "20x22px" 
        end
        return size 
    end
-- Checking whether a size parameter has been introduced, otherwise set default     
    if territory.args[4]:find("px", -2) ~= nil then 
        size = territory.args[4] 
    else 
        size = defaultSize(commonsName) 
    end
    
-- Customizing the link
    openBrackets = "[["
    closeBrackets = "]]"
    if territory.args[5] == "" then
        flagLink = ""
        textLink = ""
        openBrackets = ""
        closeBrackets = ""
    elseif territory.args[5] ~= "{{{link}}}" then
        flagLink = territory.args[5]
        textLink = territory.args[5] .. "|"
    else flagLink = link
        textLink = link .. "|"
    end
        
-- Text in addition to flag
    if territory.args[6] == "" then
        text = " " .. openBrackets .. link .. closeBrackets
    elseif territory.args[6] ~= "{{{text}}}" then 
        text = " " .. openBrackets .. textLink .. territory.args[6] .. closeBrackets
    else text = ""
    end

return '[[File:' .. flagOf .. commonsName .. '.svg|' .. border .. 'link=' .. flagLink .. '|'.. size .. ']]' .. text
end
return p