--- EepExport.lua
--- Modul zum Export aktueller Zustandsdaten einer EEP-Anlage als JSON-Datei.
--- Einbindung per require im Hauptskript der Anlage (siehe Beispiel).
---
--- Die Zustandsdaten werden im Standard je nach Version von EEP in die Datei <Anlagenpfad>\exchange\eep_export.json 
--- bzw. in <EEP-Installationspfad>\exchange\eep_export.json geschrieben.
---
--- Objekte koennen ueber die add...()-Funktionen angemeldet werden. Alle add...()-Funktionen verstehen
--- drei Eingabeformen und pruefen dabei, ob das Objekt wirklich existiert:
---   a) ein einzelner Wert:        EepExport.addSignals(12)
---   b) eine Liste von Werten:     EepExport.addSignals({ 1, 2, 3 })
---   c) ohne Eingabe:              EepExport.addSignals()   -> sucht 1..discoverMax nach Signalen
--- Die Pruefung erfolgt verzoegert beim ersten collect()/export()/run(), weil die EEP-Abfragen
--- waehrend des Ladens des Skripts nicht zuverlaessig funktionieren.
--- Zuege und Rollmaterial haben keine numerischen IDs; hier ist nur a) und b) moeglich.
---
--- Alle Rollmaterialien und indirekt damit auch alle Züge können auch komplett aus der anl3-Datei gelesen werden.
--- Aus der anl3-Datei werden in einem Durchlauf folgende Daten gelesen (config.anlFile):
---   * die Namen aller Rollmaterialien und damit indirekt auch alle Züge,
---   * die Kameras (Name, statisch/dynamisch) -> Ausgabe als "cameras" in der JSON-Datei, damit die Bridge direkt Kameras mit EEPSetCamera aufrufen kann,
---   * die Gleise der Gleisbildstellpulte (GBS), falls config.gbsTracks = true, damit die Besetztmeldungen im GBS Programm gezeigt werden können.
--- Die Abschnitte stehen in der anl3-Datei in fester Reihenfolge (Gleissystem, Fuhrpark, Gebaeudesammlung mit GBSObject,
--- Kammerasammlung); die Datei wird deshalb nur so weit gelesen, wie es noetig ist.
---
--- Automatische Erkennung von Zuegen und Rollmaterial (autoTrains / autoRollingstock):
---   * Zuege: werden aus den angemeldeten Signalen (EEPGetSignalTrainName) und virtuellen Depots
---     (EEPGetTrainyardItemName) uebernommen, sobald sie dort auftauchen. Zusaetzlich reagieren
---     die Handler fuer Rueckruf-Funktionen (installCallbacks) auf Signalhalt, Depot-Ein-/Ausfahrt,
---     Kuppeln und Trennen. Außerdem werden die Daten von EEPGetTrainActive verwendet.
---   * Rollmaterial: wird aus den Fahrzeuglisten aller bekannten Zuege uebernommen.
---   * Automatisch aufgenommene Eintraege werden wieder entfernt, wenn es sie nicht mehr gibt
---     (z.B. nach Umbenennung durch Kuppeln). Von Hand angemeldete bleiben immer erhalten.
--- Voraussetzung: Signale/Depots wurden per addSignals()/addTrainyards() angemeldet.
---
--- Automatischer Start: Beim ersten Aufruf von run() (aus EEPMain) passiert ohne weiteres Zutun:
---   * Die EEP-Rueckruffunktionen werden erweitert (siehe installCallbacks()), ausser config.installCallbacks = false.
---   * Wurden keine Signale bzw. Weichen angemeldet, wird 1..discoverMax danach durchsucht.
---     Wurden keine Depots angemeldet, wird 1..discoverDepotMax (Standard 10) durchsucht.
---   * Die Suche wird auf mehrere EEPMain-Aufrufe verteilt (discoverBudget); exportiert wird erst, wenn sie fertig ist.
---
--- Speichern der Anlage: Der Export pausiert, sobald EEP EEPOnBeforeSaveAnl() aufruft, und
--- wird durch EEPOnSaveAnl(Pfad) wieder freigegeben. Dabei merkt sich das Modul den Speicherpfad
--- (Ausgabe als global.plant.path). Dafuer installCallbacks() aufrufen oder die Handler
--- onBeforeSaveAnl() / onSaveAnl(pfad) aus den eigenen EEP-Funktionen aufrufen.

--[[ ---------------------------------------------------------------------------------------------
Beispiel fuer das Hauptskript der Anlage:

--- Optional: Modul liegt im Anlagenordner neben der .anl3-Datei
package.path = EEPGetAnlPath() .. "\\?.lua;" .. package.path

--- Lade Modul EepExport
local EepExport = require("EepExport")

--- Optional: Konfiguration (nicht erforderlich)
EepExport.configure({ 
  --outputFile       = nil,    -- Vollstaendiger Pfad der Ausgabedatei; Standard: <Anlagenpfad>\exchange\eep_export.json
  --interval         = 5,      -- Export-Intervall in EEP-Sekunden (-1 = nur manuell per M.export(), 0 = bei jedem Aufruf), Standard: 5
  pretty             = true,   -- true = eingerueckte, lesbare JSON-Ausgabe, Standard: false
  --global           = true,   -- Zeit, Jahreszeit, Wetter, Kamera exportieren, Standard: true
  --discoverMax      = 1000,   -- Bereich 1..discoverMax wird beim ersten Lauf automatisch auf vorhandene Objekte
                               -- geprueft (nil oder 0 = keine automatische Erkennung), Standard: 1000
  --discoverDepotMax = 10,     -- Obergrenze der automatischen Depot-Suche, Standard: 10
  --discoverBudget   = 0.03,   -- Rechenzeit der ID-Suche je EEPMain-Aufruf in Sekunden (0 = Suche in einem Rutsch), Standard: 0.03
  --autoTrains       = true,   -- Zuege automatisch ueber Signale und Depots einsammeln, Standard: true
  --autoRollingstock = true,   -- Rollmaterial automatisch aus den Fahrzeuglisten bekannter Zuege einsammeln, Standard: true
  --scanInterval     = 2,      -- Abstand der automatischen Suche in EEP-Sekunden, Standard: 2
  --installCallbacks = true,   -- EEP-Rueckruffunktionen automatisch erweitern, Standard: true
  --anlFile          = nil,    -- Pfad zu einer .anl3-Datei: Rollmaterialien, Kameras und GBS-Gleise werden daraus gelesen, Standard: nil
  --gbsTracks        = true,   -- mit anlFile: Gleise der Gleisbildstellpulte (GBS) fuer Besetztmeldungen anmelden, Standard: true
  debug              = true,   -- Debug, Standard: false
})

--- Optional: Auswahl der zu exportierenden Daten. Ohne Auswahl werden beim ersten run() automatisch
--- Signale und Weichen (1..discoverMax) und Depots (1..discoverDepotMax) gesucht.
EepExport.addSignals()                         -- ohne Eingabe: alle Signale 1..discoverMax suchen
EepExport.addSwitches({ 1, 2, 3 })             -- Einzelwert oder Liste: nur existierende werden aufgenommen 
EepExport.addTrainyards(EepExport.range(1, 5)) -- Bereich angeben
--EepExport.addRailTracks({ 1, 2, 3 })
--EepExport.addRoadTracks({ 1, 2, 3 })
--EepExport.addTramTracks({ 1, 2, 3 })
--EepExport.addAuxiliaryTracks({ 1, 2, 3 })
--EepExport.addControlTracks({ 1, 2, 3 })
--EepExport.addStructures({ '#1', '#2', '#3' })    -- Lua-Name oder Zahl
--EepExport.addGoods({ '#1', '#2', '#3' })         -- Lua-Name oder Zahl
--EepExport.addWeatherZones({ '#1', '#2', '#3' })  -- Lua-Name oder Zahl

--- Zuege und Rollmaterial muessen mit Namen angemeldet werden
--EepExport.addTrains({ "#ICE1", "#Gueterzug" })
--EepExport.addRollingstock({ 'Lok', 'Wagen', 'Fracht' })

function EEPMain()
  --- In EEPMain() aufrufen. Exportiert automatisch im eingestellten Intervall (EEP-Zeit in Sekunden). 
  EepExport.run()
  --- Anzeige der letzten Fehlermeldung
  if EepExport.lastError then print(EepExport.lastError) end
  
  return 1
end

--- Die Rueckruffunktionen werden beim ersten run() automatisch erweitert (Abschalten: installCallbacks = false):
--- EEPOnTrainStoppedOnSignal, 
--- EEPOnTrainEnterTrainyard, EEPOnTrainExitTrainyard, 
--- EEPOnTrainCoupling, EEPOnTrainLooseCoupling,
--- EEPOnBeforeSaveAnl, EEPOnSaveAnl.
--- Eigene Funktionen gleichen Namens bleiben erhalten und werden nach den Handlern aufgerufen.
--- Manuell (z.B. bei abgeschaltetem Automatismus) weiterhin moeglich: EepExport.installCallbacks()

--- Test-Funktionen (diese Funktionen können in einer späteren Version entfallen)

--- Test: Liest Rollmaterialien, Kameras und GBS-Gleise einer anl3-Datei in einem Durchlauf.
--- want ist optional, z.B. { cameras = true }; ohne Angabe wird alles gelesen.
--local result, err = EepExport.readAnl(path, want)   -- result.rollingstock, result.cameras, result.gbs

--- Test: Lese die Namen von Rollmaterialien aus einer anl3-Datei
--local names, err = EepExport.readRollingstockNames(path)

--- Test: Lese die Kameras aus einer anl3-Datei: Name -> { dynamic = true|false }
--local cameras, err = EepExport.readCameras(path)

--- Test: Sucht in allen Kategorien mit numerischen IDs (also ausser Zuege und Rollmaterial) nach vorhandenen Objekten.
--EepExport.discoverAll()

--- Test: Sammelt alle Zustandsdaten und gibt sie als Tabelle zurueck.
--local okCollect, data = EepExport.collect()

--- Test: Wertet alle bisher angemeldeten add...()-Aufrufe aus. Wird von collect() automatisch aufgerufen.
--local counts = EepExport.resolve()

--- Test: Sammelt die Daten und schreibt sie als JSON-Datei. Gibt true, Pfad oder false, Fehlermeldung zurueck.
--local ok, msg = EepExport.export()
------------------------------------------------------------------------------------------------]]

