# -*- coding: utf-8 -*-
"""Rail_Maps - a library of Railway Rivals maps: many versions per map, one web page (basic / advanced / detailed).

ALL TEXT INSIDE THIS PROGRAM IS ENGLISH (rule 01_CORE item 1).
Version 1.0 (2026-11-08).  Work copy; Lars copies it to the Py folder himself.
2026-11-17: Examples page (examples.html, pictures made with PicturePerfect, DEL 26d).
2026-11-16: Timeline (tab + page view), Look (black & white / hand-coloured / printed in colour), "What was done" per version, COPIES
(more photos of one draft are not new versions), other codes per map (DEL 21d, 30e).
"""
import os, sys, re, json, copy, time, shutil, html, string, queue, difflib, datetime, threading, traceback, unicodedata, tarfile, tempfile, zlib
import concurrent.futures, urllib.request, urllib.error
import ctypes, platform, subprocess, webbrowser
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, filedialog, messagebox


# *************** DEL XX - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copy verbatim into every program.  Rules, tree and table: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.
#
# Needs:  import os, sys


def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico


# *************** DEL XX - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn


# *************** DEL XX - OPEN THINGS WITH MY OWN PROGRAMS *******************
# Copy verbatim.  A link, folder, PDF, log or image opened from here lands in MY
# programs, not in Edge / Explorer / Notepad / Adobe.  Rules and the reasons
# behind them: 20_open_with_my_programs.md
#
# Which program opens WHAT is decided in ONE file, never in code:
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
# _FALLBACK_KINDS is used only when that file cannot be read.
#
# Three rules this block must never break:
#   1. It may NEVER raise (Help must open even if WhyBrowse or the table is gone).
#   2. It may NEVER hand a thing to ITSELF (that is how you build a loop).
#   3. Popen, never run() (run() would freeze this program).
# And NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it starts another copy of this program (fork bomb, 2026-09-04).
#
# The table is read ONCE, the first time something is opened - not at start-up.
#
# Needs:  import os, sys, json, shutil, subprocess, webbrowser
#         block_home.py  (_program_home, PROGRAM_NAME)

MY_PROGRAM_NAME = PROGRAM_NAME

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the other programs: a music
    program's home is 1---Musik, and Chess / Foul_bridge / Quiz_manager /
    Railroad_racing are their own worlds - none of those has a WhyBrowse or a
    DefaultHub.  So after its own home this walks UP, four levels, like
    _find_home."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - not an
    interpreter - and which() finds it first wherever the Store stub is on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, a build is only the fallback: the .py is the file that is
    actually edited, so it is always current, while a build can be days old
    (2026-09-05: File_manager's build had no command-line handling at all).
    A build is used only when there is no source or no interpreter."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# *************** DEL 05b - OPEN A MAP FILE (OWN TEXT TYPES) *****************
# ToDo: .places / .comments / .invalid_races are plain text but DefaultHub's table does not list those endings, so Windows would
# decide.  They are opened with whatever program DefaultHub gives to ordinary text files (Meditor), like pictures and PDFs.
_TEXTLIKE = re.compile(r"\.(places|comments\d*|invalid_races)$", re.I)


def _launch_my_app_flags(name: str, flags: list, argument) -> bool:
    """Like _launch_my_app but with command-line flags before the file (SeeView: --new = this file in a window of its own).
    Same rules: the .py wins, a build is the fallback, never hands a thing to itself, Popen never run, never raises."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False
    cmd = work = None
    try:
        for home in _my_app_roots():
            script = os.path.join(home, "Py", name + ".py")
            exe = os.path.join(home, "Folder-exe", name, name + ".exe")
            if os.path.isfile(script):
                pyw = _real_pythonw()
                if pyw:
                    cmd, work = [pyw, script] + list(flags) + [str(argument)], os.path.dirname(script)
                    break
            if os.path.isfile(exe):
                cmd, work = [exe] + list(flags) + [str(argument)], os.path.dirname(exe)
                break
            if os.path.isfile(script):
                break
        if not cmd:
            return False
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_map_file(path) -> None:
    """Open a map file with the program DefaultHub gives it.  A picture goes to SeeView with --new, so every picture gets its OWN
    window and two maps can be compared (without it SeeView hands the picture to the window that is already open and replaces
    the one before - found 2026-11-08)."""
    p = str(path or "")
    if p and _TEXTLIKE.search(p) and os.path.isfile(p):
        try:
            if _launch_my_app(_target_for("x.txt"), p):
                return
        except Exception:
            pass
    if p and os.path.isfile(p) and os.path.splitext(p)[1].lower() in IMG_EXT_OWN_WINDOW:
        try:
            if _target_for(p).lower() == "seeview" and _launch_my_app_flags("SeeView", ["--new"], p):
                return
        except Exception:
            pass
    open_path(p)


IMG_EXT_OWN_WINDOW = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".tif", ".tiff")


# *************** DEL XX - WINDOW ICON (EXTERNAL .ICO) ************************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL XX - ABOUT DIALOG (TEMPLATE) ****************************
# A TEMPLATE, not verbatim: adapt look / colours / emoji / name to the program,
# but KEEP THE MESSAGE (creator, documentation link, small gift).
# NOT for games - games never carry anything tied to me (see 40_games.md; they
# name the designers instead).
#
# Rules: About closes with ESC; Toplevel order grab_set(), focus_force(), <Escape>
# (make_modal does it).  Links open through open_url(), never webbrowser directly.
# The program NAME shown here has no "Issu" part (Issus, Issu's ...); only the
# creator line keeps Lars "Issu" Olsson.
#
# Needs:  import tkinter as tk
#         block_ui_helpers.py (make_modal)   block_open.py (open_url)
#
# Call:   show_about(root, "MyProgram", "What it is, in one line", "🏢")
# Change the colours by passing colors={...} that match the program's palette.

DOC_URL     = ("https://docs.google.com/document/d/"
               "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL  = "https://paypal.me/issusbarn"
WISE_URL    = "https://wise.com/pay/me/larsdenniso"

ABOUT_COLORS = dict(bg="#1e1e2e", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa",
                    sep="#3a3a4e", box="#252535", hover="#b4d4ff")


def show_about(root, app_name, tagline, emoji="🏢", colors=None):
    """Stylish About dialog with documentation link and donation info."""
    c = {**ABOUT_COLORS, **(colors or {})}

    top = tk.Toplevel(root)
    top.title("About " + app_name)
    top.configure(bg=c["bg"])
    top.resizable(False, False)
    top.transient(root)
    make_modal(top)                              # grab_set, focus_force, Escape

    # Header
    hdr = tk.Frame(top, bg=c["bg"])
    hdr.pack(fill="x")
    tk.Label(hdr, text=emoji, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 36)).pack(pady=(18, 0))
    tk.Label(hdr, text=app_name, bg=c["bg"], fg=c["accent"],
             font=("Segoe UI", 20, "bold")).pack()
    tk.Label(hdr, text=tagline, bg=c["bg"], fg=c["dim"],
             font=("Segoe UI", 9, "italic")).pack(pady=(2, 10))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20)

    # Creator
    tk.Label(top, text='Created by  Lars "Issu" Olsson', bg=c["bg"], fg=c["fg"],
             font=("Segoe UI", 10, "bold")).pack(pady=(14, 0))

    def link(parent, text, url, size=9, **pack):
        lbl = tk.Label(parent, text=text, bg=parent.cget("bg"), fg=c["accent"],
                       font=("Segoe UI", size, "underline"), cursor="hand2")
        lbl.pack(**pack)
        lbl.bind("<Button-1>", lambda e: open_url(url))
        lbl.bind("<Enter>",    lambda e: lbl.configure(fg=c["hover"]))
        lbl.bind("<Leave>",    lambda e: lbl.configure(fg=c["accent"]))
        return lbl

    link(top, "📄  View documentation", DOC_URL, pady=(6, 2))
    tk.Frame(top, bg=c["sep"], height=1).pack(fill="x", padx=20, pady=(14, 0))

    # Donation
    # Lars's wording since 2026-11-07 (rule 30): ENGLISH in every language, the wordplay focUSing on US / focuSING cha-CHING
    tk.Label(top, text="Focusing on us instead of cha-ching\nbut if you like " + app_name +
                       ", you are welcome to send a token of appreciation",
             bg=c["bg"], fg=c["dim"], font=("Segoe UI", 8, "italic"),
             wraplength=300, justify="center").pack(pady=(10, 6))
    box = tk.Frame(top, bg=c["box"], padx=16, pady=10)
    box.pack(fill="x", padx=20, pady=(0, 6))
    for text, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                      ("Wise", WISE_URL)):
        link(box, text, url, pady=1)

    tk.Button(top, text="Close", width=10, command=top.destroy).pack(pady=(8, 16))
    return top


# *************** DEL xx - TOOL POPUPS: MOVABLE, ZOOMABLE, NON-MODAL **********
# block_popups.py - copy verbatim into a program (needs: import os, tkinter as tk,
# tkinter.font as tkfont).  Two parts:
#
#   ToolPopup   a window beside the main window that you can DRAG, ZOOM (the
#               [-] 100% [+] bar, or Ctrl+mouse wheel), and close with Esc.
#               Position, zoom and "is it open" live in the PROGRAM'S OWN
#               settings dict (`store`), under three key names the program
#               picks - so they survive a restart.  Subclass it and write
#               build(self, s): s is the zoom as a float (1.0 = 100 %).  Draw
#               into self.body, or call self.canvas_area(w, h) and draw on the
#               canvas it returns (it gets a scrollbar by itself when the
#               screen is too small for the whole thing).
#
#   PlayerTextPopup  the PLAYER'S OWN TEXT, written and saved inside the program
#               (tactics, house rules, "good to remember").  Every file
#               <Helpfiles>\<program>\Playertext-<name>.txt is one text; what
#               follows the prefix is what the drop-down offers; the chosen text
#               is shown in a box with scrollbars + mouse wheel and can be edited
#               right there (saved by itself a second after the last key, and
#               when the popup closes or another text is picked).  [New...]
#               starts another text.  Nothing is ever deleted by the program.
#               An empty text never creates a file.  Call .save_now() from the
#               program's own on_close.
#
# The program supplies:
#   store      its settings dict (mutated in place)
#   keys       (show_key, pos_key, zoom_key) for a ToolPopup, e.g. ("show_aid","popup_pos","popup_zoom");
#              (show_key, pos_key, zoom_key, sel_key) for PlayerTextPopup, e.g.
#              ("show_playertext","playertext_pos","playertext_zoom","playertext_sel")
#              NB: pick names that do not collide with a text-key prefix the
#              program's self-test scans for (a "aid_*" setting broke one).
#   on_change  callable that saves the settings (e.g. lambda: save_settings(S))
#   theme      dict: bg panel fg dim accent btn btnfg field field_fg
#   on_closed  callable run after the popup closed itself (tick boxes off ...)
#   on_key     optional; Space/Enter forwarded to the game ("Play").  NEVER for
#              the notes popup - it is typed into.
#
# Open it once at start-up for a game's aid (show_key true), open the player
# text from a menu / button.  The main window keeps working: nothing here grabs input.

POPUP_ZOOMS = (50, 60, 70, 80, 90, 100, 115, 130, 150)


def popup_lines(font, texts, width):
    """How many lines the LONGEST of `texts` needs at `width` px (greedy word
    wrap).  Gives a label one fixed height whatever the language
    (01_CORE item 6)."""
    best = 1
    for t in texts:
        lines = 0
        for para in t.split("\n"):
            cur, n = "", 1
            for w in para.split():
                trial = (cur + " " + w).strip()
                if cur and font.measure(trial) > width:
                    n += 1
                    cur = w
                else:
                    cur = trial
            lines += n
        best = max(best, lines)
    return best


class ToolPopup(object):
    resizable = False

    def __init__(self, root, store, keys, on_change, theme, title,
                 on_closed=None, on_key=None):
        self.root, self.store, self.theme = root, store, theme
        self.k_show, self.k_pos, self.k_zoom = keys
        self.on_change, self.on_closed = on_change, on_closed
        self.move_job = None
        self._cv = self._bar = None
        self._full_h = 0
        top = self.top = tk.Toplevel(root)
        top.title(title)
        top.configure(bg=theme["bg"])
        top.resizable(self.resizable, self.resizable)
        top.transient(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<Control-MouseWheel>",
                 lambda e: self.step(1 if e.delta > 0 else -1))
        if on_key:
            for key in ("<Return>", "<KP_Enter>", "<space>"):
                top.bind(key, lambda e: on_key())
        bar = self.toolbar = tk.Frame(top, bg=theme["panel"])
        bar.pack(fill="x")
        self._btn(bar, u"−", lambda: self.step(-1)).pack(
            side="left", padx=(6, 0), pady=3)
        self.lbl_zoom = tk.Label(bar, width=5, bg=theme["panel"],
                                 fg=theme["fg"], font=("Segoe UI", 9, "bold"))
        self.lbl_zoom.pack(side="left")
        self._btn(bar, "+", lambda: self.step(1)).pack(side="left")
        self._btn(bar, "100%", lambda: self.set_zoom(100), w=5).pack(
            side="left", padx=(6, 0))
        self.extra_toolbar(bar)
        self.body = tk.Frame(top, bg=theme["bg"])
        self.body.pack(fill="both", expand=True)
        self._rebuild()
        self._place(store.get(self.k_pos))
        top.bind("<Configure>", self._configured)

    # ---- for subclasses ------------------------------------------------------
    def build(self, s):
        raise NotImplementedError

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

    # ---- zoom ----------------------------------------------------------------
    def zoom(self):
        z = self.store.get(self.k_zoom, 100)
        return z if z in POPUP_ZOOMS else 100

    def step(self, d):
        i = POPUP_ZOOMS.index(self.zoom()) + d
        self.set_zoom(POPUP_ZOOMS[max(0, min(len(POPUP_ZOOMS) - 1, i))])

    def set_zoom(self, z):
        if z == self.zoom():
            return
        self.store[self.k_zoom] = z
        self.on_change()
        self._rebuild()
        self._place(self._where())          # the size changed: stay on screen

    def _btn(self, parent, text, cmd, w=3):
        th = self.theme
        return tk.Button(parent, text=text, command=cmd, width=w, bd=0,
                         relief="flat", bg=th["btn"], fg=th["btnfg"],
                         activebackground=th["accent"], takefocus=0,
                         cursor="hand2", font=("Segoe UI", 9, "bold"))

    def _rebuild(self):
        self.before_rebuild()
        for w in self.body.winfo_children():
            w.destroy()
        self._cv = None
        self.lbl_zoom.configure(text="%d%%" % self.zoom())
        self.build(self.zoom() / 100.0)
        self.top.update_idletasks()
        self._fit()

    # ---- a canvas that scrolls only when the screen is too small --------------
    def canvas_area(self, w, h):
        th = self.theme
        frame = tk.Frame(self.body, bg=th["bg"])
        frame.pack(padx=6)
        cv = tk.Canvas(frame, width=w, height=h, bg=th["bg"], bd=0,
                       highlightthickness=0, scrollregion=(0, 0, w, h))
        cv.pack(side="left")
        bar = tk.Scrollbar(frame, command=cv.yview, bg=th["panel"])
        cv.configure(yscrollcommand=bar.set)
        cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(
            -1 if e.delta > 0 else 1, "units"))
        self._cv, self._bar, self._full_h = cv, bar, h
        return cv

    def resize_canvas(self, h):
        """The drawing is finished and turned out `h` px high."""
        h = int(h)
        w = int(self._cv.cget("width"))
        self._cv.configure(height=h, scrollregion=(0, 0, w, h))
        self._full_h = h

    def _fit(self):
        cv = self._cv
        if cv is None:
            return
        cv.configure(height=self._full_h)
        self._bar.pack_forget()
        self.top.update_idletasks()
        excess = self.top.winfo_reqheight() - (self.top.winfo_screenheight() - 90)
        if excess > 0:
            cv.configure(height=max(240, self._full_h - excess))
            self._bar.pack(side="left", fill="y")

    # ---- position ------------------------------------------------------------
    def _where(self):
        return [self.top.winfo_x(), self.top.winfo_y()]

    def _place(self, pos):
        top, root = self.top, self.root
        top.update_idletasks()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        ok = (isinstance(pos, (list, tuple)) and len(pos) == 2
              and all(isinstance(v, int) for v in pos)
              and -w + 60 < pos[0] < sw - 60 and 0 <= pos[1] < sh - 60)
        if ok:
            x, y = pos
            x = min(x, max(0, sw - w)) if x + w > sw + 40 else x
        else:                               # default: right of the main window
            root.update_idletasks()
            x = root.winfo_x() + root.winfo_width() + 8
            y = root.winfo_y()
            if x + w > sw:                  # no room: hug the screen edge
                x = max(0, sw - w)
            y = max(0, min(y, sh - h - 40))
        top.geometry("+%d+%d" % (x, y))

    def _configured(self, event):
        if event.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(400, self._moved)

    def _moved(self):
        self.move_job = None
        try:
            self.store[self.k_pos] = [int(v) for v in self._where()]
            self.on_change()
        except Exception:
            pass

    def retitle(self, title):
        self.top.title(title)

    def close(self):
        try:
            self.before_close()
        except Exception:
            pass
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
        try:
            self.top.destroy()
        except Exception:
            pass
        self.store[self.k_show] = False
        self.on_change()
        if self.on_closed:
            self.on_closed()


PLAYERTEXT_PREFIX = "Playertext-"
PLAYERTEXT_DEFAULT_LABELS = {
    "hint": "Your own text - saved by itself as Playertext-<name>.txt in the "
            "program's Helpfiles folder.  Every such file there can be picked above.",
    "folder": "Folder", "new": "New...", "wrap": "Wrap",
    "newname": "Name of the new text (tactics, remember, house rules ...):",
    "ok": "OK", "cancel": "Cancel"}


def playertext_names(folder):
    """The <name> of every Playertext-<name>.txt in `folder`, sorted.  A
    Notes.txt from the first version of this block becomes Playertext-Notes.txt."""
    try:
        old, new = (os.path.join(folder, "Notes.txt"),
                    os.path.join(folder, PLAYERTEXT_PREFIX + "Notes.txt"))
        if os.path.isfile(old) and not os.path.exists(new):
            os.replace(old, new)
    except OSError:
        pass
    out = []
    try:
        for n in os.listdir(folder):
            if (n.lower().startswith(PLAYERTEXT_PREFIX.lower())
                    and n.lower().endswith(".txt")
                    and len(n) > len(PLAYERTEXT_PREFIX) + 4):
                out.append(n[len(PLAYERTEXT_PREFIX):-4])
    except OSError:
        pass
    return sorted(out, key=lambda s: s.lower())


def playertext_clean(name):
    """A name that is safe in a file name (no \\ / : * ? " < > |)."""
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


class PlayerTextPopup(ToolPopup):
    """The player's own text, written and saved INSIDE the program: tactics,
    house rules, things to remember.  Every file
    <Helpfiles>/<program>/Playertext-<name>.txt is one text; the part after
    the prefix is what the drop-down offers, and the chosen one is shown in a
    box with a scrollbar and mouse-wheel scrolling (and a horizontal bar when
    "Wrap" is off).  Typing saves by itself a second later and on close/switch.
    [New...] starts another text.  Nothing is ever deleted by the program.
    keys = (show_key, pos_key, zoom_key, selected_name_key)
    labels() -> dict with any of PLAYERTEXT_DEFAULT_LABELS' keys (a language
    switch calls relabel() which asks again).  Call .save_now() from the
    program's own on_close."""
    resizable = True

    def __init__(self, root, store, keys, on_change, theme, title, folder,
                 labels, on_closed=None, default_name="Notes"):
        self.folder, self.labels = folder, labels
        self.k_sel = keys[3]
        self.txt = self.hbar = self.btn_folder = self.lbl_status = None
        self.save_job = None
        self.dirty = False
        self.saved = None                   # None = no file yet
        names = playertext_names(folder)
        sel = store.get(self.k_sel)
        self.name = sel if sel in names else (names[0] if names else default_name)
        self.content = self._read(self.name)
        self.wrap = None
        ToolPopup.__init__(self, root, store, keys[:3], on_change, theme,
                           title, on_closed)
        self.wrap = self.wrap or tk.BooleanVar(value=True)
        self.top.after(80, self._focus)

    def _l(self, key):
        try:
            return self.labels().get(key) or PLAYERTEXT_DEFAULT_LABELS[key]
        except Exception:
            return PLAYERTEXT_DEFAULT_LABELS[key]

    def _path(self, name=None):
        return os.path.join(self.folder,
                            PLAYERTEXT_PREFIX + (name or self.name) + ".txt")

    def _focus(self):
        try:
            self.txt.focus_set()
        except Exception:
            pass

    def _read(self, name):
        self.saved = None
        self.dirty = False
        try:
            if os.path.isfile(self._path(name)):
                with open(self._path(name), encoding="utf-8-sig",
                          errors="replace") as fh:
                    text = fh.read()
                self.saved = text
                return text
        except Exception:
            pass
        return ""

    def extra_toolbar(self, bar):
        self.btn_folder = self._btn(bar, self._l("folder"), self._open_folder,
                                    w=8)
        self.btn_folder.pack(side="right", padx=6)

    def _open_folder(self):
        try:
            os.makedirs(self.folder, exist_ok=True)
            os.startfile(self.folder)
        except Exception:
            pass

    def before_rebuild(self):
        if self.txt is not None:
            try:
                self.content = self.txt.get("1.0", "end-1c")
            except Exception:
                pass

    def build(self, s):
        th = self.theme
        if self.wrap is None:
            self.wrap = tk.BooleanVar(value=True)
        row = tk.Frame(self.body, bg=th["bg"])
        row.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(row, text=PLAYERTEXT_PREFIX, bg=th["bg"], fg=th["dim"],
                 font=("Segoe UI", 9)).pack(side="left")
        names = playertext_names(self.folder)
        if self.name not in names:
            names = sorted(names + [self.name], key=lambda x: x.lower())
        self.var_name = tk.StringVar(value=self.name)
        om = tk.OptionMenu(row, self.var_name, *names, command=self._picked)
        om.configure(bg=th["btn"], fg=th["btnfg"], activebackground=th["accent"],
                     highlightthickness=0, bd=0, relief="flat", takefocus=0,
                     font=("Segoe UI", 9, "bold"), cursor="hand2")
        om["menu"].configure(bg=th["btn"], fg=th["btnfg"],
                             activebackground=th["accent"],
                             font=("Segoe UI", 9))
        om.pack(side="left")
        self._btn(row, self._l("new"), self._new, w=8).pack(side="left", padx=6)
        tk.Checkbutton(row, text=self._l("wrap"), variable=self.wrap,
                       command=self._wrap_changed, bg=th["bg"], fg=th["fg"],
                       selectcolor=th["panel"], activebackground=th["bg"],
                       activeforeground=th["accent"], highlightthickness=0,
                       takefocus=0, font=("Segoe UI", 9)).pack(side="right")
        box = tk.Frame(self.body, bg=th["panel"])
        box.pack(fill="both", expand=True, padx=6, pady=(4, 2))
        box.grid_rowconfigure(0, weight=1)
        box.grid_columnconfigure(0, weight=1)
        vbar = tk.Scrollbar(box, orient="vertical", bg=th["panel"])
        self.hbar = tk.Scrollbar(box, orient="horizontal", bg=th["panel"])
        self.txt = tk.Text(
            box, width=46, height=18, undo=True, bd=0, highlightthickness=0,
            padx=8, pady=6, bg=th["field"], fg=th["field_fg"],
            insertbackground=th["field_fg"], insertofftime=0,
            insertontime=1000,                           # no blinking cursor
            wrap="word" if self.wrap.get() else "none",
            font=("Segoe UI", max(7, int(round(10 * s)))),
            yscrollcommand=vbar.set, xscrollcommand=self.hbar.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vbar.grid(row=0, column=1, sticky="ns")
        vbar.configure(command=self.txt.yview)
        self.hbar.configure(command=self.txt.xview)
        self._wrap_changed()
        self.txt.insert("1.0", self.content)
        self.txt.edit_modified(False)
        self.txt.edit_reset()

        def modified(e):
            if self.txt.edit_modified():
                self.txt.edit_modified(False)
                self._changed()
        self.txt.bind("<<Modified>>", modified)
        self.lbl_status = tk.Label(self.body, anchor="w", justify="left",
                                   bg=th["bg"], fg=th["dim"],
                                   font=("Segoe UI", 8), wraplength=420,
                                   text=self._l("hint"))
        self.lbl_status.pack(fill="x", padx=8, pady=(0, 4))

    def _wrap_changed(self):
        on = self.wrap.get()
        self.txt.configure(wrap="word" if on else "none")
        if on:
            self.hbar.grid_forget()
        else:
            self.hbar.grid(row=1, column=0, sticky="ew")

    def _picked(self, name):
        if name != self.name:
            self._switch(name)

    def _switch(self, name):
        self.save_now()
        self.txt = None                     # do not cache the old text
        self.name = name
        self.content = self._read(name)
        self.store[self.k_sel] = name
        self.on_change()
        self._rebuild()
        self._focus()

    def _new(self):
        th = self.theme
        self.save_now()
        dlg = tk.Toplevel(self.top)
        dlg.title(self._l("new"))
        dlg.transient(self.top)
        dlg.configure(bg=th["bg"])
        dlg.resizable(False, False)
        tk.Label(dlg, text=self._l("newname"), bg=th["bg"], fg=th["fg"],
                 font=("Segoe UI", 9)).pack(padx=14, pady=(12, 4))
        var = tk.StringVar()
        ent = tk.Entry(dlg, textvariable=var, width=30, bd=0,
                       bg=th["field"], fg=th["field_fg"],
                       insertbackground=th["field_fg"], insertofftime=0,
                       insertontime=1000, font=("Segoe UI", 10))
        ent.pack(padx=14, ipady=3)

        def ok(event=None):
            nm = playertext_clean(var.get())
            dlg.destroy()
            if nm:
                existing = {n.lower(): n for n in playertext_names(self.folder)}
                self._switch(existing.get(nm.lower(), nm))
        row = tk.Frame(dlg, bg=th["bg"])
        row.pack(pady=10)
        self._btn(row, self._l("ok"), ok, w=8).pack(side="left", padx=4)
        self._btn(row, self._l("cancel"), dlg.destroy, w=8).pack(side="left",
                                                                  padx=4)
        dlg.bind("<Return>", ok)
        dlg.bind("<Escape>", lambda e: dlg.destroy())
        dlg.update_idletasks()
        dlg.geometry("+%d+%d" % (self.top.winfo_x() + 40, self.top.winfo_y() + 80))
        dlg.grab_set()
        ent.focus_force()

    def _changed(self):
        self.dirty = True
        if self.save_job:
            self.top.after_cancel(self.save_job)
        self.save_job = self.top.after(1000, self.save_now)

    def save_now(self):
        if self.save_job:
            try:
                self.top.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        if self.txt is None or not self.dirty:
            return
        try:
            text = self.txt.get("1.0", "end-1c")
        except Exception:
            return
        self.content = text
        if self.saved is None and not text.strip():
            self.dirty = False              # an empty text never makes a file
            return
        try:
            os.makedirs(self.folder, exist_ok=True)
            tmp = self._path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.replace(tmp, self._path())
            self.saved, self.dirty = text, False
        except Exception:
            pass

    def before_close(self):
        self.save_now()

    def relabel(self, title):
        self.retitle(title)
        self.btn_folder.configure(text=self._l("folder"))
        self._rebuild()


# *************** DEL 20 - CONSTANTS, SETTINGS, CATALOG *****************
# ToDo: Rail_Maps keeps a LIBRARY of Railway Rivals maps.  One catalog (Helpfiles\Rail_Maps\catalog.json):
#   maps  = one record per map (name, code, creator, year, steps ... from the Excel sheet)
#   files = every file found in the library folders, each one linked to a map and put in a COLUMN
# Columns: orig (the original drafts, many per map), issu (my own coloured versions), json, places, pdf,
# comments, invalid, extra.  The program never moves, renames or deletes a library file.
# ToDo (later): upload to Webdock from here (AppSite's ssh/scp code), a Swedish page.

COLS = [("orig", "Original"), ("version", "Version"), ("issu", "Issu's"), ("json", "Json"), ("places", "Places"), ("pdf", "PDF"),
        ("comments", "Comments"), ("invalid", "Invalid races"), ("extra", "Extra")]
COL_NAME = dict(COLS)
IMG_EXT = {".jpg", ".jpeg", ".png", ".gif", ".bmp"}
DOC_EXT = {".txt", ".doc", ".docx", ".html", ".htm", ".rtf"}
EXTRA_FOLDERS = ("1---extra_information", "1---information")

DEFAULT_SETTINGS = {
    "roots": [
        {"path": r"B:\0---Burn\Rail\1---Jobba_med\2---Original", "role": "original"},
        {"path": r"B:\0---Burn\Rail\0---Kartor", "role": "issu"},
        {"path": r"B:\0---Burn\Rail\1---Jobba_med\0---Som_Json", "role": "json"},
        # my newest own maps lie loose in the working folder itself: "flat" = only the files directly in it, no sub folders
        {"path": r"B:\0---Burn\Rail\1---Jobba_med", "role": "issu", "flat": True},
    ],
    "ignore_folders": ["0---Old", "0---Program", "Backup", "Back"],
    "excel": r"C:\0---Temp\Spel---RAIL.xlsx",
    "drive_folder": "",
    "vps_base": "",
    "extra_tools": "Cyberboard, Hand-drawn, Map creator",   # the 'Program used' options (Pick...): Xxx, Xxy, Zzz - I edit this list
    "extra_quality": "",                                   # my own quality options: Blurry scan=photo, Wrong colours=minor
    "extra_looks": "",                                     # my own 'Look' options (besides Black & white / Hand-coloured / Printed in colour): Sepia, Pencil
    "contact_email": "",                                   # where the page's "Add or correct" form is mailed to (empty = copy only)
    "upload_dir": r"Q:\Min enhet\Railway_rivals_maps",   # Google Drive for desktop, the account made for these maps (Lars 2026-11-08)
    # "Add files..." COPIES each file into this folder (the original stays where it was) so the library does not depend on the
    # folder the file came from.  Empty = the old way: the catalog just points at the file where it lies.  (Lars 2026-11-11)
    "import_dir": r"B:\0---Burn\Rail\1---Jobba_med\2---Original-2027",
    # The Google Drive folder where visitors drop map files / drafts for me (each in a folder with their own name).  Shown on the page
    # (About + the "Add or correct" form) and checked for new files by Make upload folder / Upload page.  Empty = nothing shown.
    "incoming_url": "https://drive.google.com/drive/folders/1borqopomstFhJNkZ4qzvJpLs3dMXhwBE?usp=sharing",
    "out_dir": "",
    "page_title": "Railway Rivals maps",
    "hide_empty": False,                 # Lars 2026-11-15: maps with no file are LISTED (with a message to visitors); this hides them again
    "only_confirmed": False,
    "field_levels": {},
    "source_order": ["drive", "vps"],          # (2026-11-14: the old "issusbarn.se" source lived on HTG, which is gone)
}
SOURCE_LABELS = {"drive": "Google Drive", "vps": "Webdock"}
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Rail_Maps/1.0"

SETTINGS_FILE = os.path.join(PROGRAM_HF_DIR, "settings.json")
CATALOG_FILE = os.path.join(PROGRAM_HF_DIR, "catalog.json")
BACKUP_DIR = os.path.join(PROGRAM_HF_DIR, "Backups")
MAP_FIELDS = [("name", "Map"), ("code", "Code"), ("codes2", "Other codes (SG=English, XY=old)"), ("have", "Have"), ("comment", "Comment"), ("draft_note", "Draft (sheet)"),
              ("by", "Base map creator(s)"), ("helped", "Helped by (codes)"), ("year", "Year (or 1985-06, 1985-06-12)"), ("steps", "Steps"), ("sr", "S.R. (how often special runs, like 2/7)"),
              ("cities", "Cities"), ("minp", "Min. players"), ("mindist", "Min. race distance (empty = 7)"), ("rivers", "Rivers"), ("exceptions", "Exceptions / comments"),
              ("fnote", "Note (from .comments)"), ("need", "Need"), ("want", "Want"),
              ("qnote", "Quality note (on the page)")]
# QUALITY: a colour mark, per VERSION (file) and per MAP.  "" = fine.  The page colours the file chip / the map name and has a
# "Wanted" view that collects everything marked.  `notes` of a map is PRIVATE (never on the page); `qnote` / file `note` are public.
#   "photo" = the MAP is fine but the picture of it is bad (blurry photo, bad scan): somebody may still have the original ->
#   a better picture is wanted.  Blue on the page.
QUALITY = [("", "Fine"), ("minor", "Could be better"), ("photo", "Map fine, picture poor (better photo wanted)"),
           ("poor", "Poor quality"), ("missing", "Missing")]
QUALITY_LABEL = dict(QUALITY)
QUALITY_RANK = {"": 0, "minor": 1, "photo": 2, "poor": 3, "missing": 4}
# Lars 2026-11-10: my OWN options for "Program used" and for Quality (Sources & folders...).  Program used: "Xxx, Xxy, Zzz" -> offered
# by the Pick... button.  Quality: "Blurry scan=photo, Wrong colours=minor" - each own option BEHAVES like a built-in one (minor = yellow,
# photo = blue, poor = red; default minor), so colours, the Wanted view and the legend keep working.  apply_custom_options() rebuilds
# QUALITY / QUALITY_LABEL / QUALITY_RANK IN PLACE (every menu and lookup reads these), keys are "u_<label>".
QUALITY_BUILTIN = list(QUALITY)
QUALITY_RANK_BUILTIN = dict(QUALITY_RANK)
QUALITY_LEVEL_WORDS = {"minor": "minor", "yellow": "minor", "photo": "photo", "blue": "photo", "poor": "poor", "red": "poor"}
QUALITY_BASE = {}                                   # own key -> the built-in key it behaves like
EXTRA_TOOLS = []                                    # own "Program used" options


def split_list(text):
    """'Xxx, Xxy; Zzz' -> ['Xxx', 'Xxy', 'Zzz'] (comma / semicolon / new line, empty and double entries dropped)."""
    out = []
    for part in re.split(r"[,;\n]", text or ""):
        part = part.strip()
        if part and part.lower() not in [o.lower() for o in out]:
            out.append(part)
    return out


def parse_extra_quality(text):
    """'Blurry scan=photo, Wrong colours' -> [('u_blurry_scan', 'Blurry scan', 'photo'), ('u_wrong_colours', 'Wrong colours', 'minor')].
    Labels equal to a built-in label are skipped; an unknown word after '=' counts as minor."""
    out, taken = [], {v.lower() for _k, v in QUALITY_BUILTIN}
    for item in split_list(text):
        label, _eq, word = item.partition("=")
        label = label.strip()
        if not label or label.lower() in taken:
            continue
        taken.add(label.lower())
        slug = re.sub(r"[^a-z0-9]+", "_", label.lower()).strip("_") or "x%d" % (len(out) + 1)
        key = "u_" + slug
        if any(key == o[0] for o in out):
            key += "_%d" % (len(out) + 1)
        out.append((key, label, QUALITY_LEVEL_WORDS.get(word.strip().lower(), "minor")))
    return out


def apply_custom_options(settings):
    """Call after the settings are loaded / saved (and before a page is built)."""
    EXTRA_TOOLS[:] = split_list(settings.get("extra_tools", ""))
    own_looks = parse_extra_looks(settings.get("extra_looks", ""))          # Lars 2026-11-16: own 'Look' options
    LOOKS[:] = LOOKS_BUILTIN + own_looks
    LOOK_LABEL.clear()
    LOOK_LABEL.update(dict(LOOKS))
    LOOK_SHORT.clear()
    LOOK_SHORT.update(LOOK_SHORT_BUILTIN)
    LOOK_SHORT.update({k: v for k, v in own_looks})
    own = parse_extra_quality(settings.get("extra_quality", ""))
    QUALITY[:] = [q for q in QUALITY_BUILTIN if q[0] != "missing"] + [(k, lab) for k, lab, _b in own] + [("missing", QUALITY_LABEL_MISSING)]
    QUALITY_LABEL.clear()
    QUALITY_LABEL.update(dict(QUALITY))
    QUALITY_RANK.clear()
    QUALITY_RANK.update(QUALITY_RANK_BUILTIN)
    QUALITY_BASE.clear()
    colours = globals().get("QUALITY_COLOURS")
    base_colours = globals().get("QUALITY_COLOURS_BUILTIN") or {}
    if colours is not None:
        colours.clear()
        colours.update(base_colours)
    for key, _lab, base in own:
        QUALITY_BASE[key] = base
        QUALITY_RANK[key] = QUALITY_RANK_BUILTIN[base]
        if colours is not None:
            colours[key] = base_colours.get(base, "#fff0b3")


QUALITY_LABEL_MISSING = dict(QUALITY_BUILTIN)["missing"]
QUALITY_CSS_VARS = {"minor": ("qm", "qmf"), "photo": ("qb", "qbf"), "poor": ("qp", "qpf")}


def quality_css():
    """CSS for my own quality options on the page: the chip / dot looks like the built-in one it is based on."""
    css = ""
    for key, base in QUALITY_BASE.items():
        bg, fg = QUALITY_CSS_VARS[base]
        css += "a.chip.q-%s,span.chip.q-%s{background:var(--%s);color:var(--%s)}.dot.q-%s{background:var(--%s)}" % (key, key, bg, fg, key, bg)
    return css
# Lars (2026-11-08): the designer of every Issu's / Json file is him - filled in automatically (see default_designers)
ME_CODE, ME_NAME = "LO", "Lars Olsson"
ME_COLS = ("issu", "json")
# The information the PAGE can show.  Each one has a LEVEL that I choose (Info fields... in the program):
#   basic = in every view, advanced = in Advanced + Detailed, detailed = only in Detailed, hidden = nowhere (the (i) box shows
#   everything that is not hidden).  `by` (creators of the base map) and `latest` (the newest draft: who, when) are made from
#   the creators typed per version.
INFO_FIELDS = [("by", "Creator"), ("helped", "Helped by"), ("latest", "Latest draft"), ("year", "Year"), ("steps", "Steps"), ("sr", "S.R."),
               ("cities", "Cities"), ("minp", "Min. players"), ("mindist", "Min. race distance"), ("rivers", "Rivers"),
               ("exceptions", "Exceptions"), ("fnote", "Note"), ("comment", "Comment"), ("draft_note", "Draft (sheet)"), ("sruns", "Special runs"),
               ("need", "Need"), ("want", "Want"), ("have", "Have"), ("nr", "Map number"), ("gaps", "Missing drafts"),
               ("added", "Added information"), ("older", "Older information")]
LEVELS = ["basic", "advanced", "detailed", "hidden"]
DEFAULT_LEVELS = {"by": "basic", "helped": "advanced", "year": "basic", "latest": "advanced", "steps": "advanced", "cities": "advanced",
                  "minp": "advanced", "mindist": "detailed", "sr": "detailed", "rivers": "detailed", "exceptions": "detailed", "fnote": "detailed", "comment": "detailed",
                  "draft_note": "detailed", "sruns": "detailed", "need": "hidden", "want": "hidden",
                  "have": "hidden", "nr": "hidden", "gaps": "detailed", "added": "advanced", "older": "detailed"}
STATE = {"only_confirmed": False}      # set from the settings; included() reads it


def load_json(path, default):
    try:
        with open(path, encoding="utf-8") as fh:
            return json.load(fh)
    except Exception:
        return default


def save_json(path, data):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".new"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(data, fh, ensure_ascii=False, indent=1)
    os.replace(tmp, path)


def load_settings():
    s = copy.deepcopy(DEFAULT_SETTINGS)
    s.update(load_json(SETTINGS_FILE, {}))
    s.pop("site_base", None)                 # HTG is gone (2026-11-14): the old "issusbarn.se files" source is dropped from old settings files
    s["source_order"] = [x for x in (s.get("source_order") or []) if x in ("drive", "vps")] or ["drive", "vps"]
    if not s.get("out_dir"):
        s["out_dir"] = os.path.join(PROGRAM_HF_DIR, "Site")
    STATE["only_confirmed"] = bool(s.get("only_confirmed"))
    apply_custom_options(s)
    return s


def level_of(settings, key):
    lv = (settings.get("field_levels") or {}).get(key) or DEFAULT_LEVELS.get(key, "hidden")
    return lv if lv in LEVELS else "hidden"


def new_catalog():
    return {"version": 1, "maps": [], "files": [], "people": {}, "helpers": {}}


def is_excel_error(text):
    """True for a cell that holds an Excel error instead of a value: #VÄRDE! (Swedish #VALUE!), #N/A, #REF!, #NAMN? ..."""
    return bool(re.fullmatch(r"#[A-ZÅÄÖ/0-9]+[!?]?", str(text or "").strip().upper()))


def load_catalog():
    c = load_json(CATALOG_FILE, None)
    if not isinstance(c, dict):
        return new_catalog()
    for k, v in new_catalog().items():
        c.setdefault(k, v)
    # Lars 2026-11-09: "#VÄRDE!" sat at the top of the designer list = a broken formula cell in the sheet, read in as a person
    c["people"] = {k: v for k, v in c["people"].items() if not (is_excel_error(k) or is_excel_error(v))}
    default_designers(c)
    merge_helpers(c)                         # a helper who is also a creator lives in Creators only
    fix_designer_names(c)                    # a designer typed as a name ('Peter Robbins') becomes its code ('PR')
    hide_comments2(c)                        # .comments2 files are of no interest (2026-11-14)
    settle_unofficial(c)                     # an unofficial code gives way to an official one
    migrate_looks(c)                         # a note 'Black & white' / 'Coloured' becomes the Look of the version (2026-11-16)
    fix_copies(c)                            # a copy whose main file is gone / moved is a version again
    return c


def default_designers(cat):
    """Every Issu's / Json file is drawn by me (code LO): fills `by` when it is empty and I have not edited it myself
    (`by_edited` is set when the designer is typed in Details / Assign, so clearing it by hand sticks).  Returns how many changed."""
    cat.setdefault("people", {}).setdefault(ME_CODE, ME_NAME)
    n = 0
    for f in cat.get("files", []):
        if (f.get("col") in ME_COLS and not str(f.get("by", "")).strip() and not f.get("by_edited")
                and os.path.splitext(f.get("path", ""))[1].lower() not in NOT_LO_EXT):      # LO draws .bmp only (2026-11-14)
            f["by"] = ME_CODE
            n += 1
    return n


def save_catalog(cat, backup=False):
    settle_unofficial(cat)                   # every save: an unofficial code that now clashes with an official one is removed + logged
    fix_copies(cat)                          # every save: a copy link to a file that is gone / moved is dropped
    if backup and os.path.isfile(CATALOG_FILE):
        os.makedirs(BACKUP_DIR, exist_ok=True)
        shutil.copy2(CATALOG_FILE, os.path.join(BACKUP_DIR, "catalog_%s.json" % time.strftime("%Y%m%d_%H%M%S")))
        old = sorted(os.listdir(BACKUP_DIR))
        for n in old[:-20]:
            try:
                os.remove(os.path.join(BACKUP_DIR, n))
            except OSError:
                pass
    save_json(CATALOG_FILE, cat)


def catalog_stamp(cat):
    """A short fingerprint of the catalog's content: the window compares it with the one stored by the last Build page to say
    'page out of date' (a save that changes nothing - like the one after the Upload job - keeps the same fingerprint)."""
    body = {k: v for k, v in cat.items() if k != "numbers"}          # the saved number list is not on the page
    return "%08x" % zlib.crc32(json.dumps(body, sort_keys=True, ensure_ascii=False).encode("utf-8"))


# *************** DEL 21 - NAME PARSING AND MATCHING *****************
# ToDo: file names in the library are messy (prefix code "AL---", "(kopia)", "draft_1c", "V1,5", "RR", "BR_Whyte ..."), so a
# file is reduced to (code, key, draft).  `key` is what the map name is compared with.

def ascii_fold(s):
    return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))


def norm_key(s):
    s = ascii_fold(str(s)).lower().replace("&", " and ")
    s = re.sub(r"[^a-z0-9]+", " ", s)
    return re.sub(r"\s+", " ", s).strip()


JUNK_PAREN = re.compile(r"\((?:kopia|copy|original|annan[ _]draft|next[ _]version|text|notes|a|b|c|d|\d{4}|[^)]*kopia[^)]*)\)", re.I)


def draft_rank(label):
    """'1c' -> (1, 3), '1,3' -> (1, 3), '2b' -> (2, 2), '' -> (0,).  Used only to ORDER versions."""
    label = str(label or "").strip().lower()
    out = []
    lead = re.match(r"(\d+(?:[,.]\d+)*)([a-z])?(?![a-z])", label)      # '1 Cyberboard' counts as 1, '1c' as 1c
    if lead:
        label = lead.group(1) + (lead.group(2) or "")
    for tok in re.findall(r"\d+|[a-z]", label):
        out.append(int(tok) if tok.isdigit() else ord(tok) - 96)
    return tuple(out) or (0,)


def parse_name(basename):
    """(code, key, draft) of a library file name."""
    stem = os.path.splitext(basename)[0]
    if re.search(r"\.(comments\d?|places|invalid_races|comments_race)$", basename, re.I):
        stem = basename.rsplit(".", 1)[0]
    stem = re.sub(r"_places$", "", stem, flags=re.I)
    stem = re.sub(r"RR(?=$|_v|_\d)", "", stem) if len(stem) > 4 else stem
    s = stem.replace("_", " ")
    code = ""
    m = re.match(r"^([A-Za-z]{1,4}(?:\([A-Za-z]\))?)---(.*)$", s)
    if m:
        code, s = m.group(1), m.group(2)
    s = re.sub(r"\s*---\s*", " ", s)
    s = re.sub(r"\s*\(BR Whyte.*$|\s+BR Whyte.*$", "", s)
    draft = ""
    m = re.search(r"draft\s*v?\s*(\d[\d,\.]*[a-z]?)", s, re.I)
    if m:
        draft = m.group(1)
        s = s[:m.start()] + s[m.end():]
    else:
        m = re.search(r"(?:^|\s)v\.?\s*(\d[\d,\.]*[a-z]?)(?=\s|\)|$)", s, re.I)
        if m:
            draft = m.group(1)
            s = s[:m.start()] + " " + s[m.end():]
        else:
            m = re.search(r"\s(\d[a-z])$", s)
            if m:
                draft = m.group(1)
                s = s[:m.start()]
    s = JUNK_PAREN.sub(" ", s)
    if not code:
        m = re.search(r"\(([A-Z]{1,4}\d?)\)", s)
        if m:
            code = m.group(1)
    s = re.sub(r"\([A-Z]{1,4}\d?\)", " ", s)
    s = re.sub(r"\(draft[^)]*\)", " ", s, flags=re.I)
    s = s.replace("(", " ").replace(")", " ")
    return code.upper(), norm_key(s), draft.strip(",. ")


def classify(path, role, rel_folder):
    """Column of a library file, or None when the file is not part of the library."""
    base = os.path.basename(path)
    low = base.lower()
    ext = os.path.splitext(low)[1]
    if ".replaced_" in low or low.endswith((".rar", ".bak", ".tmp")) or low.startswith("~$"):
        return None
    if ext == ".json":
        return "json"
    if ext == ".places" or low.endswith("_places.txt"):
        return "places"
    if ".comments" in low:
        return "comments"
    if ext == ".invalid_races":
        return "invalid"
    if ext == ".pdf":
        return "pdf"
    if any(p.lower() in EXTRA_FOLDERS for p in rel_folder.replace("/", "\\").split("\\")):
        return "extra" if ext in IMG_EXT or ext in DOC_EXT else None
    if ext in IMG_EXT:
        # Lars 2026-11-14: LO (my own column) is .bmp ONLY - a jpg / png / gif in my folders is somebody else's picture
        return "issu" if (role == "issu" and ext == ".bmp") else "orig"
    if ext in DOC_EXT:
        return "extra"
    return None


def smart_title(name):
    name = str(name).strip()
    if name.isupper():
        name = string.capwords(name.lower())
        name = re.sub(r"\b(Of|And|The|De|Du|La|Le|To)\b", lambda m: m.group(1).lower(), name)
        name = name[:1].upper() + name[1:]
    return name


def slug(text):
    return re.sub(r"[^a-z0-9]+", "-", ascii_fold(text).lower()).strip("-") or "map"


def map_by_id(cat):
    return {m["id"]: m for m in cat["maps"]}


# ---- help from visitors: the page makes a text form, they e-mail it, Incoming info... reads it ----
SUB_KEYS = {"map": "map", "part": "part", "new or correction": "kind", "draft": "draft", "date": "date", "designers": "by",
            "designer": "by", "program used": "tool", "program": "tool", "year": "year", "steps": "steps", "cities": "cities",
            "other information": "other", "my name": "name"}
SUB_LABELS = [("map", "Map"), ("part", "Part"), ("kind", "New or correction"), ("draft", "Draft"), ("date", "Date"),
              ("by", "Designers"), ("tool", "Program used"), ("year", "Year"), ("steps", "Steps"), ("cities", "Cities"),
              ("other", "Other information"), ("name", "My name")]


def parse_submissions(text):
    """Reads the pasted e-mail text: 'Key: value' lines, a 'Map:' line starts a new form, lines without a key continue the value
    before (Other information is often several lines).  Quote marks (> ) in front of the lines are ignored."""
    subs, cur, key = [], None, None
    for line in text.splitlines():
        s = line.strip().lstrip("> ").strip()
        if re.match(r"(?i)^railmaps?\s+info\b", s):
            cur, key = None, None
            continue
        mm = re.match(r"^([A-Za-z][A-Za-z ]{1,24}?)\s*:\s*(.*)$", s)
        if mm and mm.group(1).strip().lower() in SUB_KEYS:
            key = SUB_KEYS[mm.group(1).strip().lower()]
            if key == "map" or cur is None:
                cur = {}
                subs.append(cur)
            cur[key] = mm.group(2).strip()
        elif cur is not None and key == "other" and s:          # only Other information runs over several lines (the rest is "Thanks, Anna")
            cur[key] = (cur.get(key, "") + "\n" + s).strip()
    return [x for x in subs if any(v.strip() for v in x.values())]


def sub_text(sub):
    return "RAILMAPS INFO v1\n" + "".join("%s: %s\n" % (lab, sub.get(k, "")) for k, lab in SUB_LABELS if sub.get(k, "").strip())


def find_map_for_submission(cat, name):
    k = norm_key(name or "")
    if not k:
        return None
    for m in cat["maps"]:
        if norm_key(m["name"]) == k:
            return m
    best = suggest_maps(cat, k, "", n=1)
    return best[0][0] if best and best[0][1] >= 0.75 else None


def names_to_codes(cat, text):
    """Designers as people wrote them (codes or names) -> the codes of the list; a name not in the list stays as it was written."""
    out = []
    for tok in re.split(r"\s*(?:,|\+|/|&|\band\b)\s*", text or ""):
        tok = tok.strip()
        if not tok:
            continue
        if tok.strip("? ") == "":
            out.append("?")                                   # a "not sure" mark stays (see parse_designers)
            continue
        pre, post = "?" if tok.startswith("?") else "", "?" if tok.endswith("?") else ""
        tok = tok.strip("? ")
        if tok.upper() in cat["people"]:
            out.append(pre + tok.upper() + post)
            continue
        low = tok.lower()
        words = set(re.findall(r"\w+", low))
        hit = [c for c, n in cat["people"].items() if n.lower() == low] or [
            c for c, n in cat["people"].items() if len(low) > 3 and words <= set(re.findall(r"\w+", n.lower()))]
        out.append(pre + (hit[0] if len(hit) == 1 else tok) + post)
    return norm_designers(",".join(out))


def _replace(obj, field, new, label, who, today, lines, edited=None):
    """Sets a new value; the old one is KEPT in obj['older'] (shown as Older information) and the giver is credited."""
    old = str(obj.get(field, "") or "")
    if old == new:
        return
    if old:
        obj.setdefault("older", []).append({"field": field, "label": label, "value": old, "on": today, "by": who})
    obj[field] = new
    obj.setdefault("credit", {})[field] = who
    if edited is not None and field not in edited:
        edited.append(field)                       # the Excel import must not overwrite it
    lines.append("%s: %s%s%s" % (label, new, ("   (was: %s - kept as older information)" % old) if old else "",
                                 ("   (courtesy of %s)" % who) if who else ""))


def apply_submission(cat, m, sub, today):
    """Puts one form's information on a map.  Returns the lines describing what was done."""
    who = sub.get("name", "").strip()
    lines, extra = [], []
    ed = m.setdefault("edited", [])
    for fld, label in (("year", "Year"), ("steps", "Steps"), ("cities", "Cities")):
        v = sub.get(fld, "").strip()
        if not v:
            continue
        if fld == "year" and parse_date(v) is None:
            extra.append("Year (as written): " + v)
        else:
            _replace(m, fld, v, label, who, today, lines, ed)
    draft = sub.get("draft", "").strip()
    by = names_to_codes(cat, sub.get("by", ""))
    date = sub.get("date", "").strip()
    tool = sub.get("tool", "").strip()
    if date and parse_date(date) is None:
        extra.append("Date (as written): " + date)
        date = ""
    if draft:
        fl = [f for f in cat["files"] if f.get("map") == m["id"] and not f.get("gone") and f.get("col") in ("orig", "version")
              and str(f.get("draft", "")).strip().lower() == draft.lower()]
        if fl:
            for f in fl:
                for fld, val, label in (("date", date, "Date"), ("by", by, "Designers"), ("tool", tool, "Program")):
                    if val:
                        _replace(f, fld, val, "Draft %s - %s" % (draft, label), who, today, lines)
                        f["manual"] = True
        elif date or by or tool:
            m.setdefault("reported", []).append({"draft": draft, "date": date, "by": by, "tool": tool, "who": who, "on": today})
            lines.append("Draft %s is not in the library - kept as a reported draft (%s)" % (draft, ", ".join(
                x for x in (fmt_date(date) if date else "", ("by " + by) if by else "", tool) if x)))
    else:
        if by:
            _replace(m, "by", by, "Designers", who, today, lines, ed)
        if date and not sub.get("year", "").strip():
            _replace(m, "year", date, "Year", who, today, lines, ed)
        if tool:
            extra.append("Program: " + tool)
    other = sub.get("other", "").strip()
    for t in ([other] if other else []) + extra:
        m.setdefault("added", []).append({"text": t, "by": who, "on": today})
        lines.append("Added information: %s%s" % (t, ("   (courtesy of %s)" % who) if who else ""))
    cat.setdefault("submissions", []).append({"on": today, "map": m["id"], "by": who, "raw": sub_text(sub)})
    return lines


def plan_submission(cat, m, sub):
    """The same as apply_submission but on copies - to show what WOULD happen."""
    tmp = {"maps": [copy.deepcopy(m)], "files": [copy.deepcopy(f) for f in cat["files"] if f.get("map") == m["id"]],
           "people": cat["people"]}
    return apply_submission(tmp, tmp["maps"][0], sub, time.strftime("%Y-%m-%d"))


def credit_of(obj):
    return ", ".join(sorted({v for v in (obj.get("credit") or {}).values() if v}))


def added_text(m):
    bits = ["%s%s" % (a["text"], (" (courtesy of %s)" % a["by"]) if a.get("by") else "") for a in m.get("added", [])]
    for r in m.get("reported", []):
        bits.append("Reported draft %s: %s%s" % (r["draft"], ", ".join(x for x in (fmt_date(r["date"]) if r.get("date") else "",
                     ("by " + r["by"]) if r.get("by") else "", r.get("tool", "")) if x), (" (courtesy of %s)" % r["who"]) if r.get("who") else ""))
    return "; ".join(bits)


def older_text(cat, m):
    items = list(m.get("older", []))
    for f in cat["files"]:
        if f.get("map") == m["id"]:
            items += f.get("older", [])
    return "; ".join("%s: %s (until %s)" % (o["label"], fmt_date(o["value"]) if o["field"] in ("date", "year") else o["value"], o["on"])
                     for o in items)


def sruns_of(m):
    """The special runs of a map: {never, same, odd[], even[], skip}.  Usually 6 destinations (or 6 odd + 6 even = 12), but any number
    of lines is allowed.  never = the map has no special runs at all; skip = drafts that have none ("1a, 1b")."""
    s = m.get("sruns") or {}
    return {"never": bool(s.get("never")), "same": bool(s.get("same")), "odd": list(s.get("odd") or []),
            "even": list(s.get("even") or []), "skip": str(s.get("skip") or "").strip()}


def sruns_text(m):
    s = sruns_of(m)
    if s["never"]:
        return "None - this map never has special runs"
    parts = []
    if s["same"] and s["odd"]:
        parts.append("Every race (%d): %s" % (len(s["odd"]), ", ".join(s["odd"])))
    else:
        if s["odd"]:
            parts.append("Odd (%d): %s" % (len(s["odd"]), ", ".join(s["odd"])))
        if s["even"]:
            parts.append("Even (%d): %s" % (len(s["even"]), ", ".join(s["even"])))
    if s["skip"] and parts:
        parts.append("Not in draft " + s["skip"])
    return "; ".join(parts)


def new_map(cat, name, **kw):
    ids = {m["id"] for m in cat["maps"]}
    base = slug(name)
    mid, n = base, 2
    while mid in ids:
        mid = "%s-%d" % (base, n)
        n += 1
    m = {"id": mid, "name": name, "code": "", "have": "", "comment": "", "draft_note": "", "by": "", "year": "", "steps": "",
         "sr": "", "cities": "", "minp": "", "rivers": "", "exceptions": "", "sruns": {}, "need": "", "want": "",
         "nr": "", "notes": "", "qnote": "", "quality": "", "hidden": False, "edited": [], "gap_ack": {}}
    m.update(kw)
    cat["maps"].append(m)
    return m


class Matcher(object):
    """Finds the map a file belongs to.  Order: same key -> same code + similar key -> very similar key."""

    def __init__(self, cat):
        self.by_key, self.by_code, self.by_nr, self.same_key, self.same_noand = {}, {}, {}, {}, {}
        for m in cat["maps"]:
            if str(m.get("nr", "")).isdigit():
                self.by_nr.setdefault(int(m["nr"]), m)
            k = norm_key(m["name"])
            self.by_key.setdefault(k, m)
            self.same_key.setdefault(k, []).append(m)          # several maps can share a name (Austria AUS / Austria OS)
            self.same_noand.setdefault(" ".join(t for t in k.split() if t != "and"), []).append(m)
            c = (m.get("code") or "").strip().upper()
            if c and c not in ("-", "???", "?"):
                self.by_code.setdefault(c, []).append(m)
        self.keys = list(self.by_key)

    def find(self, code, key):
        if not key:
            return None, 0.0
        num = re.match(r"^(\d{3,4})(?:\s|$)", key)          # 0063.places, 0063_(7_hexes).invalid_races = the map NUMBER
        if num:
            m = self.by_nr.get(int(num.group(1)))
            return (m, 1.0) if m else (None, 0.0)
        m = self.by_key.get(key)
        if m:
            twins = self.same_key.get(key, [])
            if len(twins) > 1 and code:                      # same name, several maps: the code in the file name decides
                hit = [t for t in twins if (t.get("code") or "").strip().upper() == code.upper()]
                if len(hit) == 1:
                    return hit[0], 1.0
            return m, 1.0
        toks = key.split()
        for i in range(len(toks) - 1, 0, -1):            # "alberta ab", "benelux bn 0 hex": map name + its CODE (Alberta_AB_draft_1b.places)
            head = " ".join(t for t in toks[:i] if t != "and")          # "California_Nevada" = "California & Nevada"
            for t in self.same_noand.get(head, []):
                if re.sub(r"\W", "", t.get("code") or "").upper() == toks[i].upper():
                    return t, 0.97
        cands = self.by_code.get(code) or []
        if code and len(cands) == 1:
            r = difflib.SequenceMatcher(None, key, norm_key(cands[0]["name"])).ratio()
            if r >= 0.55 or key in norm_key(cands[0]["name"]) or norm_key(cands[0]["name"]) in key:
                return cands[0], max(r, 0.9)
        best = difflib.get_close_matches(key, self.keys, n=2, cutoff=0.84)
        if best:
            return self.by_key[best[0]], difflib.SequenceMatcher(None, key, best[0]).ratio()
        return None, 0.0


def suggest_maps(cat, key, code="", n=8):
    """[(map, score 0..1)] best first - what a file with this name/code probably is.  Only a SUGGESTION."""
    out = []
    key = " ".join(FOREIGN_WORDS.get(w, w) for w in key.split())          # Indien -> india, Skandinavien -> scandinavia ...
    ks = key.replace(" ", "")
    for m in cat["maps"]:
        mk = norm_key(m["name"])
        mks = mk.replace(" ", "").replace("and", "")
        r = difflib.SequenceMatcher(None, key, mk).ratio() if key else 0.0
        if key and mk and (key in mk or mk in key):
            r = max(r, 0.75)
        if len(ks) >= 5 and len(mks) >= 5:                                   # "senegalgambia" = "Senegal & Gambia", "srilanka" = "Sri Lanka"
            r = max(r, difflib.SequenceMatcher(None, ks, mks).ratio() if abs(len(ks) - len(mks)) <= 3 else 0.0)
            if ks == mks or ks in mks or mks in ks:
                r = max(r, 0.8)
        if code and (m.get("code") or "").strip().upper() == code.upper():
            r += 0.15
        out.append((min(r, 1.0), m))
    out.sort(key=lambda x: (-x[0], norm_key(x[1]["name"])))
    return [(m, s) for s, m in out[:n]]


# Swedish / German words in file names -> the English the sheet uses (only for SUGGESTIONS, never changes a name).
FOREIGN_WORDS = {"indien": "india", "kroatien": "croatia", "sibirien": "siberia", "skandinavien": "scandinavia",
                 "deutschland": "germany", "suedwest": "south west", "sudwest": "south west", "suedost": "south east",
                 "sverige": "sweden", "norge": "norway", "danmark": "denmark", "finland": "finland", "schweiz": "switzerland",
                 "osterreich": "austria", "oesterreich": "austria", "spanien": "spain", "frankreich": "france",
                 "italien": "italy", "polen": "poland", "ungarn": "hungary", "tschechien": "czech", "russland": "russia",
                 "ryssland": "russia", "tyskland": "germany", "storbritannien": "britain"}


def map_label(cat, m):
    """Name for a list: 'Nigeria' - or, when another map has the same name, 'Nigeria (nr 173, ???, 2020)' so twins can be told apart."""
    twins = [x for x in cat["maps"] if x is not m and norm_key(x["name"]) == norm_key(m["name"])]
    if not twins:
        return m["name"]
    bits = [("nr " + str(m["nr"])) if m.get("nr") else "", m.get("code") or "", str(m.get("year") or "")]
    return "%s (%s)" % (m["name"], ", ".join(b for b in bits if b))


def suggested_maps(cat, rec, limit=3):
    """The map(s) a file with no map probably belongs to: the best match, or all that tie for it (two maps with the same name)."""
    sg = suggest_maps(cat, rec.get("guess_key", ""), rec.get("guess_code", ""), n=6)
    if not sg or sg[0][1] < 0.4:
        return []
    return [m for m, s in sg if s >= sg[0][1] - 0.001][:limit]


def newest_original_of(cat, map_id):
    """The file to compare with: the newest ORIGINAL picture of the map (else any original, else my own coloured picture), or None."""
    def pool(cols, images_only):
        out = [f for f in cat["files"] if f.get("map") == map_id and not f.get("gone") and f.get("col") in cols and not f.get("copy_of")
               and os.path.isfile(f["path"]) and (not images_only or os.path.splitext(f["path"])[1].lower() in IMG_EXT)]
        return sort_versions(out)
    for cols, imgs in ((("orig",), True), (("orig",), False), (("issu", "version", "json"), True)):
        p = pool(cols, imgs)
        if p:
            return p[-1]
    return None


MONTHS = {m: i for i, m in enumerate(("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"), 1)}


def date_from_name(name):
    """'..._10_march_2020_...' -> '2020-03-10', else ''."""
    m = re.search(r"(?:^|[_\s,\-])(\d{1,2})[_\s\-]+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[_\s]+(\d{4})", name, re.I)
    if not m:
        m = re.search(r"(?:^|[_\s,\-])(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*[_\s]+(\d{4})", name, re.I)
        if m:
            return "%04d-%02d" % (int(m.group(2)), MONTHS[m.group(1).lower()[:3]])
        return ""
    try:
        return "%04d-%02d-%02d" % (int(m.group(3)), MONTHS[m.group(2).lower()[:3]], int(m.group(1)))
    except (ValueError, KeyError):
        return ""


MONTH_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
               "December"]


def parse_date(text):
    """A date as exact as I know it: '1985', '1985-06' or '1985-06-12' (also 1985/06/12, 12.6.1985).  Returns the normal form,
    '' for nothing, None when it is not a date."""
    s = str(text or "").strip()
    if not s:
        return ""
    m = re.fullmatch(r"(\d{4})(?:[-/.](\d{1,2})(?:[-/.](\d{1,2}))?)?", s)
    if m:
        y, mo, d = int(m.group(1)), m.group(2), m.group(3)
    else:
        m = re.fullmatch(r"(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})", s)          # day-month-year
        if not m:
            return None
        y, mo, d = int(m.group(3)), m.group(2), m.group(1)
    try:
        if mo is None:
            return "%04d" % y
        mo = int(mo)
        if not 1 <= mo <= 12:
            return None
        if d is None:
            return "%04d-%02d" % (y, mo)
        datetime.date(y, mo, int(d))
        return "%04d-%02d-%02d" % (y, mo, int(d))
    except ValueError:
        return None


def fmt_date(text):
    """'1985' -> 1985, '1985-06' -> June 1985, '1985-06-12' -> 12 June 1985 (anything else is shown as typed)."""
    p = parse_date(text)
    if not p:
        return str(text or "").strip()
    parts = p.split("-")
    if len(parts) == 1:
        return parts[0]
    if len(parts) == 2:
        return "%s %s" % (MONTH_NAMES[int(parts[1]) - 1], parts[0])
    return "%d %s %s" % (int(parts[2]), MONTH_NAMES[int(parts[1]) - 1], parts[0])


def date_key(text):
    """Sortable form: '1985' < '1985-06' < '1985-06-12' within the same year; '' sorts first."""
    p = parse_date(text) or ""
    if not p:
        return ""
    return "-".join((p.split("-") + ["00", "00"])[:3])


def ver_key(f):
    """The order of the versions of a map: draft, then date (as exact as known), then the file's own time."""
    return (draft_rank(f.get("draft")), date_key(f.get("date")), f.get("mtime", 0))


def sort_versions(files):
    """The files of ONE map in version order (a new list).  Normally by draft, then date (ver_key).  But when EVERY original of the
    map has a date, the originals go by DATE (draft and file time only break ties): different designers number their drafts
    differently (South East Australia: DW's 2a from 1992, BRW's 1,2 from 2013 and 1,2,1 from 2020 - 2a is the OLDEST, not the
    newest).  Lars asked for this 2026-11-09.  Other columns keep the draft order; the originals just swap places among themselves."""
    out = sorted(files, key=ver_key)
    slots = [i for i, f in enumerate(out) if f.get("col") == "orig"]
    if len(slots) >= 2 and all(date_key(out[i].get("date")) for i in slots):
        by_date = sorted((out[i] for i in slots), key=lambda f: (date_key(f.get("date")), draft_rank(f.get("draft")), f.get("mtime", 0)))
        for i, f in zip(slots, by_date):
            out[i] = f
    return out


def guess_by(basename, people):
    """Creator codes whose SURNAME is in the file name (BR_Whyte -> BRW).  A suggestion, never confirmed."""
    low = norm_key(basename)
    hits = []
    for code, name in people.items():
        parts = norm_key(name).split()
        if parts and len(parts[-1]) > 3 and re.search(r"\b%s\b" % re.escape(parts[-1]), low):
            hits.append(code)
    return ",".join(hits)


def parse_designers(text):
    """Designer codes with 'not sure' marks (Lars 2026-11-09: "?DW?" = probably DW, but it does not say so on the map).
    A '?' can be typed like a designer of its own, or stuck to a code: 'BRW,?,DW,?'  '?DW?'  'DW?'  '?,DW,BRW,?' all work.
    A lone '?' opens a group of suspects, the next lone '?' closes it; a lone '?' at the very end of the list marks the code before
    it; a group that is never closed runs to the end.  Returns [(code, suspected)]."""
    toks = [t.strip() for t in re.split(r"[,+/]", str(text or "")) if t.strip()]
    out, in_group = [], False
    for i, t in enumerate(toks):
        if t.strip("? ") == "":                              # a lone '?' (or '??')
            if in_group:
                in_group = False
            elif i == len(toks) - 1:
                if out:
                    out[-1] = (out[-1][0], True)
            else:
                in_group = True
            continue
        start, end = t.startswith("?"), t.endswith("?")
        if start:
            in_group = True
        out.append((t.strip("? ").strip(), in_group or end))
        if end:
            in_group = False
    return out


def fmt_designers(items):
    """[(code, suspected)] -> 'BRW,?DW,AB?' : the first '?' of a group sits right before its first code, the last right after its last."""
    out = []
    for i, (c, sus) in enumerate(items):
        before = i > 0 and items[i - 1][1]
        after = i + 1 < len(items) and items[i + 1][1]
        out.append(("?" if sus and not before else "") + c + ("?" if sus and not after else ""))
    return ",".join(out)


def resolve_code(people, token):
    """A designer typed as a NAME or in other letters ('Peter Robbins', 'pr') -> the code of the list ('PR').  Anything that is not
    clearly one person stays as it was (Lars 2026-11-09: a file had 'Peter Robbins' as its designer and the page showed the name twice)."""
    t = str(token).strip()
    if t in people:
        return t
    for c in people:
        if c.upper() == t.upper():
            return c
    low = " ".join(t.lower().split())
    hits = [c for c, n in people.items() if " ".join(n.lower().split()) == low]
    return hits[0] if len(hits) == 1 else t


def norm_designers(text, people=None):
    """What I typed -> the tidy form: the start '?' and end '?' moved together so they sit tight around the suspects;
    with `people` a typed name becomes its code."""
    items = parse_designers(text)
    if people:
        items = [(resolve_code(people, c), s) for c, s in items]
    return fmt_designers(items)


def all_people(cat):
    """Every person who can be named: the creators (cat['people']) AND the helpers-only list (cat['helpers']).  A code is in one list
    only - the creators win (merge_helpers takes care of that).  Creators show up under Helpers... too; helpers never under Creators."""
    d = dict(cat.get("helpers", {}))
    d.update(cat.get("people", {}))
    return d


def merge_helpers(cat):
    """Keeps the two lists free of duplicates: a helper whose CODE is a creator is dropped; a helper with the same NAME as a creator
    is dropped and its code, wherever it was used, becomes the creator's code.  Returns how many helpers were removed."""
    people, helpers = cat.get("people", {}), cat.setdefault("helpers", {})
    by_name = {" ".join(n.lower().split()): c for c, n in people.items()}
    remap, gone = {}, []
    for code, name in list(helpers.items()):
        if code in people:
            gone.append(code)
        elif " ".join(name.lower().split()) in by_name:
            remap[code] = by_name[" ".join(name.lower().split())]
            gone.append(code)
    for code in gone:
        helpers.pop(code, None)
    if remap:
        for obj in list(cat.get("maps", [])) + list(cat.get("files", [])):
            for fld in ("by", "helped"):
                if obj.get(fld):
                    obj[fld] = fmt_designers([(remap.get(c, c), s) for c, s in parse_designers(obj[fld])])
    return len(gone)


def names_of(cat, codes):
    """'BRW, DW' -> ['Brendan Richard Whyte', 'David Gwyn Watts'] (unknown codes stay as they are; a suspect gets ' (?)')."""
    ppl = all_people(cat)
    return [ppl.get(resolve_code(ppl, c), c) + (" (?)" if sus else "") for c, sus in parse_designers(codes)]


def codes_of(codes, people=None):
    """'BRW, ?DW?' -> ['BRW', 'DW?'] - the short codes, for the small lines under a version on the page."""
    return [(resolve_code(people, c) if people else c) + ("?" if sus else "") for c, sus in parse_designers(codes)]


def fix_designer_names(cat):
    """Writes every typed NAME in a designer / helped field as its code (once, when the catalog is loaded).  Returns how many changed."""
    n = 0
    for obj in list(cat.get("maps", [])) + list(cat.get("files", [])):
        for fld in ("by", "helped"):
            old = obj.get(fld)
            if old:
                new = norm_designers(old, all_people(cat))
                if new != old:
                    obj[fld] = new
                    n += 1
    return n


def creators_problems(people):
    """Texts about the Creators list that look wrong: the same code twice is not possible here (a dict), but the same NAME under two
    codes, a code that contains , + / (those separate designers), and COMBINATIONS that exist twice (two entries made of the same
    people - 'S R = Richard Smith + Jim Reader' and a second entry for RS + JR, or a code like 'DO, BRW')."""
    out = []
    byname = {}
    for c, n in people.items():
        byname.setdefault(" ".join(n.lower().split()), []).append(c)
        if re.search(r"[,+/]", c):
            out.append("The code '%s' contains , + or /  - those separate designers, so this code can never be used.  Pick a code without them." % c)
    for n, cs in byname.items():
        if len(cs) > 1:
            out.append("The name '%s' is used by more than one code: %s." % (people[cs[0]], ", ".join(cs)))
    singles = {c: n for c, n in people.items() if not re.search(r"[+&/,]|\band\b", n) and not re.search(r"[,+/]", c)}

    def members(code, name):
        parts = [p.strip() for p in re.split(r"[,+/]|&|\band\b", name) if p.strip()]
        if len(parts) < 2:
            parts = [p.strip() for p in re.split(r"[,+/]", code) if p.strip()]
        if len(parts) < 2:
            return None
        return frozenset(resolve_code(singles, p) for p in parts)
    seen = {}
    for c, n in people.items():
        mem = members(c, n)
        if mem and len(mem) >= 2:
            seen.setdefault(mem, []).append(c)
    for mem, cs in seen.items():
        if len(cs) > 1:
            out.append("The combination %s already exists more than once: %s." % (" + ".join(sorted(mem)), ", ".join(cs)))
    return out


GAP_STATES = [("probable", "Probably missing"), ("never", "Never released / does not exist"), ("looking", "Looking for it")]


def draft_gaps(cat, m):
    """[{label, state}] - drafts that are PROBABLY missing because the ones I have skip over them: originals 1b, 1c, 1f -> 1d, 1e.
    Only a guess (someone may have kept 1d private until 1f), so each one has a state I set: probable (default), never (it does not
    exist - stop asking) or looking (I want it: the page lists it under Wanted).  Looks only between the lowest and the highest
    letter of the same number (and between numbers), so it never invents drafts before the first or after the last one."""
    by_major, comma = {}, False
    for f in cat["files"]:
        if f.get("map") != m["id"] or f.get("gone") or f.get("col") != "orig" or f.get("copy_of"):
            continue
        lab = str(f.get("draft", "")).strip().lower()
        a = re.fullmatch(r"(\d+)([a-z])", lab)
        b = re.fullmatch(r"(\d+),(\d+)", lab)
        c = re.fullmatch(r"(\d+)", lab)
        if a:
            by_major.setdefault(int(a.group(1)), set()).add(ord(a.group(2)) - 96)
        elif b:
            by_major.setdefault(int(b.group(1)), set()).add(int(b.group(2)))
            comma = True
        elif c:
            by_major.setdefault(int(c.group(1)), set()).add(0)
    labels = []
    for major, minors in sorted(by_major.items()):
        letters = sorted(x for x in minors if x > 0)
        for x in range(letters[0] + 1, letters[-1]) if len(letters) >= 2 else ():
            if x not in minors:
                labels.append(("%d,%d" % (major, x)) if comma else "%d%s" % (major, chr(96 + x)))
    majors = sorted(by_major)
    for mj in range(majors[0] + 1, majors[-1]) if len(majors) >= 2 else ():
        if mj not in by_major:
            labels.append(str(mj))
    ack = m.get("gap_ack") or {}
    return [{"label": lab, "state": ack.get(lab, "probable")} for lab in labels]


def gap_text(cat, m, states=("probable", "looking")):
    return ", ".join(g["label"] for g in draft_gaps(cat, m) if g["state"] in states)


def wanted_note(cat, m):
    """The public note of a map for the page: my quality note + the drafts I am looking for."""
    bits = [m.get("qnote", "")]
    looking = gap_text(cat, m, ("looking",))
    if looking:
        bits.append("Looking for draft " + looking)
    return "; ".join(b for b in bits if b)


def version_label(f):
    """'Original 1b' / 'Version 2' ... - what a visitor calls a file."""
    return (COL_NAME.get(f["col"], f["col"]) + (" " + str(f["draft"]) if f.get("draft") else "")).strip()


def help_items(m, fl):
    """The questions for visitors on a map: [{"w": what it is about, "q": the question, "i": index of the file in the page data or -1}].
    `fl` = the map's files in page order (those that are on the page); a question on a file that is not on the page is not shown."""
    out = []
    if (m.get("help") or "").strip():
        out.append({"w": "Whole map", "q": m["help"].strip(), "i": -1})
    for i, f in enumerate(fl):
        if (f.get("help") or "").strip():
            out.append({"w": version_label(f) + (" (" + os.path.basename(f["path"]) + ")"), "q": f["help"].strip(), "i": i})
    return out


def picture_count(cat, m):
    """How many map FILES (not the text files: places, invalid races, comments) the map has right now."""
    return sum(1 for f in cat["files"] if f.get("map") == m["id"] and included(f) and f.get("col") not in TXT_COLS)


def marks_to_ask_about(cat, ids=None):
    """Maps marked COMPLETELY MISSING that have got more files since the mark was made (or since I last said 'keep it').
    The mark remembers how many files the map had then (nothing_files; a mark from before that was written counts 0)."""
    return [m for m in cat["maps"] if m.get("nothing") and (ids is None or m["id"] in ids)
            and picture_count(cat, m) > int(m.get("nothing_files", 0) or 0)]

def map_quality(cat, m, files=None):
    """The mark of a map: the worst of its own mark and the mark of its NEWEST original (what the page shows first).
    A map with no included file at all counts as 'missing'."""
    if files is None:
        files = [f for f in cat["files"] if f.get("map") == m["id"] and included(f)]
    best = m.get("quality", "") or ""
    if m.get("nothing"):
        return "missing"                                  # marked COMPLETELY MISSING by hand (other files do not change that)
    orig = sort_versions([f for f in files if f["col"] == "orig" and not f.get("copy_of")])
    if orig and QUALITY_RANK.get(orig[-1].get("quality", ""), 0) > QUALITY_RANK.get(best, 0):
        best = orig[-1]["quality"]
    if not best and any(g["state"] == "looking" for g in draft_gaps(cat, m)):
        best = "minor"                                    # I am looking for a draft of it
    if not files and not best:
        best = "missing"
    return best


def map_done_state(cat, m, files=None):
    """(state, done_count, file_count) of a map: state is 'done' when every file of the map (not gone, not ignored) is marked done,
    'partly' when only some are, '' when none is (or the map has no file).  `done` is the 'I am finished with this file' mark
    (Save & Done); it is separate from `confirmed` and never goes to the page."""
    if files is None:
        files = [f for f in cat["files"] if f.get("map") == m["id"] and not f.get("gone") and not f.get("ign")]
    n = len(files)
    d = sum(1 for f in files if f.get("done"))
    if n and d == n:
        return "done", d, n
    return ("partly" if d else ""), d, n


# *************** DEL 21c - CODES (MISSING / FREE / UNOFFICIAL), THE LO CHECK, COMMENT FILES *****************
# ToDo (Lars 2026-11-14): (1) which maps have NO code, which codes are free (usually AA..XX) and an UNOFFICIAL code for a map without
# one - kept in `ucode`, never in `code` (that is the sheet's), always shown with a "~" and described as unofficial, and it GIVES WAY
# (is removed and logged in cat["ucode_log"]) the moment the map gets an official code or another map gets that very code.
# (2) LO (Lars) draws .bmp only: a jpg / pdf in the Issu's column, or with LO as designer, is a mistake.
# (3) The `.comments` file of a map (one per map) fills the map's "Exceptions / comments" field, minus the word NOTE:.
# (4) A file shown in a list as 'jpg' = a real .jpg / .jpeg.

NO_CODE_WORDS = ("", "-", "?", "???")
CODE_RANGE_DEFAULT = ("AA", "XX")                       # the unused codes are usually in this range
CODE_STOP_WORDS = {"the", "of", "and", "de", "du", "la", "le", "to", "a"}
NOT_LO_EXT = {".jpg", ".jpeg", ".png", ".gif", ".pdf"}   # LO only ever makes .bmp
JPG_EXT = {".jpg", ".jpeg"}
UCODE_NOTE = ("UNOFFICIAL - not a Railway Rivals code.  It is only a suggestion for a map that has no official code, and it is "
              "removed by itself as soon as the map gets a real code or another map gets this very code.")


def code_base(code):
    """'BB(N)' -> 'BB', 'CD??' -> 'CD', 'B?' -> 'B'.  '-', '?', '???' and empty -> '' (the map has no code)."""
    s = re.sub(r"\([^)]*\)", "", str(code or "")).replace("?", "").strip().upper()
    return "" if s in ("", "-") else s


def maps_without_code(cat, hidden=False):
    return [m for m in cat["maps"] if not code_base(m.get("code")) and (hidden or not m.get("hidden"))]


def official_taken(cat):
    """{code: [maps]} - every official code (code_base) of every map, hidden maps too."""
    d = {}
    for m in cat["maps"]:
        b = code_base(m.get("code"))
        if b:
            d.setdefault(b, []).append(m)
    for m in cat["maps"]:                                   # the other codes of a map (SG = English edition ...) are taken as well
        for code, _note in alt_codes(m):
            b = code_base(code)
            if b and m not in d.setdefault(b, []):
                d[b].append(m)
    return d


def unofficial_taken(cat, skip=None):
    """{code: map} of the unofficial codes in use (not counting the map `skip`)."""
    d = {}
    for m in cat["maps"]:
        u = str(m.get("ucode") or "").strip().upper()
        if u and m is not skip and not code_base(m.get("code")):
            d.setdefault(u, m)
    return d


def ucode_label(m):
    """'~AB' for the unofficial code of a map that has no official one, else ''."""
    u = str(m.get("ucode") or "").strip().upper()
    return ("~" + u) if u and not code_base(m.get("code")) else ""


def code_shown(m):
    """What the Code column shows: the official code, else the unofficial one with its '~', else what the sheet has (-, ???)."""
    return m.get("code", "") if code_base(m.get("code")) else (ucode_label(m) or m.get("code", ""))


def code_sequence(length, lo="", hi=""):
    """Every letter code of `length` letters in alphabetical order (AA, AB ... AZ, BA ...), limited to lo..hi when those have that length."""
    import itertools
    lo, hi = str(lo or "").upper(), str(hi or "").upper()
    out = []
    for tup in itertools.product(string.ascii_uppercase, repeat=length):
        c = "".join(tup)
        if len(lo) == length and c < lo:
            continue
        if len(hi) == length and c > hi:
            continue
        out.append(c)
    return out


def free_code_rows(cat, length=2, lo="AA", hi="XX"):
    """[(code, status, map name)] for every code of the range: status 'free', 'official' or 'unofficial'."""
    off, unoff = official_taken(cat), unofficial_taken(cat)
    rows = []
    for c in code_sequence(length, lo, hi):
        if c in off:
            rows.append((c, "official", off[c][0]["name"]))
        elif c in unoff:
            rows.append((c, "unofficial", unoff[c]["name"]))
        else:
            rows.append((c, "free", ""))
    return rows


def ucode_candidates(name, length=2):
    """Codes that could be made from a map name, best first: the initials of the words (North Korea -> NK), the first letters, then the
    first letter + every later letter of the name (Afghanistan -> AF, AG, AH ...)."""
    import itertools
    words = [re.sub(r"[^a-z]", "", w) for w in norm_key(name).split() if w not in CODE_STOP_WORDS]
    words = [w for w in words if w]
    out = []

    def add(c):
        c = c.upper()
        if len(c) == length and c.isalpha() and c not in out:
            out.append(c)
    if not words:
        return out
    add("".join(w[0] for w in words)[:length])
    add(words[0][:length])
    allletters = "".join(words)
    add(words[0][0] + "".join(w[0] for w in words[1:])[:length - 1])
    for combo in itertools.combinations(allletters[1:], length - 1):
        add(allletters[0] + "".join(combo))
    return out


def ucode_options(cat, m, length=2, lo="AA", hi="XX"):
    """Every code that could be the unofficial code of map `m`, best first (name based ones, then the rest of the range): not official,
    not the unofficial code of another map.  'Next suggestion' walks through this list."""
    off, used = official_taken(cat), set(unofficial_taken(cat, skip=m))
    inrange = code_sequence(length, lo, hi)
    out = []
    for c in ucode_candidates(m["name"], length) + inrange:
        if c in inrange and c not in off and c not in used and c not in out:
            out.append(c)
    return out


def check_ucode(cat, m, code):
    """'' when `code` may be the unofficial code of map `m`, else the reason why not (text for the user)."""
    c = str(code or "").strip().upper()
    if not c:
        return "The code is empty."
    if not re.fullmatch(r"[A-Z][A-Z0-9]{0,4}", c):
        return "An unofficial code is 1-5 letters/digits, starting with a letter."
    if code_base(m.get("code")):
        return "'%s' has an official code (%s) already." % (m["name"], m.get("code"))
    off = official_taken(cat).get(c)
    if off:
        return "%s is an OFFICIAL code (%s)." % (c, off[0]["name"])
    other = unofficial_taken(cat, skip=m).get(c)
    if other:
        return "%s is already the unofficial code of %s." % (c, other["name"])
    return ""


def suggest_ucodes(cat, length=2, lo="AA", hi="XX", renew=False, only=None):
    """[(map, code)] - a code for every visible map without an official code (and, unless `renew`, without an unofficial one).
    Free = not official and not unofficial for another map; inside lo..hi.  Names decide first, then the first free code of the range."""
    off, used = official_taken(cat), set(unofficial_taken(cat))
    inrange = set(code_sequence(length, lo, hi))
    todo = [m for m in maps_without_code(cat) if renew or not str(m.get("ucode") or "").strip()]
    if only is not None:                                # just this map / these maps (a hidden map may be asked for by hand)
        todo = list(only) if isinstance(only, (list, tuple)) else [only]
    if renew:
        used -= {str(m.get("ucode") or "").strip().upper() for m in todo}
    spare = [c for c in code_sequence(length, lo, hi) if c not in off and c not in used]
    out = []
    for m in sorted(todo, key=lambda x: norm_key(x["name"])):
        pick = next((c for c in ucode_candidates(m["name"], length) if c in inrange and c not in off and c not in used), None)
        if pick is None:
            pick = next((c for c in spare if c not in used), None)
        if pick is None:
            continue                                     # the range is full
        used.add(pick)
        out.append((m, pick))
    return out


def settle_unofficial(cat, today=None):
    """An unofficial code backs off: when its map got an official code, when another map now has that official code, or when two
    maps hold the same unofficial code.  The code is removed from the map and written to cat['ucode_log'] (seen=False until I have been
    told).  Returns the new lines of text."""
    today = today or time.strftime("%Y-%m-%d")
    off = official_taken(cat)
    notes, seen = [], {}
    for m in sorted(cat["maps"], key=lambda x: norm_key(x["name"])):
        u = str(m.get("ucode") or "").strip().upper()
        if not u:
            continue
        why = ""
        if code_base(m.get("code")):
            why = "%s now has its own official code (%s)" % (m["name"], m.get("code"))
        elif u in off:
            why = "%s is now the OFFICIAL code of %s" % (u, off[u][0]["name"])
        elif u in seen:
            why = "%s already holds this unofficial code" % seen[u]["name"]
        if why:
            m.pop("ucode", None)
            m.pop("ucode_date", None)
            line = "The unofficial code %s of %s gave way: %s." % (u, m["name"], why)
            cat.setdefault("ucode_log", []).append({"date": today, "map": m["name"], "code": u, "text": line, "seen": False})
            notes.append(line)
        else:
            m["ucode"] = u
            seen[u] = m
    return notes


def lo_problems(cat):
    """[(file record, why)] - jpg / png / gif / pdf files that sit in the Issu's column or have LO among their designers."""
    out = []
    for f in cat["files"]:
        if f.get("gone") or f.get("ign"):
            continue
        ext = os.path.splitext(f["path"])[1].lower()
        if ext not in NOT_LO_EXT:
            continue
        why = []
        if f.get("col") in ME_COLS:
            why.append("in the Issu's column")
        if ME_CODE in [c for c, _s in parse_designers(f.get("by", ""))]:
            why.append("LO is its designer")
        if why:
            out.append((f, " + ".join(why)))
    return out


def lo_fix(cat, recs, col_for_images="orig"):
    """Moves the files out of the Issu's column (images -> `col_for_images`, pdf -> PDF) and takes LO away from their designers.
    The designer field is marked as typed by hand, so nothing puts LO back.  Returns the number of files changed."""
    n = 0
    for f in recs:
        ext = os.path.splitext(f["path"])[1].lower()
        if f.get("col") in ME_COLS:
            f["col"] = "pdf" if ext == ".pdf" else col_for_images
            f["manual"] = True
        items = [(c, s) for c, s in parse_designers(f.get("by", "")) if c != ME_CODE]
        f["by"] = fmt_designers(items)
        f["by_edited"] = True
        n += 1
    return n


def comment_text(raw):
    """The text of a `.comments` file for the map's Exceptions field: the word NOTE: at the start is dropped, empty lines are
    dropped, the lines are joined with ' | ' (the field is one line)."""
    lines = [l.strip() for l in str(raw or "").replace("\r", "").split("\n")]
    lines = [l for l in lines if l]
    if lines:
        lines[0] = re.sub(r"^note\s*:\s*", "", lines[0], flags=re.I).strip()
    return " | ".join(l for l in lines if l)


def read_text_file(path):
    with open(path, "rb") as fh:
        data = fh.read(200000)
    for enc in ("utf-8-sig", "cp1252"):
        try:
            return data.decode(enc)
        except UnicodeDecodeError:
            continue
    return data.decode("utf-8", "replace")


def apply_comment_files(cat, say=print):
    """Every map with a `.comments` file gets its text in the field Note (`fnote`; NOTE: dropped).  The sheet's own text stays in
    Exceptions / comments - two fields (Lars 2026-11-14).  Rules: a Note I typed myself (`edited`) is never touched; an empty Note is
    filled; a Note that holds the text of an earlier read is refreshed.  Several `.comments` files on one map -> the newest is used.
    Returns how many maps changed."""
    by_map = {}
    for f in cat["files"]:
        if f.get("map") and not f.get("gone") and not f.get("ign") and f["path"].lower().endswith(".comments") and os.path.isfile(f["path"]):
            by_map.setdefault(f["map"], []).append(f)
    maps = map_by_id(cat)
    for m in cat["maps"]:                       # first version (2026-11-14) wrote the file text into Exceptions: take it back out again
        old = m.pop("exc_file_text", None)
        if old is not None and str(m.get("exceptions", "") or "").strip() == old and "exceptions" not in m.get("edited", []):
            m["exceptions"] = ""
    changed = 0
    for mid, files in by_map.items():
        m = maps.get(mid)
        if m is None:
            continue
        files.sort(key=lambda f: os.path.getmtime(f["path"]))
        try:
            text = comment_text(read_text_file(files[-1]["path"]))
        except OSError:
            continue
        if len({comment_text(read_text_file(f["path"])) for f in files if os.path.isfile(f["path"])}) > 1:
            say("  %s has %d different .comments files - the newest is used." % (m["name"], len(files)))
        if not text or "fnote" in m.get("edited", []):
            continue
        cur = str(m.get("fnote", "") or "").strip()
        if cur == text:
            m["fnote_src"] = text
        elif not cur or cur == m.get("fnote_src"):
            m["fnote"], m["fnote_src"] = text, text
            changed += 1
    say("Comment files: %d map(s) got their .comments text in the Note field." % changed)
    return changed


def hide_comments2(cat):
    """`.comments2` files hold what is already on the map (I write it in Details by hand): they are hidden like an ignored file.
    Returns how many were hidden now."""
    n = 0
    for f in cat["files"]:
        if f["path"].lower().endswith(".comments2") and not f.get("ign"):
            f["ign"], f["ign_why"] = True, "comments2"
            n += 1
    return n


def map_has_jpg(files):
    return any(os.path.splitext(f["path"])[1].lower() in JPG_EXT for f in files if not f.get("gone") and not f.get("ign"))


def steps_after_sheet_or_scan(cat, say=print):
    """Runs after every Scan folders / Import Excel: the .comments texts go into Exceptions, unofficial codes back off for official
    ones, and a jpg / pdf in LO's column is reported."""
    apply_comment_files(cat, say)
    for line in settle_unofficial(cat):
        say(line)
    n = migrate_looks(cat)
    if n:
        say("%d version(s) got their Look (black & white / coloured) from a note or a file name." % n)
    fix_copies(cat)
    auto_copies(cat, say)                    # the SURE copies (same name + draft); the unsure ones wait in 'Find copies...'
    left = [c for c in copy_candidates(cat, pictures=False) if c[0] == "probable"]
    if left:
        say("%d pair(s) of pictures MIGHT be copies of each other - press 'Find copies...' to decide." % len(left))
    bad = lo_problems(cat)
    if bad:
        say("WARNING: %d jpg/pdf file(s) are in the Issu's column or have LO as designer - LO is .bmp only.  Press 'Check LO...'." % len(bad))


# *************** DEL 21d - LOOK, WHAT WAS DONE, COPIES, OTHER CODES, TIMELINE (Lars 2026-11-16) *****************
# ToDo (Lars 2026-11-16): (1) a TIMELINE of every map: the first version to the left, the later drafts to the right, then who made each
# version and what was done to it (revised, coloured, cosmetic change, digitalized ...), and far right who designed the FIRST map and its
# code(s) (a map may have changed its code or have two, like South Germany: SG for the English and SD for the German edition).
# (2) the LOOK of a version: Black & white / Hand-coloured (coloured in afterwards, by hand) / Printed in colour.  Old notes that only say
# "Black & white" or "Coloured" are turned into this field by themselves (migrate_looks).
# (3) COPIES: two photos / scans of the very same draft (maybe different light) are ONE version - the extra file is a copy of the main
# file (`copy_of` = path of the main file) and is never counted as a new design.  Sure ones are marked by themselves (same name + draft +
# compatible designers / date / look), unsure ones wait in "Find copies...".  A black & white map and the same draft coloured in
# afterwards are NOT copies (different look = a version of its own).
# ToDo (later): more clever picture matching (photos taken at an angle give a poor pixel match, so names / draft / date decide).

# The three built-in looks are fixed (never removed or renamed).  My OWN options (Sources & folders > "My 'Look' options") are added after
# them, key "u_<name>"; an own option that is IN USE on a version can be neither removed nor re-spelled (see settings_dialog / parse_extra_looks).
LOOKS_BUILTIN = [("", "Not known"), ("bw", "Black & white"), ("hand", "Hand-coloured (coloured in afterwards)"), ("print", "Printed in colour")]
LOOKS = list(LOOKS_BUILTIN)                         # rebuilt IN PLACE by apply_custom_options (every menu reads it)
LOOK_LABEL = dict(LOOKS)
LOOK_SHORT_BUILTIN = {"bw": "B&W", "hand": "hand-coloured", "print": "colour print"}
LOOK_SHORT = dict(LOOK_SHORT_BUILTIN)


def parse_extra_looks(text):
    """'Sepia, Pencil drawing' -> [('u_sepia', 'Sepia'), ('u_pencil_drawing', 'Pencil drawing')].  A label equal to a built-in one (or to its
    short form) is skipped, and so is a second label that gives the same key.  The key comes from the spelling (letters / digits only)."""
    taken = {v.lower() for k, v in LOOKS_BUILTIN if k} | {v.lower() for v in LOOK_SHORT_BUILTIN.values()} | {"not known"}
    out, keys = [], set()
    for label in split_list(text):
        key = "u_" + re.sub(r"[^a-z0-9]+", "_", label.lower()).strip("_")
        if label.lower() in taken or key == "u_" or key in keys:
            continue
        keys.add(key)
        out.append((key, label))
    return out
CHANGE_CHOICES = ["First version", "Revised", "Cosmetic change", "Coloured", "Digitalized", "Redrawn", "Corrected", "Tidied up"]
COPY_COLS = ("orig", "version", "issu")
TIMELINE_COLS = ("orig", "version")                 # the designs: my own colourings (Issu's) and the json files are not part of the timeline
BW_RE = re.compile(r"black\s*(?:&|and|/|-)?\s*white|\bb\s*[&/]\s*w\b|svartvit", re.I)
HAND_RE = re.compile(r"\bcolou?red\b", re.I)
WHOLE_NOTE_LOOK = {"black & white": "bw", "black and white": "bw", "b&w": "bw", "b/w": "bw", "bw": "bw", "b & w": "bw",
                   "coloured": "hand", "colored": "hand", "hand coloured": "hand", "hand-coloured": "hand", "coloured by hand": "hand",
                   "colour": "print", "color": "print", "in colour": "print", "printed in colour": "print", "colour print": "print"}


def look_from_note(note):
    """(look, rest of the note).  A note that only says 'Black & white' / 'Coloured' / 'Colour' becomes the look and the note is empty;
    a longer note that mentions black & white or 'coloured' gives the look and is kept as it is."""
    t = str(note or "").strip()
    if not t:
        return "", ""
    plain = re.sub(r"[\s.,;!]+", " ", t).strip().lower()
    if plain in WHOLE_NOTE_LOOK:
        return WHOLE_NOTE_LOOK[plain], ""
    if BW_RE.search(t):
        return "bw", t
    if HAND_RE.search(t):
        return "hand", t
    return "", t


def migrate_looks(cat):
    """The old way was a note ('Black & white', 'Coloured') - fill the Look field from it (and from a '(b&w)' in the file name) where the
    look is empty and was not set by hand.  Idempotent.  Returns how many files changed."""
    n = 0
    for f in cat.get("files", []):
        if f.get("col") not in COPY_COLS or f.get("look") or f.get("look_edited"):
            continue
        look, rest = look_from_note(f.get("note"))
        if look:
            f["look"], f["note"] = look, rest
            n += 1
        elif BW_RE.search(os.path.basename(f.get("path", ""))):
            f["look"] = "bw"
            n += 1
    return n


def known_changes(cat):
    """The Pick... list of 'What was done': the usual words + everything already typed."""
    used = {f.get("change", "").strip() for f in cat["files"] if f.get("change", "").strip()}
    return sorted(set(CHANGE_CHOICES) | used, key=str.lower)


# ---- other codes of a map ----
def alt_codes(m):
    """[(code, note)] from the map's `codes2` text: 'SG=English, XY=old code until 1998' (comma / semicolon / new line; 'SG (English)' works too)."""
    out = []
    for part in split_list(m.get("codes2", "")):
        mm = re.match(r"^([^\s=:(]+)\s*[=:(]?\s*(.*?)\)?$", part)
        if mm and mm.group(1).strip("?"):
            out.append((mm.group(1).upper(), mm.group(2).strip()))
    return out


def codes_text(m):
    """The code(s) of a map as one text: 'SD  (also SG = English)'."""
    main = code_shown(m)
    extra = ", ".join(c + ((" = " + n) if n else "") for c, n in alt_codes(m))
    return (main + ("  (also " + extra + ")" if extra else "")).strip()


# ---- copies ----
PART_WORDS = {"top", "bottom", "left", "right", "upper", "lower", "north", "south", "east", "west", "part", "sheet", "page", "inset", "side",
              "front", "back", "northern", "southern", "eastern", "western", "centre", "center", "middle"}
SIG_CACHE = {}


def copy_key(basename):
    """The name of a picture reduced to what says WHICH map and draft it is: no code prefix, no 'kopia / copy / (2)', 'draft' word gone,
    brackets opened ('Georgia_(draft_1c)' and 'Georgia_1c' give the same key).  '(a)' / '(b)' stay: they are often two sheets of one map."""
    s = os.path.splitext(basename)[0].replace("_", " ")
    s = re.sub(r"^[A-Za-z]{1,4}(?:\([A-Za-z]\))?\s*---\s*", "", s)
    s = re.sub(r"(?i)\b(kopia|copy|kopie)\b", " ", s)
    s = re.sub(r"\(\s*\d\s*\)", " ", s)
    s = re.sub(r"(?i)\bdraft\s*v?\s*", " ", s)
    s = re.sub(r"\(([^)]*)\)", r" \1 ", s)
    return norm_key(s)


def _codes_set(text):
    return {c.strip("? ").upper() for c, _s in parse_designers(text) if c.strip("? ")}


def designers_compatible(a, b):
    sa, sb = _codes_set(a), _codes_set(b)
    return not sa or not sb or sa == sb


def dates_compatible(a, b):
    pa, pb = parse_date(a) or "", parse_date(b) or ""
    return not pa or not pb or pa.startswith(pb) or pb.startswith(pa)


def looks_compatible(a, b):
    return not a or not b or a == b


def _picture_sig(path, n=16):
    """A tiny grey picture (n x n, contrast stretched) + the width/height ratio, or None.  Cached by path + time."""
    try:
        key = (path, os.path.getmtime(path))
        if key in SIG_CACHE:
            return SIG_CACHE[key]
        sig = None
        if os.path.splitext(path)[1].lower() in (".jpg", ".jpeg", ".png", ".gif") and os.path.getsize(path) < 30000000:
            from PIL import Image, ImageOps
            with Image.open(path) as im:
                im.draft("L", (n * 8, n * 8))
                im = im.convert("L")
                asp = im.width / float(im.height or 1)
                sig = (list(ImageOps.autocontrast(im.resize((n, n))).tobytes()), asp)
        SIG_CACHE[key] = sig
        return sig
    except Exception:
        return None


def picture_match(fa, fb):
    """0..1: how much the two pictures look alike (grey 16x16 correlation), None when one cannot be read.  Photos of one map taken at
    other angles score low - it is only a hint, never the decision."""
    sa, sb = _picture_sig(fa["path"]), _picture_sig(fb["path"])
    if not sa or not sb:
        return None
    a, b = sa[0], sb[0]
    n = len(a)
    ma, mb = sum(a) / float(n), sum(b) / float(n)
    va = sum((x - ma) ** 2 for x in a) ** 0.5
    vb = sum((y - mb) ** 2 for y in b) ** 0.5
    if va == 0 or vb == 0:
        return None
    return max(0.0, sum((x - ma) * (y - mb) for x, y in zip(a, b)) / (va * vb))


def fix_copies(cat):
    """Drops a copy link that no longer makes sense (the main file is gone / ignored / on another map or in another column, or itself a
    copy: chains are shortened first).  Returns how many links were dropped."""
    by_path = {f.get("path", "").lower(): f for f in cat.get("files", [])}
    n = 0
    for f in cat.get("files", []):
        hops = 0
        while f.get("copy_of") and hops < 6:
            g = by_path.get(f["copy_of"].lower())
            if g is not None and g is not f and g.get("copy_of"):
                f["copy_of"] = g["copy_of"]
                hops += 1
            else:
                break
    for f in cat.get("files", []):
        p = f.get("copy_of")
        if not p:
            continue
        g = by_path.get(p.lower())
        if not (g is not None and g is not f and not g.get("copy_of") and f.get("map") and g.get("map") == f.get("map")
                and g.get("col") == f.get("col") and not g.get("gone") and not g.get("ign") and not f.get("ign")):
            f.pop("copy_of", None)
            f.pop("copy_why", None)
            n += 1
    return n


def copies_of(cat, primary):
    return [f for f in cat["files"] if f.get("copy_of") and f["copy_of"].lower() == primary["path"].lower()]


def primary_of(cat, f):
    if not f.get("copy_of"):
        return None
    return next((g for g in cat["files"] if g["path"].lower() == f["copy_of"].lower()), None)


def best_primary(files):
    """The file that stays the MAIN one of a group of copies: the best quality mark, confirmed, the biggest picture, the shortest path."""
    return sorted(files, key=lambda f: (QUALITY_RANK.get(f.get("quality", ""), 0), 0 if f.get("confirmed") else 1,
                                        -int(f.get("size", 0) or 0), len(f.get("path", ""))))[0]


def apply_copy(cat, primary, copy_f, why=""):
    """`copy_f` becomes a copy of `primary` (its own copies follow).  Empty facts of the main file are filled from the copy."""
    for g in cat["files"]:
        if g.get("copy_of") and g["copy_of"].lower() == copy_f["path"].lower():
            g["copy_of"] = primary["path"]
    copy_f["copy_of"], copy_f["copy_why"] = primary["path"], why
    for k in ("date", "by", "helped", "tool", "look", "change"):
        if not primary.get(k) and copy_f.get(k):
            primary[k] = copy_f[k]
    for lst in (primary.get("not_copy"), copy_f.get("not_copy")):
        if lst:
            for p in list(lst):
                if p.lower() in (primary["path"].lower(), copy_f["path"].lower()):
                    lst.remove(p)


def unmark_copy(cat, f):
    """The file is NOT a copy after all: it becomes a version of its own and is never offered as a copy of that file again."""
    p = f.pop("copy_of", None)
    f.pop("copy_why", None)
    if p:
        f.setdefault("not_copy", [])
        if p not in f["not_copy"]:
            f["not_copy"].append(p)


def make_primary(cat, f):
    """The copy `f` becomes the MAIN file; the old main file and the other copies become its copies."""
    old = primary_of(cat, f)
    if old is None:
        return
    others = copies_of(cat, old)
    f.pop("copy_of", None)
    f.pop("copy_why", None)
    for g in [old] + [x for x in others if x is not f]:
        g["copy_of"], g["copy_why"] = f["path"], g.get("copy_why") or "made main file by hand"


def _picture_ratio(path):
    """Width / height of a picture (only the file header is read), None when it cannot be read."""
    try:
        key = ("shape", path, os.path.getmtime(path))
        if key not in SIG_CACHE:
            from PIL import Image
            with Image.open(path) as im:
                SIG_CACHE[key] = im.width / float(im.height or 1)
        return SIG_CACHE[key]
    except Exception:
        return None


def same_shape(a, b):
    """False when two pictures cannot be the same sheet: a landscape and a portrait one are the same sheet turned 90 degrees (fine), but a
    long strip and a squarish page are not.  Unreadable pictures count as fitting."""
    ra, rb = _picture_ratio(a["path"]), _picture_ratio(b["path"])
    if not ra or not rb:
        return True
    return max(ra, rb) / min(ra, rb) <= 1.3 or abs(ra * rb - 1.0) <= 0.3


def copy_pair(a, b, pictures=True):
    """None, or (level, why, match) for two files that might be the same draft photographed twice.  level 'sure' = same name and draft;
    'probable' = same draft and the facts agree, and something else points the same way (the same date, a similar name, a similar picture)."""
    if a.get("col") != b.get("col") or a.get("map") != b.get("map") or not a.get("map"):
        return None
    if str(a.get("draft", "")).strip().lower() != str(b.get("draft", "")).strip().lower():
        return None
    if not (looks_compatible(a.get("look", ""), b.get("look", "")) and designers_compatible(a.get("by", ""), b.get("by", ""))
            and dates_compatible(a.get("date", ""), b.get("date", ""))):
        return None
    if a["path"].lower() in [p.lower() for p in b.get("not_copy", [])] or b["path"].lower() in [p.lower() for p in a.get("not_copy", [])]:
        return None
    ka, kb = copy_key(os.path.basename(a["path"])), copy_key(os.path.basename(b["path"]))
    if ka and ka == kb:
        if same_shape(a, b):
            return ("sure", "same name and draft", None)
        return ("probable", "same name and draft, but the pictures have different shapes", picture_match(a, b) if pictures else None)
    diff = set(ka.split()) ^ set(kb.split())
    if any(t in PART_WORDS or len(t) <= 1 for t in diff):          # (a) / (b), top / bottom ... = two sheets of one map, not two photos
        return None
    if re.search(r"\d{4}", " ".join(diff)) or (ka != kb and re.sub(r"\d", "", ka) == re.sub(r"\d", "", kb)):
        return None                                                  # another year in the name, or only a number differs (Canada1 / Canada2)
    why = []
    da, db = parse_date(a.get("date", "")) or "", parse_date(b.get("date", "")) or ""
    if da and da == db:
        why.append("same date")
    if ka and kb and difflib.SequenceMatcher(None, ka, kb).ratio() >= 0.75:
        why.append("similar names")
    match = picture_match(a, b) if pictures else None
    if match is not None and match >= 0.8:
        why.append("similar picture %d%%" % round(match * 100))
    return ("probable", ", ".join(why), match) if why else None


def copy_candidates(cat, only_map=None, pictures=True):
    """[(level, a, b, why, match)] for every pair of files that might be copies of each other (files already marked as a copy are not
    looked at; a main file can still get new copies)."""
    groups = {}
    for f in cat.get("files", []):
        if (f.get("map") and (only_map is None or f["map"] == only_map) and not f.get("gone") and not f.get("ign") and not f.get("copy_of")
                and f.get("col") in COPY_COLS and os.path.splitext(f.get("path", ""))[1].lower() in IMG_EXT):
            groups.setdefault((f["map"], f["col"], str(f.get("draft", "")).strip().lower()), []).append(f)
    out = []
    for fl in groups.values():
        for i in range(len(fl)):
            for j in range(i + 1, len(fl)):
                r = copy_pair(fl[i], fl[j], pictures)
                if r:
                    out.append((r[0], fl[i], fl[j], r[1], r[2]))
    return out


def auto_copies(cat, say=print):
    """Marks the SURE copies (same name + draft, facts agree) as copies of the best file of their group.  Returns [(copy, main)]."""
    sure = {}
    for lvl, a, b, _why, _m in copy_candidates(cat, pictures=False):
        if lvl == "sure":
            sure.setdefault(a["path"], set()).add(b["path"])
            sure.setdefault(b["path"], set()).add(a["path"])
    by_path = {f["path"]: f for f in cat["files"]}
    clusters = []                         # a file joins a cluster only when it is a SURE copy of EVERY file in it (a file with an unknown look
    for p in sorted(sure):                # may be a copy of a black & white one and of a coloured one, but those two are not copies of each other)
        for cl in clusters:
            if all(q in sure[p] for q in cl):
                cl.append(p)
                break
        else:
            clusters.append([p])
    done = []
    for paths in clusters:
        fl = [by_path[p] for p in paths]
        if len(fl) < 2:
            continue
        main = best_primary(fl)
        for f in fl:
            if f is not main:
                apply_copy(cat, main, f, "same name and draft")
                done.append((f, main))
                say("  copy: %s is a copy of %s" % (os.path.basename(f["path"]), os.path.basename(main["path"])))
    if done:
        say("%d file(s) were marked as copies of another file of the same draft (not counted as new versions)." % len(done))
    return done


def real_versions(files):
    """The files that count as versions (copies left out)."""
    return [f for f in files if not f.get("copy_of")]


# ---- the timeline ----
def timeline_files(files):
    """The designs of a map, the oldest first: originals and versions (a redraw in another program), copies left out.  Same order rules
    as sort_versions (by date when every original has one)."""
    return sort_versions([f for f in files if f.get("col") in TIMELINE_COLS and not f.get("copy_of")])


def earliest_date(m, tl):
    """(sort key, text) of the EARLIEST date known for a map: the oldest date among its versions (`tl` = timeline_files) and the map's own
    Year.  The first version often has no date, so the first date that exists is used (Lars 2026-11-16).  ('', '') when nothing is known."""
    cands = [f.get("date", "") for f in tl] + [m.get("year", "")]
    cands = [c for c in cands if parse_date(c)]
    if not cands:
        return "", ""
    best = min(cands, key=date_key)
    return date_key(best), fmt_date(best)


def timeline_made(cat, f):
    """Who made this version and what was done: 'BRW + helped: AB - Cyberboard - revised' (the text of the 'Made by' columns)."""
    ppl = all_people(cat)
    bits = []
    by = " + ".join(codes_of(f.get("by", ""), ppl))
    if by:
        bits.append(by)
    hp = " + ".join(codes_of(f.get("helped", ""), ppl))
    if hp:
        bits.append("helped: " + hp)
    if f.get("tool"):
        bits.append(f["tool"])
    if f.get("change"):
        bits.append(f["change"])
    return " - ".join(bits)


def timeline_table(cat, find="", min_versions=0, kmax=8):
    """(k, rows) for the Timeline tab of the program: rows are [map id, map name, version cells (k), made-by cells (k), first designer, codes].
    The page builds the same thing from the page data."""
    by_map = {}
    for f in cat["files"]:
        if f.get("map") and not f.get("gone") and not f.get("ign"):
            by_map.setdefault(f["map"], []).append(f)
    rows = []
    t = norm_key(find)
    for m in cat["maps"]:
        if m.get("hidden"):
            continue
        tl = timeline_files(by_map.get(m["id"], []))
        if len(tl) < min_versions:
            continue
        who = " + ".join(names_of(cat, m.get("by", "")))
        if t and t not in norm_key(m["name"] + " " + m.get("code", "") + " " + m.get("codes2", "") + " " + who):
            continue
        rows.append((m, tl, who))
    # OLDEST FIRST (not alphabetical): by the earliest date known for the map; maps with no date at all come last, by name
    rows.sort(key=lambda r: (earliest_date(r[0], r[1])[0] == "", earliest_date(r[0], r[1])[0], norm_key(r[0]["name"])))
    k = max(1, min(kmax, max([len(tl) for _m, tl, _w in rows] or [1])))
    out = []
    for m, tl, who in rows:
        ver, made = [], []
        for i in range(k):
            grp = tl[i:] if i == k - 1 else tl[i:i + 1]
            ver.append("  |  ".join(" ".join(x for x in (
                (g.get("draft") or ("version" if g["col"] == "version" else "-")), fmt_date(g.get("date", "")), LOOK_SHORT.get(g.get("look", ""), ""),
                ("+%d cop%s" % (len(copies_of(cat, g)), "y" if len(copies_of(cat, g)) == 1 else "ies") if copies_of(cat, g) else "")) if x) for g in grp))
            made.append("  |  ".join(timeline_made(cat, g) for g in grp))
        ed = earliest_date(m, tl)[1]
        out.append([m["id"], m["name"] + (("   [%s]" % ed) if ed else "")] + ver + made + [who, codes_text(m)])
    return k, out


# *************** DEL 22 - SCAN THE LIBRARY FOLDERS *****************
# ToDo: a rescan keeps every manual choice (`manual` = column/draft/map typed by me), marks vanished files `gone`
# and never removes anything from the catalog by itself.

def rename_file_copy(cat, rec, new_name):
    """Renames a map file WITHOUT touching the original: the file is copied under the new name into a folder called 'renamed' that
    lies next to the file's own folder (inside 'renamed' itself when it is already there).  The catalog record follows the copy
    (map, draft, date ... stay) and the OLD path is remembered in cat['renamed'], so a scan never counts the original name again.
    Returns the new path."""
    old = rec["path"]
    if not os.path.isfile(old):
        raise OSError("The file is not there: " + old)
    name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", new_name).strip(" .")
    if not name:
        raise ValueError("The new name is empty.")
    if not os.path.splitext(name)[1]:
        name += os.path.splitext(old)[1]
    folder = os.path.dirname(old)
    dest_dir = folder if os.path.basename(folder).lower() == "renamed" else os.path.join(os.path.dirname(folder), "renamed")
    target = os.path.join(dest_dir, name)
    if os.path.exists(target) and target.lower() != old.lower():
        raise FileExistsError("There is already a file with that name in 'renamed': " + target)
    if target.lower() == old.lower():
        return old
    os.makedirs(dest_dir, exist_ok=True)
    shutil.copy2(old, target)
    cat.setdefault("renamed", {})[old.lower()] = target
    rec.setdefault("renamed_from", old)
    rec["path"], rec["pub"], rec["drive_id"], rec["manual"] = target, "", "", True
    return target


def import_copy(src, settings):
    """Where an added file should live.  Returns (path, copied).  The file is COPIED (never moved) into settings['import_dir']
    unless that is empty or the file already lies inside the import folder or one of the library folders.  A file with the same name
    but other content gets ' (2)', ' (3)' ... in its name; an identical copy that is already there is reused (nothing copied)."""
    import filecmp
    dest = (settings.get("import_dir") or "").strip()
    if not dest:
        return src, False
    src_n = os.path.normcase(os.path.abspath(src))
    for base in [dest] + [r.get("path", "") for r in settings.get("roots", [])]:
        if base:
            b = os.path.normcase(os.path.abspath(base)).rstrip("\\") + "\\"
            if src_n.startswith(b):
                return src, False
    os.makedirs(dest, exist_ok=True)
    stem, ext = os.path.splitext(os.path.basename(src))
    target, n = os.path.join(dest, stem + ext), 1
    while os.path.exists(target):
        if os.path.getsize(target) == os.path.getsize(src) and filecmp.cmp(src, target, shallow=False):
            return target, False
        n += 1
        target = os.path.join(dest, "%s (%d)%s" % (stem, n, ext))
    shutil.copy2(src, target)
    return target, True


def scan_covers(root, path, ignore=()):
    """True when scan_library would have LOOKED for this file under this root: inside the folder (a 'flat' root: directly in it,
    not in a sub-folder) and not in an ignored folder.  Before 2026-11-15 any path that merely started with the root counted, so files
    I had imported into a sub-folder of the flat root '1---Jobba_med' (2---Original-2027, renamed) were marked 'no longer there'."""
    base = os.path.normcase(os.path.abspath(root.get("path", ""))).rstrip("\\")
    p = os.path.normcase(os.path.abspath(path))
    if not base or not p.startswith(base + "\\"):
        return False
    rel_dirs = os.path.dirname(p)[len(base):].strip("\\")
    if not rel_dirs:
        return True
    if root.get("flat"):
        return False
    return not any(d in ignore for d in rel_dirs.lower().split("\\"))


def scan_library(cat, settings, say=print):
    ignore = {n.lower() for n in settings.get("ignore_folders", [])}
    known = {f["path"].lower(): f for f in cat["files"]}
    seen, found = set(), 0
    matcher = Matcher(cat)
    for root in settings.get("roots", []):
        top, role = root.get("path", ""), root.get("role", "original")
        if not os.path.isdir(top):
            say("Folder not found (skipped): %s" % top)
            continue
        say("Scanning %s  [%s]" % (top, role))
        for dirpath, dirs, names in os.walk(top):
            dirs[:] = [] if root.get("flat") else sorted(d for d in dirs if d.lower() not in ignore)
            rel = os.path.relpath(dirpath, top)
            rel = "" if rel == "." else rel
            for name in sorted(names):
                full = os.path.join(dirpath, name)
                col = classify(full, role, rel)
                if col is None:
                    continue
                try:
                    st = os.stat(full)
                except OSError:
                    continue
                key = full.lower()
                low_name = name.lower()
                if key in cat.get("renamed", {}):
                    continue                                 # the original of a renamed file: its copy in 'renamed' is the one that counts
                seen.add(key)
                rec = known.get(key)
                if rec is None:
                    code, k, draft = parse_name(name)
                    m, score = matcher.find(code, k)
                    rec = {"path": full, "root": role, "col": col, "draft": draft, "map": m["id"] if m else "",
                           "score": round(score, 2), "guess_key": k, "guess_code": code, "manual": False, "ign": False,
                           "gone": False, "drive_id": "", "pub": "", "confirmed": False, "done": False, "quality": "", "note": "", "tool": "",
                           "date": date_from_name(name), "fdate": time.strftime("%Y-%m-%d", time.localtime(st.st_mtime)),
                           "by": guess_by(name, cat.get("people", {}))}
                    if low_name.endswith(".comments2"):
                        rec["ign"], rec["ign_why"] = True, "comments2"       # of no interest (Lars 2026-11-14): hidden like an ignored file
                    cat["files"].append(rec)
                    known[key] = rec
                    found += 1
                rec["size"], rec["mtime"], rec["gone"] = st.st_size, int(st.st_mtime), False
                if not rec.get("manual"):
                    rec["col"] = col
    default_designers(cat)
    hide_comments2(cat)
    gone = 0
    for rec in cat["files"]:
        if rec["path"].lower() in seen:
            continue
        covered = any(os.path.isdir(r.get("path", "")) and scan_covers(r, rec["path"], ignore) for r in settings["roots"])
        if os.path.isfile(rec["path"]) and (rec.get("manual") or not covered):
            rec["gone"] = False                  # it is there - the scan just does not look in that folder (Myanmar, Uzbekistan ... 2026-11-15)
        elif covered:
            if not rec.get("gone"):
                gone += 1
            rec["gone"] = True
    say("Scan done: %d new file(s), %d no longer there, %d in the catalog." % (found, gone, len(cat["files"])))
    return found


def rematch_unassigned(cat, say=print):
    """Try again to place files that have no map (after the sheet was imported, a map was renamed ...)."""
    matcher, n, moved = Matcher(cat), 0, 0
    for rec in cat["files"]:
        if rec.get("manual") or rec.get("ign"):
            continue
        m, score = matcher.find(rec.get("guess_code", ""), rec.get("guess_key", ""))
        if not rec.get("map"):
            if m:
                rec["map"], rec["score"] = m["id"], round(score, 2)
                n += 1
        elif m and m["id"] != rec["map"] and score >= 1.0:
            # Auto-placed file whose name now points exactly at ANOTHER map: a map number that was missing before, or the code
            # in the name (AUS / OS) that picks one of several maps with the same name.  Only when the file's number or code
            # decides it - never moves a file because of a fuzzy match.
            cur = next((x for x in cat["maps"] if x["id"] == rec["map"]), None)
            same_name = cur is not None and norm_key(cur["name"]) == norm_key(m["name"])
            by_number = bool(re.match(r"^\d{3,4}(\s|$)", rec.get("guess_key", "")))
            if same_name or by_number:
                rec["map"], rec["score"] = m["id"], 1.0
                moved += 1
    say("Placed %d more file(s)%s." % (n, (", moved %d to the right one of two maps with the same name or number" % moved) if moved else ""))
    if cat.get("numbers"):                       # files that are only a number: the saved number list (Lars's own numbering) places them
        n += place_numbered_files(cat, None, say, quiet=True)
    return n


def sheet_numbers(path):
    """{map number (int): (name, code)} from the sheet's NR column (G) and MAP column (B); stops where the creators list starts."""
    try:
        import openpyxl
    except ImportError:
        raise RuntimeError("The Excel reader (openpyxl) is not installed for this Python.")
    wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
    try:
        ws = wb["Maps"] if "Maps" in wb.sheetnames else wb[wb.sheetnames[0]]
        rows = list(ws.iter_rows(values_only=True))
    finally:
        wb.close()
    hdr = [str(c).strip().upper() if c is not None else "" for c in rows[0]]
    col = {h: i for i, h in enumerate(hdr) if h}
    inr, imap, icode = col.get("NR", 6), col.get("MAP", 1), col.get("CODE", 2)
    out = {}
    for r in rows[1:]:
        if isinstance(r[1] if len(r) > 1 else None, str) and r[1].strip().upper().startswith("DESIGNERS"):
            break
        nr = cell_text(r[inr]) if inr < len(r) else ""
        name = r[imap] if imap < len(r) else None
        if nr.isdigit() and isinstance(name, str) and name.strip() and not name.strip().startswith("#"):
            out.setdefault(int(nr), (smart_title(name), (cell_text(r[icode]) if icode < len(r) else "").upper()))
    return out


def place_numbered_files(cat, path, say=print, quiet=False):
    """Files named only with a map NUMBER (0016.comments2, 0063.places ...) -> the map with that number.  The number -> map name link
    is the sheet (column NR = G, column MAP = B).  A number whose map is not in the catalog yet (a twin that an old import merged into
    another map) gets its map made from the sheet row (name, code, number); a map of the same name without a number gets the number.
    Returns how many files were placed."""
    # Lars (2026-11-09): "that information may well be saved, even if it is MY numbering" -> the number -> name/code list is kept in the
    # catalog (cat["numbers"]) every time the sheet is read, and used when the sheet is not there.
    saved = cat.setdefault("numbers", {})
    table = {int(k): (v[0], v[1] if len(v) > 1 else "") for k, v in saved.items() if str(k).isdigit() and v}
    if path and os.path.isfile(path):
        fresh = sheet_numbers(path)
        table.update(fresh)
        for n, (name, code) in fresh.items():
            saved[str(n)] = [name, code]
        say("Read %d map numbers from the sheet (kept in the catalog)." % len(fresh))
    elif table:
        if not quiet:
            say("The sheet was not used - the %d map numbers saved in the catalog are used." % len(table))
    else:
        raise RuntimeError("No sheet and no saved map numbers: choose the Excel sheet first.")
    by_nr ={int(m["nr"]): m for m in cat["maps"] if str(m.get("nr", "")).strip().isdigit()}
    placed, made, numbered, missing = 0, 0, 0, set()
    for rec in cat["files"]:
        if rec.get("map") or rec.get("ign") or rec.get("gone"):
            continue
        key = rec.get("guess_key", "")
        if not re.match(r"^\d{1,4}$", key) or int(key) == 0:
            continue
        n = int(key)
        m = by_nr.get(n)
        if m is None:
            if n not in table:
                missing.add(key)
                continue
            name, code = table[n]
            m = next((x for x in cat["maps"] if norm_key(x["name"]) == norm_key(name) and not str(x.get("nr", "")).strip()), None)
            if m is not None:
                m["nr"] = str(n)
                if code and not (m.get("code") or "").strip():
                    m["code"] = code
                numbered += 1
            else:
                m = new_map(cat, name, nr=str(n), code=code)
                made += 1
            by_nr[n] = m
        rec["map"], rec["score"] = m["id"], 1.0
        placed += 1
    if placed or not quiet:
        say("Numbered files: %d placed (%d new map(s) made from the saved number list, %d existing map(s) got their number)."
            % (placed, made, numbered))
    if missing and not quiet:
        say("Numbers that are not in the sheet (left on the Unassigned tab): " + ", ".join(sorted(missing)))
    return placed


def make_maps_from_unassigned(cat, say=print):
    """One new map per distinct file key among the files that have no map."""
    groups = {}
    for rec in cat["files"]:
        if rec.get("map") or rec.get("ign") or rec.get("gone") or not rec.get("guess_key"):
            continue
        if re.match(r"^\d{3,4}(\s|$)", rec["guess_key"]):
            continue                                     # a map NUMBER with no such map in the sheet: leave it for me to look at
        groups.setdefault(rec["guess_key"], []).append(rec)
    for k, recs in sorted(groups.items()):
        code = next((r["guess_code"] for r in recs if r.get("guess_code")), "")
        name = string.capwords(k)
        m = new_map(cat, name, code=code)
        for r in recs:
            r["map"], r["score"] = m["id"], 1.0
    say("Made %d new map(s) from files without a map." % len(groups))
    return len(groups)


# *************** DEL 23 - EXCEL IMPORT (the sheet Spel---RAIL.xlsx) *****************
# ToDo: reads sheet "Maps": the header row names the columns, the map rows end where the row "DESIGNERS:" starts; below it
# the creators (col B = name, col C = code) are read.  Rows after the creators ("* MISSING *" list) are not maps.
# The sheet is a live SOURCE: every import refreshes the fields it supplies, EXCEPT the ones I have typed by hand in the program
# (`edited` list of the map) - those are never overwritten.

SHEET_FIELDS = {"HAVE": "have", "COMMENT": "comment", "DRAFT": "draft_note", "NR": "nr", "CITIES": "cities", "YEAR": "year",
                "BY": "by", "MIN.": "minp", "RIVERS": "rivers", "EXCEPTIONS/COMMENTS": "exceptions", "NEED": "need",
                "WANT": "want", "STEPS": "steps", "S.R.": "sr", "CODE": "code"}


SHEET_STAT_ROWS = {"originals", "non-originals", "unfinished", "impossible", "finished", "missing", "total"}


def cell_text(v, month_day=False):
    """Text of a cell.  S.R. is typed like 2/7 but Excel stored it as a DATE (shown m/d): month_day turns it back into '2/7'."""
    if v is None:
        return ""
    if isinstance(v, float) and v == int(v):
        v = int(v)
    if isinstance(v, (datetime.datetime, datetime.date)):
        return "%d/%d" % (v.month, v.day) if month_day else ""
    s = str(v).strip()
    return "" if s.startswith("#") else s


def is_grey_cell(cell):
    """True when the cell's font colour is a light grey (all three channels about equal and bright, like EEEEEE) - the sheet's way of
    writing 'not verified'.  Black, theme colours and every real colour (orange, purple, green ...) are not grey."""
    try:
        c = cell.font.color
        if c is None or c.type != "rgb" or not isinstance(c.rgb, str) or len(c.rgb) != 8:
            return False
        r, g, b = int(c.rgb[2:4], 16), int(c.rgb[4:6], 16), int(c.rgb[6:8], 16)
    except Exception:
        return False
    return min(r, g, b) >= 0xC8 and max(r, g, b) - min(r, g, b) <= 10


def import_excel(cat, path, say=print):
    try:
        import openpyxl
    except ImportError:
        raise RuntimeError("The Excel reader (openpyxl) is not installed for this Python.")
    wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
    ws = wb["Maps"] if "Maps" in wb.sheetnames else wb[wb.sheetnames[0]]
    rows = list(ws.iter_rows(values_only=True))
    hdr = [str(c).strip().upper() if c is not None else "" for c in rows[0]]
    col = {h: i for i, h in enumerate(hdr) if h and h not in ("", "|")}
    imap = col.get("MAP", 1)
    # Lars 2026-11-09: in column STEPS a GREY number (font colour ~EEEEEE, mostly "200") is a default that nobody has verified - only the
    # steps written in another colour (black, orange, purple ...) belong in the program.  The grey ones are skipped (and cleared).
    grey_rows = set()
    if col.get("STEPS") is not None:
        for i, crow in enumerate(ws.iter_rows(min_col=col["STEPS"] + 1, max_col=col["STEPS"] + 1)):
            if is_grey_cell(crow[0]):
                grey_rows.add(i)
    added = filled = cleared = 0
    people_row = None
    # A map is identified by its NUMBER (column NR), not by its name: the sheet has several rows with the same name (Austria AUS 16 /
    # Austria OS 17, Austria-Hungary 1911 18 / 283 ...) and they are different maps.  Before 2026-11-08 they were merged into one.
    sheet_nrs = set()
    if col.get("NR") is not None:
        for r in rows[1:]:
            if isinstance(r[1] if len(r) > 1 else None, str) and r[1].strip().upper().startswith("DESIGNERS"):
                break
            if col["NR"] < len(r) and cell_text(r[col["NR"]]).isdigit():
                sheet_nrs.add(cell_text(r[col["NR"]]))
    for i, r in enumerate(rows[1:], start=1):
        b = r[1] if len(r) > 1 else None
        if isinstance(b, str) and b.strip().upper().startswith("DESIGNERS"):
            people_row = i + 1
            break
        name = r[imap] if len(r) > imap else None
        if not isinstance(name, str) or not name.strip() or name.strip().startswith("#") or name.strip().lower().startswith("ledigt"):
            continue
        has_nr = col.get("NR") is not None and col["NR"] < len(r) and cell_text(r[col["NR"]])
        has_code = col.get("CODE") is not None and col["CODE"] < len(r) and cell_text(r[col["CODE"]])
        if not (has_nr or has_code) or name.strip().lower() in SHEET_STAT_ROWS:
            continue                                     # statistics rows ("Originals", "Total" ...) are not maps
        name = smart_title(name)
        row_nr = cell_text(r[col["NR"]]) if col.get("NR") is not None and col["NR"] < len(r) else ""
        row_code = (cell_text(r[col["CODE"]]) if col.get("CODE") is not None and col["CODE"] < len(r) else "").upper()
        if row_nr.isdigit():                              # Lars's own numbering is kept in the catalog (cat["numbers"]) for good
            cat.setdefault("numbers", {})[str(int(row_nr))] = [name, row_code]
        existing = None
        if row_nr.isdigit():
            existing = next((m for m in cat["maps"] if str(m.get("nr", "")).strip() == row_nr), None)
        if existing is None:
            for m in cat["maps"]:
                if norm_key(m["name"]) != norm_key(name):
                    continue
                m_nr = str(m.get("nr", "")).strip()
                if row_nr.isdigit() and m_nr and m_nr != row_nr and m_nr in sheet_nrs:
                    continue                                 # that map is another row of the sheet (same name, other number)
                if not row_nr.isdigit() and m_nr and (m.get("code") or "").upper() != row_code:
                    continue
                existing = m
                break
        if existing is None:
            existing = new_map(cat, name)
            added += 1
        for h, fld in SHEET_FIELDS.items():
            idx = col.get(h)
            if idx is None or idx >= len(r):
                continue
            txt = cell_text(r[idx], month_day=(fld == "sr"))
            if fld == "steps" and i in grey_rows:                # grey = not verified: no steps (an old value is cleared)
                if existing.get("steps") and "steps" not in existing.setdefault("edited", []):
                    existing["steps"] = ""
                    cleared += 1
                continue
            if txt and existing.get(fld) != txt and fld not in existing.setdefault("edited", []):
                existing[fld] = txt
                filled += 1
        ex_o = [cell_text(r[col[k]]) for k in ("O1", "O2", "O3", "O4", "O5", "O6", "O7") if k in col and col[k] < len(r)]
        ex_e = [cell_text(r[col[k]]) for k in ("E1", "E2", "E3", "E4", "E5", "E6") if k in col and col[k] < len(r)]
        all_dash = bool(ex_o or ex_e) and all(x in ("", "-") for x in ex_o + ex_e)    # the sheet says "-" everywhere
        ex_o = [x for x in ex_o if x and x != "-"]
        ex_e = [x for x in ex_e if x and x != "-"]
        existing.pop("starts", None)                      # old names of what is now "sruns"
        existing.pop("ends", None)
        sr_zero = cell_text(r[col["S.R."]]) == "0" if "S.R." in col and col["S.R."] < len(r) else False
        if (ex_o or ex_e or (all_dash and sr_zero)) and "sruns" not in existing.setdefault("edited", []):
            old = sruns_of(existing)
            new = dict(old, odd=ex_o, even=ex_e, same=(ex_o == ex_e), never=bool(all_dash and sr_zero and not ex_o and not ex_e))
            if new["same"]:
                new["even"] = []
            if new != old:
                existing["sruns"] = new
                filled += 1
    people = 0
    if people_row is not None:
        for r in rows[people_row:]:
            b = r[1] if len(r) > 1 else None
            c = r[2] if len(r) > 2 else None
            if b is None and c is None:
                if people:
                    break
                continue
            if is_excel_error(b) or is_excel_error(c):
                continue                                   # a broken formula in the sheet is not a person (was "#VÄRDE!")
            if isinstance(b, str) and isinstance(c, str) and b.strip() and c.strip() and not b.startswith("*"):
                if c.strip() not in cat["people"]:
                    cat["people"][c.strip()] = b.strip()
                    people += 1
            elif people:
                break
    say("Excel: %d new map(s), %d field(s) filled, %d creator(s) read.%s" % (
        added, filled, people, ("  Steps: %d grey (unverified) value(s) removed, %d grey cell(s) skipped." % (cleared, len(grey_rows))) if grey_rows else ""))
    return added, filled, people


# *************** DEL 24 - PUBLIC NAMES, THUMBNAILS, UPLOAD FOLDER *****************
# ToDo: every map gets ONE folder on the web / Drive (`<code>---<name>`), every file keeps its own name inside it.  `pub` is the
# path "folder/file" and is the same on all sources, which is how the page finds a file on Drive/the site/Webdock.

def safe_part(text):
    s = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", str(text)).strip(" .")
    return re.sub(r"\s+", "_", s)[:80] or "map"


def map_folder(m):
    code = (m.get("code") or "").strip()
    bad = code in ("", "-", "?", "???")
    return safe_part((("%s---" % code) if not bad else "") + m["name"])


TXT_COLS = ("places", "invalid", "comments")      # text files: published with .txt added to the name so a browser SHOWS them (Lars 2026-11-14)


def included(rec):
    if STATE.get("only_confirmed") and not rec.get("confirmed"):
        return False
    if str(rec.get("path", "")).lower().endswith(".comments"):
        return False            # its text is in the map's Exceptions / comments field (apply_comment_files): the file itself is not published
    return bool(rec.get("map")) and not rec.get("gone") and not rec.get("ign")


def pub_file_name(rec, base):
    """The name a file gets on the web / in the upload folder: a places / invalid races / comments file gets '.txt' added."""
    if rec.get("col") in TXT_COLS and not base.lower().endswith(".txt"):
        return base + ".txt"
    return base


def assign_pub(cat):
    """Fill `pub` for every included file; names that would collide get ' (2)'.  An existing pub is kept."""
    maps = map_by_id(cat)
    folders, used = {}, set()
    for m in cat["maps"]:
        f, n = map_folder(m), 2
        while f.lower() in folders.values():
            f = "%s_%d" % (map_folder(m), n)
            n += 1
        folders[m["id"]] = f.lower()
        m["folder"] = f
    for rec in cat["files"]:
        if included(rec) and rec.get("pub"):
            used.add(rec["pub"].lower())
    for rec in cat["files"]:
        if not included(rec) or rec["map"] not in maps:
            continue
        m = maps[rec["map"]]
        want_dir = m["folder"]
        if (rec.get("pub") and rec["pub"].split("/")[0] == want_dir
                and (rec.get("col") not in TXT_COLS or rec["pub"].lower().endswith(".txt"))):
            continue
        if rec.get("pub") and rec.get("col") in TXT_COLS and not rec["pub"].lower().endswith(".txt"):
            rec["drive_id"] = ""                    # the name gets '.txt': a NEW file on Drive, the old id belongs to the old copy
        base = pub_file_name(rec, os.path.basename(rec["path"]))
        stem, ext = os.path.splitext(base)
        pub, n = "%s/%s" % (want_dir, base), 2
        while pub.lower() in used:
            pub = "%s/%s (%d)%s" % (want_dir, stem, n, ext)
            n += 1
        used.add(pub.lower())
        rec["pub"] = pub


def make_thumb(src, dst, size=360):
    from PIL import Image
    Image.MAX_IMAGE_PIXELS = None
    with Image.open(src) as im:
        im = im.convert("RGB")
        im.thumbnail((size, size))
        os.makedirs(os.path.dirname(dst), exist_ok=True)
        im.save(dst, "JPEG", quality=80)


def pick_thumb_source(files):
    """My own coloured version first (newest), else the newest original image."""
    def newest(col):
        c = [f for f in files if f["col"] == col and os.path.splitext(f["path"])[1].lower() in IMG_EXT and os.path.isfile(f["path"])]
        c = sort_versions(c)
        return c[-1] if c else None
    return newest("issu") or newest("orig")


# ---- Google Drive for desktop: start it when the upload folder is not there (Lars 2026-11-14; same method as AppSite) ----
DRIVE_EXE_PATTERNS = (r"C:\Program Files\Google\Drive File Stream\*\GoogleDriveFS.exe",)
DRIVE_PROCESS = "GoogleDriveFS.exe"


def find_drive_exe():
    """The newest GoogleDriveFS.exe of 'Google Drive for desktop' (the folder name is its version), or ''."""
    import glob
    found = []
    for pat in DRIVE_EXE_PATTERNS:
        found.extend(glob.glob(pat))
    found.sort(key=lambda p: tuple(int(x) for x in re.findall(r"\d+", os.path.basename(os.path.dirname(p)))))
    return found[-1] if found else ""


def drive_running():
    tl = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "tasklist.exe")        # full path, never the bare name
    try:
        out = subprocess.run([tl, "/FI", "IMAGENAME eq " + DRIVE_PROCESS, "/NH"], capture_output=True, text=True, timeout=30,
                             creationflags=0x08000000 if os.name == "nt" else 0).stdout
    except (OSError, subprocess.SubprocessError):
        return False
    return DRIVE_PROCESS.lower() in out.lower()


def upload_dir_ready(dest):
    """The upload folder is there, or its parent is (then the folder is made): the Drive drive is mounted."""
    return os.path.isdir(dest) or os.path.isdir(os.path.dirname(dest.rstrip("\\/")))


def ensure_upload_dir(dest, say=print, timeout=180):
    """If the upload folder is not reachable (Google Drive for desktop is not running, so its drive letter is missing) start Drive and
    wait until the folder appears.  Raises RuntimeError with the reason when it does not."""
    if upload_dir_ready(dest):
        return
    if not drive_running():
        exe = find_drive_exe()
        if not exe:
            raise RuntimeError("The upload folder is not there (%s) and Google Drive for desktop was not found (looked for %s).  "
                               "Install it or start it by hand." % (dest, DRIVE_EXE_PATTERNS[0]))
        say("The upload folder is not there - starting Google Drive for desktop ...")
        try:
            subprocess.Popen([exe], close_fds=True, creationflags=(0x00000008 | 0x00000200) if os.name == "nt" else 0)
        except OSError as exc:
            raise RuntimeError("Could not start Google Drive for desktop: %s" % exc)
    else:
        say("Google Drive for desktop is running - waiting for the upload folder to appear ...")
    end, last = time.time() + timeout, 0
    while time.time() < end:
        if upload_dir_ready(dest):
            say("The upload folder is there.")
            return
        if time.time() - last > 20:
            say("  still waiting for %s ..." % dest)
            last = time.time()
        time.sleep(2)
    raise RuntimeError("The upload folder did not appear within %d seconds: %s\nLog in to Google Drive for desktop (the account for the "
                       "maps), then run Make upload folder again." % (timeout, dest))


def make_upload_folder(cat, settings, say=print):
    """Copy the library files to <upload_dir>\\<map folder>\\<file>.  Only files that are missing or differ in size/time.
    Written straight over an old copy (so a Drive-for-desktop file keeps its id/link).  Never deletes."""
    dest = settings.get("upload_dir", "").strip()
    if not dest:
        raise RuntimeError("Set the upload folder first (Sources & folders).")
    ensure_upload_dir(dest, say)
    assign_pub(cat)
    n_copy = n_same = n_miss = size = 0
    for rec in cat["files"]:
        if not included(rec) or not rec.get("pub"):
            continue
        if not os.path.isfile(rec["path"]):
            n_miss += 1
            continue
        target = os.path.join(dest, *rec["pub"].split("/"))
        try:
            st = os.stat(target)
            if st.st_size == rec.get("size", -1) and st.st_mtime >= rec.get("mtime", 0) - 2:
                n_same += 1
                continue
        except OSError:
            pass
        os.makedirs(os.path.dirname(target), exist_ok=True)
        shutil.copyfile(rec["path"], target)
        os.utime(target, (rec["mtime"], rec["mtime"]))
        n_copy += 1
        size += rec.get("size", 0)
        if n_copy % 25 == 0:
            say("  copied %d file(s) ..." % n_copy)
    say("Upload folder: %d copied (%.1f MB), %d already there, %d missing at the source." % (n_copy, size / 1048576.0, n_same, n_miss))
    n_copy += copy_tools(dest, say)
    return n_copy


# *************** DEL 24b - TOOLS NEXT TO THE MAPS (Hex_Labels) *****************
# Lars (2026-11-15): the maps page also offers the program Hex_Labels (writes hexagon names - A1, B1, C2 ... - on a map picture).
# Two downloads: the Windows program (the ExeForge folder Folder-exe\Hex_Labels, packed into Hex_Labels_Windows.zip so nobody needs
# Python) and the Python source Hex_Labels.py.  Make upload folder puts both in <upload_dir>\Tools\ (written straight over the old copy,
# so the Drive file keeps its id; the zip is only made again when something in the exe folder is newer), Fetch Drive links stores the ids
# in cat["tools"], Build page writes tools.html with the download links.  Hex_Labels itself reads the map list from the page and fetches
# the pictures from Drive ("Browse maps...").
# ToDo: more tools = one more row in TOOLS.
TOOLS_FOLDER = "Tools"
TOOLS = [{"name": "Hex Labels",
          "text": "Writes the hexagon names (A1, B1, C2 ...) on a map picture.  It finds the hexagon grid by itself; you mark A1, pick the "
                  "naming system and how often the names are shown, hide the names where something else is in the way, and save the result "
                  "as bmp, png or jpg.  <b>Browse maps...</b> in the program lists the maps of this site (Lars’s own coloured maps first, "
                  "the ones without markings) and fetches the picture from Google Drive.",
          "downloads": [{"file": "Hex_Labels_Windows.zip", "exe_dir": "Hex_Labels",
                         "label": "Windows program - no Python needed (unpack the zip, start Hex_Labels.exe)"},
                        {"file": "Hex_Labels.py", "label": "Python source (needs Python 3 with Pillow and numpy)"}]},
         # 2026-11-15: the Android app that photographs a paper map straight; its "Rail map" mode (code from me) sends the pictures to me.
         {"name": "PicturePerfect (Android)",
          "text": "An Android app that photographs a paper map <b>straight</b>: it finds the sheet, draws a frame round it, takes the picture by "
                  "itself when the phone is held still, straightens it into a flat rectangle and warns when the light is bad (such a picture gets "
                  "<i>-Bad_light</i> at the end of its name).  The pictures are saved on your phone, in Pictures/PicturePerfect, and nothing is sent "
                  "anywhere unless you switch on the Rail map mode below.  <b><a href=\"examples.html\">See examples of the pictures it makes</a></b>.<br><br>"
                  "<b>Install:</b> download the .apk, open it on your phone and allow installing from this source when Android asks.<br><br>"
                  "<b>Send your maps to this collection (optional):</b> the <b>Rail map</b> mode sends every picture you keep to the site owner "
                  "automatically, so nobody has to plug in a cable.  It is <b>off</b> until you have a code:"
                  "<ol><li>Ask the site owner for a <b>code</b> (a long text that starts with <i>ISSUSYNC1:</i>).  It is made for you personally "
                  "and can be taken back.</li>"
                  "<li>In the app press the gear (Settings), find <b>Rail map mode</b>, paste the code and press <b>Use the code</b>.  The mode "
                  "is now on; you can switch it Off and On again, or Clear the code, whenever you like.</li>"
                  "<li>Take a picture as usual.  When you press <b>Keep</b> it is saved on your phone <u>and</u> sent to the collection.  "
                  "<b>Redo</b> never sends.  A small note on the camera screen says how many pictures are waiting.  With no internet they wait "
                  "and are sent later, when the app is open.</li></ol>"
                  "The owner then places your picture on the right map.",
          "downloads": [{"file": "PicturePerfect.apk", "dirs": [os.path.join("1---Annat", "0---Android", "PicturePerfect", "APK")],
                         "label": "Android app (the .apk)"}]}]


def tool_downloads():
    """[(tool, download)] for every file the Tools page offers."""
    return [(t, d) for t in TOOLS for d in t["downloads"]]


def tool_source(dl):
    """The download's source: the .py next to this program (Py\\), or the ExeForge folder Folder-exe\\<exe_dir> (a folder, to be zipped).
    '' when it is not there."""
    here = os.path.dirname(os.path.abspath(sys.executable if getattr(sys, "frozen", False) else __file__))
    if dl.get("exe_dir"):
        for d in (os.path.join(BASE_DIR, "Folder-exe", dl["exe_dir"]), os.path.join(os.path.dirname(here), "Folder-exe", dl["exe_dir"])):
            if os.path.isfile(os.path.join(d, dl["exe_dir"] + ".exe")):
                return d
        return ""
    extra = [os.path.join(BASE_DIR, d) for d in dl.get("dirs", [])] + [os.path.join(os.path.dirname(here), d) for d in dl.get("dirs", [])]
    for d in (here, os.path.join(BASE_DIR, "Py")) + tuple(extra):
        p = os.path.join(d, dl["file"])
        if os.path.isfile(p):
            return p
    return ""


def zip_is_current(folder, zip_path):
    """True when the zip exists and nothing in the folder is newer than it."""
    try:
        zt = os.path.getmtime(zip_path)
    except OSError:
        return False
    for dp, _dn, names in os.walk(folder):
        for n in names:
            if os.path.getmtime(os.path.join(dp, n)) > zt:
                return False
    return True


def zip_folder(folder, zip_path):
    """Pack <folder> into zip_path with the folder name as the top folder (so unpacking gives a folder).  Written straight to zip_path."""
    import zipfile
    top = os.path.basename(os.path.normpath(folder))
    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as z:
        for dp, _dn, names in os.walk(folder):
            for n in sorted(names):
                full = os.path.join(dp, n)
                z.write(full, os.path.join(top, os.path.relpath(full, folder)))


def copy_tools(dest, say=print):
    """Copy the tool files to <dest>\\Tools\\ when they differ (a zip is made of an exe folder).  Returns how many were copied/made."""
    n = 0
    for t, dl in tool_downloads():
        src = tool_source(dl)
        if not src:
            say("Tool file %s: its source was not found next to this program - not uploaded." % dl["file"])
            continue
        target = os.path.join(dest, TOOLS_FOLDER, dl["file"])
        os.makedirs(os.path.dirname(target), exist_ok=True)
        if dl.get("exe_dir"):
            if zip_is_current(src, target):
                continue
            say("Packing %s into %s (a minute) ..." % (src, dl["file"]))
            zip_folder(src, target)
            n += 1
            say("Tool %s made in the upload folder (%s, %.1f MB)." % (dl["file"], TOOLS_FOLDER, os.path.getsize(target) / 1048576.0))
            continue
        try:
            with open(src, "rb") as a, open(target, "rb") as b:
                same = a.read() == b.read()
        except OSError:
            same = False
        if not same:
            shutil.copyfile(src, target)
            n += 1
            say("Tool %s copied to the upload folder (%s)." % (dl["file"], TOOLS_FOLDER))
    return n


def tools_html(cat):
    """The body of tools.html."""
    ids = cat.get("tools", {}) or {}
    parts = ["<p class=\"note\">Programs that go with the maps.  The Windows program needs nothing installed: unpack the zip somewhere "
             "(not inside the zip window) and start the .exe.  Windows may ask you to confirm because the program is not signed.  "
             "The Android app is an .apk file.</p>"]
    for t in TOOLS:
        links = []
        for dl in t["downloads"]:
            did = ids.get(dl["file"], "")
            if did:
                links.append("<a href=\"%s\">%s</a> - %s" % (html.escape(drive_direct(did)), html.escape(dl["file"]), html.escape(dl["label"])))
            else:
                links.append("%s - <em>(not on Google Drive yet)</em>" % html.escape(dl["file"]))
        parts.append("<h2>%s</h2><p>%s</p><p>%s</p>" % (html.escape(t["name"]), t["text"], "<br>".join(links)))
    return "".join(parts)

# *************** DEL 25 - GOOGLE DRIVE LINKS (public folder, no API key) *****************
# ToDo: same method as AppSite/MusicSite (embeddedfolderview).  The Drive folder holds one sub folder per map (the same
# `pub` names).  Fetch matches by folder + file name and stores the Drive file id; the page uses it for the Drive source.

class DriveError(Exception):
    pass


NOT_SHARED_HELP = ("Google Drive would not show that folder.  Open the folder in Drive, Share, 'General access: Anyone with the "
                   "link', role Viewer, and paste the link again.")


def http_get(url, timeout=30):
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "*/*", "Accept-Language": "en-US,en"})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        data = resp.read()
    for enc in ("utf-8", "cp1252"):
        try:
            return data.decode(enc)
        except UnicodeDecodeError:
            continue
    return data.decode("utf-8", "replace")


def drive_id_from(text):
    text = (text or "").strip()
    for pat in (r"/folders/([A-Za-z0-9_\-]{10,})", r"/file/d/([A-Za-z0-9_\-]{10,})", r"[?&]id=([A-Za-z0-9_\-]{10,})"):
        m = re.search(pat, text)
        if m:
            return m.group(1)
    return text if re.fullmatch(r"[A-Za-z0-9_\-]{10,}", text) else ""


def drive_direct(file_id):
    return "https://drive.usercontent.google.com/download?id=%s&export=download&confirm=t" % file_id


def drive_entries(folder_id):
    """([files], [folders]) directly in a public Drive folder; each is {name, id}."""
    url = "https://drive.google.com/embeddedfolderview?id=%s#list" % folder_id
    try:
        page = http_get(url)
    except urllib.error.HTTPError as exc:
        if exc.code in (401, 403, 404):                      # 401 = Google's answer for a folder that is not shared
            raise DriveError(NOT_SHARED_HELP)
        raise DriveError("Google Drive answered HTTP %s.  Wait a moment and try again." % exc.code)
    except (urllib.error.URLError, OSError) as exc:
        raise DriveError("Could not reach Google Drive.  Check the internet connection.\n%s" % exc)
    if "flip-entry" not in page:
        if "flip-entries" in page or "flip-contents" in page:
            return [], []
        raise DriveError(NOT_SHARED_HELP)
    out, folders = [], []
    for chunk in page.split('class="flip-entry"')[1:]:
        m_id = re.search(r'id="entry-([A-Za-z0-9_\-]+)"', chunk)
        m_t = re.search(r'class="flip-entry-title"[^>]*>(.*?)</div>', chunk, re.S)
        m_h = re.search(r'href="([^"]+)"', chunk)
        if not (m_id and m_t):
            continue
        item = {"name": html.unescape(re.sub(r"<[^>]+>", "", m_t.group(1))).strip(), "id": m_id.group(1)}
        (folders if "/folders/" in (m_h.group(1) if m_h else "") else out).append(item)
    return out, folders


def drive_fetch_ids(cat, settings, say=print):
    root_id = drive_id_from(settings.get("drive_folder", ""))
    if not root_id:
        raise RuntimeError("Paste the Drive folder link first (Sources & folders).")
    assign_pub(cat)
    _files, folders = drive_entries(root_id)
    say("Drive: %d map folder(s) found, reading them ..." % len(folders))

    def one(f):
        try:
            return f, drive_entries(f["id"])[0], None
        except DriveError as exc:
            return f, [], str(exc).split("\n")[0]
    index, bad = {}, 0
    with concurrent.futures.ThreadPoolExecutor(8) as ex:
        for f, files, err in ex.map(one, folders):
            if err:
                bad += 1
                say("  could not read '%s': %s" % (f["name"], err))
            for x in files:
                index[(f["name"].lower(), x["name"].lower())] = x["id"]
    hit = miss = 0
    for rec in cat["files"]:
        if not included(rec) or not rec.get("pub"):
            continue
        folder, name = rec["pub"].split("/", 1)
        did = index.get((folder.lower(), name.lower()))
        if did:
            rec["drive_id"] = did
            hit += 1
        else:
            rec["drive_id"] = ""
            miss += 1
    say("Drive: %d file(s) linked, %d not on Drive yet, %d folder(s) unreadable." % (hit, miss, bad))
    cat["tools"] = {dl["file"]: index.get((TOOLS_FOLDER.lower(), dl["file"].lower()), "") for _t, dl in tool_downloads()}
    say("Tools: %s" % ", ".join("%s %s" % (k, "linked" if v else "not on Drive yet") for k, v in cat["tools"].items()))
    return hit, miss


def check_incoming(settings, say=print):
    """Looks in the public Drive folder where visitors drop files (setting incoming_url): one level of sub folders (a folder per person).
    Says what is there and which files are NEW since the last check (ids kept in settings['incoming_seen']).  Reads only - nothing is
    downloaded, moved or deleted.  Never raises for Drive trouble (the upload that called it must not fail because of this).
    Returns the list of new files as 'Folder/name'."""
    fid = drive_id_from(settings.get("incoming_url", ""))
    if not fid:
        return []
    say("Incoming folder on Drive (files from visitors) ...")
    try:
        top_files, folders = drive_entries(fid)
        rows = [("", f) for f in top_files]
        for fo in folders:
            try:
                rows += [(fo["name"], f) for f in drive_entries(fo["id"])[0]]
            except DriveError as exc:
                say("  could not read the folder '%s': %s" % (fo["name"], str(exc).split("\n")[0]))
    except DriveError as exc:
        say("  could not read the incoming folder: %s" % str(exc).split("\n")[0])
        return []
    seen = set(settings.get("incoming_seen", []))
    new = [(who, f) for who, f in rows if f["id"] not in seen]
    say("  %d file(s) in %d person folder(s) (+ %d loose), %d NEW since the last check." % (len(rows), len(folders), len(top_files), len(new)))
    for who, f in new:
        say("  NEW: %s" % ((who + "/" if who else "") + f["name"]))
    settings["incoming_seen"] = sorted(seen | {f["id"] for _w, f in rows})
    return [(who + "/" if who else "") + f["name"] for who, f in new]


# *************** DEL 25b - PICTURE DROP (maps photographed with the PicturePerfect app land in the incoming Drive folder) *****************
# Lars (2026-11-15): other people can switch on "Rail map" mode in his Android app PicturePerfect.  A picture is then saved on their phone AND
# sent to the incoming Drive folder (setting incoming_url) - the folder this program already checks - in a sub folder with the person's name.
# How the door works (same idea as the YourBook book drop, but Drive only, so NO server work and no WebdockTool job):
#   * a Google Apps Script web app runs AS ME (this program writes the script file with my secret and the incoming folder id in it,
#     pdrop_script_text; I paste it into script.google.com once and deploy it, the steps are in its header);
#   * for every person I make a CODE: "ISSUSYNC1:" + base64url(JSON {a:"railmap", u:<web app address>, k:<token>, i:<id>, n:<name>}) - the
#     generic pairing code of my synced apps.  token = first 40 hex of HMAC-SHA256(secret, id|name), so the script needs no list of people;
#     a person is switched off by telling the script the id (it keeps a list of taken-back ids);
#   * the phone asks the script for ONE resumable-upload address per picture and sends the picture straight to Google.  The person never gets
#     any other access to my Drive, and the code carries no secret of mine (only that person's own token).
#   * Fetch pictures (pdrop_pickup) downloads the NEW Map_*.jpg files of the person folders into the import folder as <Person>-<name>.jpg and
#     lists them as unassigned files (a name like Map_2026-11-15_1830-Bad_light.jpg says nothing about which map it is - I place it by hand).
# ToDo: the code format is the shared ISSUSYNC1 (see WhyBrowse.py sync_code_make/parse); real Drive + real Apps Script are untested here.
import hmac, hashlib, base64

PDROP_APP = "railmap"
PDROP_NAME_RE = re.compile(r"^Map_[0-9A-Za-z_\-]{1,60}\.jpe?g$", re.I)

# The Apps Script.  @SECRET@ and @FOLDER@ are filled in by pdrop_script_text.  (Everything inside is English.)
PDROP_GS = r"""// Rail Maps picture drop - a Google Apps Script web app that runs AS THE OWNER (made by Rail_Maps.py; this file is PRIVATE: it holds the secret).
//
// SET UP (once, about two minutes):
//   1. script.google.com > New project > paste this whole file over Code.gs.  Project settings > tick "Show appsscript.json" and make it contain
//        { "timeZone": "Europe/Stockholm", "runtimeVersion": "V8", "exceptionLogging": "STACKDRIVER",
//          "webapp": { "executeAs": "USER_DEPLOYING", "access": "ANYONE_ANONYMOUS" },
//          "oauthScopes": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/script.external_request"] }
//   2. Run the function check_folder() once (Google asks you to allow it - it is YOUR script on YOUR Drive).  The log must say the folder was found.
//   3. Deploy > New deployment > type Web app > Execute as: Me > Who has access: Anyone > Deploy.  Copy the Web app URL (ends in /exec)
//      and paste it in Rail_Maps > Picture drop...
// To change this script later: Deploy > Manage deployments > edit (pencil) > New version (the URL stays the same).
//
// What it does: a person with a valid code asks for an upload place for ONE picture (Map_....jpg); it makes a Drive resumable-upload address in a
// sub folder (named after the person) of the incoming folder and hands it over.  The address works for that one file only.
var SECRET = "@SECRET@";
var FOLDER_ID = "@FOLDER@";
var MAX_MB = 40;

function json_(o) {
  return ContentService.createTextOutput(JSON.stringify(o)).setMimeType(ContentService.MimeType.JSON);
}

function props_() { return PropertiesService.getScriptProperties(); }

function revoked_() {
  try { return JSON.parse(props_().getProperty("REV") || "{}"); } catch (e) { return {}; }
}

function check_folder() {
  var f = DriveApp.getFolderById(FOLDER_ID);
  Logger.log("The incoming folder was found: " + f.getName());
}

function doGet(e) { return json_({ ok: true, hello: "railmapdrop" }); }

function sameKey_(a, b) {
  a = String(a || ""); b = String(b || "");
  if (a.length !== b.length || !a.length) return false;
  var r = 0;
  for (var i = 0; i < a.length; i++) r |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return r === 0;
}

function hex_(bytes) {
  var s = "";
  for (var i = 0; i < bytes.length; i++) { var v = (bytes[i] + 256) % 256; s += (v < 16 ? "0" : "") + v.toString(16); }
  return s;
}

function token_(id, name) {
  return hex_(Utilities.computeHmacSha256Signature(String(id) + "|" + String(name), SECRET)).slice(0, 40);
}

function cleanPerson_(s) { return String(s || "").replace(/[\\\/:*?"<>|\u0000-\u001f]/g, "_").trim().slice(0, 40); }

function doPost(e) {
  var d;
  try { d = JSON.parse(e.postData.contents); } catch (x) { return json_({ ok: false, error: "bad json" }); }
  if (!d || typeof d !== "object") return json_({ ok: false, error: "bad json" });
  var lock = LockService.getScriptLock();
  lock.waitLock(25000);
  try {
    return json_(act_(d, Date.now()));
  } catch (err) {
    return json_({ ok: false, error: String(err && err.message ? err.message : err) });
  } finally {
    lock.releaseLock();
  }
}

function personFolder_(name) {
  var top = DriveApp.getFolderById(FOLDER_ID);
  var it = top.getFoldersByName(name);
  return it.hasNext() ? it.next() : top.createFolder(name);
}

// Pure logic (the test calls this with fake Google services).
function act_(d, now) {
  var a = String(d.a || "");
  if (a === "revoke" || a === "unrevoke" || a === "list" || a === "ping") {
    if (!sameKey_(d.o, SECRET)) return { ok: false, error: "wrong key" };
    var rev = revoked_();
    if (a === "revoke") rev[String(d.i)] = now;
    if (a === "unrevoke") delete rev[String(d.i)];
    if (a === "revoke" || a === "unrevoke") props_().setProperty("REV", JSON.stringify(rev));
    return { ok: true, revoked: Object.keys(rev) };
  }
  var id = String(d.i || ""), nm = cleanPerson_(d.n);
  if (!id || !nm || !sameKey_(d.t, token_(id, String(d.n || "")))) return { ok: false, error: "wrong code" };
  if (revoked_()[id]) return { ok: false, error: "taken back" };
  if (a === "me") return { ok: true, name: nm, max_mb: MAX_MB };
  if (a !== "begin") return { ok: false, error: "unknown" };
  var file = String(d.name || ""), size = parseInt(d.size, 10) || 0;
  if (!/^Map_[0-9A-Za-z_\-]{1,60}\.jpe?g$/i.test(file)) return { ok: false, error: "that is not a map picture" };
  if (size <= 0 || size > MAX_MB * 1048576) return { ok: false, error: "the picture is too big (largest allowed: " + MAX_MB + " MB)" };
  var folder = personFolder_(nm);
  if (folder.getFilesByName(file).hasNext()) return { ok: true, done: true };           // sent before (a retry after a broken answer): nothing to do
  var meta = { name: file, parents: [folder.getId()], mimeType: "image/jpeg", description: "PicturePerfect Rail map from " + nm };
  var r = UrlFetchApp.fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable", {
    method: "post", contentType: "application/json; charset=UTF-8", payload: JSON.stringify(meta), muteHttpExceptions: true,
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken(), "X-Upload-Content-Type": "image/jpeg", "X-Upload-Content-Length": String(size) }
  });
  if (r.getResponseCode() !== 200) return { ok: false, error: "Drive said " + r.getResponseCode() };
  var h = r.getHeaders(), loc = "";
  for (var hk in h) { if (String(hk).toLowerCase() === "location") loc = String(h[hk]); }
  if (!loc) return { ok: false, error: "Drive gave no upload address" };
  return { ok: true, session: loc };
}
"""


class PDropError(Exception):
    pass


def pdrop_new_secret():
    import secrets
    return secrets.token_urlsafe(24)


def pdrop_clean_person(name):
    """The person's name as the script and the Drive folder see it (the same cleaning as cleanPerson_ in the script)."""
    return re.sub(r'[\\/:*?"<>|\x00-\x1f]', "_", str(name or "")).strip()[:40]


def pdrop_token(secret, pid, name):
    return hmac.new(secret.encode("utf-8"), ("%s|%s" % (pid, name)).encode("utf-8"), hashlib.sha256).hexdigest()[:40]


def pdrop_make_code(url, secret, pid, name):
    """The text I hand to one person: ISSUSYNC1: + base64url(JSON).  The 'k' token is only that person's own (no secret inside)."""
    body = {"a": PDROP_APP, "u": url, "k": pdrop_token(secret, pid, name), "i": pid, "n": name}
    raw = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    return "ISSUSYNC1:" + base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")


def pdrop_parse_code(text):
    """The dict {a,u,k,i,n} of a code found anywhere in pasted text, or None."""
    m = re.search(r"ISSUSYNC1:([A-Za-z0-9_\-]{16,4000})", re.sub(r"\s+", "", text or ""))
    if not m:
        return None
    d = None
    s = m.group(1)
    for cut in range(4):              # words after the code (no space left once whitespace is removed) may add 1-3 stray letters: the JSON ends by itself
        s2 = s[:len(s) - cut]
        if len(s2) % 4 == 1:
            continue
        try:
            d, _end = json.JSONDecoder().raw_decode(base64.urlsafe_b64decode(s2 + "=" * (-len(s2) % 4)).decode("utf-8", "replace"))
            break
        except Exception:
            d = None
    if not isinstance(d, dict) or d.get("a") != PDROP_APP or not str(d.get("u", "")).startswith("http") or len(str(d.get("k", ""))) < 8:
        return None
    return d


def pdrop_script_text(settings):
    """The Apps Script file with my secret and the incoming folder in it (the secret is made the first time; the caller saves settings)."""
    fid = drive_id_from(settings.get("incoming_url", ""))
    if not fid:
        raise PDropError("Set the incoming Drive folder first (Sources & folders > the Drive folder where visitors send files).")
    if not settings.get("pdrop_secret"):
        settings["pdrop_secret"] = pdrop_new_secret()
    return PDROP_GS.replace("@SECRET@", settings["pdrop_secret"]).replace("@FOLDER@", fid)


def pdrop_call(url, payload, timeout=60):
    """POST one JSON message to the Apps Script address (it answers through a redirect; urllib follows it with a GET) -> the answer dict."""
    req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), method="POST",
                                 headers={"Content-Type": "text/plain;charset=UTF-8", "User-Agent": USER_AGENT})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            data = resp.read()
    except (urllib.error.URLError, OSError) as exc:
        raise PDropError("Could not reach the picture drop: %s" % exc)
    try:
        ans = json.loads(data.decode("utf-8"))
    except ValueError:
        raise PDropError("The picture drop answered in a way I could not read (is the Web app address right and deployed for 'Anyone'?).")
    if not ans.get("ok"):
        raise PDropError(str(ans.get("error") or "the picture drop said no"))
    return ans


def pdrop_add_person(settings, name, now=None):
    """Makes a new person + code.  Returns the person record {id, name, code, at, off}."""
    url = (settings.get("pdrop_url") or "").strip()
    if not url:
        raise PDropError("Paste the Web app address of the deployed script first.")
    nm = pdrop_clean_person(name)
    if not nm:
        raise PDropError("Give the person a name (it becomes the Drive folder name).")
    if not settings.get("pdrop_secret"):
        settings["pdrop_secret"] = pdrop_new_secret()
    import secrets
    pid = "p" + secrets.token_hex(4)
    rec = {"id": pid, "name": nm, "code": pdrop_make_code(url, settings["pdrop_secret"], pid, nm),
           "at": time.strftime("%Y-%m-%d", time.localtime(now or time.time())), "off": False}
    settings.setdefault("pdrop_people", []).append(rec)
    return rec


def pdrop_switch(settings, pid, off):
    """Takes a person's code back (or gives it back): tells the script and remembers it.  Raises PDropError when the script cannot be reached."""
    rec = next((p for p in settings.get("pdrop_people", []) if p["id"] == pid), None)
    if rec is None:
        raise PDropError("No such person.")
    pdrop_call(settings["pdrop_url"], {"a": "revoke" if off else "unrevoke", "o": settings.get("pdrop_secret", ""), "i": pid})
    rec["off"] = bool(off)
    return rec


def drive_download(file_id, dest, timeout=180):
    """Downloads a public Drive file to dest (through .part).  Returns the size.  Raises DriveError."""
    req = urllib.request.Request(drive_direct(file_id), headers={"User-Agent": USER_AGENT})
    tmp = dest + ".part"
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp, open(tmp, "wb") as out:
            shutil.copyfileobj(resp, out)
    except (urllib.error.URLError, OSError) as exc:
        try:
            os.remove(tmp)
        except OSError:
            pass
        raise DriveError("Could not download the picture: %s" % exc)
    os.replace(tmp, dest)
    return os.path.getsize(dest)


def pdrop_new_files(settings, say=print):
    """[(person, {name, id})] of the Map_*.jpg files in the incoming folder's person folders that I have not fetched before."""
    fid = drive_id_from(settings.get("incoming_url", ""))
    if not fid:
        raise PDropError("Set the incoming Drive folder first (Sources & folders).")
    _top, folders = drive_entries(fid)
    seen = set(settings.get("pdrop_seen", []))
    out = []
    for fo in folders:
        try:
            files = drive_entries(fo["id"])[0]
        except DriveError as exc:
            say("  could not read the folder '%s': %s" % (fo["name"], str(exc).split("\n")[0]))
            continue
        out += [(fo["name"], f) for f in files if PDROP_NAME_RE.match(f["name"]) and f["id"] not in seen]
    return out


def pdrop_register(cat, settings, path, who, name):
    """Puts a fetched picture into the catalog as an UNASSIGNED file (the map is chosen by hand)."""
    if any(f["path"].lower() == path.lower() for f in cat["files"]):
        return None
    st = os.stat(path)
    code, k, draft = parse_name(os.path.basename(path))
    rec = {"path": path, "root": "added", "col": classify(path, "original", "") or "extra", "draft": draft, "map": "", "score": 0,
           "guess_key": k, "guess_code": code, "manual": False, "ign": False, "gone": False, "drive_id": "", "pub": "",
           "size": st.st_size, "mtime": int(st.st_mtime), "confirmed": False, "done": False, "quality": "", "note": "", "tool": "",
           "by": "", "date": date_from_name(name), "fdate": time.strftime("%Y-%m-%d", time.localtime(st.st_mtime)),
           "imported_from": "Drive: %s/%s" % (who, name), "from_app": who}
    cat["files"].append(rec)
    return rec


def pdrop_pickup(cat, settings, say=print, fetch=None):
    """Fetch the new pictures: download, check it is a JPEG, copy to the import folder as <Person>-<name>, list as unassigned.
    A picture that cannot be fetched stays 'new' for the next time.  Returns the list of new paths."""
    fetch = fetch or drive_download
    new = pdrop_new_files(settings, say)
    say("Picture drop: %d new picture(s) in the incoming folder." % len(new))
    got = []
    scratch = tempfile.mkdtemp(prefix="railmaps_drop_")
    try:
        for who, f in new:
            person = pdrop_clean_person(who) or "Unknown"
            tmp = os.path.join(scratch, "%s-%s" % (person, f["name"]))
            try:
                fetch(f["id"], tmp)
                with open(tmp, "rb") as fh:
                    head = fh.read(3)
                if head != b"\xff\xd8\xff":
                    raise DriveError("it is not a JPEG picture (Drive may have sent a web page instead)")
                path, _copied = import_copy(tmp, settings)
                if path == tmp:                                  # no import folder set: keep it next to the program's own data
                    keep = os.path.join(PROGRAM_HF_DIR, "From_app")
                    os.makedirs(keep, exist_ok=True)
                    path = os.path.join(keep, os.path.basename(tmp))
                    shutil.copy2(tmp, path)
                pdrop_register(cat, settings, path, who, f["name"])
                settings.setdefault("pdrop_seen", []).append(f["id"])
                got.append(path)
                say("  fetched: %s/%s -> %s" % (who, f["name"], path))
            except (DriveError, OSError) as exc:
                say("  could NOT fetch %s/%s: %s" % (who, f["name"], str(exc).split("\n")[0]))
            finally:
                try:
                    os.remove(tmp)
                except OSError:
                    pass
    finally:
        shutil.rmtree(scratch, ignore_errors=True)
    say("Picture drop: %d picture(s) fetched.  They are on the Unassigned files tab - give each one its map." % len(got))
    return got


# *************** DEL 26 - BUILD THE PAGE *****************
# ToDo: ONE static page (maps.html + thumbs\).  Three views: basic (newest original per map), advanced (all versions in
# columns + info button), detailed (basic + the information inline).  A source switch (Drive / Webdock) re-points
# every link.  English only for now.

def build_data(cat, settings):
    default_designers(cat)
    assign_pub(cat)
    files_by_map = {}
    for rec in cat["files"]:
        if included(rec) and rec.get("pub"):
            files_by_map.setdefault(rec["map"], []).append(rec)
    fields = [{"k": k, "t": label, "v": LEVELS.index(level_of(settings, k)) + 1}
              for k, label in INFO_FIELDS if level_of(settings, k) != "hidden"]
    shown = {f["k"] for f in fields}
    out = []
    for m in sorted(cat["maps"], key=lambda x: norm_key(x["name"])):
        fl = files_by_map.get(m["id"], [])
        if m.get("hidden") or (not fl and settings.get("hide_empty") and m.get("quality") != "missing" and not m.get("nothing")
                              and not (m.get("help") or "").strip()):
            continue
        fl_all = sort_versions(fl)
        paths = {f["path"].lower() for f in fl_all}
        copies_by = {}                       # copies (more photos of the same draft) hang under their main file and are not versions
        for f in fl_all:
            if f.get("copy_of") and f["copy_of"].lower() in paths:
                copies_by.setdefault(f["copy_of"].lower(), []).append(f)
        fl = [f for f in fl_all if not (f.get("copy_of") and f["copy_of"].lower() in paths)]
        info = {}
        for k in shown:
            if k == "by":
                v = " + ".join(names_of(cat, m.get("by", "")))
            elif k == "helped":
                v = " + ".join(names_of(cat, m.get("helped", "")))
            elif k == "mindist":
                v = str(m.get("mindist", "") or "").strip()          # 7 is the rule: only exceptions are written
                if v in ("7", "-", "?"):
                    v = ""
            elif k == "sruns":
                v = sruns_text(m)
            elif k == "added":
                v = added_text(m)
            elif k == "older":
                v = older_text(cat, m)
            elif k == "gaps":
                v = ("Probably missing: " + gap_text(cat, m)) if gap_text(cat, m) else ""
            elif k == "latest":
                orig = [f for f in fl if f["col"] == "orig"]
                v = ""
                if orig:
                    n = orig[-1]
                    bits = [("draft " + n["draft"]) if n.get("draft") else ""]
                    who = " + ".join(names_of(cat, n.get("by", "")))
                    if who:
                        bits.append("by " + who)
                    help_ = " + ".join(names_of(cat, n.get("helped", "")))
                    if help_:
                        bits.append("helped by " + help_)
                    if n.get("tool"):
                        bits.append(n["tool"])
                    if n.get("look"):
                        bits.append(LOOK_SHORT.get(n["look"], ""))
                    if n.get("change"):
                        bits.append(n["change"])
                    if n.get("date"):
                        bits.append(fmt_date(n["date"]))
                    v = ", ".join(b for b in bits if b)
            else:
                v = str(m.get(k, "") or "")
                if v in ("-", "?"):
                    v = ""
                elif k == "year":
                    v = fmt_date(v)
            cr = (m.get("credit") or {}).get(k)
            if v and cr and k in ("by", "year", "steps", "cities"):
                v += " (courtesy of %s)" % cr
            if v:
                info[k] = v
        pos = {id(f): i for i, f in enumerate(fl)}
        out.append({
            "id": m["id"], "n": m["name"], "c": m.get("code", ""), "t": 1 if m.get("thumb") else 0, "i": info,
            "tx": [pos[id(f)] for f in timeline_files(fl)],         # the timeline: indexes into "f", the first version first
            "c2": [list(x) for x in alt_codes(m)],                  # other codes of the map: [[code, note]]
            "fb": " + ".join(names_of(cat, m.get("by", ""))) if "by" in shown else "",      # who designed the FIRST map
            "ts": earliest_date(m, timeline_files(fl))[0], "te": earliest_date(m, timeline_files(fl))[1],   # earliest known date: the timeline is ordered by it
            "cn": len(fl_all) - len(fl),                         # how many extra photos (copies) the map has
            "u": ucode_label(m)[1:],            # the UNOFFICIAL code (only when the map has no official one); the page marks it clearly
            "q": map_quality(cat, m, fl), "qn": wanted_note(cat, m), "cm": 1 if m.get("nothing") else 0, "nf": 0 if (fl or m.get("nothing")) else 1,
            "hl": help_items(m, fl),
            "f": [{"c": f["col"], "l": f.get("draft", ""), "p": f["pub"], "d": f.get("drive_id", ""), "s": f.get("size", 0),
                   "m": f.get("mtime", 0), "b": names_of(cat, f.get("by", "")), "dt": fmt_date(f.get("date", "")),
                   "bc": codes_of(f.get("by", ""), all_people(cat)), "h": names_of(cat, f.get("helped", "")),
                   "hc": codes_of(f.get("helped", ""), all_people(cat)),
                   "cf": 1 if f.get("confirmed") else 0, "q": f.get("quality", ""), "n": f.get("note", ""),
                   "tl": f.get("tool", ""), "cr": credit_of(f), "lk": f.get("look", ""), "ch": f.get("change", ""),
                   "cp": [{"c": g["col"], "l": g.get("draft", ""), "p": g["pub"], "d": g.get("drive_id", ""), "s": g.get("size", 0),
                           "m": g.get("mtime", 0), "q": g.get("quality", ""), "n": g.get("note", ""), "b": [], "h": []}
                          for g in copies_by.get(f["path"].lower(), [])]} for f in fl]})
    sources = []
    for sid in settings.get("source_order", ["drive", "vps"]):
        if sid == "drive":
            sources.append({"id": "drive", "label": SOURCE_LABELS["drive"], "base": ""})
        elif sid == "vps" and settings.get("vps_base", "").strip():
            sources.append({"id": "vps", "label": SOURCE_LABELS["vps"], "base": settings["vps_base"].strip()})
    if not any(f["d"] for m in out for f in m["f"]):
        sources = [s for s in sources if s["id"] != "drive"]
    return {"title": settings.get("page_title", "Maps"), "built": time.strftime("%Y-%m-%d"), "sources": sources,
            "cols": [[k, v] for k, v in COLS], "looks": {k: [v, LOOK_SHORT.get(k, v)] for k, v in LOOKS if k}, "fields": fields, "maps": out,
            "quality": {k: v for k, v in QUALITY if k}, "qown": [[k, QUALITY_LABEL[k]] for k in QUALITY_BASE], "contact": settings.get("contact_email", "").strip(),
            "incoming": settings.get("incoming_url", "").strip()}


def revive_gone(cat, say=print):
    """Files I added by hand that are marked 'gone' (no longer there) but ARE on the disk: the mark was wrong (the scan used to flag files in
    sub-folders of a flat library folder) - take it off, so Build page does not need a Scan first.  Returns how many."""
    n = 0
    for f in cat["files"]:
        if f.get("gone") and f.get("manual") and os.path.isfile(f.get("path", "")):
            f["gone"] = False
            n += 1
    if n:
        say("%d file(s) were marked 'no longer there' but exist on the disk - fixed." % n)
    return n


def build_page(cat, settings, say=print):
    out = settings["out_dir"]
    revive_gone(cat, say)
    os.makedirs(os.path.join(out, "thumbs"), exist_ok=True)
    assign_pub(cat)
    by_map = {}
    for rec in cat["files"]:
        if included(rec):
            by_map.setdefault(rec["map"], []).append(rec)
    made = reused = 0
    keep = set()
    for m in cat["maps"]:
        src = pick_thumb_source(by_map.get(m["id"], []))
        m["thumb"] = False
        if not src:
            continue
        dst = os.path.join(out, "thumbs", m["id"] + ".jpg")
        stamp = "%s|%s|%s" % (src["path"], src.get("mtime"), src.get("size"))
        if os.path.isfile(dst) and m.get("thumb_stamp") == stamp:
            reused += 1
        else:
            try:
                make_thumb(src["path"], dst)
                m["thumb_stamp"] = stamp
                made += 1
            except Exception as exc:
                say("  no thumbnail for %s: %s" % (m["name"], exc))
                continue
        m["thumb"] = True
        keep.add(m["id"] + ".jpg")
    for n in os.listdir(os.path.join(out, "thumbs")):
        if n not in keep:
            try:
                os.remove(os.path.join(out, "thumbs", n))
            except OSError:
                pass
    data = build_data(cat, settings)
    blob = json.dumps(data, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
    page = PAGE_TEMPLATE.replace("</style></head>", quality_css() + "</style></head>", 1).replace("__DATA__", blob).replace("__TITLE__", html.escape(settings.get("page_title", "Maps")))
    with open(os.path.join(out, "maps.html"), "w", encoding="utf-8") as fh:
        fh.write(page)
    build_extra_pages(cat, settings, say)
    n_files = sum(len(m["f"]) for m in data["maps"])
    if not any(f["d"] for m in data["maps"] for f in m["f"]):
        others = [s["label"] for s in data["sources"]]
        say("WARNING: no Google Drive links yet - run 'Fetch Drive links' first (the Drive folder must be shared with 'Anyone with "
            "the link').  Until then the page links only to: %s - and the files are probably NOT there." % (", ".join(others) or "nothing"))
    else:
        nolink = sum(1 for m in data["maps"] for f in m["f"] if not f["d"])
        if nolink:
            say("Note: %d file(s) have no Drive link yet (not on Drive, or copied after the last 'Fetch Drive links')." % nolink)
    say("Page built: %d map(s), %d file link(s), thumbnails %d new / %d kept -> %s" % (
        len(data["maps"]), n_files, made, reused, os.path.join(out, "maps.html")))
    return data


# *************** DEL 26b - STATISTICS AND THE CODE LIST *****************
# ToDo: Lars (2026-11-09) wanted statistics (designers, maps) and a clear CODE / MAP(NAME) list, both in the program (Statistics tab)
# and as their own pages on the web site (codes.html, stats.html - written by Build page next to maps.html); every column of every
# table sorts on a click.  No statistics about the codes themselves.  Hidden maps are left out everywhere.  "Done" counts are private:
# only the program shows them.  Issu's / Json files (my colourings) are not counted as versions drawn.

def _year_of(text):
    m = re.match(r"(\d{4})", str(text or ""))
    return int(m.group(1)) if m else None


def code_rows(cat):
    """[(code, map name)] of every map that has a code, sorted by code."""
    rows = []
    for m in cat["maps"]:
        c = (m.get("code") or "").strip()
        if m.get("hidden") or c.strip("?- ") == "":              # the sheet writes ??? for an unknown code
            continue
        rows.append((c, m["name"]))
        for code, note in alt_codes(m):                          # a second / an old code of the same map (Lars 2026-11-16)
            rows.append((code, "%s  (other code of this map%s)" % (m["name"], (": " + note) if note else "")))
    return sorted(rows, key=lambda r: (r[0].upper(), norm_key(r[1])))


DESIGNER_COLS = [("Code", "t"), ("Designer", "t"), ("Base maps", "n"), ("Maps in all", "n"), ("Versions", "n"), ("Helped", "n"),
                 ("Not sure", "n"), ("First year", "n"), ("Latest year", "n")]


def designer_rows(cat):
    """One row per designer: base maps (creator of the map), maps in all (base or a version), versions drawn (originals / versions,
    not my own colourings), times helped, times only suspected (the ? marks), first and latest year."""
    visible = {m["id"] for m in cat["maps"] if not m.get("hidden")}
    st = {}
    people = all_people(cat)
    helpers_only = set(cat.get("helpers", {}))

    def S(code):
        return st.setdefault(resolve_code(people, code), {"base": set(), "any": set(), "ver": 0, "help": 0, "maybe": 0, "years": []})
    for code in cat.get("people", {}):
        S(code)
    for m in cat["maps"]:
        if m["id"] not in visible:
            continue
        y = _year_of(m.get("year"))
        for c, sus in parse_designers(m.get("by", "")):
            s = S(c)
            s["base"].add(m["id"])
            s["any"].add(m["id"])
            s["maybe"] += 1 if sus else 0
            if y:
                s["years"].append(y)
        for c, _sus in parse_designers(m.get("helped", "")):
            S(c)["help"] += 1
    for f in cat["files"]:
        if f.get("map") not in visible or f.get("gone") or f.get("ign"):
            continue
        if f.get("col") in ("orig", "version") and not f.get("copy_of"):          # a copy is the same design photographed again
            y = _year_of(f.get("date"))
            for c, sus in parse_designers(f.get("by", "")):
                s = S(c)
                s["ver"] += 1
                s["any"].add(f["map"])
                s["maybe"] += 1 if sus else 0
                if y:
                    s["years"].append(y)
        for c, _sus in parse_designers(f.get("helped", "")):
            S(c)["help"] += 1
    rows = []
    for code, s in st.items():
        if code in helpers_only:                       # helpers-only people are never listed among the designers
            continue
        rows.append([code, cat.get("people", {}).get(code, code), len(s["base"]), len(s["any"]), s["ver"], s["help"], s["maybe"],
                     min(s["years"]) if s["years"] else "", max(s["years"]) if s["years"] else ""])
    rows.sort(key=lambda r: (-r[3], -r[4], r[1].lower()))
    return rows


HELPER_COLS = [("Code", "t"), ("Helper", "t"), ("Is also a creator", "t"), ("Times helped", "n"), ("Maps helped on", "n")]


def helper_rows(cat):
    """Everybody who can help: ALL creators plus the helpers-only list, with how often they helped (map level + version level) and
    on how many maps.  Creators are shown here too, helpers are never shown among the creators."""
    people = all_people(cat)
    visible = {m["id"] for m in cat["maps"] if not m.get("hidden")}
    n, on = {}, {}
    for m in cat["maps"]:
        if m["id"] in visible:
            for c, _s in parse_designers(m.get("helped", "")):
                c = resolve_code(people, c)
                n[c] = n.get(c, 0) + 1
                on.setdefault(c, set()).add(m["id"])
    for f in cat["files"]:
        if f.get("map") in visible and not f.get("gone") and not f.get("ign"):
            for c, _s in parse_designers(f.get("helped", "")):
                c = resolve_code(people, c)
                n[c] = n.get(c, 0) + 1
                on.setdefault(c, set()).add(f["map"])
    codes = set(people) | set(n)
    rows = [[c, people.get(c, c), "yes" if c in cat.get("people", {}) else "", n.get(c, 0), len(on.get(c, ()))] for c in codes]
    rows.sort(key=lambda r: (-r[3], r[1].lower()))
    return rows


def overview_sections(cat, with_done=False):
    """[(title, headers, rows, numeric columns)] - the key numbers, maps per decade, the maps with the most original versions."""
    maps = [m for m in cat["maps"] if not m.get("hidden")]
    ids = {m["id"] for m in maps}
    live = [f for f in cat["files"] if f.get("map") in ids and not f.get("gone") and not f.get("ign")]
    per_map, orig_n = {}, {}
    for f in live:
        per_map.setdefault(f["map"], []).append(f)
        if f["col"] == "orig" and not f.get("copy_of"):
            orig_n[f["map"]] = orig_n.get(f["map"], 0) + 1
    drows = designer_rows(cat)
    key = [("Maps in the list", len(maps)),
           ("Maps with an original picture", sum(1 for m in maps if orig_n.get(m["id"]))),
           ("Maps without any file yet", sum(1 for m in maps if not per_map.get(m["id"]))),
           ("Maps with 2 or more original versions", sum(1 for n in orig_n.values() if n >= 2)),
           ("Original versions in all", sum(orig_n.values())),
           ("Designers with a map or a version", sum(1 for r in drows if r[3] > 0)),
           ("Maps looking for a better version or picture", sum(1 for m in maps if map_quality(cat, m, per_map.get(m["id"], [])) not in ("", "missing")))]
    for k, name in COLS:
        n = sum(1 for f in live if f["col"] == k)
        if n:
            key.append(("Files: " + name, n))
    designs = [f for f in live if f["col"] in TIMELINE_COLS and not f.get("copy_of")]
    for lk, lab in LOOKS[1:]:                                          # the look of the versions (Lars 2026-11-16)
        n = sum(1 for f in designs if f.get("look") == lk)
        if n:
            key.append(("Versions: " + lab.split(" (")[0].lower(), n))
    n_copies = sum(1 for f in live if f.get("copy_of"))
    if n_copies:
        key.append(("Extra photos / scans of a draft already in the list (copies)", n_copies))
    if with_done:
        key.append(("Maps done (all files)", sum(1 for m in maps if map_done_state(cat, m, per_map.get(m["id"], []))[0] == "done")))
        key.append(("Files done", sum(1 for f in live if f.get("done"))))
    dec, unknown = {}, 0
    for m in maps:
        y = _year_of(m.get("year"))
        if y:
            dec[y // 10 * 10] = dec.get(y // 10 * 10, 0) + 1
        else:
            unknown += 1
    drows_dec = [["%ds" % d, n] for d, n in sorted(dec.items())] + ([["year not known", unknown]] if unknown else [])
    top = sorted(((n, m["name"], m.get("code", "")) for m in maps for n in [orig_n.get(m["id"], 0)] if n >= 2), key=lambda t: (-t[0], t[1]))[:10]
    return [("Key numbers", ["What", "Number"], [list(r) for r in key], (1,)),
            ("Maps per decade (year of the map)", ["Decade", "Maps"], drows_dec, (1,)),
            ("Most original versions of one map", ["Map", "Code", "Versions"], [[nm, cd, n] for n, nm, cd in top], (2,))]


STAT_CSS = """
:root{--bg:#f6f4ef;--fg:#222;--dim:#6b6b6b;--card:#fff;--line:#d9d4c8;--acc:#b5532a;--acc2:#2d6a8f}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#1c1b19;--fg:#e6e2d8;--dim:#a29d90;--card:#262522;--line:#3a3833;--acc:#e08a5d;--acc2:#7fb4d6}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.4 system-ui,Segoe UI,sans-serif}
header{padding:16px;border-bottom:1px solid var(--line);background:var(--card)}h1{margin:0 0 8px;font-size:22px;color:var(--acc)}
nav a{display:inline-block;margin-right:14px;color:var(--acc2);text-decoration:none;padding:4px 0}nav a.on{color:var(--fg);font-weight:700;border-bottom:2px solid var(--acc)}
main{padding:12px 16px 24px;max-width:1000px}h2{font-size:17px;margin:22px 0 6px;color:var(--acc)}p.note{color:var(--dim);font-size:13px;margin:4px 0}
table{border-collapse:collapse;width:100%;background:var(--card)}th,td{padding:6px 10px;border-bottom:1px solid var(--line);text-align:left}
td.n,th.n{text-align:right}th{font-size:13px;color:var(--dim);cursor:pointer;user-select:none;white-space:nowrap}th:hover{color:var(--fg)}
th.asc::after{content:" \\25B2";font-size:10px}th.desc::after{content:" \\25BC";font-size:10px}
footer{padding:16px;color:var(--dim);font-size:13px;border-top:1px solid var(--line)}
@media (max-width:640px){main{padding:8px}th,td{padding:5px 5px}}
"""
STAT_JS = """
document.querySelectorAll("table.st").forEach(function(t){var hs=t.querySelectorAll("th");hs.forEach(function(h,ci){h.onclick=function(){
 var asc=h.dataset.dir!=="asc";hs.forEach(function(x){x.dataset.dir="";x.classList.remove("asc","desc")});h.dataset.dir=asc?"asc":"desc";h.classList.add(asc?"asc":"desc");
 var num=h.classList.contains("n"),rows=[].slice.call(t.tBodies[0].rows);
 var val=function(r){var c=r.cells[ci];if(num){return c.dataset.v===""?null:parseFloat(c.dataset.v)}return c.textContent.trim().toLowerCase()};
 rows.sort(function(a,b){var x=val(a),y=val(b);if(x===null&&y===null)return 0;if(x===null)return 1;if(y===null)return -1;
  var r=num?x-y:String(x).localeCompare(String(y),undefined,{numeric:true});return asc?r:-r});
 rows.forEach(function(r){t.tBodies[0].appendChild(r)})}})});
"""


class Raw(str):
    """A table cell that is already HTML (a link): stat_table_html does not escape it."""


def stat_table_html(headers, rows, numeric):
    """A table whose columns sort on a click (STAT_JS).  `numeric` = the column numbers that sort as numbers."""
    h = "<table class=\"st\"><thead><tr>%s</tr></thead><tbody>" % "".join(
        "<th%s>%s</th>" % (' class="n"' if i in numeric else "", html.escape(t)) for i, t in enumerate(headers))
    for r in rows:
        h += "<tr>" + "".join(
            ('<td class="n" data-v="%s">%s</td>' % (html.escape(str(v)), html.escape(str(v)))) if i in numeric
            else "<td>%s</td>" % (v if isinstance(v, Raw) else html.escape(str(v))) for i, v in enumerate(r)) + "</tr>"
    return h + "</tbody></table>"


def help_rows(cat, settings):
    """[[code, map (link to the map on maps.html), about, question, answer link]] - the questions for visitors, from the page data."""
    contact = (settings.get("contact_email") or "").strip()
    rows = []
    for m in build_data(cat, settings)["maps"]:
        for it in m["hl"]:
            link = Raw('<a href="maps.html#%s">%s</a>' % (urllib.parse.quote(m["id"], safe=""), html.escape(m["n"])))
            subject = "Railway Rivals maps: %s - %s" % (m["n"], it["w"])
            body = "RAILMAPS INFO v1\nMap: %s\nPart: %s\nNew or correction: \nOther information: ANSWER to the question \"%s\": \nMy name: \n" % (
                m["n"], it["w"], it["q"])
            if contact:
                ans = Raw('<a href="mailto:%s?subject=%s&amp;body=%s">Answer by e-mail</a>' % (
                    html.escape(contact), urllib.parse.quote(subject), urllib.parse.quote(body)))
            else:
                ans = Raw('<a href="maps.html#%s">Open the map to answer</a>' % urllib.parse.quote(m["id"], safe=""))
            rows.append((m["n"].lower(), it["w"], [m["c"] if m["c"] not in ("-", "?", "???") else "", link, it["w"], it["q"], ans]))
    rows.sort(key=lambda t: (t[0], t[1]))
    return [t[2] for t in rows]


# *************** DEL 26b - ABOUT PAGE (about.html) *****************
# ToDo: Lars (2026-11-10): a disclaimer / ABOUT page.  Who made Railway Rivals (David Gwyn Watts, his company Rostherne Games, later sold
# to Theo Clarke) and - the important part - that a map credited to David Watts may be the work of David AND Ann Watts, that some
# credits say "J.W." (identity not certain), and that every credit here is best-effort.  The text is EDITABLE: Helpfiles\Rail_Maps\
# about_page.txt (button "About page text..." creates it from ABOUT_DEFAULT and opens it).  Format: "# Heading" = a heading, a blank line
# = a new paragraph, "- text" = a bullet, lines of one paragraph are joined.  Plain text; the page escapes it.  {CONTACT} becomes the
# contact e-mail (setting contact_email) or, when that is empty, the sentence is dropped.
ABOUT_FILE = os.path.join(PROGRAM_HF_DIR, "about_page.txt")
ABOUT_DEFAULT = """# About this collection
This is an unofficial, privately kept library of maps for the railway game Railway Rivals: the maps, the drafts they went through, and the little
that is known about who drew them and when. It is a hobby archive, kept for the love of the game. It is not made, approved or checked by the owners of the game.

# The game and who is behind it
Railway Rivals was created by David Gwyn Watts. The game belonged to his company, Rostherne Games, which was later sold to Theo Clarke.
The name Railway Rivals, the rules and the original maps belong to their owners and creators. Nothing on these pages is meant to take that away from them.

# Who drew the maps? Please read this
Credits on old maps are often short and sometimes confusing. This page tries to be honest about what is known and what is not:
- Where David Watts (David Gwyn Watts) is named as the designer of a map, the map may be the work of David AND Ann Watts together. Old credits mostly name only David, so the sheet and this page do too, but that does not mean Ann had no part in it.
- In some cases the source says that a map was drawn by "J.W.". Who J.W. is has not been confirmed. It may be another member of the Watts family, but that is a guess and should not be taken as a fact.
- A "?" after a name means the designer is only suspected, not confirmed.
- Most maps exist in several drafts. A later draft can be drawn by someone other than the person who made the first one, or only improved by a helper. Every version therefore has its own credit, and "helped by" is kept apart from "designed by".
- Dates are given as exactly as they are known: a full date, a month, or only a year. Many are the year of the first draft, not the day the map was finished.
- Credits come from an old spreadsheet, from file names and from the comments inside the map files. They have been put together by hand and can contain mistakes.

# Corrections are welcome
If you know who really drew a map, when it was made, or if you have a draft that is missing here, please tell me. Click the pencil button next to a map, a column or a file and the form will help you write it. {CONTACT}

# If you are a rights holder
If you are the creator or an owner of a map or of the game and would like something changed, credited differently or taken down, please get in touch and I will do it. {CONTACT}

# About the collection
The collection and these pages are kept by Lars “Issu” Olsson. The map files themselves are links to files stored on Google Drive. No guarantee is given that anything here is correct or complete.
"""


def about_source():
    """The About text: the user's own file when it exists and has text, else the built-in one."""
    try:
        with open(ABOUT_FILE, encoding="utf-8") as fh:
            t = fh.read()
        if t.strip():
            return t
    except OSError:
        pass
    return ABOUT_DEFAULT


def about_html(settings):
    """The body of about.html made from the About text (see the format in the DEL 26b comment)."""
    contact = (settings.get("contact_email") or "").strip()
    text = about_source().replace("\r\n", "\n")
    if contact:
        text = text.replace("{CONTACT}", "You can write to %s." % contact)
    else:
        text = text.replace(" {CONTACT}", "").replace("{CONTACT}", "")
    inc = (settings.get("incoming_url") or "").strip()
    if inc:                                  # how to send me files; added even when my own about_page.txt does not mention it
        block = ("# Send me maps and drafts\nIf you have a map file or a draft that is missing here, put it in my Google Drive folder: %s "
                 "- please make a folder with your own name first, so I know whose files they are.\n" % inc)
        text = text.replace("{SEND}", block) if "{SEND}" in text else text.rstrip("\n") + "\n\n" + block
    else:
        text = text.replace("{SEND}", "")
    out, para, bullets = [], [], []

    def flush():
        if para:
            body = html.escape(" ".join(para))
            body = re.sub(r"(https?://[^\s<]+)", r'<a href="\1" target="_blank" rel="noopener">\1</a>', body)      # links are clickable
            out.append("<p>%s</p>" % body)
            para.clear()
        if bullets:
            out.append("<ul>%s</ul>" % "".join("<li>%s</li>" % html.escape(b) for b in bullets))
            bullets.clear()
    for line in text.split("\n"):
        s = line.strip()
        if not s:
            flush()
        elif s.startswith("# "):
            flush()
            out.append("<h2>%s</h2>" % html.escape(s[2:].strip()))
        elif s.startswith("- "):
            if para:
                flush()
            bullets.append(s[2:].strip())
        else:
            if bullets:
                flush()
            para.append(s)
    flush()
    return "".join(out)


# The short line at the bottom of every page (maps.html has the same text in its script).
FOOT_TEXT = ("Railway Rivals was created by David Gwyn Watts and belonged to his company Rostherne Games, later sold to Theo Clarke. "
             "Designer credits are best-effort: a map credited to David Watts may be by David and Ann Watts. "
             "<a href=\"about.html\">About and credits</a>. Collection and page by Lars “Issu” Olsson.")


def stat_page(title, active, body, built):
    nav = "".join('<a href="%s"%s>%s</a>' % (href, ' class="on"' if href == active else "", label)
                  for href, label in (("maps.html", "Maps"), ("help.html", "Help me"), ("missing.html", "Missing maps"),
                                      ("codes.html", "Codes"), ("stats.html", "Statistics"), ("tools.html", "Tools"),
                                      ("examples.html", "Examples"), ("about.html", "About")))
    return ("<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,"
            "initial-scale=1\"><title>%s</title><style>%s</style></head><body><header><h1>%s</h1><nav>%s</nav></header><main>%s</main>"
            "<footer>%s Updated %s.</footer><script>%s</script></body></html>"
            % (html.escape(title), STAT_CSS, html.escape(title), nav, body, FOOT_TEXT, html.escape(built), STAT_JS))


def build_extra_pages(cat, settings, say=print):
    """codes.html (CODE / MAP) and stats.html (designers + overview) next to maps.html."""
    out = settings["out_dir"]
    os.makedirs(out, exist_ok=True)
    base = settings.get("page_title", "Maps")
    built = time.strftime("%Y-%m-%d")
    rows = code_rows(cat)
    body = ("<p class=\"note\">%d codes.  Click a column heading to sort by it (click again to reverse).</p>" % len(rows)
            + stat_table_html(["Code", "Map"], [list(r) for r in rows], ()))
    urows = sorted(([ucode_label(m), m["name"]] for m in cat["maps"] if ucode_label(m) and not m.get("hidden")), key=lambda r: r[0])
    if urows:                         # unofficial codes: a table of their own, never mixed with the official ones
        body += ("<h2>Unofficial codes</h2><p class=\"note\">%s</p>" % html.escape(UCODE_NOTE)
                 + stat_table_html(["Code (unofficial)", "Map"], urows, ()))
    with open(os.path.join(out, "codes.html"), "w", encoding="utf-8") as fh:
        fh.write(stat_page(base + " - codes", "codes.html", body, built))
    body = "<h2>Designers</h2><p class=\"note\">Base maps = maps the designer created.  Maps in all = base maps plus maps where the designer " \
           "drew a later version.  Versions = original versions drawn (Lars’s own colourings are not counted).  Not sure = " \
           "entries where the designer is only suspected (marked ?).  Credits are best-effort: a map credited to David Watts may be by David " \
           "and Ann Watts - see <a href=\"about.html\">About</a>.  Click a heading to sort.</p>"
    body += stat_table_html([c for c, _t in DESIGNER_COLS], designer_rows(cat), [i for i, (_c, t) in enumerate(DESIGNER_COLS) if t == "n"])
    hrows = [r for r in helper_rows(cat) if r[3] > 0]          # on the page only helpers who actually helped
    if hrows:
        body += "<h2>Helpers</h2><p class=\"note\">People who helped with a map or a version.</p>"
        body += stat_table_html([c for c, _t in HELPER_COLS], hrows, [i for i, (_c, t) in enumerate(HELPER_COLS) if t == "n"])
    for title, hdr, drows, num in overview_sections(cat):
        body += "<h2>%s</h2>" % html.escape(title) + stat_table_html(hdr, drows, num)
    with open(os.path.join(out, "stats.html"), "w", encoding="utf-8") as fh:
        fh.write(stat_page(base + " - statistics", "stats.html", body, built))
    mrows = missing_rows(cat)
    if mrows:
        body = ("<p class=\"note\">%d map(s) that are completely missing - no picture of the map exists in the collection.  If you have one, "
                "please get in touch!  Click a heading to sort.</p>" % len(mrows)
                + stat_table_html(["Code", "Map", "Year", "Designer(s)", "Note"], mrows, ()))
    else:
        body = "<p class=\"note\">No map is marked as completely missing right now.</p>"
    with open(os.path.join(out, "missing.html"), "w", encoding="utf-8") as fh:
        fh.write(stat_page(base + " - missing maps", "missing.html", body, built))
    hrows2 = help_rows(cat, settings)
    if hrows2:
        body = ("<p class=\"note\">%d question(s) about the maps. If you know the answer, click the map name to go straight to it, or "
                "answer by e-mail. Thank you!  Click a heading to sort.</p>" % len(hrows2)
                + stat_table_html(["Code", "Map", "About", "Question", ""], hrows2, ()))
    else:
        body = "<p class=\"note\">No questions right now.</p>"
    with open(os.path.join(out, "help.html"), "w", encoding="utf-8") as fh:
        fh.write(stat_page(base + " - help me", "help.html", body, built))
    with open(os.path.join(out, "tools.html"), "w", encoding="utf-8") as fh:
        fh.write(stat_page(base + " - tools", "tools.html", tools_html(cat), built))
    with open(os.path.join(out, "about.html"), "w", encoding="utf-8") as fh:
        fh.write(stat_page(base + " - about", "about.html", about_html(settings), built))
    try:
        build_examples(settings, say)
    except Exception as exc:                       # the examples must never stop the rest of the page
        say("Examples page NOT built: %s" % exc)
    say("Extra pages built: codes.html (%d codes), stats.html, missing.html (%d missing maps), help.html (%d questions), tools.html and about.html -> %s"
        % (len(rows), len(mrows), len(hrows2), out))


def missing_rows(cat):
    """[[code, map, year, designers, note]] - the maps marked COMPLETELY MISSING (right-click).  Other files of the map (comments about
    the designer, places ...) do not matter: the mark is my decision that the MAP itself is missing, until I clear it."""
    rows = []
    for m in sorted(cat["maps"], key=lambda x: norm_key(x["name"])):
        if m.get("nothing") and not m.get("hidden"):
            code = (m.get("code") or "").strip()
            rows.append([code if code not in ("-", "?", "???") else "", m["name"], fmt_date(m.get("year", "")) if m.get("year") not in ("-", "?") else "",
                         " + ".join(names_of(cat, m.get("by", ""))), m.get("qnote", "")])
    return rows


# *************** DEL 26d - EXAMPLES PAGE (examples.html: pictures made with PicturePerfect) *****************
# ToDo: Lars (2026-11-17): the page shows what the PicturePerfect app can do.  Every picture in Helpfiles\Rail_Maps\Examples\ is one example
# (jpg / jpeg / png).  An optional text file with the SAME name (Argentina---PicturePerfect.txt for Argentina---PicturePerfect.jpeg) holds the
# description: first line "# Title", then paragraphs (blank line = new paragraph, "- " = bullet).  Without it the title is the file name up
# to the first "---".  "intro.txt" in the same folder replaces the text at the top of the page.  Build page copies the pictures to
# <page folder>\examples\ (a smaller copy for the screen when the picture is large, the ORIGINAL for download), removes copies whose source is
# gone, and writes examples.html with a full-size viewer (click the picture, scroll to look at details) + Open / Download links.
# The pictures travel with "Upload page" (the page folder is sent as a whole).  More examples later = drop the files in the folder, Build page.
EXAMPLES_DIR = os.path.join(PROGRAM_HF_DIR, "Examples")
EXAMPLES_OUT = "examples"
EX_IMG_EXT = (".jpg", ".jpeg", ".png")
EX_VIEW_EDGE = 2000                      # a picture whose long side is larger gets a screen copy of this size (the original stays for download)
EXAMPLES_INTRO_DEFAULT = """These are real photographs of paper maps, made with the Android app PicturePerfect (see the Tools page).
A photo of a sheet on a table is never straight: the paper is seen at an angle, the light is uneven and a glossy sheet reflects the lamp. PicturePerfect finds the sheet, draws a frame round it, straightens it into a flat rectangle and warns when the light is bad.
It can also take several photos of the same sheet from different sides (the second one from the opposite side) and fuse them: the sharpest detail of each photo is used and reflections are left out.
Click a picture to see it at full size and scroll around to look at the thin lines and the small print. Use Download to get the original file and judge it on your own screen.
"""


def ex_slug(name):
    """A safe file name for the web: ASCII letters, digits, dot, dash, underscore only."""
    s = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode("ascii")
    s = re.sub(r"[^A-Za-z0-9._-]+", "_", s).strip("._")
    return s or "example"


def ex_title_from(stem):
    t = stem.split("---")[0].strip() or stem
    return t.replace("_", " ").strip()


def text_to_html(text):
    """Small text format -> HTML: '# Heading', blank line = new paragraph, '- ' bullets; URLs become links.  Everything is escaped."""
    out, para, bullets = [], [], []

    def flush():
        if para:
            body = html.escape(" ".join(para))
            out.append("<p>%s</p>" % re.sub(r"(https?://[^\s<]+)", r'<a href="\1" target="_blank" rel="noopener">\1</a>', body))
            para.clear()
        if bullets:
            out.append("<ul>%s</ul>" % "".join("<li>%s</li>" % html.escape(b) for b in bullets))
            bullets.clear()
    for line in text.replace("\r\n", "\n").split("\n"):
        s = line.strip()
        if not s:
            flush()
        elif s.startswith("# "):
            flush()
            out.append("<h3>%s</h3>" % html.escape(s[2:].strip()))
        elif s.startswith("- "):
            if para:
                flush()
            bullets.append(s[2:].strip())
        else:
            if bullets:
                flush()
            para.append(s)
    flush()
    return "".join(out)


def read_text_file(path):
    try:
        with open(path, encoding="utf-8-sig") as fh:
            return fh.read()
    except (OSError, UnicodeDecodeError):
        return ""


def example_items(folder=None):
    """[{src, file, title, text, w, h, size}] - one per picture in the Examples folder, sorted by file name.  Never raises."""
    folder = folder or EXAMPLES_DIR
    items = []
    try:
        names = sorted(os.listdir(folder), key=lambda n: n.lower())
    except OSError:
        return items
    from PIL import Image
    for n in names:
        stem, ext = os.path.splitext(n)
        src = os.path.join(folder, n)
        if ext.lower() not in EX_IMG_EXT or not os.path.isfile(src):
            continue
        try:
            with Image.open(src) as im:
                w, h = im.size
        except Exception:
            continue                                 # not a readable picture: skipped
        raw = read_text_file(os.path.join(folder, stem + ".txt")).replace("\r\n", "\n").strip("\n")
        title, body = ex_title_from(stem), raw
        first, _nl, rest = raw.partition("\n")
        if first.startswith("# "):
            title, body = first[2:].strip() or title, rest
        items.append({"src": src, "file": n, "title": title, "text": body, "w": w, "h": h, "size": os.path.getsize(src)})
    return items


def examples_html(items, intro):
    """The body of examples.html."""
    parts = ["<div class=\"exintro\">%s</div>" % text_to_html(intro)]
    parts.append("<p class=\"note\">Want to try it yourself?  The app is on the <a href=\"tools.html\">Tools</a> page.</p>")
    if not items:
        parts.append("<p>No examples yet.</p>")
    for it in items:
        slug = ex_slug(it["file"])
        view = it.get("view") or slug
        kb = it["size"] / 1024.0
        size = "%.1f MB" % (kb / 1024.0) if kb >= 1024 else "%d KB" % round(kb)
        parts.append(
            "<section class=\"ex\"><h2>%s</h2>%s"
            "<figure><img class=\"exzoom\" src=\"%s/%s\" data-full=\"%s/%s\" alt=\"%s\" loading=\"lazy\"></figure>"
            "<p class=\"exlinks\"><a href=\"%s/%s\" target=\"_blank\" rel=\"noopener\">Open full size</a> &nbsp;|&nbsp; "
            "<a href=\"%s/%s\" download=\"%s\">Download the picture</a> <span class=\"note\">(%d &times; %d pixels, %s)</span></p></section>"
            % (html.escape(it["title"]), text_to_html(it["text"]), EXAMPLES_OUT, urllib.request.quote(view), EXAMPLES_OUT, urllib.request.quote(slug),
               html.escape(it["title"], quote=True), EXAMPLES_OUT, urllib.request.quote(slug), EXAMPLES_OUT, urllib.request.quote(slug),
               html.escape(it["file"], quote=True), it["w"], it["h"], size))
    parts.append("<div id=\"exbox\" hidden><div id=\"exscroll\"><img id=\"eximg\" alt=\"\"></div><div id=\"exhelp\">Scroll to look around &middot; click or press Esc to close</div></div>")
    parts.append("<script>" + EX_JS + "</script>")
    return "".join(parts)


EX_CSS = """
.exintro p{max-width:760px}.ex{margin:26px 0;padding:14px;background:var(--card);border:1px solid var(--line);border-radius:8px}
.ex h2{margin-top:0}.ex h3{font-size:15px;margin:10px 0 4px}.ex p{max-width:760px}figure{margin:12px 0 6px}
img.exzoom{max-width:100%;height:auto;border:1px solid var(--line);cursor:zoom-in;background:#fff}p.exlinks{margin:6px 0}
#exbox{position:fixed;inset:0;z-index:50;background:rgba(0,0,0,.88)}#exbox[hidden]{display:none}
#exscroll{position:absolute;inset:0;overflow:auto;cursor:zoom-out;-webkit-overflow-scrolling:touch}#eximg{display:block;max-width:none;margin:0 auto;background:#fff}
#exhelp{position:fixed;left:0;right:0;bottom:0;padding:6px 10px;text-align:center;color:#fff;background:rgba(0,0,0,.6);font-size:13px;pointer-events:none}
"""
STAT_CSS += EX_CSS
EX_JS = """
(function(){var box=document.getElementById("exbox"),im=document.getElementById("eximg"),sc=document.getElementById("exscroll");
 function close(){box.hidden=true;im.removeAttribute("src");document.body.style.overflow=""}
 document.querySelectorAll("img.exzoom").forEach(function(p){p.addEventListener("click",function(){im.src=p.dataset.full;box.hidden=false;sc.scrollTop=0;sc.scrollLeft=0;document.body.style.overflow="hidden"})});
 sc.addEventListener("click",close);document.addEventListener("keydown",function(e){if(e.key==="Escape"&&!box.hidden)close()})})();
"""


def build_examples(settings, say=print):
    """Copy the example pictures to <page folder>\\examples and write examples.html.  Returns the number of examples."""
    out = settings["out_dir"]
    dst_dir = os.path.join(out, EXAMPLES_OUT)
    os.makedirs(dst_dir, exist_ok=True)
    try:
        os.makedirs(EXAMPLES_DIR, exist_ok=True)           # so the folder is there for me to drop pictures in
    except OSError:
        pass
    items = example_items()
    keep = set()
    from PIL import Image
    Image.MAX_IMAGE_PIXELS = None
    for it in items:
        slug = ex_slug(it["file"])
        target = os.path.join(dst_dir, slug)
        keep.add(slug)
        try:
            if not (os.path.isfile(target) and os.path.getsize(target) == it["size"] and os.path.getmtime(target) >= os.path.getmtime(it["src"]) - 2):
                shutil.copyfile(it["src"], target)
            if max(it["w"], it["h"]) > EX_VIEW_EDGE:       # large picture: a lighter copy for the screen, the original is for download
                vname = os.path.splitext(slug)[0] + "-view.jpg"
                vpath = os.path.join(dst_dir, vname)
                if not (os.path.isfile(vpath) and os.path.getmtime(vpath) >= os.path.getmtime(it["src"])):
                    with Image.open(it["src"]) as im:
                        im = im.convert("RGB")
                        im.thumbnail((EX_VIEW_EDGE, EX_VIEW_EDGE), Image.LANCZOS)
                        im.save(vpath, "JPEG", quality=88)
                it["view"] = vname
                keep.add(vname)
        except OSError as exc:
            say("  example %s could not be copied: %s" % (it["file"], exc))
    for n in os.listdir(dst_dir):
        if n not in keep:
            try:
                os.remove(os.path.join(dst_dir, n))
            except OSError:
                pass
    intro = read_text_file(os.path.join(EXAMPLES_DIR, "intro.txt")).strip() or EXAMPLES_INTRO_DEFAULT
    base = settings.get("page_title", "Maps")
    with open(os.path.join(out, "examples.html"), "w", encoding="utf-8") as fh:
        fh.write(stat_page(base + " - examples", "examples.html", examples_html(items, intro), time.strftime("%Y-%m-%d")))
    say("Examples page built: %d picture(s) from %s" % (len(items), EXAMPLES_DIR))
    return len(items)


# *************** DEL 26c - UPLOAD THE PAGE TO THE SERVER *****************
# ToDo: Lars (2026-11-09): "build the upload into the rail program".  Same place and same method as AppSite's "Rail Maps" job, so the two
# never disagree:  <remote>/p/railmaps/  = the CONTENTS of the page folder (maps.html is also copied to index.html, so the folder address
# works; codes.html, stats.html and thumbs\ come along).  The folder is replaced as a whole (unpacked beside the old one, then swapped).
# Map files are NOT sent (they live on Google Drive).  No server address is written here: it is READ from AppSite's settings
# (Helpfiles\AppSite\settings.json: upd_host, upd_port, upd_user, upd_key, upd_remote, upd_url) - never written.
APPSITE_SETTINGS = os.path.join(HELPFILES_DIR, "AppSite", "settings.json")
SRV_PATH_RE = re.compile(r"^/[A-Za-z0-9_./\-]+$")


def server_cfg():
    """The server settings from AppSite's settings file, or RuntimeError with a plain explanation."""
    try:
        with open(APPSITE_SETTINGS, encoding="utf-8") as fh:
            d = json.load(fh) or {}
    except (OSError, ValueError):
        raise RuntimeError("The server settings could not be read from AppSite's settings file.\n"
                           "Open AppSite, go to its Updates tab and set up the server there first.")
    cfg = {"host": str(d.get("upd_host", "")).strip(), "port": str(d.get("upd_port", "")).strip(), "user": str(d.get("upd_user", "")).strip(),
           "key": str(d.get("upd_key", "")).strip(), "remote": str(d.get("upd_remote", "")).strip(), "url": str(d.get("upd_url", "")).strip()}
    missing = [k for k, v in cfg.items() if not v]
    if missing:
        raise RuntimeError("AppSite's Updates settings are not complete (missing: %s).  Fill them in there; this program uses the same server."
                           % ", ".join(missing))
    if not os.path.isfile(cfg["key"]):
        raise RuntimeError("The server key file was not found:\n%s\nCheck the key path in AppSite > Updates." % cfg["key"])
    return cfg


def _openssh_exe(name):
    p = shutil.which(name)
    return p if p else os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "OpenSSH", name + ".exe")


def _ssh_opts(cfg, port_flag):
    return ["-i", cfg["key"], "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new",
            "-o", "ConnectTimeout=15", port_flag, cfg["port"]]


def _run_cmd(cmd, timeout=300):
    """(returncode, stdout, stderr) - never raises."""
    try:
        r = subprocess.run(cmd, capture_output=True, timeout=timeout, creationflags=0x08000000 if os.name == "nt" else 0)
        return r.returncode, r.stdout.decode("utf-8", "replace"), r.stderr.decode("utf-8", "replace")
    except (OSError, subprocess.SubprocessError) as exc:
        return 255, "", str(exc)


def upload_page(settings, say=print):
    """Sends the page folder (out_dir) to <remote>/p/railmaps.  Returns True when it is on the server."""
    page_dir = settings.get("out_dir", "")
    if not os.path.isfile(os.path.join(page_dir, "maps.html")):
        say("No maps.html in %s - press 'Build page' first." % page_dir)
        return False
    try:
        cfg = server_cfg()
    except RuntimeError as exc:
        say("CANNOT UPLOAD: %s" % exc)
        return False
    remote = cfg["remote"].rstrip("/") + "/p/railmaps"
    url = cfg["url"].rstrip("/") + "/p/railmaps/"
    if not SRV_PATH_RE.match(remote):
        say("CANNOT UPLOAD: unsafe server path %s" % remote)
        return False
    stage = tempfile.mkdtemp(prefix="railmaps_page_")
    tgz = os.path.join(tempfile.gettempdir(), "railmaps_page_%d.tgz" % os.getpid())
    try:
        shutil.copytree(page_dir, stage, dirs_exist_ok=True)
        shutil.copyfile(os.path.join(stage, "maps.html"), os.path.join(stage, "index.html"))
        names = sorted(n for n in os.listdir(stage) if os.path.isfile(os.path.join(stage, n)))
        say("Sending the page (%s) ..." % ", ".join(names))
        with tarfile.open(tgz, "w:gz") as t:
            t.add(stage, arcname=".")
        ssh = [_openssh_exe("ssh")] + _ssh_opts(cfg, "-p") + ["%s@%s" % (cfg["user"], cfg["host"])]
        rc, _o, err = _run_cmd(ssh + ["mkdir -p '%s' && chmod 755 '%s'" % (remote.rsplit("/", 1)[0], remote.rsplit("/", 1)[0])], 120)
        if rc != 0:
            say("FAILED (ssh): %s" % (err.strip()[-200:] or "code %d" % rc))
            return False
        rc, _o, err = _run_cmd([_openssh_exe("scp")] + _ssh_opts(cfg, "-P") + [tgz, "%s@%s:%s" % (cfg["user"], cfg["host"], remote + ".tgz")], 900)
        if rc != 0:
            say("FAILED (scp): %s" % err.strip()[-200:])
            return False
        d = remote
        cmd = ("set -e; rm -rf '%(d)s.new'; mkdir -p '%(d)s.new'; tar -xzf '%(d)s.tgz' -C '%(d)s.new'; rm -f '%(d)s.tgz'; "
               "chmod -R a+rX '%(d)s.new'; if [ -d '%(d)s' ]; then rm -rf '%(d)s.old'; mv '%(d)s' '%(d)s.old'; fi; "
               "mv '%(d)s.new' '%(d)s'; rm -rf '%(d)s.old'") % {"d": d}
        rc, _o, err = _run_cmd(ssh + [cmd], 300)
        if rc != 0:
            say("FAILED (unpack): %s" % err.strip()[-200:])
            return False
    finally:
        shutil.rmtree(stage, ignore_errors=True)
        try:
            os.remove(tgz)
        except OSError:
            pass
    ok = False
    try:
        with urllib.request.urlopen(urllib.request.Request(url + "index.html", method="HEAD"), timeout=20) as r:
            ok = 200 <= r.status < 300
    except Exception:
        ok = False
    say("DONE - the page is on the server: %s   (live check: %s)" % (url, "ok" if ok else "not reachable yet"))
    say("Open %s and press Ctrl+F5 if the browser still shows the old page." % url)
    return True


# *************** DEL 26d - UPDATE EVERYTHING (v: 2026-11-14) *****************
# ToDo: ONE press does the whole round in the right order, so no step can be forgotten:  Scan folders -> Make upload folder (copy to Google
# Drive for desktop) -> Fetch Drive links -> Build page -> Upload page (Webdock, p/railmaps -> rail.issusbarn.se).  A step that fails STOPS the
# round at that step with a plain message (nothing after it is done; the page is never built from half-done work).  The catalog is saved after
# the steps that change it.  update_pipeline() has no window: the button here runs it in a worker thread, and AppSite's DO EVERYTHING button
# loads this file as a module and calls headless_update().  HTG (the old web server) is gone: the page and its map links need only Drive + Webdock.
def update_pipeline(cat, settings, say, scan=True):
    """Returns (ok, summary text).  `say(text)` gets every progress line."""
    steps = []
    if scan:
        steps.append(("Scan folders", lambda: (scan_library(cat, settings, say), rematch_unassigned(cat, say), steps_after_sheet_or_scan(cat, say))))
    steps += [("Make upload folder", lambda: make_upload_folder(cat, settings, say)),
              ("Fetch Drive links", lambda: drive_fetch_ids(cat, settings, say))]
    for i, (name, fn) in enumerate(steps, start=1):
        say("--- %d. %s ---" % (i, name))
        try:
            fn()
        except Exception as exc:
            return False, "%s failed: %s" % (name, exc)
        save_catalog(cat)
    started = time.time()
    say("--- %d. Build page ---" % (len(steps) + 1))
    try:
        build_page(cat, settings, say)
    except Exception as exc:
        return False, "Build page failed: %s" % exc
    page = os.path.join(settings.get("out_dir", ""), "maps.html")
    try:
        if os.path.getmtime(page) >= started - 1:
            settings["built_for"] = catalog_stamp(cat)
            save_json(SETTINGS_FILE, settings)
    except OSError:
        pass
    save_catalog(cat)
    say("--- %d. Upload page ---" % (len(steps) + 2))
    ok = upload_page(settings, say)
    if not ok:
        return False, "Upload page failed (see the lines above)."
    try:
        check_incoming(settings, say)
        save_json(SETTINGS_FILE, settings)
    except Exception:
        pass
    return True, "Rail Maps: the page is built and on the server."


def headless_update(say, scan=True):
    """The whole round from the saved catalog and settings, no window.  Returns (ok, summary)."""
    try:
        settings = load_settings()
        cat = load_catalog()
        if not cat.get("maps"):
            return False, "The map list is empty - open Rail_Maps once and import the sheet."
        ok, text = update_pipeline(cat, settings, say, scan=scan)
    except Exception as exc:
        return False, "Crashed: %s" % exc
    return ok, text


# *************** DEL 27 - THE PAGE TEMPLATE *****************
# ToDo: plain HTML + JS, no libraries.  __DATA__ / __TITLE__ are replaced by build_page.

PAGE_TEMPLATE = r'''<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>__TITLE__</title>
<style>
:root{--bg:#f6f4ef;--fg:#222;--dim:#6b6b6b;--card:#fff;--line:#d9d4c8;--acc:#b5532a;--acc2:#2d6a8f;--chip:#efe9dc;--qm:#f3dd8a;--qmf:#4a3a00;--qp:#e9a39b;--qpf:#4a0d07;--qb:#b9d6ef;--qbf:#0c2f4d}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--qm:#7a6420;--qmf:#fff3c4;--qp:#8a3a32;--qpf:#ffd9d4;--qb:#2f5b82;--qbf:#d9ecfb;--bg:#1c1b19;--fg:#e6e2d8;--dim:#a29d90;--card:#262522;--line:#3a3833;--acc:#e08a5d;--acc2:#7fb4d6;--chip:#33312c}}
:root[data-theme="dark"]{--bg:#1c1b19;--fg:#e6e2d8;--dim:#a29d90;--card:#262522;--line:#3a3833;--acc:#e08a5d;--acc2:#7fb4d6;--chip:#33312c}
*{box-sizing:border-box}html,body{height:100%}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.4 system-ui,Segoe UI,sans-serif;display:flex;flex-direction:column;overflow:hidden}
header{flex:none;padding:16px;border-bottom:1px solid var(--line);background:var(--card)}
h1{margin:0 0 8px;font-size:22px;color:var(--acc)}
.bar{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center}
.seg{display:inline-flex;border:1px solid var(--line);border-radius:8px;overflow:hidden}
.seg button{border:0;background:var(--card);color:var(--fg);padding:6px 12px;cursor:pointer;font:inherit}
.seg button.on{background:var(--acc);color:#fff}
.lbl{color:var(--dim);font-size:13px;margin-right:4px}
input[type=search]{padding:6px 10px;border:1px solid var(--line);border-radius:8px;background:var(--card);color:var(--fg);font:inherit;min-width:200px}
main{flex:1;min-height:0;padding:0 16px;overflow:auto}  /* header stays on top; the list scrolls inside main */
td.cd{white-space:nowrap;font-weight:600;color:var(--dim)}i.uc{font-weight:400;border-bottom:1px dotted var(--dim);cursor:help}
table{border-collapse:collapse;width:100%}th,td{padding:6px 8px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}
th{position:sticky;top:0;z-index:2;background:var(--bg);font-size:13px;color:var(--dim)}
td.nm{min-width:160px}.nm b{display:block}.nm small{color:var(--dim)}
img.th{width:84px;height:60px;object-fit:cover;border-radius:4px;border:1px solid var(--line);display:block;background:var(--chip)}
.ph{width:84px;height:60px;border-radius:4px;border:1px dashed var(--line);display:flex;align-items:center;justify-content:center;color:var(--dim);font-size:12px}
a.chip{display:inline-block;margin:1px 3px 1px 0;padding:2px 8px;border-radius:12px;background:var(--chip);color:var(--acc2);text-decoration:none;font-size:13px;white-space:nowrap}
a.chip:hover{background:var(--acc);color:#fff}
a.chip.q-minor,span.chip.q-minor{background:var(--qm);color:var(--qmf)}a.chip.q-poor,span.chip.q-poor{background:var(--qp);color:var(--qpf)}
.dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:6px;vertical-align:middle}
.dot.q-minor{background:var(--qm)}.dot.q-poor,.dot.q-missing{background:var(--qp)}
.legend{font-size:13px;color:var(--dim)}.legend .dot{margin:0 4px 0 10px}
.qn{font-size:13px;color:var(--dim);display:block}
.cmb{display:inline-block;margin-left:8px;padding:1px 7px;border-radius:10px;background:var(--qp);color:#fff;font-size:11px;font-weight:700;letter-spacing:.3px;vertical-align:middle}
.ph.cm{border:1px solid var(--qp);color:var(--qp);font-weight:700;font-size:11px;text-align:center}
.ph.nf{border:1px dashed var(--acc);color:var(--acc);font-weight:700;font-size:11px;text-align:center}
.cmb.nfb{background:var(--acc)}
.cmb.hlb{background:var(--acc);text-decoration:none;cursor:pointer}
tr.hit td{background:rgba(255,200,0,.22)}
.hq{border:1px solid var(--line);border-left:4px solid var(--acc);border-radius:6px;padding:6px 10px;margin:6px 0}
.btn{border:1px solid var(--line);background:var(--card);color:var(--acc2);border-radius:50%;width:26px;height:26px;cursor:pointer;font:inherit;font-weight:700}
.info{font-size:13px;color:var(--dim)}.info span{margin-right:12px;white-space:nowrap}.info b{color:var(--fg);font-weight:600}
dialog{border:1px solid var(--line);border-radius:12px;background:var(--card);color:var(--fg);max-width:720px;width:92vw;padding:18px}
dialog::backdrop{background:rgba(0,0,0,.45)}dialog h2{margin:0 0 8px;color:var(--acc)}
dl{display:grid;grid-template-columns:140px 1fr;gap:3px 12px;margin:8px 0}dt{color:var(--dim)}dd{margin:0}
.grp{margin:10px 0 2px;font-weight:600}
footer{padding:16px 0;color:var(--dim);font-size:13px;border-top:1px solid var(--line)}
.none{color:var(--dim)}
.ver{margin-bottom:4px}.vl{display:block;font-size:12px;color:var(--dim);line-height:1.25;white-space:nowrap}
a.chip.q-photo,span.chip.q-photo{background:var(--qb);color:var(--qbf)}.dot.q-photo{background:var(--qb)}
a.sg{margin-left:6px;cursor:pointer;color:var(--acc2);text-decoration:none}
.lk{display:inline-block;font-size:11px;border:1px solid var(--line);border-radius:8px;padding:0 6px;margin:1px 0;white-space:nowrap}
.lk.bw{color:var(--dim)}.lk.hand{color:var(--acc);border-color:var(--acc)}.lk.print{color:var(--acc2);border-color:var(--acc2)}
.tlh2 th{top:32px}th.grp{text-align:center;border-left:1px solid var(--line)}td.sep{border-left:1px solid var(--line)}
.tlnote{margin:10px 0 4px;font-size:13px;color:var(--dim);max-width:980px}
.mk{font-size:13px;line-height:1.35}.mk b{color:var(--acc)}
@media (max-width:640px){main{padding:0 8px}th,td{padding:5px 4px}}
</style></head><body>
<header><h1>__TITLE__</h1>
<nav style="margin-bottom:8px"><a href="maps.html" style="margin-right:14px;font-weight:700;color:var(--fg);text-decoration:none;border-bottom:2px solid var(--acc)">Maps</a><a href="help.html" style="margin-right:14px;color:var(--acc2);text-decoration:none">Help me</a><a href="missing.html" style="margin-right:14px;color:var(--acc2);text-decoration:none">Missing maps</a><a href="codes.html" style="margin-right:14px;color:var(--acc2);text-decoration:none">Codes</a><a href="stats.html" style="margin-right:14px;color:var(--acc2);text-decoration:none">Statistics</a><a href="tools.html" style="margin-right:14px;color:var(--acc2);text-decoration:none">Tools</a><a href="examples.html" style="margin-right:14px;color:var(--acc2);text-decoration:none">Examples</a><a href="about.html" style="color:var(--acc2);text-decoration:none">About</a></nav>
<div class="bar">
<span><span class="lbl">View</span><span class="seg" id="modes"></span></span>
<span id="srcwrap"><span class="lbl">Download from</span><span class="seg" id="srcs"></span></span>
<input type="search" id="q" placeholder="Search map, code, creator">
<label class="lbl"><input type="checkbox" id="onlyfiles"> only with files</label>
<span class="lbl" id="count"></span>
<span class="legend" id="legend"></span>
</div></header>
<main id="main"><div id="out"></div>
<footer id="foot"></footer></main>
<dialog id="dlg"></dialog>
<script>
const D=__DATA__;
const $=s=>document.querySelector(s);
const esc=s=>String(s==null?"":s).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
const LS={get(k,d){try{return localStorage.getItem(k)||d}catch(e){return d}},set(k,v){try{localStorage.setItem(k,v)}catch(e){}}};
const MODES=[["basic","Basic"],["advanced","Advanced"],["timeline","Timeline"],["detailed","Detailed"]];
const LK=D.looks||{};
const lkb=f=>f.lk&&LK[f.lk]?'<span class="lk '+f.lk+'" title="'+esc(LK[f.lk][0])+'">'+esc(LK[f.lk][1])+'</span>':"";
function cps(f){return f.cp&&f.cp.length?f.cp.map((c,i)=>chip(c,"copy "+(i+1))).join(""):""}
const cpline=f=>f.cp&&f.cp.length?(f.cp.length==1?"another photo of this draft":f.cp.length+" more photos of this draft")+": "+cps(f):"";
const QL=D.quality||{};const hasQ=D.maps.some(m=>m.q);if(hasQ)MODES.push(["wanted","Wanted"]);
let mode=LS.get("rm_mode","basic"),src=LS.get("rm_src",""),colname=Object.fromEntries(D.cols);
if(!MODES.some(m=>m[0]==mode))mode="basic";
if(!D.sources.some(s=>s.id==src))src=D.sources.length?D.sources[0].id:"";
const mb=p=>p.split("/").map(encodeURIComponent).join("/");
function url(f){
  const order=[src].concat(D.sources.map(s=>s.id).filter(i=>i!=src));
  for(const id of order){const s=D.sources.find(x=>x.id==id);if(!s)continue;
    if(id=="drive"){if(f.d)return"https://drive.usercontent.google.com/download?id="+f.d+"&export=download&confirm=t"}
    else if(s.base)return s.base.replace(/\/?$/,"/")+mb(f.p)}
  return"";
}
function mb_(n){return n>=1048576?(n/1048576).toFixed(1)+" MB":Math.max(1,Math.round(n/1024))+" KB"}
function chip(f,txt){const u=url(f);const name=f.p.split("/").pop();
  const t=esc(txt||f.l||colname[f.c]);const qc=f.q?" q-"+f.q:"";
  const tip=esc(name+" ("+mb_(f.s)+")"+(f.b&&f.b.length?" - by "+f.b.join(" + "):"")+(f.h&&f.h.length?" - helped by "+f.h.join(" + "):"")+(f.dt?" - "+f.dt:"")+(f.tl?" - "+f.tl:"")+(f.lk&&LK[f.lk]?" - "+LK[f.lk][0]:"")+(f.ch?" - "+f.ch:"")+(f.q?" - "+(QL[f.q]||f.q):"")+(f.n?" - "+f.n:""));
  return u?'<a class="chip'+qc+'" href="'+esc(u)+'" target="_blank" rel="noopener" title="'+tip+'">'+t+'</a>':'<span class="chip none'+qc+'" title="'+tip+'">'+t+'</span>'}
const of=(m,c)=>m.f.filter(f=>f.c==c);
function newest(m){const o=of(m,"orig");return o.length?o[o.length-1]:null}
function thumb(m){return m.t?'<img class="th" loading="lazy" src="thumbs/'+esc(m.id)+'.jpg" alt="">':m.cm?'<div class="ph cm">COMPLETELY<br>MISSING</div>':m.nf?'<div class="ph nf">NO FILE<br>YET</div>':'<div class="ph">'+esc(m.c||"map")+'</div>'}
const UTIP="Unofficial code - made up by the collector for a map that has no official Railway Rivals code. It is dropped when the map gets a real code.";
const alts=m=>(m.c2||[]).map(x=>'<span class="vl" style="white-space:normal"><b>'+esc(x[0])+'</b>'+(x[1]?" ("+esc(x[1])+")":"")+'</span>').join("");
const codeCell=m=>'<td class="cd">'+(codeOf(m)?esc(m.c):(m.u?'<i class="uc" title="'+esc(UTIP)+'">~'+esc(m.u)+'</i>':esc(m.c&&m.c!="-"?m.c:"")))+alts(m)+'</td>';
function codeOf(m){return !!(m.c&&/[A-Za-z0-9]/.test(m.c.replace(/\?/g,"")))}
function nameCell(m,max){return'<td class="nm"><b>'+(m.q?'<span class="dot q-'+m.q+'" title="'+esc(QL[m.q]||m.q)+'"></span>':"")+esc(m.n)+'</b>'+(m.cm?'<span class="cmb" title="The map itself is missing - no picture of it exists in the collection">COMPLETELY MISSING</span>':"")+(m.nf?'<span class="cmb nfb" title="I have no file of this map yet - if you have one, please get in touch">NO FILE YET</span>':"")+(m.hl&&m.hl.length?'<a class="cmb hlb" href="#" title="A question about this map - can you help?" onclick="show(\''+esc(m.id)+'\');return false">HELP ME</a>':"")+(max?infoLine(m,max):"")+'</td>'}
function infoLine(m,max){const p=[];
  for(const f of D.fields){if(f.v>max)continue;const v=m.i[f.k];if(v)p.push("<span>"+esc(f.t)+" <b>"+esc(v)+"</b></span>")}
  return p.length?'<div class="info">'+p.join("")+'</div>':""}
const ib=m=>'<button class="btn" title="Information and all files" onclick="show(\''+esc(m.id)+'\')">i</button> <button class="btn" title="Add or correct information" onclick="suggest(\''+esc(m.id)+'\')">\u270e</button>';
function listchips(m,c,label){const l=of(m,c);if(!l.length)return"";
  return l.map((f,i)=>chip(f,label+(l.length>1?" "+(f.l||(i+1)):""))).join("")}
function rowBasic(m,det){const n=newest(m),is=of(m,"issu"),i=is.length?is[is.length-1]:null;
  let h='<tr data-id="'+esc(m.id)+'"><td>'+thumb(m)+'</td>'+codeCell(m)+nameCell(m,det?0:1)+'<td>';
  h+=n?chip(n,"Original"+(n.l?" "+n.l:"")):'<span class="none">no original</span>';
  if(i)h+=chip(i,"Issu’s");
  const j=of(m,"json");if(j.length)h+=chip(j[j.length-1],"Json");
  h+=listchips(m,"places","Places")+listchips(m,"invalid","Invalid races");   /* the text files (shown as text in the browser) */
  h+='</td>';
  if(det)h+='<td>'+infoLine(m,3)+'</td>';
  return h+'<td>'+ib(m)+'</td></tr>'}
function vchip(f){/* a version: its chip, then a line with the date and a line with the designer codes (+ helpers) */
  let h='<div class="ver">'+chip(f);
  if(f.dt)h+='<span class="vl">'+esc(f.dt)+'</span>';
  if(f.lk&&LK[f.lk])h+='<span class="vl">'+lkb(f)+'</span>';
  if(f.bc&&f.bc.length)h+='<span class="vl" title="'+esc(f.b.join(" + "))+'">'+esc(f.bc.join(" + "))+'</span>';
  if(f.hc&&f.hc.length)h+='<span class="vl" title="'+esc(f.h.join(" + "))+'">helped: '+esc(f.hc.join(" + "))+'</span>';
  if(f.ch)h+='<span class="vl">'+esc(f.ch)+'</span>';
  if(f.cp&&f.cp.length)h+='<span class="vl">'+cpline(f)+'</span>';
  return h+'</div>'}
/* the TIMELINE view (Lars 2026-11-16): the first version on the left, later drafts to the right; then who made each version and what was
   done to it; far right who designed the FIRST map and its code(s).  Extra photos of one draft hang under it and are not new versions. */
function tlver(f){let h='<div class="ver">'+chip(f);
  if(f.dt)h+='<span class="vl">'+esc(f.dt)+'</span>';
  if(f.lk&&LK[f.lk])h+='<span class="vl">'+lkb(f)+'</span>';
  if(f.cp&&f.cp.length)h+='<span class="vl">+ '+cpline(f)+'</span>';
  return h+'</div>'}
function tlmade(f){const p=[];
  if(f.bc&&f.bc.length)p.push('<span title="'+esc(f.b.join(" + "))+'">'+esc(f.bc.join(" + "))+'</span>');
  if(f.hc&&f.hc.length)p.push('<span title="'+esc(f.h.join(" + "))+'">helped: '+esc(f.hc.join(" + "))+'</span>');
  if(f.tl)p.push(esc(f.tl));
  if(f.ch)p.push('<b>'+esc(f.ch)+'</b>');
  return '<div class="ver mk">'+(p.length?p.join(" – "):"&nbsp;")+'</div>'}
function tlcodes(m){let h=codeOf(m)?esc(m.c):(m.u?'<i class="uc" title="'+esc(UTIP)+'">~'+esc(m.u)+'</i>':esc(m.c&&m.c!="-"?m.c:""));
  return h+alts(m)}
function rowTime(m,k){const t=(m.tx||[]).map(i=>m.f[i]);
  let h='<tr data-id="'+esc(m.id)+'"><td>'+thumb(m)+'</td>'+nameCell(m,0).replace(/<\/td>$/,'<span class="qn" title="The earliest date known for this map - the list is ordered by it">'+(m.te?"earliest known: "+esc(m.te):"no date known")+'</span></td>');
  for(let pass=0;pass<2;pass++)for(let i=0;i<k;i++){const grp=i<k-1?(t[i]?[t[i]]:[]):t.slice(i);
    h+='<td'+(i==0?' class="sep"':'')+'>'+grp.map(pass?tlmade:tlver).join("")+'</td>'}
  return h+'<td class="sep nm">'+esc(m.fb||"")+'</td><td class="cd">'+tlcodes(m)+'</td><td>'+ib(m)+'</td></tr>'}
function rowAdv(m,k){const o=of(m,"orig");let h='<tr data-id="'+esc(m.id)+'"><td>'+thumb(m)+'</td>'+codeCell(m)+nameCell(m,1);
  for(let i=0;i<k;i++){let cell="";
    if(i<k-1)cell=o[i]?vchip(o[i]):"";else cell=o.slice(i).map(f=>vchip(f)).join("");
    h+='<td>'+cell+'</td>'}
  for(const c of["version","issu","json","places","invalid"])h+='<td>'+of(m,c).map(f=>vchip(f)).join("")+'</td>';
  return h+'<td>'+infoLine(m,2)+'</td><td>'+ib(m)+'</td></tr>'}
function rowWanted(m){const fl=m.f.filter(f=>f.q||f.n);
  let h='<tr data-id="'+esc(m.id)+'"><td>'+thumb(m)+'</td>'+codeCell(m)+nameCell(m,0)+'<td>'+esc(QL[m.q]||"")+'</td><td>';
  if(m.qn)h+='<span class="qn">'+esc(m.qn)+'</span>';
  h+=fl.map(f=>'<div>'+chip(f,(f.l?f.l+" \u2013 ":"")+colname[f.c])+(f.n?'<span class="qn" style="display:inline"> '+esc(f.n)+'</span>':"")+'</div>').join("");
  if(m.cm)h+='<span class="qn"><b>Completely missing</b> - the map itself is missing (no picture of it exists)</span>';
  else if(m.nf)h+='<span class="qn"><b>No file yet</b> - I have no picture of this map in the collection. If you have one, please get in touch!</span>';
  return h+'</td><td>'+ib(m)+'</td></tr>'}
function render(){
  const q=$("#q").value.trim().toLowerCase(),only=$("#onlyfiles").checked;
  let list=D.maps.filter(m=>(!only||m.f.length)&&(!q||(m.n+" "+m.c+" "+(m.u||"")+" "+(m.c2||[]).map(x=>x[0]+" "+x[1]).join(" ")+" "+(m.i.by||"")+" "+m.f.map(f=>f.b.join(" ")).join(" ")).toLowerCase().includes(q)));
  $("#count").textContent=list.length+" of "+D.maps.length+" maps";
  let h="<table>",pre="";
  if(mode=="timeline"){list=list.filter(m=>(m.tx||[]).length);
    /* OLDEST FIRST: by the earliest date known for the map (the first version often has no date); maps with no date last, by name */
    list.sort((a,b)=>(a.ts?0:1)-(b.ts?0:1)||(a.ts<b.ts?-1:a.ts>b.ts?1:0)||a.n.localeCompare(b.n));
    $("#count").textContent=list.length+" maps with a timeline";
    const k=Math.max(1,Math.min(8,Math.max(0,...list.map(m=>(m.tx||[]).length))));
    pre='<p class="tlnote"><b>Timeline.</b> The oldest maps come first (by the earliest date known for each map; maps with no known date come last). The first version of each map is on the left and the later drafts follow to the right. Then comes who made each version and what was done to it (revised, coloured, cosmetic change, digitalized ...). Far right: who designed the <b>first</b> map and its code(s) – a map may have changed its code or have two. Black &amp; white, hand-coloured (coloured in afterwards) and colour print are marked on each version. Extra photos or scans of the very same draft are shown under it and are <b>not</b> counted as new versions.</p>';
    const lab=i=>i==0?"First":i==k-1&&k>1?"Newest"+(k==8?" +":""):"Draft "+(i+1);
    h+='<thead><tr class="tlh"><th></th><th>Map</th><th class="grp" colspan="'+k+'">Versions – first on the left</th><th class="grp" colspan="'+k+'">Made by – and what was done</th><th class="grp">First designed by</th><th class="grp">Code(s)</th><th></th></tr><tr class="tlh2"><th></th><th></th>';
    for(let pass=0;pass<2;pass++)for(let i=0;i<k;i++)h+='<th'+(i==0?' class="grp"':'')+'>'+lab(i)+'</th>';
    h+='<th></th><th></th><th></th></tr></thead>'+list.map(m=>rowTime(m,k)).join("");
  }else if(mode=="wanted"){list=list.filter(m=>m.q);
    $("#count").textContent=list.length+" maps looking for improvement";
    h+="<tr><th></th><th>Code</th><th>Map</th><th>Status</th><th>What is wrong</th><th></th></tr>"+list.map(rowWanted).join("");
  }else if(mode=="advanced"){
    const k=Math.max(1,Math.min(8,Math.max(0,...list.map(m=>of(m,"orig").length))));
    h+="<tr><th></th><th>Code</th><th>Map</th>";
    for(let i=1;i<=k;i++)h+="<th>"+(i==1?"Oldest":i==k&&k>1?"Newest"+(k==8?" +":""):"Version "+i)+"</th>";
    h+="<th>Versions</th><th>Issu’s</th><th>Json</th><th>Places</th><th>Invalid races</th><th></th></tr>";
    h+=list.map(m=>rowAdv(m,k)).join("");
  }else{
    const det=mode=="detailed";
    h+="<tr><th></th><th>Code</th><th>Map</th><th>Files</th>"+(det?"<th>Information</th>":"")+"<th></th></tr>";
    h+=list.map(m=>rowBasic(m,det)).join("");
  }
  /* keep my place: remember the first map visible under the column heads, put it back at the same spot after the redraw */
  const mn=$("#main"),mt=mn.getBoundingClientRect().top;let thB=mt;
  document.querySelectorAll("#out th").forEach(t=>{thB=Math.max(thB,t.getBoundingClientRect().bottom)});const thH=thB-mt;
  let anc=null;
  for(const tr of document.querySelectorAll("#out tr[data-id]")){const r=tr.getBoundingClientRect();
    if(r.bottom>mt+thH+1){anc={id:tr.dataset.id,off:r.top-mt};break}}
  $("#out").innerHTML=pre+h+"</table>"+(list.length?"":'<p class="none">No maps match.</p>');
  if(anc){const tr=document.querySelector('#out tr[data-id="'+anc.id+'"]');
    if(tr)mn.scrollTop+=tr.getBoundingClientRect().top-mt-anc.off}
}
function show(id){const m=D.maps.find(x=>x.id==id);if(!m)return;
  const rows=D.fields.filter(f=>m.i[f.k]).map(f=>[f.t,m.i[f.k]]);
  if(codeOf(m))rows.push(["Code",m.c]);
  else if(m.u)rows.push(["Code","~"+m.u+"  (UNOFFICIAL - not an official Railway Rivals code)"]);
  else if(m.c&&m.c!="-")rows.push(["Code",m.c]);
  if(m.c2&&m.c2.length)rows.push(["Other code(s)",m.c2.map(x=>x[0]+(x[1]?" ("+x[1]+")":"")).join(", ")]);
  if(m.q)rows.push(["Quality",(QL[m.q]||m.q)+(m.qn?" \u2013 "+m.qn:"")]);
  let h='<h2>'+esc(m.n)+'</h2><dl>'+rows.map(r=>'<dt>'+esc(r[0])+'</dt><dd>'+esc(r[1])+'</dd>').join("")+'</dl>';
  if(m.nf)h+='<p class="info"><b>No file of this map yet.</b> I have the map in my list but no picture of it in the collection. If you have it, please get in touch - see below.</p>';
  if(m.cm)h+='<p class="info"><b>The map itself is missing</b> - no picture of it exists in the collection. If you have one, please get in touch!</p>';
  if(m.hl&&m.hl.length){h+='<div class="grp">Can you help?</div>'+m.hl.map((x,k)=>'<div class="hq"><b>'+esc(x.w)+':</b> '+esc(x.q)+
    ' <a class="chip" href="#" onclick="answer(\''+esc(m.id)+'\','+k+');return false">Answer this</a></div>').join("")}
  for(const [c,name] of D.cols){const fl=of(m,c);if(!fl.length)continue;
    h+='<div class="grp">'+esc(name)+'<a class="sg" href="#" title="Add or correct information here" onclick="suggest(\''+esc(m.id)+'\',\''+c+'\');return false">\u270e</a></div>';
    h+=fl.map(f=>'<div>'+chip(f,(f.l?f.l+" \u2013 ":"")+f.p.split("/").pop())+'<span class="info">'+(f.b.length?"by "+esc(f.b.join(" + "))+" ":"")+(f.h&&f.h.length?"helped by "+esc(f.h.join(" + "))+" ":"")+(f.tl?"["+esc(f.tl)+"] ":"")+(f.lk&&LK[f.lk]?esc(LK[f.lk][0])+" ":"")+(f.ch?"<b>"+esc(f.ch)+"</b> ":"")+esc(f.dt)+(f.cf?"":" (unconfirmed)")+(f.q?" \u2013 "+esc(QL[f.q]||f.q):"")+(f.n?" \u2013 "+esc(f.n):"")+(f.cr?" (courtesy of "+esc(f.cr)+")":"")+'<a class="sg" href="#" title="Correct this file" onclick="suggest(\''+esc(m.id)+'\',\''+c+'\','+m.f.indexOf(f)+');return false">\u270e</a></span>'+(f.cp&&f.cp.length?'<div class="info" style="margin-left:18px">'+cpline(f)+' (not counted as a new version)</div>':"")+'</div>').join("")}
  h+='<p class="info">Designer credits are best-effort (a map credited to David Watts may be by David and Ann Watts) \u2013 see <a href="about.html">About</a>.</p>'+sendline();
  h+='<p style="text-align:right"><button class="seg" style="padding:6px 14px" onclick="suggest(\''+esc(m.id)+'\')">\u270e Add or correct information</button> <button class="seg" style="padding:6px 14px" onclick="$(\'#dlg\').close()">Close</button></p>';
  $("#dlg").innerHTML=h;$("#dlg").showModal()}
/* a map file or draft to share goes in my Google Drive folder, in a folder with the visitor's own name (Lars 2026-11-11) */
function sendline(){return D.incoming?'<p class="info">Do you have a map file or a draft to share? Put it in <a href="'+esc(D.incoming)+'" target="_blank" rel="noopener">this Google Drive folder</a>. Please make a folder with your own name first, so I know whose files they are.</p>':""}
function suggest(id,c,fi){const m=D.maps.find(x=>x.id==id);if(!m)return;
  const f=(fi==null)?null:m.f[fi];
  const parts=["Whole map","A missing file or draft"].concat(D.cols.filter(x=>of(m,x[0]).length).map(x=>x[1]));
  const cur=c?colname[c]:"Whole map";
  const T=part=>"RAILMAPS INFO v1\nMap: "+m.n+"\nPart: "+part+"\nNew or correction: \nDraft: "+(f&&f.l?f.l:"")+"\nDate: \nDesigners: \nProgram used: \nYear: \nSteps: \nCities: \nOther information: \nMy name: \n";
  const h='<h2>Add or correct information \u2013 '+esc(m.n)+'</h2>'+
    '<p class="info">Fill in only what you know and leave the other lines as they are. Anything that does not fit a line goes after <b>Other information:</b>. Then copy the text and send it to me by e-mail.</p>'+sendline()+
    '<p><span class="lbl">Part</span><select id="sgp">'+parts.map(p=>'<option'+(p==cur?" selected":"")+'>'+esc(p)+'</option>').join("")+'</select></p>'+
    '<textarea id="sgt" rows="15" style="width:100%;font:13px/1.4 monospace;background:var(--bg);color:var(--fg);border:1px solid var(--line);border-radius:8px;padding:8px"></textarea>'+
    '<p id="sgm" class="info"></p><p style="text-align:right"><button class="seg" style="padding:6px 14px" id="sgc">Copy text</button> '+
    (D.contact?'<a class="chip" id="sge" href="#">Open in my e-mail program</a> ':"")+
    '<button class="seg" style="padding:6px 14px" onclick="$(\'#dlg\').close()">Close</button></p>';
  if($("#dlg").open)$("#dlg").close();
  $("#dlg").innerHTML=h;const ta=$("#sgt");ta.value=T(cur);
  $("#sgp").onchange=()=>{ta.value=ta.value.replace(/^Part:.*$/m,"Part: "+$("#sgp").value)};
  $("#sgc").onclick=()=>{ta.select();let ok=false;try{ok=document.execCommand("copy")}catch(e){}
    if(!ok&&navigator.clipboard)navigator.clipboard.writeText(ta.value);$("#sgm").textContent="Copied \u2013 now paste it into an e-mail."};
  if(D.contact)$("#sge").onclick=()=>{$("#sge").href="mailto:"+D.contact+"?subject="+encodeURIComponent("Railway Rivals maps: "+m.n)+"&body="+encodeURIComponent(ta.value)};
  $("#dlg").showModal()}
function answer(id,k){const m=D.maps.find(x=>x.id==id);if(!m||!m.hl||!m.hl[k])return;const x=m.hl[k];
  suggest(id,null,x.i>=0?x.i:null);const ta=$("#sgt");
  ta.value=ta.value.replace("Other information: ","Other information: ANSWER to the question \""+x.q+"\": ");
  if(x.i>=0){const f=m.f[x.i];const pp=$("#sgp");if(pp&&colname[f.c]){pp.value=colname[f.c];ta.value=ta.value.replace(/^Part:.*$/m,"Part: "+colname[f.c])}}}
function seg(el,items,cur,fn){el.innerHTML=items.map(i=>'<button data-k="'+esc(i[0])+'" class="'+(i[0]==cur?"on":"")+'">'+esc(i[1])+'</button>').join("");
  el.onclick=e=>{const k=e.target.dataset&&e.target.dataset.k;if(k){fn(k);seg(el,items,k,fn)}}}
seg($("#modes"),MODES,mode,k=>{mode=k;LS.set("rm_mode",k);render()});
if(D.sources.length>1)seg($("#srcs"),D.sources.map(s=>[s.id,s.label]),src,k=>{src=k;LS.set("rm_src",k);render()});
else $("#srcwrap").style.display="none";
$("#q").oninput=render;$("#onlyfiles").onchange=render;
$("#dlg").addEventListener("click",e=>{if(e.target===$("#dlg"))$("#dlg").close()});
$("#foot").innerHTML="Railway Rivals was created by David Gwyn Watts and belonged to his company Rostherne Games, later sold to Theo Clarke. "+
  "Designer credits are best-effort: a map credited to David Watts may be by David and Ann Watts. "+
  "<a href=\"about.html\">About and credits</a>. Collection and page by Lars “Issu” Olsson. Updated "+esc(D.built)+".";
$("#legend").innerHTML=hasQ?'<span class="dot q-minor"></span>could be better<span class="dot q-photo"></span>map fine, picture poor<span class="dot q-poor"></span>poor quality / missing'+(D.qown||[]).map(o=>'<span class="dot q-'+o[0]+'"></span>'+esc(o[1])).join(""):"";
render();
/* maps.html#<map id>  (the links on the Help me page): scroll to that map, mark it and open its information */
(function(){let id="";try{id=decodeURIComponent(location.hash.slice(1))}catch(e){}
  if(!id||!D.maps.some(m=>m.id==id))return;
  $("#q").value="";$("#onlyfiles").checked=false;render();
  const tr=[].slice.call(document.querySelectorAll("#out tr[data-id]")).find(r=>r.dataset.id==id);
  if(tr){tr.classList.add("hit");tr.scrollIntoView({block:"center"})}
  show(id)})();
</script></body></html>
'''


# *************** DEL 30 - SMALL DIALOGS *****************
# ToDo: all dialogs are modal (make_modal) and close with Escape.

QUALITY_COLOURS = {"minor": "#fff0b3", "photo": "#cfe3f5", "poor": "#f4c2bc", "missing": "#f4c2bc"}
QUALITY_COLOURS_BUILTIN = dict(QUALITY_COLOURS)
# Lars (2026-11-09): a file I am FINISHED with is green; a map is green when all its files are done, orange when only some are.
# ToDo: row colour priority in the lists = done (green) > quality colour > partly done (orange); the Done column always tells the count.
DONE_COLOURS = {"done": "#b6e8b6", "partly": "#ffd9a8"}
GREEN_BTN, GREEN_BTN_DARK = "#8fdc8f", "#2e9e44"
THEME = dict(bg="#1e1e2e", panel="#2a2a3c", fg="#e0e0e0", dim="#9090a8", accent="#89b4fa", btn="#3a3a4e", btnfg="#e0e0e0",
             field="#252535", field_fg="#e0e0e0")
HELP_TEXT = """RAIL MAPS - a library of Railway Rivals maps

WHAT IT DOES
Keeps one list of maps (the Excel sheet is the SOURCE) and links every map file in your folders to its map and to a COLUMN:
Original (the drafts), Version (the same map redrawn by someone else in another way/program), Issu's (my own coloured versions), Json
- and Places, PDF, Comments, Invalid races, Extra, which the program sets itself from the file type.  In Assign only the first four are offered.
Then it builds ONE web page (maps.html) with four views:
  Basic     - the newest original of each map (+ my version / json if they exist), a small picture, an (i) button.
  Advanced  - every version in its own column (oldest ... newest), then Issu's, Json, Places, and information.
  Timeline  - first version left, later drafts to the right, who made each + what was done, then the first designer and the code(s).
  Detailed  - like Basic, with all the information written on the line.
The (i) button opens everything about the map and all its files, with creator and date per version.

FIRST TIME
 1. Import Excel: maps, codes, creators (rows 313-340 of the sheet), steps, S.R., cities ... are read.  When the program starts
    with an empty list it offers this itself.
 2. Sources & folders: check the library folders and their roles, paste the Drive folder link, the upload folder.
    The two bottom fields are YOUR OWN options: "Program used" = names separated by commas (Xxx, Xxy, Zzz) that the Pick... button
    offers; quality = your own marks, each one behaving like a built-in one (Blurry scan=photo, Wrong colours=minor, Bad=poor; no
    "=" means minor = yellow, photo = blue, poor = red).  They appear in every quality menu and on the page (chip colour + legend).
 3. Scan folders: finds the files and puts them on the most likely map.  What it cannot place is on the Unassigned tab.
 4. Go through the files: "?" in the OK column = only a SUGGESTION from the name.  Details... sets column, draft, date and the
    creators of THAT version (the base map's creator is on the map; a later draft can have other creators).  Confirm = I have
    checked it.  Open shows the picture / PDF with the programs chosen in DefaultHub (SeeView, PDFull ...).
 5. Make upload folder -> Google Drive.  Fetch Drive links -> the page can download from Drive.  Build page -> the Site folder.

MISSING DRAFTS
When a map has the originals 1b, 1c and 1f, drafts 1d and 1e are PROBABLY missing - the program shows them as a hint ("Gaps" column,
a line under the map, and in the Assign dialog, where "Missing drafts..." fills the draft box).  It is only a guess: someone may have
kept 1d private until 1f.  "Missing drafts..." on a map lets me say, per draft: Probably missing (default), Never released (the
hint goes away) or Looking for it (the map turns yellow and is listed under Wanted).  The program only looks BETWEEN the lowest and
the highest draft I have, and a hint disappears by itself when the draft is added.

SPECIAL RUNS
"Special runs..." (under the map) opens the special runs of the map.  The sheet's columns O1-O7 (odd races) and E1-E6 (even races)
are read into two lists; usually 6 per list (12 in all), or "Odd and even races use the same list".  There is one destination per
LINE, so add or remove lines whenever the map has another number (7 on South Sweden, 1 on others).  "This map never has special runs"
and "Drafts WITHOUT special runs" (like 1a, 1b) are there too, and so is how often they are used (S.R., like 2/7, from the sheet).
What I type here is never overwritten by Import Excel.  The page shows it in the information (Info fields... > Special runs).

ADDING FILES
"Add files..." (Files tab of a map) COPIES the chosen files into the import folder (Sources & folders > "Add files... copies them
to", for example a folder called 2---Original-2027 next to the originals) and the map uses the copy, so nothing depends on the folder the
file came from.  The original is never moved or touched.  A file that already lies in the import folder or a library folder is not
copied; the same name with other content gets (2), (3) in its name.  Empty setting = the old way (the file is used where it lies).

RENAMING A FILE
"Rename..." (on a file of the map) makes a COPY of the file with the new name in a folder called renamed, next to the folder the file
lies in.  The original is never touched.  The program remembers the old name, so a later scan does not count the original again - the
map, draft, date and the rest simply follow the renamed copy (and the page / upload folder use the new name).

INCOMING INFORMATION
On the page every map has a pencil button (and the (i) box has one per column and per file).  It opens a text form - map name filled
in, then New or correction / Draft / Date / Designers / Program used / Year / Steps / Cities / Other information / My name - to copy and
e-mail to me (set my address in Sources & folders if the page should have an e-mail button).  "Incoming info..." reads such text:
paste it, Check shows what would change, Apply does it.  A new value replaces the old one, the old one is KEPT as Older information, the
giver is credited ("courtesy of NAME"), and the field is protected from Import Excel.  A draft that has no file is kept as a reported
draft; everything else goes under Added information.  A form with no map (or one I cancel) waits in the inbox.  Info fields...
decides where Added information and Older information are shown.

DATES
Every version has its OWN date, as exact as I know it: 1985, 1985-06 (June 1985) or 1985-06-12.  The page shows "1985",
"June 1985" or "12 June 1985".  The map's Year field takes the same forms.  A date in the file name (like 10_march_2020) is
read automatically; the file's own date is only a suggestion (the "File date" button) and is shown in brackets in the list,
because it says little about when the map was drawn.  Versions of the same draft are ordered by their dates.

TIMELINE, LOOK, WHAT WAS DONE, COPIES AND OTHER CODES
 - The Timeline lists the OLDEST maps first (not alphabetically): by the earliest date known for each map - the oldest date among its
   versions and the map's Year, because the first version often has no date of its own.  Maps with no date at all come last.
 - The Timeline tab (and the Timeline view on the page) shows each map as a line: the FIRST version on the left, the later drafts to the
   right, then who made each version and what was done to it, and far right who designed the first map and its code(s).  Double-click a
   map to open it on the Maps tab.  Only originals and versions (a redraw in another program) are on the timeline - my own colourings
   (Issu's) and the json files are not.
 - Look (Details...): Black & white / Hand-coloured (a map coloured in afterwards, by hand) / Printed in colour.  Old notes that just say
   "Black & white" or "Coloured" are moved into this field by themselves (once); a longer note stays as it is.  "Coloured" in an old note
   is read as hand-coloured - check the ones that were really printed in colour.
 - Own looks: Sources & folders... > "My 'Look' options" (Sepia, Pencil ...) adds options to the Look menu; the three built-in ones are
   fixed.  A look that is IN USE on a version cannot be removed or re-spelled - the program puts it back (take it off the versions first).
 - What was done (Details...): a short comment per version - revised, coloured, cosmetic change, digitalized ... (Pick... offers the usual
   words and everything you typed before).  It is shown on the timeline and in the (i) box.
 - Copies: two photos / scans of the very same draft (maybe other light or shades) are ONE version.  The extra file is a COPY of the
   main file: it is not counted as a new design (timeline, statistics, newest version, gaps), the page shows it under the main file.
   Scan / Import / "Find copies..." mark the SURE ones by themselves (same name and draft, designers / date / look agree); "Find copies..."
   also lists the unsure pairs for you to decide (B is a copy of A / A is a copy of B / Not copies) and the copies that exist (Not a copy
   after all / Make this the main file).  "Copy of..." marks the selected file(s) by hand, "Not a copy" undoes it.  A black & white map
   and the same draft coloured in afterwards have different looks, so they are NOT copies (a version of its own, comment: coloured).
   Pictures taken at other angles do not match well pixel by pixel, so names, draft, date and designers decide; the picture only helps.
 - Other codes (Maps tab, field "Other codes"): a map that has two codes, or changed its code: SG=English, SD=German or
   XY=old code until 1998.  They are shown after the code on the page and in codes.html, and they are never offered as free codes.

NOTES AND "LOOKING FOR IMPROVEMENT"
 - A map has "My notes (private)" - a text box, never on the page - and a short "Quality note (on the page)".
 - A map and every VERSION can be marked Could be better (yellow) or Poor quality (red); a map with no file at all can be marked
   Missing.  Version: Mark quality... (or Details...) and a note, e.g. "Cyberboard map, blurry".  The colour sits on the file's chip on
   the page - no extra columns - and the map's name gets a dot when its newest original is marked.
 - The page then has a fourth view, Wanted: every marked map, what is wrong and the notes.  Here and in the program "looking for
   improvement" shows only those maps.

PICTURE POOR, MAP FINE
Quality has a blue mark "Map fine, picture poor (better photo wanted)": the map itself is good but the photo / scan of it is bad, so
somebody may still have the original and could take a better picture.  It works like the other marks (version, map, Wanted view).

HELPED BY
Details... (and the map form) have a "Helped by" line next to the designers: several codes are fine (BRW,DW).  It is shown in the
(i) box, in the tooltip and as its own small line under the version in the Advanced view.

DESIGNER AND DATE UNDER EACH VERSION
In the Advanced view every version has two small lines under its chip: the date (as exact as it is known) and the designer codes.
All Issu's and Json files get the designer LO (Lars Olsson) automatically; change it in Details... and your choice sticks.

COMPARING PICTURES
Every picture opens in its OWN SeeView window (SeeView is started with --new), so two maps can lie side by side.  Select several
files and press Open to open them all (up to 6).  On the Unassigned tab "Open suggested original" opens the newest original of the
suggested map and "Compare (open both)" opens it together with the file itself.  If two maps have the same name (two Nigerias) both
originals open and the suggestion shows both, like "Nigeria (nr 172, NG, 2002)  OR  Nigeria (nr 173, ???, 2020)"; Accept suggestion
refuses those, so you choose with Assign to map...  (the Assign dialog has "Open original of selected map" and a Nr column).

TWO DIFFERENT MAPS FILED AS ONE
Select the files that are a different map in the file list and press "To new map...": they move to a new map (same name is fine,
give it a code).  Fill in year and creator on the new map afterwards.  A sheet row with its own number gets its own map by itself.

MAPS WITH THE SAME NAME
A map is identified by its NUMBER (column NR) in the sheet, not by its name, so Austria (AUS, nr 16) and Austria (OS, nr 17) are two
maps.  Files named with the number (0016.comments2, 0063.places ...) go to the map with that number; files named like
Austria_(AUS).bmp or Alberta_AB_draft_1b.places are told apart by the code.  Import Excel moves auto-placed files to the right
one of such maps; files you placed yourself are never moved.

THE EXCEL SHEET AS A SOURCE
Every Import Excel refreshes the fields the sheet supplies (steps, S.R., cities, year, rivers, comments ...) - EXCEPT a field I
have typed by hand in the program: that one is never overwritten.  New maps in the sheet are added.

DONE (finished files and maps)
"Save & Done" in the Details window (or the green "Done" button under the file list) saves, confirms and marks a file as FINISHED:
the row turns green and the Done column shows a tick.  A map is green when ALL its files are done (Done column "all"), orange
when only some are (Done column "3/11").  If a map also has a quality mark, the quality colour is shown until every file is done.
"Not done" takes the mark away.  "not done yet" above the map list hides the finished maps.  The Done mark is only for you -
it never goes to the web page.

UPLOAD PAGE
"Upload page" sends the page folder (maps.html, codes.html, stats.html, thumbs) to the server's /p/railmaps/ place - the same place and
method as AppSite's Rail Maps job.  The server is READ from AppSite's Updates settings (nothing is written here).  Map files are not
sent (they live on Google Drive).  The bottom right says whether the page is "up to date" or "OUT OF DATE" (changed since the last
Build page); if it is out of date, Upload page offers to build it first.  Press Ctrl+F5 in the browser to see the new page.

ABOUT PAGE (DISCLAIMER)
Build page also writes about.html (menu link "About" on every page, and a short credits line in the footer of every page).  It says who
made Railway Rivals (David Gwyn Watts, Rostherne Games, later sold to Theo Clarke) and that a map credited to David Watts may be by
David AND Ann Watts, that "J.W." is not identified, that credits are best-effort, and asks for corrections.  "About page text..."
opens the text in your editor (Helpfiles\\Rail_Maps\\about_page.txt, made from the built-in text the first time): "# Heading",
blank line = new paragraph, "- " = bullet, {CONTACT} = your e-mail from the settings (dropped when empty).  Save, Build page, Upload page.

STATISTICS AND THE CODE LIST
The Statistics tab shows Designers (base maps, maps in all, versions drawn, times helped, "not sure" entries, first and latest year),
Codes (CODE / MAP, nothing else) and an Overview (key numbers, maps per decade, maps with most versions + how many are done).  Click
any column heading to sort by it, click again to reverse.  Build page also writes codes.html and stats.html next to maps.html with the
same lists (every column sorts there too) and links between the three pages.  Hidden maps are left out.

NEW MAP FROM THE MOVE / ASSIGN WINDOW
"New map..." in the window where you pick the map makes a map that is not in the list yet (name, code, sheet number, year) and
selects it.  Its folder on the page is made from code + name (AUS---Austria) when the page / upload folder is built.  Import Excel
adds every sheet map that is missing, so first try that.

ORDER OF THE VERSIONS
Normally by draft number.  When EVERY original of a map has a date, the originals are ordered by date instead (different designers
number their drafts differently), so "Newest" and "Latest draft" are really the newest.

DESIGNERS I AM NOT SURE ABOUT
In a Designer / Helped by field a "?" works like a designer of its own: put one BEFORE and one AFTER the people you only suspect
("Add designer..." > "?"), e.g. BRW,?,DW,? .  When you save, the program moves the question marks tight round them: BRW,?DW?
(several suspects: ?DW,AB? - "one or both of them").  A single code can also be typed as DW? .  A lone "?" at the very end marks the
code before it.  On the page a suspect is shown as "David Gwyn Watts (?)" and, in the small lines, as DW? .

GREY STEPS IN THE SHEET
In the sheet's STEPS column a light GREY number (font colour about EEEEEE, mostly "200") means "not verified".  Import Excel skips
those (and clears an old value that came from the sheet); only steps written in another colour - black, orange, purple, green ... -
are read.  A value you typed by hand in the program is never touched.

HELP ME (questions for visitors)
For something you are unsure of - e.g. "Is this designed by DW or DP?" (the map says Copyright David Watts, drawn by DP) - type the
question in the HELP ME line of Details... (a question about THAT version), or right-click the map > "HELP ME - question for visitors"
(about the whole map).  The list shows [HELP ME] after the name.  Build page then writes help.html (the "Help me" page, linked from
every page's header): one row per question with the map name as a link that goes straight to the map and opens its information, and
an "Answer by e-mail" link (needs your e-mail in Sources & folders) that starts the answer in the page's usual form.  On maps.html
the map gets an orange HELP ME mark, and the information box has "Can you help?" with an "Answer this" button.  Empty the question
when it is answered.

COMPLETELY MISSING (right-click a map)
Right-click a map in the list > "COMPLETELY MISSING" for a map of which no picture exists.  It also works when the map has other
files - e.g. a comments file about the designer, places - they stay (Done or not); the mark is YOUR decision until you clear it.  The list shows [COMPLETELY MISSING] after the name, and the page shows the map with a red
COMPLETELY MISSING mark in every view and in the "looking for improvement" list, and Build page also writes missing.html (a sortable
"Missing maps" page: code, map, year, designers, note; linked from the header of every page).  Right-click again to clear it (when a picture turns up, clear
it yourself - nothing does it for you).  The same menu has "Quality of this map".
When a map marked COMPLETELY MISSING gets a file (Add files, Move, Assign, Scan, Import Excel) the program ASKS whether the mark should go.  "No" keeps it and it asks again only when the map gets even more files.

MAPS WITHOUT ANY FILE (Lars 2026-11-15): they are NOT hidden.  The page lists them with a "NO FILE YET" mark and the message "I have no picture of this map - if you have one, please get in touch".  Only if you really want them gone: Settings > "HIDE maps that have no files yet".

TOOLS (2026-11-15): the page also has a "Tools" page (tools.html) with the program Hex_Labels (hexagon names on a map picture) - as a Windows program that needs no Python
(Hex_Labels_Windows.zip, made from the folder Hex_Labels in Folder-exe) and as the Python source Hex_Labels.py.  Make upload folder puts both in the Tools folder of the upload
folder (the zip is only made again when the exe folder has changed - build the exe again in ExeForge first when Hex_Labels.py changed), Fetch Drive links finds their
Drive ids, Build page writes tools.html with the download links, Upload page sends it.  Hex_Labels' "Browse maps..." reads this page's map list and fetches the pictures from Drive.
The Tools page also offers the Android app PicturePerfect (PicturePerfect.apk, taken from Android\\PicturePerfect\\APK) - see PICTURE DROP below.

EXAMPLES (2026-11-17): the page has an "Examples" page (examples.html) that shows what PicturePerfect can do.  Every picture in Helpfiles\\Rail_Maps\\Examples\\ is one
example; a text file with the same name (Name.txt: first line "# Title", then paragraphs) describes it, intro.txt = the text at the top.  Build page copies the pictures to
the page folder (examples\\; the original for download, a lighter copy for the screen when a picture is large) and writes examples.html with a full-size viewer; Upload page sends
it all.  "Examples folder..." button opens the folder.  More examples later = drop the files in, Build page, Upload page.

PICTURE DROP (2026-11-15) - "Picture drop..." button: other people photograph their paper maps with the Android app PicturePerfect; with a CODE from me they can
switch on "Rail map" mode there, and every picture they keep is also sent to my incoming Drive folder (sub folder = their name).  No server needed, only Drive:
 1. "Make the script file..." writes RailMaps_PictureDrop.gs (my secret + the incoming folder inside - private).  Paste it into a new project at script.google.com, run
    check_folder() once, Deploy > Web app (Execute as: Me, Anyone), and paste the Web app address in the dialog ("Save + test").
 2. Type a name, "Make code": the code (ISSUSYNC1:...) is copied - send it to that person with the app.  "Switch off" takes a person's code back at once.
 3. "Fetch new pictures" downloads what has arrived into the import folder as <Person>-Map_date_time.jpg and lists it on the Unassigned tab - I give each one its map.
    (A name ending -Bad_light = the person's phone saw bad light.)

NUMBERED FILES (Unassigned tab)
Comment / places files that are only a number (0016.comments2, 0063.places) belong to the map with that NUMBER.  "Place numbered
files (Excel)" reads the sheet (column NR = G gives the number, column MAP = B the name) and puts every such file on its map.  If the
map is not in the program yet (a twin like Austria AUS / OS, Hungary, Middle Earth) it is made from the sheet row; a map of the same
name without a number just gets the number.  Numbers that are not in the sheet stay on the Unassigned tab and are listed in the Log.
The number list (your own numbering) is SAVED in the catalog every time the sheet is read, so numbered files are also placed by
Scan folders / Try to place again without the sheet, and the button works when the sheet is not there.
The tab also has a Find box, and the Suggested map is the 2nd column, the name read from the file the 3rd.

HELPERS
"Helpers..." (after Creators...) lists everybody who can be named in a Helped by field: ALL creators (left, read only - they are
changed under Creators...) and the people who ONLY helped (right, one per line: CODE = Full name).  The two lists are linked: a code or
a name can only be in one of them.  If you type a helper who is a creator the line is left out; if you make a helper a creator under
Creators..., the helper entry disappears (its code is kept for the creator).  People only entered under Helpers never show under
Creators or among the designers in the statistics; the Statistics tab has a Helpers list with everybody.

INFO FIELDS (Basic / Advanced / Detailed / Hidden)
"Info fields..." decides which information is shown where on the page.  Basic = in every view, Advanced = in Advanced and Detailed,
Detailed = only in Detailed, Hidden = nowhere.  The (i) box shows everything that is not Hidden.

ASSIGN TO MAP
The list is the sheet's: Map, Code, By, Year, Draft ... ordered by how well the name matches the file (percent).  "Open the file"
lets me look at the picture first.  Under the list is "This version": column, draft label, date, the designer(s) of THIS version,
the program used (Cyberboard, Hand-drawn ...), quality and a note - so a redraw of the same map by someone else, made in another
program, goes in as its own draft with its own designer.  The map itself keeps the year (e.g. 1985) and the creator of the base
map; a line under the list shows what is already on the selected map.  Details... on a file shows the same fields.  "Accept suggestion" on the Unassigned tab takes the best match at once.  "Assign to map + go there..." assigns the same way and then jumps to the Maps tab with that map and the assigned files selected.

SOURCES (Download from)
Google Drive first, then Webdock.  A source with no address is not offered.  If a file is missing on the chosen
source the page falls back to the next one.  "Only CONFIRMED files" (Sources & folders) keeps unchecked files off the page.

FILE NAMES
Each map has a folder <code>---<name>; the file names are kept.  Nothing in your library is ever moved, renamed or deleted.

CODES: MAPS WITHOUT ONE, FREE CODES, UNOFFICIAL CODES
"no code" above the map list shows only the maps that have NO code (the sheet has nothing, '-' or '???').  "Codes..." opens three tabs:
 - Maps without a code: the list, with the unofficial code each one has.  "Suggest for ALL..." proposes a code for every map without
   one, "Suggest for the selected map..." only for the map(s) you selected - one at a time.  A code is made from the map name (North
   Korea -> NK, Afghanistan -> AF ...), is NOT official and NOT used by another map; in the proposal window you choose which rows
   to keep, press "Next suggestion" for another code for the selected row, or "Change selected..." to type one.  "Type a code..." sets one by hand, "Remove unofficial code" takes it away.
 - Free codes: every code of 1, 2 or 3 letters between From and To (default AA to XX, where the unused ones usually are) with its
   status: free / OFFICIAL / unofficial.  Show = free, taken or all.
 - Unofficial codes that gave way: the history (see below).
An unofficial code is always written with a "~" (~AB), in the program, on the page (dotted underline + tooltip, and "UNOFFICIAL" in the (i)
box) and in a separate table of codes.html.  It is kept in its own field and NEVER changes the sheet's Code, the file names or the map
folders.  It GIVES WAY by itself: when the map gets an official code (Import Excel, or typed), or when ANOTHER map gets exactly that code,
the unofficial code is removed, written to the history and a message tells you which one had to go and why.
Under the map's form a line says whether the map has an official, an unofficial or no code; "Unofficial code..." there makes one for
just that map.

CHECK LO (.bmp only)
LO (Lars Olsson) only draws .bmp files, so a jpg / png / gif / pdf can never be LO's.  "Check LO..." lists such files that sit in the
Issu's column or have LO as designer; "Fix" moves them out of the Issu's column (to Original or Version, your choice; pdf to PDF) and
removes LO from their designers.  Scan folders now puts every non-bmp picture of my own folders in Original, never in Issu's, and a
Scan warns in the Log when something is wrong.

NO JPG
"no jpg" above the map list shows only the maps that have no .jpg / .jpeg file (hidden and ignored files do not count).  Together with
"with files only" it lists the maps that still need a jpg made.

REMOVE FROM PROGRAM
"Remove from map" sends a file to the Unassigned tab.  "Remove from program" (under the file buttons) takes it off the map AND hides it
there too - for files that do not belong in the program at all.  "Ignored files..." (Unassigned tab) lists everything hidden - those
files, the ones you pressed Ignore on and the .comments2 files - and "Put back" brings them back.  Nothing on disk is touched.

TEXT FILES (.comments, .comments2, .invalid_races, .places)
 - .comments: the text of the map's .comments file fills the map's "Note (from .comments)" field - the word NOTE: is left out and the
   lines are joined with " | ".  The sheet's own text stays in "Exceptions / comments" (two separate fields; both have a level under
   Info fields..., the Note's name on the page is "Note").  It happens by itself at start, and after Scan folders / Import Excel.  A Note
   I typed is never touched.  The file itself is not put on the page (its text is).  More than one .comments file on a map: the newest.
 - .comments2: hidden (see Ignored files...) - its information is written in Details by hand.
 - .invalid_races and .places: a map can have several of each.  They go to the upload folder and the page with ".txt" added to the
   name (Afghanistan.places.txt) so a browser SHOWS them; the page has "Places" and "Invalid races" chips on every map (Basic/Detailed)
   and columns in the Advanced view.  (The old copies without .txt stay on Drive: the program never deletes - remove them there.)

GOOGLE DRIVE FOR DESKTOP
Make upload folder starts Google Drive for desktop by itself when the upload folder is not there (the drive letter only exists while
Drive runs) and waits up to 3 minutes for it to appear.  If it still does not, the Log says so and nothing is copied.

Escape closes this window."""


def ask_text(root, title, prompt, initial=""):
    top = tk.Toplevel(root)
    top.title(title)
    top.resizable(False, False)
    top.transient(root)
    out = {"v": None}
    tk.Label(top, text=prompt, justify="left").pack(padx=12, pady=(12, 4), anchor="w")
    e = new_entry(top, width=48)
    e.insert(0, initial)
    e.pack(padx=12)

    def ok(_e=None):
        out["v"] = e.get()
        top.destroy()
    e.bind("<Return>", ok)
    bf = tk.Frame(top)
    bf.pack(pady=10)
    tk.Button(bf, text="OK", width=9, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=9, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)
    e.focus_set()
    root.wait_window(top)
    return out["v"]


def new_map_dialog(root, cat, name="", code=""):
    """Creates a map by hand (name, code, sheet number, year) and returns it, or None.  The map's folder on the page/upload folder is
    made from code + name (AUS---Austria) the next time the page / upload folder is built, so a map with the right code gets
    its own folder.  Lars 2026-11-09: 'Move to map' needed a Create for a map that is not in the list (AUS Austria)."""
    top = tk.Toplevel(root)
    top.title("New map")
    top.resizable(False, False)
    top.transient(root)
    out = {"m": None}
    ents = {}
    for r, (key, lab, val, w) in enumerate((("name", "Map name", name, 40), ("code", "Code (like AUS, OS)", code, 10),
                                            ("nr", "Number in the sheet (if any)", "", 10), ("year", "Year (1985 / 1985-06)", "", 12))):
        tk.Label(top, text=lab, anchor="w", width=26).grid(row=r, column=0, sticky="w", padx=(12, 4), pady=3)
        e = new_entry(top, width=w)
        e.insert(0, val)
        e.grid(row=r, column=1, sticky="w", padx=(0, 12), pady=3)
        ents[key] = e

    def ok(_e=None):
        nm, cd, nr, yr = (ents[k].get().strip() for k in ("name", "code", "nr", "year"))
        if not nm:
            messagebox.showwarning("Rail Maps", "The map needs a name.", parent=top)
            return
        if nr and not nr.isdigit():
            messagebox.showwarning("Rail Maps", "The sheet number must be digits only (or empty).", parent=top)
            return
        if yr and parse_date(yr) is None:
            messagebox.showwarning("Rail Maps", "The year must be like 1985 or 1985-06.", parent=top)
            return
        twin = next((m for m in cat["maps"] if (nr and str(m.get("nr", "")) == nr) or
                     (cd and m.get("code", "").upper() == cd.upper() and norm_key(m["name"]) == norm_key(nm))), None)
        if twin and not messagebox.askyesno("Rail Maps", "'%s' (code %s, nr %s) is already in the list.\n\nCreate another one anyway?" % (
                twin["name"], twin.get("code", ""), twin.get("nr", "")), parent=top):
            return
        out["m"] = new_map(cat, nm, code=cd.upper(), nr=nr, year=parse_date(yr) or "")
        top.destroy()
    for e in ents.values():
        e.bind("<Return>", ok)
    bf = tk.Frame(top)
    bf.grid(row=4, column=0, columnspan=2, pady=10)
    tk.Button(bf, text="Create", width=9, bg=GREEN_BTN, activebackground=GREEN_BTN, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=9, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)
    ents["name"].focus_set()
    root.wait_window(top)
    return out["m"]


def natural_key(text):
    """'AUS 10' sorts after 'AUS 9': digits compare as numbers (even positions are always text, odd ones numbers)."""
    return [int(t) if i % 2 else t.lower() for i, t in enumerate(re.split(r"(\d+)", str(text)))]


class SortableTree(object):
    """A Treeview whose every column heading sorts the rows on a click (again = reverse); blank cells always go last.
    set(headers, rows, numeric=columns that sort as numbers, widths=...) fills it."""

    def __init__(self, parent):
        self.frame = tk.Frame(parent)
        self.tv = ttk.Treeview(self.frame, show="headings", selectmode="browse")
        sb = tk.Scrollbar(self.frame, command=self.tv.yview)
        self.tv.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.tv.pack(side="left", fill="both", expand=True)
        self.rows, self.numeric, self.col, self.rev = [], (), None, False

    def set(self, headers, rows, numeric=(), widths=None):
        self.tv["columns"] = [str(i) for i in range(len(headers))]
        for i, h in enumerate(headers):
            self.tv.heading(str(i), text=h, command=lambda i=i: self.sort_by(i))
            self.tv.column(str(i), width=(widths[i] if widths else 110), anchor="e" if i in numeric else "w", stretch=(i == 1 or len(headers) == 2))
        self.rows, self.numeric, self.col, self.rev = [list(r) for r in rows], tuple(numeric), None, False
        self.show()

    def sort_by(self, i):
        self.rev = (not self.rev) if self.col == i else False
        self.col = i
        self.show()

    def show(self):
        rows = self.rows
        if self.col is not None:
            i = self.col
            full = [r for r in rows if str(r[i]).strip() != ""]
            blank = [r for r in rows if str(r[i]).strip() == ""]
            full.sort(key=(lambda r: float(r[i])) if i in self.numeric else (lambda r: natural_key(r[i])), reverse=self.rev)
            rows = full + blank
        self.tv.delete(*self.tv.get_children())
        for r in rows:
            self.tv.insert("", "end", values=r)


def known_tools(cat):
    """The Pick... list: my list from Sources & folders (starts as Cyberboard, Hand-drawn, Map creator) + every program already used."""
    used = {f.get("tool", "").strip() for f in cat["files"] if f.get("tool", "").strip()}
    return sorted(set(EXTRA_TOOLS) | used, key=str.lower)


class VersionForm(object):
    """The fields of ONE version (= one file) of a map, used by 'Assign to map' AND 'Details':
    column, draft, date, creators of THIS version, program used (Cyberboard ...), quality, note, confirmed.
    apply(files) writes only what was CHANGED against the first file, so several files can be edited at once."""

    def __init__(self, parent, cat, f0, confirmed_default=None):
        self.cat, self.f0 = cat, f0
        self.ents = {}
        self.gaps = []                      # the drafts that are probably missing on the chosen map (see draft_gaps)
        r = 0
        self.col_var = tk.StringVar(value=COL_NAME.get(f0["col"], f0["col"]))
        tk.Label(parent, text="Type (Version = same map redrawn)", anchor="w", width=24).grid(row=r, column=0, sticky="w", padx=4, pady=1)
        # Lars: only these four are a real choice (same map redrawn in another program = Version); Places/PDF/Comments are automatic
        choices = [COL_NAME[k] for k in ("orig", "version", "issu", "json")]
        if self.col_var.get() not in choices:
            choices.append(self.col_var.get())            # a file already in another column keeps it
        tk.OptionMenu(parent, self.col_var, *choices).grid(row=r, column=1, sticky="w")
        for key, lab in (("draft", "Draft (1c, 1,3 ... the program goes in Program)"), ("date", "Date: 1985 / 1985-06 / 1985-06-12"),
                         ("by", "Designer(s) of this version (codes)"), ("helped", "Helped by (codes, several ok)"),
                         ("tool", "Program used"), ("change", "What was done (revised, coloured ...)")):
            r += 1
            tk.Label(parent, text=lab, anchor="w", width=24).grid(row=r, column=0, sticky="w", padx=4, pady=1)
            e = new_entry(parent, width=34)
            e.insert(0, f0.get(key, ""))
            e.grid(row=r, column=1, sticky="w", pady=1)
            self.ents[key] = e
            if key == "by":
                tk.Button(parent, text="Add designer...", command=lambda: self.add_person("by")).grid(row=r, column=2, padx=4)
            if key == "helped":
                tk.Button(parent, text="Add helper...", command=lambda: self.add_person("helped")).grid(row=r, column=2, padx=4)
            if key == "draft":
                tk.Button(parent, text="Missing drafts...", command=self.pick_gap).grid(row=r, column=2, padx=4)
            if key == "tool":
                tk.Button(parent, text="Pick...", command=self.pick_tool).grid(row=r, column=2, padx=4)
            if key == "change":
                tk.Button(parent, text="Pick...", command=self.pick_change).grid(row=r, column=2, padx=4)
            if key == "date":
                fd = f0.get("fdate") or ""
                tk.Button(parent, text="File date" + ((" " + fd) if fd else ""), command=lambda: (
                    self.ents["date"].delete(0, "end"), self.ents["date"].insert(0, fd))).grid(row=r, column=2, padx=4)
        r += 1
        # Lars 2026-11-16: Black & white / coloured in afterwards (by hand) / printed in colour
        tk.Label(parent, text="Look (colour)", anchor="w", width=24).grid(row=r, column=0, sticky="w", padx=4, pady=1)
        self.looks = list(LOOKS)
        if f0.get("look") and f0["look"] not in LOOK_LABEL:          # a look that is not in the list any more is kept, never wiped by Save
            self.looks.append((f0["look"], "(%s)" % f0["look"]))
        self.look = tk.StringVar(value=dict(self.looks).get(f0.get("look", ""), LOOKS[0][1]))
        tk.OptionMenu(parent, self.look, *[v for _k, v in self.looks]).grid(row=r, column=1, sticky="w")
        r += 1
        tk.Label(parent, text="Quality of this version", anchor="w", width=24).grid(row=r, column=0, sticky="w", padx=4, pady=1)
        self.qual = tk.StringVar(value=QUALITY_LABEL.get(f0.get("quality", ""), "Fine"))
        tk.OptionMenu(parent, self.qual, *[v for k, v in QUALITY if k != "missing"]).grid(row=r, column=1, sticky="w")
        r += 1
        tk.Label(parent, text="Note (shown on the page)", anchor="w", width=24).grid(row=r, column=0, sticky="w", padx=4, pady=1)
        self.note = new_entry(parent, width=34)
        self.note.insert(0, f0.get("note", ""))
        self.note.grid(row=r, column=1, columnspan=2, sticky="we", pady=1)
        r += 1
        # Lars 2026-11-09 (AUS Austria: "copyright David Watts, drawn by DP" - designed by DW or DP?): a question for the visitors.  It goes
        # to the page "Help me" (help.html), where people can go straight to the map and answer.
        tk.Label(parent, text="HELP ME - question for visitors", anchor="w", width=24, fg="#a33").grid(row=r, column=0, sticky="w", padx=4, pady=1)
        self.help = new_entry(parent, width=34)
        self.help.insert(0, f0.get("help", ""))
        self.help.grid(row=r, column=1, columnspan=2, sticky="we", pady=1)
        r += 1
        self.conf =tk.BooleanVar(value=bool(f0.get("confirmed")) if confirmed_default is None else confirmed_default)
        tk.Checkbutton(parent, text="Confirmed (I have checked map, draft, date, designers)", variable=self.conf).grid(
            row=r, column=0, columnspan=3, sticky="w", padx=4, pady=(4, 0))
        r += 1
        self.done0 = bool(f0.get("done"))
        self.done_forced = False
        self.done = tk.BooleanVar(value=self.done0)
        tk.Checkbutton(parent, text="Done (I am completely finished with this file - it turns green in the lists)",
                       variable=self.done).grid(row=r, column=0, columnspan=3, sticky="w", padx=4)

    def mark_done(self):
        """What 'Save & Done' does before applying: finished = confirmed AND done."""
        self.conf.set(True)
        self.done.set(True)
        self.done_forced = True

    def add_person(self, key="by"):
        ent = self.ents[key]
        menu = tk.Menu(ent, tearoff=0)
        # "?" = not sure.  Add one before and one after the suspect(s) (BRW,?,DW,?) - Save moves them tight round them (BRW,?DW?)
        menu.add_command(label="?   (not sure - put one before and one after the suspect designers)", command=lambda: ent.insert(
            "end", ("," if ent.get().strip() else "") + "?"))
        menu.add_separator()
        # designers: creators only; helpers: every creator AND the helpers-only people
        pool = all_people(self.cat) if key == "helped" else self.cat["people"]
        for code, name in sorted(pool.items(), key=lambda kv: kv[1]):
            menu.add_command(label="%s - %s" % (code, name), command=lambda c=code: ent.insert(
                "end", ("," if ent.get().strip() else "") + c))
        menu.tk_popup(ent.winfo_rootx(), ent.winfo_rooty() + 24)

    def set_gaps(self, labels):
        self.gaps = list(labels)

    def pick_gap(self):
        menu = tk.Menu(self.ents["draft"], tearoff=0)
        if not self.gaps:
            menu.add_command(label="(no drafts look missing on this map)", state="disabled")
        for lab in self.gaps:
            menu.add_command(label="Probably this one: " + lab, command=lambda l=lab: (
                self.ents["draft"].delete(0, "end"), self.ents["draft"].insert(0, l)))
        menu.tk_popup(self.ents["draft"].winfo_rootx(), self.ents["draft"].winfo_rooty() + 24)

    def pick_tool(self):
        menu = tk.Menu(self.ents["tool"], tearoff=0)
        for name in known_tools(self.cat):
            menu.add_command(label=name, command=lambda n=name: (self.ents["tool"].delete(0, "end"), self.ents["tool"].insert(0, n)))
        menu.tk_popup(self.ents["tool"].winfo_rootx(), self.ents["tool"].winfo_rooty() + 24)

    def pick_change(self):
        menu = tk.Menu(self.ents["change"], tearoff=0)
        for name in known_changes(self.cat):
            menu.add_command(label=name, command=lambda n=name: (self.ents["change"].delete(0, "end"), self.ents["change"].insert(0, n)))
        menu.tk_popup(self.ents["change"].winfo_rootx(), self.ents["change"].winfo_rooty() + 24)

    def problem(self):
        """A text when something typed is wrong (so the dialog stays open), else ''."""
        if parse_date(self.ents["date"].get()) is None:
            return "The date must be like 1985, 1985-06 or 1985-06-12 (year, then month, then day - as exact as you know)."
        return ""

    def apply(self, files):
        f0 = self.f0
        col_key = next((k for k, v in COLS if v == self.col_var.get()), f0["col"])
        q_key = next((k for k, v in QUALITY if v == self.qual.get()), "")
        look_key = next((k for k, v in self.looks if v == self.look.get()), "")
        for f in files:
            if col_key != f0["col"]:
                f["col"] = col_key
            for k, e in self.ents.items():
                v = (parse_date(e.get()) if k == "date" else norm_designers(e.get(), all_people(self.cat)) if k in ("by", "helped") else e.get().strip()) or ""
                if v != f0.get(k, ""):
                    f[k] = v
                    if k == "by":
                        f["by_edited"] = True            # typed (or cleared) by hand: default_designers leaves it alone
            if q_key != f0.get("quality", ""):
                f["quality"] = q_key
            if look_key != f0.get("look", ""):
                f["look"] = look_key
                f["look_edited"] = True                 # chosen by hand: migrate_looks leaves it alone (also when set back to 'Not known')
            if self.note.get().strip() != f0.get("note", ""):
                f["note"] = self.note.get().strip()
            if self.help.get().strip() != f0.get("help", ""):
                if self.help.get().strip():
                    f["help"] = self.help.get().strip()
                else:
                    f.pop("help", None)
            f["confirmed"] = bool(self.conf.get())
            if self.done_forced or bool(self.done.get()) != self.done0:      # several files: only touch `done` when I changed it
                f["done"] = bool(self.done.get())
            f["manual"] = True


def pick_map(root, cat, title="Choose a map", rec=None, files=None):
    """Pick a map from the sheet's list (Map, Code, By, Year, Draft ...), ordered by how well the name matches the file.
    With a file (rec) the same dialog also takes the details of THIS VERSION - draft, date, designers, program, quality, note -
    and applies them to `files` (default: rec) when OK is pressed, so one step says 'this is the Cyberboard redraw of Hessen,
    drawn by X in 1989'.  Returns the chosen map or None."""
    if not cat["maps"]:
        messagebox.showinfo("Rail Maps", "There are no maps yet.  Press 'Import Excel' first (the list comes from the sheet).", parent=root)
        return None
    top = tk.Toplevel(root)
    top.title(title)
    top.transient(root)
    out = {"m": None}
    if rec is not None:
        tk.Label(top, text="File:  %s     (looks like: %s  [%s])" % (os.path.basename(rec["path"]), rec.get("guess_key", ""),
                                                                    rec.get("guess_code", "")), anchor="w").pack(fill="x", padx=10, pady=(10, 0))
    qf = tk.Frame(top)
    qf.pack(fill="x", padx=10, pady=(8, 4))
    tk.Label(qf, text="Find").pack(side="left")
    q = new_entry(qf, width=34)
    q.pack(side="left", padx=6)
    # Code box (Lars 2026-11-11): matches the START of the map codes only; several codes with space/comma; Enter = OK on the first one.
    tk.Label(qf, text="Code").pack(side="left", padx=(6, 0))
    qc = new_entry(qf, width=8)
    qc.pack(side="left", padx=6)
    cols = ("match", "name", "nr", "code", "by", "year", "draft", "have")
    tv = ttk.Treeview(top, columns=cols, show="headings", selectmode="browse", height=11 if rec is not None else 18)

    def open_original():
        sel = tv.selection()
        o = newest_original_of(cat, sel[0]) if sel else None
        if o:
            open_map_file(o["path"])
        else:
            messagebox.showinfo("Rail Maps", "The selected map has no picture to open yet.", parent=top)
    def create_map():
        pre = ""
        if rec is not None:
            pre = (rec.get("guess_key") or "").title()
        m = new_map_dialog(top, cat, name=q.get().strip() or pre, code=(rec.get("guess_code", "") if rec is not None else "").upper())
        if m:
            q.delete(0, "end")
            qc.delete(0, "end")
            q.insert(0, m["name"])
            fill()
            if tv.exists(m["id"]):
                tv.selection_set(m["id"])
                tv.see(m["id"])
    tk.Button(qf, text="New map...", command=create_map).pack(side="right", padx=(6, 0))
    if rec is not None:
        tk.Button(qf, text="Open the file", command=lambda: open_map_file(rec["path"])).pack(side="right")
        tk.Button(qf, text="Open original of selected map", command=open_original).pack(side="right", padx=6)
    for c, w, t_ in (("match", 56, "Match"), ("name", 250, "Map"), ("nr", 40, "Nr"), ("code", 56, "Code"), ("by", 70, "By"),
                     ("year", 50, "Year"), ("draft", 70, "Draft"), ("have", 50, "Have")):
        tv.heading(c, text=t_)
        tv.column(c, width=w, anchor="w" if c == "name" else "center")
    tv.pack(padx=10, fill="both", expand=True)
    on_map = tk.StringVar(value="")
    tk.Label(top, textvariable=on_map, anchor="w", justify="left", wraplength=640).pack(fill="x", padx=10, pady=(4, 0))
    form = None
    if rec is not None:
        box = tk.LabelFrame(top, text="This version")
        box.pack(fill="x", padx=10, pady=(6, 0))
        form = VersionForm(box, cat, rec, confirmed_default=True)
    scores = {}
    if rec is not None:
        for m, s in suggest_maps(cat, rec.get("guess_key", ""), rec.get("guess_code", ""), n=len(cat["maps"])):
            scores[m["id"]] = s

    def show_existing(_e=None):
        sel = tv.selection()
        if not sel:
            on_map.set("")
            return
        m = map_by_id(cat)[sel[0]]
        have = sort_versions([f for f in cat["files"] if f.get("map") == m["id"] and not f.get("gone")])
        bits = ["%s %s%s%s" % (COL_NAME.get(f["col"], f["col"]), f.get("draft") or "-",
                               (" by " + f["by"]) if f.get("by") else "", (" [%s]" % f["tool"]) if f.get("tool") else "") for f in have[:8]]
        gaps = [g["label"] for g in draft_gaps(cat, m) if g["state"] != "never"]
        if form is not None:
            form.set_gaps(gaps)
        on_map.set("Map year %s, base creator %s.   Already on this map: %s%s%s" % (
            m.get("year") or "?", " + ".join(names_of(cat, m.get("by", ""))) or "?", "; ".join(bits) or "nothing yet",
            " ..." if len(have) > 8 else "", ("   Probably missing: " + ", ".join(gaps)) if gaps else ""))

    def fill(_e=None):
        t_ = norm_key(q.get())
        codes_ = [c.upper() for c in re.split(r"[\s,;]+", qc.get().strip()) if c]
        tv.delete(*tv.get_children())
        if scores:
            maps = sorted(cat["maps"], key=lambda x: (-scores.get(x["id"], 0), norm_key(x["name"])))
        else:
            maps = sorted(cat["maps"], key=lambda x: norm_key(x["name"]))
        first = None
        for m in maps:
            if t_ and t_ not in norm_key("%s %s %s" % (m["name"], m.get("code", ""), " ".join(names_of(cat, m.get("by", ""))))):
                continue
            if codes_ and not any((m.get("code") or "").upper().startswith(c) for c in codes_):
                continue
            pct = ("%d%%" % round(scores[m["id"]] * 100)) if scores else ""
            tv.insert("", "end", iid=m["id"], values=(pct, m["name"], m.get("nr", ""), m.get("code", ""), m.get("by", ""), m.get("year", ""),
                                                      m.get("draft_note", ""), m.get("have", "")))
            first = first or m["id"]
        if first:
            tv.selection_set(first)
            tv.see(first)
        show_existing()

    def ok(_e=None, done=False):
        sel = tv.selection()
        if sel:
            if form is not None and form.problem():
                messagebox.showwarning("Rail Maps", form.problem(), parent=top)
                return
            out["m"] = map_by_id(cat)[sel[0]]
            if form is not None:
                if done:
                    form.mark_done()
                form.apply(files or [rec])
            top.destroy()
    q.bind("<KeyRelease>", fill)
    q.bind("<Return>", ok)
    qc.bind("<KeyRelease>", fill)
    qc.bind("<Return>", ok)
    tv.bind("<<TreeviewSelect>>", show_existing)
    tv.bind("<Double-Button-1>", ok)
    bf = tk.Frame(top)
    bf.pack(pady=8)
    tk.Button(bf, text="OK", width=9, bg=GREEN_BTN, activebackground=GREEN_BTN, command=ok).pack(side="left", padx=4)
    if rec is not None:
        tk.Button(bf, text="OK & Done", width=12, bg=GREEN_BTN_DARK, fg="white", activebackground=GREEN_BTN_DARK,
                  activeforeground="white", font=("Segoe UI", 9, "bold"), command=lambda: ok(done=True)).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=9, command=top.destroy).pack(side="left", padx=4)
    fill()
    # Lars: Assign must NOT lock the main window (he has to open the picture from the main list while it is open) - so no grab here
    top.bind("<Escape>", lambda _e: top.destroy())
    top.lift()
    top.focus_force()
    q.focus_set()
    root.wait_window(top)
    return out["m"]


def file_details_dialog(root, cat, files, anchor=None):
    """Details of the selected version(s) of a map.  Only what I change is applied.
    NOT modal (Lars 2026-11-08): the main window stays clickable and the picture can be opened from here; the dialog sits
    just above the `anchor` button (the Details button, far right since 2026-11-09), right edges aligned, because the map
    picture is on the left of the screen."""
    old = getattr(root, "_details_top", None)
    try:
        if old is not None and old.winfo_exists():            # already open: bring that one forward instead of opening a second
            old.deiconify()
            old.lift()
            old.focus_force()
            return False
    except tk.TclError:
        pass
    top = tk.Toplevel(root)
    root._details_top = top
    top.title("Version details")
    # Lars (2026-11-09): NO top.transient(root) here.  On Windows a transient window is OWNED by the main window and clicking an owned
    # window brings its owner to the front too - which hid the map picture he had open next to it.  Independent window = clicking
    # Details never raises Rail Maps (it still is its own taskbar entry and is shown on top when it opens).
    top.resizable(False, False)
    f0 = files[0]
    tk.Label(top, text="%d file(s):  %s%s" % (len(files), os.path.basename(f0["path"]), "  ..." if len(files) > 1 else ""),
             anchor="w").pack(fill="x", padx=10, pady=(10, 4))
    box = tk.Frame(top)
    box.pack(padx=6)
    form = VersionForm(box, cat, f0)
    mm = map_by_id(cat).get(f0.get("map"))
    if mm:
        form.set_gaps([g["label"] for g in draft_gaps(cat, mm) if g["state"] != "never"])
    out = {"ok": False}

    def ok(done=False):
        if form.problem():
            messagebox.showwarning("Rail Maps", form.problem(), parent=top)
            return
        if done:
            form.mark_done()          # Save & Done = saved + confirmed + finished (green in the lists)
        form.apply(files)             # BEFORE destroy: the entry widgets are gone afterwards (TclError "invalid command name", 2026-11-08)
        out["ok"] = True
        top.destroy()
    bf = tk.Frame(top)
    bf.pack(fill="x", padx=10, pady=10)
    # Lars (2026-11-09): "Open the file" sat next to Save and was clicked by mistake -> it is now alone on the far right,
    # Save is green and Save & Done (saves + confirms + marks the file finished) is dark green.
    tk.Button(bf, text="Save", width=10, bg=GREEN_BTN, activebackground=GREEN_BTN, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Save & Done", width=13, bg=GREEN_BTN_DARK, fg="white", activebackground=GREEN_BTN_DARK,
              activeforeground="white", font=("Segoe UI", 9, "bold"), command=lambda: ok(True)).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    tk.Button(bf, text="Open the file", width=12, command=lambda: [open_map_file(f["path"]) for f in files[:6]]).pack(side="right", padx=4)
    top.update_idletasks()
    try:
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        # Lars (2026-11-09): Details sits at the far right now -> the dialog opens just above it with its RIGHT edge on the button's
        # right edge, so the map picture on the left stays uncovered.  Lars (same day): it opened OUTSIDE his screen - the old code
        # clamped to the PRIMARY monitor's size, wrong when the program lives on another monitor.  Now everything is clamped to the
        # MAIN WINDOW's own rectangle (always on the monitor he is using); no usable button position = centred on the main window.
        rx, ry, rw, rh = root.winfo_rootx(), root.winfo_rooty(), root.winfo_width(), root.winfo_height()
        if rw < w + 20 or rh < h + 20:                              # main window tiny / not laid out yet: use its corner as is
            rw, rh = max(rw, w + 20), max(rh, h + 20)
        if anchor is not None and anchor.winfo_ismapped() and anchor.winfo_width() > 1:
            x = anchor.winfo_rootx() + anchor.winfo_width() - w
            y = anchor.winfo_rooty() - h - 48                       # 48 = gap + the window's title bar: never covers the button
        else:
            x, y = rx + (rw - w) // 2, ry + (rh - h) // 2
        x = max(rx, min(x, rx + rw - w - 10))
        y = max(ry, min(y, ry + rh - h - 10))
        top.geometry("+%d+%d" % (x, y))
    except Exception:
        pass
    # focus_force + Escape like every dialog, but NO grab_set: the main program must stay usable while this is open
    top.focus_force()
    top.bind("<Escape>", lambda e: top.destroy())
    root.wait_window(top)
    return out["ok"]


def gaps_dialog(root, cat, m, on_saved):
    """The drafts that look missing on this map: say for each one if it is probably missing, never released, or wanted."""
    gaps = draft_gaps(cat, m)
    if not gaps:
        messagebox.showinfo("Rail Maps", "No draft looks missing on '%s'.\n(It only looks between the lowest and highest draft I "
                            "have - like 1b, 1c, 1f -> 1d, 1e.)" % m["name"], parent=root)
        return
    top = tk.Toplevel(root)
    top.title("Missing drafts - " + m["name"])
    top.transient(root)
    top.resizable(False, False)
    tk.Label(top, text="These drafts are skipped between the ones I have.  It is only a guess - someone may have kept a draft "
                       "private until a later one.", justify="left", wraplength=480).grid(row=0, column=0, columnspan=2, padx=10,
                                                                                      pady=(10, 6), sticky="w")
    vars_ = {}
    for r, g in enumerate(gaps, start=1):
        tk.Label(top, text="Draft " + g["label"], anchor="w", width=14).grid(row=r, column=0, padx=10, sticky="w")
        v = tk.StringVar(value=dict(GAP_STATES)[g["state"]])
        tk.OptionMenu(top, v, *[lab for _k, lab in GAP_STATES]).grid(row=r, column=1, sticky="w", pady=1)
        vars_[g["label"]] = v

    def ok():
        ack = {}
        for lab, v in vars_.items():
            key = next(k for k, name in GAP_STATES if name == v.get())
            if key != "probable":
                ack[lab] = key
        m["gap_ack"] = {k: v for k, v in (m.get("gap_ack") or {}).items() if k not in vars_}
        m["gap_ack"].update(ack)
        on_saved()
        top.destroy()
    bf = tk.Frame(top)
    bf.grid(row=len(gaps) + 1, column=0, columnspan=2, pady=10)
    tk.Button(bf, text="Save", width=10, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)


def sruns_dialog(root, m, on_saved):
    """Special runs of one map.  Odd and even races each have a list (usually 6, so 12 in all); one destination per line, so any
    number of lines works.  'Same list for odd and even' hides the second list."""
    s = sruns_of(m)
    top = tk.Toplevel(root)
    top.title("Special runs - " + m["name"])
    top.transient(root)
    never = tk.BooleanVar(value=s["never"])
    same = tk.BooleanVar(value=s["same"])
    tk.Checkbutton(top, text="This map never has special runs", variable=never).grid(row=0, column=0, columnspan=2, sticky="w", padx=10, pady=(10, 0))
    tk.Checkbutton(top, text="Odd and even races use the same list", variable=same).grid(row=1, column=0, columnspan=2, sticky="w", padx=10)
    tk.Label(top, text="One destination per line - add or remove lines as the map needs (usually 6 per list).",
             anchor="w").grid(row=2, column=0, columnspan=2, sticky="w", padx=10, pady=(6, 0))
    lab_o = tk.Label(top, text="Odd races", anchor="w")
    lab_e = tk.Label(top, text="Even races", anchor="w")
    lab_o.grid(row=3, column=0, sticky="w", padx=10)
    lab_e.grid(row=3, column=1, sticky="w", padx=10)
    t_o = new_text(top, width=34, height=10, wrap="none")
    t_e = new_text(top, width=34, height=10, wrap="none")
    t_o.grid(row=4, column=0, padx=10, sticky="we")
    t_e.grid(row=4, column=1, padx=10, sticky="we")
    t_o.insert("1.0", "\n".join(s["odd"]))
    t_e.insert("1.0", "\n".join(s["even"]))
    cnt = tk.StringVar()
    tk.Label(top, textvariable=cnt, anchor="w").grid(row=5, column=0, columnspan=2, sticky="w", padx=10)
    tk.Label(top, text="Drafts WITHOUT special runs (like 1a, 1b)", anchor="w").grid(row=6, column=0, sticky="w", padx=10, pady=(6, 0))
    e_skip = new_entry(top, width=30)
    e_skip.grid(row=6, column=1, sticky="w", padx=10, pady=(6, 0))
    e_skip.insert(0, s["skip"])
    tk.Label(top, text="How often (S.R., like 2/7)", anchor="w").grid(row=7, column=0, sticky="w", padx=10, pady=(4, 0))
    e_sr = new_entry(top, width=12)
    e_sr.grid(row=7, column=1, sticky="w", padx=10, pady=(4, 0))
    e_sr.insert(0, m.get("sr", ""))

    def lines(t):
        return [x.strip() for x in t.get("1.0", "end").splitlines() if x.strip()]

    def update(*_a):
        st = "disabled" if never.get() else "normal"
        t_o.configure(state=st)
        t_e.configure(state="disabled" if (never.get() or same.get()) else "normal")
        if same.get():
            lab_o.configure(text="Every race")
        else:
            lab_o.configure(text="Odd races")
        lab_e.configure(text="" if same.get() else "Even races")
        cnt.set("Odd: %d   Even: %d" % (len(lines(t_o)), len(lines(t_e)) if not same.get() else len(lines(t_o))))
    never.trace_add("write", update)
    same.trace_add("write", update)
    t_o.bind("<KeyRelease>", update)
    t_e.bind("<KeyRelease>", update)
    update()

    def ok():
        m["sruns"] = {"never": never.get(), "same": same.get(), "odd": lines(t_o) if not never.get() or lines(t_o) else [],
                      "even": [] if same.get() else lines(t_e), "skip": e_skip.get().strip()}
        if "sruns" not in m.setdefault("edited", []):
            m["edited"].append("sruns")                   # typed by hand: the Excel import will never overwrite it
        sr = e_sr.get().strip()
        if sr != m.get("sr", ""):
            m["sr"] = sr
            if "sr" not in m["edited"]:
                m["edited"].append("sr")
        on_saved()
        top.destroy()
    bf = tk.Frame(top)
    bf.grid(row=8, column=0, columnspan=2, pady=10)
    tk.Button(bf, text="Save", width=10, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)


def inbox_dialog(root, cat, on_saved):
    """Reads the forms people e-mailed (pasted here), shows what would change, and applies it: new values replace the old ones, the old
    ones are kept as 'older information', the giver is credited ('courtesy of').  A form with no map can be kept in the inbox.
    Not modal on purpose (the map picker opens from here)."""
    top = tk.Toplevel(root)
    top.title("Incoming information")
    top.transient(root)
    top.bind("<Escape>", lambda _e: top.destroy())
    tk.Label(top, text="Paste the e-mail text here (it may hold several forms), then press Check.", anchor="w").pack(fill="x", padx=10, pady=(10, 2))
    paste = new_text(top, width=96, height=11, wrap="word")
    paste.pack(padx=10)
    tk.Label(top, text="What will happen", anchor="w").pack(fill="x", padx=10, pady=(8, 2))
    plan = new_text(top, width=96, height=11, wrap="word")
    plan.pack(padx=10)
    state = {"items": []}

    def show_plan(text):
        plan.configure(state="normal")
        plan.delete("1.0", "end")
        plan.insert("1.0", text)
        plan.configure(state="disabled")

    def check():
        subs = parse_submissions(paste.get("1.0", "end"))
        state["items"] = []
        if not subs:
            show_plan("Nothing found - the text needs lines like  Map: ...  /  Draft: ...  /  Other information: ...")
            return
        out = []
        for n, sub in enumerate(subs, start=1):
            m = find_map_for_submission(cat, sub.get("map", ""))
            if m is None:
                m = pick_map(root, cat, "Which map is form %d about? (written: '%s')  Cancel = no map, keep it in the inbox" % (n, sub.get("map", "")))
            state["items"].append((sub, m))
            if m is None:
                out.append("Form %d (%s): NO MAP - will be kept in the inbox below.\n" % (n, sub.get("map", "") or "no map name"))
                continue
            lines = plan_submission(cat, m, sub)
            out.append("Form %d  -  %s%s\n    %s\n" % (n, m["name"], ("   from " + sub["name"]) if sub.get("name") else "",
                                                       "\n    ".join(lines) or "(nothing to change)"))
        show_plan("\n".join(out))

    def apply():
        if not state["items"]:
            check()
            if not state["items"]:
                return
        today = time.strftime("%Y-%m-%d")
        for sub, m in state["items"]:
            if m is None:
                cat.setdefault("inbox", []).append({"on": today, "map": sub.get("map", ""), "raw": sub_text(sub)})
            else:
                apply_submission(cat, m, sub, today)
        state["items"] = []
        paste.delete("1.0", "end")
        show_plan("Done.")
        refill()
        on_saved()

    def keep():
        subs = parse_submissions(paste.get("1.0", "end"))
        for sub in subs:
            cat.setdefault("inbox", []).append({"on": time.strftime("%Y-%m-%d"), "map": sub.get("map", ""), "raw": sub_text(sub)})
        if subs:
            paste.delete("1.0", "end")
            refill()
            on_saved()
    bf = tk.Frame(top)
    bf.pack(pady=6)
    tk.Button(bf, text="Check", width=12, command=check).pack(side="left", padx=4)
    tk.Button(bf, text="Apply", width=12, command=apply).pack(side="left", padx=4)
    tk.Button(bf, text="Keep in inbox", width=14, command=keep).pack(side="left", padx=4)
    tk.Button(bf, text="Close", width=10, command=top.destroy).pack(side="left", padx=4)
    tk.Label(top, text="Inbox (forms kept for later)", anchor="w").pack(fill="x", padx=10)
    lb = tk.Listbox(top, width=110, height=4, exportselection=False)
    lb.pack(padx=10)

    def refill():
        lb.delete(0, "end")
        for it in cat.get("inbox", []):
            lb.insert("end", "%s   %s   %s" % (it["on"], it.get("map") or "(no map)", it["raw"].replace("\n", " | ")[:70]))

    def load():
        sel = lb.curselection()
        if sel:
            it = cat["inbox"].pop(sel[0])
            paste.insert("end", it["raw"] + "\n")
            refill()
            on_saved()

    def drop():
        sel = lb.curselection()
        if sel and messagebox.askyesno("Rail Maps", "Remove this form from the inbox?", parent=top):
            cat["inbox"].pop(sel[0])
            refill()
            on_saved()
    bf2 = tk.Frame(top)
    bf2.pack(pady=(2, 10))
    tk.Button(bf2, text="Load into the box", command=load).pack(side="left", padx=4)
    tk.Button(bf2, text="Remove", command=drop).pack(side="left", padx=4)
    refill()
    top.lift()
    paste.focus_set()


def levels_dialog(root, settings, on_saved):
    """Which information is Basic / Advanced / Detailed / Hidden on the page."""
    top = tk.Toplevel(root)
    top.title("Info fields")
    top.transient(root)
    top.resizable(False, False)
    tk.Label(top, text="Basic = in every view     Advanced = in Advanced + Detailed     Detailed = only in Detailed     "
                       "Hidden = nowhere\n(the (i) box of a map shows everything that is not Hidden)", justify="left").grid(
        row=0, column=0, columnspan=2, padx=10, pady=(10, 6), sticky="w")
    vars_ = {}
    for r, (k, label) in enumerate(INFO_FIELDS, start=1):
        tk.Label(top, text=label, anchor="w", width=22).grid(row=r, column=0, sticky="w", padx=10)
        v = tk.StringVar(value=level_of(settings, k).capitalize())
        tk.OptionMenu(top, v, *[x.capitalize() for x in LEVELS]).grid(row=r, column=1, sticky="w", pady=1)
        vars_[k] = v

    def ok():
        settings["field_levels"] = {k: v.get().lower() for k, v in vars_.items()}
        on_saved()
        top.destroy()
    bf = tk.Frame(top)
    bf.grid(row=len(INFO_FIELDS) + 1, column=0, columnspan=2, pady=10)
    tk.Button(bf, text="Save", width=10, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)


def show_text_window(root, title, text, width=86, height=34):
    top = tk.Toplevel(root)
    top.title(title)
    top.transient(root)
    t = new_text(top, width=width, height=height, wrap="word")
    sb = tk.Scrollbar(top, command=t.yview)
    t.configure(yscrollcommand=sb.set)
    sb.pack(side="right", fill="y")
    t.pack(side="left", fill="both", expand=True)
    t.insert("1.0", text)
    t.configure(state="disabled")
    make_modal(top)
    return top


def fmt_size(n):
    n = n or 0
    return "%.1f MB" % (n / 1048576.0) if n >= 1048576 else "%d KB" % max(1, round(n / 1024.0)) if n else ""


# *************** DEL 30b - CODES, LO CHECK AND IGNORED FILES (dialogs) *****************
# ToDo (Lars 2026-11-14): codes_dialog = maps without a code / free codes / unofficial codes that gave way; lo_dialog = jpg/pdf that
# sit in LO's column; ignored_dialog = files hidden by "Remove from program" (and the .comments2 files) with a way back.

def _tree_with_scroll(parent, columns, widths, height=14, selectmode="extended"):
    fr = tk.Frame(parent)
    tv = ttk.Treeview(fr, columns=[c for c, _t in columns], show="headings", selectmode=selectmode, height=height)
    for (c, t), w in zip(columns, widths):
        tv.heading(c, text=t)
        tv.column(c, width=w, anchor="w")
    sb = tk.Scrollbar(fr, command=tv.yview)
    tv.configure(yscrollcommand=sb.set)
    sb.pack(side="right", fill="y")
    tv.pack(side="left", fill="both", expand=True)
    return fr, tv


def ucode_proposal_dialog(parent, cat, proposals, options=None):
    """Shows the proposed unofficial codes; returns the [(map, code)] I accept (selected rows) or None.  `options(map)` (optional) gives
    the list of codes the 'Next suggestion' button walks through for the selected row."""
    top = tk.Toplevel(parent)
    top.title("Suggested unofficial codes")
    top.transient(parent)
    top.geometry("640x520")
    tk.Label(top, text=UCODE_NOTE, wraplength=600, justify="left", fg="#8a1c1c").pack(padx=10, pady=(10, 4), anchor="w")
    tk.Label(top, text="Select the rows you want (all are selected).  'Change selected...' types another code for one row.",
             justify="left").pack(padx=10, anchor="w")
    rows = {m["id"]: [m, c] for m, c in proposals}
    fr, tv = _tree_with_scroll(top, (("map", "Map"), ("code", "Unofficial code")), (400, 160), height=16)
    fr.pack(fill="both", expand=True, padx=10, pady=6)
    for mid, (m, c) in rows.items():
        tv.insert("", "end", iid=mid, values=(m["name"], "~" + c))
    tv.selection_set(list(rows))
    out = {"v": None}

    def change():
        sel = tv.selection()
        if len(sel) != 1:
            messagebox.showinfo("Rail Maps", "Select ONE row to change its code.", parent=top)
            return
        m = rows[sel[0]][0]
        new = ask_text(top, "Unofficial code", "Unofficial code for %s:" % m["name"], rows[sel[0]][1])
        if new is None:
            return
        new = new.strip().upper().lstrip("~")
        why = check_ucode(cat, m, new)
        if not why and any(c == new for k, (_m, c) in rows.items() if k != sel[0]):
            why = "%s is already proposed for another map." % new
        if why:
            messagebox.showwarning("Rail Maps", why, parent=top)
            return
        rows[sel[0]][1] = new
        tv.item(sel[0], values=(m["name"], "~" + new))

    def nxt():
        sel = tv.selection()
        if len(sel) != 1:
            messagebox.showinfo("Rail Maps", "Select ONE row to get another suggestion for it.", parent=top)
            return
        m = rows[sel[0]][0]
        others = {c for k, (_m, c) in rows.items() if k != sel[0]}
        opts = [c for c in options(m) if c not in others]
        if not opts:
            messagebox.showinfo("Rail Maps", "No other free code.", parent=top)
            return
        cur = rows[sel[0]][1]
        rows[sel[0]][1] = opts[(opts.index(cur) + 1) % len(opts)] if cur in opts else opts[0]
        tv.item(sel[0], values=(m["name"], "~" + rows[sel[0]][1]))

    def ok():
        out["v"] = [(rows[i][0], rows[i][1]) for i in tv.selection()]
        top.destroy()
    bf = tk.Frame(top)
    bf.pack(pady=8)
    tk.Button(bf, text="Use the selected codes", width=22, bg=GREEN_BTN, activebackground=GREEN_BTN, command=ok).pack(side="left", padx=4)
    if options:
        tk.Button(bf, text="Next suggestion", width=16, command=nxt).pack(side="left", padx=4)
    tk.Button(bf, text="Change selected...", width=18, command=change).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)
    parent.wait_window(top)
    return out["v"]


def codes_dialog(root, cat, on_saved):
    """Which maps have no CODE, which codes are free (usually AA..XX), unofficial codes for the code-less maps, and which unofficial
    codes have had to give way to an official one."""
    top = tk.Toplevel(root)
    top.title("Codes")
    top.transient(root)
    top.geometry("900x580")
    nb = ttk.Notebook(top)
    nb.pack(fill="both", expand=True, padx=8, pady=(8, 2))
    t1, t2, t3 = tk.Frame(nb), tk.Frame(nb), tk.Frame(nb)
    nb.add(t1, text="  Maps without a code  ")
    nb.add(t2, text="  Free codes  ")
    nb.add(t3, text="  Unofficial codes that gave way  ")
    rng = {"len": tk.IntVar(value=2), "lo": tk.StringVar(value=CODE_RANGE_DEFAULT[0]), "hi": tk.StringVar(value=CODE_RANGE_DEFAULT[1]),
           "show": tk.StringVar(value="free")}

    def rng_values():
        n = rng["len"].get()
        return n, rng["lo"].get().strip().upper(), rng["hi"].get().strip().upper()

    # ---- tab 1: maps without a code ----
    tk.Label(t1, text="A map has NO code when the sheet has nothing, '-' or '???' in its Code column.  " + UCODE_NOTE,
             wraplength=840, justify="left", fg="#8a1c1c").pack(padx=6, pady=(6, 2), anchor="w")
    lbl1 = tk.Label(t1, anchor="w")
    lbl1.pack(fill="x", padx=6)
    fr1, tv1 = _tree_with_scroll(t1, (("map", "Map"), ("nr", "Nr"), ("year", "Year"), ("sheet", "Sheet says"), ("uc", "Unofficial code")),
                                 (380, 60, 80, 90, 150), height=16)
    fr1.pack(fill="both", expand=True, padx=6, pady=4)

    def refresh1():
        tv1.delete(*tv1.get_children())
        lst = maps_without_code(cat)
        for m in sorted(lst, key=lambda x: norm_key(x["name"])):
            tv1.insert("", "end", iid=m["id"], values=(m["name"], m.get("nr", ""), m.get("year", ""), m.get("code", "") or "(empty)",
                                                      ucode_label(m) + ("   UNOFFICIAL" if ucode_label(m) else "")))
        n_u = sum(1 for m in lst if ucode_label(m))
        lbl1.configure(text="%d map(s) without an official code (hidden maps not counted); %d of them have an unofficial code." % (len(lst), n_u))

    def suggest():
        n, lo, hi = rng_values()
        renew = False
        if any(ucode_label(m) for m in maps_without_code(cat)):
            renew = messagebox.askyesno("Rail Maps", "Some maps already have an unofficial code.\n\nMake NEW suggestions for them too?\n"
                                        "(No = only the maps that have none.)", parent=top)
        props = suggest_ucodes(cat, n, lo, hi, renew=renew)
        if not props:
            messagebox.showinfo("Rail Maps", "Nothing to suggest: every map without a code has an unofficial code already, or no free code "
                                "is left in the range %s-%s." % (lo, hi), parent=top)
            return
        apply_picked(ucode_proposal_dialog(top, cat, props, lambda m: ucode_options(cat, m, n, lo, hi)))

    def apply_picked(picked):
        if picked:
            today = time.strftime("%Y-%m-%d")
            for m, c in picked:
                m["ucode"], m["ucode_date"] = c, today
            on_saved()
            refresh1()
            refresh2()

    def suggest_selected():
        """Only the map(s) selected in the list - one at a time (Lars 2026-11-14); 'Next suggestion' tries another code for it."""
        sel = [map_by_id(cat)[i] for i in tv1.selection()]
        if not sel:
            messagebox.showinfo("Rail Maps", "Select a map in the list first.", parent=top)
            return
        n, lo, hi = rng_values()
        props = suggest_ucodes(cat, n, lo, hi, renew=True, only=sel)
        if not props:
            messagebox.showinfo("Rail Maps", "No free code is left in the range %s-%s." % (lo, hi), parent=top)
            return
        apply_picked(ucode_proposal_dialog(top, cat, props, lambda m: ucode_options(cat, m, n, lo, hi)))

    def type_code():
        sel = tv1.selection()
        if len(sel) != 1:
            messagebox.showinfo("Rail Maps", "Select ONE map in the list.", parent=top)
            return
        m = map_by_id(cat)[sel[0]]
        new = ask_text(top, "Unofficial code", "Unofficial code for %s  (empty = remove it):" % m["name"], str(m.get("ucode") or ""))
        if new is None:
            return
        new = new.strip().upper().lstrip("~")
        if not new:
            m.pop("ucode", None)
            m.pop("ucode_date", None)
        else:
            why = check_ucode(cat, m, new)
            if why:
                messagebox.showwarning("Rail Maps", why, parent=top)
                return
            m["ucode"], m["ucode_date"] = new, time.strftime("%Y-%m-%d")
        on_saved()
        refresh1()
        refresh2()

    def remove_codes():
        sel = [map_by_id(cat)[i] for i in tv1.selection()]
        sel = [m for m in sel if m.get("ucode")]
        if not sel:
            messagebox.showinfo("Rail Maps", "Select maps that have an unofficial code.", parent=top)
            return
        for m in sel:
            m.pop("ucode", None)
            m.pop("ucode_date", None)
        on_saved()
        refresh1()
        refresh2()
    b1 = tk.Frame(t1)
    b1.pack(pady=4)
    tk.Button(b1, text="Suggest for ALL...", width=18, command=suggest).pack(side="left", padx=3)
    tk.Button(b1, text="Suggest for the selected map...", width=28, command=suggest_selected).pack(side="left", padx=3)
    tk.Button(b1, text="Type a code...", width=16, command=type_code).pack(side="left", padx=3)
    tk.Button(b1, text="Remove unofficial code", width=22, command=remove_codes).pack(side="left", padx=3)

    # ---- tab 2: free codes ----
    f2 = tk.Frame(t2)
    f2.pack(fill="x", padx=6, pady=6)
    tk.Label(f2, text="Letters").pack(side="left")
    tk.OptionMenu(f2, rng["len"], 1, 2, 3).pack(side="left", padx=(2, 10))
    tk.Label(f2, text="from").pack(side="left")
    e_lo = new_entry(f2, width=6, textvariable=rng["lo"])
    e_lo.pack(side="left", padx=(2, 8))
    tk.Label(f2, text="to").pack(side="left")
    e_hi = new_entry(f2, width=6, textvariable=rng["hi"])
    e_hi.pack(side="left", padx=(2, 12))
    for key, lab in (("free", "free"), ("taken", "taken"), ("all", "all")):
        tk.Radiobutton(f2, text=lab, value=key, variable=rng["show"]).pack(side="left")
    tk.Button(f2, text="Show", width=8, command=lambda: refresh2()).pack(side="left", padx=10)
    lbl2 = tk.Label(t2, anchor="w", justify="left", wraplength=840)
    lbl2.pack(fill="x", padx=6)
    fr2, tv2 = _tree_with_scroll(t2, (("code", "Code"), ("status", "Status"), ("map", "Map")), (100, 120, 520), height=16)
    fr2.pack(fill="both", expand=True, padx=6, pady=4)
    for e in (e_lo, e_hi):
        e.bind("<Return>", lambda ev: refresh2())

    def refresh2(*_a):
        n, lo, hi = rng_values()
        rows = free_code_rows(cat, n, lo, hi)
        free = [r for r in rows if r[1] == "free"]
        want = rng["show"].get()
        shown = [r for r in rows if want == "all" or (want == "free" and r[1] == "free") or (want == "taken" and r[1] != "free")]
        tv2.delete(*tv2.get_children())
        for c, st, who in shown[:3000]:
            tv2.insert("", "end", values=(c, {"free": "free", "official": "OFFICIAL", "unofficial": "unofficial (~)"}[st], who))
        lbl2.configure(text="%d of the %d codes %s-%s are free (not official, no unofficial code).%s" % (
            len(free), len(rows), rows[0][0] if rows else "", rows[-1][0] if rows else "",
            "  (The first 3000 rows are listed.)" if len(shown) > 3000 else ""))

    # ---- tab 3: unofficial codes that gave way ----
    tk.Label(t3, text="An unofficial code is removed by itself when its map gets an official code, or when another map gets that very code.",
             anchor="w").pack(fill="x", padx=6, pady=6)
    fr3, tv3 = _tree_with_scroll(t3, (("date", "Date"), ("text", "What happened")), (100, 740), height=16)
    fr3.pack(fill="both", expand=True, padx=6, pady=4)

    def refresh3():
        tv3.delete(*tv3.get_children())
        for e in reversed(cat.get("ucode_log", [])):
            tv3.insert("", "end", values=(e.get("date", ""), e.get("text", "")))

    def clear3():
        if cat.get("ucode_log") and messagebox.askyesno("Rail Maps", "Clear this list?", parent=top):
            cat["ucode_log"] = []
            on_saved()
            refresh3()
    tk.Button(t3, text="Clear the list", width=16, command=clear3).pack(pady=4)
    for e in cat.get("ucode_log", []):
        e["seen"] = True
    refresh1()
    refresh2()
    refresh3()
    bf = tk.Frame(top)
    bf.pack(pady=(2, 8))
    tk.Button(bf, text="Close", width=12, command=top.destroy).pack()
    make_modal(top)
    root.wait_window(top)


def lo_dialog(root, cat, on_saved):
    """LO (Lars) draws .bmp only.  Lists the jpg / png / gif / pdf files in the Issu's column or with LO as designer and moves them."""
    top = tk.Toplevel(root)
    top.title("Check LO")
    top.transient(root)
    top.geometry("940x520")
    tk.Label(top, text="LO (Lars Olsson) only makes .bmp files.  A jpg / png / gif / pdf can never be LO's: these files sit in the Issu's "
                       "column or have LO as designer.  The fix moves them out of the Issu's column and takes LO away from their designers "
                       "(the other designers stay).", wraplength=900, justify="left").pack(padx=10, pady=(10, 4), anchor="w")
    lbl = tk.Label(top, anchor="w")
    lbl.pack(fill="x", padx=10)
    fr, tv = _tree_with_scroll(top, (("file", "File"), ("col", "Column"), ("by", "Designers"), ("map", "Map"), ("why", "Problem")),
                               (300, 80, 100, 220, 200), height=14)
    fr.pack(fill="both", expand=True, padx=10, pady=6)
    where = tk.StringVar(value="orig")
    rb = tk.Frame(top)
    rb.pack(fill="x", padx=10)
    tk.Label(rb, text="Pictures that were in the Issu's column go to:").pack(side="left")
    tk.Radiobutton(rb, text="Original", value="orig", variable=where).pack(side="left", padx=6)
    tk.Radiobutton(rb, text="Version (the same map redrawn by someone else)", value="version", variable=where).pack(side="left")
    items = {}

    def fill():
        tv.delete(*tv.get_children())
        items.clear()
        maps = map_by_id(cat)
        for f, why in lo_problems(cat):
            i = str(cat["files"].index(f))
            items[i] = f
            tv.insert("", "end", iid=i, values=(os.path.basename(f["path"]), COL_NAME.get(f["col"], f["col"]), f.get("by", ""),
                                               maps[f["map"]]["name"] if f.get("map") in maps else "(no map)", why))
        lbl.configure(text=("%d file(s) to look at." % len(items)) if items else "Nothing wrong: no jpg/pdf is in the Issu's column or has LO as designer.")

    def fix():
        sel = [items[i] for i in tv.selection() if i in items] or list(items.values())
        if not sel:
            return
        if not messagebox.askyesno("Rail Maps", "Fix %d file(s)?\n\nThey leave the Issu's column and LO is taken away as designer.  "
                                   "Nothing on disk is touched." % len(sel), parent=top):
            return
        lo_fix(cat, sel, where.get())
        on_saved()
        fill()

    def open_sel():
        for i in tv.selection()[:6]:
            open_map_file(items[i]["path"])
    bf = tk.Frame(top)
    bf.pack(pady=8)
    tk.Button(bf, text="Fix the selected (all if none)", width=28, bg=GREEN_BTN, activebackground=GREEN_BTN, command=fix).pack(side="left", padx=4)
    tk.Button(bf, text="Open", width=10, command=open_sel).pack(side="left", padx=4)
    tk.Button(bf, text="Close", width=10, command=top.destroy).pack(side="left", padx=4)
    fill()
    make_modal(top)
    root.wait_window(top)


def ignored_dialog(root, cat, on_saved):
    """Files hidden from every list: 'Remove from program', 'Ignore' and the .comments2 files.  A way back for each of them."""
    top = tk.Toplevel(root)
    top.title("Ignored files")
    top.transient(root)
    top.geometry("940x520")
    tk.Label(top, text="These files are hidden everywhere (not on the page, not in the upload folder, not on the Unassigned tab).  "
                       "'Put back' makes them visible again - on their map, or on the Unassigned tab when they have none.",
             wraplength=900, justify="left").pack(padx=10, pady=(10, 4), anchor="w")
    lbl = tk.Label(top, anchor="w")
    lbl.pack(fill="x", padx=10)
    fr, tv = _tree_with_scroll(top, (("file", "File"), ("map", "Map"), ("why", "Why hidden"), ("folder", "Folder")), (260, 200, 150, 300), height=15)
    fr.pack(fill="both", expand=True, padx=10, pady=6)
    items = {}
    show_c2 = tk.BooleanVar(value=False)

    def fill():
        tv.delete(*tv.get_children())
        items.clear()
        maps = map_by_id(cat)
        n2 = 0
        for i, f in enumerate(cat["files"]):
            if not f.get("ign"):
                continue
            if f.get("ign_why") == "comments2":
                n2 += 1
                if not show_c2.get():
                    continue
            items[str(i)] = f
            tv.insert("", "end", iid=str(i), values=(os.path.basename(f["path"]), maps[f["map"]]["name"] if f.get("map") in maps else "",
                                                    f.get("ign_why") or "ignored", os.path.dirname(f["path"])))
        lbl.configure(text="%d file(s) hidden%s." % (len(items), ("; %d .comments2 file(s) are not listed" % n2) if n2 and not show_c2.get() else ""))

    def back():
        sel = [items[i] for i in tv.selection() if i in items]
        for f in sel:
            f["ign"] = False
            f.pop("ign_why", None)
        if sel:
            on_saved()
            fill()

    def open_sel():
        for i in tv.selection()[:6]:
            open_map_file(items[i]["path"])
    tk.Checkbutton(top, text="also list the .comments2 files (hidden because they are of no interest)", variable=show_c2, command=fill).pack(anchor="w", padx=10)
    bf = tk.Frame(top)
    bf.pack(pady=8)
    tk.Button(bf, text="Put back", width=14, bg=GREEN_BTN, activebackground=GREEN_BTN, command=back).pack(side="left", padx=4)
    tk.Button(bf, text="Open", width=10, command=open_sel).pack(side="left", padx=4)
    tk.Button(bf, text="Close", width=10, command=top.destroy).pack(side="left", padx=4)
    fill()
    make_modal(top)
    root.wait_window(top)


# *************** DEL 30d - PICTURE DROP DIALOG (codes for the PicturePerfect app) *****************
def pdrop_dialog(root, settings, save_settings, fetch_now):
    """One window: (1) the Apps Script file, (2) its Web app address, (3) a code per person, switch off, (4) fetch the new pictures.
    save_settings() writes settings.json; fetch_now() starts the 'Fetch pictures' job (the window closes first)."""
    top = tk.Toplevel(root)
    top.title("Picture drop - the PicturePerfect app")
    top.transient(root)
    top.resizable(False, False)
    tk.Label(top, justify="left", anchor="w", text=(
        "People you give a CODE can switch on 'Rail map' mode in the PicturePerfect app.  Every picture they keep is then also\n"
        "sent to your incoming Drive folder (a sub folder with their name).  'Fetch new pictures' brings them to this computer.")).grid(
        row=0, column=0, columnspan=4, sticky="w", padx=12, pady=(10, 6))
    state = {}

    def say_status(t):
        state["lab"].configure(text=t)

    # step 1 + 2: the script
    tk.Label(top, text="1. Script", anchor="w", font=("Segoe UI", 9, "bold")).grid(row=1, column=0, sticky="w", padx=12)
    f1 = tk.Frame(top)
    f1.grid(row=2, column=0, columnspan=4, sticky="we", padx=12, pady=(0, 4))

    def make_script():
        try:
            text = pdrop_script_text(settings)
        except PDropError as exc:
            messagebox.showwarning("Rail Maps", str(exc), parent=top)
            return
        save_settings()
        folder = os.path.join(PROGRAM_HF_DIR, "Picture_drop")
        os.makedirs(folder, exist_ok=True)
        path = os.path.join(folder, "RailMaps_PictureDrop.gs")
        with open(path, "w", encoding="utf-8", newline="\n") as fh:
            fh.write(text)
        open_path(path)
        messagebox.showinfo("Rail Maps", "The script file is made and opened:\n%s\n\nPrivate - it holds your secret; do not share it.\n\n"
                            "Paste ALL of it into a new project at script.google.com, follow the steps at the top of the file, deploy it as a Web "
                            "app (Execute as: Me, access: Anyone), then paste the Web app address below." % path, parent=top)
    tk.Button(f1, text="Make the script file...", command=make_script).pack(side="left")
    tk.Label(f1, text="  2. Web app address:").pack(side="left")
    url_e = new_entry(f1, width=58)
    url_e.insert(0, settings.get("pdrop_url", ""))
    url_e.pack(side="left", padx=4)

    def save_url():
        u = url_e.get().strip()
        if u and not re.match(r"^https://script\.google\.com/macros/s/[A-Za-z0-9_\-]+/exec$", u):
            messagebox.showwarning("Rail Maps", "That does not look like a Web app address (it starts with https://script.google.com/macros/s/ and ends with /exec).",
                                   parent=top)
            return False
        settings["pdrop_url"] = u
        save_settings()
        return True

    def test_script():
        if not save_url() or not settings.get("pdrop_url"):
            return
        try:
            pdrop_call(settings["pdrop_url"], {"a": "ping", "o": settings.get("pdrop_secret", "")})
            say_status("The script answered - it is deployed and the secret matches.")
        except PDropError as exc:
            say_status("Not working: %s" % exc)
    tk.Button(f1, text="Save + test", command=test_script).pack(side="left")

    # step 3: people
    tk.Label(top, text="3. People (one code each)", anchor="w", font=("Segoe UI", 9, "bold")).grid(row=3, column=0, sticky="w", padx=12, pady=(6, 0))
    tree = ttk.Treeview(top, columns=("name", "made", "state"), show="headings", height=7, selectmode="browse")
    for c, t, w in (("name", "Name", 220), ("made", "Made", 90), ("state", "State", 100)):
        tree.heading(c, text=t)
        tree.column(c, width=w, anchor="w")
    tree.grid(row=4, column=0, columnspan=3, sticky="we", padx=(12, 0))
    code_box = new_text(top, width=44, height=7, wrap="char")
    code_box.grid(row=4, column=3, sticky="ns", padx=(6, 12))

    def fill():
        tree.delete(*tree.get_children())
        for p in settings.get("pdrop_people", []):
            tree.insert("", "end", iid=p["id"], values=(p["name"], p.get("at", ""), "switched off" if p.get("off") else "on"))

    def show_code(_e=None):
        sel = tree.selection()
        code_box.delete("1.0", "end")
        if sel:
            p = next((x for x in settings.get("pdrop_people", []) if x["id"] == sel[0]), None)
            if p:
                code_box.insert("1.0", p["code"])
    tree.bind("<<TreeviewSelect>>", show_code)

    f3 = tk.Frame(top)
    f3.grid(row=5, column=0, columnspan=4, sticky="we", padx=12, pady=4)
    tk.Label(f3, text="Name:").pack(side="left")
    name_e = new_entry(f3, width=24)
    name_e.pack(side="left", padx=4)

    def make_code():
        if not save_url():
            return
        try:
            rec = pdrop_add_person(settings, name_e.get())
        except PDropError as exc:
            messagebox.showwarning("Rail Maps", str(exc), parent=top)
            return
        save_settings()
        name_e.delete(0, "end")
        fill()
        tree.selection_set(rec["id"])
        top.clipboard_clear()
        top.clipboard_append(rec["code"])
        say_status("Code for %s made and copied - paste it in a message to them (it holds only their own key)." % rec["name"])

    def copy_code():
        sel = tree.selection()
        if sel:
            p = next(x for x in settings["pdrop_people"] if x["id"] == sel[0])
            top.clipboard_clear()
            top.clipboard_append(p["code"])
            say_status("Code for %s copied." % p["name"])

    def switch(off):
        sel = tree.selection()
        if not sel:
            return
        try:
            pdrop_switch(settings, sel[0], off)
        except PDropError as exc:
            messagebox.showwarning("Rail Maps", str(exc), parent=top)
            return
        save_settings()
        fill()
        tree.selection_set(sel[0])
        say_status("Done.")
    tk.Button(f3, text="Make code", command=make_code).pack(side="left", padx=2)
    tk.Button(f3, text="Copy code", command=copy_code).pack(side="left", padx=2)
    tk.Button(f3, text="Switch off", command=lambda: switch(True)).pack(side="left", padx=(12, 2))
    tk.Button(f3, text="Switch on again", command=lambda: switch(False)).pack(side="left", padx=2)

    # step 4
    state["lab"] = tk.Label(top, text="", anchor="w", justify="left", fg="#2a5a9a")
    state["lab"].grid(row=6, column=0, columnspan=4, sticky="we", padx=12)
    bf = tk.Frame(top)
    bf.grid(row=7, column=0, columnspan=4, pady=10)

    def go_fetch():
        if not save_url():
            return
        top.destroy()
        fetch_now()
    tk.Button(bf, text="4. Fetch new pictures", width=22, command=go_fetch).pack(side="left", padx=4)
    tk.Button(bf, text="Close", width=10, command=top.destroy).pack(side="left", padx=4)
    fill()
    make_modal(top)
    root.wait_window(top)


# *************** DEL 30e - COPIES (dialogs) *****************
# ToDo (Lars 2026-11-16): two photos / scans of the very same draft are ONE version - the extra file is a "copy" of the main file and is not
# counted as a new design (timeline, statistics, newest version).  copies_dialog = the pairs that MIGHT be copies (decide each) and the
# copies already made (undo, or swap which file is the main one); pick_file_dialog = choose the main file for 'Copy of...'.

def pick_file_dialog(root, title, prompt, files):
    """A small list of files (name, draft, date, designers, look); returns the chosen file record or None."""
    top = tk.Toplevel(root)
    top.title(title)
    top.transient(root)
    top.geometry("820x380")
    tk.Label(top, text=prompt, wraplength=780, justify="left").pack(padx=10, pady=(10, 4), anchor="w")
    fr, tv = _tree_with_scroll(top, (("file", "File"), ("draft", "Draft"), ("date", "Date"), ("by", "By"), ("look", "Look")),
                               (400, 60, 90, 90, 120), height=10, selectmode="browse")
    fr.pack(fill="both", expand=True, padx=10, pady=6)
    items = {}
    for i, f in enumerate(files):
        items[str(i)] = f
        tv.insert("", "end", iid=str(i), values=(os.path.basename(f["path"]), f.get("draft", ""), f.get("date", ""), f.get("by", ""),
                                                 LOOK_LABEL.get(f.get("look", ""), "").split(" (")[0]))
    out = {"f": None}

    def ok():
        sel = tv.selection()
        if sel:
            out["f"] = items[sel[0]]
            top.destroy()
    bf = tk.Frame(top)
    bf.pack(pady=8)
    tk.Button(bf, text="OK", width=12, bg=GREEN_BTN, activebackground=GREEN_BTN, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Open", width=10, command=lambda: [open_map_file(items[i]["path"]) for i in tv.selection()[:2]]).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    tv.bind("<Double-Button-1>", lambda e: ok())
    make_modal(top)
    root.wait_window(top)
    return out["f"]


def copies_dialog(root, cat, on_saved):
    """Find copies...: the SURE ones are marked first (same name + draft), then the pairs that MIGHT be the same draft photographed
    twice are listed for me to decide, together with the copies that already exist."""
    top = tk.Toplevel(root)
    top.title("Copies - the same draft photographed twice")
    top.transient(root)
    top.geometry("1100x700")
    tk.Label(top, text="A copy is another photo or scan of a draft that is already in the list (maybe with other light or colours).  It is NOT a "
                       "new version: the timeline and the statistics do not count it, the page shows it under the main file.  A black & white map "
                       "and the same draft coloured in afterwards are not copies (that is a version of its own).",
             wraplength=1060, justify="left").pack(padx=10, pady=(10, 4), anchor="w")
    lbl1 = tk.Label(top, anchor="w", font=("Segoe UI", 9, "bold"))
    lbl1.pack(fill="x", padx=10)
    fr1, tv1 = _tree_with_scroll(top, (("map", "Map"), ("a", "File A"), ("b", "File B"), ("why", "Why it might be a copy"), ("facts", "A | B")),
                                 (190, 250, 250, 200, 170), height=9, selectmode="browse")
    fr1.pack(fill="both", expand=True, padx=10, pady=4)
    bf1 = tk.Frame(top)
    bf1.pack(pady=2)
    lbl2 = tk.Label(top, anchor="w", font=("Segoe UI", 9, "bold"))
    lbl2.pack(fill="x", padx=10, pady=(8, 0))
    fr2, tv2 = _tree_with_scroll(top, (("map", "Map"), ("c", "Copy"), ("m", "Main file"), ("why", "Why")), (190, 290, 290, 280), height=9,
                                 selectmode="extended")
    fr2.pack(fill="both", expand=True, padx=10, pady=4)
    bf2 = tk.Frame(top)
    bf2.pack(pady=2)
    pairs, copies = {}, {}
    maps = map_by_id(cat)

    def short(f):
        return " ".join(x for x in (f.get("draft") and "draft " + f["draft"], f.get("date", ""), f.get("by", ""),
                                    LOOK_SHORT.get(f.get("look", ""), "")) if x) or "-"

    def fill():
        top.configure(cursor="watch")
        top.update_idletasks()
        tv1.delete(*tv1.get_children())
        tv2.delete(*tv2.get_children())
        pairs.clear()
        copies.clear()
        for i, (_lvl, a, b, why, match) in enumerate([c for c in copy_candidates(cat) if c[0] == "probable"]):
            pairs[str(i)] = (a, b)
            tv1.insert("", "end", iid=str(i), values=(maps[a["map"]]["name"] if a.get("map") in maps else "", os.path.basename(a["path"]),
                                                      os.path.basename(b["path"]), why, short(a) + "  |  " + short(b)))
        n = 0
        for i, f in enumerate(cat["files"]):
            if f.get("copy_of") and not f.get("gone") and not f.get("ign"):
                main = primary_of(cat, f)
                if main is None:
                    continue
                copies[str(i)] = (f, main)
                tv2.insert("", "end", iid=str(i), values=(maps[f["map"]]["name"] if f.get("map") in maps else "", os.path.basename(f["path"]),
                                                          os.path.basename(main["path"]), f.get("copy_why", "")))
                n += 1
        lbl1.configure(text="%d pair(s) that might be copies of each other - decide each one:" % len(pairs))
        lbl2.configure(text="%d file(s) are copies of another file (not counted as versions):" % n)
        top.configure(cursor="")

    def mark(which):
        sel = tv1.selection()
        if not sel:
            messagebox.showinfo("Rail Maps", "Select a pair in the upper list first.", parent=top)
            return
        a, b = pairs[sel[0]]
        main, cp = (a, b) if which == "b" else (b, a)
        apply_copy(cat, main, cp, "marked by hand")
        on_saved()
        fill()

    def not_copies():
        sel = tv1.selection()
        if not sel:
            return
        a, b = pairs[sel[0]]
        a.setdefault("not_copy", []).append(b["path"])
        b.setdefault("not_copy", []).append(a["path"])
        on_saved()
        fill()

    def open_pair(src):
        sel = src.selection()
        if sel:
            x, y = (pairs[sel[0]] if src is tv1 else copies[sel[0]])
            for f in (x, y):
                open_map_file(f["path"])

    def undo():
        sel = [copies[i] for i in tv2.selection() if i in copies]
        for f, _main in sel:
            unmark_copy(cat, f)
        if sel:
            on_saved()
            fill()

    def swap():
        sel = [copies[i] for i in tv2.selection() if i in copies]
        if len(sel) == 1:
            make_primary(cat, sel[0][0])
            on_saved()
            fill()
    for text, cmd, w in (("B is a copy of A", lambda: mark("b"), 18), ("A is a copy of B", lambda: mark("a"), 18),
                         ("Not copies (two versions)", not_copies, 24), ("Open both", lambda: open_pair(tv1), 12)):
        tk.Button(bf1, text=text, width=w, command=cmd).pack(side="left", padx=4)
    for text, cmd, w in (("Not a copy after all", undo, 22), ("Make this the main file", swap, 24), ("Open both", lambda: open_pair(tv2), 12),
                         ("Close", top.destroy, 10)):
        tk.Button(bf2, text=text, width=w, command=cmd).pack(side="left", padx=4)
    fill()
    make_modal(top)
    root.wait_window(top)


# *************** DEL 31 - SETTINGS DIALOG ("Sources & folders") *****************
def settings_dialog(root, settings, on_saved, cat=None):
    top = tk.Toplevel(root)
    top.title("Sources & folders")
    top.transient(root)
    top.resizable(False, False)
    fields = [("excel", "Excel sheet (Spel---RAIL.xlsx)"), ("drive_folder", "Google Drive folder link (public)"),
              ("vps_base", "Webdock files address"),
              ("upload_dir", "Upload folder (copy of the files)"),
              ("import_dir", "Add files... copies them to (empty = leave in place)"), ("out_dir", "Page output folder"), ("page_title", "Page title"),
              ("contact_email", "My e-mail for the page's 'Add or correct' form"),
              ("incoming_url", "Drive folder where visitors send files (link)"),
              ("extra_tools", "My 'Program used' options: Xxx, Xxy, Zzz"),
              ("extra_looks", "My 'Look' options: Sepia, Pencil, ..."),
              ("extra_quality", "My quality options: Name=minor/photo/poor, ...")]
    ents = {}
    for i, (k, lab) in enumerate(fields):
        tk.Label(top, text=lab, anchor="w", width=44).grid(row=i, column=0, padx=(10, 4), pady=3, sticky="w")
        e = new_entry(top, width=62)
        val = settings.get(k, "")
        if k == "extra_tools":              # my list + every program already used on a file, so nothing that exists is missing
            used = [f.get("tool", "").strip() for f in (cat or {}).get("files", []) if f.get("tool", "").strip()]
            val = ", ".join(split_list(", ".join(split_list(val) + sorted(set(used), key=str.lower))))
        elif k == "extra_looks":            # only the own looks (the three built-in ones are fixed and always there)
            val = ", ".join(lab for _key, lab in parse_extra_looks(val))
        elif k == "extra_quality":          # my own marks written back as Name=level (the built-in ones are fixed, see the hint row)
            val = ", ".join("%s=%s" % (lab, base) for _key, lab, base in parse_extra_quality(val))
        e.insert(0, val)
        e.grid(row=i, column=1, padx=(0, 10), pady=3)
        ents[k] = e
    tk.Label(top, text="Built-in quality marks (always there): " + ", ".join(v for k, v in QUALITY_BUILTIN if k and k != "missing") +
             " - own marks go in the field above; a mark that is in use is kept even if removed there\n"
             "Built-in looks (fixed): " + ", ".join(v.split(" (")[0] for k, v in LOOKS_BUILTIN if k) +
             " - an own look that is in use on a version cannot be removed or re-spelled (it is put back)",
             anchor="w", justify="left", fg="#666").grid(row=len(fields), column=0, columnspan=2, padx=10, sticky="w")
    hide_empty = tk.BooleanVar(value=bool(settings.get("hide_empty")))
    only_conf = tk.BooleanVar(value=bool(settings.get("only_confirmed")))
    tk.Checkbutton(top, text="HIDE maps that have no files yet (normally they are listed, with a message)", variable=hide_empty).grid(row=len(fields) + 1, column=1, sticky="w")
    tk.Checkbutton(top, text="Only CONFIRMED files go on the page / upload folder", variable=only_conf).grid(
        row=len(fields) + 1, column=0, sticky="w", padx=10)
    tk.Label(top, text="Library folders (role decides how a picture is used)", anchor="w").grid(
        row=len(fields) + 2, column=0, columnspan=2, padx=10, pady=(10, 2), sticky="w")
    roots = [dict(r) for r in settings.get("roots", [])]
    lb = tk.Listbox(top, width=100, height=6, exportselection=False)
    lb.grid(row=len(fields) + 3, column=0, columnspan=2, padx=10)

    def refill():
        lb.delete(0, "end")
        for r in roots:
            lb.insert("end", "[%s%s]  %s" % (r["role"], ", flat" if r.get("flat") else "", r["path"]))
    refill()

    def add_root():
        d = filedialog.askdirectory(parent=top, title="Library folder")
        if not d:
            return
        role = ask_text(top, "Role", "Role: original (drafts) / issu (my versions) / json", "original")
        if role and role.strip().lower() in ("original", "issu", "json"):
            roots.append({"path": d.replace("/", "\\"), "role": role.strip().lower()})
            refill()

    def del_root():
        sel = lb.curselection()
        if sel:
            roots.pop(sel[0])
            refill()
    bf = tk.Frame(top)
    bf.grid(row=len(fields) + 4, column=0, columnspan=2, pady=6)
    tk.Button(bf, text="Add folder...", command=add_root).pack(side="left", padx=4)
    tk.Button(bf, text="Remove from list", command=del_root).pack(side="left", padx=4)

    def ok():
        old_looks = dict(parse_extra_looks(settings.get("extra_looks", "")))
        for k, e in ents.items():
            settings[k] = e.get().strip()
        # SAFETY (Lars 2026-11-16): an own look that is IN USE on a version can be neither removed nor re-spelled - it is put back as it was.
        new_looks = dict(parse_extra_looks(settings.get("extra_looks", "")))
        used = {x.get("look") for x in (cat or {}).get("files", []) if x.get("look")}
        put_back = []
        for key in used:
            if key in old_looks and new_looks.get(key) != old_looks[key]:
                put_back.append("%s  (%d version(s))" % (old_looks[key], sum(1 for x in cat["files"] if x.get("look") == key)))
                new_looks[key] = old_looks[key]
        if put_back:
            settings["extra_looks"] = ", ".join(list(dict(parse_extra_looks(settings.get("extra_looks", "")), **new_looks).values()))
            messagebox.showinfo("Rail Maps", "These looks are in use and cannot be removed or re-spelled, so they were put back as they were:\n\n"
                                + "\n".join(put_back) + "\n\n(Take the look off the versions first, then it can be changed.)", parent=top)
        settings["hide_empty"] = bool(hide_empty.get())
        settings["only_confirmed"] = bool(only_conf.get())
        STATE["only_confirmed"] = settings["only_confirmed"]
        settings["roots"] = roots
        # an own quality mark that is IN USE on a file / map never disappears, even if I removed it from the field
        in_use = {x.get("quality") for x in list((cat or {}).get("files", [])) + list((cat or {}).get("maps", []))}
        have = {key for key, _lab, _base in parse_extra_quality(settings.get("extra_quality", ""))}
        keep = ["%s=%s" % (QUALITY_LABEL[k], b) for k, b in QUALITY_BASE.items() if k in in_use and k not in have]
        if keep:
            settings["extra_quality"] = ", ".join(split_list(settings.get("extra_quality", "")) + keep)
        apply_custom_options(settings)
        on_saved()
        top.destroy()
    bf2 = tk.Frame(top)
    bf2.grid(row=len(fields) + 5, column=0, columnspan=2, pady=(2, 10))
    tk.Button(bf2, text="Save", width=10, command=ok).pack(side="left", padx=4)
    tk.Button(bf2, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)


def creators_dialog(root, cat, on_saved):
    top = tk.Toplevel(root)
    top.title("Creators (code = name)")
    top.transient(root)
    tk.Label(top, text="One per line:  CODE = Full name   (the BY column of the sheet uses the codes; '+' joins codes)",
             anchor="w").pack(padx=10, pady=(10, 2), fill="x")
    t = new_text(top, width=60, height=24)
    t.pack(padx=10)
    t.insert("1.0", "\n".join("%s = %s" % (k, v) for k, v in sorted(cat["people"].items())))

    def ok():
        people = {}
        for line in t.get("1.0", "end").splitlines():
            if "=" in line:
                a, b = line.split("=", 1)
                if a.strip() and b.strip():
                    people[a.strip()] = b.strip()
        dup_codes = [ln.split("=", 1)[0].strip() for ln in t.get("1.0", "end").splitlines() if "=" in ln]
        dup_codes = sorted({c for c in dup_codes if c and dup_codes.count(c) > 1})
        problems = creators_problems(people) + ["The code '%s' is written on more than one line - only the last one is kept." % c
                                                for c in dup_codes]
        if problems and not messagebox.askyesno("Rail Maps", "Look at this before saving:\n\n- " + "\n- ".join(problems) +
                                                "\n\nSave anyway?", parent=top):
            return
        cat["people"] = people
        n_h = merge_helpers(cat)                    # a helper that is now a creator is only a creator (no duplicates)
        fix_designer_names(cat)                     # a name typed as a designer somewhere now has a code
        on_saved()
        if n_h:
            messagebox.showinfo("Rail Maps", "%d person(s) were also in the Helpers list and are now only creators "
                                "(they still show under Helpers..., which lists all creators)." % n_h, parent=top)
        top.destroy()
    bf = tk.Frame(top)
    bf.pack(pady=8)
    tk.Button(bf, text="Save", width=10, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)


def helpers_dialog(root, cat, on_saved):
    """Helpers...  Left: ALL creators (read only - they are changed under Creators...).  Right: the people who are ONLY helpers
    (CODE = Full name).  The two lists never share a code or a name; helpers-only people never show under Creators."""
    top = tk.Toplevel(root)
    top.title("Helpers (code = name)")
    top.transient(root)
    tk.Label(top, text="Everybody who can be named as a helper.  Left: all creators (change them under Creators...).  "
                       "Right: people who ONLY helped - one per line:  CODE = Full name", anchor="w", justify="left",
             wraplength=760).pack(padx=10, pady=(10, 2), fill="x")
    body = tk.Frame(top)
    body.pack(padx=10, fill="both", expand=True)
    tk.Label(body, text="Creators (read only)", anchor="w").grid(row=0, column=0, sticky="w")
    tk.Label(body, text="Only helpers (editable)", anchor="w").grid(row=0, column=1, sticky="w", padx=(10, 0))
    tl = new_text(body, width=40, height=22)
    tl.grid(row=1, column=0, sticky="nsew")
    tl.insert("1.0", "\n".join("%s = %s" % (k, v) for k, v in sorted(cat["people"].items())))
    tl.configure(state="disabled")
    t = new_text(body, width=40, height=22)
    t.grid(row=1, column=1, sticky="nsew", padx=(10, 0))
    t.insert("1.0", "\n".join("%s = %s" % (k, v) for k, v in sorted(cat.get("helpers", {}).items())))
    body.columnconfigure(0, weight=1)
    body.columnconfigure(1, weight=1)

    def ok():
        helpers, notes = {}, []
        by_name = {" ".join(n.lower().split()): c for c, n in cat["people"].items()}
        for line in t.get("1.0", "end").splitlines():
            if "=" not in line:
                continue
            a, b = (x.strip() for x in line.split("=", 1))
            if not a or not b:
                continue
            if a in cat["people"]:
                notes.append("%s is already a creator (%s) - left out here." % (a, cat["people"][a]))
            elif " ".join(b.lower().split()) in by_name:
                notes.append("%s is already a creator under the code %s - left out here." % (b, by_name[" ".join(b.lower().split())]))
            elif any(ch in a for ch in ",+/"):
                notes.append("The code '%s' contains , + or / - those separate designers.  Left out." % a)
            else:
                helpers[a] = b
        if notes and not messagebox.askyesno("Rail Maps", "Look at this before saving:\n\n- " + "\n- ".join(notes) +
                                             "\n\nSave the rest?", parent=top):
            return
        cat["helpers"] = helpers
        merge_helpers(cat)
        fix_designer_names(cat)
        on_saved()
        top.destroy()
    bf = tk.Frame(top)
    bf.pack(pady=8)
    tk.Button(bf, text="Save", width=10, command=ok).pack(side="left", padx=4)
    tk.Button(bf, text="Cancel", width=10, command=top.destroy).pack(side="left", padx=4)
    make_modal(top)


# *************** DEL 32 - THE MAIN WINDOW *****************
class App(object):
    def __init__(self, root):
        self.root = root
        self.settings = load_settings()
        self.cat = load_catalog()
        self.cur = None            # the map record being edited
        self.busy = False
        self.q = queue.Queue()
        self.playertext = None
        root.title("Rail Maps")
        root.geometry("1280x760")
        try:                                              # remembered size / place / maximised from last time
            g = self.settings.get("window") or {}
            if g.get("w") and g.get("h"):
                w = max(800, min(int(g["w"]), root.winfo_screenwidth()))
                h = max(500, min(int(g["h"]), root.winfo_screenheight()))
                x = max(0, min(int(g.get("x", 0)), root.winfo_screenwidth() - 200))
                y = max(0, min(int(g.get("y", 0)), root.winfo_screenheight() - 150))
                root.geometry("%dx%d+%d+%d" % (w, h, x, y))
            if g.get("zoomed"):
                root.state("zoomed")
        except Exception:
            pass
        self._build_ui()
        self.refresh_maps()
        self.refresh_unassigned()
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        try:
            save_catalog(self.cat, backup=True)
        except Exception:
            pass
        if not self.cat["maps"] and os.path.isfile(self.settings.get("excel", "")) and not os.environ.get("RAILMAPS_NO_PROMPT"):
            root.after(400, self.first_run_excel)
        elif self.cat["maps"] and not os.environ.get("RAILMAPS_NO_PROMPT"):
            root.after(600, self.auto_excel)
        if not os.environ.get("RAILMAPS_NO_PROMPT"):
            root.after(1200, self.auto_comments)
            root.after(1700, self.auto_copies_start)
        root.after(300, self.report_gave_way)

    def auto_comments(self):
        """At start: the .comments files fill Exceptions / comments of their maps (by themselves; typed text is never touched)."""
        if self.busy:
            return
        try:
            n = apply_comment_files(self.cat, self.say)
            if n:
                self.save()
                self.refresh_maps()
                if self.cur:
                    self.load_map()
            self.flush_log()
        except Exception as exc:
            self.say("Comment files: %s" % exc)

    def auto_copies_start(self):
        """At start: the SURE copies (another photo of a draft already in the list: same name + draft, designers / date / look agree) are
        marked by themselves (Lars 2026-11-16).  The unsure pairs wait in 'Find copies...'."""
        if self.busy:
            return
        try:
            done = auto_copies(self.cat, self.say)
            if done:
                self.save()
                self.refresh_maps()
                self.refresh_files()
            self.flush_log()
        except Exception as exc:
            self.say("Copies: %s" % exc)

    def report_gave_way(self):
        """An unofficial code that had to give way (its map got an official code ...) is told here, once."""
        new = [e for e in self.cat.get("ucode_log", []) if not e.get("seen")]
        if not new or getattr(self, "_told", False):
            return
        self._told = True
        for e in new:
            e["seen"] = True
        try:
            save_catalog(self.cat)
        except Exception:
            pass
        messagebox.showinfo("Rail Maps", "%d UNOFFICIAL code(s) gave way to an official one:\n\n%s\n\n(The Codes... window keeps this list.)" % (
            len(new), "\n".join(e.get("text", "") for e in new[:15]) + ("\n..." if len(new) > 15 else "")), parent=self.root)
        self._told = False
        self.refresh_maps()

    def auto_excel(self):
        """The Excel sheet is the source: when it is newer than the last import (or was never imported by this version), read it again
        by itself.  Only empty / not-hand-edited fields change (special runs included)."""
        path = self.settings.get("excel", "")
        try:
            mt = os.path.getmtime(path)
        except OSError:
            return
        if self.settings.get("excel_seen") != mt and not self.busy:
            def fn(say):
                import_excel(self.cat, path, say)
                rematch_unassigned(self.cat, say)
                steps_after_sheet_or_scan(self.cat, say)
                self.settings["excel_seen"] = mt
                save_json(SETTINGS_FILE, self.settings)
            self.run_job("Import Excel (sheet changed)", fn)

    def first_run_excel(self):
        if messagebox.askyesno("Rail Maps", "The map list is empty.\n\nRead the maps, codes, creators and details from the Excel "
                               "sheet now?\n(%s)" % self.settings["excel"], parent=self.root):
            self.do_excel()

    # ---- layout ----
    def _build_ui(self):
        root = self.root
        bar = tk.Frame(root)
        bar.pack(fill="x", padx=6, pady=(4, 0))
        bar2 = tk.Frame(root)
        bar2.pack(fill="x", padx=6, pady=(2, 4))
        self.job_buttons = []
        for row, text, cmd in ((bar, "Update everything", self.do_update_all),
                               (bar, "Scan folders", self.do_scan), (bar, "Import Excel", self.do_excel),
                               (bar, "Sources && folders...", self.do_settings), (bar, "Creators...", self.do_creators),
                               (bar, "Helpers...", self.do_helpers), (bar, "Info fields...", self.do_levels),
                               (bar, "Incoming info...", self.do_inbox),
                               (bar2, "Make upload folder", self.do_upload), (bar2, "Fetch Drive links", self.do_drive),
                               (bar2, "Build page", self.do_build), (bar2, "Upload page", self.do_upload_page),
                               (bar2, "Codes...", self.do_codes), (bar2, "Check LO...", self.do_check_lo),
                               (bar2, "Picture drop...", self.do_pdrop)):
            b = tk.Button(row, text=text.replace("&&", "&"), command=cmd, width=max(12, len(text) - 1))
            b.pack(side="left", padx=2)
            self.job_buttons.append(b)
        tk.Button(bar2, text="Open page", command=self.open_page, width=10).pack(side="left", padx=(10, 2))
        tk.Button(bar2, text="About page text...", command=self.edit_about_text, width=16).pack(side="left", padx=2)
        tk.Button(bar2, text="Examples folder...", command=self.open_examples_folder, width=16).pack(side="left", padx=2)
        tk.Button(bar, text="Notes", command=self.show_notes, width=7).pack(side="right", padx=2)
        tk.Button(bar, text="About", command=lambda: show_about(root, "Rail Maps", "A library of Railway Rivals maps", "\U0001F682"),
                  width=7).pack(side="right", padx=2)
        tk.Button(bar, text="Help", command=lambda: show_text_window(root, "Help", HELP_TEXT), width=7).pack(side="right", padx=2)
        self.nb = ttk.Notebook(root)
        self.nb.pack(fill="both", expand=True, padx=6, pady=(0, 6))
        self.tab_maps = tk.Frame(self.nb)
        self.tab_un = tk.Frame(self.nb)
        self.tab_log = tk.Frame(self.nb)
        self.tab_stats = tk.Frame(self.nb)
        self.tab_time = tk.Frame(self.nb)
        self.nb.add(self.tab_maps, text="  Maps  ")
        self.nb.add(self.tab_time, text="  Timeline  ")
        self.nb.add(self.tab_un, text="  Unassigned files  ")
        self.nb.add(self.tab_stats, text="  Statistics  ")
        self.nb.add(self.tab_log, text="  Log  ")
        self._build_maps_tab()
        self._build_timeline_tab()
        self._build_un_tab()
        self._build_stats_tab()
        self.nb.bind("<<NotebookTabChanged>>", self.on_tab_changed)
        self.log = new_text(self.tab_log, wrap="word", state="disabled")
        sb = tk.Scrollbar(self.tab_log, command=self.log.yview)
        self.log.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.log.pack(fill="both", expand=True)
        sbar = tk.Frame(root)
        sbar.pack(fill="x", padx=8)
        # Lars 2026-11-09: he uploaded an OLD page (not rebuilt after his changes) and saw "no difference" -> this tells him.
        self.lbl_page = tk.Label(sbar, anchor="e", text="", font=("Segoe UI", 9, "bold"))
        self.lbl_page.pack(side="right")
        self.status = tk.Label(sbar, anchor="w", text="")
        self.status.pack(side="left", fill="x", expand=True)
        self.update_page_label()

    def _build_maps_tab(self):
        pw = tk.PanedWindow(self.tab_maps, orient="horizontal", sashrelief="raised")
        pw.pack(fill="both", expand=True)
        left = tk.Frame(pw)
        right = tk.Frame(pw)
        pw.add(left, width=520)
        pw.add(right)
        top = tk.Frame(left)
        top.pack(fill="x", pady=3)
        tk.Label(top, text="Find").pack(side="left")
        self.find = new_entry(top, width=18)
        self.find.pack(side="left", padx=4)
        self.find.bind("<KeyRelease>", lambda e: self.refresh_maps())
        # Find by CODE only (Lars 2026-11-11): the text is matched against the START of the map codes, nothing else; several codes
        # separated by space or comma show all of them (AUS OS).  Enter selects the first map in the list.
        tk.Label(top, text="Code").pack(side="left", padx=(8, 0))
        self.find_code = new_entry(top, width=8)
        self.find_code.pack(side="left", padx=4)
        self.find_code.bind("<KeyRelease>", lambda e: self.refresh_maps())
        self.find_code.bind("<Return>", self.select_first_map)
        tk.Button(top, text="New map", command=self.new_map_click, width=9).pack(side="right")
        top2 = tk.Frame(left)                      # second row: the filters (one row was wider than the pane and hid New map)
        top2.pack(fill="x")
        self.only_files = tk.BooleanVar(value=False)
        tk.Checkbutton(top2, text="with files only", variable=self.only_files, command=self.refresh_maps).pack(side="left")
        self.only_wanted = tk.BooleanVar(value=False)
        tk.Checkbutton(top2, text="looking for improvement", variable=self.only_wanted, command=self.refresh_maps).pack(side="left")
        self.only_notdone = tk.BooleanVar(value=False)
        tk.Checkbutton(top2, text="not done yet", variable=self.only_notdone, command=self.refresh_maps).pack(side="left")
        # Lars 2026-11-14: two more "not done yet" style filters - maps with no CODE, and maps whose folder holds no jpg file
        top3 = tk.Frame(left)
        top3.pack(fill="x")
        self.only_nocode = tk.BooleanVar(value=False)
        tk.Checkbutton(top3, text="no code", variable=self.only_nocode, command=self.refresh_maps).pack(side="left")
        self.only_nojpg = tk.BooleanVar(value=False)
        tk.Checkbutton(top3, text="no jpg", variable=self.only_nojpg, command=self.refresh_maps).pack(side="left")
        tk.Label(top3, text="(only maps with NO jpg file)", fg="#666").pack(side="left", padx=4)
        cols = ("have", "code", "name", "by", "year", "orig", "issu", "json", "gaps", "done")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", selectmode="browse")
        for c, w, t in (("have", 46, "Have"), ("code", 50, "Code"), ("name", 200, "Map"), ("by", 50, "By"), ("year", 46, "Year"),
                        ("orig", 40, "Orig"), ("issu", 40, "Issu"), ("json", 40, "Json"), ("gaps", 70, "Gaps"), ("done", 50, "Done")):
            self.tree.heading(c, text=t)
            self.tree.column(c, width=w, anchor="w" if c == "name" else "center", stretch=(c == "name"))
        sb = tk.Scrollbar(left, command=self.tree.yview)
        self.tree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.tree.pack(fill="both", expand=True)
        self.tree.bind("<<TreeviewSelect>>", self.on_select_map)
        self.tree.bind("<Button-3>", self.map_menu)             # right-click a map: COMPLETELY MISSING, quality
        for tag, colour in list(QUALITY_COLOURS.items()) + list(DONE_COLOURS.items()):
            self.tree.tag_configure(tag, background=colour)
        # right: form + files
        form = tk.Frame(right)
        form.pack(fill="x", padx=6, pady=4)
        self.ents = {}
        for i, (k, lab) in enumerate(MAP_FIELDS):
            r, c = divmod(i, 2)
            tk.Label(form, text=lab, anchor="w", width=17).grid(row=r, column=c * 2, sticky="w", pady=1)
            e = new_entry(form, width=30)
            e.grid(row=r, column=c * 2 + 1, padx=(0, 10), pady=1)
            e.bind("<FocusOut>", lambda ev: self.commit())
            self.ents[k] = e
        self.hidden = tk.BooleanVar(value=False)
        r = (len(MAP_FIELDS) + 1) // 2
        tk.Checkbutton(form, text="Hide this map on the page", variable=self.hidden, command=self.commit).grid(
            row=r, column=1, sticky="w")
        tk.Button(form, text="Delete map", command=self.delete_map, width=12).grid(row=r, column=3, sticky="e")
        tk.Label(form, text="Quality of this map", anchor="w", width=17).grid(row=r + 1, column=0, sticky="w", pady=(4, 0))
        self.mq = tk.StringVar(value=QUALITY_LABEL[""])
        tk.OptionMenu(form, self.mq, *[v for _k, v in QUALITY]).grid(row=r + 1, column=1, sticky="w", pady=(4, 0))
        self.mq.trace_add("write", lambda *a: self.commit())
        tk.Label(form, text="My notes (private)", anchor="nw", width=17).grid(row=r + 2, column=0, sticky="nw", pady=(4, 0))
        self.notes_txt = new_text(form, width=84, height=3, wrap="word")
        self.notes_txt.grid(row=r + 2, column=1, columnspan=3, sticky="we", pady=(4, 0))
        self.notes_txt.bind("<FocusOut>", lambda ev: self.commit())
        # A second Details button in the middle of the program (Lars 2026-11-11); the one at the far right of the file buttons stays.
        tk.Button(form, text="Details...", command=self.file_details, width=14).grid(row=r + 3, column=1, sticky="w", pady=(4, 0))
        self.lbl_creator = tk.Label(right, anchor="w", text="")
        self.lbl_creator.pack(fill="x", padx=8)
        uf = tk.Frame(right)                       # the unofficial code of a map without an official one (clearly NOT official)
        uf.pack(fill="x", padx=8)
        self.lbl_uc = tk.Label(uf, anchor="w", text="", fg="#8a1c1c")
        self.lbl_uc.pack(side="left", fill="x", expand=True)
        tk.Button(uf, text="Unofficial code...", command=self.unofficial_menu, width=16).pack(side="right")
        gf = tk.Frame(right)
        gf.pack(fill="x", padx=8)
        self.lbl_gaps = tk.Label(gf, anchor="w", text="")
        self.lbl_gaps.pack(side="left", fill="x", expand=True)
        tk.Button(gf, text="Missing drafts...", command=self.do_gaps, width=16).pack(side="right")
        sf = tk.Frame(right)
        sf.pack(fill="x", padx=8)
        self.lbl_sr = tk.Label(sf, anchor="w", text="")
        self.lbl_sr.pack(side="left", fill="x", expand=True)
        tk.Button(sf, text="Special runs...", command=self.do_sruns, width=16).pack(side="right")
        self.lbl_inf = tk.Label(right, anchor="w", text="")
        self.lbl_inf.pack(fill="x", padx=8)
        fcols = ("file", "col", "draft", "date", "by", "helped", "tool", "look", "change", "copy", "conf", "done", "q", "note", "size", "drive")
        self.ftree = ttk.Treeview(right, columns=fcols, show="headings", selectmode="extended", height=12)
        for c, w, t in (("file", 200, "File"), ("col", 70, "Column"), ("draft", 45, "Draft"), ("date", 75, "Date"), ("by", 70, "By"),
                        ("helped", 70, "Helped by"), ("tool", 70, "Program"), ("look", 80, "Look"), ("change", 90, "What was done"),
                        ("copy", 110, "Copy of"), ("conf", 30, "OK"), ("done", 45, "Done"), ("q", 90, "Quality"), ("note", 140, "Note"), ("size", 55, "Size"), ("drive", 40, "Drive")):
            self.ftree.heading(c, text=t)
            self.ftree.column(c, width=w, anchor="w" if c in ("file", "by", "note", "change", "copy") else "center", stretch=(c in ("file", "note")))
        for tag, colour in list(QUALITY_COLOURS.items()) + [("done", DONE_COLOURS["done"])]:
            self.ftree.tag_configure(tag, background=colour)
        self.ftree.pack(fill="both", expand=True, padx=6, pady=4)
        self.ftree.bind("<Double-Button-1>", lambda e: self.file_open())
        # The button rows are packed BEFORE the (expanding) file list, at the bottom: in a small window the list shrinks instead of
        # the buttons disappearing (Details "did nothing" because the button was squeezed out of sight, 2026-11-09).
        fb = tk.Frame(right)
        fb2 = tk.Frame(right)
        fb3 = tk.Frame(right)
        fb4 = tk.Frame(right)
        fb3.pack(side="bottom", fill="x", padx=6, pady=(0, 6), before=self.ftree)
        fb4.pack(side="bottom", fill="x", padx=6, pady=(0, 2), before=self.ftree)
        # Lars 2026-11-16: copies = more photos / scans of the very same draft (not a new version)
        for text, cmd in (("Copy of...", self.file_copy_of), ("Not a copy", self.file_not_copy), ("Find copies...", self.do_copies)):
            tk.Button(fb4, text=text, command=cmd, width=14).pack(side="left", padx=1)
        tk.Label(fb4, text="a copy = another photo / scan of a draft that is already there; it does not count as a new version",
                 fg="#666").pack(side="left", padx=6)
        fb2.pack(side="bottom", fill="x", padx=6, pady=(0, 2), before=self.ftree)
        fb.pack(side="bottom", fill="x", padx=6, pady=(0, 2), before=self.ftree)
        for row, items in ((fb, (("Open", self.file_open), ("Details...", self.file_details), ("Rename...", self.file_rename),
                                 ("Mark quality...", self.file_mark), ("Confirm", self.file_confirm),
                                 ("Confirm all", self.file_confirm_all))),
                           (fb2, (("Add files...", self.file_add), ("Move to map...", self.file_move),
                                  ("To new map...", self.file_newmap), ("Remove from map", self.file_remove),
                                  ("Show in folder", self.file_folder), ("Done", self.file_done),
                                  ("Not done", self.file_notdone)))):
            for text, cmd in items:
                b = tk.Button(row, text=text, command=cmd, width=9 if text in ("Done", "Not done") else 14)
                if text == "Done":
                    b.configure(bg=GREEN_BTN, activebackground=GREEN_BTN)
                # Lars (2026-11-09): the map picture is usually open on the LEFT and covered Details -> Details, Done and Not done
                # sit at the far right (under the Size/Drive columns); Done is packed first so it is the right-most one.
                b.pack(side="right" if text in ("Details...", "Done", "Not done") else "left", padx=1)
                if text == "Details...":
                    self.details_btn = b
        # Lars 2026-11-14: "Remove from map" sends the file to Unassigned; this one takes it off the map AND hides it there
        tk.Button(fb3, text="Remove from program", command=self.file_remove_program, width=20).pack(side="left", padx=1)
        tk.Label(fb3, text="hides the file everywhere (not on Unassigned either) - 'Ignored files...' on the Unassigned tab brings it back",
                 fg="#666").pack(side="left", padx=6)

    def _build_stats_tab(self):
        """Statistics: designers / codes / overview.  Every column sorts on a click.  The same lists are written as web pages by Build page."""
        top = tk.Frame(self.tab_stats)
        top.pack(fill="x", pady=4, padx=6)
        self.stat_mode = tk.StringVar(value="designers")
        for key, lab in (("designers", "Designers"), ("helpers", "Helpers"), ("codes", "Codes (CODE / MAP)"), ("overview", "Overview")):
            tk.Radiobutton(top, text=lab, value=key, variable=self.stat_mode, indicatoron=False, width=20,
                           command=self.refresh_stats).pack(side="left", padx=2)
        self.stat_note = tk.Label(self.tab_stats, anchor="w", justify="left", wraplength=1100)
        self.stat_note.pack(fill="x", padx=8)
        self.stat_tree = SortableTree(self.tab_stats)
        self.stat_tree.frame.pack(fill="both", expand=True, padx=6, pady=4)

    def refresh_stats(self):
        mode = self.stat_mode.get()
        if mode == "designers":
            self.stat_note.configure(text="Base maps = maps the designer created.  Maps in all = base maps + maps with a later version "
                                          "by the designer.  Versions = original versions drawn (my own colourings are not counted).  "
                                          "Not sure = entries where the designer is only suspected (?).  Click a heading to sort.")
            self.stat_tree.set([c for c, _t in DESIGNER_COLS], designer_rows(self.cat),
                               [i for i, (_c, t) in enumerate(DESIGNER_COLS) if t == "n"], [60, 220, 80, 90, 80, 70, 70, 80, 90])
        elif mode == "helpers":
            self.stat_note.configure(text="Everybody who can be named as a helper: ALL creators plus the people only entered under Helpers... "
                                          "(those never show among the designers).  Click a heading to sort.")
            self.stat_tree.set([c for c, _t in HELPER_COLS], helper_rows(self.cat),
                               [i for i, (_c, t) in enumerate(HELPER_COLS) if t == "n"], [80, 260, 120, 100, 120])
        elif mode == "codes":
            rows = code_rows(self.cat)
            self.stat_note.configure(text="%d codes.  Click a heading to sort by Code or by Map.  The page codes.html has the same list." % len(rows))
            self.stat_tree.set(["Code", "Map"], rows, (), [120, 520])
        else:
            rows = []
            for title, hdr, drows, num in overview_sections(self.cat, with_done=True):
                for r in drows:
                    rows.append([title] + [str(x) for x in r])
            width = max(len(r) for r in rows) if rows else 3
            rows = [r + [""] * (width - len(r)) for r in rows]
            self.stat_note.configure(text="Key numbers, maps per decade and the maps with the most original versions.  "
                                          "(Done counts are only shown here, never on the web page.)")
            self.stat_tree.set(["Section", "What", "Number / code", "Versions"][:width], rows, (), [260, 360, 110, 80])

    def _build_un_tab(self):
        top = tk.Frame(self.tab_un)
        top.pack(fill="x", pady=4)
        top2 = tk.Frame(self.tab_un)
        top2.pack(fill="x", pady=(0, 4))
        for text, cmd in (("Open", self.un_open), ("Open suggested original", self.un_open_suggested),
                          ("Compare (open both)", lambda: self.un_open_suggested(True)),
                          ("Accept suggestion", self.un_accept), ("Assign to map...", self.un_assign),
                          ("Assign to map + go there...", lambda: self.un_assign(True))):
            tk.Button(top, text=text, command=cmd, width=24 if len(text) > 24 else (20 if len(text) > 16 else 16)).pack(side="left", padx=2)
        for text, cmd in (("New map from file", self.un_newmap), ("Ignore", self.un_ignore),
                          ("Try to place again", self.un_rematch), ("Make maps from all", self.un_makeall),
                          ("Place numbered files (Excel)", self.un_numbered), ("Ignored files...", self.do_ignored)):
            tk.Button(top2, text=text, command=cmd, width=max(len(text) - 1, 20) if len(text) > 16 else 16).pack(side="left", padx=2)
        self.un_label = tk.Label(top, text="")
        self.un_label.pack(side="left", padx=10)
        # Lars 2026-11-09: a search / filter box for the Unassigned files tab
        top3 = tk.Frame(self.tab_un)
        top3.pack(fill="x", pady=(0, 4))
        tk.Label(top3, text="Find").pack(side="left", padx=(2, 0))
        self.un_find = new_entry(top3, width=40)
        self.un_find.pack(side="left", padx=4)
        self.un_find.bind("<KeyRelease>", lambda e: self.refresh_unassigned())
        tk.Button(top3, text="Clear", width=8, command=lambda: (self.un_find.delete(0, "end"), self.refresh_unassigned())).pack(side="left")
        tk.Label(top3, text="(all words must match the file name, the name read from it, the suggested map, the column or 'From')",
                 fg="#666").pack(side="left", padx=8)
        # Lars 2026-11-09: Suggested map is the 2nd column and Name read from the file the 3rd
        self.untree = ttk.Treeview(self.tab_un, columns=("file", "sugg", "guess", "col", "size", "root"), show="headings",
                                   selectmode="extended")
        for c, w, t in (("file", 330, "File"), ("sugg", 300, "Suggested map"), ("guess", 200, "Name read from the file"),
                        ("col", 70, "Column"), ("size", 60, "Size"), ("root", 70, "From")):
            self.untree.heading(c, text=t)
            self.untree.column(c, width=w, anchor="w")
        self.untree.bind("<Double-Button-1>", lambda e: self.un_open())
        sb = tk.Scrollbar(self.tab_un, command=self.untree.yview)
        self.untree.configure(yscrollcommand=sb.set)
        sb.pack(side="right", fill="y")
        self.untree.pack(fill="both", expand=True)

    # ---- helpers ----
    def say(self, text):
        self.q.put(text)

    def flush_log(self):
        try:
            while True:
                t = self.q.get_nowait()
                if t is None:
                    continue
                self.log.configure(state="normal")
                self.log.insert("end", t + "\n")
                self.log.see("end")
                self.log.configure(state="disabled")
                self.status.configure(text=t[:160])
        except queue.Empty:
            pass

    def run_job(self, title, fn, after=None):
        if self.busy:
            return
        self.commit()
        self.busy = True
        for b in self.job_buttons:
            b.configure(state="disabled")
        self.nb.select(self.tab_log)
        self.say("--- %s ---" % title)
        result = {}

        def work():
            try:
                result["v"] = fn(self.say)
            except Exception as exc:
                self.say("ERROR: %s" % exc)
                self.say(traceback.format_exc().strip().splitlines()[-1])

        th = threading.Thread(target=work, daemon=True)
        th.start()

        def poll():
            self.flush_log()
            if th.is_alive():
                self.root.after(150, poll)
                return
            self.flush_log()
            self.busy = False
            for b in self.job_buttons:
                b.configure(state="normal")
            try:
                save_catalog(self.cat)
            except Exception as exc:
                self.say("Could not save the catalog: %s" % exc)
            self.refresh_maps()
            self.refresh_unassigned()
            self.flush_log()
            self.update_page_label()
            self.report_gave_way()
            if after:
                after(result.get("v"))
        poll()

    def save(self):
        try:
            save_catalog(self.cat)
        except Exception as exc:
            messagebox.showerror("Rail Maps", "Could not save: %s" % exc)
        self.update_page_label()
        if any(not e.get("seen") for e in self.cat.get("ucode_log", [])):
            self.root.after(150, self.report_gave_way)         # an unofficial code backed off: tell me (after the dialog that saved)

    def update_page_label(self):
        """Bottom right: is the web page built from the latest catalog?  (Build page stores the catalog's fingerprint, `catalog_stamp`, in the settings as `built_for`.)"""
        page = os.path.join(self.settings.get("out_dir", ""), "maps.html")
        if not os.path.isfile(page):
            self.lbl_page.configure(text="Page not built yet - press Build page", fg="#b00020")
        elif self.settings.get("built_for") != catalog_stamp(self.cat):
            self.lbl_page.configure(text="Page is OUT OF DATE - press Build page, then upload", fg="#b00020")
        else:
            self.lbl_page.configure(text="Page is up to date (built from the latest changes)", fg="#1b7f2a")

    def mark_built(self, started):
        """After Build page: remember which catalog state the page was made from (only when maps.html really was rewritten)."""
        page = os.path.join(self.settings.get("out_dir", ""), "maps.html")
        try:
            if os.path.getmtime(page) >= started - 1:
                self.settings["built_for"] = catalog_stamp(self.cat)
                save_json(SETTINGS_FILE, self.settings)
        except OSError:
            pass
        self.update_page_label()

    # ---- jobs ----
    def do_scan(self):
        def fn(say):
            n = scan_library(self.cat, self.settings, say)
            rematch_unassigned(self.cat, say)
            steps_after_sheet_or_scan(self.cat, say)
            return n
        self.run_job("Scan folders", fn, after=lambda v: self.check_missing_marks())

    def do_excel(self):
        path = self.settings.get("excel", "")
        if not os.path.isfile(path):
            path = filedialog.askopenfilename(parent=self.root, title="Excel sheet", filetypes=[("Excel", "*.xlsx *.xlsm")])
            if not path:
                return
            self.settings["excel"] = path
            save_json(SETTINGS_FILE, self.settings)

        def fn(say):
            import_excel(self.cat, path, say)
            rematch_unassigned(self.cat, say)
            steps_after_sheet_or_scan(self.cat, say)
            try:
                self.settings["excel_seen"] = os.path.getmtime(path)
                save_json(SETTINGS_FILE, self.settings)
            except OSError:
                pass
        self.run_job("Import Excel", fn, after=lambda v: self.check_missing_marks())

    def _incoming_after(self, new):
        """After an upload job: the Drive folder was checked; tell me about files that visitors have put there."""
        save_json(SETTINGS_FILE, self.settings)
        if new:
            messagebox.showinfo("Rail Maps", "%d NEW file(s) in the incoming Drive folder:\n\n%s%s" % (
                len(new), "\n".join(new[:15]), "\n..." if len(new) > 15 else ""), parent=self.root)

    def do_update_all(self):
        """Scan -> upload folder -> Drive links -> Build page -> Upload page, in one press (DEL 26d)."""
        if self.busy:
            return
        if not messagebox.askyesno("Rail Maps", "Update everything now?\n\nScan the folders, copy new files to the Google Drive upload folder, fetch the "
                                   "Drive links, build the page and upload it to the server - in that order.  It stops at the first step that fails.",
                                   parent=self.root):
            return

        def job(say):
            ok, text = update_pipeline(self.cat, self.settings, say)
            say(("DONE - " if ok else "STOPPED - ") + text)
            return ok
        self.run_job("Update everything", job, after=lambda _r: self.update_page_label())

    def do_upload(self):
        def job(say):
            make_upload_folder(self.cat, self.settings, say)
            return check_incoming(self.settings, say)
        self.run_job("Make upload folder", job, after=self._incoming_after)

    def do_drive(self):
        self.run_job("Fetch Drive links", lambda say: drive_fetch_ids(self.cat, self.settings, say))

    def do_build(self):
        started = time.time()
        self.run_job("Build page", lambda say: build_page(self.cat, self.settings, say), after=lambda _r: self.mark_built(started))

    def do_upload_page(self):
        """Upload page: if the page is older than the latest changes it offers to build it first (the old page was uploaded once and
        'nothing changed')."""
        if self.busy:
            return
        self.commit()
        self.update_page_label()
        page = os.path.join(self.settings.get("out_dir", ""), "maps.html")
        stale = (not os.path.isfile(page)) or self.settings.get("built_for") != catalog_stamp(self.cat)
        if stale:
            ans = messagebox.askyesnocancel("Rail Maps", "The page is OUT OF DATE (older than your latest changes).\n\n"
                                            "Build it first and then upload?   (No = upload the old page as it is.)", parent=self.root)
            if ans is None:
                return
            if ans:
                started = time.time()
                self.run_job("Build page", lambda say: build_page(self.cat, self.settings, say),
                             after=lambda _r: (self.mark_built(started), self.root.after(100, self._upload_now)))
                return
        self._upload_now()

    def _upload_now(self):
        def job(say):
            upload_page(self.settings, lambda t: say(t))
            return check_incoming(self.settings, say)
        self.run_job("Upload page", job, after=self._incoming_after)

    def open_page(self):
        p = os.path.join(self.settings["out_dir"], "maps.html")
        if os.path.isfile(p):
            open_path(p)
        else:
            messagebox.showinfo("Rail Maps", "Build the page first.")

    def edit_about_text(self):
        """Opens the text of the About page (about.html) in my text editor; the file is made from the built-in text the first time."""
        try:
            if not os.path.isfile(ABOUT_FILE):
                os.makedirs(os.path.dirname(ABOUT_FILE), exist_ok=True)
                with open(ABOUT_FILE, "w", encoding="utf-8", newline="\n") as fh:
                    fh.write(ABOUT_DEFAULT)
        except OSError as exc:
            messagebox.showerror("Rail Maps", "The About text file could not be made:\n%s" % exc, parent=self.root)
            return
        open_path(ABOUT_FILE)
        messagebox.showinfo("Rail Maps", "The About page text is opened in your text editor:\n%s\n\nSave it there, then press 'Build page' "
                            "(and 'Upload page') to put it on the web.\n\n# Heading, a blank line between paragraphs, '- ' for a bullet."
                            % ABOUT_FILE, parent=self.root)

    def open_examples_folder(self):
        """Opens the folder with the pictures of the Examples page (examples.html); made when missing."""
        try:
            os.makedirs(EXAMPLES_DIR, exist_ok=True)
        except OSError as exc:
            messagebox.showerror("Rail Maps", "The Examples folder could not be made:\n%s" % exc, parent=self.root)
            return
        open_path(EXAMPLES_DIR)
        messagebox.showinfo("Rail Maps", "Every picture in this folder is one example on the Examples page:\n%s\n\n"
                            "A text file with the same name (Name.txt) is its description: first line '# Title', then paragraphs.\n"
                            "intro.txt = the text at the top of the page.\n\nThen press 'Build page' and 'Upload page'." % EXAMPLES_DIR,
                            parent=self.root)

    def do_settings(self):
        settings_dialog(self.root, self.settings, self.settings_saved, self.cat)

    def settings_saved(self):
        save_json(SETTINGS_FILE, self.settings)
        for tag, colour in QUALITY_COLOURS.items():          # my own quality options may be new: give their rows a colour
            self.tree.tag_configure(tag, background=colour)
            self.ftree.tag_configure(tag, background=colour)

    def do_levels(self):
        levels_dialog(self.root, self.settings, lambda: save_json(SETTINGS_FILE, self.settings))

    def do_creators(self):
        creators_dialog(self.root, self.cat, self.save)
        self.show_creator()

    def do_helpers(self):
        helpers_dialog(self.root, self.cat, self.save)
        self.show_creator()

    def show_notes(self):
        if self.playertext is not None:
            try:
                if self.playertext.top.winfo_exists():
                    self.playertext.top.lift()
                    return
            except Exception:
                pass
        keys = ("show_playertext", "playertext_pos", "playertext_zoom", "playertext_sel")
        self.playertext = PlayerTextPopup(self.root, self.settings, keys, lambda: save_json(SETTINGS_FILE, self.settings), THEME,
                                          "Notes", PROGRAM_HF_DIR, lambda: {})

    # ---- maps list ----
    def refresh_maps(self):
        keep = self.cur["id"] if self.cur else None
        t = norm_key(self.find.get())
        codes = [c.upper() for c in re.split(r"[\s,;]+", self.find_code.get().strip()) if c]
        counts, fbm, live = {}, {}, {}
        for f in self.cat["files"]:
            if f.get("map") and not f.get("gone") and not f.get("ign"):
                live.setdefault(f["map"], []).append(f)           # for the Done column / row colour
            if included(f):
                counts.setdefault(f["map"], {}).setdefault(f["col"], 0)
                if not f.get("copy_of"):                          # a copy is no new version
                    counts[f["map"]][f["col"]] += 1
                fbm.setdefault(f["map"], []).append(f)
        self.tree.delete(*self.tree.get_children())
        shown = 0
        for m in sorted(self.cat["maps"], key=lambda x: norm_key(x["name"])):
            c = counts.get(m["id"], {})
            if self.only_files.get() and not c:
                continue
            if t and t not in norm_key(m["name"] + " " + m.get("code", "") + " " + str(m.get("ucode") or "") + " " + m.get("by", "")):
                continue
            if codes and not any((m.get("code") or "").upper().startswith(c) or ucode_label(m)[1:].startswith(c.lstrip("~")) and ucode_label(m)
                                 for c in codes):
                continue
            if self.only_nocode.get() and code_base(m.get("code")):
                continue
            if self.only_nojpg.get() and map_has_jpg(live.get(m["id"], [])):
                continue
            q = map_quality(self.cat, m, fbm.get(m["id"], []))
            if self.only_wanted.get() and not q:
                continue
            ds, nd, nf = map_done_state(self.cat, m, live.get(m["id"], []))
            if self.only_notdone.get() and ds == "done":
                continue
            tag = "done" if ds == "done" else (q or ds)          # done (green) > quality colour > partly done (orange)
            dtxt = "✔ all" if ds == "done" else ("%d/%d" % (nd, nf) if ds else "")
            shown_name = m["name"] + ("   [COMPLETELY MISSING]" if m.get("nothing") else "")
            if (m.get("help") or "").strip() or any((f.get("help") or "").strip() for f in live.get(m["id"], [])):
                shown_name += "   [HELP ME]"
            self.tree.insert("", "end", iid=m["id"], values=(m.get("have", ""), code_shown(m), shown_name, m.get("by", ""),
                                                             m.get("year", ""), c.get("orig", "") or "", c.get("issu", "") or "",
                                                             c.get("json", "") or "", gap_text(self.cat, m), dtxt),
                             tags=((tag,) if tag else ()))
            shown += 1
        if keep and self.tree.exists(keep):
            self.tree.selection_set(keep)
        self.status.configure(text="%d of %d maps, %d files in the catalog" % (shown, len(self.cat["maps"]), len(self.cat["files"])))

    def map_menu(self, event):
        """Right-click on a map in the list.  COMPLETELY MISSING = the map itself is missing (other files such as comments may exist): the page
        then shows the map with a red "COMPLETELY MISSING" mark in every view and in the "looking for improvement" list."""
        iid = self.tree.identify_row(event.y)
        if not iid:
            return
        self.tree.selection_set(iid)
        self.root.update_idletasks()
        m = next((x for x in self.cat["maps"] if x["id"] == iid), None)
        if m is None:
            return
        has_files = any(f.get("map") == iid and included(f) for f in self.cat["files"])
        menu = tk.Menu(self.root, tearoff=0)
        if m.get("nothing"):
            menu.add_command(label="Not completely missing any more (clear the mark)", command=lambda: self.set_nothing(m, False))
        else:
            # allowed even when the map has files (comments about the designer, places ...): it is the MAP that is missing
            menu.add_command(label="COMPLETELY MISSING  (the map itself is missing" + (" - other files such as comments stay)" if has_files else ")"),
                             command=lambda: self.set_nothing(m, True))
        menu.add_command(label="HELP ME - question for visitors about this map..." + ("  (change / clear)" if m.get("help") else ""),
                         command=lambda: self.ask_map_question(m))
        menu.add_separator()
        sub = tk.Menu(menu, tearoff=0)
        for k, v in QUALITY:
            sub.add_command(label=v, command=lambda k=k: self.set_map_quality(m, k))
        menu.add_cascade(label="Quality of this map", menu=sub)
        menu.tk_popup(event.x_root, event.y_root)

    def ask_map_question(self, m):
        """A question about the WHOLE map for the Help me page (a question about one version is set in Details...).  Empty = clear."""
        import tkinter.simpledialog as sd
        q = sd.askstring("Help me", "Question for visitors about '%s'  (empty = remove it):" % m["name"], initialvalue=m.get("help", ""),
                         parent=self.root)
        if q is None:
            return
        self.commit()
        if q.strip():
            m["help"] = q.strip()
        else:
            m.pop("help", None)
        self.save()
        self.refresh_maps()

    def check_missing_marks(self, ids=None):
        """A map marked COMPLETELY MISSING has got a file: ask whether the mark should go (Lars 2026-11-15).  Yes = removed;
        No = kept, and I am not asked again until the map gets even more files."""
        changed = False
        for m in marks_to_ask_about(self.cat, ids):
            n = picture_count(self.cat, m)
            if messagebox.askyesno("Rail Maps", "'%s' is marked COMPLETELY MISSING, but it now has %d file(s).\n\nRemove the COMPLETELY MISSING mark?\n"
                                   "(No = keep the mark; I will not ask again until the map gets more files.)" % (map_label(self.cat, m), n),
                                   parent=self.root):
                m.pop("nothing", None)
                m.pop("nothing_files", None)
            else:
                m["nothing_files"] = n
            changed = True
        if changed:
            self.save()
            self.refresh_maps()

    def set_nothing(self, m, on):
        self.commit()
        if on:
            m["nothing"] = True
            m["nothing_files"] = picture_count(self.cat, m)
        else:
            m.pop("nothing", None)
            m.pop("nothing_files", None)
        self.save()
        self.refresh_maps()

    def set_map_quality(self, m, key):
        self.commit()
        if self.cur is m:                       # the form's own menu must agree first, or the next commit() would write the old value back
            self.mq.set(QUALITY_LABEL.get(key, QUALITY_LABEL[""]))
        m["quality"] = key
        self.save()
        self.refresh_maps()

    def on_select_map(self, _e=None):
        sel = self.tree.selection()
        self.commit()
        if not sel:
            return
        self.cur = map_by_id(self.cat).get(sel[0])
        self.load_map()

    def load_map(self):
        m = self.cur
        for k, e in self.ents.items():
            e.delete(0, "end")
            e.insert(0, m.get(k, "") if m else "")
        self.hidden.set(bool(m and m.get("hidden")))
        self.notes_txt.delete("1.0", "end")
        if m:
            self.notes_txt.insert("1.0", m.get("notes", ""))
            self.mq.set(QUALITY_LABEL.get(m.get("quality", ""), QUALITY_LABEL[""]))
        self.show_creator()
        self.refresh_files()

    def show_creator(self):
        m = self.cur
        if not m:
            self.lbl_creator.configure(text="")
            self.lbl_uc.configure(text="")
            return
        names = names_of(self.cat, m.get("by", ""))
        self.lbl_creator.configure(text=("Creator: " + " + ".join(names)) if names else "")
        if code_base(m.get("code")):
            self.lbl_uc.configure(text="")
        elif ucode_label(m):
            self.lbl_uc.configure(text="Unofficial code %s  (NOT an official code - it gives way when the map gets a real one)" % ucode_label(m))
        else:
            self.lbl_uc.configure(text="This map has no official code.")

    def unofficial_menu(self):
        """The unofficial code of the selected map: suggest one, type one, or remove it."""
        m = self.cur
        if not m:
            return
        self.commit()
        if code_base(m.get("code")):
            messagebox.showinfo("Rail Maps", "'%s' has an official code (%s) - an unofficial code is only for maps without one." % (
                m["name"], m.get("code")), parent=self.root)
            return
        menu = tk.Menu(self.root, tearoff=0)
        menu.add_command(label="Suggest one for this map", command=lambda: self.ucode_set(m, suggest_ucodes(self.cat, renew=True, only=m)))
        menu.add_command(label="Type a code...", command=lambda: self.ucode_type(m))
        if m.get("ucode"):
            menu.add_command(label="Remove the unofficial code", command=lambda: self.ucode_set(m, None))
        menu.tk_popup(self.root.winfo_pointerx(), self.root.winfo_pointery())

    def ucode_set(self, m, proposals):
        if proposals is None:
            m.pop("ucode", None)
            m.pop("ucode_date", None)
        elif not proposals:
            messagebox.showinfo("Rail Maps", "No free code is left in the range %s-%s." % CODE_RANGE_DEFAULT, parent=self.root)
            return
        else:
            m["ucode"], m["ucode_date"] = proposals[0][1], time.strftime("%Y-%m-%d")
        self.save()
        self.show_creator()
        self.refresh_maps()

    def ucode_type(self, m):
        new = ask_text(self.root, "Unofficial code", "Unofficial code for %s  (empty = remove it):\n%s" % (m["name"], UCODE_NOTE),
                       str(m.get("ucode") or ""))
        if new is None:
            return
        new = new.strip().upper().lstrip("~")
        if new:
            why = check_ucode(self.cat, m, new)
            if why:
                messagebox.showwarning("Rail Maps", why, parent=self.root)
                return
        self.ucode_set(m, [(m, new)] if new else None)

    def do_codes(self):
        self.commit()
        codes_dialog(self.root, self.cat, self.save)
        self.show_creator()
        self.refresh_maps()

    def do_pdrop(self):
        """Picture drop...: codes for the PicturePerfect app's 'Rail map' mode + fetching what people sent (DEL 25b / 30d)."""
        self.commit()
        pdrop_dialog(self.root, self.settings, lambda: save_json(SETTINGS_FILE, self.settings), self.do_pdrop_fetch)

    def do_pdrop_fetch(self):
        def job(say):
            got = pdrop_pickup(self.cat, self.settings, say)
            save_json(SETTINGS_FILE, self.settings)
            return got

        def after(got):
            self.refresh_unassigned()
            if got:
                messagebox.showinfo("Rail Maps", "%d new picture(s) fetched from the PicturePerfect app.\n\nThey are on the 'Unassigned files' tab "
                                    "(give each one its map: Assign to map...)." % len(got), parent=self.root)
        self.run_job("Fetch pictures from the app", job, after=after)

    # ---- copies (Lars 2026-11-16) ----
    def do_copies(self):
        """Find copies...: marks the sure ones, then the dialog lists the unsure pairs and the copies that exist."""
        self.commit()
        done = auto_copies(self.cat, self.say)
        if done:
            self.save()
            self.flush_log()
        copies_dialog(self.root, self.cat, self.save)
        self.refresh_files()
        self.refresh_maps()
        self.refresh_timeline()

    def file_copy_of(self):
        """The selected file(s) are other photos of a draft that is already there: pick the main file."""
        files = [f for f in self.sel_files() if not f.get("gone")]
        if not files or not self.cur:
            messagebox.showinfo("Rail Maps", "Select the file(s) that are copies first, then press Copy of...", parent=self.root)
            return
        chosen = {f["path"].lower() for f in files}
        cands = [g for g in self.cat["files"] if g.get("map") == self.cur["id"] and g["path"].lower() not in chosen and not g.get("copy_of")
                 and not g.get("gone") and not g.get("ign") and g.get("col") == files[0].get("col") and files[0].get("col") in COPY_COLS]
        if not cands:
            messagebox.showinfo("Rail Maps", "There is no other file in the same column of this map to be the main file "
                                "(a copy must be on the same map and in the same column as its main file).", parent=self.root)
            return
        main = pick_file_dialog(self.root, "Copy of...", "Which file is the MAIN file?  The selected file(s) become copies of it - "
                                "another photo or scan of the same draft, not a new version.", cands)
        if main is None:
            return
        for f in files:
            if f.get("col") != main.get("col"):
                continue
            apply_copy(self.cat, main, f, "marked by hand")
            f["manual"] = True
        self.save()
        self.refresh_files()
        self.refresh_maps()
        self.refresh_timeline()

    def file_not_copy(self):
        files = [f for f in self.sel_files() if f.get("copy_of")]
        if not files:
            messagebox.showinfo("Rail Maps", "Select a file that is marked as a copy (the 'Copy of' column) first.", parent=self.root)
            return
        for f in files:
            unmark_copy(self.cat, f)
        self.save()
        self.refresh_files()
        self.refresh_maps()
        self.refresh_timeline()

    # ---- the Timeline tab (Lars 2026-11-16) ----
    def _build_timeline_tab(self):
        top = tk.Frame(self.tab_time)
        top.pack(fill="x", pady=4, padx=6)
        tk.Label(top, text="Find").pack(side="left")
        self.tl_find = new_entry(top, width=22)
        self.tl_find.pack(side="left", padx=4)
        self.tl_find.bind("<KeyRelease>", lambda e: self.refresh_timeline())
        self.tl_multi = tk.BooleanVar(value=False)
        tk.Checkbutton(top, text="only maps with 2 or more versions", variable=self.tl_multi, command=self.refresh_timeline).pack(side="left", padx=8)
        tk.Label(top, text="double-click a map to open it on the Maps tab", fg="#666").pack(side="left", padx=8)
        self.tl_note = tk.Label(self.tab_time, anchor="w", justify="left", wraplength=1180, fg="#444",
                                text="Oldest maps first (by the earliest date known for each map, shown in [ ]; maps with no date come last).  The first version of a map is on the left and the later drafts follow to the right; then who made each version and "
                                     "what was done to it; far right who designed the FIRST map and its code(s).  Copies (more photos of the same draft) "
                                     "are not counted: '+1 copy' is shown on the version.  Look: B&W = black & white, hand-coloured = coloured in "
                                     "afterwards, colour print = printed in colour.  Set it all in Details...")
        self.tl_note.pack(fill="x", padx=8)
        fr = tk.Frame(self.tab_time)
        fr.pack(fill="both", expand=True, padx=6, pady=4)
        self.tl_tree = ttk.Treeview(fr, show="headings", selectmode="browse")
        sbv = tk.Scrollbar(fr, command=self.tl_tree.yview)
        sbh = tk.Scrollbar(fr, orient="horizontal", command=self.tl_tree.xview)
        self.tl_tree.configure(yscrollcommand=sbv.set, xscrollcommand=sbh.set)
        sbv.pack(side="right", fill="y")
        sbh.pack(side="bottom", fill="x")
        self.tl_tree.pack(fill="both", expand=True)
        self.tl_tree.bind("<Double-Button-1>", self.timeline_open)
        self.tl_ids = {}

    def on_tab_changed(self, _e=None):
        sel = self.nb.select()
        if sel == str(self.tab_stats):
            self.refresh_stats()
        elif sel == str(self.tab_time):
            self.refresh_timeline()

    def refresh_timeline(self):
        if not hasattr(self, "tl_tree"):
            return
        k, rows = timeline_table(self.cat, self.tl_find.get(), 2 if self.tl_multi.get() else 1)
        names = ["Map"] + [("First" if i == 0 else ("Newest" if i == k - 1 and k > 1 else "Draft %d" % (i + 1))) for i in range(k)] \
            + [("Made by: " + ("first" if i == 0 else ("newest" if i == k - 1 and k > 1 else "draft %d" % (i + 1)))) for i in range(k)] \
            + ["First designed by", "Code(s)"]
        cols = ["c%d" % i for i in range(len(names))]
        self.tl_tree.delete(*self.tl_tree.get_children())
        self.tl_tree.configure(columns=cols)
        for c, n in zip(cols, names):
            self.tl_tree.heading(c, text=n)
            self.tl_tree.column(c, width=190 if c == "c0" else (150 if c in ("c%d" % (len(names) - 2), "c%d" % (len(names) - 1)) else 140),
                                anchor="w", stretch=False)
        self.tl_ids = {}
        for i, r in enumerate(rows):
            self.tl_ids[str(i)] = r[0]
            self.tl_tree.insert("", "end", iid=str(i), values=r[1:])

    def timeline_open(self, _e=None):
        sel = self.tl_tree.selection()
        if not sel or sel[0] not in self.tl_ids:
            return
        mid = self.tl_ids[sel[0]]
        self.nb.select(self.tab_maps)
        if not self.tree.exists(mid):                 # a filter hides it: clear the filters
            self.find.delete(0, "end")
            self.find_code.delete(0, "end")
            for v in (self.only_files, self.only_wanted, self.only_notdone, self.only_nocode, self.only_nojpg):
                v.set(False)
            self.refresh_maps()
        if self.tree.exists(mid):
            self.tree.selection_set(mid)
            self.tree.see(mid)

    def do_check_lo(self):
        self.commit()
        lo_dialog(self.root, self.cat, self.save)
        self.refresh_files()
        self.refresh_maps()

    def do_ignored(self):
        ignored_dialog(self.root, self.cat, self.save)
        self.refresh_unassigned()
        self.refresh_files()
        self.refresh_maps()

    def file_remove_program(self):
        """Takes the selected files off the map AND hides them (ign): they are not on the Unassigned tab either.  Ignored files... brings them back."""
        files = self.sel_files()
        if not files:
            messagebox.showinfo("Rail Maps", "Select the file(s) to remove from the program first.", parent=self.root)
            return
        if len(files) > 5 and not messagebox.askyesno("Rail Maps", "Remove %d files from the program?\n(They are hidden everywhere; "
                                                      "nothing on disk is touched.)" % len(files), parent=self.root):
            return
        for f in files:
            f["map"], f["ign"], f["ign_why"], f["manual"], f["pub"], f["drive_id"] = "", True, "removed from program", True, "", ""
        self.save()
        self.refresh_files()
        self.refresh_maps()
        self.refresh_unassigned()

    def commit(self):
        m = self.cur
        if not m:
            return
        changed = False
        for k, e in self.ents.items():
            v = e.get().strip()
            if k in ("by", "helped") and v:
                v = norm_designers(v, all_people(self.cat))   # "?" marks moved tight round the suspects; a typed name -> its code
                if v != e.get().strip():
                    e.delete(0, "end")
                    e.insert(0, v)
            if k == "name" and not v:
                continue
            if m.get(k, "") != v:
                m[k] = v
                changed = True
                if k not in m.setdefault("edited", []):
                    m["edited"].append(k)             # typed by hand: the Excel import will never overwrite it
        if bool(m.get("hidden")) != bool(self.hidden.get()):
            m["hidden"] = bool(self.hidden.get())
            changed = True
        notes = self.notes_txt.get("1.0", "end").strip()
        if m.get("notes", "") != notes:
            m["notes"] = notes
            changed = True
        qkey = next((k for k, v in QUALITY if v == self.mq.get()), m.get("quality", ""))
        if m.get("quality", "") != qkey:
            m["quality"] = qkey
            changed = True
        if changed:
            self.save()
            if self.tree.exists(m["id"]):
                self.tree.item(m["id"], values=(m.get("have", ""), code_shown(m), m["name"], m.get("by", ""), m.get("year", ""))
                               + tuple(self.tree.item(m["id"], "values")[5:]))
            self.show_creator()
            self.refresh_maps()

    def select_first_map(self, _event=None):
        kids = self.tree.get_children()
        if kids:
            self.tree.selection_set(kids[0])
            self.tree.see(kids[0])

    def new_map_click(self):
        m = new_map_dialog(self.root, self.cat)
        if m:
            self.save()
            self.find.delete(0, "end")
            self.find_code.delete(0, "end")
            self.refresh_maps()
            self.tree.selection_set(m["id"])
            self.tree.see(m["id"])

    def delete_map(self):
        m = self.cur
        if not m:
            return
        n = sum(1 for f in self.cat["files"] if f.get("map") == m["id"])
        if not messagebox.askyesno("Delete map", "Delete '%s' from the list?\n%d file(s) become unassigned.  Nothing on disk is touched."
                                   % (m["name"], n), parent=self.root):
            return
        for f in self.cat["files"]:
            if f.get("map") == m["id"]:
                f["map"] = ""
                f["manual"] = True
        self.cat["maps"].remove(m)
        self.cur = None
        self.save()
        self.load_map()
        self.refresh_maps()
        self.refresh_unassigned()

    # ---- files of the selected map ----
    def do_inbox(self):
        inbox_dialog(self.root, self.cat, lambda: (self.save(), self.load_map(), self.refresh_maps()))

    def do_sruns(self):
        if self.cur:
            self.commit()                                  # first take what is typed in the boxes, then the dialog may change S.R.
            sruns_dialog(self.root, self.cur, lambda: (self.save(), self.load_map(), self.refresh_maps()))

    def do_gaps(self):
        if self.cur:
            gaps_dialog(self.root, self.cat, self.cur, lambda: (self.save(), self.refresh_files(), self.refresh_maps()))

    def refresh_files(self):
        self.ftree.delete(*self.ftree.get_children())
        if not self.cur:
            self.lbl_gaps.configure(text="")
            self.lbl_sr.configure(text="")
            self.lbl_inf.configure(text="")
            return
        n_old = len(older_text(self.cat, self.cur).split("; ")) if older_text(self.cat, self.cur) else 0
        self.lbl_inf.configure(text=("Incoming info: %d added, %d older value(s) kept" % (len(self.cur.get("added", [])) + len(self.cur.get("reported", [])), n_old))
                               if (self.cur.get("added") or self.cur.get("reported") or n_old) else "")
        txt = sruns_text(self.cur)
        self.lbl_sr.configure(text=("Special runs: " + txt) if txt else "Special runs: not filled in")
        g = [x for x in draft_gaps(self.cat, self.cur) if x["state"] != "never"]
        self.lbl_gaps.configure(text=("Probably missing drafts: " + ", ".join(
            x["label"] + (" (looking)" if x["state"] == "looking" else "") for x in g)) if g else "")
        rows = [(i, f) for i, f in enumerate(self.cat["files"]) if f.get("map") == self.cur["id"]]
        order = {k: n for n, (k, _v) in enumerate(COLS)}
        rank = {id(f): n for n, f in enumerate(sort_versions([f for _i, f in rows]))}
        rows.sort(key=lambda p: (order.get(p[1]["col"], 99), rank[id(p[1])]))
        for i, f in rows:
            label = os.path.basename(f["path"]) + ("   (missing)" if f.get("gone") else "") + ("   (ignored)" if f.get("ign") else "")
            self.ftree.insert("", "end", iid=str(i), values=(label, COL_NAME.get(f["col"], f["col"]), f.get("draft", ""),
                                                             f.get("date") or ("(%s)" % f["fdate"] if f.get("fdate") else ""), f.get("by", ""),
                                                             f.get("helped", ""), f.get("tool", ""),
                                                             LOOK_SHORT.get(f.get("look", ""), ""), f.get("change", ""),
                                                             (os.path.basename(f["copy_of"]) if f.get("copy_of") else ""),
                                                             "yes" if f.get("confirmed") else "?",
                                                             "✔" if f.get("done") else "",
                                                             QUALITY_LABEL.get(f.get("quality", ""), "") if f.get("quality") else "",
                                                             f.get("note", ""), fmt_size(f.get("size")),
                                                             "yes" if f.get("drive_id") else ""),
                              tags=(("done",) if f.get("done") else ((f["quality"],) if f.get("quality") else ())))

    def sel_files(self, tree=None):
        tree = tree or self.ftree
        return [self.cat["files"][int(i)] for i in tree.selection()]

    def file_add(self):
        if not self.cur:
            return
        paths = filedialog.askopenfilenames(parent=self.root, title="Add files to " + self.cur["name"])
        copied, failed = [], []
        for p in paths:
            p = p.replace("/", "\\")
            if any(f["path"].lower() == p.lower() for f in self.cat["files"]):
                for f in self.cat["files"]:
                    if f["path"].lower() == p.lower():
                        f["map"], f["manual"], f["gone"], f["ign"] = self.cur["id"], True, False, False
                continue
            src = p
            try:                                   # copy into the import folder (the original stays where it is)
                p, did_copy = import_copy(src, self.settings)
            except OSError as exc:
                failed.append("%s: %s" % (os.path.basename(src), exc))
                continue
            if did_copy:
                copied.append(p)
            if any(f["path"].lower() == p.lower() for f in self.cat["files"]):      # the copy is already in the catalog
                for f in self.cat["files"]:
                    if f["path"].lower() == p.lower():
                        f["map"], f["manual"], f["gone"], f["ign"] = self.cur["id"], True, False, False
                continue
            col = classify(p, "original", "") or "extra"
            try:
                st = os.stat(p)
            except OSError:
                continue
            code, k, draft = parse_name(os.path.basename(p))
            self.cat["files"].append({"path": p, "root": "added", "col": col, "draft": draft, "map": self.cur["id"], "score": 1.0,
                                      "guess_key": k, "guess_code": code, "manual": True, "ign": False, "gone": False,
                                      "drive_id": "", "pub": "", "size": st.st_size, "mtime": int(st.st_mtime),
                                      "confirmed": True, "quality": "", "note": "", "tool": "", "by": guess_by(os.path.basename(p), self.cat["people"]),
                                      "date": date_from_name(os.path.basename(p)),
                                      "fdate": time.strftime("%Y-%m-%d", time.localtime(st.st_mtime)),
                                      "imported_from": src if p.lower() != src.lower() else ""})
        self.save()
        self.refresh_files()
        self.refresh_maps()
        self.check_missing_marks({self.cur["id"]})
        if copied:
            messagebox.showinfo("Rail Maps", "%d file(s) copied to:\n%s\n\nThe originals were not touched." %
                                (len(copied), self.settings.get("import_dir", "")), parent=self.root)
        if failed:
            messagebox.showerror("Rail Maps", "These files could NOT be copied (not added):\n\n" + "\n".join(failed), parent=self.root)

    def _set_col(self, files, col):
        for f in files:
            f["col"], f["manual"] = col, True
        self.save()
        self.refresh_files()

    def file_rename(self):
        files = self.sel_files()
        if len(files) != 1:
            messagebox.showinfo("Rail Maps", "Select ONE file to rename.", parent=self.root)
            return
        rec = files[0]
        new = ask_text(self.root, "Rename", "New name (the original is kept; a copy with the new name goes to 'renamed')",
                       os.path.basename(rec["path"]))
        if not new or new.strip() == os.path.basename(rec["path"]):
            return
        try:
            target = rename_file_copy(self.cat, rec, new.strip())
        except (OSError, ValueError) as exc:
            messagebox.showerror("Rail Maps", str(exc), parent=self.root)
            return
        self.save()
        self.refresh_files()
        messagebox.showinfo("Rail Maps", "Copied to:\n%s\n\nThe original is untouched and will not be counted twice." % target, parent=self.root)

    def file_details(self):
        files = self.sel_files()
        if not files:
            messagebox.showinfo("Rail Maps", "Select a file in the list first (click its row), then press Details.", parent=self.root)
            return
        if file_details_dialog(self.root, self.cat, files, getattr(self, "details_btn", None)):
            self.save()
            self.refresh_files()
            self.refresh_maps()

    def file_mark(self):
        files = self.sel_files()
        if not files:
            return
        menu = tk.Menu(self.root, tearoff=0)
        for k, v in QUALITY:
            if k != "missing":
                menu.add_command(label=v, command=lambda k=k: self._set_quality(files, k))
        menu.tk_popup(self.root.winfo_pointerx(), self.root.winfo_pointery())

    def _set_quality(self, files, key):
        for f in files:
            f["quality"] = key
        self.save()
        self.refresh_files()
        self.refresh_maps()

    def file_confirm(self):
        for f in self.sel_files():
            f["confirmed"], f["manual"] = True, True
        self.save()
        self.refresh_files()

    def file_done(self):
        """Selected files: I am finished with them (confirmed + done).  Nothing selected = all files of the map ask first."""
        files = self.sel_files()
        if not files and self.cur:
            todo = [f for f in self.cat["files"] if f.get("map") == self.cur["id"] and not f.get("gone") and not f.get("ign")]
            if not todo or not messagebox.askyesno("Rail Maps", "Mark ALL %d files of '%s' as done?" % (len(todo), self.cur["name"]),
                                                   parent=self.root):
                return
            files = todo
        for f in files:
            f["confirmed"], f["done"], f["manual"] = True, True, True
        self.save()
        self.refresh_files()
        self.refresh_maps()

    def file_notdone(self):
        for f in self.sel_files():
            f["done"] = False
        self.save()
        self.refresh_files()
        self.refresh_maps()

    def file_confirm_all(self):
        if not self.cur:
            return
        for f in self.cat["files"]:
            if f.get("map") == self.cur["id"] and not f.get("gone"):
                f["confirmed"], f["manual"] = True, True
        self.save()
        self.refresh_files()

    def file_move(self):
        files = self.sel_files()
        if not files:
            return
        m = pick_map(self.root, self.cat, "Move to which map?", files[0], files)
        if m:
            for f in files:
                f["map"], f["manual"], f["pub"], f["drive_id"] = m["id"], True, "", ""
            self.save()
            self.refresh_files()
            self.refresh_maps()
            self.refresh_unassigned()
            self.check_missing_marks({m["id"]})

    def file_newmap(self):
        """Split: the selected files are a DIFFERENT map that was filed under this one (two kinds of Nigeria) - they move to a new map."""
        files = self.sel_files()
        if not files or not self.cur:
            messagebox.showinfo("Rail Maps", "Select the files that are a different map.", parent=self.root)
            return
        name = ask_text(self.root, "New map from the selected files",
                        "These %d file(s) are a DIFFERENT map than '%s'.\nName of the new map (the same name is fine):" % (
                            len(files), self.cur["name"]), self.cur["name"])
        if not name or not name.strip():
            return
        code = ask_text(self.root, "New map", "Code of the new map (e.g. NG, or empty):", "")
        if code is None:
            return
        m = new_map(self.cat, name.strip(), code=code.strip().upper())
        for f in files:
            f["map"], f["manual"], f["pub"], f["drive_id"] = m["id"], True, "", ""
        self.save()
        self.refresh_maps()
        self.refresh_files()
        self.refresh_unassigned()
        messagebox.showinfo("Rail Maps", "%d file(s) moved to the new map '%s'.\nFind it in the list (type its name in the search box) "
                            "to fill in year, creator and the rest." % (len(files), map_label(self.cat, m)), parent=self.root)

    def file_remove(self):
        files = self.sel_files()
        for f in files:
            f["map"], f["manual"], f["pub"], f["drive_id"] = "", True, "", ""
        if files:
            self.save()
            self.refresh_files()
            self.refresh_maps()
            self.refresh_unassigned()

    def file_open(self):
        for f in self.sel_files()[:6]:                   # several selected = several windows, to compare
            open_map_file(f["path"])

    def file_folder(self):
        for f in self.sel_files()[:1]:
            open_path(os.path.dirname(f["path"]))

    # ---- unassigned ----
    def refresh_unassigned(self):
        words = self.un_find.get().lower().split() if getattr(self, "un_find", None) is not None else []
        keep = set(self.untree.selection())                    # typing in the filter must not lose the selection
        self.untree.delete(*self.untree.get_children())
        n = shown = 0
        cache = {}
        for i, f in enumerate(self.cat["files"]):
            if f.get("map") or f.get("ign") or f.get("gone"):
                continue
            n += 1
            key = (f.get("guess_key", ""), f.get("guess_code", ""))
            if key not in cache:
                cache[key] = suggest_maps(self.cat, key[0], key[1], n=1)
            sg = cache[key]
            if sg and sg[0][1] >= 0.4:
                tied = suggested_maps(self.cat, f)
                sugg = "%s  (%d%%)" % ("   OR   ".join(map_label(self.cat, m) for m in tied), round(sg[0][1] * 100))
            else:
                sugg = ""
            vals = (os.path.basename(f["path"]), sugg, "%s  [%s]" % (f.get("guess_key", ""), f.get("guess_code", "")),
                    COL_NAME.get(f["col"], f["col"]), fmt_size(f.get("size")), f.get("root", ""))
            if words:
                hay = " ".join(str(v) for v in vals).lower()
                if not all(w in hay for w in words):
                    continue
            shown += 1
            self.untree.insert("", "end", iid=str(i), values=vals)
        still = [k for k in keep if self.untree.exists(k)]
        if still:
            self.untree.selection_set(still)
        self.un_label.configure(text=("%d file(s) without a map" % n) if not words else "%d of %d file(s) without a map shown" % (shown, n))

    def un_open(self):
        for f in self.sel_files(self.untree)[:6]:
            open_map_file(f["path"])             # DefaultHub decides: pictures -> SeeView (own window each), PDF -> PDFull

    def un_open_suggested(self, with_file=False):
        """Open the newest original of the suggested map (both maps when two have the same name) - and the file itself with
        `with_file` - each in its own window, so they can be compared side by side."""
        files = self.sel_files(self.untree)[:1]
        if not files:
            messagebox.showinfo("Rail Maps", "Select a file first.", parent=self.root)
            return
        f = files[0]
        maps = suggested_maps(self.cat, f)
        if not maps:
            messagebox.showinfo("Rail Maps", "There is no suggestion for this file.  Use 'Assign to map...' - its dialog can open "
                                "the original of any map.", parent=self.root)
            return
        if with_file:
            open_map_file(f["path"])
        shown = 0
        for m in maps:
            o = newest_original_of(self.cat, m["id"])
            if o:
                open_map_file(o["path"])
                shown += 1
        if not shown:
            messagebox.showinfo("Rail Maps", "'%s' has no picture file to compare with yet." % map_label(self.cat, maps[0]), parent=self.root)

    def un_accept(self):
        files = self.sel_files(self.untree)
        n = 0
        ambiguous = 0
        for f in files:
            tied = suggested_maps(self.cat, f)
            if len(tied) > 1:
                ambiguous += 1                    # two maps with the same name (Nigeria): I must choose, not the program
            elif tied:
                f["map"], f["manual"], f["confirmed"] = tied[0]["id"], True, True
                n += 1
        if ambiguous:
            messagebox.showinfo("Rail Maps", "%d file(s) fit TWO maps with the same name - not accepted.  Use 'Compare (open both)' "
                                "to see which one it is, then 'Assign to map...'." % ambiguous, parent=self.root)
        if n:
            self.save()
            self.refresh_unassigned()
            self.refresh_maps()
            self.check_missing_marks()
        elif not ambiguous:
            messagebox.showinfo("Rail Maps", "No suggestion for the selected file(s).  Use 'Assign to map...'.", parent=self.root)

    def un_assign(self, go=False):
        """Assign the selected files to a map.  With `go` (button 'Assign to map + go there...', Lars 2026-11-21) the program then jumps
        to the Maps tab, selects that map and selects the assigned files in its file list - no scrolling to find the place."""
        files = self.sel_files(self.untree)
        if not files:
            return
        m = pick_map(self.root, self.cat, "Assign to which map?", files[0], files)
        if m:
            for f in files:
                f["map"], f["manual"] = m["id"], True
            self.save()
            self.refresh_unassigned()
            self.refresh_maps()
            self.check_missing_marks({m["id"]})
            if go:
                self.goto_map_files(m["id"], files)

    def goto_map_files(self, mid, files):
        """Show map `mid` on the Maps tab (clearing the filters if one hides it) and select `files` in its file list."""
        self.nb.select(self.tab_maps)
        if not self.tree.exists(mid):                 # a filter hides the map: clear the filters
            self.find.delete(0, "end")
            self.find_code.delete(0, "end")
            for v in (self.only_files, self.only_wanted, self.only_notdone, self.only_nocode, self.only_nojpg):
                v.set(False)
            self.refresh_maps()
        if not self.tree.exists(mid):
            return
        self.tree.selection_set(mid)
        self.tree.see(mid)
        self.root.update()                            # let the list's select event load the map + its file list FIRST (it rebuilds the list)
        if not self.cur or self.cur["id"] != mid:
            self.on_select_map()
        ids = [str(i) for i, f in enumerate(self.cat["files"]) if any(f is g for g in files)]
        ids = [i for i in ids if self.ftree.exists(i)]
        if ids:
            self.ftree.selection_set(ids)
            self.ftree.see(ids[0])
            self.ftree.focus_set()

    def un_newmap(self):
        files = self.sel_files(self.untree)
        if not files:
            return
        name = ask_text(self.root, "New map", "Name of the new map:", string.capwords(files[0].get("guess_key", "")))
        if name and name.strip():
            m = new_map(self.cat, name.strip(), code=files[0].get("guess_code", ""))
            for f in files:
                f["map"], f["manual"], f["confirmed"] = m["id"], True, True
            self.save()
            self.refresh_unassigned()
            self.refresh_maps()

    def un_ignore(self):
        for f in self.sel_files(self.untree):
            f["ign"] = True
        self.save()
        self.refresh_unassigned()

    def un_rematch(self):
        rematch_unassigned(self.cat, self.say)
        self.flush_log()
        self.save()
        self.refresh_unassigned()
        self.refresh_maps()

    def un_numbered(self):
        """Place the files that are only a number (0016.comments2 ...) through the sheet's NR / MAP columns."""
        path = self.settings.get("excel", "")
        if not os.path.isfile(path) and not self.cat.get("numbers"):
            path = filedialog.askopenfilename(parent=self.root, title="Excel sheet (the number -> map name list)",
                                              filetypes=[("Excel", "*.xlsx *.xlsm")])
            if not path:
                return
            self.settings["excel"] = path
            save_json(SETTINGS_FILE, self.settings)
        self.run_job("Place numbered files", lambda say: place_numbered_files(self.cat, path, say),
                     after=lambda n: (self.nb.select(self.tab_un), messagebox.showinfo(
                         "Rail Maps", "%s file(s) placed through the sheet's numbers.\n\nThe Log tab says which maps were made and which "
                         "numbers are not in the sheet." % (n if n is not None else 0), parent=self.root)))

    def un_makeall(self):
        if messagebox.askyesno("Make maps", "Make a new map for every group of files without a map?", parent=self.root):
            make_maps_from_unassigned(self.cat, self.say)
            self.flush_log()
            self.save()
            self.refresh_unassigned()
            self.refresh_maps()

    def on_close(self):
        self.commit()
        try:
            if self.playertext is not None:
                self.playertext.save_now()
        except Exception:
            pass
        self.save()
        try:
            zoomed = self.root.state() == "zoomed"
            if zoomed:
                self.root.state("normal")
                self.root.update_idletasks()
            self.settings["window"] = {"w": self.root.winfo_width(), "h": self.root.winfo_height(),
                                       "x": self.root.winfo_x(), "y": self.root.winfo_y(), "zoomed": zoomed}
        except Exception:
            pass
        save_json(SETTINGS_FILE, self.settings)
        self.root.destroy()


# *************** DEL 99 - MAIN *****************
def main():
    os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
    _set_app_id()
    root = tk.Tk()
    App(root)
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()


if __name__ == "__main__":
    main()


