# Hornfolding - Folding a horn / tapped-horn channel in a rectangular box
# Copyright (C) 2026 Tobias McFadden
# Contact: Tobias@McFadden.de
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""
Hornfolding_v0.69.py  -  Folding a horn / tapped-horn channel in a rectangular box
===================================================================================

Purpose
-------
Calculates how a horn channel of constant width and linearly growing height
is folded into an enclosure of given size, and provides the areas
S1..S5 and path lengths for Hornresp.

UNITS (important!)
------------------
The script works unit-free. It only has to be consistent:
    Lengths in  UNIT        (default: cm)
    Areas in    UNIT²       (default: cm²)
To work in mm, change UNIT below to "mm" and then enter
all lengths in mm and all areas in mm² (e.g. S2 = 13000 instead of 130).
Typical mistake: lengths in mm, area in cm² -> the channel becomes absurdly flat.

Inputs
------
WoodThickness (a)     Wood thickness
BraceWidth            Width of the bracing in the enclosure
Width, Height, Depth  Outer dimensions of the enclosure
The horn values are asked for in the order of Hornresp: S1, S2, S3 (or the slope), L23, S4, S5; then DriverOffset.
S1                    Area at the closed end behind the driver. 'auto' = same slope throughout
                      S1-S2-S3. With a kink in board a S1 is the Hornresp value (the real S1 follows from the volume);
                      without a kink (0.69) a specified S1 has no effect: the Hornresp S1 follows from the built volume.
S2                    Area at the driver (starting value)
Slope b               Height increase of the channel per path length
                      (0.1 = 10 cm height per metre of path)
  Mode 1: b is calculated from S3 and the length L23 (S2 to S3; earlier name "Con")
  Mode 2: b is entered directly
Slope after S3 b'     Slope of the channel between S3 and S4. 'auto' (Enter) = calculated from the box:
                      b' is chosen so that the area from S3 to S4 grows uniformly
                      (linear area, Hornresp Par) with b': S4 = S3 + b1*b'*Path(S3-S4).
                      A number (also negative) overrides this.
S3Position            1-7 or auto (a); with auto: among the positions whose length S2-S3
                      (L23) deviates by at most 10 % from the desired L23, the one with the
                      smallest area shortfall (actual below idealised cone) is chosen.
                      If no position is within 10 %, the closest calculable position is used.
S4                    optional: the area S4 desired in Hornresp (number or free). For comparison
                      only: S4 results from the box and is compared with the desired value.
S5                    optional: the area S5 desired in Hornresp (number or auto), comparison only.
DriverOffset          Distance of S2 + S4 (the driver centre) from the left outer edge; defines the
                      driver position. The actual path length S4-S5 is calculated from the
                      resulting geometry.
Kink                  y/n: draw board a with a kink at S2 if S1 deviates from the continuous
                      slope (default y)

S3 positions (slope change only where a board ends)
-------------------------------------------------------------
  1  entry of bend 3  (C3, top left, before the shaft)
  2  exit of bend 3   (C3, start of the shaft)
  3  entry of bend 4  (C4, end of the shaft)
  4  exit of bend 4   (start of the middle channel between c and d)
  5  entry of bend 5  (C5)
  6  exit of bend 5   (C5, start of the short descent between d and b)
  7  entry of bend 6  (C6, into the chamber)
Since 0.52 the positions are numbered in flow order (the former 5 'exit of bend 5' is now 6).
From S3 onwards the boards are cut so that the channel grows with the slope b': c at its left end
(positions 1, 2), d at its right end (positions 1-6). The cut list gives gross length and end angles.

Input file (optional, for the test phase)
------------------------------------------
On every run the script writes all inputs to 'Hornfolding_Input.txt' (next to the
script) and reads them back in on the next run: each value is accepted with Enter
or overwritten by typing. On request (y) all values are
accepted without prompting. With 'python Hornfolding_v0.69.py my_file.txt' a different file is read
(without prompting). Format:
    Name = value        # comment        (comma or point as decimal separator)
Names: WoodThickness, BraceWidth, Width, Height, Depth, S1 (number or 'auto'), S2, Mode,
Slope (Mode 2 only), S3 and L23 (Mode 1 only; L23 also with S3Position = auto), S4 and S5 (number or
'auto' = no target; comparison values), DriverOffset, Slope2 (b': number or 'auto'), S3Position (1-7 or auto),
DriverDiameter, MagnetDiameter and DriverDepth (number or
'auto' = unknown; fit checks; MagnetDiameter auto = 0.5 x DriverDiameter), HornrespFile (optional exported Hornresp text file), Kink (y/n), SVG (y/n).

Command line
------------
    python Hornfolding_v0.69.py [input_file] [--batch] [--output-dir DIR] [--no-save-input]
input_file          input file (Name = value) or an exported Hornresp single-simulation text file
--batch             use the saved values without prompting (error if a required value is missing)
--output-dir DIR    directory for the generated files (SVG, cut list, saved input, Hornresp result)
--no-save-input     do not save the inputs of this run

Derived quantities
------------------
b1        Net width of the channel        = Width - BraceWidth - 2a
W2        Width of the S2 chord           = S2 / b1   (chord perpendicular to the centreline)
W(s)      Channel width at path s         = W2 + b*s  (s = path along the centreline from S2),
                                           after S3: W(s3) + b'*(s - s3)

Calculation principle (from 0.50: geometry first, everything along the centreline)
-----------------------------------------------------------------------
Straight boards are exact rectangles, inclined against each other by the wedge angle psi = 2*atan(b/2), so that
the channel width on straight sections grows exactly linearly with the centreline path. Each bend is solved
in turn (bend 1 to 5) via the position of its inner corner so that the exit width matches the law
W(s); the path in the bend is the fan construction (hand construction, empirically confirmed at 90 degrees,
the geometric generalisation for other angles). The entry width then matches by itself
(check value in the output). All outputs (S2-S5, L23, path lengths, cutting list) come from this geometry.

Model note (0.64): the folding always assumes parallel side walls, i.e. a LINEAR area law = Hornresp flare type "Par"
(see Hornresp help: Par is for a rectangular segment with two parallel and two sloping sides, area linear with length).
Never use "Con" in Hornresp for these horns. The script warns when an imported Hornresp file contains Con segments.
The length S2-S3 input is called L23 (Hornresp name); the old name "Con" is still read.

Mouth (0.67): the front-wall boards D1 and D2 are bevelled so that the slopes of board a (a1 with a kink) and of board d
continue to the outer face of the wall; S5 is the vertical distance between these bevelled edges at the outer face (x = 0).

Depth check (0.68): DriverDepth is compared with the free depth from the driver centre along the board normal to the opposite
wall (underside of d; behind the end of d its end face or the ceiling). With MagnetDiameter (auto = 0.5 x DriverDiameter) the
free depth is also checked at the magnet edges; the sign of the wall inclination delta (tan(delta) = -dh/du, u along board a)
follows from the geometry. With a kink in board a the centreline of the chamber S4-S5 is a polyline (kink at the cross-section
through the kink point K_up).

Hornresp areas S1 and S5 (0.69): every Hornresp segment should reproduce the BUILT air volume. S1 = 2*V12/L12 - S2
(with a kink the real S1 is solved so that this equals the specified S1; without a kink a specified S1 has no effect).
S5 is the mean of the volume-equal S5 (2*V45/L45 - S4) and the inertance-equal S5 (same integral ds/A as the built
chamber); a note appears if the two differ by more than 2 %. S4 inside bend 6 uses the built mouth area S5.

Version history: see CHANGELOG.md.   Licence: see the header at the top of this file and the file License.md.
"""

import argparse
import math
import os
import sys
import tempfile
from html import escape
from pathlib import Path

VERSION = "0.69"
UNIT = "cm"          # "cm" or "mm"; all inputs must be given in this unit
if UNIT not in ("cm", "mm"):
    raise ValueError("UNIT must be 'cm' or 'mm'.")
CM = 10.0 if UNIT == "mm" else 1.0   # 1 cm expressed in the chosen unit

# --- Tuning constants (numerical search and checks; none of them is a model parameter of the horn) ------------------
SEARCH_STEP = 0.1 * CM       # Grid only for finding the sign change (no longer for the result)
SEARCH_STEP_BEND = 0.25 * CM # same for the bend parameter in build() (length along the board, in UNIT)
BEND_MIN = 0.5 * CM          # smallest bend parameter tried (distance of an inner corner from the previous one)
BEND_MARGIN = 0.5 * CM         # margin kept to the box wall when the search range of a bend is limited
BOX_TOL = 1e-6 * CM           # tolerance when testing that a point lies inside the box
RATIO_WARN = 1.33       # warning if the cross-section ratio exit/entry in a bend is larger (Brian Steele)
COS_PSI_MIN = 0.17            # largest wedge angle about 80 deg; beyond that the search limits (division by cos) become meaningless
B_MIN, B_MAX, B_STEP = -0.3, 1.0, 0.02     # search range for b' (not a model limit)


class FoldingError(Exception):
    """Raised when a fold has no solution."""


# ---------------------------------------------------------------------------
# Input
# ---------------------------------------------------------------------------
INPUT_FILE = "Hornfolding_Input.txt"   # next to the script; rewritten at every run

KNOWN_KEYS = {"wood_thickness", "brace_width", "width", "height", "depth",
              "driver_offset", "s1", "s2", "mode", "slope", "s3", "l23", "svg",
              "slope2", "s3position", "s4", "kink", "driver_diameter", "magnet_diameter", "driver_depth", "hornresp", "s5"}

# Input names (normalised: lower case, no spaces/underscores) -> internal keys.
# The former German names are still accepted; L23 is the Hornresp name of the length S2-S3 (old name: "Con").
LEGACY_NAMES = {"woodthickness": "wood_thickness", "bracewidth": "brace_width", "driveroffset": "driver_offset",
                "driverdiameter": "driver_diameter", "magnetdiameter": "magnet_diameter", "driverdepth": "driver_depth", "hornrespfile": "hornresp",
                "holzstaerke": "wood_thickness", "verstrebungsbreite": "brace_width", "breite": "width",
                "hoehe": "height", "tiefe": "depth", "anfangslaenge": "driver_offset", "modus": "mode",
                "steigung": "slope", "steigung2": "slope2", "knick": "kink",
                "treiberdurchmesser": "driver_diameter", "treibertiefe": "driver_depth", "con": "l23"}


def _norm(name):
    """Normalise a key name: lower case, no spaces/underscores/hyphens, umlauts -> ae etc."""
    n = name.strip().lower()
    for old, new in (("ä", "ae"), ("ö", "oe"), ("ü", "ue"), ("ß", "ss")):
        n = n.replace(old, new)
    for char in (" ", "_", "-"):
        n = n.replace(char, "")
    n = LEGACY_NAMES.get(n, n)
    return {"a": "wood_thickness"}.get(n, n)


def load_input_file(filepath):
    """Reads 'name = value' lines ('#' starts a comment). Returns {key: text}."""
    values = {}
    with open(filepath, "rb") as fh:
        raw = fh.read()
    try:
        text = raw.decode("utf-8-sig")
    except UnicodeDecodeError:
        text = raw.decode("cp1252", errors="replace")          # file saved as ANSI (older Windows editors)
    for nr, line in enumerate(text.splitlines(), 1):
        line = line.split("#", 1)[0].strip()
        if not line:
            continue
        if "=" not in line:
            raise FoldingError(f"Input file, line {nr}: expected 'name = value', found: '{line}'")
        name, value = line.split("=", 1)
        key = _norm(name)
        if key in values:      # aliases such as Width/Breite must not silently overwrite each other
            raise FoldingError(f"Input file, line {nr}: duplicate entry '{name.strip()}'.")
        values[key] = value.strip()
    unknown = sorted(k for k in values if k not in KNOWN_KEYS)
    if unknown:
        print("WARNING: Unknown entries in the input file (typo?): "
              + ", ".join(unknown))
    return values


def p_number(minimum=None, strict=False, words=None):
    """Parser for numbers; words: {word: value}, e.g. {'auto': 12.0}; 'a' counts as 'auto'."""
    words = words or {}

    def parse(text):
        s = text.strip().lower()
        if s == "a" and "auto" in words:
            s = "auto"
        if s in words:
            return words[s], s
        try:
            w = float(s.replace(",", "."))
        except ValueError:
            extra = "".join(f" or '{k}'" for k in words)
            raise ValueError(f"Please enter a number{extra}.")
        if not math.isfinite(w):
            raise ValueError("Please enter a finite number.")
        if minimum is not None and ((strict and w <= minimum) or (not strict and w < minimum)):
            raise ValueError(f"The value must be {'greater than' if strict else 'at least'} {minimum}.")
        return w, w
    return parse


def p_choice(allowed, alias=None):
    alias = alias or {}

    def parse(text):
        s = alias.get(text.strip().lower(), text.strip().lower())
        if s not in allowed:
            raise ValueError("Allowed: " + ", ".join(allowed))
        return s, s
    return parse


def p_yes_no(text):
    s = text.strip().lower()
    if s in ("y", "yes", "j", "ja"):
        return True, "y"
    if s in ("n", "no", "nein"):
        return False, "n"
    raise ValueError("Please enter y or n.")


class InputDialog:
    """Asks for every value; Enter accepts the value from the input file (or the default)."""

    def __init__(self, values=None, fast=False):
        self.values = dict(values or {})
        self.fast = fast     # True: take values from the file without asking
        self.used = {}          # key -> value (for saving)

    def ask(self, key, label, parse, default=None):
        raw = self.values.get(key, default)
        from_file = key in self.values
        while True:
            if self.fast:
                if raw is None or not str(raw).strip():
                    raise FoldingError(f"Input file: missing required value '{key}' ({label}).")
                typed = ""
            else:
                hint = f" (Enter = {raw})" if raw is not None else ""
                typed = input(f"{label}{hint}: ").strip()
            text = typed if typed else raw
            if text is None or not str(text).strip():
                print("  Please enter a value.")
                continue
            try:
                value, stored = parse(str(text))
            except ValueError as error:
                if self.fast and not typed:
                    raise FoldingError(f"Input file: {label}: '{text}' - {error}")
                print(f"  {error}")
                continue
            if self.fast and not typed:
                print(f"{label}: {text}   ({'from file' if from_file else 'default'})")
            self.used[key] = stored
            return value


def accept_all():
    while True:
        answer = input("Accept all values from the file without asking? "
                        "(y = yes, Enter = go through them one by one and change): ").strip().lower()
        if answer in ("", "n", "no", "nein"):
            return False
        if answer in ("y", "yes", "j", "ja"):
            return True
        print("  Please enter y or Enter.")


def _write_atomic(filepath, data):
    """Write completely to a temporary file first, then replace: the old file survives any error."""
    target = Path(filepath).resolve()
    temp = None
    try:
        with tempfile.NamedTemporaryFile(dir=target.parent, prefix=target.name + ".", suffix=".tmp", delete=False) as fh:
            temp = Path(fh.name)
            fh.write(data)
            fh.flush()
            os.fsync(fh.fileno())
        os.replace(temp, target)
    finally:
        if temp is not None:
            temp.unlink(missing_ok=True)


def save_inputs(values, filepath):
    """Writes all inputs as an input file (read again at the next run)."""
    def fmt(w):
        return w if isinstance(w, str) else f"{w:.10g}".replace(".", ",")
    fields = [("WoodThickness", "wood_thickness", ""), ("BraceWidth", "brace_width", ""),
              ("Width", "width", ""), ("Height", "height", ""), ("Depth", "depth", ""),
              ("S1", "s1", "number or auto (= same slope throughout)"),
              ("S2", "s2", "area at the driver"),
              ("Mode", "mode", "1 = specify S3 and L23, 2 = specify the slope"),
              ("Slope", "slope", "mode 2 only"),
              ("S3", "s3", "mode 1 only"), ("L23", "l23", "length S2-S3 (old name: Con); mode 1 only (and with S3Position = auto)"),
              ("S4", "s4", "S4 target from Hornresp (comparison only), number or auto (= no target)"),
              ("S5", "s5", "S5 target from Hornresp (comparison only), number or auto (= no target)"),
              ("DriverOffset", "driver_offset", "distance of S2 + S4 (the driver centre) from the left outer edge"),
              ("Slope2", "slope2", "b' after S3: auto (= calculated from the box) or a number, also negative"),
              ("S3Position", "s3position", "1-7 or auto (chosen from the desired L23)"),
              ("HornrespFile", "hornresp", "exported Hornresp text file (optional); S1-S5, L23 are read from it"),
              ("DriverDiameter", "driver_diameter", "gross (frame) diameter, auto = unknown"),
              ("MagnetDiameter", "magnet_diameter", "magnet/motor diameter for the depth check, auto = 0.5 x DriverDiameter"),
              ("DriverDepth", "driver_depth", "mounting depth incl. magnet at the S4 side, auto = unknown"),
              ("Kink", "kink", "board a with a kink (S1 then = Hornresp value): y or n"),
              ("SVG", "svg", "create the drawing: y or n")]
    lines = ["# Hornfolding - inputs of the last run (overwritten automatically at every run)",
              f"# Lengths in {UNIT}, areas in {UNIT}²; comma or point as decimal separator.", ""]
    for name, key, comment in fields:
        if key in values:
            line = f"{name} = {fmt(values[key])}"
            lines.append(f"{line:<30}# {comment}" if comment else line)
    _write_atomic(filepath, ("\n".join(lines) + "\n").encode("utf-8"))


# ---------------------------------------------------------------------------
# Hornresp text files (exported single simulations: "Key = value" lines, sections start with '|')
# ---------------------------------------------------------------------------
HORN_ROWS = ("S1", "S2", "Con", "F12", "S2", "S3", "Con", "F23", "S3", "S4", "Con", "F34", "S4", "S5", "Con", "F45")
HORN_LENGTHS = (2, 6, 10, 14)


def _hornresp_lines(filepath):
    """Lines of a Hornresp file (latin-1 so that every byte survives unchanged), with line endings."""
    with open(filepath, "rb") as fh:
        return fh.read().decode("latin-1").splitlines(keepends=True)


def is_hornresp_file(filepath):
    try:
        return any(z.strip().startswith("|HORN PARAMETER VALUES") for z in _hornresp_lines(filepath)[:60])
    except OSError:
        return False


def _horn_entries(lines):
    """[(line index, key, value text)] of the horn section in file order; checks the expected order of the keys."""
    entries, inside = [], False
    for i, z in enumerate(lines):
        t = z.strip()
        if t.startswith("|"):
            inside = t.startswith("|HORN PARAMETER VALUES")
            continue
        if inside and "=" in t:
            k, v = t.split("=", 1)
            entries.append((i, k.strip(), v.strip()))
    if len(entries) != len(HORN_ROWS) or any(
            key not in ("Con", "Par") if n in HORN_LENGTHS else key != HORN_ROWS[n]
            for n, (_, key, _) in enumerate(entries)):
        raise FoldingError("Hornresp file: the horn section does not have the expected structure "
                             "(four Con/Par segments with S1..S5 and F12..F45; other flare types are unsupported).")
    return entries


HR_FACTOR_LENGTH = 10.0 if UNIT == "mm" else 1.0               # Hornresp cm -> script unit
HR_FACTOR_AREA = HR_FACTOR_LENGTH ** 2


def read_hornresp(filepath):
    """Relevant values of a Hornresp text file: S1..S5 and the four section lengths."""
    entries = _horn_entries(_hornresp_lines(filepath))
    try:
        w = [float(e[2].replace(",", ".")) for e in entries]
    except ValueError:
        raise FoldingError("Hornresp file: a horn value is not a number.")
    for n, (_, key, _) in enumerate(entries):
        if not math.isfinite(w[n]):
            raise FoldingError(f"Hornresp file: {key} must be finite (entry {n + 1}).")
        # S1 may be zero at the closed end; active lengths and S2..S5 may not.
        positive = (key.startswith("S") and key != "S1") or n in HORN_LENGTHS
        if (key == "S1" and w[n] < 0) or (positive and w[n] <= 0):
            raise FoldingError(f"Hornresp file: invalid {key} = {w[n]:g} (entry {n + 1}).")
    for i, j in ((1, 4), (5, 8), (9, 12)):
        if not math.isclose(w[i], w[j], rel_tol=1e-9, abs_tol=1e-9):
            raise FoldingError(f"Hornresp file: inconsistent repeated area {entries[i][1]}.")
    fl, la = HR_FACTOR_AREA, HR_FACTOR_LENGTH                   # Hornresp always uses cm and cm²
    return {"S1": w[0] * fl, "S2": w[1] * fl, "S3": w[5] * fl, "S4": w[9] * fl, "S5": w[13] * fl,
            "L12": w[2] * la, "L23": w[6] * la, "L34": w[10] * la, "L45": w[14] * la,
            "flares": tuple(entries[n][1] for n in HORN_LENGTHS)}


def write_hornresp(source, target, values):
    """Replaces only the horn values; flare types and everything else stay as in the source."""
    if Path(source).resolve() == Path(target).resolve() or (Path(target).exists() and os.path.samefile(source, target)):
        raise FoldingError("Hornresp source and output must be different files.")
    numbers = ("S1", "S2", "S3", "S4", "S5", "L12", "L23", "L34", "L45")
    for key in numbers:
        value = values.get(key)
        if value is None or not math.isfinite(value) or (value < 0 if key == "S1" else value <= 0):
            raise FoldingError(f"Invalid Hornresp output value for {key}: {value}.")
    lines = _hornresp_lines(source)
    entries = _horn_entries(lines)
    values = {k_: values[k_] / (HR_FACTOR_AREA if k_.startswith("S") else HR_FACTOR_LENGTH) for k_ in numbers}
    new = {0: values["S1"], 1: values["S2"], 2: values["L12"], 4: values["S2"], 5: values["S3"], 6: values["L23"],
           8: values["S3"], 9: values["S4"], 10: values["L34"], 12: values["S4"], 13: values["S5"], 14: values["L45"]}
    for n, value in new.items():
        i, _key, _ = entries[n]
        z = lines[i]
        end = z[len(z.rstrip("\r\n")):]
        head = z.split("=", 1)[0]
        lines[i] = f"{head}= {value:.2f}{end}"
    _write_atomic(target, "".join(lines).encode("latin-1"))



def s4_bend6_level(geo):
    """0 = S4 behind bend 6, 1 = S4 inside bend 6 behind B6, 2 = S4 before B6 (inside the curved part)."""
    d, t = geo["s4_over_x0"], geo["bend_geo"][5]["parts"]
    if not geo["s4_in_bend"]:
        return 0
    return 1 if d >= -t[2] - 1e-9 else 2


def free_height(geo, origin, direction, box):
    """Free distance from `origin` along the unit vector `direction` to the nearest wall of the channel
    (boards b, c, d and the box walls; board a itself is excluded). Returns (distance, name) or (None, "")."""
    xl, xr, floor_z, ceil_z = box
    segs = []
    for nm, poly in (("b", geo["poly"]["b"]), ("c", geo["poly"]["c"])):
        segs += [(poly[i], poly[(i + 1) % len(poly)], nm) for i in range(len(poly))]
    pd_ = geo["poly"]["d"]                       # Ld_t, C5, C6, Ld_l
    names_d = ("d top side", "d end face", "d underside", "d left face")
    segs += [(pd_[i], pd_[(i + 1) % 4], names_d[i]) for i in range(4)]
    segs += [((xl, floor_z), (xr, floor_z), "floor"), ((xl, ceil_z), (xr, ceil_z), "ceiling"),
             ((xl, floor_z), (xl, ceil_z), "left wall"), ((xr, floor_z), (xr, ceil_z), "right wall")]
    best = (None, "")
    for p_, q_, nm in segs:
        ex_, ey_ = q_[0] - p_[0], q_[1] - p_[1]
        den = direction[0] * ey_ - direction[1] * ex_
        if abs(den) < 1e-12:
            continue
        wx, wy = p_[0] - origin[0], p_[1] - origin[1]
        t = (wx * ey_ - wy * ex_) / den                  # along the ray
        u = (wx * direction[1] - wy * direction[0]) / den  # along the segment (0..1)
        if t > 1e-9 and -1e-9 <= u <= 1 + 1e-9 and (best[0] is None or t < best[0]):
            best = (t, nm)
    return best


def kink_check(geo, b1, a, L12, L45):
    """Estimate for a kinked board a: acoustic mass (inertance) and volume of the segments S1-S2 and S4-S5,
    built vs. Hornresp's linear segment. Profiles from the stations and the kink (support points); estimate only."""
    seg_i = integrate_inertia

    def seg_v(pr):
        return sum((s2 - s1) * (A1 + A2) / 2 for (s1, A1), (s2, A2) in zip(pr[:-1], pr[1:]))
    fl, K, Ls, Kup = geo["area"], geo["K"], geo["Ls"], geo["K_up"]
    S1h, S1r, S2, S4, S5h, S5r = fl["S1"], geo["S1_real"], fl["S2"], fl["S4"], fl["S5"], geo["S5_real"]
    S1c, Kc = (Ls[0], a + (Ls[1] - a) / 2), (K[0], a + (K[1] - a) / 2)
    e_k = _unit_vec((K[0] - Ls[0], K[1] - Ls[1]))
    t_ = _unit_vec((1.0 + e_k[0] + geo["ex"][0], e_k[1] + geo["ex"][1]))
    p1 = [(0.0, S1r), (_dist(S1c, Kc), (K[1] - a) / abs(t_[0]) * b1), (L12, S2)]
    Ld, dd = geo["Ld_l"], geo["dd"]
    # Vertical distance (approximation; the exact cross-section is perpendicular to the centreline).
    # The error is cos((psi + alpha_d)/2) - 1, below 0.5% for typical THAM slopes; only the console estimate is affected.
    a_kup = (Ld[1] + (Kup[0] - Ld[0]) * dd[1] / dd[0] - Kup[1]) * b1
    x4 = geo["U4"][0]
    p4 = [(0.0, S4), (L45 * (x4 - Kup[0]) / x4, a_kup), (L45, S5r)]
    h1, h4 = [(0.0, S1h), (L12, S2)], [(0.0, S4), (L45, S5h)]
    ih1, ip1, ih4, ip4 = (seg_i(p) for p in (h1, p1, h4, p4))
    if not all(math.isfinite(v) and v > 0 for v in (ih1, ip1, ih4, ip4)):
        raise ValueError("Kink comparison requires finite, positive inertance.")
    return {"M1": ih1 / ip1, "M4": ih4 / ip4,
            "dL1": (ih1 - ip1) * S1r, "dL4": (ih4 - ip4) * S5r,
            "dV1": seg_v(h1) - seg_v(p1), "dV4": seg_v(h4) - seg_v(p4)}


def find_input_file(argument=None):
    """(path, explicit): command-line argument or file next to the script, else (None, False)."""
    if argument is not None:
        return os.path.abspath(argument), True
    filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), INPUT_FILE)
    if not os.path.exists(filepath):                     # older file names
        for old_name in ("Hornfaltung_Input.txt", "Hornfaltung_Eingabe.txt"):
            old = os.path.join(os.path.dirname(os.path.abspath(__file__)), old_name)
            if os.path.exists(old):
                filepath = old
                break
    return (filepath, False) if os.path.exists(filepath) else (None, False)


