averageTraffic = {
    modDir = g_currentModDirectory,
    xmlDir = g_currentModSettingsDirectory
}

TrafficSystem.onCreate = Utils.overwrittenFunction(TrafficSystem.onCreate, function (self, superFunc, transformId)
    local xmlFilename = getUserAttribute(transformId, "xmlFile")

    if  xmlFilename ~= nil then
        local mod = g_modManager:getModByName("FS22_RussianLicensePlates")
        if mod ~= nil and g_modIsLoaded["FS22_RussianLicensePlates"] then
            prefix = "ru"
            print("Average Traffic Info: FS22_RussianLicensePlates found. Russian License Plates will be loaded for traffic.")
        else
            prefix = "eu"
        end
    
        local mod = g_modManager:getModByName("FS22_UkrainianLicensePlates")
        if mod ~= nil and g_modIsLoaded["FS22_UkrainianLicensePlates"] then
            prefix = "ua"
            print("Average Traffic Info: FS22_UkrainianLicensePlates found. Ukrainian License Plates will be loaded for traffic.")
        else
            prefix = "eu"
        end

        local randomTraffic = math.random(1, 5)
        local randomFilename = string.format("%sxml/trafficSystem%s.xml", averageTraffic.modDir, randomTraffic)
        local xml = loadXMLFile("mod_trafficSystems", randomFilename)

        local i = 0
        while true do
            local filename = getXMLString(xml, "trafficSystems.trafficSystem(" .. i .. ")#filename")
            if filename ~= nil and filename ~= "" then
                local xmlFilename = Utils.getFilename(filename, averageTraffic.modDir)
                local len = xmlFilename:len()
                local ext = xmlFilename:sub(len - 5)

                if ext == prefix .. ".xml" then
                    local lightsProfile = g_gameSettings:getValue("lightsProfile")
                    local useHighProfile = lightsProfile == GS_PROFILE_HIGH or lightsProfile == GS_PROFILE_VERY_HIGH
                    local trafficSystem = TrafficSystem.new(g_server ~= nil, g_client ~= nil)
            
                    if trafficSystem:load(xmlFilename, transformId, useHighProfile, g_server ~= nil, g_client ~= nil) then
                        trafficSystem:register(true)
                        g_currentMission.onCreateObjectSystem:add(trafficSystem)
                        trafficSystem:setEnabled(g_currentMission.missionInfo.trafficEnabled)
                        print("Average Traffic Info: TrafficSystem xml " .. tostring(xmlFilename) .. " loaded!")
                    else
                        trafficSystem:delete()
                    end
            
                    g_currentMission.trafficSystem = trafficSystem
                end
            else
                break
            end
            i = i + 1
        end

        delete(xml)
    else
        print("Error: Missing xmlFile attribute for traffic system in " .. getName(transformId))
    end
end)