local M = {}

--- Letzte Fehlermeldung (nil, wenn der letzte Export bzw. Lauf fehlerfrei war).
M.lastError = nil

-- ---------------------------------------------------------------------------------------------
-- Konfiguration
-- ---------------------------------------------------------------------------------------------
local config = {
  outputFile       = nil,   -- Vollstaendiger Pfad der Ausgabedatei; Standard: <Anlagenpfad>\exchange\eep_export.json
  interval         = 5,     -- Export-Intervall in EEP-Sekunden (-1 = nur manuell per M.export(), 0 = bei jedem Aufruf)
  pretty           = false, -- true = eingerueckte, lesbare JSON-Ausgabe
  global           = true,  -- Zeit, Jahreszeit, Wetter, Kamera exportieren
  discoverMax      = 1000,  -- Obergrenze der ID-Suche, wenn add...() ohne Eingabe aufgerufen wird
  discoverDepotMax = 10,    -- Obergrenze der ID-Suche fuer virtuelle Depots (nil oder 0 = keine Depot-Suche)
  discoverBudget   = 0.03,  -- Rechenzeit der ID-Suche je Aufruf in Sekunden (0 = Suche in einem Rutsch).
                            -- Exportiert wird erst, wenn die Suche abgeschlossen ist.
  autoTrains       = true,  -- Zuege automatisch ueber Signale und Depots einsammeln
  autoRollingstock = true,  -- Rollmaterial automatisch aus den Fahrzeuglisten bekannter Zuege einsammeln
  scanInterval     = 2,     -- Abstand der automatischen Suche in EEP-Sekunden
  saveTimeout      = 60,    -- Sicherheitsnetz: Export-Pause endet nach so vielen realen Sekunden von selbst,
                            -- falls EEPOnSaveAnl nie kommt (0 = kein Timeout)
  installCallbacks = true,  -- EEP-Rueckruffunktionen beim ersten run() automatisch erweitern
  trainScanBatch   = 100,   -- Rollmaterialien je Suchlauf, deren Zug per EEPRollingstockGetTrainName ermittelt wird (0 = aus)
  anlFile          = nil,   -- Pfad zu einer .anl3-Datei; daraus werden Rollmaterialien, Kameras und GBS-Gleise gelesen
  gbsTracks        = true,  -- bei gesetztem anlFile auch alle in GBS eingetragenen Gleise zur Besetztabfrage anmelden
  debug            = false, -- Debugging-Information anzeigen
}

local registry = {
  signals = {}, 
  switches = {}, 
  depots = {},
  railTracks = {}, 
  roadTracks = {}, 
  tramTracks = {}, 
  auxTracks = {}, 
  controlTracks = {},
  structures = {}, 
  goods = {}, 
  zones = {}, 
  trains = {}, 
  rollingstock = {},
}
local pending = {}      -- noch nicht ausgewertete add...()-Aufrufe
local anlLoaded = nil   -- anlFile, aus dem Rollmaterial, Kameras und GBS-Gleise zuletzt gelesen wurden
local cameraList = nil  -- Kameras aus der anl3-Datei: Name -> { dynamic = true|false }
local lastExport = nil
local lastScan   = nil       
local initialized = false  -- automatische Initialisierung (Callbacks, Suche) bereits erfolgt
local callbacksInstalled = false
local paused      = false  -- Export pausiert, solange die Anlage gespeichert wird
local pausedSince = nil    -- reale Zeit (os.time) des Pausenbeginns
local savedPath   = nil    -- zuletzt in EEPOnSaveAnl gemeldeter Speicherpfad (inkl. Dateiname) 

-- ---------------------------------------------------------------------------------------------
-- Hilfsfunktionen
-- ---------------------------------------------------------------------------------------------

--- Ruft eine EEP-Funktion geschuetzt auf. Fehlt die Funktion (aeltere EEP-Version) oder wirft
--- sie einen Fehler, wird false zurueckgegeben.
local function unwrap(status, ...)
  if status then return ... end
  return false
end

local function try(fn, ...)
  if type(fn) ~= "function" then return false end
  return unwrap(pcall(fn, ...))
end

                                    
                             
                                      
     
              
   