# ---------------------------------------------------------------------------
# Root finding
# ---------------------------------------------------------------------------
def find_roots(f, x_lo, x_hi, step=SEARCH_STEP, only_first=False):
    """Roots of f in [x_lo, x_hi]: grid scan for sign changes, then bisection.

    Non-finite function values (invalid geometry, NaN) count as a gap: no sign change is
    counted across a gap, and a bisection that runs into a gap is discarded.
    Tangential roots without a sign change can be missed by this grid method.
    A residual check rejects jumps whose bracket shrinks without approaching zero.
    """
    if not all(math.isfinite(x) for x in (x_lo, x_hi, step)) or step <= 0:
        raise ValueError("Root search requires finite bounds and a positive finite step.")
    if x_hi <= x_lo:
        return []
    n = max(1, int(math.ceil((x_hi - x_lo) / step)))
    roots = []
    x0 = x_lo
    f0 = f(x0)
    if math.isfinite(f0) and f0 == 0:
        roots.append(x0)
        if only_first:
            return roots
    for i in range(1, n + 1):
        x1 = min(x_lo + i * step, x_hi)
        f1 = f(x1)
        # A root exactly at a grid point also counts directly after a geometry gap (NaN).
        if math.isfinite(f1) and f1 == 0:
            roots.append(x1)
        elif math.isfinite(f0) and math.isfinite(f1):
            # No product: f0*f1 can underflow to -0.0 for tiny values.
            if f0 != 0 and (f0 < 0) != (f1 < 0):
                lo, hi, f_lo = x0, x1, f0
                ok = True
                tolerance = max(abs(f0), abs(f1)) * 1e-10
                best_x, best_f = (x0, f0) if abs(f0) < abs(f1) else (x1, f1)
                for _ in range(100):
                    mid = lo + (hi - lo) / 2
                    if mid == lo or mid == hi:
                        break  # floating-point resolution reached; further calls would not help.
                    f_mid = f(mid)
                    if not math.isfinite(f_mid):
                        ok = False
                        break
                    if abs(f_mid) < abs(best_f):
                        best_x, best_f = mid, f_mid
                    if f_mid == 0:
                        break
                    if (f_lo < 0) != (f_mid < 0):
                        hi = mid
                    else:
                        lo, f_lo = mid, f_mid
                if ok and abs(best_f) <= tolerance:
                    roots.append(best_x)
        if only_first and roots:
            return roots
        x0, f0 = x1, f1
    return roots


def find_root(f, x_lo, x_hi, step=SEARCH_STEP):
    """First root of f in [x_lo, x_hi], or None."""
    w = find_roots(f, x_lo, x_hi, step, only_first=True)
    return w[0] if w else None


def lambda4_limit(width):
    """Frequency [Hz] at which `width` (in UNIT) is a quarter of the wavelength (c = 344 m/s)."""
    return {"cm": 34400.0, "mm": 344000.0}.get(UNIT, 34400.0) / (4.0 * width)


def liter(volume):
    """Volume in UNIT³ -> litres (cm³ -> /1000, mm³ -> /1e6)."""
    return volume / {"cm": 1.0e3, "mm": 1.0e6}.get(UNIT, 1.0e3)


def integrate_inertia(profile):
    """Integral ds/A for a piecewise linear profile [(path, area), ...].

    A zero area at either end of a section makes the integral diverge,
    so such sections must not simply drop out of the sum.
    """
    if any(not math.isfinite(s) or not math.isfinite(A) or A < 0 for s, A in profile):
        raise ValueError("Inertance requires finite positions and nonnegative areas.")
    if any(s2 < s1 for (s1, _), (s2, _) in zip(profile, profile[1:])):
        raise ValueError("Inertance profile positions must be nondecreasing.")
    parts = []
    for (s1, A1), (s2, A2) in zip(profile, profile[1:]):
        ds = s2 - s1
        if ds == 0:
            continue
        if A1 == 0 or A2 == 0:
            return math.inf
        dA = A2 - A1
        if dA == 0:
            mean = 1.0 / A1
        elif abs(dA) < 0.5 * A1:
            mean = math.log1p(dA / A1) / dA
        else:
            mean = (math.log(A2) - math.log(A1)) / dA
        parts.append(ds * mean)
    return math.fsum(parts)



POSITIONS = {
    1: "entry of bend 3 (C3, top left, before the shaft)",
    2: "exit of bend 3 (C3, start of the shaft)",
    3: "entry of bend 4 (C4, end of the shaft)",
    4: "exit of bend 4 (start of the middle channel)",
    5: "entry of bend 5 (C5)",
    6: "exit of bend 5 (C5, start of the short descent)",
    7: "entry of bend 6 (C6, into the chamber)",
}


# ---------------------------------------------------------------------------
# Calculation core 0.5: geometry first, everything along the centreline
#
# Law: the channel width (chord perpendicular to the centreline) grows with the path s along the
# centreline:   W(s) = W2 + b*s   up to S3,   then   W(s3) + b'*(s - s3).   W2 = S2/b1.
# Straight boards are exact rectangles tilted against each other by the wedge angle psi = 2*atan(b/2);
# the chord then grows exactly linearly with the centreline path on straight sections.
# Each bend is solved in turn via the position of its inner corner such that the exit chord
# matches the law W(s_exit). The entry chord then fits automatically (check value).
# ---------------------------------------------------------------------------
def _ang(b):
    """Wedge angle of two channel walls that diverge by b per unit of centreline path."""
    return 2.0 * math.atan(b / 2.0)


def _add(p, v, t=1.0):
    return (p[0] + t * v[0], p[1] + t * v[1])


def _neg(v):
    return (-v[0], -v[1])


def _bend(C, w_in, w_out, wall_in, wall_out):
    G = bend_hand(C, w_in, w_out, wall_in, wall_out)
    ue = _unit_vec((w_in[0][0] + w_in[1][0], w_in[0][1] + w_in[1][1]))
    ua = _unit_vec((w_out[0][0] + w_out[1][0], w_out[0][1] + w_out[1][1]))
    G["theta"] = math.degrees(math.acos(max(-1.0, min(1.0, ue[0] * ua[0] + ue[1] * ua[1]))))
    return G


S3_FOLD = {1: (3, "E"), 2: (3, "X"), 3: (4, "E"), 4: (4, "X"), 5: (5, "E"), 6: (5, "X"), 7: (6, "E")}   # (bend, entry/exit)


_REJECTION = [""]        # reason for the last rejected geometry (for error messages)


def build(P, k, b_after):
    """Complete construction for S3 position k and slope b' = b_after. Returns dict or None (no solution)."""
    _REJECTION[0] = ""
    a, b, T, H, L45, b1, W2 = P["a"], P["b"], P["depth"], P["H"], P["L45"], P["b1"], P["W2"]
    xl, xr, zc = a, T - a, H - a
    psi = _ang(b)
    if math.cos(psi) < COS_PSI_MIN:
        _REJECTION[0] = "slope too large (wedge angle)"
        return None
    ex, en = (math.cos(psi), math.sin(psi)), (-math.sin(psi), math.cos(psi))
    floor, ceil_ = ((0.0, a), (1.0, 0.0)), ((0.0, zc), (1.0, 0.0))
    wB, wD = ((xr, 0.0), (0.0, 1.0)), ((xl, 0.0), (0.0, 1.0))
    b_shaft = b_after if k <= 2 else b                # slope in the left shaft (c end face / D)
    b_mid = b_after if k <= 4 else b                    # slope in the middle channel (c/d)
    b_riser = b_after if k <= 6 else b                  # slope of the short descent (end face of d / b)
    alpha_d = psi - _ang(b_mid)                    # inclination of d against the horizontal
    dd = (math.cos(alpha_d), math.sin(alpha_d))
    n_perp = (dd[1], -dd[0])                       # normal of d (lower face lies a along it)
    beta = psi - _ang(b_riser)                     # d is cut so that the descent opens with the slope b_riser
    n_ab = (math.sin(beta), -math.cos(beta))       # end face of d, pointing down (bevelled unless beta = alpha_d)
    ps = _ang(b_shaft)
    ab = (math.sin(ps), -math.cos(ps))             # end face of c, pointing down
    ab_b = _neg(en)                                # left face of b, pointing down

    # --- S2: chord perpendicular to the bisector of floor and board a, through the driver centre ------
    U2 = (L45 + a / 2 * math.sin(psi), a + W2 * math.cos(psi / 2))      # underside of a
    F2 = (U2[0] + W2 * math.sin(psi / 2), a)                           # foot point on the floor
    S2c = _midpoint(U2, F2)
    U4 = _add(U2, en, a)                                               # top side of a (S4)

    def law(s, s3):
        if s3 is None or s <= s3:
            return W2 + b * s
        return W2 + b * s3 + b_after * (s - s3)

    sf = S3_FOLD[k]
    state = {"s3": None}
    folds = []

    def solve(nr, mk, lo, hi, X_prev, s_prev, step=SEARCH_STEP_BEND):
        def evaluate(par):
            try:
                G, extra = mk(par)
            except (ZeroDivisionError, ValueError):
                return None
            if G is None or not (G["w1"] > 0 and G["w2"] > 0):
                return None
            for pk_ in (G["E0"], G["A"], G["B"], G["X0"], G["C"], G["Ci"], G["Cx"], G["Q"]):   # bend incl. cross-section ends and outer corner stays inside the box
                if not (xl - BOX_TOL <= pk_[0] <= xr + BOX_TOL and a - BOX_TOL <= pk_[1] <= zc + BOX_TOL):
                    return None
            if not bend_sign_ok(G):          # construction would run backwards (see bend_sign_ok)
                return None
            s_e = s_prev + math.hypot(G["E0"][0] - X_prev[0], G["E0"][1] - X_prev[1])
            vpl = sum(G["parts"])
            s_x = s_e + vpl
            s3 = state["s3"]
            if sf[0] == nr:
                s3 = s_e if sf[1] == "E" else s_x
            return G, extra, s_e, s_x, vpl, s3

        def res(par):
            r = evaluate(par)
            if r is None:
                return float("nan")
            G, extra, s_e, s_x, vpl, s3 = r
            return G["w2"] - law(s_x, s3)
        par = find_root(res, lo, hi, step)
        if par is None:
            return None
        G, extra, s_e, s_x, vpl, s3 = evaluate(par)
        if sf[0] == nr:
            state["s3"] = s3
        folds.append({"nr": nr, "par": par, "G": G, "s_e": s_e, "s_x": s_x, "vpl": vpl,
                      "law_in": law(s_e, s3), "law_out": law(s_x, s3)})
        return G, extra, s_x

    def mk1(t):
        C = _add(U2, ex, t)
        return _bend(C, ((1.0, 0.0), ex), (en, (0.0, 1.0)), floor, wB), C
    limit = 2.0 * (T + H)                           # no path section of the search can be longer than this
    r = solve(1, mk1, BEND_MIN, min((xr - U2[0]) / math.cos(psi) - BEND_MARGIN, limit), S2c, 0.0)
    if r is None:
        return None
    G1, C1, s1x = r

    def mk2(t):
        C = _add(C1, en, t)
        return _bend(C, (en, (0.0, 1.0)), (_neg(ex), (-1.0, 0.0)), wB, ceil_), C
    r = solve(2, mk2, BEND_MIN, min((zc - C1[1]) / math.cos(psi) - BEND_MARGIN, limit), G1["X0"], s1x)
    if r is None:
        return None
    G2, C2, s2x = r

    def mk3(t):
        C = _add(C2, ex, -t)
        return _bend(C, (_neg(ex), (-1.0, 0.0)), (ab, (0.0, -1.0)), ceil_, wD), C
    r = solve(3, mk3, BEND_MIN, min((C2[0] - xl) / math.cos(psi) - BEND_MARGIN, limit), G2["X0"], s2x)
    if r is None:
        return None
    G3, C3, s3x = r
    c_bottom = _add(C2, en, -a)                      # underside of c (point, direction ex)
    C4 = _intersect(C3, ab, c_bottom, ex)              # lower left corner of c (end face ab)

    def mk4(v):
        Pd = (C4[0], C4[1] - v)
        return _bend(C4, (ab, (0.0, -1.0)), (ex, dd), wD, (Pd, dd)), Pd
    r = solve(4, mk4, BEND_MIN, C4[1] - a - 2 * BEND_MARGIN, G3["X0"], s3x)
    if r is None:
        return None
    G4, Pd, s4x = r
    w_cun = (C4, ex)
    q_l = _add(C1, ex, -a)
    w_bli = (q_l, en)

    def mk5(tau):
        C = _add(Pd, dd, tau)
        return _bend(C, (ex, dd), (n_ab, ab_b), w_cun, w_bli), C
    r = solve(5, mk5, BEND_MIN, 2.0 * T, G4["X0"], s4x)
    if r is None:
        return None
    G5, C5, s5x = r
    a_top = (U4, ex)                               # top side of a (floor of the chamber), extended
    Pd_u = _add(Pd, n_perp, a)
    C6 = _intersect(C5, n_ab, Pd_u, dd)
    G6 = _bend(C6, (n_ab, ab_b), (_neg(dd), _neg(ex)), w_bli, a_top)
    if not (G6["w1"] > 0 and G6["w2"] > 0):                              # same validation as in solve()
        return None
    for pk_ in (G6["E0"], G6["A"], G6["B"], G6["X0"], G6["C"], G6["Ci"], G6["Cx"], G6["Q"]):
        if not (xl - BOX_TOL <= pk_[0] <= xr + BOX_TOL and a - BOX_TOL <= pk_[1] <= zc + BOX_TOL):
            return None
    if not bend_sign_ok(G6):
        _REJECTION[0] = ("bend 6: the construction runs backwards (cross-section ratio too large for this turning angle); "
                         "the path length would be wrong")
        return None
    s_e6 = s5x + math.hypot(G6["E0"][0] - G5["X0"][0], G6["E0"][1] - G5["X0"][1])
    s_x6 = s_e6 + sum(G6["parts"])
    if k == 7:
        state["s3"] = s_e6
    folds.append({"nr": 6, "par": 0.0, "G": G6, "s_e": s_e6, "s_x": s_x6, "vpl": sum(G6["parts"]),
                  "law_in": law(s_e6, state["s3"]), "law_out": law(s_x6, state["s3"]), "free_exit": True})
    bend_geo = [G1, G2, G3, G4, G5, G6]
    Cs = [C1, C2, C3, C4, C5, C6]

    # --- Board a (with or without a kink at S2), S1 ---------------------------------------------------
    z_u = U2[1] + (xl - U2[0]) * math.tan(psi)       # underside of a at x = xl without a kink
    s1_same = max(0.0, z_u - a) * b1
    kink = bool(P.get("kink")) and U2[0] > xl + 1e-9 and abs(P["S1"] - s1_same) > 1e-3 * CM ** 2
    r_driver = max(0.0, P.get("driver_d") or 0.0) / 2        # half gross driver diameter (0 = unknown)
    K = K_up = Kc = None
    kink_note = ""
    if kink:
        # Kink point K on the underside of a2, r_driver to the left of the driver centre (S2); a2 stays straight
        # at least half a driver diameter on both sides of the driver centre, on the underside AND on the top side
        # (the mitre shortens the top side, so the kink is shifted until both sides have the free length).
        t_max = (U2[0] - xl) / ex[0] - CM                       # mindestens 1 cm von a1 erhalten
        if t_max <= 0:
            kink = False
            kink_note = "no room for a kink between the driver and the left wall"
    if kink:
        S2c_ = _midpoint(U2, F2)
        S1h = P["S1"]

        def kink_solve(t_k):
            """Kink at distance t_k left of U2: real S1 from volume equality; returns (K, Kc, Ls, Lu, K_up, Lz) or None."""
            K = _add(U2, ex, -t_k)
            Kc = (K[0], a + (K[1] - a) / 2)

            def area12(Lz):                                  # side-view area between S1 and the S2 chord
                return _poly_area([(xl, a), (xl, Lz), K, U2, F2])

            def length12(Lz):
                return _dist((xl, a + (Lz - a) / 2), Kc) + _dist(Kc, S2c_)

            def rest(Lz):                                       # area of the drawing - area of Hornresp's segment
                return area12(Lz) - length12(Lz) * (S1h + P["W2"] * b1) / 2 / b1
            lo, hi = a + 1e-3, a + 3.0 * (zc - a)               # real S1 such that the volume equals Hornresp's
            r_lo, r_hi = rest(lo), rest(hi)
            if r_lo * r_hi > 0:
                _REJECTION[0] = ("Board a with a kink: no real S1 makes the volume S1-S2 equal to Hornresp's linear "
                                 "segment (kink too close to the wall or S1 too different from the continuous slope).")
                return None
            for _ in range(80):
                mid = (lo + hi) / 2
                r_mid = rest(mid)
                if r_lo * r_mid <= 0:
                    hi, r_hi = mid, r_mid
                else:
                    lo, r_lo = mid, r_mid
            Lz = (lo + hi) / 2
            if Lz <= a + 1e-6 or Lz >= zc - a:                  # a1 must stay inside the box
                _REJECTION[0] = "Board a with a kink: the real S1 needed for Hornresp's volume would not fit in the box."
                return None
            Ls = (xl, Lz)
            e_k = _unit_vec((K[0] - Ls[0], K[1] - Ls[1]))
            n_k = (-e_k[1], e_k[0])
            K_up = _intersect(_add(Ls, n_k, a), e_k, _add(U2, en, a), ex)
            Lu = _intersect(_add(Ls, n_k, a), e_k, (xl, 0.0), (0.0, 1.0))
            return K, Kc, Ls, Lu, K_up, Lz
        t_k = min(r_driver, t_max)
        result = None
        for _ in range(6):
            result = kink_solve(t_k)
            if result is None:
                return None
            missing = r_driver - ((U4[0] - result[4][0]) * ex[0] + (U4[1] - result[4][1]) * ex[1])   # top side free length
            if missing <= 1e-9 or t_k >= t_max:
                break
            t_k = min(t_k + missing, t_max)
        if r_driver > t_k + 1e-9:
            kink_note = f"kink moved: half driver diameter {r_driver:.1f} does not fit left of S2 (max. {t_max:.1f})"
        K, Kc, Ls, Lu, K_up, Lz = result
        poly_a = [Ls, K, C1, _add(C1, en, a), K_up, Lu]
        s1_eff = (Lz - a) * b1
    else:
        Ls = (xl, z_u)
        Lu = (xl, z_u + a / math.cos(psi))
        poly_a = [Ls, C1, _add(C1, en, a), Lu]
        s1_eff = s1_same
    if Ls[1] < a - 1e-6 or Lu[1] <= Ls[1] or Lu[1] > zc + 1e-6:
        _REJECTION[0] = (f"board a would leave the box at the left wall (underside at height {Ls[1]:.2f}, "
                         f"floor top at {a:.2f}): slope too steep for this driver position")
        return None
    # --- further boards -----------------------------------------------------------------------------
    B0 = _add(C1, en, a)
    poly_b = [B0, _add(B0, ex, -a), _add(_add(C2, en, -a), ex, -a), _add(C2, en, -a)]
    poly_c = [C2, C3, C4, _add(C2, en, -a)]
    z_dt = Pd[1] + (xl - Pd[0]) * math.tan(alpha_d)
    z_dl = Pd_u[1] + (xl - Pd_u[0]) * math.tan(alpha_d)
    Ld_t, Ld_l = (xl, z_dt), (xl, z_dl)
    if not (a - 1e-6 <= Ld_l[1] <= Ld_t[1] <= zc + 1e-6) or Ld_l[1] <= Lu[1]:
        _REJECTION[0] = (f"board d or the mouth would leave the box at the left wall (d underside {Ld_l[1]:.2f}, "
                         f"top {Ld_t[1]:.2f}, a top {Lu[1]:.2f}; box {a:.2f} .. {zc:.2f})")
        return None
    poly_d = [Ld_t, C5, C6, Ld_l]
    # --- Mouth bevel: D1 and D2 continue the slopes of a (a1) and d through the front wall ---------------
    top_slope = (K_up[1] - Lu[1]) / (K_up[0] - Lu[0]) if kink else ex[1] / ex[0]
    Lu0 = (0.0, Lu[1] - xl * top_slope)                       # top edge of D1 at the outer face (x = 0)
    Ld0 = (0.0, Ld_l[1] - xl * math.tan(alpha_d))             # bottom edge of D2 at the outer face
    if not (a - BOX_TOL <= Lu0[1] < Ld0[1] <= zc + BOX_TOL):
        _REJECTION[0] = (f"the mouth bevel of D1/D2 would leave the box at the outer face (D1 top {Lu0[1]:.2f}, "
                         f"D2 bottom {Ld0[1]:.2f}; box {a:.2f} .. {zc:.2f})")
        return None
    # --- Cross-sections, centreline -----------------------------------------------------------------
    S2_lin = (U2, F2)
    S4_lin = _crossline(U4, ex, Pd_u, dd)
    S4c = _midpoint(*S4_lin)
    S1c = (xl, a + (Ls[1] - a) / 2)
    S5_lin = (Lu0, Ld0)
    S5c = _midpoint(*S5_lin)
    # --- Centreline: S1c, (kink Kc), S2c, (A,B)*6, S5c.  S1..S5 are cross-sections, NOT waypoints of the path. ---
    ua6 = G6["uc_out"]
    # Distance of the driver centre behind the exit cross-section of bend 6 (negative: S4 lies in the bend).
    # Reference point C6 instead of X0 gives the same value: X0 lies on the exit chord C6-Cx6, which is perpendicular to ua6.
    s4_over_x0 = (U4[0] - G6["C"][0]) * ua6[0] + (U4[1] - G6["C"][1]) * ua6[1]
    s4_in_bend = s4_over_x0 < -1e-9
    pts = [S1c, S2c]
    q_inserted = False
    for G in bend_geo:
        pts += [G["A"], G["B"]]
    if kink:
        # Board a with a kink: the walls of the chamber change direction at the cross-section through K_up. The centreline
        # follows the bisector (a2 top, d) from bend 6 up to that cross-section (perpendicular to ua6 through K_up), then
        # goes straight to the mouth centre S5c (bisector of a1 top and d); no bend construction at the kink.
        Bk = G6["B"]
        t_q = (K_up[0] - Bk[0]) * ua6[0] + (K_up[1] - Bk[1]) * ua6[1]
        t_x = (G6["X0"][0] - Bk[0]) * ua6[0] + (G6["X0"][1] - Bk[1]) * ua6[1]
        if t_q > max(t_x, 0.0) + 1e-6:
            pts += [(Bk[0] + ua6[0] * t_q, Bk[1] + ua6[1] * t_q)]
            q_inserted = True
    pts += [S5c]
    cum = [0.0]
    for i, (p_, q_) in enumerate(zip(pts[:-1], pts[1:])):
        lg = math.hypot(q_[0] - p_[0], q_[1] - p_[1])
        if i == 0 and kink:                      # S1 -> S2 runs via the kink
            lg = _dist(p_, Kc) + _dist(Kc, q_)
        cum.append(cum[-1] + lg)
    s_e6 = cum[12] - G6["parts"][0]               # path position of the entry (E0) of bend 6
    s_x6 = cum[13] + G6["parts"][2]               # path position of the exit (X0) of bend 6
    if s4_in_bend:
        # S4 in the curved part: the cross-section is the fan ray from the inner corner C6 through the driver centre
        # U4; its path position is where this ray meets the bend path E0-A-B-X0
        hits = _ray_path(G6["C"], (U4[0] - G6["C"][0], U4[1] - G6["C"][1]),
                               [G6["E0"], G6["A"], G6["B"], G6["X0"]])
        if hits is None:
            _REJECTION[0] = "S4 (driver centre) lies outside the fan of bend 6"
            return None
        s4_cum = s_e6 + hits
        S4_lin = (G6["C"], U4)
        S4c = _midpoint(*S4_lin)
    else:
        s4_cum = cum[13] + (S4c[0] - G6["B"][0]) * ua6[0] + (S4c[1] - G6["B"][1]) * ua6[1]
    if s4_cum >= cum[-1] - 1e-6:
        _REJECTION[0] = "S4 would lie at or behind the mouth"
        return None
    s_s4 = s4_cum - cum[1]
    s3_lin = {1: (G3["C"], G3["Ci"]), 2: (G3["C"], G3["Cx"]), 3: (G4["C"], G4["Ci"]), 4: (G4["C"], G4["Cx"]),
              5: (G5["C"], G5["Ci"]), 6: (G5["C"], G5["Cx"]), 7: (G6["C"], G6["Ci"])}[k]
    section = {"S1": ((xl, a), Ls), "S2": S2_lin, "S3": s3_lin, "S4": S4_lin, "S5": S5_lin}
    area = {n: _dist(*section[n]) * b1 for n in section}
    S4_fan = area["S4"]
    S1_real, S5_real = area["S1"], _dist(*S5_lin) * b1
    # Chamber S4-S5: path length and built air volume (independent of the Hornresp areas)
    l45 = cum[-1] - s4_cum
    s4_foot = G6["C"] if s4_in_bend else S4_lin[1]
    if kink:
        ch45 = [Lu0, Lu, K_up, U4, s4_foot, Ld_l, Ld0]
    else:
        ch45 = [Lu0, Lu, U4, s4_foot, Ld_l, Ld0]
    v45 = _poly_area(ch45) * b1
    if s4_in_bend:
        # Theoretical S4 for Hornresp: the straight line S4 -> mouth passes through the built exit area Ax of bend 6 (at X0)
        # and ends in the REAL mouth area S5_real (not in the Hornresp S5, which is derived from S4 afterwards):
        #     S4 = Ax + (Ax - S5_real) * L2 / Lk          L2 = path S4 -> X0 (inside bend 6), Lk = path X0 -> mouth
        # (0.69: no coupling to the Hornresp S5, hence no pole at Lk = L2 as in 0.68 with a kink).
        Ax = b1 * G6["w2"]
        L2, Lk = s_x6 - s4_cum, cum[-1] - s_x6
        if Lk <= 1e-6:
            _REJECTION[0] = "S4 in bend 6 and no straight chamber path between the bend exit and the mouth"
            return None
        area["S4"] = Ax + (Ax - S5_real) * L2 / Lk
    S4_drawing = S4_lin
    if s4_in_bend:
        # drawing: from the driver centre straight towards C6 (through the path), exactly as long as the calculated S4 area
        # corresponds to (S4 / b1), so that the purple line shows the same cross-section as the printed result
        ric = _unit_vec((G6["C"][0] - U4[0], G6["C"][1] - U4[1]))
        S4_drawing = (U4, _add(U4, ric, area["S4"] / b1))
    # --- Hornresp areas S1 and S5 (0.69): every Hornresp segment reproduces the BUILT air volume ---------------
    # S1-S2 (closed end, acts as a compliance): equal volume, S1_HR = 2*V12/L12 - S2.
    #   With a kink the real S1 was solved so that this gives exactly the specified S1 (kink_solve).
    #   Without a kink the built volume is used; a specified S1 has no effect then (use Kink = y to simulate another S1).
    if kink:
        area["S1"] = P["S1"]
    else:
        v12 = _poly_area([(xl, a), (xl, Ls[1]), U2, F2]) * b1
        area["S1"] = max(0.0, 2 * v12 / cum[1] - area["S2"])
    # S4-S5 (mouth): volume (compliance) and inertance (air mass) cannot both be matched with a straight segment of
    # the given length; S5_HR is the mean of the volume-equal S5_vol and the inertance-equal S5_inert.
    S4h = area["S4"]
    s5_vol = 2 * v45 / l45 - S4h
    prof45 = [(0.0, S4h), (l45, S5_real)]
    if kink and q_inserted and cum[-2] - s4_cum > 1e-9:
        # real profile with the kink: cross-section through K_up, perpendicular to the centreline (direction ua6)
        n6 = (-ua6[1], ua6[0])
        try:
            a_kup = _dist(K_up, _intersect(K_up, n6, Ld_l, dd)) * b1
            prof45 = [(0.0, S4h), (cum[-2] - s4_cum, a_kup), (l45, S5_real)]
        except ZeroDivisionError:
            pass
    s5_inert = None
    if S4h > 0:
        m_real = integrate_inertia(prof45)

        def f_(x_):                                   # inertance of the straight segment S4h -> x_ minus the real one
            return (l45 * math.log(x_ / S4h) / (x_ - S4h) if abs(x_ - S4h) > 1e-9 * S4h else l45 / S4h) - m_real
        lo_, hi_ = S4h * 1e-3, S4h * 1e3
        if f_(lo_) * f_(hi_) < 0:
            for _ in range(200):
                mid_ = math.sqrt(lo_ * hi_)
                if f_(lo_) * f_(mid_) <= 0:
                    hi_ = mid_
                else:
                    lo_ = mid_
            s5_inert = math.sqrt(lo_ * hi_)
    area["S5"] = 0.5 * (s5_vol + s5_inert) if (s5_inert is not None and s5_vol > 0) else s5_vol
    if area["S4"] <= 0 or area["S5"] <= 0 or _dist(*S4_lin) <= 0:
        if area["S4"] <= 0:
            _REJECTION[0] = f"the theoretical Hornresp S4 would be {area['S4']:.0f} (<= 0)"
        elif area["S5"] <= 0:
            _REJECTION[0] = (f"the Hornresp S5 from the volume S4-S5 would be {area['S5']:.0f} (<= 0); "
                             f"the chamber volume is too large for this S4")
        return None
    s3 = state["s3"]
    if s3 is None or s3 >= s_s4 - 1e-9:           # S3 must lie before S4
        return None
    # --- Driver centre -> D1, volume check, inertance ----------------------------------------------
    d1_bottom = _dist(U2, Ls)
    d1_top = _dist(U4, Lu)
    prof = [(0.0, S1_real), (cum[1], area["S2"])]
    for i, G in enumerate(bend_geo):
        prof.append((cum[2 + 2 * i] - G["parts"][0], b1 * G["w1"]))
        prof.append((cum[3 + 2 * i] + G["parts"][2], b1 * G["w2"]))
    prof += [(cum[-1], S5_real)]
    if not s4_in_bend:
        prof.append((s4_cum, area["S4"]))
    prof.sort()
    vol_path = sum((s2_ - s1_) * (A1_ + A2_) / 2 for (s1_, A1_), (s2_, A2_) in zip(prof[:-1], prof[1:]))
    inertia = integrate_inertia(prof)
    # The mouth opening passes through the front wall: S5 is at x=0, while the
    # internal box volume starts at x=xl=a. Include this wall-thickness aperture
    # in both the drawn air volume and the numerical air-volume balance.
    mouth_poly = [Lu0, Lu, Ld_l, Ld0]
    vol_mouth = _poly_area(mouth_poly) * b1
    air_area = ((xr - xl) * (zc - a)
               - sum(_poly_area(pg) for pg in (poly_a, poly_b, poly_c, poly_d)))
    vol_air = air_area * b1 + vol_mouth
    ratio = [(nm, max(G["w1"], G["w2"]) / min(G["w1"], G["w2"])) for nm, G in zip(BEND_NAMES, bend_geo)]
    return {"s4_over_x0": s4_over_x0, "bend_geo": bend_geo, "C": Cs, "folds": folds, "s3": s3, "U2": U2, "U4": U4, "F2": F2, "S2c": S2c, "S4c": S4c,
            "Pd": Pd, "dd": dd, "n_ab": n_ab, "ab": ab, "psi": psi, "alpha_d": alpha_d, "ex": ex, "en": en,
            "poly": {"a": poly_a, "b": poly_b, "c": poly_c, "d": poly_d}, "Ls": Ls, "Lu": Lu, "Ld_t": Ld_t, "Ld_l": Ld_l, "Lu0": Lu0, "Ld0": Ld0,
            "kink": kink, "K": K, "K_up": K_up, "kink_note": kink_note, "S1_real": S1_real, "S5_real": S5_real, "r_driver": r_driver, "t_kink": (_dist(U2, K) if K else 0.0), "s1_eff": s1_eff, "s1_same": s1_same, "s4_cond": 0.0, "s5_vol": s5_vol, "s5_inert": s5_inert, "section": section, "area": area,
            "path_pts": ([S1c, Kc] + pts[1:]) if kink else pts, "cum": cum, "s_s4": s_s4, "s4_cum": s4_cum,
            "s4_in_bend": s4_in_bend, "S4_drawing": S4_drawing, "S4_fan": S4_fan, "v45_actual": v45, "d1": (d1_bottom, d1_top),
            "vol_path": vol_path, "vol_air": vol_air, "vol_mouth": vol_mouth, "mouth_poly": mouth_poly,
            "inertia": inertia, "ratios": ratio,
            "w_max": max(max(G["w1"], G["w2"]) for G in bend_geo), "C4": C4, "C3": C3, "C2": C2, "C1": C1}