--- Erzeugt eine Zahlenliste aus einem Bereich, z.B. range(1, 20).
function M.range(first, last)
  local t = {}
  for i = first, last do t[#t + 1] = i end
  return t
end

-- Statische Daten (aendern sich nie): werden je Objekt und Feld nur einmal ermittelt.
-- kategorie -> name -> { feld = wert }
local staticCache = { signals = {}, rollingstock = {}, structures = {}, goods = {} }

--- Liefert den gecachten Wert; fehlt er noch, wird fn(...) einmal aufgerufen und bei Erfolg gespeichert.
local function cachedStatic(store, key, field, fn, ...)
  local st = store[key]
  if not st then st = {}; store[key] = st end
  if st[field] == nil then
    local ok, value = try(fn, ...)
    if ok then st[field] = value end
  end
  return st[field]
end

-- ---------------------------------------------------------------------------------------------
-- JSON-Encoder (minimal, ohne externe Abhaengigkeiten)
-- ---------------------------------------------------------------------------------------------
local escapes = {
  ['"'] = '\\"', 
  ['\\'] = '\\\\', 
  ['\b'] = '\\b', 
  ['\f'] = '\\f',
  ['\n'] = '\\n', 
  ['\r'] = '\\r', 
  ['\t'] = '\\t',
}

local function encodeString(s)
  -- Schnellpfad: die meisten Strings enthalten nichts, was maskiert werden muss
  if not s:find('[%c"\\]') then return '"' .. s .. '"' end
  s = s:gsub(
    '[%c"\\]', 
    function(c)
      return escapes[c] or string.format("\\u%04x", string.byte(c))
    end
  )
  return '"' .. s .. '"'
end

local function encodeNumber(v)
  if v ~= v or v == math.huge or v == -math.huge then return "null" end
  if v % 1 == 0 and math.abs(v) < 1e15 then return string.format("%d", v) end
  return string.format("%.6g", v)
end

local function isArray(t)
  local n = 0
  for k in pairs(t) do
    if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return false end
    n = n + 1
  end
  return n == #t
end

--- Schreibt die JSON-Teilstrings in den Puffer out (wird am Ende mit table.concat zusammengesetzt).
local function encodeTo(out, v, pretty, indent)
  local tv = type(v)
                                   

  if tv == "string" then
    out[#out + 1] = encodeString(v)

  elseif tv == "number" then
    out[#out + 1] = encodeNumber(v)
                                                                               
                                   

  elseif tv == "boolean" then
    out[#out + 1] = v and "true" or "false"

  elseif tv == "table" then
    if next(v) == nil then out[#out + 1] = "{}"; return end

    local nl, ind, ind2, sep = "", "", "", ":"
    if pretty then
      nl = "\n"; ind = string.rep("  ", indent + 1); ind2 = string.rep("  ", indent); sep = ": "
    end

                    
                                          
    
    if isArray(v) then
      out[#out + 1] = "[" .. nl
      for i = 1, #v do
        if i > 1 then out[#out + 1] = "," .. nl end
        out[#out + 1] = ind
        encodeTo(out, v[i], pretty, indent + 1)
      end
      out[#out + 1] = nl .. ind2 .. "]"
    else
      local keys = {}
      for k in pairs(v) do keys[#keys + 1] = k end
      -- Sortiert wird nur fuer die lesbare Ausgabe; JSON-Objekte sind ohnehin ungeordnet
      if pretty then table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) end
      out[#out + 1] = "{" .. nl
      for i, k in ipairs(keys) do
        if i > 1 then out[#out + 1] = "," .. nl end
                                                 
        out[#out + 1] = ind .. encodeString(tostring(k)) .. sep
        encodeTo(out, v[k], pretty, indent + 1)
      end
      out[#out + 1] = nl .. ind2 .. "}"
    end

  else
    out[#out + 1] = "null"
  end
end

--- Wandelt eine Lua-Tabelle in einen JSON-String um.
function M.toJson(value, pretty)
  -- Alternative: json.lua (c) 2020 rxi rxi https://github.com/rxi/json.lua oder cjson.dll
  local out = {}
  encodeTo(out, value, pretty and true or false, 0)
  return table.concat(out)
end

-- ---------------------------------------------------------------------------------------------
-- Objektkategorien: Existenzpruefung + Anmeldung (add...)
-- ---------------------------------------------------------------------------------------------

-- Existenzpruefungen: liefern true, wenn es das Objekt gibt.
-- Signal/Weiche: Stellung 0 bedeutet "existiert nicht".
local function existsSignal(id)
  local v = try(EEPGetSignal, id)
  return type(v) == "number" and v ~= 0
end

local function existsSwitch(id)
  local v = try(EEPGetSwitch, id)
  return type(v) == "number" and v ~= 0
end

-- Gleise: Die Registrierung liefert true, wenn das Element existiert, und macht es
-- gleichzeitig fuer Besetztabfragen verfuegbar (zwingende Voraussetzung).
local function registrar(fn)
  return function(id) return try(fn, id) == true end
end

local function existsStructure(name) return try(EEPStructureGetPosition, name) == true end
local function existsGoods(name)     return try(EEPGoodsGetPosition, name) == true end
local function existsZone(id)        return try(EEPGetZonePos, id) == true end

-- Depot: gilt als vorhanden, wenn mindestens ein Fahrzeugverband dort registriert ist.
local function existsDepot(id)
  local n = try(EEPGetTrainyardItemsCount, id)
  return type(n) == "number" and n > 0
end

-- Zug/Rollmaterial: Abfrage ueber den Namen (Zug auch, wenn er gerade im Depot steht).
local function existsTrain(name)
  if try(EEPGetTrainSpeed, name) == true then return true end
  return try(EEPIsTrainInTrainyard, name) == true
end

local function existsRollingstock(name)
  return try(EEPRollingstockGetTrainName, name) == true
end

-- Normalisierung der Eingabewerte
local function toId(v)
  local n = tonumber(v)
  if n and n % 1 == 0 then return n end
  return nil
end

local function toLuaName(v)
  if type(v) == "number" then return "#" .. string.format("%d", v) end
  if type(v) == "string" and v ~= "" then return v end
  return nil
end

local function toName(v)
  if type(v) == "string" and v ~= "" then return v end
  return nil
end

local categories = {
  signals       = { list = registry.signals,       exists = existsSignal,                         normalize = toId,      scan = true },
  switches      = { list = registry.switches,      exists = existsSwitch,                         normalize = toId,      scan = true },
  depots        = { list = registry.depots,        exists = existsDepot,                          normalize = toId,      scan = true, scanMaxKey = "discoverDepotMax" },
  railTracks    = { list = registry.railTracks,    exists = registrar(EEPRegisterRailTrack),      normalize = toId,      scan = true },
  roadTracks    = { list = registry.roadTracks,    exists = registrar(EEPRegisterRoadTrack),      normalize = toId,      scan = true },
  tramTracks    = { list = registry.tramTracks,    exists = registrar(EEPRegisterTramTrack),      normalize = toId,      scan = true },
  auxTracks     = { list = registry.auxTracks,     exists = registrar(EEPRegisterAuxiliaryTrack), normalize = toId,      scan = true },
  controlTracks = { list = registry.controlTracks, exists = registrar(EEPRegisterControlTrack),   normalize = toId,      scan = true },
  structures    = { list = registry.structures,    exists = existsStructure,                      normalize = toLuaName, scan = true },
  goods         = { list = registry.goods,         exists = existsGoods,                          normalize = toLuaName, scan = true },
  zones         = { list = registry.zones,         exists = existsZone,                           normalize = toId,      scan = true },
  trains        = { list = registry.trains,        exists = existsTrain,                          normalize = toName,    scan = false },
  rollingstock  = { list = registry.rollingstock,  exists = existsRollingstock,                   normalize = toName,    scan = false },
}
-- set: Mengen-Index zur Liste (schnelle Pruefung "schon angemeldet?" ohne lineare Suche)
for key, cat in pairs(categories) do cat.key = key; cat.set = {} end

-- Automatisch aufgenommene Eintraege je Kategorie: key -> { [wert] = true }
local autoSet = {}

--- Wertet einen add...()-Aufruf aus: prueft die Werte und haengt vorhandene Objekte an die Liste an.
--- Gibt die Anzahl neu hinzugefuegter Objekte zurueck und ob die Suche abgeschlossen ist (false, wenn die
--- Zeitgrenze deadline erreicht wurde; job.cursor merkt sich dann die Position).
local function process(cat, input, scan, auto, job, deadline)
  local added = 0
  
  local function consider(value)
    value = cat.normalize(value)
    if value == nil then return end
    
    if cat.set[value] then
      -- von Hand bestaetigt: wird nie mehr automatisch entfernt
      if not auto and autoSet[cat.key] then autoSet[cat.key][value] = nil end
      
    elseif cat.exists(value) then
      cat.list[#cat.list + 1] = value
      cat.set[value] = true
      added = added + 1
      if auto then
        autoSet[cat.key] = autoSet[cat.key] or {}
        autoSet[cat.key][value] = true
      end
    end
  end

  if scan then
    if cat.scan then
      local max = config[cat.scanMaxKey or "discoverMax"] or 0
      local id = job and job.cursor or 0
      while id < max do
        id = id + 1
        consider(id)
        if deadline and id < max and os.clock() > deadline then
          job.cursor = id
          return added, false
        end
      end
    end
  elseif type(input) == "table" then
    for _, value in ipairs(input) do consider(value) end
  else
    consider(input)
  end
  return added, true
end

local function queue(key, input, auto)
  pending[#pending + 1] = { key = key, input = input, scan = (input == nil), auto = auto }
end

-- ---------------------------------------------------------------------------------------------
-- Daten aus einer .anl3-Datei lesen (Rollmaterial, Kameras, GBS-Gleise) in EINEM Durchlauf
-- ---------------------------------------------------------------------------------------------
-- Die Datei wird in Bloecken gelesen und nicht als Ganzes geladen. Die Abschnitte stehen in fester Reihenfolge:
                                                                                                     
                                                                                          
                                                                                                   
                                                      
               
--   1. Gleissystem
--   2. Fuhrpark mit Rollmaterial
--   3. Gebaeudesammlung mit GBSObject
--   4. Kammerasammlung
-- Je Phase wird nur nach den dann moeglichen Abschnittsanfaengen gesucht; alles andere (Landschaft,
-- Gleise usw.) wird uebersprungen. Die Kammerasammlung beendet den GBS-Bereich. Sind keine Kameras
-- gewuenscht, endet das Lesen dort, sonst am Ende der Kammerasammlung. Der Rest der Datei wird nie gelesen.

local function codepointToUtf8(cp)
  if not cp then return "" end
  if cp < 0x80 then return string.char(cp) end
  if cp < 0x800 then
    return string.char(0xC0 + math.floor(cp / 0x40), 0x80 + cp % 0x40)
  end
  if cp < 0x10000 then
    return string.char(0xE0 + math.floor(cp / 0x1000), 0x80 + math.floor(cp / 0x40) % 0x40, 0x80 + cp % 0x40)
  end
  return string.char(
    0xF0 + math.floor(cp / 0x40000),
    0x80 + math.floor(cp / 0x1000) % 0x40,
    0x80 + math.floor(cp / 0x40) % 0x40,
    0x80 + cp % 0x40
  )
end

local function xmlUnescape(s)
  if not s:find("&", 1, true) then return s end
  s = s:gsub("&#[xX](%x+);", function(h) return codepointToUtf8(tonumber(h, 16)) end)
  s = s:gsub("&#(%d+);",     function(d) return codepointToUtf8(tonumber(d)) end)
  s = s:gsub("&lt;", "<")
  s = s:gsub("&gt;", ">")
  s = s:gsub("&quot;", '"')
  s = s:gsub("&apos;", "'")
  s = s:gsub("&amp;", "&")   -- zuletzt, damit "&amp;lt;" nicht doppelt aufgeloest wird
  return s
end

--- UTF-8 (Latin-1-Bereich) -> ANSI, damit Namen wie die von EEP geliefern aussehen
local function utf8ToAnsi(s)
  return (s:gsub("([\194\195])([\128-\191])", function(a, b)
    return string.char((a:byte() - 194) * 64 + b:byte())
  end))
end

--- Position des ">" das ein Tag beendet (">" in Anfuehrungszeichen zaehlt nicht), sonst nil.
local function findTagEnd(buf, from)
  local pos = from
  while true do
    local i = buf:find('[">]', pos)
    if not i then return nil end
    if buf:sub(i, i) == ">" then return i end
    local j = buf:find('"', i + 1, true)
    if not j then return nil end
    pos = j + 1
  end
end

--- Sammelt die Gleis-IDs eines <GBSObject>...</GBSObject>-Blocks in found[GleissystemID][GleisID] = true.
--- (<Tracks1..4><Table Count="n" e0=".." e1=".."/>, siehe EEP_GBS.html)
local function parseGbsBlock(block, found)
  local system = block:match('^<GBSObject[^>]-GleissystemID="(%d+)"') or "1"
  found[system] = found[system] or {}
  for tag in block:gmatch("<Tracks%d>%s*<Table([^>]*)>") do
    local count = tonumber(tag:match('Count="(%d+)"')) or 0
    for i = 0, count - 1 do
      local id = tonumber(tag:match('%se' .. i .. '="(%d+)"'))
      if id and id > 0 then found[system][id] = true end
    end
  end
end

--- Liest eine .anl3-Datei in einem Durchlauf.
--- want = { rollingstock = bool, cameras = bool, gbs = bool }  (Standard: alles)
--- Ergebnis:
---   rollingstock = Liste der Namen aller Rollmaterialien (Fuhrpark/Zugverband/Rollmaterial@name,
---                  Reihenfolge wie in der Datei, ohne Duplikate)
---   cameras      = Kamerasammlung: Name -> { dynamic = true|false }
---                  (die Platzhalter "Leer", "blank", "Vide" werden ausgelassen)
---   gbs          = Gleissystem-Nummer (TrackSystemNumber, 1 = Bahn, 2 = Tram, 3 = Strasse,
---                  4 = Wasserwege, 5 = Steuerstrecken) -> sortierte Liste der in GBS eingetragenen GleisIDs
--- Bei einem Fehler: nil, Fehlermeldung.
function M.readAnl(path, want)
  want = want or { rollingstock = true, cameras = true, gbs = true }
  local file, err = io.open(path, "rb")
  if not file then return nil, "Datei nicht lesbar: " .. tostring(err) end

  local result = { rollingstock = {}, cameras = {}, gbs = {} }
  local seen = {}        -- Namen der Rollmaterialien (Duplikate vermeiden)
  local sysNumber = {}   -- GleissystemID -> TrackSystemNumber
  local found = {}       -- GleissystemID -> { [GleisID] = true }
  local done = { fuhrpark = not want.rollingstock, kameras = not want.cameras, gbs = not want.gbs }
  local sysPassed = not want.gbs   -- true: <Gleissystem ...> wird nicht mehr gesucht (nur fuer GBS noetig)
                                  
                                       
                                  
                                      
   
  local mode = nil       -- nil = Suche nach dem naechsten Abschnitt, sonst "fuhrpark" oder "kameras"
  local buf, eof = "", false

  --- Fruehester Abschnittsanfang ab pos, der in der aktuellen Phase noch moeglich ist.
  local function nextMarker(pos)
    local at, kind
    local function probe(marker, k)
      local s = buf:find(marker, pos, true)
      if s and (not at or s < at) then at, kind = s, k end
    end
    if not sysPassed     then probe("<Gleissystem ", "sys") end
    if not done.fuhrpark then probe("<Fuhrpark", "fuhrpark") end
    if not done.gbs      then probe("<GBSObject", "gbs") end
    -- beendet den GBS-Bereich und startet ggf. die Kameras
    if want.gbs or want.cameras then probe("<Kammerasammlung", "kameras") end
    return at, kind
  end

  while not eof and not (done.fuhrpark and done.kameras and done.gbs) do
    local chunk = file:read(262144)
    if chunk then buf = buf .. chunk else eof = true end

    local pos, more = 1, false   -- more = true: Puffer ist aufgebraucht, naechsten Block nachladen
    while not more do

      if mode == "fuhrpark" then
        local sR = buf:find("<Rollmaterial", pos, true)
        local sE = buf:find("</Fuhrpark", pos, true)
        if sE and (not sR or sE < sR) then
          done.fuhrpark, mode, pos = true, nil, sE + 10
          sysPassed = true                                 -- Gleissysteme stehen vor dem Fuhrpark
        elseif not sR then
          pos = math.max(pos, #buf - 12); more = true      -- Rest koennte ein Teil von "<Rollmaterial" sein
        else
          local e = findTagEnd(buf, sR + 13)
          if not e then
            pos = sR; more = true                          -- Tag noch unvollstaendig: Block nachladen
          else
            local attrs = buf:sub(sR + 13, e - 1)
            for key, value in attrs:gmatch('([%w_:%-]+)%s*=%s*"([^"]*)"') do
              if key == "name" then
                local name = utf8ToAnsi(xmlUnescape(value))
                if name ~= "" and not seen[name] then
                  if config.debug then print("EepExport: Rollmaterial in anl3-Datei gefunden: ", name) end
                  seen[name] = true
                  result.rollingstock[#result.rollingstock + 1] = name
                end
                break
              end
            end
            pos = e + 1
          end
        end

      elseif mode == "kameras" then
        local sK = buf:find("<Kammera%s", pos)
        local sE = buf:find("</Kammerasammlung", pos, true)
        if sE and (not sK or sE < sK) then
          done.kameras, mode, pos = true, nil, sE + 17
        elseif not sK then
          pos = math.max(pos, #buf - 20); more = true
        else
          local e = findTagEnd(buf, sK + 8)
          if not e then
            pos = sK; more = true
          else
            local attrs = buf:sub(sK + 8, e - 1)
            local name = attrs:match('%sname="([^"]*)"')
            if name then
              name = utf8ToAnsi(xmlUnescape(name))
              if name ~= "Leer" and name ~= "blank" and name ~= "Vide" then
                result.cameras[name] = { dynamic = attrs:match('%sDynamic="(%d+)"') == "1" }
              end
            end
            pos = e + 1
          end
        end

      else
        local at, kind = nextMarker(pos)
                      
                                      
                                                           
                                               
                                                                   
             
           

        if not at then
          pos = math.max(pos, #buf - 20); more = true      -- Anfang koennte ueber die Blockgrenze reichen

        elseif kind == "fuhrpark" then
          local e = findTagEnd(buf, at + 9)
          if not e then
            pos = at; more = true
          elseif buf:sub(e - 1, e - 1) == "/" then
            done.fuhrpark, sysPassed = true, true; pos = e + 1   -- leerer Abschnitt ohne Inhalt
          else
            mode, sysPassed = "fuhrpark", true; pos = e + 1
          end

        elseif kind == "kameras" then
          -- Ab hier gibt es weder Fuhrpark noch GBS noch Gleissysteme
          local e = findTagEnd(buf, at + 16)
          if not e then
            pos = at; more = true
          else
            done.gbs, done.fuhrpark, sysPassed = true, true, true
            if done.kameras or buf:sub(e - 1, e - 1) == "/" then
              done.kameras = true; pos = e + 1                 -- Kameras nicht gewuenscht oder leer: fertig
            else
              mode = "kameras"; pos = e + 1
            end
          end

        elseif kind == "gbs" then
          local e = buf:find("</GBSObject>", at, true)
          if not e then
            pos = at; more = true                          -- GBS noch unvollstaendig: Block nachladen
          else
            parseGbsBlock(buf:sub(at, e), found)
            sysPassed = true
            pos = e + 1
          end

        else  -- "sys": <Gleissystem GleissystemID=".." TrackSystemNumber=".."> (ab EEP 16)
          local e = buf:find(">", at, true)
          if not e then
            pos = at; more = true
          else
            local attrs = buf:sub(at, e)
            local id = attrs:match('GleissystemID="(%d+)"')
            local nr = attrs:match('TrackSystemNumber="(%d+)"')
            if id or nr then sysNumber[id or nr] = nr or id end
            pos = e + 1
          end
        end
      end
    end
    buf = buf:sub(pos)
  end
  file:close()

  -- Gleissystem-IDs erst jetzt in Systemnummern uebersetzen (unabhaengig von der Reihenfolge in der Datei)
  for system, set in pairs(found) do
    local nr = tonumber(sysNumber[system] or system)
    local list = result.gbs[nr] or {}
    for id in pairs(set) do list[#list + 1] = id end
    table.sort(list)
    result.gbs[nr] = list
  end

  return result
end

--- Liest die Namen aller Rollmaterialien aus einer .anl3-Datei. Liste oder nil, Fehlermeldung.
function M.readRollingstockNames(path)
  local r, err = M.readAnl(path, { rollingstock = true })
  if not r then return nil, err end
  return r.rollingstock
end

--- Liest die Kameras aus einer .anl3-Datei: Name -> { dynamic = true|false } oder nil, Fehlermeldung.
function M.readCameras(path)
  local r, err = M.readAnl(path, { cameras = true })
  if not r then return nil, err end
  return r.cameras
end

--- Liest die in Gleisbildstellpulten (GBS) eingetragenen Gleise: Gleissystem-Nummer -> Liste der GleisIDs.
function M.readGbsTracks(path)
  local r, err = M.readAnl(path, { gbs = true })
  if not r then return nil, err end
  return r.gbs
end

-- Gleissystem-Nummer -> Kategorie der Gleisregistrierung (EEPRegisterRailTrack usw.)
local gbsTrackCategory = { [1] = "railTracks", [2] = "tramTracks", [3] = "roadTracks", [4] = "auxTracks", [5] = "controlTracks" }

--- Meldet die GBS-Gleise (Gleissystem-Nummer -> GleisIDs) zur Besetztabfrage an.
local function queueGbsTracks(systems)
  for nr, ids in pairs(systems) do
    local key = gbsTrackCategory[nr]
    if key and #ids > 0 then
      if config.debug then print(string.format("EepExport: %d GBS-Gleise in Gleissystem %d (%s)", #ids, nr, key)) end
      queue(key, ids, true)
    end
  end
end

--- Liest config.anlFile einmalig (je Datei) und meldet Rollmaterialien (automatisch aufgenommen; nicht mehr
--- vorhandene werden spaeter per pruneMissing entfernt) und GBS-Gleise an. Die Kameras werden fuer den Export gemerkt.
local function loadAnl()
  local path = config.anlFile
  if type(path) ~= "string" or path == "" or anlLoaded == path then return end
  anlLoaded = path   -- nur einmal je Datei versuchen, auch bei Fehler

  local s0 = os.clock()

  local ok, res, err = pcall(M.readAnl, path, {
    rollingstock = true,
    cameras      = true,
    gbs          = config.gbsTracks and true or false,
  })
  if not ok then res, err = nil, res end
  if not res then
    M.lastError = "EepExport: anl3-Datei " .. tostring(path) .. ": " .. tostring(err)
    if config.debug then print(M.lastError) end
    return
  end

  if config.debug then
    local cams = 0
    for _ in pairs(res.cameras) do cams = cams + 1 end
    print(string.format("EepExport: %s in %.1f ms gelesen (%d Rollmaterialien, %d Kameras)",
      path, (os.clock() - s0) * 1000, #res.rollingstock, cams))
  end

  if #res.rollingstock > 0 then queue("rollingstock", res.rollingstock, true) end
  cameraList = res.cameras
  queueGbsTracks(res.gbs)
end

--- Meldet die in den GBS einer .anl3-Datei eingetragenen Gleise an (ohne config.anlFile).
function M.addGbsTracks(path)
  local r, err = M.readAnl(path, { gbs = true })
  if r then
    queueGbsTracks(r.gbs)
  else
    M.lastError = "EepExport: GBS-Gleise aus " .. tostring(path) .. ": " .. tostring(err)
    if config.debug then print(M.lastError) end
  end
end

--- Wertet alle bisher angemeldeten add...()-Aufrufe aus. Wird von collect() automatisch aufgerufen.
--- Gibt eine Tabelle mit der Anzahl neu hinzugefuegter Objekte je Kategorie zurueck.
--- Umfangreiche ID-Suchlaeufe werden auf mehrere Aufrufe verteilt (config.discoverBudget); unfertige
--- Auftraege bleiben in pending und werden beim naechsten Aufruf fortgesetzt.
function M.resolve()
                                                       
  
  loadAnl()   -- falls config.anlFile gesetzt ist (einmalig je Datei): Rollmaterial, Kameras, GBS-Gleise

  local queued = pending
  pending = {}
  local counts = {}

  local budget = config.discoverBudget
  local deadline = (budget and budget > 0) and (os.clock() + budget) or nil

  for _, job in ipairs(queued) do
    if deadline and job.scan and os.clock() > deadline then
      pending[#pending + 1] = job        -- Zeitscheibe verbraucht: beim naechsten Aufruf
    else
      local added, finished = process(categories[job.key], job.input, job.scan, job.auto, job, deadline)
      counts[job.key] = (counts[job.key] or 0) + added
      if not finished then pending[#pending + 1] = job end
    end
  end
  return counts
end

-- Anmeldefunktionen: Einzelwert, Liste oder ohne Eingabe (Suche 1..discoverMax)
function M.addSignals(input)         queue("signals",       input) end
function M.addSwitches(input)        queue("switches",      input) end
function M.addTrainyards(input)      queue("depots",        input) end
function M.addRailTracks(input)      queue("railTracks",    input) end
function M.addRoadTracks(input)      queue("roadTracks",    input) end
function M.addTramTracks(input)      queue("tramTracks",    input) end
function M.addAuxiliaryTracks(input) queue("auxTracks",     input) end
function M.addControlTracks(input)   queue("controlTracks", input) end
function M.addStructures(input)      queue("structures",    input) end   -- Zahl 12 oder "#12" bzw. "#12_Name"
function M.addGoods(input)           queue("goods",         input) end
function M.addWeatherZones(input)    queue("zones",         input) end
function M.addTrains(input)          queue("trains",        input) end   -- nur Namen mit #-Praefix
function M.addRollingstock(input)    queue("rollingstock",  input) end   -- nur Namen

--- Sucht in allen Kategorien mit numerischen IDs (alle ausser Zuege/Rollmaterial) nach vorhandenen Objekten.
function M.discoverAll()
  -- Reihenfolge fuer discoverAll() ohne Zuege und Rollmeterialien
  local scanOrder = { 
    "signals", 
    "switches", 
    "depots", 
    "railTracks", 
    "roadTracks", 
    "tramTracks", 
    "auxTracks",
    "controlTracks", 
    "structures", 
    "goods", 
    "zones", 
  }
  for _, key in ipairs(scanOrder) do queue(key, nil) end
end

-- ---------------------------------------------------------------------------------------------
-- Automatische Erkennung von Zuegen und Rollmaterial
-- ---------------------------------------------------------------------------------------------
local vehicleCount = {}   -- Zugname -> zuletzt gelesene Fahrzeugzahl (spart wiederholte Abfragen)
local trainCursor = 0   -- Position der reihum laufenden Zugsuche ueber die Rollmaterialliste
--- Nimmt einen Zug bzw. ein Fahrzeug automatisch auf (mit Existenzpruefung).
--- Zugnamen werden mit und ohne #-Praefix versucht, da Rueckrufe sie teils ohne liefern.
local function addAuto(key, name)
  if type(name) ~= "string" or name == "" then return end
  
  local cat = categories[key]
  if key == "trains" then
    if cat.set[name] or cat.set["#" .. name] then return end
    
    if not existsTrain(name) and name:sub(1, 1) ~= "#" and existsTrain("#" .. name) then
      name = "#" .. name
    end
    
  elseif cat.set[name] then
    return
  end
  
  if config.debug then print(string.format("EepExport auto discovery: %s %s", key, name)) end

  process(cat, name, false, true)
end

--- Entfernt automatisch aufgenommene Eintraege, die es nicht mehr gibt. Grundlage sind die gerade
--- gesammelten Daten (map = Ergebnis von collectMap): Eintraege mit exists == false entfallen,
--- ohne dass dafuer weitere EEP-Abfragen noetig sind.
local function pruneMissing(key, map)
  local set = autoSet[key]
  if not set or next(set) == nil then return end

  local cat, keep, removed = categories[key], {}, false
  for _, value in ipairs(cat.list) do
    local entry = map[tostring(value)]
    if set[value] and entry and entry.exists == false then
      removed = true
      if config.debug then print(string.format("EepExport auto removal: %s %s", key, value)) end

                            
      set[value], cat.set[value] = nil, nil
      vehicleCount[value] = nil
      if staticCache[key] then staticCache[key][value] = nil end
      map[tostring(value)] = nil          -- erscheint nicht in der Ausgabe
    else
      keep[#keep + 1] = value
    end
  end

  if removed then
    -- registry.* muss dieselbe Tabelle bleiben: Inhalt an Ort und Stelle ersetzen
    for i = #cat.list, 1, -1 do cat.list[i] = nil end
    for i, v in ipairs(keep) do cat.list[i] = v end
  end
end

--- Durchsucht angemeldete Signale und Depots nach Zuegen und bekannte Zuege nach Fahrzeugen.
local function scanForTrains()
  if config.autoTrains then
    for _, id in ipairs(registry.signals) do
      local n = try(EEPGetSignalTrainsCount, id)
      if type(n) == "number" then
        for i = 1, n do addAuto("trains", try(EEPGetSignalTrainName, id, i)) end
      end
    end
    for _, id in ipairs(registry.depots) do
      local n = try(EEPGetTrainyardItemsCount, id)
      if type(n) == "number" then
        for slot = 1, n do addAuto("trains", try(EEPGetTrainyardItemName, id, slot)) end
      end
    end
  end
  
  -- Zuege ueber das Rollmaterial: z.B. aus der anl3-Datei gelesene Fahrzeuge verraten ihren Zug.
  -- Reihum in Bloecken, damit bei vielen Fahrzeugen nicht jeder Lauf alle abfragen muss.
  if config.autoTrains then
    local list = registry.rollingstock
    local total = #list
    local batch = math.min(config.trainScanBatch or 0, total)
    for _ = 1, batch do
      trainCursor = trainCursor % total + 1
      local ok, trainName = try(EEPRollingstockGetTrainName, list[trainCursor])
      if ok and type(trainName) == "string" and trainName ~= "" then addAuto("trains", trainName) end
    end
  end

  if config.autoRollingstock then
    for _, train in ipairs(registry.trains) do
      local count = try(EEPGetRollingstockItemsCount, train)
      if type(count) == "number" and count > 0 and vehicleCount[train] ~= count then
        vehicleCount[train] = count
        for i = 0, count - 1 do addAuto("rollingstock", try(EEPGetRollingstockItemName, train, i)) end
      end
    end
  end
end

-- Handler fuer EEP-Rueckruffunktionen (koennen auch von Hand aus eigenen Funktionen aufgerufen werden)
function M.onTrainStoppedOnSignal(signalId, trainName)
  if config.autoTrains then addAuto("trains", trainName) end
end

function M.onTrainEnterTrainyard(depotId, trainName)
  if config.autoTrains then addAuto("trains", trainName) end
end

function M.onTrainExitTrainyard(depotId, trainName)
  if config.autoTrains then addAuto("trains", trainName) end
end

function M.onTrainCoupling(movingTrainName, standingTrainName, combinedTrainName)
  if config.autoTrains then addAuto("trains", combinedTrainName) end
end

function M.onTrainLooseCoupling(retainedTrainName, detachedTrainName, originalTrainName)
  if config.autoTrains then
    addAuto("trains", retainedTrainName)
    addAuto("trains", detachedTrainName)
  end
end

-- Handler fuer das Speichern der Anlage
local function nowSeconds()
  if type(os) == "table" and type(os.time) == "function" then return os.time() end
  return nil
end

function M.onBeforeSaveAnl()
  paused = true
  pausedSince = nowSeconds()
end

function M.onSaveAnl(projectPath)
  if type(projectPath) == "string" and projectPath ~= "" then savedPath = projectPath end
  paused = false
  pausedSince = nil
  lastExport = nil   -- nach dem Speichern zeitnah neu exportieren
end

--- true, solange der Export wegen eines laufenden Speichervorgangs ausgesetzt ist.
function M.isExportPaused()
  if not paused then return false end
  
  local timeout, now = config.saveTimeout, nowSeconds()
  if timeout and timeout > 0 and pausedSince and now and now - pausedSince > timeout then
    paused = false      -- EEPOnSaveAnl blieb aus: Pause beenden
    pausedSince = nil
    return false
  end
  return true
end

--- Haengt die Handler an die globalen EEP-Rueckruffunktionen. Bereits vorhandene Funktionen
--- des Hauptskripts bleiben erhalten und werden danach aufgerufen. Deshalb erst NACH deren
--- Definition aufrufen (am Ende des Skripts); sonst ueberschreibt die spaetere Definition den Handler.
function M.installCallbacks()
  if callbacksInstalled then return end
  callbacksInstalled = true

  local function chain(name, handler)
    local previous = _G[name]
    _G[name] = function(...)
      pcall(handler, ...)
      if previous then return previous(...) end
    end
  end
  
  chain("EEPOnTrainStoppedOnSignal", M.onTrainStoppedOnSignal)
  chain("EEPOnTrainEnterTrainyard",  M.onTrainEnterTrainyard)
  chain("EEPOnTrainExitTrainyard",   M.onTrainExitTrainyard)
  chain("EEPOnTrainCoupling",        M.onTrainCoupling)
  chain("EEPOnTrainLooseCoupling",   M.onTrainLooseCoupling)
  chain("EEPOnBeforeSaveAnl",        M.onBeforeSaveAnl)
  chain("EEPOnSaveAnl",              M.onSaveAnl)
end

--- Automatische Initialisierung beim ersten run(): Callbacks erweitern und, falls nichts angemeldet
--- wurde, Signale/Weichen (1..discoverMax) bzw. Depots (1..discoverDepotMax) suchen.
local function hasPending(key)
  for _, job in ipairs(pending) do
    if job.key == key then return true end
  end
  return false
end

local function autoInit()
  if initialized then return end
  initialized = true

  if config.installCallbacks then M.installCallbacks() end

  local function discoverIfEmpty(key, max)
    if (max or 0) > 0 and #categories[key].list == 0 and not hasPending(key) then
      queue(key, nil)
    end
  end
  discoverIfEmpty("signals",  config.discoverMax)
  discoverIfEmpty("switches", config.discoverMax)
  discoverIfEmpty("depots",   config.discoverDepotMax)
end

-- ---------------------------------------------------------------------------------------------
-- Einzel-Erfassung
-- ---------------------------------------------------------------------------------------------
local function collectGlobal()
  local g = {
    eepVersion = EEPVer,
    language   = EEPLng,
    time       = { seconds = EEPTime, hour = EEPTimeH, minute = EEPTimeM, second = EEPTimeS },
    timeLapse  = try(EEPGetTimeLapse) or nil,              -- Verfuegbar ab EEP 17.2 - Plugin 2 (nicht in 17.3)
    fps        = try(EEPGetFramesPerSecond) or nil,        -- Verfuegbar ab EEP 17.2 - Plugin 2 (nicht in 17.3)
    season     = try(EEPGetSeason) or nil,                 -- Verfuegbar ab EEP 17.2 - Plugin 2 (nicht in 17.3)
    plant      = {
      name     = try(EEPGetAnlName) or nil,                -- Verfuegbar ab EEP 17.1 - Plugin 1 (nicht in 17.3)
      path      = savedPath,                               -- aus EEPOnSaveAnl (inkl. Dateiname)
      directory = try(EEPGetAnlPath) or nil,               -- Anlagenordner (ohne Dateiname), verfuegbar ab EEP 18.1 - Plugin 1
      version  = try(EEPGetAnlVer) or nil,                 -- Verfuegbar ab EEP 17
      language = try(EEPGetAnlLng) or nil,                 -- Anlagensprache in Bezug auf Achsen, Verfuegbar ab EEP 17
    },
    weather = {
      cloudsMode      = try(EEPGetCloudsMode) or nil,      -- Verfuegbar ab EEP 17.1 - Plugin 1 (nicht in 17.3)
      cloudsIntensity = try(EEPGetCloudsIntensity) or nil, -- Verfuegbar ab EEP 16.1 - Plugin 1
      wind            = try(EEPGetWindIntensity) or nil,   -- Verfuegbar ab EEP 16.1 - Plugin 1
      rain            = try(EEPGetRainIntensity) or nil,   -- Verfuegbar ab EEP 16.1 - Plugin 1
      snow            = try(EEPGetSnowIntensity) or nil,   -- Verfuegbar ab EEP 16.1 - Plugin 1
      hail            = try(EEPGetHailIntensity) or nil,   -- Verfuegbar ab EEP 16.1 - Plugin 1
      fog             = try(EEPGetFogIntensity) or nil,    -- Verfuegbar ab EEP 16.1 - Plugin 1
    },
  }
  
  -- Ermittelt die Position der aktuellen Kamera
  local ok, x, y, z = try(EEPGetCameraPosition)            -- Verfuegbar ab EEP 16.1 - Plugin 1 
  if ok then g.cameraPosition = { x = x, y = y, z = z } end
  
  -- Ermittelt die Ausrichtung der aktuellen Kamera
  local ok2, rx, ry, rz = try(EEPGetCameraRotation)        -- Verfuegbar ab EEP 16.1 - Plugin 1
  if ok2 then g.cameraRotation = { x = rx, y = ry, z = rz } end
  
  -- Ermittelt, welcher "Fahrzeugverband" derzeit im Steuerdialog ausgewaehlt ist
  local activeTrain = try(EEPGetTrainActive)               -- Verfuegbar ab EEP 15 - Plugin 1
  if activeTrain and activeTrain ~= "" then 
    g.activeTrain = activeTrain
    if config.autoTrains then addAuto("trains", activeTrain) end  
  end

  -- Ermittelt, welches Fahrzeug derzeit im Steuerdialog ausgewaehlt ist
  local activeRollingstock = try(EEPRollingstockGetActive) -- Verfuegbar ab EEP 15 - Plugin 1
  if activeRollingstock and activeRollingstock ~= "" then g.activeRollingstock = activeRollingstock  end
  
  return g
end

-- Signale
local function collectSignal(id)
  local s = { state = try(EEPGetSignal, id) or nil }

  -- STATIC: je Feld nur einmal ermitteln (Fehlschlaege werden beim naechsten Export erneut versucht)
  local cache = staticCache.signals
  local count = cachedStatic(cache, id, "functionCount", EEPGetSignalFunctions, id) -- AB EEP 17.3 Plug-in 3
  local itemName = cachedStatic(cache, id, "itemName", EEPGetSignalItemName, id)    -- AB EEP 17.3 Plug-in 3
  s.functionCount = count
  if itemName ~= "" then s.itemName = itemName end

  -- Stellungstexte: erst ablegen, wenn alle Funktionen gelesen werden konnten
  local st = cache[id]
  if type(count) == "number" and count > 0 and st.functions == nil then
    local functions = {}
    for i = 1, count do
      local okF, position, text = try(EEPGetSignalFunction, id, i)  -- AB EEP 17.3 Plug-in 3
      if okF then functions[#functions + 1] = { index = i, position = position, text = text } end
    end
    if #functions == count then
      st.functions = functions
      if config.debug then
        print(string.format("EepExport: Signal %s: %s, %d Stellungen gelesen", tostring(id), tostring(itemName), count))
      end
    end
  end
  s.functions = st and st.functions or nil
	
	
-- Simulation weil die Funktionen in meiner EEP-Version noch nicht zur Verfügung stehen
-- Anlage: Einsteigen
if id == 21 then
	s.functionCount = 3
	s.itemName = "HpSig_E_V40_69_V7"
	s.functions = { 
		{ index = 1, position = 2,    text = "Halt" }, 
		{ index = 2, position = 1,    text = "Fahrt" }, 
		{ index = 3, position = 1040, text = "Fahrt mit 40kmh" }, 
	}
end
if id == 32 then
	s.functionCount = 4
	s.itemName = "HpSig_A_V40_69_V7"
	s.functions = { 
		{ index = 1, position = 2,    text = "Halt" }, 
		{ index = 2, position = 1,    text = "Fahrt" }, 
		{ index = 3, position = 1040, text = "Fahrt mit 40kmh" }, 
		{ index = 4, position = 999,  text = "Sh1 - Rangierfahrt" }, 
	}
end


  local n = try(EEPGetSignalTrainsCount, id)
  if n then
    s.trainsCount = n
    local names = {}
    for i = 1, n do
      local name = try(EEPGetSignalTrainName, id, i)
      if name then names[#names + 1] = name end
    end
    s.trains = names
  end

  local okD, dist = try(EEPGetSignalStopDistance, id)
  if okD then s.stopDistance = dist end

  local okT, tag = try(EEPSignalGetTagText, id)
  if okT and tag ~= "" then s.tag = tag end

  return s
end

-- Weichen
local function collectSwitch(id)
  local s = { state = try(EEPGetSwitch, id) or nil }
  
  local okT, tag = try(EEPSwitchGetTagText, id)
  if okT and tag and tag ~= "" then s.tag = tag end
  
  return s
end

-- Depots
local function collectDepot(id)
  local count = try(EEPGetTrainyardItemsCount, id)
  if not count then return { exists = false } end
  local d = { exists = true, itemCount = count, items = {} }
  
  for slot = 1, count do
    local name = try(EEPGetTrainyardItemName, id, slot)
    if name and name ~= "" then
      d.items[#d.items + 1] = {
        slot   = slot,
        name   = name,
        status = try(EEPGetTrainyardItemStatus, id, name, 0) or nil, -- 0 = in Fahrt, 1 = im Depot wartend
      }
    end
  end
  
  return d
end
  
-- Fahrwege
local function collectTrack(isReservedFn, id)
  local ok, occupied = try(isReservedFn, id)
  if not ok then return { exists = false } end
  local t = { occupied = occupied and true or false }
  
  if occupied then
    local ok1, _, name = try(isReservedFn, id, true)
    if ok1 and name and name ~= "" then t.frontTrain = name end
  end
  
  return t
end

-- Züge
-- rsMap: bereits gesammelte Rollmaterialdaten (Name -> Daten) dieses Exports. Position und Gleis des ersten
-- Fahrzeugs werden daraus uebernommen (gleicher Zeitpunkt, keine zusaetzliche EEP-Abfrage).
local function collectTrain(name, rsMap)
  local okS, speed = try(EEPGetTrainSpeed, name) -- aktuelle Geschwindigkeit
  if not okS then
    -- Zug existiert evtl. nur im Depot
    local okY, depot = try(EEPIsTrainInTrainyard, name)
    if okY then return { exists = true, trainyard = depot } end
    return { exists = false }
  end
  local t = { exists = true, speed = speed }
  
  local okT, target = try(EEPGetTrainSpeed, name, true) -- Sollgeschwindigkeit
  if okT then t.targetSpeed = target end
  
  local okR, route = try(EEPGetTrainRoute, name)
  if okR then t.route = route end
  
  local okL, len = try(EEPGetTrainLength, name)
  if okL then t.length = len end
  
  local okLi, light = try(EEPGetTrainLight, name) -- verfügbar ab EEP 18.0
  if okLi then t.light = light end
  
  local okCf, cf = try(EEPGetTrainCouplingFront, name) -- verfügbar ab EEP 18.0
  if okCf then t.couplingFront = cf end
  
  local okCr, cr = try(EEPGetTrainCouplingRear, name) -- verfügbar ab EEP 18.0
  if okCr then t.couplingRear = cr end
  
  local okY, depot = try(EEPIsTrainInTrainyard, name)
  if okY then t.trainyard = depot end
  
  -- Die Fahrzeugliste wird bei jedem Export frisch gelesen: Kuppeln und Trennen kann an jeder
  -- Stelle des Zuges geschehen, die Zusammensetzung laesst sich nicht aus wenigen Werten ableiten.
  local count = try(EEPGetRollingstockItemsCount, name)
  if count then
    t.vehicleCount = count
    local vehicles = {}
    for i = 0, count - 1 do
      local vname = try(EEPGetRollingstockItemName, name, i)
      if vname and vname ~= "" then
        vehicles[#vehicles + 1] = vname
        -- unbekannte Fahrzeuge sofort aufnehmen (nur eine Mengenabfrage, solange sie bekannt sind)
        if config.autoRollingstock then addAuto("rollingstock", vname) end
      end
    end
    t.vehicles = vehicles
    
    -- Position des Zuges = Position des ersten Fahrzeugs
    local first = vehicles[1]
    if first then
      local rs = rsMap and rsMap[first]
      if rs and rs.exists then
        t.position, t.track = rs.position, rs.track
      else
        local okP, x, y, z = try(EEPRollingstockGetPosition, first)
        if okP then t.position = { x = x, y = y, z = z } end
        
        local okTr, trackId, pos, dir, system = try(EEPRollingstockGetTrack, first)
        if okTr then t.track = { id = trackId, position = pos, direction = dir, system = system } end
      end
    end
  end
  
  return t
end

-- Rollmaterialien
local function collectRollingstock(name)
  local ok, trainName = try(EEPRollingstockGetTrainName, name)
  if not ok then return { exists = false } end
  local r = { exists = true, train = trainName }
  
  local okP, x, y, z = try(EEPRollingstockGetPosition, name)
  if okP then r.position = { x = x, y = y, z = z } end
  
  local okR, rx, ry, rz = try(EEPRollingstockGetRotation, name) -- verfügbar ab EEP 18.1 Plugin 1
  if okR then r.rotation = { x = rx, y = ry, z = rz } end
  
  -- Abstand (in Meter) zum Anfang des Gleisstücks, auf dem sich das Fahrzeug befindet.
  -- Ausrichtung relativ zur Fahrtrichtung des Gleisstücks, auf dem sich das Fahrzeug befindet:
  --   1 = in Fahrtrichtung,
  --   0 = entgegen der Fahrtrichtung.
  -- Systemnummer des Gleises, auf dem das Fahrzeug unterwegs ist:
  --   1 = Bahngleise,
  --   2 = Straße,
  --   3 = Straßenbahngleise,
  --   4 = sonstige Splines / Wasserwege
  local okT, trackId, pos, dir, system = try(EEPRollingstockGetTrack, name)
  if okT then r.track = { id = trackId, position = pos, direction = dir, system = system } end
  
  -- STATIC Länge des Fahrzeugs von Kupplung zu Kupplung in Meter
  r.length = cachedStatic(staticCache.rollingstock, name, "length", EEPRollingstockGetLength, name)
                                

  -- STATIC Anzahl der Getriebegaenge (0 = nicht motorisiert)
  r.gears = cachedStatic(staticCache.rollingstock, name, "gears", EEPRollingstockGetMotor, name)

  -- STATIC ModelType DE / EN
  -- 1 = Tenderlok / tank locomotive
  -- 2 = Schlepptenderlok / tender locomotive
  -- 3 = Tender / tender
  -- 4 = Elektrolok / electric locomotive
  -- 5 = Diesellok / diesel locomotive
  -- 6 = Triebwagen / railcar
  -- 7 = U- oder S-Bahn / communter train
  -- 8 = Straßenbahn / tram
  -- 9 = Güterwaggon / freight waggons
  -- 10 = Personenwaggon / person transport
  -- 11 = Luftfahrzeug / aero vehicles
  -- 12 = Maschine (z.B. Kran) / machines (e.g. cranes)
  -- 13 = Wasserfahrzeug / ships
  -- 14 = LKW / trucks
  -- 15 = PKW / cars
  r.modelType = cachedStatic(staticCache.rollingstock, name, "modelType", EEPRollingstockGetModelType, name)
  
  -- zurückgelegte Strecke des Rollmaterials seit dem Einsetzen in EEP
  local okKm, mileage = try(EEPRollingstockGetMileage, name)
  if okKm then r.mileage = mileage end
  
  -- true, wenn wenn das angegebene Fahrzeug vorwärts ausgerichtet ist, sonst false
  local okO, forward = try(EEPRollingstockGetOrientation, name)
  if okO then r.forward = forward end
  
  -- Stellung der Kupplung
  -- 1 = Kupplung scharf / active
  -- 2 = Abstoßen / inactive
  -- 3 = Gekuppelt / coupled
  local okF, cf = try(EEPRollingstockGetCouplingFront, name)
  if okF then r.couplingFront = cf end
  
  local okB, cr = try(EEPRollingstockGetCouplingRear, name)
  if okB then r.couplingRear = cr end
  
  -- true, wenn der Rauch an-, oder false, wenn der Rauch ausgeschaltet ist
  local okS, smoke = try(EEPRollingstockGetSmoke, name)
  if okS then r.smoke = smoke end
  
  -- Status des Hakens
  -- 0 = ausgeschaltet,
  -- 1 = eingeschaltet
  -- 3 = Ladegut am Haken
  local okH, hook = try(EEPRollingstockGetHook, name)
  if okH then r.hook = hook end
  
  local okTag, tag = try(EEPRollingstockGetTagText, name)
  if okTag and tag ~= "" then r.tag = tag end
  
  return r
end

-- Immobilien
local function collectStructure(name)
  local okP, x, y, z = try(EEPStructureGetPosition, name)
  if not okP then return { exists = false } end
  local s = { exists = true, position = { x = x, y = y, z = z } }
  
  local okR, rx, ry, rz = try(EEPStructureGetRotation, name)
  if okR then s.rotation = { x = rx, y = ry, z = rz } end
  
	-- STATIC
  s.modelType = cachedStatic(staticCache.structures, name, "modelType", EEPStructureGetModelType, name)
  
  local okS, smoke = try(EEPStructureGetSmoke, name)
  if okS then s.smoke = smoke end
  
  local okL, light = try(EEPStructureGetLight, name)
  if okL then s.light = light end
  
  local okF, fire = try(EEPStructureGetFire, name)
  if okF then s.fire = fire end
  
  local okT, tag = try(EEPStructureGetTagText, name)
  if okT and tag ~= "" then s.tag = tag end
  
  return s
end

-- Güter
local function collectGoods(name)
  local okP, x, y, z = try(EEPGoodsGetPosition, name)
  if not okP then return { exists = false } end
  local g = { exists = true, position = { x = x, y = y, z = z } }
  
  local okR, rx, ry, rz = try(EEPGoodsGetRotation, name)
  if okR then g.rotation = { x = rx, y = ry, z = rz } end
  
	-- STATIC
  g.modelType = cachedStatic(staticCache.goods, name, "modelType", EEPGoodsGetModelType, name)
  
  local okT, tag = try(EEPGoodsGetTagText, name) -- Ab EEP 18.0
  if okT and tag ~= "" then g.tag = tag end
  
  return g
end

-- Wetterzonen
local function collectZone(id)
  local okP, x, y, z, radius = try(EEPGetZonePos, id)
  if not okP then return { exists = false } end
  local zone = { exists = true, position = { x = x, y = y, z = z }, radius = radius }
  
  local _, wind   = try(EEPGetZoneWindIntensity, id)
  local _, rain   = try(EEPGetZoneRainIntensity, id)
  local _, snow   = try(EEPGetZoneSnowIntensity, id)
  local _, hail   = try(EEPGetZoneHailIntensity, id)
  local _, fog    = try(EEPGetZoneFogIntensity, id)
  local _, clouds = try(EEPGetZoneClouds, id)
  zone.wind, zone.rain, zone.snow, zone.hail, zone.fog, zone.clouds =
    wind or nil, rain or nil, snow or nil, hail or nil, fog or nil, clouds or nil
    
  return zone
end

--- Erzeugt aus einer Liste einen nach Schluessel (als String) indizierten Objekt-Eintrag.
local function collectMap(list, fn)
  local out = {}
  for _, key in ipairs(list) do
    out[tostring(key)] = fn(key)
  end
  return out
end

-- ---------------------------------------------------------------------------------------------
-- Oeffentliche API
-- ---------------------------------------------------------------------------------------------

--- Setzt Konfigurationswerte. Beispiel: EepExport.configure({ interval = 10, pretty = true })
function M.configure(options)
  for k, v in pairs(options or {}) do config[k] = v end
  -- Bei geaenderter anl3-Datei bzw. geaendertem gbsTracks die Datei erneut lesen
  if options and (options.anlFile ~= nil or options.gbsTracks ~= nil) then anlLoaded = nil end
end

--- Sammelt alle Zustandsdaten und gibt sie als Tabelle zurueck.
function M.collect()
  M.resolve()               -- Ermittelt den Status der registrierten Objekte
  scanForTrains()           -- Suche nach neuen Zuegen
                                                                     
                                                                                 
  
  local data = {}
  data.meta = { exportedAtEepTime = EEPTime } -- oder string.format("%02d:%02d:%02d", EEPTimeH, EEPTimeM, EEPTimeS)}
  if config.global then data.global = collectGlobal() end
  -- Kameras (statisch, aus der anl3-Datei): Name -> { dynamic = true|false }; Aufruf mit EEPSetCamera(0|1, Name)
  if cameraList then data.cameras = cameraList end
  data.signals      = collectMap(registry.signals, collectSignal)
  data.switches     = collectMap(registry.switches, collectSwitch)
  data.trainyards   = collectMap(registry.depots, collectDepot)
  data.structures   = collectMap(registry.structures, collectStructure)
  data.goods        = collectMap(registry.goods, collectGoods)
  data.weatherZones = collectMap(registry.zones, collectZone)
  data.tracks = {
    rail      = collectMap(registry.railTracks,    function(id) return collectTrack(EEPIsRailTrackReserved, id) end),
    road      = collectMap(registry.roadTracks,    function(id) return collectTrack(EEPIsRoadTrackReserved, id) end),
    tram      = collectMap(registry.tramTracks,    function(id) return collectTrack(EEPIsTramTrackReserved, id) end),
    auxiliary = collectMap(registry.auxTracks,     function(id) return collectTrack(EEPIsAuxiliaryTrackReserved, id) end),
    control   = collectMap(registry.controlTracks, function(id) return collectTrack(EEPIsControlTrackReserved, id) end),
  }

  -- Rollmaterial zuerst: collectTrain uebernimmt daraus Position und Gleis des ersten Fahrzeugs
  data.rollingstock = collectMap(registry.rollingstock, collectRollingstock)
  data.trains       = collectMap(registry.trains, function(name) return collectTrain(name, data.rollingstock) end)

  -- Fahrzeuge, die collectTrain gerade neu aufgenommen hat, noch im selben Export erfassen
  for _, vname in ipairs(registry.rollingstock) do
    local key = tostring(vname)
    if data.rollingstock[key] == nil then data.rollingstock[key] = collectRollingstock(vname) end
  end

  -- Automatisch aufgenommene Zuege/Fahrzeuge entfernen, die es nicht mehr gibt (aus den gesammelten Daten)
  pruneMissing("trains", data.trains)
  pruneMissing("rollingstock", data.rollingstock)
  return data
end

--- Ermittelt den Ausgabepfad.
local function outputPath()
  if config.outputFile then return config.outputFile end
  
  local base = try(EEPGetAnlPath)
  if (not base or base == "") and savedPath then
    base = savedPath:match("^(.*)[/\\\\][^/\\\\]*$")   -- Ordner aus dem in EEPOnSaveAnl gemerkten Pfad
  end
  if base and base ~= "" then return base .. "\\exchange\\eep_export.json" end
  return "exchange\\eep_export.json"
end

--- Sammelt die Daten und schreibt sie als JSON-Datei. Gibt true, Pfad oder false, Fehlermeldung zurueck.
function M.export()
  if M.isExportPaused() then
    return false, "Export pausiert (Anlage wird gespeichert)"
  end

  -- Setzt M.lastError und liefert false, Fehlermeldung
  local function fail(message, path)
    M.lastError = message
    if config.debug then
      print(string.format(
        "EepExport.export um %02d:%02d:%02d%s, %s",
        EEPTimeH, EEPTimeM, EEPTimeS,
        path and (", file " .. path) or "",
        message
      ))
    end
    return false, message
  end

  local s0 = os.clock()

  -- Aktuelle Daten sammeln
  local okCollect, data = pcall(M.collect)
  if not okCollect then
    return fail("EepExport.export: Daten sammeln fehlgeschlagen: " .. tostring(data))
  end

  local s1 = os.clock()

  -- Umwandlung der Daten in JSON
  local okJson, json = pcall(M.toJson, data, config.pretty)
  if not okJson then
    return fail("EepExport.export: JSON-Erzeugung fehlgeschlagen: " .. tostring(json))
  end

  local s2 = os.clock()

  -- Datei schreiben
  local path = outputPath()
  local file, err, errnum = io.open(path, "w") -- w write, a append
  if not file then
    return fail("EepExport.export: Datei nicht schreibbar: " .. tostring(err) .. " " .. tostring(errnum), path)
  end
  local okWrite, writeErr = file:write(json)
  file:close()
  if not okWrite then
    return fail("EepExport.export: Schreiben fehlgeschlagen: " .. tostring(writeErr), path)
  end

  local s3 = os.clock()

  if config.debug then
    print(string.format(
      "EepExport.export um %02d:%02d:%02d, file %s, collect %.1f ms, json %.1f ms length %d, write %.1f ms",
      EEPTimeH, EEPTimeM, EEPTimeS,
      path,
      (s1 - s0) * 1000,        -- collect
      (s2 - s1) * 1000, #json, -- json
      (s3 - s2) * 1000         -- write
    ))
  end

  M.lastError = nil
  lastExport = EEPTime
  return true, path
end

--- In EEPMain() aufrufen. Exportiert automatisch im eingestellten Intervall (EEP-Zeit).
function M.run()
  local okPrepare, prepareErr = pcall(function()
    autoInit()
    M.resolve()

    if lastScan == nil or EEPTime < lastScan or EEPTime - lastScan >= (config.scanInterval or 2) then
      lastScan = EEPTime
      scanForTrains()
    end
  end)
  if not okPrepare then
    M.lastError = "EepExport.run: Suche nach Objekten fehlgeschlagen: " .. tostring(prepareErr)
    if config.debug then print(M.lastError) end
  end
  
  if not config.interval or config.interval < 0 then return end
  
  -- Die ID-Suche laeuft noch (auf mehrere Aufrufe verteilt): erst exportieren, wenn alles gefunden wurde,
  -- damit keine unvollstaendigen Daten geschrieben werden.
  if #pending > 0 then return end
  
  if M.isExportPaused() then return end
  
  if lastExport == nil or config.interval == 0 or EEPTime < lastExport or EEPTime - lastExport >= config.interval then
    local ok, msg = M.export()
    if not ok then
      lastExport = EEPTime  -- Fehlermeldung nicht mit jedem Zyklus wiederholen
      print("EepExport: ", msg)
    end
  end
end


return M