BEND_NAMES = ("Bend 1 (bottom right)", "Bend 2 (top right)", "Bend 3 (top left)",
               "Bend 4 (left, into d)", "Bend 5 (right, downwards)", "Bend 6 (into the chamber)")


def compute(P, k, b_after):
    """Results for S3 position k and slope b' = b_after (dict) or FoldingError."""
    try:
        geo = build(P, k, b_after)
    except (ZeroDivisionError, ValueError, OverflowError) as err:
        raise FoldingError(f"Geometry cannot be calculated ({err}).")
    if geo is None:
        raise FoldingError(f"For S3 position {k} and b' = {b_after:.4f} the fold path does not fit in the box "
                             f"(a bend cannot be closed with the width law)." + (f" Last reason: {_REJECTION[0]}" if _REJECTION[0] else ""))
    b1, fl, cum = P["b1"], geo["area"], geo["cum"]
    path_s1_s2 = cum[1]
    s_s4 = geo["s_s4"]
    path_s4_s5 = cum[-1] - geo["s4_cum"]
    l23 = geo["s3"]
    path_s3_s4 = s_s4 - l23
    total = path_s1_s2 + s_s4 + path_s4_s5
    S3, S4 = fl["S3"], fl["S4"]
    b_cone = (S4 - S3) / (b1 * path_s3_s4) if path_s3_s4 > 0 else float("nan")
    th = [G["theta"] for G in geo["bend_geo"]]
    bends = [(nm, G["w1"], G["w2"], t_, G["parts"]) for nm, G, t_ in zip(BEND_NAMES, geo["bend_geo"], th)]
    return {"k": k, "b_after": b_after, "b_cone": b_cone, "s3": l23, "l23": l23, "S3": S3, "S4": S4, "S5": fl["S5"],
            "S2": fl["S2"], "path_s1_s2": path_s1_s2, "path_s4_s5": path_s4_s5, "path_s3_s4": path_s3_s4,
            "total": total, "bends": bends, "geo": geo}




def shortfall(P, R):
    """Largest relative undershoot of the actual cone (fan in the bends, chords at bend ends) below the
    idealised cone through the calculated S1-S5, in % (0 = nowhere below)."""
    geo = R["geo"]
    kd = cone_data({"b1": P["b1"], "l23_new": R["l23"], "unit": UNIT, "a": P["a"]}, geo)
    worst = 0.0
    tab = [(n, s_, A_) for n, s_, A_ in kd["points"]]
    for bg in kd["bends"]:
        tab += [("F", s_, A_) for s_, A_, _ in bg["fans"]]
    for _, s_, A_ in tab:
        ideal = kd["lin"](kd["ideal"], s_)
        if ideal > 0:
            worst = max(worst, (ideal - A_) / ideal * 100.0)
    return worst


def solve_b_consistent(P, k):
    """b' such that the area S3 -> S4 grows uniformly with b': S4 = S3 + b1*b'*path(S3-S4).

    Returns (b', number of solutions found); if there are several, the one closest to b is used.
    Invalid geometries (FoldingError) count as a gap, not as a numerical value.
    """
    b1 = P["b1"]

    def h(b_after):
        try:
            R = compute(P, k, b_after)
        except FoldingError:
            return float("nan")
        return R["S4"] - R["S3"] - b1 * b_after * R["path_s3_s4"]
    roots = find_roots(h, B_MIN, B_MAX, B_STEP)
    if not roots:
        margin = ""
        h_lo, h_hi = h(B_MIN), h(B_MAX)
        if math.isfinite(h_lo) and math.isfinite(h_hi):
            margin = (f" Difference S4 - (S3 + b1*b'*path) at the boundary: {h_lo:+.1f} at b' = {B_MIN:g}, "
                    f"{h_hi:+.1f} at b' = {B_MAX:g} {UNIT}² (same sign: a solution outside "
                    f"the search range is possible, but not certain).")
        else:
            margin = (f" At at least one boundary of the search range the geometry is invalid "
                    f"(b' = {B_MIN:g}: {'valid' if math.isfinite(h_lo) else 'invalid'}, "
                    f"b' = {B_MAX:g}: {'valid' if math.isfinite(h_hi) else 'invalid'}).")
        raise FoldingError(f"For position {k} there is no slope in the range b' = {B_MIN:g} ... {B_MAX:g} "
                             f"for which S4 fits the geometry (box too small or position "
                             f"unsuitable). Specify b' manually if needed." + margin)
    roots.sort(key=lambda w: abs(w - P["b"]))
    return roots[0], len(roots)


def _unit_vec(v):
    l = math.hypot(v[0], v[1])
    return (v[0] / l, v[1] / l)


def _intersect(P, u, Q, v):
    """Intersection point of the lines P+t*u and Q+s*v."""
    det = -u[0] * v[1] + u[1] * v[0]
    if abs(det) < 1e-9 * math.hypot(*u) * math.hypot(*v):
        raise ZeroDivisionError("Lines are parallel")
    t = (-(Q[0] - P[0]) * v[1] + (Q[1] - P[1]) * v[0]) / det
    return (P[0] + t * u[0], P[1] + t * u[1])


def _midpoint(p, q):
    return ((p[0] + q[0]) / 2, (p[1] + q[1]) / 2)


def _dist(p, q):
    return math.hypot(p[0] - q[0], p[1] - q[1])


def _poly_area(pts):
    """Area of a polygon (Gauss's shoelace formula)."""
    return abs(sum(p[0] * q[1] - q[0] * p[1] for p, q in zip(pts, pts[1:] + pts[:1]))) / 2.0


def _ray_path(C, r, pf):
    """Distance along the polyline pf from its first point to the first intersection with the ray C + t*r (t > 0);
    None if the ray does not meet the polyline."""
    run = 0.0
    for p_, q_ in zip(pf[:-1], pf[1:]):
        d = (q_[0] - p_[0], q_[1] - p_[1])
        det = -r[0] * d[1] + r[1] * d[0]
        lg = math.hypot(*d)
        if abs(det) > 1e-12 * math.hypot(*r) * lg:
            w = (p_[0] - C[0], p_[1] - C[1])
            t = (-w[0] * d[1] + w[1] * d[0]) / det
            u = (r[0] * w[1] - r[1] * w[0]) / det
            if t > 0 and -1e-9 <= u <= 1 + 1e-9:
                return run + min(max(u, 0.0), 1.0) * lg
        run += lg
    return None


def _crossline(P, d1, Q, d2):
    """Cross-section of a straight channel section: from P (lies on wall 1, direction d1) perpendicular to the
    centreline (= bisector of the two walls) to wall 2 (point Q, direction d2).
    d1, d2: wall directions in flow direction. Returns: (P, foot point on wall 2)."""
    ub = _unit_vec((d1[0] + d2[0], d1[1] + d2[1]))
    n = (-ub[1], ub[0])
    return P, _intersect(P, n, Q, d2)


def bend_hand(C, w_in, w_out, wall_in, wall_out):
    """Manual construction of a bend at the inner corner C.

    w_in / w_out: two direction vectors each (in flow direction) of the two walls of the entry and
    exit channel. wall_in / wall_out: the respective outer wall as (point, direction).
    The centreline of each channel lies on the bisector of its two walls; the
    cross-section is perpendicular to it and starts at C.
    """
    uc_in = _unit_vec((w_in[0][0] + w_in[1][0], w_in[0][1] + w_in[1][1]))
    uc_out = _unit_vec((w_out[0][0] + w_out[1][0], w_out[0][1] + w_out[1][1]))
    P_ein = _intersect(C, (-uc_in[1], uc_in[0]), *wall_in)       # cross-section meets the outer wall
    P_aus = _intersect(C, (-uc_out[1], uc_out[0]), *wall_out)
    Q = _intersect(*wall_in, *wall_out)                            # outer corner of the bend
    O1, O2 = _midpoint(P_ein, Q), _midpoint(P_aus, Q)
    E0, X0 = _midpoint(C, P_ein), _midpoint(C, P_aus)                   # centres of the two cross-sections
    A = _intersect(E0, uc_in, C, (O1[0] - C[0], O1[1] - C[1]))
    B = _intersect(X0, uc_out, C, (O2[0] - C[0], O2[1] - C[1]))
    return {"C": C, "Ci": P_ein, "Cx": P_aus, "Q": Q, "O1": O1, "O2": O2, "A": A, "B": B, "E0": E0, "X0": X0,
            "w1": _dist(C, P_ein), "w2": _dist(C, P_aus), "uc_in": uc_in, "uc_out": uc_out,
            "parts": (_dist(E0, A), _dist(A, B), _dist(B, X0))}


def bend_sign_ok(G):
    """True if the hand construction runs forward: E0 -> A along the entry direction and B -> X0 along the exit direction.
    A part with the wrong direction would still be added as a positive length (parts are distances), i.e. the path would be wrong.
    Occurs only for strongly widening bends with sharp turns (checked: not in the 34 regression cases)."""
    sa = (G["A"][0] - G["E0"][0]) * G["uc_in"][0] + (G["A"][1] - G["E0"][1]) * G["uc_in"][1]
    sb = (G["X0"][0] - G["B"][0]) * G["uc_out"][0] + (G["X0"][1] - G["B"][1]) * G["uc_out"][1]
    return sa >= -1e-6 and sb >= -1e-6


# ---------------------------------------------------------------------------
# Unrolled horn cones (evaluation of the drawing geometry, does not change the calculation)
#   a) Specification: input / Hornresp values with imported Con/Par law (g["ref"])
#   b) Idealised:     calculated S1-S5 at the centreline distances of the drawing, linear in between
#   c) Actual:        length of the cross-section line x b1 at the cross-sections of the construction
#                     (straight board sections: exactly linear; bends: only entry/exit known, in between
#                     NO unambiguous cross-section -> dotted and shaded grey/red)
# ---------------------------------------------------------------------------
def _fan_profile(G, step, s_e, b1):
    """Cross-section profile in the bend: straight line from the inner corner C through the point of the bend path (E0-A-B-X0)
    at path s to the outer boundary (entry wall to outer corner Q, then exit wall).
    Returns: list of (total path, area, path within bend)."""
    C, Pe, Pa = G["C"], G["Ci"], G["Cx"]
    Q = (2 * G["O1"][0] - Pe[0], 2 * G["O1"][1] - Pe[1])
    pf = [G["E0"], G["A"], G["B"], G["X0"]]
    lg = [math.hypot(q[0] - p[0], q[1] - p[1]) for p, q in zip(pf[:-1], pf[1:])]
    total = sum(lg)
    ss = [i * step for i in range(int(total // step) + 1)] + [lg[0], lg[0] + lg[1], total]
    # additional sample where the ray points at the outer corner Q (peak of the cross-section)
    rq = (Q[0] - C[0], Q[1] - C[1])
    rest = 0.0
    for p_, q_, l_ in zip(pf[:-1], pf[1:], lg):
        ex_, ey_ = q_[0] - p_[0], q_[1] - p_[1]
        det = rq[0] * (-ey_) - rq[1] * (-ex_)
        if abs(det) > 1e-12:
            rx, ry = p_[0] - C[0], p_[1] - C[1]
            t_ = (rx * (-ey_) - ry * (-ex_)) / det
            u_ = (rq[0] * ry - rq[1] * rx) / det
            if t_ > 0 and 0 <= u_ <= 1:
                ss.append(rest + u_ * l_)
        rest += l_
    ss = sorted(set(round(v, 9) for v in ss if 0 <= v <= total))

    def point(sv):
        rest = sv
        for p, q, l_ in zip(pf[:-1], pf[1:], lg):
            if rest <= l_ + 1e-12:
                f = rest / l_ if l_ > 0 else 0.0
                return (p[0] + f * (q[0] - p[0]), p[1] + f * (q[1] - p[1]))
            rest -= l_
        return pf[-1]

    def hits(v):
        best = None
        for X_, Y_ in ((Pe, Q), (Q, Pa)):
            ex_, ey_ = Y_[0] - X_[0], Y_[1] - X_[1]
            det = v[0] * (-ey_) - v[1] * (-ex_)
            if abs(det) < 1e-12:
                continue
            rx, ry = X_[0] - C[0], X_[1] - C[1]
            t = (rx * (-ey_) - ry * (-ex_)) / det
            u_ = (v[0] * ry - v[1] * rx) / det
            if t > 0 and -1e-9 <= u_ <= 1 + 1e-9 and (best is None or t < best):
                best = t
        return best
    res = []
    for sv in ss:
        P_ = point(sv)
        v = (P_[0] - C[0], P_[1] - C[1])
        t = hits(v)
        if t is None:
            res.append(None)                           # no reliable intersection: gap instead of value
            continue
        res.append((s_e + sv, t * math.hypot(*v) * b1, sv))
    return res


def cone_data(g, geo):
    """Computes the sample points of the three cones. Returns: dict (s = path along the centreline)."""
    bend_geo, b1 = geo["bend_geo"], g["b1"]
    cum = geo["cum"]
    s_s2, s_s4, s_s5 = cum[1], geo["s4_cum"], cum[-1]
    bends = []
    for i, G in enumerate(bend_geo):
        s_e = cum[2 + 2 * i] - G["parts"][0]
        s_x = cum[3 + 2 * i] + G["parts"][2]
        w1, w2 = G["w1"], G["w2"]
        bends.append({"nr": i + 1, "s_e": s_e, "s_x": s_x, "A_e": w1 * b1, "A_x": w2 * b1,
                       "ratio": max(w1, w2) / min(w1, w2) if min(w1, w2) > 0 else float("inf")})
    s_s3 = s_s2 + g["l23_new"]
    actual_h = {"S1": (0.0, geo["area"]["S1"]), "S2": (s_s2, geo["area"]["S2"]), "S3": (s_s3, geo["area"]["S3"]),
             "S4": (s_s4, geo["area"]["S4"]), "S5": (s_s5, geo["area"]["S5"])}      # Hornresp values
    actual = dict(actual_h)                                                                  # built (actual) values
    # Equivalent areas for Hornresp are not necessarily the built cross-sections.
    # This also holds without a kink (S5 correction) and for S4 inside bend 6.
    actual["S1"] = (0.0, geo["S1_real"])
    actual["S5"] = (s_s5, geo["S5_real"])
    if geo["s4_in_bend"]:
        actual["S4"] = (s_s4, geo["S4_fan"])
    extra = []
    if geo["kink"]:
        # actual cone: built S1 and S5 (set above), plus the kink as a support point; the idealised cone keeps the Hornresp values
        a_, K, Ls, ex = g["a"], geo["K"], geo["Ls"], geo["ex"]
        s_k = _dist((Ls[0], a_ + (Ls[1] - a_) / 2), (K[0], a_ + (K[1] - a_) / 2))
        e_k = _unit_vec((K[0] - Ls[0], K[1] - Ls[1]))
        m_ = _unit_vec((e_k[0] + ex[0], e_k[1] + ex[1]))                              # mean direction of the underside at K
        t_ = _unit_vec((1.0 + m_[0], m_[1]))                                          # bisector of floor and underside
        extra = [("K", s_k, (K[1] - a_) / abs(t_[0]) * b1)]                          # chord perpendicular to it, K to floor
    step_len = 1.0 if g["unit"] == "cm" else 10.0               # step size 1 cm (or 10 mm) of bend path
    for bg, G in zip(bends, bend_geo):
        raw_f = _fan_profile(G, step_len, bg["s_e"], b1)
        bg["fans"] = [q_ for q_ in raw_f if q_ is not None]
        bg["fan_pieces"], cur = [], []            # contiguous pieces
        bg["fan_gaps"] = 0                        # number of runs without a reliable fan point
        prev_none = False
        for q_ in raw_f:
            if q_ is None and not prev_none:
                bg["fan_gaps"] += 1
            prev_none = q_ is None
            if q_ is None:
                if cur:
                    bg["fan_pieces"].append(cur)
                cur = []
            else:
                cur.append(q_)
        if cur:
            bg["fan_pieces"].append(cur)
    pkt = [("S1",) + actual["S1"], ("S2",) + actual["S2"], ("S3",) + actual["S3"], ("S4",) + actual["S4"], ("S5",) + actual["S5"]] + extra
    for bg in bends:
        pkt.append((f"E{bg['nr']}", bg["s_e"], bg["A_e"]))
        pkt.append((f"X{bg['nr']}", bg["s_x"], bg["A_x"]))
    pkt.sort(key=lambda t: (t[1], t[0]))

    def in_bend(s):
        for bg in bends:
            if bg["s_e"] + 1e-9 < s < bg["s_x"] - 1e-9:
                return bg
        return None
    segments = []
    for p_, q_ in zip(pkt[:-1], pkt[1:]):
        if q_[1] - p_[1] < 1e-9:
            continue
        bg = in_bend((p_[1] + q_[1]) / 2)
        segments.append({"s0": p_[1], "A0": p_[2], "s1": q_[1], "A1": q_[2], "bend": bg["nr"] if bg else None,
                         "uncertain": bool(bg and bg["ratio"] > RATIO_WARN)})
    # idealised: calculated S1..S5 at the drawn stations
    ideal = [actual_h[n] for n in ("S1", "S2", "S3", "S4", "S5")]
    ideal.sort()
    ref = g.get("ref")
    ref_pts = None
    ref_stations = None
    if ref:
        s = 0.0
        ref_pts = [(0.0, ref["S1"])]
        ref_stations = list(ref_pts)
        flares = ref.get("flares", ("Par",) * 4)
        for i, (nm, ln, fl) in enumerate((("S2", ref["L12"], ref["S2"]), ("S3", ref["L23"], ref["S3"]),
                                         ("S4", ref["L34"], ref["S4"]), ("S5", ref["L45"], ref["S5"]))):
            # Con: sqrt(area) linear; Par: area itself linear.
            if flares[i] == "Con":
                start = math.sqrt(ref_pts[-1][1])
                end = math.sqrt(fl)
                for j in range(1, 40):
                    t = j / 40
                    ref_pts.append((s + ln * t, (start + (end - start) * t) ** 2))
            s += ln
            ref_pts.append((s, fl))
            ref_stations.append((s, fl))

    def lin(tab, s):
        if s <= tab[0][0]:
            return tab[0][1]
        for (s0, A0), (s1, A1) in zip(tab[:-1], tab[1:]):
            if s0 <= s <= s1:
                return A0 + (A1 - A0) * (s - s0) / (s1 - s0) if s1 > s0 else A0
        return tab[-1][1]
    deviation = [(nm, s, A, A - lin(ideal, s), (A / lin(ideal, s) - 1) * 100 if lin(ideal, s) else float("nan"))
           for nm, s, A in pkt]
    for bg in bends:                                  # all fan samples enter the deviation as well
        for s_, A_, _ in bg["fans"]:
            i_ = lin(ideal, s_)
            deviation.append(("F", s_, A_, A_ - i_, (A_ / i_ - 1) * 100 if i_ else float("nan")))
    deviation.sort(key=lambda t: t[1])
    return {"stations": actual, "points": pkt, "segments": segments, "bends": bends, "ideal": ideal,
            "ref": ref_pts, "ref_stations": ref_stations, "deviation": deviation, "lin": lin}


def cone_svg(kd, x0, y0, width, u):
    """SVG fragments of the cone plot (space: width x approx. 560 px from (x0, y0)). Returns (list, height)."""
    out = []
    ml, mr = 70, 30
    pw = width - ml - mr
    top, h1_, gap, h2_ = 50, 330, 70, 120
    s_max = max(kd["stations"]["S5"][0], max(p[1] for p in kd["points"]), max(p[0] for p in (kd["ref"] or [(0, 0)]))) * 1.02
    allA = [p[2] for p in kd["points"]] + [f_[1] for bg in kd["bends"] for f_ in bg["fans"]] + [p[1] for p in kd["ideal"]] + [p[1] for p in (kd["ref"] or [])]
    a_max = max(allA) * 1.08
    a_min = 0.0
    ds = [t[4] for t in kd["deviation"] if math.isfinite(t[4])]
    d_lim = max(1.0, math.ceil(max(abs(v) for v in ds) * 1.1)) if ds else 1.0

    def sx(s): return x0 + ml + s / s_max * pw
    def sy(A): return y0 + top + h1_ - (A - a_min) / (a_max - a_min) * h1_
    def dy(p): return y0 + top + h1_ + gap + h2_ / 2 - p / d_lim * h2_ / 2

    def step(m, n=8):
        raw = m / n
        e = 10 ** math.floor(math.log10(raw))
        for f in (1, 2, 2.5, 5, 10):
            if raw <= f * e:
                return f * e
        return 10 * e
    out.append(f'<text x="{x0 + ml}" y="{y0 + 18}" style="font:bold 15px sans-serif;fill:#222">'
               f'Unfolded horn profile: cross-sectional area over the path along the centreline</text>')
    # bend regions
    # grid and axes
    st = step(a_max - a_min)
    v = 0.0
    while v <= a_max:
        out.append(f'<line x1="{x0 + ml}" y1="{sy(v):.1f}" x2="{x0 + ml + pw}" y2="{sy(v):.1f}" stroke="#ccc" stroke-width="0.6"/>')
        out.append(f'<text x="{x0 + ml - 6}" y="{sy(v) + 4:.1f}" style="font:10px sans-serif;fill:#333;text-anchor:end">{v:g}</text>')
        v += st
    st = step(s_max, 10)
    v = 0.0
    while v <= s_max:
        out.append(f'<line x1="{sx(v):.1f}" y1="{y0 + top}" x2="{sx(v):.1f}" y2="{y0 + top + h1_}" stroke="#ddd" stroke-width="0.6"/>')
        out.append(f'<text x="{sx(v):.1f}" y="{y0 + top + h1_ + 14}" style="font:10px sans-serif;fill:#333;text-anchor:middle">{v:g}</text>')
        v += st
    out.append(f'<rect x="{x0 + ml}" y="{y0 + top}" width="{pw}" height="{h1_}" fill="none" stroke="#333"/>')
    out.append(f'<text x="{x0 + ml + pw / 2}" y="{y0 + top + h1_ + 30}" style="font:11px sans-serif;fill:#333;text-anchor:middle">'
               f'Path s along the centreline [{u}]</text>')
    out.append(f'<text transform="translate({x0 + 14},{y0 + top + h1_ / 2}) rotate(-90)" '
               f'style="font:11px sans-serif;fill:#333;text-anchor:middle">Area [{u}²]</text>')
    # a) reference
    if kd["ref"]:
        out.append('<polyline fill="none" stroke="#0b5ed7" stroke-width="2" stroke-dasharray="8 4" points="'
                   + " ".join(f"{sx(s):.1f},{sy(A):.1f}" for s, A in kd["ref"]) + '"/>')
        for s, A in kd.get("ref_stations") or kd["ref"]:
            out.append(f'<circle cx="{sx(s):.1f}" cy="{sy(A):.1f}" r="3.5" fill="#fff" stroke="#0b5ed7" stroke-width="1.5"/>')
    # b) idealised
    out.append('<polyline fill="none" stroke="#2e8b57" stroke-width="2" points="'
               + " ".join(f"{sx(s):.1f},{sy(A):.1f}" for s, A in kd["ideal"]) + '"/>')
    # c) actual
    for sg in kd["segments"]:
        if sg["bend"] is None:
            out.append(f'<line x1="{sx(sg["s0"]):.1f}" y1="{sy(sg["A0"]):.1f}" x2="{sx(sg["s1"]):.1f}" y2="{sy(sg["A1"]):.1f}" '
                       f'stroke="#c0392b" stroke-width="2.6"/>')
    for bg in kd["bends"]:            # bend: fan around the inner corner, one value per path step
        for piece in bg["fan_pieces"]:
            if len(piece) > 1:
                out.append('<polyline fill="none" stroke="#c0392b" stroke-width="2.2" points="'
                           + " ".join(f"{sx(s_):.1f},{sy(A_):.1f}" for s_, A_, _ in piece) + '"/>')
    for nm, s, A in kd["points"]:
        if nm[0] in "EX":
            out.append(f'<circle cx="{sx(s):.1f}" cy="{sy(A):.1f}" r="2" fill="#c0392b"/>')
    # stations
    for nm, (s, A) in kd["stations"].items():
        out.append(f'<line x1="{sx(s):.1f}" y1="{y0 + top - 8}" x2="{sx(s):.1f}" y2="{y0 + top + h1_}" '
                   f'stroke="#7b2cbf" stroke-width="1" stroke-dasharray="5 3"/>')
        out.append(f'<circle cx="{sx(s):.1f}" cy="{sy(A):.1f}" r="4.2" fill="#c0392b" stroke="#fff"/>')
        out.append(f'<text x="{sx(s):.1f}" y="{y0 + top - 12}" style="font:bold 11px sans-serif;fill:#7b2cbf;text-anchor:middle">{nm}</text>')
    # legend
    lx, ly = x0 + ml + 10, y0 + top + 14
    leg = [("#0b5ed7", "8 4", 2, "a) Reference (input / Hornresp)"),
           ("#2e8b57", "", 2, "b) Linear-area model / Par (calculated S1-S5, path from drawing)"),
           ("#c0392b", "", 2.6, "c) Actual: straight sections ⟂ centreline, bends as fan around the inner corner (1 path step each)")]
    for i, (col, da, sw, txt) in enumerate(leg):
        yy = ly + i * 15
        out.append(f'<line x1="{lx}" y1="{yy}" x2="{lx + 30}" y2="{yy}" stroke="{col}" stroke-width="{sw}"'
                   + (f' stroke-dasharray="{da}"' if da else '') + '/>')
        out.append(f'<text x="{lx + 36}" y="{yy + 4}" style="font:10px sans-serif;fill:#333">{txt}</text>')
    # deviation actual - ideal
    out.append(f'<text x="{x0 + ml}" y="{y0 + top + h1_ + gap - 14}" style="font:bold 12px sans-serif;fill:#222">'
               f'Deviation of actual (c) from idealised (b): stations, bend entries/exits and every fan sample [%]</text>')
    out.append(f'<rect x="{x0 + ml}" y="{dy(d_lim):.1f}" width="{pw}" height="{h2_}" fill="none" stroke="#333"/>')
    for p in (-d_lim, 0, d_lim):
        out.append(f'<line x1="{x0 + ml}" y1="{dy(p):.1f}" x2="{x0 + ml + pw}" y2="{dy(p):.1f}" stroke="#bbb" stroke-width="0.6"/>')
        out.append(f'<text x="{x0 + ml - 6}" y="{dy(p) + 4:.1f}" style="font:10px sans-serif;fill:#333;text-anchor:end">{p:+g}</text>')
    for bg in kd["bends"]:                           # fan samples: continuous line per piece (gaps stay open)
        for piece in bg["fan_pieces"]:
            pts_ = [(s_, kd["lin"](kd["ideal"], s_)) for s_, A_, _ in piece]
            dev = [(s_, (A_ / i_ - 1) * 100) for (s_, A_, _), (_, i_) in zip(piece, pts_) if i_]
            if len(dev) > 1:
                out.append('<polyline fill="none" stroke="#c0392b" stroke-width="1.4" points="'
                           + " ".join(f"{sx(s_):.1f},{dy(d_):.1f}" for s_, d_ in dev) + '"/>')
    for nm, s, A, da_, dp in kd["deviation"]:
        if not math.isfinite(dp) or nm == "F":
            continue
        col = "#c0392b" if nm[0] == "S" else "#888"
        out.append(f'<line x1="{sx(s):.1f}" y1="{dy(0):.1f}" x2="{sx(s):.1f}" y2="{dy(dp):.1f}" stroke="{col}" stroke-width="2"/>')
        out.append(f'<circle cx="{sx(s):.1f}" cy="{dy(dp):.1f}" r="2.8" fill="{col}"/>')
        if nm[0] == "S":
            yy = dy(dp) - 6 if dp >= 0 else dy(dp) + 14
            out.append(f'<text x="{sx(s):.1f}" y="{yy:.1f}" style="font:bold 10px sans-serif;fill:#7b2cbf;text-anchor:middle">{nm} {dp:+.2f}</text>')
    h = top + h1_ + gap + h2_ + 30
    return out, h



def _inner_angle(p, q, r):
    """Interior angle at corner q between the edges q->p and q->r, in degrees (90 = square cut)."""
    v1, v2 = (p[0] - q[0], p[1] - q[1]), (r[0] - q[0], r[1] - q[1])
    c = (v1[0] * v2[0] + v1[1] * v2[1]) / (math.hypot(*v1) * math.hypot(*v2))
    return math.degrees(math.acos(max(-1.0, min(1.0, c))))


def _fmt_cut(entry):
    """Text for the cut list: gross length, long face, end angles (90 = square)."""
    lab, name, length, w_, d_, n_, a1, a2, area = entry
    ang = "square ends" if abs(a1 - 90) < 0.05 and abs(a2 - 90) < 0.05 else f"end angles {a1:.1f} / {a2:.1f} deg"
    side = f" (long face: {area})" if area and ang != "square ends" else ""
    return f"{length:.1f} x {w_:.1f} x {d_:g}  {ang}{side}" + (f"  x{n_}" if n_ > 1 else "")


def draw_svg(g, filename="horn_folding.svg"):
    """Draws the construction (from g['geo']) as SVG and returns (checks, cutlist, geo)."""
    geo = g["geo"]
    u = g["unit"]
    a, T, H, b1 = g["a"], g["T"], g["H"], g["b1"]
    xl, xr, zc = a, T - a, H - a
    G, Cs, poly_ = geo["bend_geo"], geo["C"], geo["poly"]
    C1, C2, C3, C4, C5, C6 = Cs
    en = geo["en"]
    Wi = g["Width"] - 2 * a                       # inner width between the side panels
    Ls, Lu, Ld_t, Ld_l = geo["Ls"], geo["Lu"], geo["Ld_t"], geo["Ld_l"]
    Lu0, Ld0 = geo["Lu0"], geo["Ld0"]
    section, fl = geo["section"], geo["area"]

    # --- Cut list (length top / bottom for angled ends) -----------------------------------------
    a_up_r = _add(C1, en, a)                          # top right corner of board a

    def cut_quad(q0, q1, q2, q3):
        """Cut data of a board with the corners q0 (lower left), q1 (lower right), q2 (upper right), q3 (upper left)."""
        low, up = _dist(q0, q1), _dist(q3, q2)
        if low >= up:
            return (low, _inner_angle(q1, q0, q3), _inner_angle(q0, q1, q2), "lower")
        return (up, _inner_angle(q2, q3, q0), _inner_angle(q3, q2, q1), "upper")
    if geo["kink"]:
        cut_a1 = cut_quad(Ls, geo["K"], geo["K_up"], Lu)
        cut_a = cut_quad(geo["K"], C1, a_up_r, geo["K_up"])          # a2 (driver board)
    else:
        a_low_len, a_up_len = _dist(Ls, C1), _dist(Lu, a_up_r)
        if a_low_len >= a_up_len:                          # gross length = longest face
            cut_a = (a_low_len, _inner_angle(C1, Ls, Lu), _inner_angle(Ls, C1, a_up_r), "lower")
        else:
            cut_a = (a_up_len, _inner_angle(a_up_r, Lu, Ls), _inner_angle(Lu, a_up_r, C1), "upper")
    c_low_r = _add(C2, en, -a)
    top_c, bot_c = _dist(C2, C3), _dist(c_low_r, C4)
    if top_c >= bot_c:
        cut_c = (top_c, _inner_angle(C2, C3, C4), _inner_angle(C3, C2, c_low_r), "top")
    else:
        cut_c = (bot_c, _inner_angle(c_low_r, C4, C3), _inner_angle(C4, c_low_r, C2), "bottom")
    top_d, bot_d = _dist(Ld_t, C5), _dist(Ld_l, C6)
    if top_d >= bot_d:
        cut_d = (top_d, _inner_angle(C5, Ld_t, Ld_l), _inner_angle(Ld_t, C5, C6), "top")
    else:
        cut_d = (bot_d, _inner_angle(C6, Ld_l, Ld_t), _inner_angle(Ld_l, C6, C5), "bottom")
    # D1 / D2: vertical boards; the top edge of D1 and the bottom edge of D2 are bevelled to continue the slopes of a / d
    cut_d1 = cut_quad((0.0, a), Lu0, Lu, (xl, a))
    cut_d2 = cut_quad(Ld0, (0.0, zc), (xl, zc), Ld_l)
    side_ = {"lower": "outer", "upper": "inner"}
    cutlist = [
        *([("a1", "Baffle, mouth part", cut_a1[0], Wi, a, 1, cut_a1[1], cut_a1[2], cut_a1[3])] if geo["kink"] else []),
        ("a2" if geo["kink"] else "a", "Baffle (driver)", cut_a[0], Wi, a, 1, cut_a[1], cut_a[2], cut_a[3]),
        ("b", "Angled right wall", _dist(C1, C2) - 2 * a, Wi, a, 1, 90.0, 90.0, ""),
        ("c", "Upper intermediate board", cut_c[0], Wi, a, 1, cut_c[1], cut_c[2], cut_c[3]),
        ("d", "Lower intermediate board", cut_d[0], Wi, a, 1, cut_d[1], cut_d[2], cut_d[3]),
        ("A", "Floor", T, Wi, a, 1, 90.0, 90.0, ""),
        ("B", "Right wall", H - 2 * a, Wi, a, 1, 90.0, 90.0, ""),
        ("C", "Ceiling", T, Wi, a, 1, 90.0, 90.0, ""),
        ("D1", "Left wall, lower", cut_d1[0], Wi, a, 1, cut_d1[1], cut_d1[2], side_[cut_d1[3]]),
        ("D2", "Left wall, upper", cut_d2[0], Wi, a, 1, cut_d2[1], cut_d2[2], side_[cut_d2[3]]),
        ("E/F", "Side panels", T, H, a, 2, 90.0, 90.0, ""),
    ]
    checks = {"S2 area: drawing - input": fl["S2"] - g["S2"]}
    for f in geo["folds"]:
        if not f.get("free_exit"):
            checks[f"Bend {f['nr']} exit: width - law"] = f["G"]["w2"] - f["law_out"]
        checks[f"Bend {f['nr']} entry: width - law"] = f["G"]["w1"] - f["law_in"]

    margin = 40
    W = 1200
    kk = (W - 2 * margin) / T                        # box drawing spans the full width; text below, profiles last
    Hp = H * kk + 2 * margin

    def X(x): return margin + x * kk
    def Z(z): return margin + (H - z) * kk

    def poly(points, css_class):
        return f'<polygon class="{css_class}" points="' + " ".join(f"{X(x):.2f},{Z(z):.2f}" for x, z in points) + '"/>'

    parts = [poly([(xl, a), (xr, a), (xr, zc), (xl, zc)], "luft"),
             poly(geo["mouth_poly"], "luft"),                 # mouth opening through the front wall
             poly([(0, 0), (T, 0), (T, a), (0, a)], "holz"),                               # A
             poly([(0, H - a), (T, H - a), (T, H), (0, H)], "holz"),                       # C
             poly([(T - a, a), (T, a), (T, H - a), (T - a, H - a)], "holz"),               # B
             poly([(0, a), (a, a), Lu, Lu0], "holz"),                                         # D1
             poly([Ld0, Ld_l, (a, H - a), (0, H - a)], "holz")]                            # D2
    poly_z = dict(poly_)                                  # boards as drawn (a is split at the kink)
    if geo["kink"]:
        del poly_z["a"]
        poly_z["a1"] = [Ls, geo["K"], geo["K_up"], Lu]
        poly_z["a2"] = [geo["K"], C1, _add(C1, en, a), geo["K_up"]]
    for nm_ in poly_z:
        parts.append(poly(poly_z[nm_], "holz"))
    if geo["kink"]:                                                        # joint between a1 and a2
        parts.append(f'<line x1="{X(geo["K"][0]):.1f}" y1="{Z(geo["K"][1]):.1f}" x2="{X(geo["K_up"][0]):.1f}" '
                     f'y2="{Z(geo["K_up"][1]):.1f}" stroke="#7a5a2e" stroke-width="1"/>')
    marks_b = {nm_: (sum(p[0] for p in pg) / len(pg), sum(p[1] for p in pg) / len(pg)) for nm_, pg in poly_z.items()}
    marks_b.update({"A": (T / 2, a / 2), "B": (T - a / 2, H / 2), "C": (T / 2, H - a / 2),
                     "D1": (a / 2, (a + Lu[1]) / 2), "D2": (a / 2, (Ld_l[1] + H - a) / 2)})
    for nm_, (x, z) in marks_b.items():
        parts.append(f'<text class="bl" x="{X(x):.1f}" y="{Z(z) + 4:.1f}">{nm_}</text>')

    # --- Bends: auxiliary lines ------------------------------------------------------------------------
    for idx, Gb in enumerate(G, 1):
        def ln(p_, q, kl):
            parts.append(f'<line class="{kl}" x1="{X(p_[0]):.1f}" y1="{Z(p_[1]):.1f}" x2="{X(q[0]):.1f}" y2="{Z(q[1]):.1f}"/>')
        ln(Gb["C"], Gb["Ci"], "sek")
        ln(Gb["C"], Gb["Cx"], "sek")
        ln(Gb["C"], Gb["O1"], "faecher")
        ln(Gb["C"], Gb["O2"], "faecher")
        for n_ in ("O1", "O2"):
            parts.append(f'<circle class="po" cx="{X(Gb[n_][0]):.1f}" cy="{Z(Gb[n_][1]):.1f}" r="2.5"/>')
        parts.append(f'<circle class="pc" cx="{X(Gb["C"][0]):.1f}" cy="{Z(Gb["C"][1]):.1f}" r="3.5"/>')
        parts.append(f'<text class="lbc" x="{X(Gb["C"][0]) - 4:.1f}" y="{Z(Gb["C"][1]) - 6:.1f}">C{idx}</text>')
    pts = geo["path_pts"]
    parts.append('<polyline class="weg" points="' + " ".join(f"{X(x):.1f},{Z(z):.1f}" for x, z in pts) + '"/>')
    for idx, Gb in enumerate(G, 1):
        for n_ in ("A", "B"):
            parts.append(f'<circle class="pa" cx="{X(Gb[n_][0]):.1f}" cy="{Z(Gb[n_][1]):.1f}" r="3.2"/>')
            parts.append(f'<text class="lbr" x="{X(Gb[n_][0]) + 4:.1f}" y="{Z(Gb[n_][1]) + 12:.1f}">{n_}{idx}</text>')
    pp = [(X(x), Z(z)) for x, z in pts]
    for (x0, y0), (x1_, y1_) in zip(pp[:-1], pp[1:]):
        L = math.hypot(x1_ - x0, y1_ - y0)
        if L < 6 * kk:
            continue
        mx, my = (x0 + x1_) / 2, (y0 + y1_) / 2
        dx, dy = (x1_ - x0) / L, (y1_ - y0) / L
        sp = (mx + dx * 7, my + dy * 7)
        l_ = (mx - dx * 5 - dy * 5, my - dy * 5 + dx * 5)
        r_ = (mx - dx * 5 + dy * 5, my - dy * 5 - dx * 5)
        parts.append(f'<polygon class="pfeil" points="{sp[0]:.1f},{sp[1]:.1f} {l_[0]:.1f},{l_[1]:.1f} {r_[0]:.1f},{r_[1]:.1f}"/>')
    foot = section["S4"][1]
    section = dict(section)
    section["S4"] = geo["S4_drawing"]               # drawn line (in bend 6: length = calculated cross-section)
    if C6[0] < foot[0] and not geo["s4_in_bend"]:                      # d is shorter than the S4 line: imaginary extension
        parts.append(f'<line class="verl" x1="{X(C6[0]):.1f}" y1="{Z(C6[1]):.1f}" x2="{X(foot[0]):.1f}" y2="{Z(foot[1]):.1f}"/>')
    for name, (p_, q) in section.items():
        parts.append(f'<line class="quer" x1="{X(p_[0]):.1f}" y1="{Z(p_[1]):.1f}" x2="{X(q[0]):.1f}" y2="{Z(q[1]):.1f}"/>')
    for name, (p_, q) in section.items():
        x, z = (p_[0] + q[0]) / 2, (p_[1] + q[1]) / 2
        parts.append(f'<circle class="marke" cx="{X(x):.1f}" cy="{Z(z):.1f}" r="9"/>')
        parts.append(f'<text class="mt" x="{X(x):.1f}" y="{Z(z) + 4:.1f}">{name}</text>')

    # --- Info column ----------------------------------------------------------------------------------
    d1_bottom, d1_top = geo["d1"]
    lines = [
        ("t", "Hornfolding - section (side view)"),
        ("n", f"Lengths in {u}, areas in {u}², 1 {u} = {kk:.1f} px"),
        ("n", f"Outside {T:g} x {H:g} {u} (depth x height), wood {a:g} {u}"),
        ("n", f"Width law W(s) = {g['W2']:.3f} + {g['b']:.5f} s (s = path from S2), channel width b1 = {b1:.2f} {u}"),
        ("n", f"Board a in two parts a1/a2 (kink {geo['t_kink']:.1f} {u} from the driver centre; S1, S5 = Hornresp values)"
              if geo["kink"] else
              "Board a runs straight through without a kink (Hornresp S1 from built volume)"),
        ("n", ""), ("h", "Result"),
        ("n", f"S1 = {geo['area']['S1']:.1f}     Path S1-S2 = {g['path_s1_s2']:.2f}"),
        ("n", f"S2 = {g['S2']:.1f}     Path S2-S3 = {g['l23_new']:.2f}"),
        ("n", f"S3 = {fl['S3']:.1f}     Path S3-S4 = {g['path_s3_s4']:.2f}"),
        ("n", f"S4 = {fl['S4']:.1f}     Path S4-S5 = {g['path_s4_s5']:.2f}"),
        ("n", f"S5 = {fl['S5']:.1f}"),
        *([("n", f"built (real): S1 = {geo['S1_real']:.1f},  S5 = {geo['S5_real']:.1f}")] if geo["kink"] else []),
        ("n", ""), ("h", f"Slopes (S3 at position {g['k']})"),
        ("n", f"b  (S2-S3) = {g['b']:.5f}   area gradient b1*b  = {b1 * g['b']:.3f} {u}²/{u}"),
        ("n", f"b' (S3-S4) = {g['b_after']:.5f}   area gradient b1*b' = {b1 * g['b_after']:.3f} {u}²/{u}"),
        ("n", "b = width increase per path length; linear area = Hornresp Par, not Con"),
        ("n", ""), ("h", "Construction check"),
    ]
    for name, value in checks.items():
        lines.append(("n", f"{name}: {value:+.3f} {u + '²' if 'area' in name else u}"))
    if abs(g["S1"] - geo["s1_same"]) > 0.5:
        lines.append(("n", f"S1 = {g['S1']:.1f} deviates from the continuous slope ({geo['s1_same']:.1f})"))
        if not geo["kink"]:
            lines.append(("n", "Without a kink the specified S1 has no effect: Hornresp S1 and S5 follow from the built volumes"))
    lines += [("n", ""), ("h", "Path segments per bend: straight + chord + straight")]
    for nm_, w1_, w2_, th_, (a1_, ch_, b2_) in g["bends"]:
        lines.append(("n", f"{nm_.split(' (')[0]}: {th_:.1f} deg, {w1_:.1f} -> {w2_:.1f}:  "
                            f"{a1_:.2f} + {ch_:.2f} + {b2_:.2f} = {a1_ + ch_ + b2_:.2f}"))
    lines += [("n", "Driver centre: distance from the inner face of D1"),
               ("n", f"along board a: underside {d1_bottom:.2f}, top side {d1_top:.2f} {u}"),
               ("n", f"Air {liter(geo['vol_air']):.1f} l (mouth {liter(geo['vol_mouth']):.1f} l), "
                     f"path volume {liter(geo['vol_path']):.1f} l "
                     f"({geo['vol_path'] / geo['vol_air'] * 100:.1f} %)")]
    for nm_, r_ in geo["ratios"]:
        if r_ > RATIO_WARN:
            lines.append(("n", f"WARNING {nm_.split(' (')[0]}: cross-section ratio {r_:.2f} > {RATIO_WARN},"))
            lines.append(("n", "  bend approximation uncertain."))
    if s4_bend6_level(geo) == 2:
        lines += [("n", "WARNING: S4 lies in bend 6 BEFORE B6 -"), ("n", "  S4 is a theoretical value (line drawn with its length);"),
                   ("n", "  reconsider driver position / box.")]
    elif s4_bend6_level(geo) == 1:
        lines += [("n", "Note: S4 lies inside bend 6 (behind B6);"), ("n", "  S4 is a theoretical value (line drawn with its length).")]
    lines += [("n", f"Largest bend cross-section {geo['w_max']:.1f} {u} = λ/4 at approx. {lambda4_limit(geo['w_max']):.0f} Hz"),
               ("n", f"Total path length S1-S5 = {g['total']:.2f} {u}"),
               ("n", "Inner boards meet at right angles (butt joints).")]
    lines += [("n", ""), ("h", f"Cut list (length x width x thickness, {u})")]
    for entry in cutlist:
        lines.append(("n", f"{entry[0]:<4}{entry[1]}: {_fmt_cut(entry)}"))
    lines += [("n", "Length = gross length of the longest face; end angle 90 = square cut."),
               ("n", "Angle = interior angle of the board at the two ends of that face."),
               ("n", ""), ("h", "Notes"),
               ("n", "C = inner corner; grey dashed: cross-sections of the bends,"),
               ("n", "perpendicular to the angle bisector of the channel walls."),
               ("n", "Blue: C to centre O (cross-section end - outer corner)."),
               ("n", "A, B = intersections of the centreline (red) with the blue lines."),
               ("n", "Purple dashed: cross-sections S1-S5."),
               ("n", "S2, S3, S4 are perpendicular to the centreline."),
               ("n", "S2/S4 pass through the driver centre on board a."),
               ("n", "S1 and S5 (openings) are vertical."),
               ("n", "Area = line length x net width."),
               ("n", "Brace width is deducted from the channel width (all areas);"),
               ("n", "braces and driver are not drawn, their position is not modelled."),
               ("n", "Check values near 0 = construction follows the law.")]
    def i_ab(mark):
        return next(i for i, z in enumerate(lines) if z[0] == "h" and z[1].startswith(mark))
    i_check, i_cut = i_ab("Construction check"), i_ab("Cut list")
    top_edge, block_a, block_b = lines[:i_check], lines[i_check:i_cut - 1], lines[i_cut:]

    def text_block(lst, x, y0):
        for i, (kind, text) in enumerate(lst):
            parts.append(f'<text class="{kind}" x="{x:.0f}" y="{y0 + i * 19}">{escape(text)}</text>')
        return y0 + len(lst) * 19
    column = (W - 2 * margin) / 2
    y_text = Hp + 5
    ya = text_block(top_edge + [("n", "")] + block_a, margin, y_text)
    yb = text_block(block_b, margin + column, y_text)
    Hp = max(ya, yb) + 30
    kd = cone_data(g, geo)
    # Fan profile piece by piece (a gap without a reliable fan point is closed by the neighbouring support points:
    # bend entry/exit areas are part of kd["points"]; inside a bend the neighbouring pieces are joined by a straight line).
    tab_f = sorted([(s_, A_) for _, s_, A_ in kd["points"]] +
                   [(s_, A_) for bg in kd["bends"] for piece in bg["fan_pieces"] for s_, A_, _ in piece])
    geo["fan_gaps"] = sum(bg["fan_gaps"] for bg in kd["bends"])
    geo["vol_fans"] = sum((s2_ - s1_) * (A1_ + A2_) / 2 for (s1_, A1_), (s2_, A2_) in zip(tab_f[:-1], tab_f[1:]))
    geo["inertia_fans"] = integrate_inertia(tab_f)
    cone_parts, cone_h = cone_svg(kd, 0, Hp, W, u)
    parts += cone_parts
    Hp += cone_h
    if filename is None:
        return checks, cutlist, geo
    svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{W:.0f}" height="{Hp:.0f}" viewBox="0 0 {W:.0f} {Hp:.0f}">\n'
        '<style>\n'
        '.holz{fill:#dcb98a;stroke:#7a5a2e;stroke-width:1}\n.luft{fill:#e9f2fb;stroke:none}\n'
        '.weg{fill:none;stroke:#c0392b;stroke-width:2.5;stroke-linejoin:round}\n'
        '.verl{stroke:#7a5a2e;stroke-width:1.5;stroke-dasharray:2 3}\n'
        '.quer{stroke:#7b2cbf;stroke-width:1.8;stroke-dasharray:7 4}\n'
        '.sek{stroke:#888;stroke-width:1;stroke-dasharray:4 3}\n'
        '.faecher{stroke:#0b5ed7;stroke-width:1.1}\n'
        '.pa{fill:#c0392b}.po{fill:#0b5ed7}.pc{fill:#222}\n'
        '.lbr{font:bold 8px sans-serif;fill:#c0392b}.lbc{font:bold 9px sans-serif;fill:#222}\n'
        '.pfeil{fill:#c0392b}\n'
        '.marke{fill:#fff;stroke:#c0392b;stroke-width:1.5}\n'
        '.mt{font:bold 9px sans-serif;text-anchor:middle;fill:#c0392b}\n'
        '.bl{font:bold 9px sans-serif;fill:#4a2f0b;text-anchor:middle}\n'
        '.t{font:bold 15px sans-serif;fill:#222}\n.h{font:bold 12px sans-serif;fill:#222}\n.n{font:12px sans-serif;fill:#333}\n'
        '</style>\n'
        f'<rect width="{W:.0f}" height="{Hp:.0f}" fill="#ffffff"/>\n' + "\n".join(parts) + "\n</svg>\n")
    with open(filename, "w", encoding="utf-8") as fh:
        fh.write(svg)
    return checks, cutlist, geo



# ---------------------------------------------------------------------------
# Main program
# ---------------------------------------------------------------------------
def main(argv=None):
    """Coordinates dialog and files; argv makes the command line testable."""
    parser = argparse.ArgumentParser(description="Fold a horn channel into a rectangular enclosure.")
    parser.add_argument("input", nargs="?", help="Input file or exported Hornresp file (no prompting)")
    parser.add_argument("--batch", action="store_true", help="Use saved values without prompting; fail if required values are missing")
    parser.add_argument("--output-dir", type=Path, help="Directory for generated files and the saved input")
    parser.add_argument("--no-save-input", action="store_true", help="Do not save the input values of this run")
    args = parser.parse_args(argv)
    folder = str((args.output_dir or Path(__file__).resolve().parent).resolve())
    L, F = UNIT, UNIT + "²"
    try:
        sys.stdout.reconfigure(errors="replace")      # console/pipe with a narrow code page (Windows): never crash on a special character
    except (AttributeError, ValueError):
        pass
    print(f"Hornfolding Version {VERSION}")
    print(f"All lengths in {L}, all areas in {F}.\n")
    print("Model: linear area expansion = Hornresp flare type Par (parallel side walls). Do NOT use Con.\n")

    # Input file (last used values)
    values = {}
    fast = False
    filepath, explicit = find_input_file(args.input)
    batch = args.batch or explicit
    hr_path = None
    if filepath is not None and os.path.exists(filepath) and is_hornresp_file(filepath):
        hr_path = filepath                                  # a Hornresp file was passed: other values come from the normal input file
        filepath, explicit = None, False
        std = os.path.join(os.path.dirname(os.path.abspath(__file__)), INPUT_FILE)
        if os.path.exists(std):
            filepath = std
    if filepath is not None:
        if not os.path.exists(filepath):
            raise FoldingError(f"Input file not found: {filepath}")
        values = load_input_file(filepath)
        print(f"Values from {filepath}\nEnter accepts the displayed value, typing something overrides it.\n")
        fast = True if batch else accept_all()
        print()
    else:
        fast = batch
    if hr_path is None and values.get("hornresp") and values["hornresp"].lower() not in ("auto", "none", ""):
        # Relative references belong to the input file, not to the working directory.
        hr_path = os.path.expanduser(values["hornresp"])
        if not os.path.isabs(hr_path):
            hr_path = os.path.join(os.path.dirname(os.path.abspath(filepath)), hr_path)
        hr_path = os.path.abspath(hr_path)
        if not os.path.exists(hr_path):
            raise FoldingError(f"Hornresp file not found: {hr_path}")
    hr_values = None
    if hr_path is not None:
        hr_values = read_hornresp(hr_path)
        if "Con" in hr_values["flares"]:
            print("WARNING: imported Con segments differ from the linear-area model used for folding and volume matching.")
            print("  Reference plot: imported flares. Volume/inertance checks: linear area (Par).")
            print("  Export: flare types of the source file are kept unchanged. Set all four segments to Par in Hornresp.")
        values.update({"hornresp": hr_path, "mode": "1", "s1": f"{hr_values['S1']:g}", "s2": f"{hr_values['S2']:g}",
                      "s3": f"{hr_values['S3']:g}", "l23": f"{hr_values['L23']:g}", "s4": f"{hr_values['S4']:g}",
                      "s5": f"{hr_values['S5']:g}"})
        print(f"Hornresp file: {hr_path}")
        print(f"  S1 = {hr_values['S1']:g}, S2 = {hr_values['S2']:g}, S3 = {hr_values['S3']:g} (L23 = {hr_values['L23']:g}), "
              f"S4 = {hr_values['S4']:g}, S5 = {hr_values['S5']:g}; lengths L12 = {hr_values['L12']:g}, "
              f"L34 = {hr_values['L34']:g}, L45 = {hr_values['L45']:g}")
        print("  taken over: S1, S2, S3, L23; S4, S5 and the lengths L12, L34, L45 as comparison values; mode 1.\n")
    entries = InputDialog(values, fast)

    a = entries.ask("wood_thickness", f"Wood thickness a [{L}]", p_number(0, True))
    brace = entries.ask("brace_width", f"Brace width [{L}]", p_number(0))
    width = entries.ask("width", f"Width [{L}]", p_number(0, True))
    height = entries.ask("height", f"Height [{L}]", p_number(0, True))
    depth = entries.ask("depth", f"Depth [{L}]", p_number(0, True))

    b1 = width - brace - 2 * a
    d = height - 2 * a
    e = depth - 2 * a

    print(f"\nNet width (at S2 and S3): {b1:.4f} {L}")
    print(f"Net height: {d:.4f} {L}")
    print(f"Net depth: {e:.4f} {L}")
    for name, value in (("Net width", b1), ("Net height", d), ("Net depth", e)):
        if value <= 0:
            raise FoldingError(f"{name} is {value:.2f} {L} - the dimensions are inconsistent "
                                 f"(wood thickness/brace too large or enclosure too small).")

    # Horn values in the order of Hornresp: S1, S2, S3 (or the slope), L23, S4, S5; then the driver position
    S1 = entries.ask("s1", f"Area S1 [{F}]  (number or 'auto' = same slope throughout)",
                   p_number(0, words={"auto": None}), default="auto")
    S2 = entries.ask("s2", f"Area S2 [{F}]", p_number(0, True))

    W2 = S2 / b1                       # width of the S2 chord (perpendicular to the centreline)
    if W2 < a:
        print(f"\nWARNING: Channel width at the throat W2 = {W2:.3f} {L} is smaller than the "
              f"wood thickness ({a} {L}). Does the unit of S2 ({F}) match the lengths ({L})?")

    choice = entries.ask("mode", "Mode: 1 = specify S3 and L23, 2 = specify slope",
                     p_choice(("1", "2")))
    l23_wanted = None
    S3_wanted = None
    if choice == "1":
        S3_wanted = entries.ask("s3", f"Area S3 [{F}]", p_number(0, True))
        l23_wanted = entries.ask("l23", f"Length L23 (S2 to S3) [{L}]", p_number(0, True))
        b = (S3_wanted / b1 - W2) / l23_wanted      # width law W(s) = W2 + b*s, exact along the centreline
        print(f"Calculated slope b: {b}")
    else:
        b = entries.ask("slope", "Slope of the line (height increase per path length, e.g. 0.1)", p_number())

    print(f"\nW2 (S2 chord): {W2:.5f} {L}")
    print(f"Slope (b): {b}")

    psi_ = _ang(b)
    if math.cos(psi_) < COS_PSI_MIN:
        raise FoldingError(f"Slope b = {b:g} gives a wedge angle of {math.degrees(psi_):.1f} deg between the boards "
                             f"(maximum {math.degrees(math.acos(COS_PSI_MIN)):.0f} deg, i.e. |b| < "
                             f"{2 * math.tan(math.acos(COS_PSI_MIN) / 2):.2f}). Check the input (Mode 1: S3, L23, S2).")

    s4_wanted = entries.ask("s4", f"S4 target from Hornresp [{F}] (number or 'auto' = no target; comparison only)",
                          p_number(0, True, words={"auto": None, "free": None, "frei": None}), default="auto")
    s5_wanted = entries.ask("s5", f"S5 target from Hornresp [{F}] (number or 'auto' = no target; comparison only)",
                          p_number(0, True, words={"auto": None}), default="auto")
    driver_offset = entries.ask("driver_offset",
                             f"Driver offset (distance of S2 + S4, i.e. the driver centre, from the left outer edge) [{L}]", p_number(0))
    c = depth - a - driver_offset
    print(f"Initial path S2 to wall of first bend: {c:.4f} {L}")
    if c <= 0:
        raise FoldingError(f"Initial path is {c:.2f} {L} - the dimensions are inconsistent "
                             f"(driver offset too large or enclosure too small).")

    # With a continuously straight board (S1-S2-S3), S1 follows from S2 and the slope.
    h_s1 = W2 * math.cos(psi_ / 2) + (a - driver_offset - a / 2 * math.sin(psi_)) * math.tan(psi_)
    if h_s1 < 0:
        print("Note: With this slope the board at the S1 end would have a negative height; "
              "'auto' gives S1 = 0.")
    s1_auto = max(0.0, h_s1) * b1
    if S1 is None:
        S1 = s1_auto
        print(f"S1 = auto: {s1_auto:.1f} {F} (same slope throughout)")
    b_manual = entries.ask("slope2",
                          "Slope after S3 (b')  ('auto' = calculated from the box, or a number, may be negative)",
                          p_number(words={"auto": None}), default="auto")
    print("S3 positions:")
    for kk, txt in POSITIONS.items():
        print(f"  {kk}  {txt}")
    pos = entries.ask("s3position", "S3 position (1-7, or 'auto' / 'a' = automatically matched to the desired L23)",
                    p_choice(tuple(str(i) for i in sorted(POSITIONS)) + ("auto",), {"a": "auto"}), default="auto")
    if pos == "auto" and l23_wanted is None:
        l23_wanted = entries.ask("l23", f"Desired length L23 (S2 to S3) for choosing the position [{L}]",
                               p_number(0, True))
    driver_d = entries.ask("driver_diameter", f"Driver gross (frame) diameter [{L}] ('auto' = unknown)",
                          p_number(0, True, words={"auto": 0.0}), default="auto")
    magnet_d = entries.ask("magnet_diameter", f"Magnet diameter [{L}] ('auto' = 0.5 x driver diameter, used for the depth check)",
                          p_number(0, True, words={"auto": None}), default="auto")
    if magnet_d is None:
        magnet_d = 0.5 * driver_d if driver_d > 0 else 0.0
    driver_t = entries.ask("driver_depth", f"Driver mounting depth incl. magnet [{L}] ('auto' = unknown)",
                          p_number(0, True, words={"auto": 0.0}), default="auto")
    with_kink = entries.ask("kink", "Board a with a kink if S1 differs (S1 = Hornresp value)? (y/n)",
                          p_yes_no, default="y")
    with_svg = entries.ask("svg", "Generate SVG drawing? (y/n)", p_yes_no, default="y")

    # Save inputs (before the calculation, so they survive an error)
    store = dict(values)
    store.update(entries.used)
    last_file = os.path.join(folder, INPUT_FILE)
    if args.output_dir is not None:
        Path(folder).mkdir(parents=True, exist_ok=True)
    if not args.no_save_input:
        try:
            save_inputs(store, last_file)
            print(f"\nInputs saved: {last_file}")
        except OSError as error:
            print(f"\n(Inputs could not be saved: {error}.)")

    P = {"a": a, "b": b, "W2": W2, "L45": driver_offset,
         "depth": depth, "b1": b1, "S1": S1, "H": height, "Width": width, "kink": with_kink,
         "driver_d": driver_d}

    cand = {}
    for kk in sorted(POSITIONS):
        try:
            note_k = ""
            if b_manual is None:
                b_k, n_sol = solve_b_consistent(P, kk)
                if n_sol > 1:
                    note_k = f"{n_sol} solutions for b', the one nearest to b chosen"
            else:
                b_k = b_manual
            Rk = compute(P, kk, b_k)
            Rk["shortfall"] = shortfall(P, Rk)
            cand[kk] = (Rk, note_k)
        except FoldingError as error:
            cand[kk] = (None, str(error))

    if pos == "auto":
        possible = [kk for kk in cand if cand[kk][0] is not None]
        if not possible:
            reasons = {}
            for kk_, (_, txt_) in cand.items():
                if "Last reason: " in txt_:
                    reasons.setdefault(txt_.split("Last reason: ")[-1], []).append(kk_)
            extra = ""
            if len(reasons) == 1:
                extra = f" Reason: {next(iter(reasons))}"
            elif reasons:
                extra = " Reasons: " + "; ".join(f"positions {', '.join(map(str, v))}: {r}" for r, v in reasons.items())
            raise FoldingError("None of the S3 positions can be calculated with these dimensions." + extra)
        near = [kk for kk in possible if abs(cand[kk][0]["l23"] - l23_wanted) <= 0.10 * l23_wanted]
        if not near:
            near = [min(possible, key=lambda kk: abs(cand[kk][0]["l23"] - l23_wanted))]
        smallest = min(cand[kk][0]["shortfall"] for kk in near)
        same = [kk for kk in near if cand[kk][0]["shortfall"] <= smallest + 0.5]      # 0.5 percentage points count as equivalent
        k = min(same, key=lambda kk: abs(cand[kk][0]["l23"] - l23_wanted))
    else:
        k = int(pos)
        if cand[k][0] is None:
            raise FoldingError(f"S3 position {k} cannot be calculated: {cand[k][1]}")
    R = cand[k][0]

    print(f"\nS3 positions compared (lengths in {L}, areas in {F}):")
    head = "  Pos       L23         S3" + ("   S3/input" if S3_wanted is not None else "") + "      Slope b'         S4"
    head += "   S4 target" if s4_wanted is not None else ""
    head += "     dL23 %" if l23_wanted is not None else ""
    print(head + "   Path S3-S4   Total path  Undershoot")
    for kk, (Rk, note_k) in cand.items():
        mark = "   <-- chosen" if kk == k else ""
        if Rk is None:
            print(f"  {kk}   cannot be calculated: {note_k}{mark}")
        else:
            wu = f"  {Rk['S4'] - s4_wanted:+9.1f}" if s4_wanted is not None else ""
            s3_dev = f"  {(Rk['S3'] / S3_wanted - 1) * 100:+7.1f} %" if S3_wanted is not None else ""
            dl23 = f"  {(Rk['l23'] - l23_wanted) / l23_wanted * 100:+8.1f} %" if l23_wanted is not None else ""
            print(f"  {kk}  {Rk['l23']:8.2f}  {Rk['S3']:9.1f}{s3_dev}   {Rk['b_after']:10.4f}  {Rk['S4']:9.1f}{wu}{dl23}  "
                  f"{Rk['path_s3_s4']:10.2f}   {Rk['total']:10.2f}  {Rk['shortfall']:7.1f} %"
                  + (f"   ({note_k})" if note_k else "") + mark)
    print("  (Undershoot = largest undershoot of the actual cross-section below the idealised cone through S1-S5;"
          " undesirable, because smaller than in the simulation.)")
    if S3_wanted is not None:
        print(f"  (S3/input column: calculated S3 area relative to the desired S3 = {S3_wanted:g}; "
              "negative = smaller than desired.)")
    if l23_wanted is not None:
        print("  (dL23% = (L23_calc - L23_wanted) / L23_wanted. Selection (auto): among positions within +-10 % of "
              "L23_wanted (or closest if none), smallest shortfall (within 0.5 pp) wins, ties broken by closest L23.)")
    if s4_wanted is not None:
        print(f"  (S4 target column: calculated S4 minus desired S4 = {s4_wanted:g})")

    print(f"\nChosen: S3 position {k} - {POSITIONS[k]}")
    print(f"\nBends solved in sequence (width law along the centreline, lengths in {L}):")
    print(f"  {'':<8}{'Pos. C':>9}{'Entry':>10}{'Law':>9}{'Exit':>10}{'Law':>9}{'Path s in':>11}")
    for f_ in R["geo"]["folds"]:
        Gf = f_["G"]
        out_str = f"{f_['law_out']:9.3f}" if not f_.get("free_exit") else "   (free)"
        print(f"  Bend  {f_['nr']:<2}{f_['par']:9.3f}{Gf['w1']:10.3f}{f_['law_in']:9.3f}{Gf['w2']:10.3f}"
              f"{out_str}{f_['s_e']:11.2f}")
    print("  (Bend 6: exit not bound to the law - the chamber results from the geometry.)")

    print(f"\nFinal values (lengths in {L}, areas in {F}):")
    print(f"S1 (Hornresp):           {R['geo']['area']['S1']}")
    print(f"Path S1 - S2:            {R['path_s1_s2']}")
    print(f"S3:                     {R['S3']}")
    print(f"Path S2 - S3 (L23):     {R['l23']}")
    print(f"S4:                     {R['S4']}")
    print(f"Path S3 - S4:            {R['path_s3_s4']}")
    print(f"S5:                     {R['S5']}")
    print(f"Path S4 - S5:            {R['path_s4_s5']}")
    _g = R["geo"]
    if not _g["kink"] and abs(S1 - _g["s1_same"]) > 0.005 * max(_g["s1_same"], 1.0):
        print(f"Note: S1 = {S1:g} was specified, but board a has no kink: the Hornresp S1 follows from the built volume "
              f"S1-S2 ({_g['area']['S1']:.1f} {F}). Use Kink = y to simulate a different S1.")
    if driver_d > 0:
        r_ = driver_d / 2
        ex_ = _g["ex"]

        def along(p_, q_):                                       # distance q - p along board a
            return (q_[0] - p_[0]) * ex_[0] + (q_[1] - p_[1]) * ex_[1]
        a_top_r = (_g["C1"][0] + _g["en"][0] * a, _g["C1"][1] + _g["en"][1] * a)
        free = {"channel side, to board b": along(_g["U2"], _g["C1"]),
                "chamber side, to board b": along(_g["U4"], a_top_r)}
        if _g["kink"]:
            free["channel side, to the kink"] = along(_g["K"], _g["U2"])
            free["chamber side, to the kink"] = along(_g["K_up"], _g["U4"])
        else:
            free["channel side, to the left wall"] = along(_g["Ls"], _g["U2"])
            free["chamber side, to the left wall"] = along(_g["Lu"], _g["U4"])
        print(f"Driver check: half diameter {r_:.1f} {L}; free straight length of board a from the driver centre:")
        for nm_, v_ in free.items():
            print(f"  {nm_}: {v_:.1f} {L}" + ("" if v_ >= r_ - 1e-6 else "  <-- WARNING: the driver frame does not fit"))
    if driver_t > 0:
        # Free depth: from the driver centre U4 (top side of board a) along the board normal en to the opposite wall
        # (underside of d; behind the end of d: its end face or the ceiling).
        box_ = (a, depth - a, a, height - a)
        en_, ex_b = _g["en"], _g["ex"]
        h4, h4_name = free_height(_g, _g["U4"], en_, box_)
        if h4 is None:
            print("Driver depth: no opposite wall found along the board normal (check not possible).")
        else:
            theo = ""
            if _g["s4_in_bend"]:
                # S4 lies in the bend: besides the real wall also the distance to the extended underside of d
                # (the chamber height as it would be without the bend opening), the smaller value is checked
                h4_real = h4
                pd_ = _g["poly"]["d"]
                dl_ = _unit_vec((pd_[2][0] - pd_[3][0], pd_[2][1] - pd_[3][1]))
                # the line is intersected only in the direction of the ray (in front of U4); parallel lines and
                # intersections behind U4 are discarded, as in free_height()
                try:
                    px_ = _intersect(_g["U4"], en_, pd_[3], dl_)
                    hx_ = (px_[0] - _g["U4"][0]) * en_[0] + (px_[1] - _g["U4"][1]) * en_[1]
                except ZeroDivisionError:
                    hx_ = None
                theo = f"  (S4 lies inside bend 6; real wall behind: {h4_real:.1f} {L})"
                if hx_ is not None and 1e-9 < hx_ < h4:
                    h4, h4_name = hx_, "extended underside of d"
            print(f"Driver depth {driver_t:.1f} {L}; free depth at the driver centre, perpendicular to board a, "
                  f"to the {h4_name}: {h4:.1f} {L}{theo}"
                  + ("" if h4 >= driver_t else "  <-- WARNING: the driver (magnet) does not fit between a and d"))
            if magnet_d > 0:
                # h(u) = free depth at the distance u from the centre along board a (u along ex). Sign of delta from the
                # geometry: tan(delta) = -dh/du, so that delta > 0 means the walls converge towards +u (h decreases);
                # h(u) = h4 - u*tan(delta) is evaluated by casting the ray at the magnet edges (exact, no linearisation).
                rm = magnet_d / 2
                res = {}
                for sgn, lab in ((-1, "edge towards -ex"), (1, "edge towards +ex")):
                    org = (_g["U4"][0] + sgn * rm * ex_b[0], _g["U4"][1] + sgn * rm * ex_b[1])
                    res[sgn] = free_height(_g, org, en_, box_)
                h_m, h_p = res[-1][0], res[1][0]
                if h_m is None or h_p is None:
                    print("Magnet check: no opposite wall found at a magnet edge.")
                else:
                    tan_d = (h_m - h_p) / (2 * rm)
                    print(f"Magnet diameter {magnet_d:.1f} {L}: free depth at the edges {h_m:.1f} (towards -ex, {res[-1][1]}) / "
                          f"{h_p:.1f} (towards +ex, {res[1][1]}); wall inclination tan(delta) = {tan_d:+.4f} "
                          f"(delta > 0: walls converge towards +ex)")
                    hmin = min(h_m, h_p, h4)
                    if hmin < driver_t:
                        print(f"  <-- WARNING: at the magnet edge only {hmin:.1f} {L} are free (needed {driver_t:.1f})")
                    for sgn in (-1, 1) if not _g["s4_in_bend"] else ():
                        if res[sgn][1] not in ("d underside", "d end face"):
                            print(f"  <-- WARNING: the magnet edge ({'-' if sgn < 0 else '+'}ex side) lies outside the channel under board d "
                                  f"(opposite wall: {res[sgn][1]})")
    if R["geo"]["kink"]:
        gk = R["geo"]
        print(f"Board a with kink: S1 (Hornresp) = {R['geo']['area']['S1']:.2f}, built S1 = {gk['S1_real']:.2f};  "
              f"S5 (Hornresp) = {gk['area']['S5']:.2f}, built S5 = {gk['S5_real']:.2f} {F}")
        print(f"  (S1 from volume equality with a linear area segment (Hornresp Par), S5 see below; "
              f"kink {gk['t_kink']:.1f} {L} from the driver centre)")
        if gk["kink_note"]:
            print(f"WARNING: {gk['kink_note']}")
        try:
            kk_ = kink_check(gk, b1, a, R["path_s1_s2"], R["path_s4_s5"])
        except (ZeroDivisionError, ValueError):
            print("  Kink check: not possible (a segment cross-section is zero or negative; acoustic mass would be infinite).")
            kk_ = None
        if kk_ is not None:
            print(f"  Kink check (estimate; acoustic mass M = integral ds/A, built / linear-area Par segment): "
                  f"S1-S2 {1 / kk_['M1']:.3f}, S4-S5 {1 / kk_['M4']:.3f}")
            print(f"    equivalent length shift at the mouth (Par model minus built): S1 side {kk_['dL1']:+.2f} {L}, "
                  f"S5 side {kk_['dL4']:+.2f} {L} (of {R['total']:.0f} {L} total path);  "
                  f"volume difference {liter(kk_['dV1']):+.2f} / {liter(kk_['dV4']):+.2f} l")
            print("    Values below about 2 % are uncritical in this estimate; for very large kinks the estimate itself is unreliable.")
        if gk["r_driver"] <= 0:
            print("WARNING: no driver diameter given - the kink is placed at the driver centre (S2/S4). "
                  "Enter DriverDiameter so that a2 stays straight at least half a driver diameter on each side.")
    print(f"[diag] S4 relative to exit of bend 6 (X0), along the centreline: {R['geo']['s4_over_x0']:.2f} {L}")
    level6 = s4_bend6_level(R["geo"])
    gg = R["geo"]
    if gg["s4_in_bend"]:
        print(f"S4 lies in the curved part of bend 6: cross-section = fan ray from C6 through the driver centre "
              f"(length {gg['S4_fan'] / b1:.1f} {L}, fan area {gg['S4_fan']:.1f} {F}); path position "
              f"{gg['s4_cum'] - gg['cum'][1]:.2f} {L} behind S2.")
        print(f"  S4 for Hornresp = {R['S4']:.1f} {F} (theoretical: straight chamber line to the built mouth area S5, extended back through the "
              f"built exit area of bend 6; not the fan area).")
    if gg.get("s5_inert") is not None and gg["s5_vol"] > 0:
        print(f"S5 (Hornresp) = mean of the volume-equal S5 ({gg['s5_vol']:.1f}) and the inertance-equal S5 "
              f"({gg['s5_inert']:.1f}); built S5 = {gg['S5_real']:.1f} {F}")
        if abs(gg["s5_vol"] - gg["s5_inert"]) / gg["s5_vol"] > 0.02:
            print(f"  Note: volume and inertance give different S5 ({(gg['s5_inert'] / gg['s5_vol'] - 1) * 100:+.1f} % apart); "
                  f"a straight Hornresp segment cannot match both.")
    v_hr = (R["S4"] + R["S5"]) / 2 * R["path_s4_s5"]
    print(f"Volume S4-S5: built {liter(gg['v45_actual']):.2f} l, linear-area Par segment {liter(v_hr):.2f} l "
          f"({(v_hr / gg['v45_actual'] - 1) * 100:+.1f} %)")
    if level6 == 2:
        print("\n" + "!" * 78)
        print(f"WARNING: S4 lies in the curved part of bend 6, {-gg['s4_over_x0']:.1f} {L} before its exit,")
        print("         BEFORE the point B6. Constructionally this is unfavourable (the driver sits in the bend);")
        print("         the area S4 is a theoretical value there, the real channel has no such cross-section.")
        print("         Please reconsider DriverOffset, the S3 position or the box dimensions.")
        print("!" * 78 + "\n")
    elif level6 == 1:
        print(f"Note: S4 lies inside bend 6, {-gg['s4_over_x0']:.1f} {L} before its exit (behind B6). "
              f"S4 is a theoretical value there (see above); please check the drawing.")
    print(f"Total path length:      {R['total']}")
    print(f"Slope b  (S2 - S3) = {b:g}   (area gradient b1*b  = {b1 * b:.4g} {F}/{L})")
    print(f"Slope b' (S3 - S4) = {R['b_after']:.5g}   (area gradient b1*b' = {b1 * R['b_after']:.4g} {F}/{L})"
          + ("  (calculated from the box)" if b_manual is None else "  (specified)"))
    print(f"Linear-area model (Par) S3 -> S4: uniform slope {R['b_cone']:.5g} "
          f"(check: S3 + b1*b'*path = {R['S3'] + b1 * R['b_after'] * R['path_s3_s4']:.2f}, S4 = {R['S4']:.2f})")
    if s5_wanted is not None:
        print(f"S5 target {s5_wanted:g}: calculated S5 (Hornresp value) deviates by {R['S5'] - s5_wanted:+.2f} {F} "
              f"({(R['S5'] / s5_wanted - 1) * 100:+.2f} %).")
    if hr_values:
        print(f"Hornresp lengths (comparison): L12 = {hr_values['L12']:g} (calc. {R['path_s1_s2']:.2f}), "
              f"L34 = {hr_values['L34']:g} (calc. {R['path_s3_s4']:.2f}), "
              f"L45 = {hr_values['L45']:g} (calc. {R['path_s4_s5']:.2f})")
    if s4_wanted is not None:
        print(f"S4 target {s4_wanted:g}: calculated S4 deviates by {R['S4'] - s4_wanted:+.2f} {F} "
              f"({(R['S4'] / s4_wanted - 1) * 100:+.2f} %).")

    print(f"\nPath parts per bend (straight up to A + chord A-B + straight from B), in {L}:")
    for name_, w1_, w2_, th_, (a1_, ch_, b2_) in R["bends"]:
        print(f"  {name_:<30}{th_:6.1f} deg   {w1_:7.2f} -> {w2_:7.2f}   "
              f"{a1_:6.2f} + {ch_:6.2f} + {b2_:6.2f} = {a1_ + ch_ + b2_:7.2f}")

    if l23_wanted is not None:
        print(f"\nNote: desired L23 = {l23_wanted:.3f}, calculated L23 = {R['l23']:.3f} "
              f"(deviation {R['l23'] - l23_wanted:+.3f} {L}). "
              f"In case of deviation, adjust S3/L23 if necessary or choose a different S3 position.")

    # --- Hornresp output file (the original is never overwritten) -----------------------------------
    if hr_path is not None:
        stem, ext = os.path.splitext(hr_path)
        target = stem + "_Hornfolding" + (ext or ".txt")
        if args.output_dir is not None:
            target = os.path.join(folder, os.path.basename(target))
        hr_new = {"S1": R["geo"]["area"]["S1"], "S2": S2, "S3": R["S3"], "S4": R["S4"], "S5": R["S5"],
                  "L12": R["path_s1_s2"], "L23": R["l23"], "L34": R["path_s3_s4"], "L45": R["path_s4_s5"]}
        try:
            write_hornresp(hr_path, target, hr_new)
            print(f"\nHornresp file written: {target}")
            print("  changed: S1-S5 and the four lengths"
                  + "; flare types and all other parameters preserved.")
        except (OSError, FoldingError) as error:
            print(f"\nWARNING: Hornresp file could not be written: {error}")

    # --- SVG drawing (optional) -----------------------------------------
    if with_svg:
        g = {
            "unit": L, "a": a, "T": depth, "H": height, "L45": driver_offset, "b": b, "b1": b1, "W2": W2,
            "S1": S1, "S2": S2, "Width": width, "k": k, "b_after": R["b_after"], "geo": R["geo"],
            "l23_new": R["l23"], "path_s1_s2": R["path_s1_s2"], "path_s4_s5": R["path_s4_s5"],
            "path_s3_s4": R["path_s3_s4"], "bends": R["bends"], "total": R["total"],
            # Target cone (a): input/Hornresp values; if a target value is missing, the script value applies
            "ref": {"S1": S1, "S2": S2, "S3": S3_wanted if choice == "1" else R["S3"],
                    "S4": s4_wanted if s4_wanted is not None else R["S4"],
                    "S5": s5_wanted if s5_wanted is not None else R["S5"],
                    "L12": hr_values["L12"] if hr_values else R["path_s1_s2"],
                    "L23": l23_wanted if l23_wanted is not None else R["l23"],
                    "L34": hr_values["L34"] if hr_values else R["path_s3_s4"],
                    "L45": hr_values["L45"] if hr_values else R["path_s4_s5"],
                    "flares": hr_values["flares"] if hr_values else ("Par",) * 4},
        }
        filename = os.path.join(folder, "horn_folding.svg")
        try:
            checks, cutlist, _geo = draw_svg(g, filename)
        except OSError:                       # script folder not writable
            if args.output_dir is not None:
                raise  # Never silently ignore an explicitly requested target.
            filename = os.path.abspath("horn_folding.svg")
            checks, cutlist, _geo = draw_svg(g, filename)
        print(f"\nDrawing written: {filename}")
        print("Drawing check:")
        for name, value in checks.items():
            print(f"  {name}: {value:+.3f} {F if 'area' in name else L}")
        d1u, d1o = _geo["d1"]
        print("\nDriver centre: distance from the inner face of D1 along board a (for marking the cutouts):")
        print(f"  Underside (channel side, S2): {d1u:.2f} {L}     Top side (chamber side, S4): {d1o:.2f} {L}")
        print(f"\nCheck: air volume of the drawing {liter(_geo['vol_air']):.2f} l "
              f"(incl. mouth opening {liter(_geo['vol_mouth']):.2f} l; net width {b1:.2f} {L}); "
              f"volume along the centreline (integral A ds) {liter(_geo['vol_path']):.2f} l "
              f"= {_geo['vol_path'] / _geo['vol_air'] * 100:.1f} %")
        print("  (Close to 100 % means: the horn volume along the centreline matches the air space of the drawing; "
              "the difference is due to bend corners and approximation.)")
        print(f"  Same integral with the fan profile of the plot (peaks at the outer corners): "
              f"{liter(_geo['vol_fans']):.2f} l = {_geo['vol_fans'] / _geo['vol_air'] * 100:.1f} %")
        print("  (Both are approximations of the drawn air volume; which is closer depends on the geometry "
              "(the fan profile is usually closer, the linear interpolation for strongly widening bends).)")
        if _geo.get("fan_gaps", 0) > 0:
            print(f"  Note: the fan profile has {_geo['fan_gaps']} gap(s) (no reliable construction); bridged by straight lines "
                  f"in the fan volume / inertance.")
        print(f"  Inertance integral ds/A = {_geo['inertia']:.5f} 1/{L} (stations), "
              f"{_geo['inertia_fans']:.5f} 1/{L} (with fan profile)")
        for nm_, r_ in _geo["ratios"]:
            if r_ > RATIO_WARN:
                print(f"WARNING: {nm_}: cross-section ratio {r_:.2f} (exit/entry) is greater than {RATIO_WARN} - "
                      f"the bend approximation (centreline across the corner) is unreliable there; path probably shorter than calculated.")
        print(f"Note: The largest bend cross-section ({_geo['w_max']:.1f} {L}) corresponds to lambda/4 at approx. "
              f"{lambda4_limit(_geo['w_max']):.0f} Hz (c = 344 m/s). The bend approximation (plane wavefront in the "
              f"cross-section) is only valid well below that.")
        print("Note: The volume of the driver (and the braces) is not subtracted here. In reality it reduces the "
              "chamber S4-S5 behind the driver. Hornresp has no parameter for this (Vtc is the volume in front of "
              "the driver), so S4 would have to be adjusted by judgement.")
        print(f"\nCut list (length x width x thickness in {L}):")
        for entry in cutlist:
            print(f"  {entry[0]:<4}{entry[1]:<26}{_fmt_cut(entry)}")
        csv_name = os.path.join(os.path.dirname(filename), "horn_cutlist.csv")
        try:
            with open(csv_name, "w", encoding="utf-8-sig") as fh:
                fh.write(f"Board;Name;Gross length ({L});Width ({L});Thickness ({L});Qty;End angle 1 (deg);"
                         f"End angle 2 (deg);Long face\n")
                for lab, name, l_, w_, d_, n_, a1_, a2_, fc_ in cutlist:
                    if abs(a1_ - 90) < 0.05 and abs(a2_ - 90) < 0.05:
                        fc_ = ""                              # square cut: no long face
                    fh.write(f"{lab};{name};{l_:.1f};{w_:.1f};{d_:g};{n_};{a1_:.1f};{a2_:.1f};{fc_}\n".replace(".", ","))
            print(f"Cut list written: {csv_name}")
        except OSError:
            print("(Cut list could not be written as CSV.)")


if __name__ == "__main__":
    try:
        main()
    except FoldingError as error:
        print(f"\nERROR: {error}")
        sys.exit(1)
    except (OSError, UnicodeError) as error:
        print(f"\nERROR: File could not be read or written: {error}")
        sys.exit(1)
    except (KeyboardInterrupt, EOFError):
        print("\nAborted.")
        sys.exit(1)
