{"id":"5JTZAH5PYS","url":"https://pastebin.ca/5JTZAH5PYS","raw_url":"https://raw.anybin.ca/5JTZAH5PYS","visibility":"public","access":"public","created_at":1795095125712,"expires_at":1795699925712,"fetch_limit":null,"fetches_used":0,"reads_remaining":null,"size_bytes":130175,"syntax_hint":null,"title":null,"filename":null,"change_note":null,"cipher":null,"cipher_meta":null,"parent_id":null,"root_id":"5JTZAH5PYS","version":1,"owner_id":null,"recipient_id":null,"body":"# Hornfolding - Folding a horn / tapped-horn channel in a rectangular box\n# Copyright (C) 2026 Tobias McFadden\n# Contact: Tobias@McFadden.de\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n\"\"\"\nHornfolding_v0.69.py  -  Folding a horn / tapped-horn channel in a rectangular box\n===================================================================================\n\nPurpose\n-------\nCalculates how a horn channel of constant width and linearly growing height\nis folded into an enclosure of given size, and provides the areas\nS1..S5 and path lengths for Hornresp.\n\nUNITS (important!)\n------------------\nThe script works unit-free. It only has to be consistent:\n    Lengths in  UNIT        (default: cm)\n    Areas in    UNIT²       (default: cm²)\nTo work in mm, change UNIT below to \"mm\" and then enter\nall lengths in mm and all areas in mm² (e.g. S2 = 13000 instead of 130).\nTypical mistake: lengths in mm, area in cm² -> the channel becomes absurdly flat.\n\nInputs\n------\nWoodThickness (a)     Wood thickness\nBraceWidth            Width of the bracing in the enclosure\nWidth, Height, Depth  Outer dimensions of the enclosure\nThe horn values are asked for in the order of Hornresp: S1, S2, S3 (or the slope), L23, S4, S5; then DriverOffset.\nS1                    Area at the closed end behind the driver. 'auto' = same slope throughout\n                      S1-S2-S3. With a kink in board a S1 is the Hornresp value (the real S1 follows from the volume);\n                      without a kink (0.69) a specified S1 has no effect: the Hornresp S1 follows from the built volume.\nS2                    Area at the driver (starting value)\nSlope b               Height increase of the channel per path length\n                      (0.1 = 10 cm height per metre of path)\n  Mode 1: b is calculated from S3 and the length L23 (S2 to S3; earlier name \"Con\")\n  Mode 2: b is entered directly\nSlope after S3 b'     Slope of the channel between S3 and S4. 'auto' (Enter) = calculated from the box:\n                      b' is chosen so that the area from S3 to S4 grows uniformly\n                      (linear area, Hornresp Par) with b': S4 = S3 + b1*b'*Path(S3-S4).\n                      A number (also negative) overrides this.\nS3Position            1-7 or auto (a); with auto: among the positions whose length S2-S3\n                      (L23) deviates by at most 10 % from the desired L23, the one with the\n                      smallest area shortfall (actual below idealised cone) is chosen.\n                      If no position is within 10 %, the closest calculable position is used.\nS4                    optional: the area S4 desired in Hornresp (number or free). For comparison\n                      only: S4 results from the box and is compared with the desired value.\nS5                    optional: the area S5 desired in Hornresp (number or auto), comparison only.\nDriverOffset          Distance of S2 + S4 (the driver centre) from the left outer edge; defines the\n                      driver position. The actual path length S4-S5 is calculated from the\n                      resulting geometry.\nKink                  y/n: draw board a with a kink at S2 if S1 deviates from the continuous\n                      slope (default y)\n\nS3 positions (slope change only where a board ends)\n-------------------------------------------------------------\n  1  entry of bend 3  (C3, top left, before the shaft)\n  2  exit of bend 3   (C3, start of the shaft)\n  3  entry of bend 4  (C4, end of the shaft)\n  4  exit of bend 4   (start of the middle channel between c and d)\n  5  entry of bend 5  (C5)\n  6  exit of bend 5   (C5, start of the short descent between d and b)\n  7  entry of bend 6  (C6, into the chamber)\nSince 0.52 the positions are numbered in flow order (the former 5 'exit of bend 5' is now 6).\nFrom S3 onwards the boards are cut so that the channel grows with the slope b': c at its left end\n(positions 1, 2), d at its right end (positions 1-6). The cut list gives gross length and end angles.\n\nInput file (optional, for the test phase)\n------------------------------------------\nOn every run the script writes all inputs to 'Hornfolding_Input.txt' (next to the\nscript) and reads them back in on the next run: each value is accepted with Enter\nor overwritten by typing. On request (y) all values are\naccepted without prompting. With 'python Hornfolding_v0.69.py my_file.txt' a different file is read\n(without prompting). Format:\n    Name = value        # comment        (comma or point as decimal separator)\nNames: WoodThickness, BraceWidth, Width, Height, Depth, S1 (number or 'auto'), S2, Mode,\nSlope (Mode 2 only), S3 and L23 (Mode 1 only; L23 also with S3Position = auto), S4 and S5 (number or\n'auto' = no target; comparison values), DriverOffset, Slope2 (b': number or 'auto'), S3Position (1-7 or auto),\nDriverDiameter, MagnetDiameter and DriverDepth (number or\n'auto' = unknown; fit checks; MagnetDiameter auto = 0.5 x DriverDiameter), HornrespFile (optional exported Hornresp text file), Kink (y/n), SVG (y/n).\n\nCommand line\n------------\n    python Hornfolding_v0.69.py [input_file] [--batch] [--output-dir DIR] [--no-save-input]\ninput_file          input file (Name = value) or an exported Hornresp single-simulation text file\n--batch             use the saved values without prompting (error if a required value is missing)\n--output-dir DIR    directory for the generated files (SVG, cut list, saved input, Hornresp result)\n--no-save-input     do not save the inputs of this run\n\nDerived quantities\n------------------\nb1        Net width of the channel        = Width - BraceWidth - 2a\nW2        Width of the S2 chord           = S2 / b1   (chord perpendicular to the centreline)\nW(s)      Channel width at path s         = W2 + b*s  (s = path along the centreline from S2),\n                                           after S3: W(s3) + b'*(s - s3)\n\nCalculation principle (from 0.50: geometry first, everything along the centreline)\n-----------------------------------------------------------------------\nStraight boards are exact rectangles, inclined against each other by the wedge angle psi = 2*atan(b/2), so that\nthe channel width on straight sections grows exactly linearly with the centreline path. Each bend is solved\nin turn (bend 1 to 5) via the position of its inner corner so that the exit width matches the law\nW(s); the path in the bend is the fan construction (hand construction, empirically confirmed at 90 degrees,\nthe geometric generalisation for other angles). The entry width then matches by itself\n(check value in the output). All outputs (S2-S5, L23, path lengths, cutting list) come from this geometry.\n\nModel note (0.64): the folding always assumes parallel side walls, i.e. a LINEAR area law = Hornresp flare type \"Par\"\n(see Hornresp help: Par is for a rectangular segment with two parallel and two sloping sides, area linear with length).\nNever use \"Con\" in Hornresp for these horns. The script warns when an imported Hornresp file contains Con segments.\nThe length S2-S3 input is called L23 (Hornresp name); the old name \"Con\" is still read.\n\nMouth (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\ncontinue to the outer face of the wall; S5 is the vertical distance between these bevelled edges at the outer face (x = 0).\n\nDepth check (0.68): DriverDepth is compared with the free depth from the driver centre along the board normal to the opposite\nwall (underside of d; behind the end of d its end face or the ceiling). With MagnetDiameter (auto = 0.5 x DriverDiameter) the\nfree depth is also checked at the magnet edges; the sign of the wall inclination delta (tan(delta) = -dh/du, u along board a)\nfollows from the geometry. With a kink in board a the centreline of the chamber S4-S5 is a polyline (kink at the cross-section\nthrough the kink point K_up).\n\nHornresp areas S1 and S5 (0.69): every Hornresp segment should reproduce the BUILT air volume. S1 = 2*V12/L12 - S2\n(with a kink the real S1 is solved so that this equals the specified S1; without a kink a specified S1 has no effect).\nS5 is the mean of the volume-equal S5 (2*V45/L45 - S4) and the inertance-equal S5 (same integral ds/A as the built\nchamber); a note appears if the two differ by more than 2 %. S4 inside bend 6 uses the built mouth area S5.\n\nVersion history: see CHANGELOG.md.   Licence: see the header at the top of this file and the file License.md.\n\"\"\"\n\nimport argparse\nimport math\nimport os\nimport sys\nimport tempfile\nfrom html import escape\nfrom pathlib import Path\n\nVERSION = \"0.69\"\nUNIT = \"cm\"          # \"cm\" or \"mm\"; all inputs must be given in this unit\nif UNIT not in (\"cm\", \"mm\"):\n    raise ValueError(\"UNIT must be 'cm' or 'mm'.\")\nCM = 10.0 if UNIT == \"mm\" else 1.0   # 1 cm expressed in the chosen unit\n\n# --- Tuning constants (numerical search and checks; none of them is a model parameter of the horn) ------------------\nSEARCH_STEP = 0.1 * CM       # Grid only for finding the sign change (no longer for the result)\nSEARCH_STEP_BEND = 0.25 * CM # same for the bend parameter in build() (length along the board, in UNIT)\nBEND_MIN = 0.5 * CM          # smallest bend parameter tried (distance of an inner corner from the previous one)\nBEND_MARGIN = 0.5 * CM         # margin kept to the box wall when the search range of a bend is limited\nBOX_TOL = 1e-6 * CM           # tolerance when testing that a point lies inside the box\nRATIO_WARN = 1.33       # warning if the cross-section ratio exit/entry in a bend is larger (Brian Steele)\nCOS_PSI_MIN = 0.17            # largest wedge angle about 80 deg; beyond that the search limits (division by cos) become meaningless\nB_MIN, B_MAX, B_STEP = -0.3, 1.0, 0.02     # search range for b' (not a model limit)\n\n\nclass FoldingError(Exception):\n    \"\"\"Raised when a fold has no solution.\"\"\"\n\n\n# ---------------------------------------------------------------------------\n# Input\n# ---------------------------------------------------------------------------\nINPUT_FILE = \"Hornfolding_Input.txt\"   # next to the script; rewritten at every run\n\nKNOWN_KEYS = {\"wood_thickness\", \"brace_width\", \"width\", \"height\", \"depth\",\n              \"driver_offset\", \"s1\", \"s2\", \"mode\", \"slope\", \"s3\", \"l23\", \"svg\",\n              \"slope2\", \"s3position\", \"s4\", \"kink\", \"driver_diameter\", \"magnet_diameter\", \"driver_depth\", \"hornresp\", \"s5\"}\n\n# Input names (normalised: lower case, no spaces/underscores) -> internal keys.\n# The former German names are still accepted; L23 is the Hornresp name of the length S2-S3 (old name: \"Con\").\nLEGACY_NAMES = {\"woodthickness\": \"wood_thickness\", \"bracewidth\": \"brace_width\", \"driveroffset\": \"driver_offset\",\n                \"driverdiameter\": \"driver_diameter\", \"magnetdiameter\": \"magnet_diameter\", \"driverdepth\": \"driver_depth\", \"hornrespfile\": \"hornresp\",\n                \"holzstaerke\": \"wood_thickness\", \"verstrebungsbreite\": \"brace_width\", \"breite\": \"width\",\n                \"hoehe\": \"height\", \"tiefe\": \"depth\", \"anfangslaenge\": \"driver_offset\", \"modus\": \"mode\",\n                \"steigung\": \"slope\", \"steigung2\": \"slope2\", \"knick\": \"kink\",\n                \"treiberdurchmesser\": \"driver_diameter\", \"treibertiefe\": \"driver_depth\", \"con\": \"l23\"}\n\n\ndef _norm(name):\n    \"\"\"Normalise a key name: lower case, no spaces/underscores/hyphens, umlauts -> ae etc.\"\"\"\n    n = name.strip().lower()\n    for old, new in ((\"ä\", \"ae\"), (\"ö\", \"oe\"), (\"ü\", \"ue\"), (\"ß\", \"ss\")):\n        n = n.replace(old, new)\n    for char in (\" \", \"_\", \"-\"):\n        n = n.replace(char, \"\")\n    n = LEGACY_NAMES.get(n, n)\n    return {\"a\": \"wood_thickness\"}.get(n, n)\n\n\ndef load_input_file(filepath):\n    \"\"\"Reads 'name = value' lines ('#' starts a comment). Returns {key: text}.\"\"\"\n    values = {}\n    with open(filepath, \"rb\") as fh:\n        raw = fh.read()\n    try:\n        text = raw.decode(\"utf-8-sig\")\n    except UnicodeDecodeError:\n        text = raw.decode(\"cp1252\", errors=\"replace\")          # file saved as ANSI (older Windows editors)\n    for nr, line in enumerate(text.splitlines(), 1):\n        line = line.split(\"#\", 1)[0].strip()\n        if not line:\n            continue\n        if \"=\" not in line:\n            raise FoldingError(f\"Input file, line {nr}: expected 'name = value', found: '{line}'\")\n        name, value = line.split(\"=\", 1)\n        key = _norm(name)\n        if key in values:      # aliases such as Width/Breite must not silently overwrite each other\n            raise FoldingError(f\"Input file, line {nr}: duplicate entry '{name.strip()}'.\")\n        values[key] = value.strip()\n    unknown = sorted(k for k in values if k not in KNOWN_KEYS)\n    if unknown:\n        print(\"WARNING: Unknown entries in the input file (typo?): \"\n              + \", \".join(unknown))\n    return values\n\n\ndef p_number(minimum=None, strict=False, words=None):\n    \"\"\"Parser for numbers; words: {word: value}, e.g. {'auto': 12.0}; 'a' counts as 'auto'.\"\"\"\n    words = words or {}\n\n    def parse(text):\n        s = text.strip().lower()\n        if s == \"a\" and \"auto\" in words:\n            s = \"auto\"\n        if s in words:\n            return words[s], s\n        try:\n            w = float(s.replace(\",\", \".\"))\n        except ValueError:\n            extra = \"\".join(f\" or '{k}'\" for k in words)\n            raise ValueError(f\"Please enter a number{extra}.\")\n        if not math.isfinite(w):\n            raise ValueError(\"Please enter a finite number.\")\n        if minimum is not None and ((strict and w <= minimum) or (not strict and w < minimum)):\n            raise ValueError(f\"The value must be {'greater than' if strict else 'at least'} {minimum}.\")\n        return w, w\n    return parse\n\n\ndef p_choice(allowed, alias=None):\n    alias = alias or {}\n\n    def parse(text):\n        s = alias.get(text.strip().lower(), text.strip().lower())\n        if s not in allowed:\n            raise ValueError(\"Allowed: \" + \", \".join(allowed))\n        return s, s\n    return parse\n\n\ndef p_yes_no(text):\n    s = text.strip().lower()\n    if s in (\"y\", \"yes\", \"j\", \"ja\"):\n        return True, \"y\"\n    if s in (\"n\", \"no\", \"nein\"):\n        return False, \"n\"\n    raise ValueError(\"Please enter y or n.\")\n\n\nclass InputDialog:\n    \"\"\"Asks for every value; Enter accepts the value from the input file (or the default).\"\"\"\n\n    def __init__(self, values=None, fast=False):\n        self.values = dict(values or {})\n        self.fast = fast     # True: take values from the file without asking\n        self.used = {}          # key -> value (for saving)\n\n    def ask(self, key, label, parse, default=None):\n        raw = self.values.get(key, default)\n        from_file = key in self.values\n        while True:\n            if self.fast:\n                if raw is None or not str(raw).strip():\n                    raise FoldingError(f\"Input file: missing required value '{key}' ({label}).\")\n                typed = \"\"\n            else:\n                hint = f\" (Enter = {raw})\" if raw is not None else \"\"\n                typed = input(f\"{label}{hint}: \").strip()\n            text = typed if typed else raw\n            if text is None or not str(text).strip():\n                print(\"  Please enter a value.\")\n                continue\n            try:\n                value, stored = parse(str(text))\n            except ValueError as error:\n                if self.fast and not typed:\n                    raise FoldingError(f\"Input file: {label}: '{text}' - {error}\")\n                print(f\"  {error}\")\n                continue\n            if self.fast and not typed:\n                print(f\"{label}: {text}   ({'from file' if from_file else 'default'})\")\n            self.used[key] = stored\n            return value\n\n\ndef accept_all():\n    while True:\n        answer = input(\"Accept all values from the file without asking? \"\n                        \"(y = yes, Enter = go through them one by one and change): \").strip().lower()\n        if answer in (\"\", \"n\", \"no\", \"nein\"):\n            return False\n        if answer in (\"y\", \"yes\", \"j\", \"ja\"):\n            return True\n        print(\"  Please enter y or Enter.\")\n\n\ndef _write_atomic(filepath, data):\n    \"\"\"Write completely to a temporary file first, then replace: the old file survives any error.\"\"\"\n    target = Path(filepath).resolve()\n    temp = None\n    try:\n        with tempfile.NamedTemporaryFile(dir=target.parent, prefix=target.name + \".\", suffix=\".tmp\", delete=False) as fh:\n            temp = Path(fh.name)\n            fh.write(data)\n            fh.flush()\n            os.fsync(fh.fileno())\n        os.replace(temp, target)\n    finally:\n        if temp is not None:\n            temp.unlink(missing_ok=True)\n\n\ndef save_inputs(values, filepath):\n    \"\"\"Writes all inputs as an input file (read again at the next run).\"\"\"\n    def fmt(w):\n        return w if isinstance(w, str) else f\"{w:.10g}\".replace(\".\", \",\")\n    fields = [(\"WoodThickness\", \"wood_thickness\", \"\"), (\"BraceWidth\", \"brace_width\", \"\"),\n              (\"Width\", \"width\", \"\"), (\"Height\", \"height\", \"\"), (\"Depth\", \"depth\", \"\"),\n              (\"S1\", \"s1\", \"number or auto (= same slope throughout)\"),\n              (\"S2\", \"s2\", \"area at the driver\"),\n              (\"Mode\", \"mode\", \"1 = specify S3 and L23, 2 = specify the slope\"),\n              (\"Slope\", \"slope\", \"mode 2 only\"),\n              (\"S3\", \"s3\", \"mode 1 only\"), (\"L23\", \"l23\", \"length S2-S3 (old name: Con); mode 1 only (and with S3Position = auto)\"),\n              (\"S4\", \"s4\", \"S4 target from Hornresp (comparison only), number or auto (= no target)\"),\n              (\"S5\", \"s5\", \"S5 target from Hornresp (comparison only), number or auto (= no target)\"),\n              (\"DriverOffset\", \"driver_offset\", \"distance of S2 + S4 (the driver centre) from the left outer edge\"),\n              (\"Slope2\", \"slope2\", \"b' after S3: auto (= calculated from the box) or a number, also negative\"),\n              (\"S3Position\", \"s3position\", \"1-7 or auto (chosen from the desired L23)\"),\n              (\"HornrespFile\", \"hornresp\", \"exported Hornresp text file (optional); S1-S5, L23 are read from it\"),\n              (\"DriverDiameter\", \"driver_diameter\", \"gross (frame) diameter, auto = unknown\"),\n              (\"MagnetDiameter\", \"magnet_diameter\", \"magnet/motor diameter for the depth check, auto = 0.5 x DriverDiameter\"),\n              (\"DriverDepth\", \"driver_depth\", \"mounting depth incl. magnet at the S4 side, auto = unknown\"),\n              (\"Kink\", \"kink\", \"board a with a kink (S1 then = Hornresp value): y or n\"),\n              (\"SVG\", \"svg\", \"create the drawing: y or n\")]\n    lines = [\"# Hornfolding - inputs of the last run (overwritten automatically at every run)\",\n              f\"# Lengths in {UNIT}, areas in {UNIT}²; comma or point as decimal separator.\", \"\"]\n    for name, key, comment in fields:\n        if key in values:\n            line = f\"{name} = {fmt(values[key])}\"\n            lines.append(f\"{line:<30}# {comment}\" if comment else line)\n    _write_atomic(filepath, (\"\\n\".join(lines) + \"\\n\").encode(\"utf-8\"))\n\n\n# ---------------------------------------------------------------------------\n# Hornresp text files (exported single simulations: \"Key = value\" lines, sections start with '|')\n# ---------------------------------------------------------------------------\nHORN_ROWS = (\"S1\", \"S2\", \"Con\", \"F12\", \"S2\", \"S3\", \"Con\", \"F23\", \"S3\", \"S4\", \"Con\", \"F34\", \"S4\", \"S5\", \"Con\", \"F45\")\nHORN_LENGTHS = (2, 6, 10, 14)\n\n\ndef _hornresp_lines(filepath):\n    \"\"\"Lines of a Hornresp file (latin-1 so that every byte survives unchanged), with line endings.\"\"\"\n    with open(filepath, \"rb\") as fh:\n        return fh.read().decode(\"latin-1\").splitlines(keepends=True)\n\n\ndef is_hornresp_file(filepath):\n    try:\n        return any(z.strip().startswith(\"|HORN PARAMETER VALUES\") for z in _hornresp_lines(filepath)[:60])\n    except OSError:\n        return False\n\n\ndef _horn_entries(lines):\n    \"\"\"[(line index, key, value text)] of the horn section in file order; checks the expected order of the keys.\"\"\"\n    entries, inside = [], False\n    for i, z in enumerate(lines):\n        t = z.strip()\n        if t.startswith(\"|\"):\n            inside = t.startswith(\"|HORN PARAMETER VALUES\")\n            continue\n        if inside and \"=\" in t:\n            k, v = t.split(\"=\", 1)\n            entries.append((i, k.strip(), v.strip()))\n    if len(entries) != len(HORN_ROWS) or any(\n            key not in (\"Con\", \"Par\") if n in HORN_LENGTHS else key != HORN_ROWS[n]\n            for n, (_, key, _) in enumerate(entries)):\n        raise FoldingError(\"Hornresp file: the horn section does not have the expected structure \"\n                             \"(four Con/Par segments with S1..S5 and F12..F45; other flare types are unsupported).\")\n    return entries\n\n\nHR_FACTOR_LENGTH = 10.0 if UNIT == \"mm\" else 1.0               # Hornresp cm -> script unit\nHR_FACTOR_AREA = HR_FACTOR_LENGTH ** 2\n\n\ndef read_hornresp(filepath):\n    \"\"\"Relevant values of a Hornresp text file: S1..S5 and the four section lengths.\"\"\"\n    entries = _horn_entries(_hornresp_lines(filepath))\n    try:\n        w = [float(e[2].replace(\",\", \".\")) for e in entries]\n    except ValueError:\n        raise FoldingError(\"Hornresp file: a horn value is not a number.\")\n    for n, (_, key, _) in enumerate(entries):\n        if not math.isfinite(w[n]):\n            raise FoldingError(f\"Hornresp file: {key} must be finite (entry {n + 1}).\")\n        # S1 may be zero at the closed end; active lengths and S2..S5 may not.\n        positive = (key.startswith(\"S\") and key != \"S1\") or n in HORN_LENGTHS\n        if (key == \"S1\" and w[n] < 0) or (positive and w[n] <= 0):\n            raise FoldingError(f\"Hornresp file: invalid {key} = {w[n]:g} (entry {n + 1}).\")\n    for i, j in ((1, 4), (5, 8), (9, 12)):\n        if not math.isclose(w[i], w[j], rel_tol=1e-9, abs_tol=1e-9):\n            raise FoldingError(f\"Hornresp file: inconsistent repeated area {entries[i][1]}.\")\n    fl, la = HR_FACTOR_AREA, HR_FACTOR_LENGTH                   # Hornresp always uses cm and cm²\n    return {\"S1\": w[0] * fl, \"S2\": w[1] * fl, \"S3\": w[5] * fl, \"S4\": w[9] * fl, \"S5\": w[13] * fl,\n            \"L12\": w[2] * la, \"L23\": w[6] * la, \"L34\": w[10] * la, \"L45\": w[14] * la,\n            \"flares\": tuple(entries[n][1] for n in HORN_LENGTHS)}\n\n\ndef write_hornresp(source, target, values):\n    \"\"\"Replaces only the horn values; flare types and everything else stay as in the source.\"\"\"\n    if Path(source).resolve() == Path(target).resolve() or (Path(target).exists() and os.path.samefile(source, target)):\n        raise FoldingError(\"Hornresp source and output must be different files.\")\n    numbers = (\"S1\", \"S2\", \"S3\", \"S4\", \"S5\", \"L12\", \"L23\", \"L34\", \"L45\")\n    for key in numbers:\n        value = values.get(key)\n        if value is None or not math.isfinite(value) or (value < 0 if key == \"S1\" else value <= 0):\n            raise FoldingError(f\"Invalid Hornresp output value for {key}: {value}.\")\n    lines = _hornresp_lines(source)\n    entries = _horn_entries(lines)\n    values = {k_: values[k_] / (HR_FACTOR_AREA if k_.startswith(\"S\") else HR_FACTOR_LENGTH) for k_ in numbers}\n    new = {0: values[\"S1\"], 1: values[\"S2\"], 2: values[\"L12\"], 4: values[\"S2\"], 5: values[\"S3\"], 6: values[\"L23\"],\n           8: values[\"S3\"], 9: values[\"S4\"], 10: values[\"L34\"], 12: values[\"S4\"], 13: values[\"S5\"], 14: values[\"L45\"]}\n    for n, value in new.items():\n        i, _key, _ = entries[n]\n        z = lines[i]\n        end = z[len(z.rstrip(\"\\r\\n\")):]\n        head = z.split(\"=\", 1)[0]\n        lines[i] = f\"{head}= {value:.2f}{end}\"\n    _write_atomic(target, \"\".join(lines).encode(\"latin-1\"))\n\n\n\ndef s4_bend6_level(geo):\n    \"\"\"0 = S4 behind bend 6, 1 = S4 inside bend 6 behind B6, 2 = S4 before B6 (inside the curved part).\"\"\"\n    d, t = geo[\"s4_over_x0\"], geo[\"bend_geo\"][5][\"parts\"]\n    if not geo[\"s4_in_bend\"]:\n        return 0\n    return 1 if d >= -t[2] - 1e-9 else 2\n\n\ndef free_height(geo, origin, direction, box):\n    \"\"\"Free distance from `origin` along the unit vector `direction` to the nearest wall of the channel\n    (boards b, c, d and the box walls; board a itself is excluded). Returns (distance, name) or (None, \"\").\"\"\"\n    xl, xr, floor_z, ceil_z = box\n    segs = []\n    for nm, poly in ((\"b\", geo[\"poly\"][\"b\"]), (\"c\", geo[\"poly\"][\"c\"])):\n        segs += [(poly[i], poly[(i + 1) % len(poly)], nm) for i in range(len(poly))]\n    pd_ = geo[\"poly\"][\"d\"]                       # Ld_t, C5, C6, Ld_l\n    names_d = (\"d top side\", \"d end face\", \"d underside\", \"d left face\")\n    segs += [(pd_[i], pd_[(i + 1) % 4], names_d[i]) for i in range(4)]\n    segs += [((xl, floor_z), (xr, floor_z), \"floor\"), ((xl, ceil_z), (xr, ceil_z), \"ceiling\"),\n             ((xl, floor_z), (xl, ceil_z), \"left wall\"), ((xr, floor_z), (xr, ceil_z), \"right wall\")]\n    best = (None, \"\")\n    for p_, q_, nm in segs:\n        ex_, ey_ = q_[0] - p_[0], q_[1] - p_[1]\n        den = direction[0] * ey_ - direction[1] * ex_\n        if abs(den) < 1e-12:\n            continue\n        wx, wy = p_[0] - origin[0], p_[1] - origin[1]\n        t = (wx * ey_ - wy * ex_) / den                  # along the ray\n        u = (wx * direction[1] - wy * direction[0]) / den  # along the segment (0..1)\n        if t > 1e-9 and -1e-9 <= u <= 1 + 1e-9 and (best[0] is None or t < best[0]):\n            best = (t, nm)\n    return best\n\n\ndef kink_check(geo, b1, a, L12, L45):\n    \"\"\"Estimate for a kinked board a: acoustic mass (inertance) and volume of the segments S1-S2 and S4-S5,\n    built vs. Hornresp's linear segment. Profiles from the stations and the kink (support points); estimate only.\"\"\"\n    seg_i = integrate_inertia\n\n    def seg_v(pr):\n        return sum((s2 - s1) * (A1 + A2) / 2 for (s1, A1), (s2, A2) in zip(pr[:-1], pr[1:]))\n    fl, K, Ls, Kup = geo[\"area\"], geo[\"K\"], geo[\"Ls\"], geo[\"K_up\"]\n    S1h, S1r, S2, S4, S5h, S5r = fl[\"S1\"], geo[\"S1_real\"], fl[\"S2\"], fl[\"S4\"], fl[\"S5\"], geo[\"S5_real\"]\n    S1c, Kc = (Ls[0], a + (Ls[1] - a) / 2), (K[0], a + (K[1] - a) / 2)\n    e_k = _unit_vec((K[0] - Ls[0], K[1] - Ls[1]))\n    t_ = _unit_vec((1.0 + e_k[0] + geo[\"ex\"][0], e_k[1] + geo[\"ex\"][1]))\n    p1 = [(0.0, S1r), (_dist(S1c, Kc), (K[1] - a) / abs(t_[0]) * b1), (L12, S2)]\n    Ld, dd = geo[\"Ld_l\"], geo[\"dd\"]\n    # Vertical distance (approximation; the exact cross-section is perpendicular to the centreline).\n    # The error is cos((psi + alpha_d)/2) - 1, below 0.5% for typical THAM slopes; only the console estimate is affected.\n    a_kup = (Ld[1] + (Kup[0] - Ld[0]) * dd[1] / dd[0] - Kup[1]) * b1\n    x4 = geo[\"U4\"][0]\n    p4 = [(0.0, S4), (L45 * (x4 - Kup[0]) / x4, a_kup), (L45, S5r)]\n    h1, h4 = [(0.0, S1h), (L12, S2)], [(0.0, S4), (L45, S5h)]\n    ih1, ip1, ih4, ip4 = (seg_i(p) for p in (h1, p1, h4, p4))\n    if not all(math.isfinite(v) and v > 0 for v in (ih1, ip1, ih4, ip4)):\n        raise ValueError(\"Kink comparison requires finite, positive inertance.\")\n    return {\"M1\": ih1 / ip1, \"M4\": ih4 / ip4,\n            \"dL1\": (ih1 - ip1) * S1r, \"dL4\": (ih4 - ip4) * S5r,\n            \"dV1\": seg_v(h1) - seg_v(p1), \"dV4\": seg_v(h4) - seg_v(p4)}\n\n\ndef find_input_file(argument=None):\n    \"\"\"(path, explicit): command-line argument or file next to the script, else (None, False).\"\"\"\n    if argument is not None:\n        return os.path.abspath(argument), True\n    filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), INPUT_FILE)\n    if not os.path.exists(filepath):                     # older file names\n        for old_name in (\"Hornfaltung_Input.txt\", \"Hornfaltung_Eingabe.txt\"):\n            old = os.path.join(os.path.dirname(os.path.abspath(__file__)), old_name)\n            if os.path.exists(old):\n                filepath = old\n                break\n    return (filepath, False) if os.path.exists(filepath) else (None, False)\n\n\n# ---------------------------------------------------------------------------\n# Root finding\n# ---------------------------------------------------------------------------\ndef find_roots(f, x_lo, x_hi, step=SEARCH_STEP, only_first=False):\n    \"\"\"Roots of f in [x_lo, x_hi]: grid scan for sign changes, then bisection.\n\n    Non-finite function values (invalid geometry, NaN) count as a gap: no sign change is\n    counted across a gap, and a bisection that runs into a gap is discarded.\n    Tangential roots without a sign change can be missed by this grid method.\n    A residual check rejects jumps whose bracket shrinks without approaching zero.\n    \"\"\"\n    if not all(math.isfinite(x) for x in (x_lo, x_hi, step)) or step <= 0:\n        raise ValueError(\"Root search requires finite bounds and a positive finite step.\")\n    if x_hi <= x_lo:\n        return []\n    n = max(1, int(math.ceil((x_hi - x_lo) / step)))\n    roots = []\n    x0 = x_lo\n    f0 = f(x0)\n    if math.isfinite(f0) and f0 == 0:\n        roots.append(x0)\n        if only_first:\n            return roots\n    for i in range(1, n + 1):\n        x1 = min(x_lo + i * step, x_hi)\n        f1 = f(x1)\n        # A root exactly at a grid point also counts directly after a geometry gap (NaN).\n        if math.isfinite(f1) and f1 == 0:\n            roots.append(x1)\n        elif math.isfinite(f0) and math.isfinite(f1):\n            # No product: f0*f1 can underflow to -0.0 for tiny values.\n            if f0 != 0 and (f0 < 0) != (f1 < 0):\n                lo, hi, f_lo = x0, x1, f0\n                ok = True\n                tolerance = max(abs(f0), abs(f1)) * 1e-10\n                best_x, best_f = (x0, f0) if abs(f0) < abs(f1) else (x1, f1)\n                for _ in range(100):\n                    mid = lo + (hi - lo) / 2\n                    if mid == lo or mid == hi:\n                        break  # floating-point resolution reached; further calls would not help.\n                    f_mid = f(mid)\n                    if not math.isfinite(f_mid):\n                        ok = False\n                        break\n                    if abs(f_mid) < abs(best_f):\n                        best_x, best_f = mid, f_mid\n                    if f_mid == 0:\n                        break\n                    if (f_lo < 0) != (f_mid < 0):\n                        hi = mid\n                    else:\n                        lo, f_lo = mid, f_mid\n                if ok and abs(best_f) <= tolerance:\n                    roots.append(best_x)\n        if only_first and roots:\n            return roots\n        x0, f0 = x1, f1\n    return roots\n\n\ndef find_root(f, x_lo, x_hi, step=SEARCH_STEP):\n    \"\"\"First root of f in [x_lo, x_hi], or None.\"\"\"\n    w = find_roots(f, x_lo, x_hi, step, only_first=True)\n    return w[0] if w else None\n\n\ndef lambda4_limit(width):\n    \"\"\"Frequency [Hz] at which `width` (in UNIT) is a quarter of the wavelength (c = 344 m/s).\"\"\"\n    return {\"cm\": 34400.0, \"mm\": 344000.0}.get(UNIT, 34400.0) / (4.0 * width)\n\n\ndef liter(volume):\n    \"\"\"Volume in UNIT³ -> litres (cm³ -> /1000, mm³ -> /1e6).\"\"\"\n    return volume / {\"cm\": 1.0e3, \"mm\": 1.0e6}.get(UNIT, 1.0e3)\n\n\ndef integrate_inertia(profile):\n    \"\"\"Integral ds/A for a piecewise linear profile [(path, area), ...].\n\n    A zero area at either end of a section makes the integral diverge,\n    so such sections must not simply drop out of the sum.\n    \"\"\"\n    if any(not math.isfinite(s) or not math.isfinite(A) or A < 0 for s, A in profile):\n        raise ValueError(\"Inertance requires finite positions and nonnegative areas.\")\n    if any(s2 < s1 for (s1, _), (s2, _) in zip(profile, profile[1:])):\n        raise ValueError(\"Inertance profile positions must be nondecreasing.\")\n    parts = []\n    for (s1, A1), (s2, A2) in zip(profile, profile[1:]):\n        ds = s2 - s1\n        if ds == 0:\n            continue\n        if A1 == 0 or A2 == 0:\n            return math.inf\n        dA = A2 - A1\n        if dA == 0:\n            mean = 1.0 / A1\n        elif abs(dA) < 0.5 * A1:\n            mean = math.log1p(dA / A1) / dA\n        else:\n            mean = (math.log(A2) - math.log(A1)) / dA\n        parts.append(ds * mean)\n    return math.fsum(parts)\n\n\n\nPOSITIONS = {\n    1: \"entry of bend 3 (C3, top left, before the shaft)\",\n    2: \"exit of bend 3 (C3, start of the shaft)\",\n    3: \"entry of bend 4 (C4, end of the shaft)\",\n    4: \"exit of bend 4 (start of the middle channel)\",\n    5: \"entry of bend 5 (C5)\",\n    6: \"exit of bend 5 (C5, start of the short descent)\",\n    7: \"entry of bend 6 (C6, into the chamber)\",\n}\n\n\n# ---------------------------------------------------------------------------\n# Calculation core 0.5: geometry first, everything along the centreline\n#\n# Law: the channel width (chord perpendicular to the centreline) grows with the path s along the\n# centreline:   W(s) = W2 + b*s   up to S3,   then   W(s3) + b'*(s - s3).   W2 = S2/b1.\n# Straight boards are exact rectangles tilted against each other by the wedge angle psi = 2*atan(b/2);\n# the chord then grows exactly linearly with the centreline path on straight sections.\n# Each bend is solved in turn via the position of its inner corner such that the exit chord\n# matches the law W(s_exit). The entry chord then fits automatically (check value).\n# ---------------------------------------------------------------------------\ndef _ang(b):\n    \"\"\"Wedge angle of two channel walls that diverge by b per unit of centreline path.\"\"\"\n    return 2.0 * math.atan(b / 2.0)\n\n\ndef _add(p, v, t=1.0):\n    return (p[0] + t * v[0], p[1] + t * v[1])\n\n\ndef _neg(v):\n    return (-v[0], -v[1])\n\n\ndef _bend(C, w_in, w_out, wall_in, wall_out):\n    G = bend_hand(C, w_in, w_out, wall_in, wall_out)\n    ue = _unit_vec((w_in[0][0] + w_in[1][0], w_in[0][1] + w_in[1][1]))\n    ua = _unit_vec((w_out[0][0] + w_out[1][0], w_out[0][1] + w_out[1][1]))\n    G[\"theta\"] = math.degrees(math.acos(max(-1.0, min(1.0, ue[0] * ua[0] + ue[1] * ua[1]))))\n    return G\n\n\nS3_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)\n\n\n_REJECTION = [\"\"]        # reason for the last rejected geometry (for error messages)\n\n\ndef build(P, k, b_after):\n    \"\"\"Complete construction for S3 position k and slope b' = b_after. Returns dict or None (no solution).\"\"\"\n    _REJECTION[0] = \"\"\n    a, b, T, H, L45, b1, W2 = P[\"a\"], P[\"b\"], P[\"depth\"], P[\"H\"], P[\"L45\"], P[\"b1\"], P[\"W2\"]\n    xl, xr, zc = a, T - a, H - a\n    psi = _ang(b)\n    if math.cos(psi) < COS_PSI_MIN:\n        _REJECTION[0] = \"slope too large (wedge angle)\"\n        return None\n    ex, en = (math.cos(psi), math.sin(psi)), (-math.sin(psi), math.cos(psi))\n    floor, ceil_ = ((0.0, a), (1.0, 0.0)), ((0.0, zc), (1.0, 0.0))\n    wB, wD = ((xr, 0.0), (0.0, 1.0)), ((xl, 0.0), (0.0, 1.0))\n    b_shaft = b_after if k <= 2 else b                # slope in the left shaft (c end face / D)\n    b_mid = b_after if k <= 4 else b                    # slope in the middle channel (c/d)\n    b_riser = b_after if k <= 6 else b                  # slope of the short descent (end face of d / b)\n    alpha_d = psi - _ang(b_mid)                    # inclination of d against the horizontal\n    dd = (math.cos(alpha_d), math.sin(alpha_d))\n    n_perp = (dd[1], -dd[0])                       # normal of d (lower face lies a along it)\n    beta = psi - _ang(b_riser)                     # d is cut so that the descent opens with the slope b_riser\n    n_ab = (math.sin(beta), -math.cos(beta))       # end face of d, pointing down (bevelled unless beta = alpha_d)\n    ps = _ang(b_shaft)\n    ab = (math.sin(ps), -math.cos(ps))             # end face of c, pointing down\n    ab_b = _neg(en)                                # left face of b, pointing down\n\n    # --- S2: chord perpendicular to the bisector of floor and board a, through the driver centre ------\n    U2 = (L45 + a / 2 * math.sin(psi), a + W2 * math.cos(psi / 2))      # underside of a\n    F2 = (U2[0] + W2 * math.sin(psi / 2), a)                           # foot point on the floor\n    S2c = _midpoint(U2, F2)\n    U4 = _add(U2, en, a)                                               # top side of a (S4)\n\n    def law(s, s3):\n        if s3 is None or s <= s3:\n            return W2 + b * s\n        return W2 + b * s3 + b_after * (s - s3)\n\n    sf = S3_FOLD[k]\n    state = {\"s3\": None}\n    folds = []\n\n    def solve(nr, mk, lo, hi, X_prev, s_prev, step=SEARCH_STEP_BEND):\n        def evaluate(par):\n            try:\n                G, extra = mk(par)\n            except (ZeroDivisionError, ValueError):\n                return None\n            if G is None or not (G[\"w1\"] > 0 and G[\"w2\"] > 0):\n                return None\n            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\n                if not (xl - BOX_TOL <= pk_[0] <= xr + BOX_TOL and a - BOX_TOL <= pk_[1] <= zc + BOX_TOL):\n                    return None\n            if not bend_sign_ok(G):          # construction would run backwards (see bend_sign_ok)\n                return None\n            s_e = s_prev + math.hypot(G[\"E0\"][0] - X_prev[0], G[\"E0\"][1] - X_prev[1])\n            vpl = sum(G[\"parts\"])\n            s_x = s_e + vpl\n            s3 = state[\"s3\"]\n            if sf[0] == nr:\n                s3 = s_e if sf[1] == \"E\" else s_x\n            return G, extra, s_e, s_x, vpl, s3\n\n        def res(par):\n            r = evaluate(par)\n            if r is None:\n                return float(\"nan\")\n            G, extra, s_e, s_x, vpl, s3 = r\n            return G[\"w2\"] - law(s_x, s3)\n        par = find_root(res, lo, hi, step)\n        if par is None:\n            return None\n        G, extra, s_e, s_x, vpl, s3 = evaluate(par)\n        if sf[0] == nr:\n            state[\"s3\"] = s3\n        folds.append({\"nr\": nr, \"par\": par, \"G\": G, \"s_e\": s_e, \"s_x\": s_x, \"vpl\": vpl,\n                      \"law_in\": law(s_e, s3), \"law_out\": law(s_x, s3)})\n        return G, extra, s_x\n\n    def mk1(t):\n        C = _add(U2, ex, t)\n        return _bend(C, ((1.0, 0.0), ex), (en, (0.0, 1.0)), floor, wB), C\n    limit = 2.0 * (T + H)                           # no path section of the search can be longer than this\n    r = solve(1, mk1, BEND_MIN, min((xr - U2[0]) / math.cos(psi) - BEND_MARGIN, limit), S2c, 0.0)\n    if r is None:\n        return None\n    G1, C1, s1x = r\n\n    def mk2(t):\n        C = _add(C1, en, t)\n        return _bend(C, (en, (0.0, 1.0)), (_neg(ex), (-1.0, 0.0)), wB, ceil_), C\n    r = solve(2, mk2, BEND_MIN, min((zc - C1[1]) / math.cos(psi) - BEND_MARGIN, limit), G1[\"X0\"], s1x)\n    if r is None:\n        return None\n    G2, C2, s2x = r\n\n    def mk3(t):\n        C = _add(C2, ex, -t)\n        return _bend(C, (_neg(ex), (-1.0, 0.0)), (ab, (0.0, -1.0)), ceil_, wD), C\n    r = solve(3, mk3, BEND_MIN, min((C2[0] - xl) / math.cos(psi) - BEND_MARGIN, limit), G2[\"X0\"], s2x)\n    if r is None:\n        return None\n    G3, C3, s3x = r\n    c_bottom = _add(C2, en, -a)                      # underside of c (point, direction ex)\n    C4 = _intersect(C3, ab, c_bottom, ex)              # lower left corner of c (end face ab)\n\n    def mk4(v):\n        Pd = (C4[0], C4[1] - v)\n        return _bend(C4, (ab, (0.0, -1.0)), (ex, dd), wD, (Pd, dd)), Pd\n    r = solve(4, mk4, BEND_MIN, C4[1] - a - 2 * BEND_MARGIN, G3[\"X0\"], s3x)\n    if r is None:\n        return None\n    G4, Pd, s4x = r\n    w_cun = (C4, ex)\n    q_l = _add(C1, ex, -a)\n    w_bli = (q_l, en)\n\n    def mk5(tau):\n        C = _add(Pd, dd, tau)\n        return _bend(C, (ex, dd), (n_ab, ab_b), w_cun, w_bli), C\n    r = solve(5, mk5, BEND_MIN, 2.0 * T, G4[\"X0\"], s4x)\n    if r is None:\n        return None\n    G5, C5, s5x = r\n    a_top = (U4, ex)                               # top side of a (floor of the chamber), extended\n    Pd_u = _add(Pd, n_perp, a)\n    C6 = _intersect(C5, n_ab, Pd_u, dd)\n    G6 = _bend(C6, (n_ab, ab_b), (_neg(dd), _neg(ex)), w_bli, a_top)\n    if not (G6[\"w1\"] > 0 and G6[\"w2\"] > 0):                              # same validation as in solve()\n        return None\n    for pk_ in (G6[\"E0\"], G6[\"A\"], G6[\"B\"], G6[\"X0\"], G6[\"C\"], G6[\"Ci\"], G6[\"Cx\"], G6[\"Q\"]):\n        if not (xl - BOX_TOL <= pk_[0] <= xr + BOX_TOL and a - BOX_TOL <= pk_[1] <= zc + BOX_TOL):\n            return None\n    if not bend_sign_ok(G6):\n        _REJECTION[0] = (\"bend 6: the construction runs backwards (cross-section ratio too large for this turning angle); \"\n                         \"the path length would be wrong\")\n        return None\n    s_e6 = s5x + math.hypot(G6[\"E0\"][0] - G5[\"X0\"][0], G6[\"E0\"][1] - G5[\"X0\"][1])\n    s_x6 = s_e6 + sum(G6[\"parts\"])\n    if k == 7:\n        state[\"s3\"] = s_e6\n    folds.append({\"nr\": 6, \"par\": 0.0, \"G\": G6, \"s_e\": s_e6, \"s_x\": s_x6, \"vpl\": sum(G6[\"parts\"]),\n                  \"law_in\": law(s_e6, state[\"s3\"]), \"law_out\": law(s_x6, state[\"s3\"]), \"free_exit\": True})\n    bend_geo = [G1, G2, G3, G4, G5, G6]\n    Cs = [C1, C2, C3, C4, C5, C6]\n\n    # --- Board a (with or without a kink at S2), S1 ---------------------------------------------------\n    z_u = U2[1] + (xl - U2[0]) * math.tan(psi)       # underside of a at x = xl without a kink\n    s1_same = max(0.0, z_u - a) * b1\n    kink = bool(P.get(\"kink\")) and U2[0] > xl + 1e-9 and abs(P[\"S1\"] - s1_same) > 1e-3 * CM ** 2\n    r_driver = max(0.0, P.get(\"driver_d\") or 0.0) / 2        # half gross driver diameter (0 = unknown)\n    K = K_up = Kc = None\n    kink_note = \"\"\n    if kink:\n        # Kink point K on the underside of a2, r_driver to the left of the driver centre (S2); a2 stays straight\n        # at least half a driver diameter on both sides of the driver centre, on the underside AND on the top side\n        # (the mitre shortens the top side, so the kink is shifted until both sides have the free length).\n        t_max = (U2[0] - xl) / ex[0] - CM                       # mindestens 1 cm von a1 erhalten\n        if t_max <= 0:\n            kink = False\n            kink_note = \"no room for a kink between the driver and the left wall\"\n    if kink:\n        S2c_ = _midpoint(U2, F2)\n        S1h = P[\"S1\"]\n\n        def kink_solve(t_k):\n            \"\"\"Kink at distance t_k left of U2: real S1 from volume equality; returns (K, Kc, Ls, Lu, K_up, Lz) or None.\"\"\"\n            K = _add(U2, ex, -t_k)\n            Kc = (K[0], a + (K[1] - a) / 2)\n\n            def area12(Lz):                                  # side-view area between S1 and the S2 chord\n                return _poly_area([(xl, a), (xl, Lz), K, U2, F2])\n\n            def length12(Lz):\n                return _dist((xl, a + (Lz - a) / 2), Kc) + _dist(Kc, S2c_)\n\n            def rest(Lz):                                       # area of the drawing - area of Hornresp's segment\n                return area12(Lz) - length12(Lz) * (S1h + P[\"W2\"] * b1) / 2 / b1\n            lo, hi = a + 1e-3, a + 3.0 * (zc - a)               # real S1 such that the volume equals Hornresp's\n            r_lo, r_hi = rest(lo), rest(hi)\n            if r_lo * r_hi > 0:\n                _REJECTION[0] = (\"Board a with a kink: no real S1 makes the volume S1-S2 equal to Hornresp's linear \"\n                                 \"segment (kink too close to the wall or S1 too different from the continuous slope).\")\n                return None\n            for _ in range(80):\n                mid = (lo + hi) / 2\n                r_mid = rest(mid)\n                if r_lo * r_mid <= 0:\n                    hi, r_hi = mid, r_mid\n                else:\n                    lo, r_lo = mid, r_mid\n            Lz = (lo + hi) / 2\n            if Lz <= a + 1e-6 or Lz >= zc - a:                  # a1 must stay inside the box\n                _REJECTION[0] = \"Board a with a kink: the real S1 needed for Hornresp's volume would not fit in the box.\"\n                return None\n            Ls = (xl, Lz)\n            e_k = _unit_vec((K[0] - Ls[0], K[1] - Ls[1]))\n            n_k = (-e_k[1], e_k[0])\n            K_up = _intersect(_add(Ls, n_k, a), e_k, _add(U2, en, a), ex)\n            Lu = _intersect(_add(Ls, n_k, a), e_k, (xl, 0.0), (0.0, 1.0))\n            return K, Kc, Ls, Lu, K_up, Lz\n        t_k = min(r_driver, t_max)\n        result = None\n        for _ in range(6):\n            result = kink_solve(t_k)\n            if result is None:\n                return None\n            missing = r_driver - ((U4[0] - result[4][0]) * ex[0] + (U4[1] - result[4][1]) * ex[1])   # top side free length\n            if missing <= 1e-9 or t_k >= t_max:\n                break\n            t_k = min(t_k + missing, t_max)\n        if r_driver > t_k + 1e-9:\n            kink_note = f\"kink moved: half driver diameter {r_driver:.1f} does not fit left of S2 (max. {t_max:.1f})\"\n        K, Kc, Ls, Lu, K_up, Lz = result\n        poly_a = [Ls, K, C1, _add(C1, en, a), K_up, Lu]\n        s1_eff = (Lz - a) * b1\n    else:\n        Ls = (xl, z_u)\n        Lu = (xl, z_u + a / math.cos(psi))\n        poly_a = [Ls, C1, _add(C1, en, a), Lu]\n        s1_eff = s1_same\n    if Ls[1] < a - 1e-6 or Lu[1] <= Ls[1] or Lu[1] > zc + 1e-6:\n        _REJECTION[0] = (f\"board a would leave the box at the left wall (underside at height {Ls[1]:.2f}, \"\n                         f\"floor top at {a:.2f}): slope too steep for this driver position\")\n        return None\n    # --- further boards -----------------------------------------------------------------------------\n    B0 = _add(C1, en, a)\n    poly_b = [B0, _add(B0, ex, -a), _add(_add(C2, en, -a), ex, -a), _add(C2, en, -a)]\n    poly_c = [C2, C3, C4, _add(C2, en, -a)]\n    z_dt = Pd[1] + (xl - Pd[0]) * math.tan(alpha_d)\n    z_dl = Pd_u[1] + (xl - Pd_u[0]) * math.tan(alpha_d)\n    Ld_t, Ld_l = (xl, z_dt), (xl, z_dl)\n    if not (a - 1e-6 <= Ld_l[1] <= Ld_t[1] <= zc + 1e-6) or Ld_l[1] <= Lu[1]:\n        _REJECTION[0] = (f\"board d or the mouth would leave the box at the left wall (d underside {Ld_l[1]:.2f}, \"\n                         f\"top {Ld_t[1]:.2f}, a top {Lu[1]:.2f}; box {a:.2f} .. {zc:.2f})\")\n        return None\n    poly_d = [Ld_t, C5, C6, Ld_l]\n    # --- Mouth bevel: D1 and D2 continue the slopes of a (a1) and d through the front wall ---------------\n    top_slope = (K_up[1] - Lu[1]) / (K_up[0] - Lu[0]) if kink else ex[1] / ex[0]\n    Lu0 = (0.0, Lu[1] - xl * top_slope)                       # top edge of D1 at the outer face (x = 0)\n    Ld0 = (0.0, Ld_l[1] - xl * math.tan(alpha_d))             # bottom edge of D2 at the outer face\n    if not (a - BOX_TOL <= Lu0[1] < Ld0[1] <= zc + BOX_TOL):\n        _REJECTION[0] = (f\"the mouth bevel of D1/D2 would leave the box at the outer face (D1 top {Lu0[1]:.2f}, \"\n                         f\"D2 bottom {Ld0[1]:.2f}; box {a:.2f} .. {zc:.2f})\")\n        return None\n    # --- Cross-sections, centreline -----------------------------------------------------------------\n    S2_lin = (U2, F2)\n    S4_lin = _crossline(U4, ex, Pd_u, dd)\n    S4c = _midpoint(*S4_lin)\n    S1c = (xl, a + (Ls[1] - a) / 2)\n    S5_lin = (Lu0, Ld0)\n    S5c = _midpoint(*S5_lin)\n    # --- Centreline: S1c, (kink Kc), S2c, (A,B)*6, S5c.  S1..S5 are cross-sections, NOT waypoints of the path. ---\n    ua6 = G6[\"uc_out\"]\n    # Distance of the driver centre behind the exit cross-section of bend 6 (negative: S4 lies in the bend).\n    # Reference point C6 instead of X0 gives the same value: X0 lies on the exit chord C6-Cx6, which is perpendicular to ua6.\n    s4_over_x0 = (U4[0] - G6[\"C\"][0]) * ua6[0] + (U4[1] - G6[\"C\"][1]) * ua6[1]\n    s4_in_bend = s4_over_x0 < -1e-9\n    pts = [S1c, S2c]\n    q_inserted = False\n    for G in bend_geo:\n        pts += [G[\"A\"], G[\"B\"]]\n    if kink:\n        # Board a with a kink: the walls of the chamber change direction at the cross-section through K_up. The centreline\n        # follows the bisector (a2 top, d) from bend 6 up to that cross-section (perpendicular to ua6 through K_up), then\n        # goes straight to the mouth centre S5c (bisector of a1 top and d); no bend construction at the kink.\n        Bk = G6[\"B\"]\n        t_q = (K_up[0] - Bk[0]) * ua6[0] + (K_up[1] - Bk[1]) * ua6[1]\n        t_x = (G6[\"X0\"][0] - Bk[0]) * ua6[0] + (G6[\"X0\"][1] - Bk[1]) * ua6[1]\n        if t_q > max(t_x, 0.0) + 1e-6:\n            pts += [(Bk[0] + ua6[0] * t_q, Bk[1] + ua6[1] * t_q)]\n            q_inserted = True\n    pts += [S5c]\n    cum = [0.0]\n    for i, (p_, q_) in enumerate(zip(pts[:-1], pts[1:])):\n        lg = math.hypot(q_[0] - p_[0], q_[1] - p_[1])\n        if i == 0 and kink:                      # S1 -> S2 runs via the kink\n            lg = _dist(p_, Kc) + _dist(Kc, q_)\n        cum.append(cum[-1] + lg)\n    s_e6 = cum[12] - G6[\"parts\"][0]               # path position of the entry (E0) of bend 6\n    s_x6 = cum[13] + G6[\"parts\"][2]               # path position of the exit (X0) of bend 6\n    if s4_in_bend:\n        # S4 in the curved part: the cross-section is the fan ray from the inner corner C6 through the driver centre\n        # U4; its path position is where this ray meets the bend path E0-A-B-X0\n        hits = _ray_path(G6[\"C\"], (U4[0] - G6[\"C\"][0], U4[1] - G6[\"C\"][1]),\n                               [G6[\"E0\"], G6[\"A\"], G6[\"B\"], G6[\"X0\"]])\n        if hits is None:\n            _REJECTION[0] = \"S4 (driver centre) lies outside the fan of bend 6\"\n            return None\n        s4_cum = s_e6 + hits\n        S4_lin = (G6[\"C\"], U4)\n        S4c = _midpoint(*S4_lin)\n    else:\n        s4_cum = cum[13] + (S4c[0] - G6[\"B\"][0]) * ua6[0] + (S4c[1] - G6[\"B\"][1]) * ua6[1]\n    if s4_cum >= cum[-1] - 1e-6:\n        _REJECTION[0] = \"S4 would lie at or behind the mouth\"\n        return None\n    s_s4 = s4_cum - cum[1]\n    s3_lin = {1: (G3[\"C\"], G3[\"Ci\"]), 2: (G3[\"C\"], G3[\"Cx\"]), 3: (G4[\"C\"], G4[\"Ci\"]), 4: (G4[\"C\"], G4[\"Cx\"]),\n              5: (G5[\"C\"], G5[\"Ci\"]), 6: (G5[\"C\"], G5[\"Cx\"]), 7: (G6[\"C\"], G6[\"Ci\"])}[k]\n    section = {\"S1\": ((xl, a), Ls), \"S2\": S2_lin, \"S3\": s3_lin, \"S4\": S4_lin, \"S5\": S5_lin}\n    area = {n: _dist(*section[n]) * b1 for n in section}\n    S4_fan = area[\"S4\"]\n    S1_real, S5_real = area[\"S1\"], _dist(*S5_lin) * b1\n    # Chamber S4-S5: path length and built air volume (independent of the Hornresp areas)\n    l45 = cum[-1] - s4_cum\n    s4_foot = G6[\"C\"] if s4_in_bend else S4_lin[1]\n    if kink:\n        ch45 = [Lu0, Lu, K_up, U4, s4_foot, Ld_l, Ld0]\n    else:\n        ch45 = [Lu0, Lu, U4, s4_foot, Ld_l, Ld0]\n    v45 = _poly_area(ch45) * b1\n    if s4_in_bend:\n        # Theoretical S4 for Hornresp: the straight line S4 -> mouth passes through the built exit area Ax of bend 6 (at X0)\n        # and ends in the REAL mouth area S5_real (not in the Hornresp S5, which is derived from S4 afterwards):\n        #     S4 = Ax + (Ax - S5_real) * L2 / Lk          L2 = path S4 -> X0 (inside bend 6), Lk = path X0 -> mouth\n        # (0.69: no coupling to the Hornresp S5, hence no pole at Lk = L2 as in 0.68 with a kink).\n        Ax = b1 * G6[\"w2\"]\n        L2, Lk = s_x6 - s4_cum, cum[-1] - s_x6\n        if Lk <= 1e-6:\n            _REJECTION[0] = \"S4 in bend 6 and no straight chamber path between the bend exit and the mouth\"\n            return None\n        area[\"S4\"] = Ax + (Ax - S5_real) * L2 / Lk\n    S4_drawing = S4_lin\n    if s4_in_bend:\n        # drawing: from the driver centre straight towards C6 (through the path), exactly as long as the calculated S4 area\n        # corresponds to (S4 / b1), so that the purple line shows the same cross-section as the printed result\n        ric = _unit_vec((G6[\"C\"][0] - U4[0], G6[\"C\"][1] - U4[1]))\n        S4_drawing = (U4, _add(U4, ric, area[\"S4\"] / b1))\n    # --- Hornresp areas S1 and S5 (0.69): every Hornresp segment reproduces the BUILT air volume ---------------\n    # S1-S2 (closed end, acts as a compliance): equal volume, S1_HR = 2*V12/L12 - S2.\n    #   With a kink the real S1 was solved so that this gives exactly the specified S1 (kink_solve).\n    #   Without a kink the built volume is used; a specified S1 has no effect then (use Kink = y to simulate another S1).\n    if kink:\n        area[\"S1\"] = P[\"S1\"]\n    else:\n        v12 = _poly_area([(xl, a), (xl, Ls[1]), U2, F2]) * b1\n        area[\"S1\"] = max(0.0, 2 * v12 / cum[1] - area[\"S2\"])\n    # S4-S5 (mouth): volume (compliance) and inertance (air mass) cannot both be matched with a straight segment of\n    # the given length; S5_HR is the mean of the volume-equal S5_vol and the inertance-equal S5_inert.\n    S4h = area[\"S4\"]\n    s5_vol = 2 * v45 / l45 - S4h\n    prof45 = [(0.0, S4h), (l45, S5_real)]\n    if kink and q_inserted and cum[-2] - s4_cum > 1e-9:\n        # real profile with the kink: cross-section through K_up, perpendicular to the centreline (direction ua6)\n        n6 = (-ua6[1], ua6[0])\n        try:\n            a_kup = _dist(K_up, _intersect(K_up, n6, Ld_l, dd)) * b1\n            prof45 = [(0.0, S4h), (cum[-2] - s4_cum, a_kup), (l45, S5_real)]\n        except ZeroDivisionError:\n            pass\n    s5_inert = None\n    if S4h > 0:\n        m_real = integrate_inertia(prof45)\n\n        def f_(x_):                                   # inertance of the straight segment S4h -> x_ minus the real one\n            return (l45 * math.log(x_ / S4h) / (x_ - S4h) if abs(x_ - S4h) > 1e-9 * S4h else l45 / S4h) - m_real\n        lo_, hi_ = S4h * 1e-3, S4h * 1e3\n        if f_(lo_) * f_(hi_) < 0:\n            for _ in range(200):\n                mid_ = math.sqrt(lo_ * hi_)\n                if f_(lo_) * f_(mid_) <= 0:\n                    hi_ = mid_\n                else:\n                    lo_ = mid_\n            s5_inert = math.sqrt(lo_ * hi_)\n    area[\"S5\"] = 0.5 * (s5_vol + s5_inert) if (s5_inert is not None and s5_vol > 0) else s5_vol\n    if area[\"S4\"] <= 0 or area[\"S5\"] <= 0 or _dist(*S4_lin) <= 0:\n        if area[\"S4\"] <= 0:\n            _REJECTION[0] = f\"the theoretical Hornresp S4 would be {area['S4']:.0f} (<= 0)\"\n        elif area[\"S5\"] <= 0:\n            _REJECTION[0] = (f\"the Hornresp S5 from the volume S4-S5 would be {area['S5']:.0f} (<= 0); \"\n                             f\"the chamber volume is too large for this S4\")\n        return None\n    s3 = state[\"s3\"]\n    if s3 is None or s3 >= s_s4 - 1e-9:           # S3 must lie before S4\n        return None\n    # --- Driver centre -> D1, volume check, inertance ----------------------------------------------\n    d1_bottom = _dist(U2, Ls)\n    d1_top = _dist(U4, Lu)\n    prof = [(0.0, S1_real), (cum[1], area[\"S2\"])]\n    for i, G in enumerate(bend_geo):\n        prof.append((cum[2 + 2 * i] - G[\"parts\"][0], b1 * G[\"w1\"]))\n        prof.append((cum[3 + 2 * i] + G[\"parts\"][2], b1 * G[\"w2\"]))\n    prof += [(cum[-1], S5_real)]\n    if not s4_in_bend:\n        prof.append((s4_cum, area[\"S4\"]))\n    prof.sort()\n    vol_path = sum((s2_ - s1_) * (A1_ + A2_) / 2 for (s1_, A1_), (s2_, A2_) in zip(prof[:-1], prof[1:]))\n    inertia = integrate_inertia(prof)\n    # The mouth opening passes through the front wall: S5 is at x=0, while the\n    # internal box volume starts at x=xl=a. Include this wall-thickness aperture\n    # in both the drawn air volume and the numerical air-volume balance.\n    mouth_poly = [Lu0, Lu, Ld_l, Ld0]\n    vol_mouth = _poly_area(mouth_poly) * b1\n    air_area = ((xr - xl) * (zc - a)\n               - sum(_poly_area(pg) for pg in (poly_a, poly_b, poly_c, poly_d)))\n    vol_air = air_area * b1 + vol_mouth\n    ratio = [(nm, max(G[\"w1\"], G[\"w2\"]) / min(G[\"w1\"], G[\"w2\"])) for nm, G in zip(BEND_NAMES, bend_geo)]\n    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,\n            \"Pd\": Pd, \"dd\": dd, \"n_ab\": n_ab, \"ab\": ab, \"psi\": psi, \"alpha_d\": alpha_d, \"ex\": ex, \"en\": en,\n            \"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,\n            \"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,\n            \"path_pts\": ([S1c, Kc] + pts[1:]) if kink else pts, \"cum\": cum, \"s_s4\": s_s4, \"s4_cum\": s4_cum,\n            \"s4_in_bend\": s4_in_bend, \"S4_drawing\": S4_drawing, \"S4_fan\": S4_fan, \"v45_actual\": v45, \"d1\": (d1_bottom, d1_top),\n            \"vol_path\": vol_path, \"vol_air\": vol_air, \"vol_mouth\": vol_mouth, \"mouth_poly\": mouth_poly,\n            \"inertia\": inertia, \"ratios\": ratio,\n            \"w_max\": max(max(G[\"w1\"], G[\"w2\"]) for G in bend_geo), \"C4\": C4, \"C3\": C3, \"C2\": C2, \"C1\": C1}\n\n\nBEND_NAMES = (\"Bend 1 (bottom right)\", \"Bend 2 (top right)\", \"Bend 3 (top left)\",\n               \"Bend 4 (left, into d)\", \"Bend 5 (right, downwards)\", \"Bend 6 (into the chamber)\")\n\n\ndef compute(P, k, b_after):\n    \"\"\"Results for S3 position k and slope b' = b_after (dict) or FoldingError.\"\"\"\n    try:\n        geo = build(P, k, b_after)\n    except (ZeroDivisionError, ValueError, OverflowError) as err:\n        raise FoldingError(f\"Geometry cannot be calculated ({err}).\")\n    if geo is None:\n        raise FoldingError(f\"For S3 position {k} and b' = {b_after:.4f} the fold path does not fit in the box \"\n                             f\"(a bend cannot be closed with the width law).\" + (f\" Last reason: {_REJECTION[0]}\" if _REJECTION[0] else \"\"))\n    b1, fl, cum = P[\"b1\"], geo[\"area\"], geo[\"cum\"]\n    path_s1_s2 = cum[1]\n    s_s4 = geo[\"s_s4\"]\n    path_s4_s5 = cum[-1] - geo[\"s4_cum\"]\n    l23 = geo[\"s3\"]\n    path_s3_s4 = s_s4 - l23\n    total = path_s1_s2 + s_s4 + path_s4_s5\n    S3, S4 = fl[\"S3\"], fl[\"S4\"]\n    b_cone = (S4 - S3) / (b1 * path_s3_s4) if path_s3_s4 > 0 else float(\"nan\")\n    th = [G[\"theta\"] for G in geo[\"bend_geo\"]]\n    bends = [(nm, G[\"w1\"], G[\"w2\"], t_, G[\"parts\"]) for nm, G, t_ in zip(BEND_NAMES, geo[\"bend_geo\"], th)]\n    return {\"k\": k, \"b_after\": b_after, \"b_cone\": b_cone, \"s3\": l23, \"l23\": l23, \"S3\": S3, \"S4\": S4, \"S5\": fl[\"S5\"],\n            \"S2\": fl[\"S2\"], \"path_s1_s2\": path_s1_s2, \"path_s4_s5\": path_s4_s5, \"path_s3_s4\": path_s3_s4,\n            \"total\": total, \"bends\": bends, \"geo\": geo}\n\n\n\n\ndef shortfall(P, R):\n    \"\"\"Largest relative undershoot of the actual cone (fan in the bends, chords at bend ends) below the\n    idealised cone through the calculated S1-S5, in % (0 = nowhere below).\"\"\"\n    geo = R[\"geo\"]\n    kd = cone_data({\"b1\": P[\"b1\"], \"l23_new\": R[\"l23\"], \"unit\": UNIT, \"a\": P[\"a\"]}, geo)\n    worst = 0.0\n    tab = [(n, s_, A_) for n, s_, A_ in kd[\"points\"]]\n    for bg in kd[\"bends\"]:\n        tab += [(\"F\", s_, A_) for s_, A_, _ in bg[\"fans\"]]\n    for _, s_, A_ in tab:\n        ideal = kd[\"lin\"](kd[\"ideal\"], s_)\n        if ideal > 0:\n            worst = max(worst, (ideal - A_) / ideal * 100.0)\n    return worst\n\n\ndef solve_b_consistent(P, k):\n    \"\"\"b' such that the area S3 -> S4 grows uniformly with b': S4 = S3 + b1*b'*path(S3-S4).\n\n    Returns (b', number of solutions found); if there are several, the one closest to b is used.\n    Invalid geometries (FoldingError) count as a gap, not as a numerical value.\n    \"\"\"\n    b1 = P[\"b1\"]\n\n    def h(b_after):\n        try:\n            R = compute(P, k, b_after)\n        except FoldingError:\n            return float(\"nan\")\n        return R[\"S4\"] - R[\"S3\"] - b1 * b_after * R[\"path_s3_s4\"]\n    roots = find_roots(h, B_MIN, B_MAX, B_STEP)\n    if not roots:\n        margin = \"\"\n        h_lo, h_hi = h(B_MIN), h(B_MAX)\n        if math.isfinite(h_lo) and math.isfinite(h_hi):\n            margin = (f\" Difference S4 - (S3 + b1*b'*path) at the boundary: {h_lo:+.1f} at b' = {B_MIN:g}, \"\n                    f\"{h_hi:+.1f} at b' = {B_MAX:g} {UNIT}² (same sign: a solution outside \"\n                    f\"the search range is possible, but not certain).\")\n        else:\n            margin = (f\" At at least one boundary of the search range the geometry is invalid \"\n                    f\"(b' = {B_MIN:g}: {'valid' if math.isfinite(h_lo) else 'invalid'}, \"\n                    f\"b' = {B_MAX:g}: {'valid' if math.isfinite(h_hi) else 'invalid'}).\")\n        raise FoldingError(f\"For position {k} there is no slope in the range b' = {B_MIN:g} ... {B_MAX:g} \"\n                             f\"for which S4 fits the geometry (box too small or position \"\n                             f\"unsuitable). Specify b' manually if needed.\" + margin)\n    roots.sort(key=lambda w: abs(w - P[\"b\"]))\n    return roots[0], len(roots)\n\n\ndef _unit_vec(v):\n    l = math.hypot(v[0], v[1])\n    return (v[0] / l, v[1] / l)\n\n\ndef _intersect(P, u, Q, v):\n    \"\"\"Intersection point of the lines P+t*u and Q+s*v.\"\"\"\n    det = -u[0] * v[1] + u[1] * v[0]\n    if abs(det) < 1e-9 * math.hypot(*u) * math.hypot(*v):\n        raise ZeroDivisionError(\"Lines are parallel\")\n    t = (-(Q[0] - P[0]) * v[1] + (Q[1] - P[1]) * v[0]) / det\n    return (P[0] + t * u[0], P[1] + t * u[1])\n\n\ndef _midpoint(p, q):\n    return ((p[0] + q[0]) / 2, (p[1] + q[1]) / 2)\n\n\ndef _dist(p, q):\n    return math.hypot(p[0] - q[0], p[1] - q[1])\n\n\ndef _poly_area(pts):\n    \"\"\"Area of a polygon (Gauss's shoelace formula).\"\"\"\n    return abs(sum(p[0] * q[1] - q[0] * p[1] for p, q in zip(pts, pts[1:] + pts[:1]))) / 2.0\n\n\ndef _ray_path(C, r, pf):\n    \"\"\"Distance along the polyline pf from its first point to the first intersection with the ray C + t*r (t > 0);\n    None if the ray does not meet the polyline.\"\"\"\n    run = 0.0\n    for p_, q_ in zip(pf[:-1], pf[1:]):\n        d = (q_[0] - p_[0], q_[1] - p_[1])\n        det = -r[0] * d[1] + r[1] * d[0]\n        lg = math.hypot(*d)\n        if abs(det) > 1e-12 * math.hypot(*r) * lg:\n            w = (p_[0] - C[0], p_[1] - C[1])\n            t = (-w[0] * d[1] + w[1] * d[0]) / det\n            u = (r[0] * w[1] - r[1] * w[0]) / det\n            if t > 0 and -1e-9 <= u <= 1 + 1e-9:\n                return run + min(max(u, 0.0), 1.0) * lg\n        run += lg\n    return None\n\n\ndef _crossline(P, d1, Q, d2):\n    \"\"\"Cross-section of a straight channel section: from P (lies on wall 1, direction d1) perpendicular to the\n    centreline (= bisector of the two walls) to wall 2 (point Q, direction d2).\n    d1, d2: wall directions in flow direction. Returns: (P, foot point on wall 2).\"\"\"\n    ub = _unit_vec((d1[0] + d2[0], d1[1] + d2[1]))\n    n = (-ub[1], ub[0])\n    return P, _intersect(P, n, Q, d2)\n\n\ndef bend_hand(C, w_in, w_out, wall_in, wall_out):\n    \"\"\"Manual construction of a bend at the inner corner C.\n\n    w_in / w_out: two direction vectors each (in flow direction) of the two walls of the entry and\n    exit channel. wall_in / wall_out: the respective outer wall as (point, direction).\n    The centreline of each channel lies on the bisector of its two walls; the\n    cross-section is perpendicular to it and starts at C.\n    \"\"\"\n    uc_in = _unit_vec((w_in[0][0] + w_in[1][0], w_in[0][1] + w_in[1][1]))\n    uc_out = _unit_vec((w_out[0][0] + w_out[1][0], w_out[0][1] + w_out[1][1]))\n    P_ein = _intersect(C, (-uc_in[1], uc_in[0]), *wall_in)       # cross-section meets the outer wall\n    P_aus = _intersect(C, (-uc_out[1], uc_out[0]), *wall_out)\n    Q = _intersect(*wall_in, *wall_out)                            # outer corner of the bend\n    O1, O2 = _midpoint(P_ein, Q), _midpoint(P_aus, Q)\n    E0, X0 = _midpoint(C, P_ein), _midpoint(C, P_aus)                   # centres of the two cross-sections\n    A = _intersect(E0, uc_in, C, (O1[0] - C[0], O1[1] - C[1]))\n    B = _intersect(X0, uc_out, C, (O2[0] - C[0], O2[1] - C[1]))\n    return {\"C\": C, \"Ci\": P_ein, \"Cx\": P_aus, \"Q\": Q, \"O1\": O1, \"O2\": O2, \"A\": A, \"B\": B, \"E0\": E0, \"X0\": X0,\n            \"w1\": _dist(C, P_ein), \"w2\": _dist(C, P_aus), \"uc_in\": uc_in, \"uc_out\": uc_out,\n            \"parts\": (_dist(E0, A), _dist(A, B), _dist(B, X0))}\n\n\ndef bend_sign_ok(G):\n    \"\"\"True if the hand construction runs forward: E0 -> A along the entry direction and B -> X0 along the exit direction.\n    A part with the wrong direction would still be added as a positive length (parts are distances), i.e. the path would be wrong.\n    Occurs only for strongly widening bends with sharp turns (checked: not in the 34 regression cases).\"\"\"\n    sa = (G[\"A\"][0] - G[\"E0\"][0]) * G[\"uc_in\"][0] + (G[\"A\"][1] - G[\"E0\"][1]) * G[\"uc_in\"][1]\n    sb = (G[\"X0\"][0] - G[\"B\"][0]) * G[\"uc_out\"][0] + (G[\"X0\"][1] - G[\"B\"][1]) * G[\"uc_out\"][1]\n    return sa >= -1e-6 and sb >= -1e-6\n\n\n# ---------------------------------------------------------------------------\n# Unrolled horn cones (evaluation of the drawing geometry, does not change the calculation)\n#   a) Specification: input / Hornresp values with imported Con/Par law (g[\"ref\"])\n#   b) Idealised:     calculated S1-S5 at the centreline distances of the drawing, linear in between\n#   c) Actual:        length of the cross-section line x b1 at the cross-sections of the construction\n#                     (straight board sections: exactly linear; bends: only entry/exit known, in between\n#                     NO unambiguous cross-section -> dotted and shaded grey/red)\n# ---------------------------------------------------------------------------\ndef _fan_profile(G, step, s_e, b1):\n    \"\"\"Cross-section profile in the bend: straight line from the inner corner C through the point of the bend path (E0-A-B-X0)\n    at path s to the outer boundary (entry wall to outer corner Q, then exit wall).\n    Returns: list of (total path, area, path within bend).\"\"\"\n    C, Pe, Pa = G[\"C\"], G[\"Ci\"], G[\"Cx\"]\n    Q = (2 * G[\"O1\"][0] - Pe[0], 2 * G[\"O1\"][1] - Pe[1])\n    pf = [G[\"E0\"], G[\"A\"], G[\"B\"], G[\"X0\"]]\n    lg = [math.hypot(q[0] - p[0], q[1] - p[1]) for p, q in zip(pf[:-1], pf[1:])]\n    total = sum(lg)\n    ss = [i * step for i in range(int(total // step) + 1)] + [lg[0], lg[0] + lg[1], total]\n    # additional sample where the ray points at the outer corner Q (peak of the cross-section)\n    rq = (Q[0] - C[0], Q[1] - C[1])\n    rest = 0.0\n    for p_, q_, l_ in zip(pf[:-1], pf[1:], lg):\n        ex_, ey_ = q_[0] - p_[0], q_[1] - p_[1]\n        det = rq[0] * (-ey_) - rq[1] * (-ex_)\n        if abs(det) > 1e-12:\n            rx, ry = p_[0] - C[0], p_[1] - C[1]\n            t_ = (rx * (-ey_) - ry * (-ex_)) / det\n            u_ = (rq[0] * ry - rq[1] * rx) / det\n            if t_ > 0 and 0 <= u_ <= 1:\n                ss.append(rest + u_ * l_)\n        rest += l_\n    ss = sorted(set(round(v, 9) for v in ss if 0 <= v <= total))\n\n    def point(sv):\n        rest = sv\n        for p, q, l_ in zip(pf[:-1], pf[1:], lg):\n            if rest <= l_ + 1e-12:\n                f = rest / l_ if l_ > 0 else 0.0\n                return (p[0] + f * (q[0] - p[0]), p[1] + f * (q[1] - p[1]))\n            rest -= l_\n        return pf[-1]\n\n    def hits(v):\n        best = None\n        for X_, Y_ in ((Pe, Q), (Q, Pa)):\n            ex_, ey_ = Y_[0] - X_[0], Y_[1] - X_[1]\n            det = v[0] * (-ey_) - v[1] * (-ex_)\n            if abs(det) < 1e-12:\n                continue\n            rx, ry = X_[0] - C[0], X_[1] - C[1]\n            t = (rx * (-ey_) - ry * (-ex_)) / det\n            u_ = (v[0] * ry - v[1] * rx) / det\n            if t > 0 and -1e-9 <= u_ <= 1 + 1e-9 and (best is None or t < best):\n                best = t\n        return best\n    res = []\n    for sv in ss:\n        P_ = point(sv)\n        v = (P_[0] - C[0], P_[1] - C[1])\n        t = hits(v)\n        if t is None:\n            res.append(None)                           # no reliable intersection: gap instead of value\n            continue\n        res.append((s_e + sv, t * math.hypot(*v) * b1, sv))\n    return res\n\n\ndef cone_data(g, geo):\n    \"\"\"Computes the sample points of the three cones. Returns: dict (s = path along the centreline).\"\"\"\n    bend_geo, b1 = geo[\"bend_geo\"], g[\"b1\"]\n    cum = geo[\"cum\"]\n    s_s2, s_s4, s_s5 = cum[1], geo[\"s4_cum\"], cum[-1]\n    bends = []\n    for i, G in enumerate(bend_geo):\n        s_e = cum[2 + 2 * i] - G[\"parts\"][0]\n        s_x = cum[3 + 2 * i] + G[\"parts\"][2]\n        w1, w2 = G[\"w1\"], G[\"w2\"]\n        bends.append({\"nr\": i + 1, \"s_e\": s_e, \"s_x\": s_x, \"A_e\": w1 * b1, \"A_x\": w2 * b1,\n                       \"ratio\": max(w1, w2) / min(w1, w2) if min(w1, w2) > 0 else float(\"inf\")})\n    s_s3 = s_s2 + g[\"l23_new\"]\n    actual_h = {\"S1\": (0.0, geo[\"area\"][\"S1\"]), \"S2\": (s_s2, geo[\"area\"][\"S2\"]), \"S3\": (s_s3, geo[\"area\"][\"S3\"]),\n             \"S4\": (s_s4, geo[\"area\"][\"S4\"]), \"S5\": (s_s5, geo[\"area\"][\"S5\"])}      # Hornresp values\n    actual = dict(actual_h)                                                                  # built (actual) values\n    # Equivalent areas for Hornresp are not necessarily the built cross-sections.\n    # This also holds without a kink (S5 correction) and for S4 inside bend 6.\n    actual[\"S1\"] = (0.0, geo[\"S1_real\"])\n    actual[\"S5\"] = (s_s5, geo[\"S5_real\"])\n    if geo[\"s4_in_bend\"]:\n        actual[\"S4\"] = (s_s4, geo[\"S4_fan\"])\n    extra = []\n    if geo[\"kink\"]:\n        # actual cone: built S1 and S5 (set above), plus the kink as a support point; the idealised cone keeps the Hornresp values\n        a_, K, Ls, ex = g[\"a\"], geo[\"K\"], geo[\"Ls\"], geo[\"ex\"]\n        s_k = _dist((Ls[0], a_ + (Ls[1] - a_) / 2), (K[0], a_ + (K[1] - a_) / 2))\n        e_k = _unit_vec((K[0] - Ls[0], K[1] - Ls[1]))\n        m_ = _unit_vec((e_k[0] + ex[0], e_k[1] + ex[1]))                              # mean direction of the underside at K\n        t_ = _unit_vec((1.0 + m_[0], m_[1]))                                          # bisector of floor and underside\n        extra = [(\"K\", s_k, (K[1] - a_) / abs(t_[0]) * b1)]                          # chord perpendicular to it, K to floor\n    step_len = 1.0 if g[\"unit\"] == \"cm\" else 10.0               # step size 1 cm (or 10 mm) of bend path\n    for bg, G in zip(bends, bend_geo):\n        raw_f = _fan_profile(G, step_len, bg[\"s_e\"], b1)\n        bg[\"fans\"] = [q_ for q_ in raw_f if q_ is not None]\n        bg[\"fan_pieces\"], cur = [], []            # contiguous pieces\n        bg[\"fan_gaps\"] = 0                        # number of runs without a reliable fan point\n        prev_none = False\n        for q_ in raw_f:\n            if q_ is None and not prev_none:\n                bg[\"fan_gaps\"] += 1\n            prev_none = q_ is None\n            if q_ is None:\n                if cur:\n                    bg[\"fan_pieces\"].append(cur)\n                cur = []\n            else:\n                cur.append(q_)\n        if cur:\n            bg[\"fan_pieces\"].append(cur)\n    pkt = [(\"S1\",) + actual[\"S1\"], (\"S2\",) + actual[\"S2\"], (\"S3\",) + actual[\"S3\"], (\"S4\",) + actual[\"S4\"], (\"S5\",) + actual[\"S5\"]] + extra\n    for bg in bends:\n        pkt.append((f\"E{bg['nr']}\", bg[\"s_e\"], bg[\"A_e\"]))\n        pkt.append((f\"X{bg['nr']}\", bg[\"s_x\"], bg[\"A_x\"]))\n    pkt.sort(key=lambda t: (t[1], t[0]))\n\n    def in_bend(s):\n        for bg in bends:\n            if bg[\"s_e\"] + 1e-9 < s < bg[\"s_x\"] - 1e-9:\n                return bg\n        return None\n    segments = []\n    for p_, q_ in zip(pkt[:-1], pkt[1:]):\n        if q_[1] - p_[1] < 1e-9:\n            continue\n        bg = in_bend((p_[1] + q_[1]) / 2)\n        segments.append({\"s0\": p_[1], \"A0\": p_[2], \"s1\": q_[1], \"A1\": q_[2], \"bend\": bg[\"nr\"] if bg else None,\n                         \"uncertain\": bool(bg and bg[\"ratio\"] > RATIO_WARN)})\n    # idealised: calculated S1..S5 at the drawn stations\n    ideal = [actual_h[n] for n in (\"S1\", \"S2\", \"S3\", \"S4\", \"S5\")]\n    ideal.sort()\n    ref = g.get(\"ref\")\n    ref_pts = None\n    ref_stations = None\n    if ref:\n        s = 0.0\n        ref_pts = [(0.0, ref[\"S1\"])]\n        ref_stations = list(ref_pts)\n        flares = ref.get(\"flares\", (\"Par\",) * 4)\n        for i, (nm, ln, fl) in enumerate(((\"S2\", ref[\"L12\"], ref[\"S2\"]), (\"S3\", ref[\"L23\"], ref[\"S3\"]),\n                                         (\"S4\", ref[\"L34\"], ref[\"S4\"]), (\"S5\", ref[\"L45\"], ref[\"S5\"]))):\n            # Con: sqrt(area) linear; Par: area itself linear.\n            if flares[i] == \"Con\":\n                start = math.sqrt(ref_pts[-1][1])\n                end = math.sqrt(fl)\n                for j in range(1, 40):\n                    t = j / 40\n                    ref_pts.append((s + ln * t, (start + (end - start) * t) ** 2))\n            s += ln\n            ref_pts.append((s, fl))\n            ref_stations.append((s, fl))\n\n    def lin(tab, s):\n        if s <= tab[0][0]:\n            return tab[0][1]\n        for (s0, A0), (s1, A1) in zip(tab[:-1], tab[1:]):\n            if s0 <= s <= s1:\n                return A0 + (A1 - A0) * (s - s0) / (s1 - s0) if s1 > s0 else A0\n        return tab[-1][1]\n    deviation = [(nm, s, A, A - lin(ideal, s), (A / lin(ideal, s) - 1) * 100 if lin(ideal, s) else float(\"nan\"))\n           for nm, s, A in pkt]\n    for bg in bends:                                  # all fan samples enter the deviation as well\n        for s_, A_, _ in bg[\"fans\"]:\n            i_ = lin(ideal, s_)\n            deviation.append((\"F\", s_, A_, A_ - i_, (A_ / i_ - 1) * 100 if i_ else float(\"nan\")))\n    deviation.sort(key=lambda t: t[1])\n    return {\"stations\": actual, \"points\": pkt, \"segments\": segments, \"bends\": bends, \"ideal\": ideal,\n            \"ref\": ref_pts, \"ref_stations\": ref_stations, \"deviation\": deviation, \"lin\": lin}\n\n\ndef cone_svg(kd, x0, y0, width, u):\n    \"\"\"SVG fragments of the cone plot (space: width x approx. 560 px from (x0, y0)). Returns (list, height).\"\"\"\n    out = []\n    ml, mr = 70, 30\n    pw = width - ml - mr\n    top, h1_, gap, h2_ = 50, 330, 70, 120\n    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\n    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 [])]\n    a_max = max(allA) * 1.08\n    a_min = 0.0\n    ds = [t[4] for t in kd[\"deviation\"] if math.isfinite(t[4])]\n    d_lim = max(1.0, math.ceil(max(abs(v) for v in ds) * 1.1)) if ds else 1.0\n\n    def sx(s): return x0 + ml + s / s_max * pw\n    def sy(A): return y0 + top + h1_ - (A - a_min) / (a_max - a_min) * h1_\n    def dy(p): return y0 + top + h1_ + gap + h2_ / 2 - p / d_lim * h2_ / 2\n\n    def step(m, n=8):\n        raw = m / n\n        e = 10 ** math.floor(math.log10(raw))\n        for f in (1, 2, 2.5, 5, 10):\n            if raw <= f * e:\n                return f * e\n        return 10 * e\n    out.append(f'<text x=\"{x0 + ml}\" y=\"{y0 + 18}\" style=\"font:bold 15px sans-serif;fill:#222\">'\n               f'Unfolded horn profile: cross-sectional area over the path along the centreline</text>')\n    # bend regions\n    # grid and axes\n    st = step(a_max - a_min)\n    v = 0.0\n    while v <= a_max:\n        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\"/>')\n        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>')\n        v += st\n    st = step(s_max, 10)\n    v = 0.0\n    while v <= s_max:\n        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\"/>')\n        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>')\n        v += st\n    out.append(f'<rect x=\"{x0 + ml}\" y=\"{y0 + top}\" width=\"{pw}\" height=\"{h1_}\" fill=\"none\" stroke=\"#333\"/>')\n    out.append(f'<text x=\"{x0 + ml + pw / 2}\" y=\"{y0 + top + h1_ + 30}\" style=\"font:11px sans-serif;fill:#333;text-anchor:middle\">'\n               f'Path s along the centreline [{u}]</text>')\n    out.append(f'<text transform=\"translate({x0 + 14},{y0 + top + h1_ / 2}) rotate(-90)\" '\n               f'style=\"font:11px sans-serif;fill:#333;text-anchor:middle\">Area [{u}²]</text>')\n    # a) reference\n    if kd[\"ref\"]:\n        out.append('<polyline fill=\"none\" stroke=\"#0b5ed7\" stroke-width=\"2\" stroke-dasharray=\"8 4\" points=\"'\n                   + \" \".join(f\"{sx(s):.1f},{sy(A):.1f}\" for s, A in kd[\"ref\"]) + '\"/>')\n        for s, A in kd.get(\"ref_stations\") or kd[\"ref\"]:\n            out.append(f'<circle cx=\"{sx(s):.1f}\" cy=\"{sy(A):.1f}\" r=\"3.5\" fill=\"#fff\" stroke=\"#0b5ed7\" stroke-width=\"1.5\"/>')\n    # b) idealised\n    out.append('<polyline fill=\"none\" stroke=\"#2e8b57\" stroke-width=\"2\" points=\"'\n               + \" \".join(f\"{sx(s):.1f},{sy(A):.1f}\" for s, A in kd[\"ideal\"]) + '\"/>')\n    # c) actual\n    for sg in kd[\"segments\"]:\n        if sg[\"bend\"] is None:\n            out.append(f'<line x1=\"{sx(sg[\"s0\"]):.1f}\" y1=\"{sy(sg[\"A0\"]):.1f}\" x2=\"{sx(sg[\"s1\"]):.1f}\" y2=\"{sy(sg[\"A1\"]):.1f}\" '\n                       f'stroke=\"#c0392b\" stroke-width=\"2.6\"/>')\n    for bg in kd[\"bends\"]:            # bend: fan around the inner corner, one value per path step\n        for piece in bg[\"fan_pieces\"]:\n            if len(piece) > 1:\n                out.append('<polyline fill=\"none\" stroke=\"#c0392b\" stroke-width=\"2.2\" points=\"'\n                           + \" \".join(f\"{sx(s_):.1f},{sy(A_):.1f}\" for s_, A_, _ in piece) + '\"/>')\n    for nm, s, A in kd[\"points\"]:\n        if nm[0] in \"EX\":\n            out.append(f'<circle cx=\"{sx(s):.1f}\" cy=\"{sy(A):.1f}\" r=\"2\" fill=\"#c0392b\"/>')\n    # stations\n    for nm, (s, A) in kd[\"stations\"].items():\n        out.append(f'<line x1=\"{sx(s):.1f}\" y1=\"{y0 + top - 8}\" x2=\"{sx(s):.1f}\" y2=\"{y0 + top + h1_}\" '\n                   f'stroke=\"#7b2cbf\" stroke-width=\"1\" stroke-dasharray=\"5 3\"/>')\n        out.append(f'<circle cx=\"{sx(s):.1f}\" cy=\"{sy(A):.1f}\" r=\"4.2\" fill=\"#c0392b\" stroke=\"#fff\"/>')\n        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>')\n    # legend\n    lx, ly = x0 + ml + 10, y0 + top + 14\n    leg = [(\"#0b5ed7\", \"8 4\", 2, \"a) Reference (input / Hornresp)\"),\n           (\"#2e8b57\", \"\", 2, \"b) Linear-area model / Par (calculated S1-S5, path from drawing)\"),\n           (\"#c0392b\", \"\", 2.6, \"c) Actual: straight sections ⟂ centreline, bends as fan around the inner corner (1 path step each)\")]\n    for i, (col, da, sw, txt) in enumerate(leg):\n        yy = ly + i * 15\n        out.append(f'<line x1=\"{lx}\" y1=\"{yy}\" x2=\"{lx + 30}\" y2=\"{yy}\" stroke=\"{col}\" stroke-width=\"{sw}\"'\n                   + (f' stroke-dasharray=\"{da}\"' if da else '') + '/>')\n        out.append(f'<text x=\"{lx + 36}\" y=\"{yy + 4}\" style=\"font:10px sans-serif;fill:#333\">{txt}</text>')\n    # deviation actual - ideal\n    out.append(f'<text x=\"{x0 + ml}\" y=\"{y0 + top + h1_ + gap - 14}\" style=\"font:bold 12px sans-serif;fill:#222\">'\n               f'Deviation of actual (c) from idealised (b): stations, bend entries/exits and every fan sample [%]</text>')\n    out.append(f'<rect x=\"{x0 + ml}\" y=\"{dy(d_lim):.1f}\" width=\"{pw}\" height=\"{h2_}\" fill=\"none\" stroke=\"#333\"/>')\n    for p in (-d_lim, 0, d_lim):\n        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\"/>')\n        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>')\n    for bg in kd[\"bends\"]:                           # fan samples: continuous line per piece (gaps stay open)\n        for piece in bg[\"fan_pieces\"]:\n            pts_ = [(s_, kd[\"lin\"](kd[\"ideal\"], s_)) for s_, A_, _ in piece]\n            dev = [(s_, (A_ / i_ - 1) * 100) for (s_, A_, _), (_, i_) in zip(piece, pts_) if i_]\n            if len(dev) > 1:\n                out.append('<polyline fill=\"none\" stroke=\"#c0392b\" stroke-width=\"1.4\" points=\"'\n                           + \" \".join(f\"{sx(s_):.1f},{dy(d_):.1f}\" for s_, d_ in dev) + '\"/>')\n    for nm, s, A, da_, dp in kd[\"deviation\"]:\n        if not math.isfinite(dp) or nm == \"F\":\n            continue\n        col = \"#c0392b\" if nm[0] == \"S\" else \"#888\"\n        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\"/>')\n        out.append(f'<circle cx=\"{sx(s):.1f}\" cy=\"{dy(dp):.1f}\" r=\"2.8\" fill=\"{col}\"/>')\n        if nm[0] == \"S\":\n            yy = dy(dp) - 6 if dp >= 0 else dy(dp) + 14\n            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>')\n    h = top + h1_ + gap + h2_ + 30\n    return out, h\n\n\n\ndef _inner_angle(p, q, r):\n    \"\"\"Interior angle at corner q between the edges q->p and q->r, in degrees (90 = square cut).\"\"\"\n    v1, v2 = (p[0] - q[0], p[1] - q[1]), (r[0] - q[0], r[1] - q[1])\n    c = (v1[0] * v2[0] + v1[1] * v2[1]) / (math.hypot(*v1) * math.hypot(*v2))\n    return math.degrees(math.acos(max(-1.0, min(1.0, c))))\n\n\ndef _fmt_cut(entry):\n    \"\"\"Text for the cut list: gross length, long face, end angles (90 = square).\"\"\"\n    lab, name, length, w_, d_, n_, a1, a2, area = entry\n    ang = \"square ends\" if abs(a1 - 90) < 0.05 and abs(a2 - 90) < 0.05 else f\"end angles {a1:.1f} / {a2:.1f} deg\"\n    side = f\" (long face: {area})\" if area and ang != \"square ends\" else \"\"\n    return f\"{length:.1f} x {w_:.1f} x {d_:g}  {ang}{side}\" + (f\"  x{n_}\" if n_ > 1 else \"\")\n\n\ndef draw_svg(g, filename=\"horn_folding.svg\"):\n    \"\"\"Draws the construction (from g['geo']) as SVG and returns (checks, cutlist, geo).\"\"\"\n    geo = g[\"geo\"]\n    u = g[\"unit\"]\n    a, T, H, b1 = g[\"a\"], g[\"T\"], g[\"H\"], g[\"b1\"]\n    xl, xr, zc = a, T - a, H - a\n    G, Cs, poly_ = geo[\"bend_geo\"], geo[\"C\"], geo[\"poly\"]\n    C1, C2, C3, C4, C5, C6 = Cs\n    en = geo[\"en\"]\n    Wi = g[\"Width\"] - 2 * a                       # inner width between the side panels\n    Ls, Lu, Ld_t, Ld_l = geo[\"Ls\"], geo[\"Lu\"], geo[\"Ld_t\"], geo[\"Ld_l\"]\n    Lu0, Ld0 = geo[\"Lu0\"], geo[\"Ld0\"]\n    section, fl = geo[\"section\"], geo[\"area\"]\n\n    # --- Cut list (length top / bottom for angled ends) -----------------------------------------\n    a_up_r = _add(C1, en, a)                          # top right corner of board a\n\n    def cut_quad(q0, q1, q2, q3):\n        \"\"\"Cut data of a board with the corners q0 (lower left), q1 (lower right), q2 (upper right), q3 (upper left).\"\"\"\n        low, up = _dist(q0, q1), _dist(q3, q2)\n        if low >= up:\n            return (low, _inner_angle(q1, q0, q3), _inner_angle(q0, q1, q2), \"lower\")\n        return (up, _inner_angle(q2, q3, q0), _inner_angle(q3, q2, q1), \"upper\")\n    if geo[\"kink\"]:\n        cut_a1 = cut_quad(Ls, geo[\"K\"], geo[\"K_up\"], Lu)\n        cut_a = cut_quad(geo[\"K\"], C1, a_up_r, geo[\"K_up\"])          # a2 (driver board)\n    else:\n        a_low_len, a_up_len = _dist(Ls, C1), _dist(Lu, a_up_r)\n        if a_low_len >= a_up_len:                          # gross length = longest face\n            cut_a = (a_low_len, _inner_angle(C1, Ls, Lu), _inner_angle(Ls, C1, a_up_r), \"lower\")\n        else:\n            cut_a = (a_up_len, _inner_angle(a_up_r, Lu, Ls), _inner_angle(Lu, a_up_r, C1), \"upper\")\n    c_low_r = _add(C2, en, -a)\n    top_c, bot_c = _dist(C2, C3), _dist(c_low_r, C4)\n    if top_c >= bot_c:\n        cut_c = (top_c, _inner_angle(C2, C3, C4), _inner_angle(C3, C2, c_low_r), \"top\")\n    else:\n        cut_c = (bot_c, _inner_angle(c_low_r, C4, C3), _inner_angle(C4, c_low_r, C2), \"bottom\")\n    top_d, bot_d = _dist(Ld_t, C5), _dist(Ld_l, C6)\n    if top_d >= bot_d:\n        cut_d = (top_d, _inner_angle(C5, Ld_t, Ld_l), _inner_angle(Ld_t, C5, C6), \"top\")\n    else:\n        cut_d = (bot_d, _inner_angle(C6, Ld_l, Ld_t), _inner_angle(Ld_l, C6, C5), \"bottom\")\n    # D1 / D2: vertical boards; the top edge of D1 and the bottom edge of D2 are bevelled to continue the slopes of a / d\n    cut_d1 = cut_quad((0.0, a), Lu0, Lu, (xl, a))\n    cut_d2 = cut_quad(Ld0, (0.0, zc), (xl, zc), Ld_l)\n    side_ = {\"lower\": \"outer\", \"upper\": \"inner\"}\n    cutlist = [\n        *([(\"a1\", \"Baffle, mouth part\", cut_a1[0], Wi, a, 1, cut_a1[1], cut_a1[2], cut_a1[3])] if geo[\"kink\"] else []),\n        (\"a2\" if geo[\"kink\"] else \"a\", \"Baffle (driver)\", cut_a[0], Wi, a, 1, cut_a[1], cut_a[2], cut_a[3]),\n        (\"b\", \"Angled right wall\", _dist(C1, C2) - 2 * a, Wi, a, 1, 90.0, 90.0, \"\"),\n        (\"c\", \"Upper intermediate board\", cut_c[0], Wi, a, 1, cut_c[1], cut_c[2], cut_c[3]),\n        (\"d\", \"Lower intermediate board\", cut_d[0], Wi, a, 1, cut_d[1], cut_d[2], cut_d[3]),\n        (\"A\", \"Floor\", T, Wi, a, 1, 90.0, 90.0, \"\"),\n        (\"B\", \"Right wall\", H - 2 * a, Wi, a, 1, 90.0, 90.0, \"\"),\n        (\"C\", \"Ceiling\", T, Wi, a, 1, 90.0, 90.0, \"\"),\n        (\"D1\", \"Left wall, lower\", cut_d1[0], Wi, a, 1, cut_d1[1], cut_d1[2], side_[cut_d1[3]]),\n        (\"D2\", \"Left wall, upper\", cut_d2[0], Wi, a, 1, cut_d2[1], cut_d2[2], side_[cut_d2[3]]),\n        (\"E/F\", \"Side panels\", T, H, a, 2, 90.0, 90.0, \"\"),\n    ]\n    checks = {\"S2 area: drawing - input\": fl[\"S2\"] - g[\"S2\"]}\n    for f in geo[\"folds\"]:\n        if not f.get(\"free_exit\"):\n            checks[f\"Bend {f['nr']} exit: width - law\"] = f[\"G\"][\"w2\"] - f[\"law_out\"]\n        checks[f\"Bend {f['nr']} entry: width - law\"] = f[\"G\"][\"w1\"] - f[\"law_in\"]\n\n    margin = 40\n    W = 1200\n    kk = (W - 2 * margin) / T                        # box drawing spans the full width; text below, profiles last\n    Hp = H * kk + 2 * margin\n\n    def X(x): return margin + x * kk\n    def Z(z): return margin + (H - z) * kk\n\n    def poly(points, css_class):\n        return f'<polygon class=\"{css_class}\" points=\"' + \" \".join(f\"{X(x):.2f},{Z(z):.2f}\" for x, z in points) + '\"/>'\n\n    parts = [poly([(xl, a), (xr, a), (xr, zc), (xl, zc)], \"luft\"),\n             poly(geo[\"mouth_poly\"], \"luft\"),                 # mouth opening through the front wall\n             poly([(0, 0), (T, 0), (T, a), (0, a)], \"holz\"),                               # A\n             poly([(0, H - a), (T, H - a), (T, H), (0, H)], \"holz\"),                       # C\n             poly([(T - a, a), (T, a), (T, H - a), (T - a, H - a)], \"holz\"),               # B\n             poly([(0, a), (a, a), Lu, Lu0], \"holz\"),                                         # D1\n             poly([Ld0, Ld_l, (a, H - a), (0, H - a)], \"holz\")]                            # D2\n    poly_z = dict(poly_)                                  # boards as drawn (a is split at the kink)\n    if geo[\"kink\"]:\n        del poly_z[\"a\"]\n        poly_z[\"a1\"] = [Ls, geo[\"K\"], geo[\"K_up\"], Lu]\n        poly_z[\"a2\"] = [geo[\"K\"], C1, _add(C1, en, a), geo[\"K_up\"]]\n    for nm_ in poly_z:\n        parts.append(poly(poly_z[nm_], \"holz\"))\n    if geo[\"kink\"]:                                                        # joint between a1 and a2\n        parts.append(f'<line x1=\"{X(geo[\"K\"][0]):.1f}\" y1=\"{Z(geo[\"K\"][1]):.1f}\" x2=\"{X(geo[\"K_up\"][0]):.1f}\" '\n                     f'y2=\"{Z(geo[\"K_up\"][1]):.1f}\" stroke=\"#7a5a2e\" stroke-width=\"1\"/>')\n    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()}\n    marks_b.update({\"A\": (T / 2, a / 2), \"B\": (T - a / 2, H / 2), \"C\": (T / 2, H - a / 2),\n                     \"D1\": (a / 2, (a + Lu[1]) / 2), \"D2\": (a / 2, (Ld_l[1] + H - a) / 2)})\n    for nm_, (x, z) in marks_b.items():\n        parts.append(f'<text class=\"bl\" x=\"{X(x):.1f}\" y=\"{Z(z) + 4:.1f}\">{nm_}</text>')\n\n    # --- Bends: auxiliary lines ------------------------------------------------------------------------\n    for idx, Gb in enumerate(G, 1):\n        def ln(p_, q, kl):\n            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}\"/>')\n        ln(Gb[\"C\"], Gb[\"Ci\"], \"sek\")\n        ln(Gb[\"C\"], Gb[\"Cx\"], \"sek\")\n        ln(Gb[\"C\"], Gb[\"O1\"], \"faecher\")\n        ln(Gb[\"C\"], Gb[\"O2\"], \"faecher\")\n        for n_ in (\"O1\", \"O2\"):\n            parts.append(f'<circle class=\"po\" cx=\"{X(Gb[n_][0]):.1f}\" cy=\"{Z(Gb[n_][1]):.1f}\" r=\"2.5\"/>')\n        parts.append(f'<circle class=\"pc\" cx=\"{X(Gb[\"C\"][0]):.1f}\" cy=\"{Z(Gb[\"C\"][1]):.1f}\" r=\"3.5\"/>')\n        parts.append(f'<text class=\"lbc\" x=\"{X(Gb[\"C\"][0]) - 4:.1f}\" y=\"{Z(Gb[\"C\"][1]) - 6:.1f}\">C{idx}</text>')\n    pts = geo[\"path_pts\"]\n    parts.append('<polyline class=\"weg\" points=\"' + \" \".join(f\"{X(x):.1f},{Z(z):.1f}\" for x, z in pts) + '\"/>')\n    for idx, Gb in enumerate(G, 1):\n        for n_ in (\"A\", \"B\"):\n            parts.append(f'<circle class=\"pa\" cx=\"{X(Gb[n_][0]):.1f}\" cy=\"{Z(Gb[n_][1]):.1f}\" r=\"3.2\"/>')\n            parts.append(f'<text class=\"lbr\" x=\"{X(Gb[n_][0]) + 4:.1f}\" y=\"{Z(Gb[n_][1]) + 12:.1f}\">{n_}{idx}</text>')\n    pp = [(X(x), Z(z)) for x, z in pts]\n    for (x0, y0), (x1_, y1_) in zip(pp[:-1], pp[1:]):\n        L = math.hypot(x1_ - x0, y1_ - y0)\n        if L < 6 * kk:\n            continue\n        mx, my = (x0 + x1_) / 2, (y0 + y1_) / 2\n        dx, dy = (x1_ - x0) / L, (y1_ - y0) / L\n        sp = (mx + dx * 7, my + dy * 7)\n        l_ = (mx - dx * 5 - dy * 5, my - dy * 5 + dx * 5)\n        r_ = (mx - dx * 5 + dy * 5, my - dy * 5 - dx * 5)\n        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}\"/>')\n    foot = section[\"S4\"][1]\n    section = dict(section)\n    section[\"S4\"] = geo[\"S4_drawing\"]               # drawn line (in bend 6: length = calculated cross-section)\n    if C6[0] < foot[0] and not geo[\"s4_in_bend\"]:                      # d is shorter than the S4 line: imaginary extension\n        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}\"/>')\n    for name, (p_, q) in section.items():\n        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}\"/>')\n    for name, (p_, q) in section.items():\n        x, z = (p_[0] + q[0]) / 2, (p_[1] + q[1]) / 2\n        parts.append(f'<circle class=\"marke\" cx=\"{X(x):.1f}\" cy=\"{Z(z):.1f}\" r=\"9\"/>')\n        parts.append(f'<text class=\"mt\" x=\"{X(x):.1f}\" y=\"{Z(z) + 4:.1f}\">{name}</text>')\n\n    # --- Info column ----------------------------------------------------------------------------------\n    d1_bottom, d1_top = geo[\"d1\"]\n    lines = [\n        (\"t\", \"Hornfolding - section (side view)\"),\n        (\"n\", f\"Lengths in {u}, areas in {u}², 1 {u} = {kk:.1f} px\"),\n        (\"n\", f\"Outside {T:g} x {H:g} {u} (depth x height), wood {a:g} {u}\"),\n        (\"n\", f\"Width law W(s) = {g['W2']:.3f} + {g['b']:.5f} s (s = path from S2), channel width b1 = {b1:.2f} {u}\"),\n        (\"n\", f\"Board a in two parts a1/a2 (kink {geo['t_kink']:.1f} {u} from the driver centre; S1, S5 = Hornresp values)\"\n              if geo[\"kink\"] else\n              \"Board a runs straight through without a kink (Hornresp S1 from built volume)\"),\n        (\"n\", \"\"), (\"h\", \"Result\"),\n        (\"n\", f\"S1 = {geo['area']['S1']:.1f}     Path S1-S2 = {g['path_s1_s2']:.2f}\"),\n        (\"n\", f\"S2 = {g['S2']:.1f}     Path S2-S3 = {g['l23_new']:.2f}\"),\n        (\"n\", f\"S3 = {fl['S3']:.1f}     Path S3-S4 = {g['path_s3_s4']:.2f}\"),\n        (\"n\", f\"S4 = {fl['S4']:.1f}     Path S4-S5 = {g['path_s4_s5']:.2f}\"),\n        (\"n\", f\"S5 = {fl['S5']:.1f}\"),\n        *([(\"n\", f\"built (real): S1 = {geo['S1_real']:.1f},  S5 = {geo['S5_real']:.1f}\")] if geo[\"kink\"] else []),\n        (\"n\", \"\"), (\"h\", f\"Slopes (S3 at position {g['k']})\"),\n        (\"n\", f\"b  (S2-S3) = {g['b']:.5f}   area gradient b1*b  = {b1 * g['b']:.3f} {u}²/{u}\"),\n        (\"n\", f\"b' (S3-S4) = {g['b_after']:.5f}   area gradient b1*b' = {b1 * g['b_after']:.3f} {u}²/{u}\"),\n        (\"n\", \"b = width increase per path length; linear area = Hornresp Par, not Con\"),\n        (\"n\", \"\"), (\"h\", \"Construction check\"),\n    ]\n    for name, value in checks.items():\n        lines.append((\"n\", f\"{name}: {value:+.3f} {u + '²' if 'area' in name else u}\"))\n    if abs(g[\"S1\"] - geo[\"s1_same\"]) > 0.5:\n        lines.append((\"n\", f\"S1 = {g['S1']:.1f} deviates from the continuous slope ({geo['s1_same']:.1f})\"))\n        if not geo[\"kink\"]:\n            lines.append((\"n\", \"Without a kink the specified S1 has no effect: Hornresp S1 and S5 follow from the built volumes\"))\n    lines += [(\"n\", \"\"), (\"h\", \"Path segments per bend: straight + chord + straight\")]\n    for nm_, w1_, w2_, th_, (a1_, ch_, b2_) in g[\"bends\"]:\n        lines.append((\"n\", f\"{nm_.split(' (')[0]}: {th_:.1f} deg, {w1_:.1f} -> {w2_:.1f}:  \"\n                            f\"{a1_:.2f} + {ch_:.2f} + {b2_:.2f} = {a1_ + ch_ + b2_:.2f}\"))\n    lines += [(\"n\", \"Driver centre: distance from the inner face of D1\"),\n               (\"n\", f\"along board a: underside {d1_bottom:.2f}, top side {d1_top:.2f} {u}\"),\n               (\"n\", f\"Air {liter(geo['vol_air']):.1f} l (mouth {liter(geo['vol_mouth']):.1f} l), \"\n                     f\"path volume {liter(geo['vol_path']):.1f} l \"\n                     f\"({geo['vol_path'] / geo['vol_air'] * 100:.1f} %)\")]\n    for nm_, r_ in geo[\"ratios\"]:\n        if r_ > RATIO_WARN:\n            lines.append((\"n\", f\"WARNING {nm_.split(' (')[0]}: cross-section ratio {r_:.2f} > {RATIO_WARN},\"))\n            lines.append((\"n\", \"  bend approximation uncertain.\"))\n    if s4_bend6_level(geo) == 2:\n        lines += [(\"n\", \"WARNING: S4 lies in bend 6 BEFORE B6 -\"), (\"n\", \"  S4 is a theoretical value (line drawn with its length);\"),\n                   (\"n\", \"  reconsider driver position / box.\")]\n    elif s4_bend6_level(geo) == 1:\n        lines += [(\"n\", \"Note: S4 lies inside bend 6 (behind B6);\"), (\"n\", \"  S4 is a theoretical value (line drawn with its length).\")]\n    lines += [(\"n\", f\"Largest bend cross-section {geo['w_max']:.1f} {u} = λ/4 at approx. {lambda4_limit(geo['w_max']):.0f} Hz\"),\n               (\"n\", f\"Total path length S1-S5 = {g['total']:.2f} {u}\"),\n               (\"n\", \"Inner boards meet at right angles (butt joints).\")]\n    lines += [(\"n\", \"\"), (\"h\", f\"Cut list (length x width x thickness, {u})\")]\n    for entry in cutlist:\n        lines.append((\"n\", f\"{entry[0]:<4}{entry[1]}: {_fmt_cut(entry)}\"))\n    lines += [(\"n\", \"Length = gross length of the longest face; end angle 90 = square cut.\"),\n               (\"n\", \"Angle = interior angle of the board at the two ends of that face.\"),\n               (\"n\", \"\"), (\"h\", \"Notes\"),\n               (\"n\", \"C = inner corner; grey dashed: cross-sections of the bends,\"),\n               (\"n\", \"perpendicular to the angle bisector of the channel walls.\"),\n               (\"n\", \"Blue: C to centre O (cross-section end - outer corner).\"),\n               (\"n\", \"A, B = intersections of the centreline (red) with the blue lines.\"),\n               (\"n\", \"Purple dashed: cross-sections S1-S5.\"),\n               (\"n\", \"S2, S3, S4 are perpendicular to the centreline.\"),\n               (\"n\", \"S2/S4 pass through the driver centre on board a.\"),\n               (\"n\", \"S1 and S5 (openings) are vertical.\"),\n               (\"n\", \"Area = line length x net width.\"),\n               (\"n\", \"Brace width is deducted from the channel width (all areas);\"),\n               (\"n\", \"braces and driver are not drawn, their position is not modelled.\"),\n               (\"n\", \"Check values near 0 = construction follows the law.\")]\n    def i_ab(mark):\n        return next(i for i, z in enumerate(lines) if z[0] == \"h\" and z[1].startswith(mark))\n    i_check, i_cut = i_ab(\"Construction check\"), i_ab(\"Cut list\")\n    top_edge, block_a, block_b = lines[:i_check], lines[i_check:i_cut - 1], lines[i_cut:]\n\n    def text_block(lst, x, y0):\n        for i, (kind, text) in enumerate(lst):\n            parts.append(f'<text class=\"{kind}\" x=\"{x:.0f}\" y=\"{y0 + i * 19}\">{escape(text)}</text>')\n        return y0 + len(lst) * 19\n    column = (W - 2 * margin) / 2\n    y_text = Hp + 5\n    ya = text_block(top_edge + [(\"n\", \"\")] + block_a, margin, y_text)\n    yb = text_block(block_b, margin + column, y_text)\n    Hp = max(ya, yb) + 30\n    kd = cone_data(g, geo)\n    # Fan profile piece by piece (a gap without a reliable fan point is closed by the neighbouring support points:\n    # bend entry/exit areas are part of kd[\"points\"]; inside a bend the neighbouring pieces are joined by a straight line).\n    tab_f = sorted([(s_, A_) for _, s_, A_ in kd[\"points\"]] +\n                   [(s_, A_) for bg in kd[\"bends\"] for piece in bg[\"fan_pieces\"] for s_, A_, _ in piece])\n    geo[\"fan_gaps\"] = sum(bg[\"fan_gaps\"] for bg in kd[\"bends\"])\n    geo[\"vol_fans\"] = sum((s2_ - s1_) * (A1_ + A2_) / 2 for (s1_, A1_), (s2_, A2_) in zip(tab_f[:-1], tab_f[1:]))\n    geo[\"inertia_fans\"] = integrate_inertia(tab_f)\n    cone_parts, cone_h = cone_svg(kd, 0, Hp, W, u)\n    parts += cone_parts\n    Hp += cone_h\n    if filename is None:\n        return checks, cutlist, geo\n    svg = (\n        f'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{W:.0f}\" height=\"{Hp:.0f}\" viewBox=\"0 0 {W:.0f} {Hp:.0f}\">\\n'\n        '<style>\\n'\n        '.holz{fill:#dcb98a;stroke:#7a5a2e;stroke-width:1}\\n.luft{fill:#e9f2fb;stroke:none}\\n'\n        '.weg{fill:none;stroke:#c0392b;stroke-width:2.5;stroke-linejoin:round}\\n'\n        '.verl{stroke:#7a5a2e;stroke-width:1.5;stroke-dasharray:2 3}\\n'\n        '.quer{stroke:#7b2cbf;stroke-width:1.8;stroke-dasharray:7 4}\\n'\n        '.sek{stroke:#888;stroke-width:1;stroke-dasharray:4 3}\\n'\n        '.faecher{stroke:#0b5ed7;stroke-width:1.1}\\n'\n        '.pa{fill:#c0392b}.po{fill:#0b5ed7}.pc{fill:#222}\\n'\n        '.lbr{font:bold 8px sans-serif;fill:#c0392b}.lbc{font:bold 9px sans-serif;fill:#222}\\n'\n        '.pfeil{fill:#c0392b}\\n'\n        '.marke{fill:#fff;stroke:#c0392b;stroke-width:1.5}\\n'\n        '.mt{font:bold 9px sans-serif;text-anchor:middle;fill:#c0392b}\\n'\n        '.bl{font:bold 9px sans-serif;fill:#4a2f0b;text-anchor:middle}\\n'\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'\n        '</style>\\n'\n        f'<rect width=\"{W:.0f}\" height=\"{Hp:.0f}\" fill=\"#ffffff\"/>\\n' + \"\\n\".join(parts) + \"\\n</svg>\\n\")\n    with open(filename, \"w\", encoding=\"utf-8\") as fh:\n        fh.write(svg)\n    return checks, cutlist, geo\n\n\n\n# ---------------------------------------------------------------------------\n# Main program\n# ---------------------------------------------------------------------------\ndef main(argv=None):\n    \"\"\"Coordinates dialog and files; argv makes the command line testable.\"\"\"\n    parser = argparse.ArgumentParser(description=\"Fold a horn channel into a rectangular enclosure.\")\n    parser.add_argument(\"input\", nargs=\"?\", help=\"Input file or exported Hornresp file (no prompting)\")\n    parser.add_argument(\"--batch\", action=\"store_true\", help=\"Use saved values without prompting; fail if required values are missing\")\n    parser.add_argument(\"--output-dir\", type=Path, help=\"Directory for generated files and the saved input\")\n    parser.add_argument(\"--no-save-input\", action=\"store_true\", help=\"Do not save the input values of this run\")\n    args = parser.parse_args(argv)\n    folder = str((args.output_dir or Path(__file__).resolve().parent).resolve())\n    L, F = UNIT, UNIT + \"²\"\n    try:\n        sys.stdout.reconfigure(errors=\"replace\")      # console/pipe with a narrow code page (Windows): never crash on a special character\n    except (AttributeError, ValueError):\n        pass\n    print(f\"Hornfolding Version {VERSION}\")\n    print(f\"All lengths in {L}, all areas in {F}.\\n\")\n    print(\"Model: linear area expansion = Hornresp flare type Par (parallel side walls). Do NOT use Con.\\n\")\n\n    # Input file (last used values)\n    values = {}\n    fast = False\n    filepath, explicit = find_input_file(args.input)\n    batch = args.batch or explicit\n    hr_path = None\n    if filepath is not None and os.path.exists(filepath) and is_hornresp_file(filepath):\n        hr_path = filepath                                  # a Hornresp file was passed: other values come from the normal input file\n        filepath, explicit = None, False\n        std = os.path.join(os.path.dirname(os.path.abspath(__file__)), INPUT_FILE)\n        if os.path.exists(std):\n            filepath = std\n    if filepath is not None:\n        if not os.path.exists(filepath):\n            raise FoldingError(f\"Input file not found: {filepath}\")\n        values = load_input_file(filepath)\n        print(f\"Values from {filepath}\\nEnter accepts the displayed value, typing something overrides it.\\n\")\n        fast = True if batch else accept_all()\n        print()\n    else:\n        fast = batch\n    if hr_path is None and values.get(\"hornresp\") and values[\"hornresp\"].lower() not in (\"auto\", \"none\", \"\"):\n        # Relative references belong to the input file, not to the working directory.\n        hr_path = os.path.expanduser(values[\"hornresp\"])\n        if not os.path.isabs(hr_path):\n            hr_path = os.path.join(os.path.dirname(os.path.abspath(filepath)), hr_path)\n        hr_path = os.path.abspath(hr_path)\n        if not os.path.exists(hr_path):\n            raise FoldingError(f\"Hornresp file not found: {hr_path}\")\n    hr_values = None\n    if hr_path is not None:\n        hr_values = read_hornresp(hr_path)\n        if \"Con\" in hr_values[\"flares\"]:\n            print(\"WARNING: imported Con segments differ from the linear-area model used for folding and volume matching.\")\n            print(\"  Reference plot: imported flares. Volume/inertance checks: linear area (Par).\")\n            print(\"  Export: flare types of the source file are kept unchanged. Set all four segments to Par in Hornresp.\")\n        values.update({\"hornresp\": hr_path, \"mode\": \"1\", \"s1\": f\"{hr_values['S1']:g}\", \"s2\": f\"{hr_values['S2']:g}\",\n                      \"s3\": f\"{hr_values['S3']:g}\", \"l23\": f\"{hr_values['L23']:g}\", \"s4\": f\"{hr_values['S4']:g}\",\n                      \"s5\": f\"{hr_values['S5']:g}\"})\n        print(f\"Hornresp file: {hr_path}\")\n        print(f\"  S1 = {hr_values['S1']:g}, S2 = {hr_values['S2']:g}, S3 = {hr_values['S3']:g} (L23 = {hr_values['L23']:g}), \"\n              f\"S4 = {hr_values['S4']:g}, S5 = {hr_values['S5']:g}; lengths L12 = {hr_values['L12']:g}, \"\n              f\"L34 = {hr_values['L34']:g}, L45 = {hr_values['L45']:g}\")\n        print(\"  taken over: S1, S2, S3, L23; S4, S5 and the lengths L12, L34, L45 as comparison values; mode 1.\\n\")\n    entries = InputDialog(values, fast)\n\n    a = entries.ask(\"wood_thickness\", f\"Wood thickness a [{L}]\", p_number(0, True))\n    brace = entries.ask(\"brace_width\", f\"Brace width [{L}]\", p_number(0))\n    width = entries.ask(\"width\", f\"Width [{L}]\", p_number(0, True))\n    height = entries.ask(\"height\", f\"Height [{L}]\", p_number(0, True))\n    depth = entries.ask(\"depth\", f\"Depth [{L}]\", p_number(0, True))\n\n    b1 = width - brace - 2 * a\n    d = height - 2 * a\n    e = depth - 2 * a\n\n    print(f\"\\nNet width (at S2 and S3): {b1:.4f} {L}\")\n    print(f\"Net height: {d:.4f} {L}\")\n    print(f\"Net depth: {e:.4f} {L}\")\n    for name, value in ((\"Net width\", b1), (\"Net height\", d), (\"Net depth\", e)):\n        if value <= 0:\n            raise FoldingError(f\"{name} is {value:.2f} {L} - the dimensions are inconsistent \"\n                                 f\"(wood thickness/brace too large or enclosure too small).\")\n\n    # Horn values in the order of Hornresp: S1, S2, S3 (or the slope), L23, S4, S5; then the driver position\n    S1 = entries.ask(\"s1\", f\"Area S1 [{F}]  (number or 'auto' = same slope throughout)\",\n                   p_number(0, words={\"auto\": None}), default=\"auto\")\n    S2 = entries.ask(\"s2\", f\"Area S2 [{F}]\", p_number(0, True))\n\n    W2 = S2 / b1                       # width of the S2 chord (perpendicular to the centreline)\n    if W2 < a:\n        print(f\"\\nWARNING: Channel width at the throat W2 = {W2:.3f} {L} is smaller than the \"\n              f\"wood thickness ({a} {L}). Does the unit of S2 ({F}) match the lengths ({L})?\")\n\n    choice = entries.ask(\"mode\", \"Mode: 1 = specify S3 and L23, 2 = specify slope\",\n                     p_choice((\"1\", \"2\")))\n    l23_wanted = None\n    S3_wanted = None\n    if choice == \"1\":\n        S3_wanted = entries.ask(\"s3\", f\"Area S3 [{F}]\", p_number(0, True))\n        l23_wanted = entries.ask(\"l23\", f\"Length L23 (S2 to S3) [{L}]\", p_number(0, True))\n        b = (S3_wanted / b1 - W2) / l23_wanted      # width law W(s) = W2 + b*s, exact along the centreline\n        print(f\"Calculated slope b: {b}\")\n    else:\n        b = entries.ask(\"slope\", \"Slope of the line (height increase per path length, e.g. 0.1)\", p_number())\n\n    print(f\"\\nW2 (S2 chord): {W2:.5f} {L}\")\n    print(f\"Slope (b): {b}\")\n\n    psi_ = _ang(b)\n    if math.cos(psi_) < COS_PSI_MIN:\n        raise FoldingError(f\"Slope b = {b:g} gives a wedge angle of {math.degrees(psi_):.1f} deg between the boards \"\n                             f\"(maximum {math.degrees(math.acos(COS_PSI_MIN)):.0f} deg, i.e. |b| < \"\n                             f\"{2 * math.tan(math.acos(COS_PSI_MIN) / 2):.2f}). Check the input (Mode 1: S3, L23, S2).\")\n\n    s4_wanted = entries.ask(\"s4\", f\"S4 target from Hornresp [{F}] (number or 'auto' = no target; comparison only)\",\n                          p_number(0, True, words={\"auto\": None, \"free\": None, \"frei\": None}), default=\"auto\")\n    s5_wanted = entries.ask(\"s5\", f\"S5 target from Hornresp [{F}] (number or 'auto' = no target; comparison only)\",\n                          p_number(0, True, words={\"auto\": None}), default=\"auto\")\n    driver_offset = entries.ask(\"driver_offset\",\n                             f\"Driver offset (distance of S2 + S4, i.e. the driver centre, from the left outer edge) [{L}]\", p_number(0))\n    c = depth - a - driver_offset\n    print(f\"Initial path S2 to wall of first bend: {c:.4f} {L}\")\n    if c <= 0:\n        raise FoldingError(f\"Initial path is {c:.2f} {L} - the dimensions are inconsistent \"\n                             f\"(driver offset too large or enclosure too small).\")\n\n    # With a continuously straight board (S1-S2-S3), S1 follows from S2 and the slope.\n    h_s1 = W2 * math.cos(psi_ / 2) + (a - driver_offset - a / 2 * math.sin(psi_)) * math.tan(psi_)\n    if h_s1 < 0:\n        print(\"Note: With this slope the board at the S1 end would have a negative height; \"\n              \"'auto' gives S1 = 0.\")\n    s1_auto = max(0.0, h_s1) * b1\n    if S1 is None:\n        S1 = s1_auto\n        print(f\"S1 = auto: {s1_auto:.1f} {F} (same slope throughout)\")\n    b_manual = entries.ask(\"slope2\",\n                          \"Slope after S3 (b')  ('auto' = calculated from the box, or a number, may be negative)\",\n                          p_number(words={\"auto\": None}), default=\"auto\")\n    print(\"S3 positions:\")\n    for kk, txt in POSITIONS.items():\n        print(f\"  {kk}  {txt}\")\n    pos = entries.ask(\"s3position\", \"S3 position (1-7, or 'auto' / 'a' = automatically matched to the desired L23)\",\n                    p_choice(tuple(str(i) for i in sorted(POSITIONS)) + (\"auto\",), {\"a\": \"auto\"}), default=\"auto\")\n    if pos == \"auto\" and l23_wanted is None:\n        l23_wanted = entries.ask(\"l23\", f\"Desired length L23 (S2 to S3) for choosing the position [{L}]\",\n                               p_number(0, True))\n    driver_d = entries.ask(\"driver_diameter\", f\"Driver gross (frame) diameter [{L}] ('auto' = unknown)\",\n                          p_number(0, True, words={\"auto\": 0.0}), default=\"auto\")\n    magnet_d = entries.ask(\"magnet_diameter\", f\"Magnet diameter [{L}] ('auto' = 0.5 x driver diameter, used for the depth check)\",\n                          p_number(0, True, words={\"auto\": None}), default=\"auto\")\n    if magnet_d is None:\n        magnet_d = 0.5 * driver_d if driver_d > 0 else 0.0\n    driver_t = entries.ask(\"driver_depth\", f\"Driver mounting depth incl. magnet [{L}] ('auto' = unknown)\",\n                          p_number(0, True, words={\"auto\": 0.0}), default=\"auto\")\n    with_kink = entries.ask(\"kink\", \"Board a with a kink if S1 differs (S1 = Hornresp value)? (y/n)\",\n                          p_yes_no, default=\"y\")\n    with_svg = entries.ask(\"svg\", \"Generate SVG drawing? (y/n)\", p_yes_no, default=\"y\")\n\n    # Save inputs (before the calculation, so they survive an error)\n    store = dict(values)\n    store.update(entries.used)\n    last_file = os.path.join(folder, INPUT_FILE)\n    if args.output_dir is not None:\n        Path(folder).mkdir(parents=True, exist_ok=True)\n    if not args.no_save_input:\n        try:\n            save_inputs(store, last_file)\n            print(f\"\\nInputs saved: {last_file}\")\n        except OSError as error:\n            print(f\"\\n(Inputs could not be saved: {error}.)\")\n\n    P = {\"a\": a, \"b\": b, \"W2\": W2, \"L45\": driver_offset,\n         \"depth\": depth, \"b1\": b1, \"S1\": S1, \"H\": height, \"Width\": width, \"kink\": with_kink,\n         \"driver_d\": driver_d}\n\n    cand = {}\n    for kk in sorted(POSITIONS):\n        try:\n            note_k = \"\"\n            if b_manual is None:\n                b_k, n_sol = solve_b_consistent(P, kk)\n                if n_sol > 1:\n                    note_k = f\"{n_sol} solutions for b', the one nearest to b chosen\"\n            else:\n                b_k = b_manual\n            Rk = compute(P, kk, b_k)\n            Rk[\"shortfall\"] = shortfall(P, Rk)\n            cand[kk] = (Rk, note_k)\n        except FoldingError as error:\n            cand[kk] = (None, str(error))\n\n    if pos == \"auto\":\n        possible = [kk for kk in cand if cand[kk][0] is not None]\n        if not possible:\n            reasons = {}\n            for kk_, (_, txt_) in cand.items():\n                if \"Last reason: \" in txt_:\n                    reasons.setdefault(txt_.split(\"Last reason: \")[-1], []).append(kk_)\n            extra = \"\"\n            if len(reasons) == 1:\n                extra = f\" Reason: {next(iter(reasons))}\"\n            elif reasons:\n                extra = \" Reasons: \" + \"; \".join(f\"positions {', '.join(map(str, v))}: {r}\" for r, v in reasons.items())\n            raise FoldingError(\"None of the S3 positions can be calculated with these dimensions.\" + extra)\n        near = [kk for kk in possible if abs(cand[kk][0][\"l23\"] - l23_wanted) <= 0.10 * l23_wanted]\n        if not near:\n            near = [min(possible, key=lambda kk: abs(cand[kk][0][\"l23\"] - l23_wanted))]\n        smallest = min(cand[kk][0][\"shortfall\"] for kk in near)\n        same = [kk for kk in near if cand[kk][0][\"shortfall\"] <= smallest + 0.5]      # 0.5 percentage points count as equivalent\n        k = min(same, key=lambda kk: abs(cand[kk][0][\"l23\"] - l23_wanted))\n    else:\n        k = int(pos)\n        if cand[k][0] is None:\n            raise FoldingError(f\"S3 position {k} cannot be calculated: {cand[k][1]}\")\n    R = cand[k][0]\n\n    print(f\"\\nS3 positions compared (lengths in {L}, areas in {F}):\")\n    head = \"  Pos       L23         S3\" + (\"   S3/input\" if S3_wanted is not None else \"\") + \"      Slope b'         S4\"\n    head += \"   S4 target\" if s4_wanted is not None else \"\"\n    head += \"     dL23 %\" if l23_wanted is not None else \"\"\n    print(head + \"   Path S3-S4   Total path  Undershoot\")\n    for kk, (Rk, note_k) in cand.items():\n        mark = \"   <-- chosen\" if kk == k else \"\"\n        if Rk is None:\n            print(f\"  {kk}   cannot be calculated: {note_k}{mark}\")\n        else:\n            wu = f\"  {Rk['S4'] - s4_wanted:+9.1f}\" if s4_wanted is not None else \"\"\n            s3_dev = f\"  {(Rk['S3'] / S3_wanted - 1) * 100:+7.1f} %\" if S3_wanted is not None else \"\"\n            dl23 = f\"  {(Rk['l23'] - l23_wanted) / l23_wanted * 100:+8.1f} %\" if l23_wanted is not None else \"\"\n            print(f\"  {kk}  {Rk['l23']:8.2f}  {Rk['S3']:9.1f}{s3_dev}   {Rk['b_after']:10.4f}  {Rk['S4']:9.1f}{wu}{dl23}  \"\n                  f\"{Rk['path_s3_s4']:10.2f}   {Rk['total']:10.2f}  {Rk['shortfall']:7.1f} %\"\n                  + (f\"   ({note_k})\" if note_k else \"\") + mark)\n    print(\"  (Undershoot = largest undershoot of the actual cross-section below the idealised cone through S1-S5;\"\n          \" undesirable, because smaller than in the simulation.)\")\n    if S3_wanted is not None:\n        print(f\"  (S3/input column: calculated S3 area relative to the desired S3 = {S3_wanted:g}; \"\n              \"negative = smaller than desired.)\")\n    if l23_wanted is not None:\n        print(\"  (dL23% = (L23_calc - L23_wanted) / L23_wanted. Selection (auto): among positions within +-10 % of \"\n              \"L23_wanted (or closest if none), smallest shortfall (within 0.5 pp) wins, ties broken by closest L23.)\")\n    if s4_wanted is not None:\n        print(f\"  (S4 target column: calculated S4 minus desired S4 = {s4_wanted:g})\")\n\n    print(f\"\\nChosen: S3 position {k} - {POSITIONS[k]}\")\n    print(f\"\\nBends solved in sequence (width law along the centreline, lengths in {L}):\")\n    print(f\"  {'':<8}{'Pos. C':>9}{'Entry':>10}{'Law':>9}{'Exit':>10}{'Law':>9}{'Path s in':>11}\")\n    for f_ in R[\"geo\"][\"folds\"]:\n        Gf = f_[\"G\"]\n        out_str = f\"{f_['law_out']:9.3f}\" if not f_.get(\"free_exit\") else \"   (free)\"\n        print(f\"  Bend  {f_['nr']:<2}{f_['par']:9.3f}{Gf['w1']:10.3f}{f_['law_in']:9.3f}{Gf['w2']:10.3f}\"\n              f\"{out_str}{f_['s_e']:11.2f}\")\n    print(\"  (Bend 6: exit not bound to the law - the chamber results from the geometry.)\")\n\n    print(f\"\\nFinal values (lengths in {L}, areas in {F}):\")\n    print(f\"S1 (Hornresp):           {R['geo']['area']['S1']}\")\n    print(f\"Path S1 - S2:            {R['path_s1_s2']}\")\n    print(f\"S3:                     {R['S3']}\")\n    print(f\"Path S2 - S3 (L23):     {R['l23']}\")\n    print(f\"S4:                     {R['S4']}\")\n    print(f\"Path S3 - S4:            {R['path_s3_s4']}\")\n    print(f\"S5:                     {R['S5']}\")\n    print(f\"Path S4 - S5:            {R['path_s4_s5']}\")\n    _g = R[\"geo\"]\n    if not _g[\"kink\"] and abs(S1 - _g[\"s1_same\"]) > 0.005 * max(_g[\"s1_same\"], 1.0):\n        print(f\"Note: S1 = {S1:g} was specified, but board a has no kink: the Hornresp S1 follows from the built volume \"\n              f\"S1-S2 ({_g['area']['S1']:.1f} {F}). Use Kink = y to simulate a different S1.\")\n    if driver_d > 0:\n        r_ = driver_d / 2\n        ex_ = _g[\"ex\"]\n\n        def along(p_, q_):                                       # distance q - p along board a\n            return (q_[0] - p_[0]) * ex_[0] + (q_[1] - p_[1]) * ex_[1]\n        a_top_r = (_g[\"C1\"][0] + _g[\"en\"][0] * a, _g[\"C1\"][1] + _g[\"en\"][1] * a)\n        free = {\"channel side, to board b\": along(_g[\"U2\"], _g[\"C1\"]),\n                \"chamber side, to board b\": along(_g[\"U4\"], a_top_r)}\n        if _g[\"kink\"]:\n            free[\"channel side, to the kink\"] = along(_g[\"K\"], _g[\"U2\"])\n            free[\"chamber side, to the kink\"] = along(_g[\"K_up\"], _g[\"U4\"])\n        else:\n            free[\"channel side, to the left wall\"] = along(_g[\"Ls\"], _g[\"U2\"])\n            free[\"chamber side, to the left wall\"] = along(_g[\"Lu\"], _g[\"U4\"])\n        print(f\"Driver check: half diameter {r_:.1f} {L}; free straight length of board a from the driver centre:\")\n        for nm_, v_ in free.items():\n            print(f\"  {nm_}: {v_:.1f} {L}\" + (\"\" if v_ >= r_ - 1e-6 else \"  <-- WARNING: the driver frame does not fit\"))\n    if driver_t > 0:\n        # Free depth: from the driver centre U4 (top side of board a) along the board normal en to the opposite wall\n        # (underside of d; behind the end of d: its end face or the ceiling).\n        box_ = (a, depth - a, a, height - a)\n        en_, ex_b = _g[\"en\"], _g[\"ex\"]\n        h4, h4_name = free_height(_g, _g[\"U4\"], en_, box_)\n        if h4 is None:\n            print(\"Driver depth: no opposite wall found along the board normal (check not possible).\")\n        else:\n            theo = \"\"\n            if _g[\"s4_in_bend\"]:\n                # S4 lies in the bend: besides the real wall also the distance to the extended underside of d\n                # (the chamber height as it would be without the bend opening), the smaller value is checked\n                h4_real = h4\n                pd_ = _g[\"poly\"][\"d\"]\n                dl_ = _unit_vec((pd_[2][0] - pd_[3][0], pd_[2][1] - pd_[3][1]))\n                # the line is intersected only in the direction of the ray (in front of U4); parallel lines and\n                # intersections behind U4 are discarded, as in free_height()\n                try:\n                    px_ = _intersect(_g[\"U4\"], en_, pd_[3], dl_)\n                    hx_ = (px_[0] - _g[\"U4\"][0]) * en_[0] + (px_[1] - _g[\"U4\"][1]) * en_[1]\n                except ZeroDivisionError:\n                    hx_ = None\n                theo = f\"  (S4 lies inside bend 6; real wall behind: {h4_real:.1f} {L})\"\n                if hx_ is not None and 1e-9 < hx_ < h4:\n                    h4, h4_name = hx_, \"extended underside of d\"\n            print(f\"Driver depth {driver_t:.1f} {L}; free depth at the driver centre, perpendicular to board a, \"\n                  f\"to the {h4_name}: {h4:.1f} {L}{theo}\"\n                  + (\"\" if h4 >= driver_t else \"  <-- WARNING: the driver (magnet) does not fit between a and d\"))\n            if magnet_d > 0:\n                # h(u) = free depth at the distance u from the centre along board a (u along ex). Sign of delta from the\n                # geometry: tan(delta) = -dh/du, so that delta > 0 means the walls converge towards +u (h decreases);\n                # h(u) = h4 - u*tan(delta) is evaluated by casting the ray at the magnet edges (exact, no linearisation).\n                rm = magnet_d / 2\n                res = {}\n                for sgn, lab in ((-1, \"edge towards -ex\"), (1, \"edge towards +ex\")):\n                    org = (_g[\"U4\"][0] + sgn * rm * ex_b[0], _g[\"U4\"][1] + sgn * rm * ex_b[1])\n                    res[sgn] = free_height(_g, org, en_, box_)\n                h_m, h_p = res[-1][0], res[1][0]\n                if h_m is None or h_p is None:\n                    print(\"Magnet check: no opposite wall found at a magnet edge.\")\n                else:\n                    tan_d = (h_m - h_p) / (2 * rm)\n                    print(f\"Magnet diameter {magnet_d:.1f} {L}: free depth at the edges {h_m:.1f} (towards -ex, {res[-1][1]}) / \"\n                          f\"{h_p:.1f} (towards +ex, {res[1][1]}); wall inclination tan(delta) = {tan_d:+.4f} \"\n                          f\"(delta > 0: walls converge towards +ex)\")\n                    hmin = min(h_m, h_p, h4)\n                    if hmin < driver_t:\n                        print(f\"  <-- WARNING: at the magnet edge only {hmin:.1f} {L} are free (needed {driver_t:.1f})\")\n                    for sgn in (-1, 1) if not _g[\"s4_in_bend\"] else ():\n                        if res[sgn][1] not in (\"d underside\", \"d end face\"):\n                            print(f\"  <-- WARNING: the magnet edge ({'-' if sgn < 0 else '+'}ex side) lies outside the channel under board d \"\n                                  f\"(opposite wall: {res[sgn][1]})\")\n    if R[\"geo\"][\"kink\"]:\n        gk = R[\"geo\"]\n        print(f\"Board a with kink: S1 (Hornresp) = {R['geo']['area']['S1']:.2f}, built S1 = {gk['S1_real']:.2f};  \"\n              f\"S5 (Hornresp) = {gk['area']['S5']:.2f}, built S5 = {gk['S5_real']:.2f} {F}\")\n        print(f\"  (S1 from volume equality with a linear area segment (Hornresp Par), S5 see below; \"\n              f\"kink {gk['t_kink']:.1f} {L} from the driver centre)\")\n        if gk[\"kink_note\"]:\n            print(f\"WARNING: {gk['kink_note']}\")\n        try:\n            kk_ = kink_check(gk, b1, a, R[\"path_s1_s2\"], R[\"path_s4_s5\"])\n        except (ZeroDivisionError, ValueError):\n            print(\"  Kink check: not possible (a segment cross-section is zero or negative; acoustic mass would be infinite).\")\n            kk_ = None\n        if kk_ is not None:\n            print(f\"  Kink check (estimate; acoustic mass M = integral ds/A, built / linear-area Par segment): \"\n                  f\"S1-S2 {1 / kk_['M1']:.3f}, S4-S5 {1 / kk_['M4']:.3f}\")\n            print(f\"    equivalent length shift at the mouth (Par model minus built): S1 side {kk_['dL1']:+.2f} {L}, \"\n                  f\"S5 side {kk_['dL4']:+.2f} {L} (of {R['total']:.0f} {L} total path);  \"\n                  f\"volume difference {liter(kk_['dV1']):+.2f} / {liter(kk_['dV4']):+.2f} l\")\n            print(\"    Values below about 2 % are uncritical in this estimate; for very large kinks the estimate itself is unreliable.\")\n        if gk[\"r_driver\"] <= 0:\n            print(\"WARNING: no driver diameter given - the kink is placed at the driver centre (S2/S4). \"\n                  \"Enter DriverDiameter so that a2 stays straight at least half a driver diameter on each side.\")\n    print(f\"[diag] S4 relative to exit of bend 6 (X0), along the centreline: {R['geo']['s4_over_x0']:.2f} {L}\")\n    level6 = s4_bend6_level(R[\"geo\"])\n    gg = R[\"geo\"]\n    if gg[\"s4_in_bend\"]:\n        print(f\"S4 lies in the curved part of bend 6: cross-section = fan ray from C6 through the driver centre \"\n              f\"(length {gg['S4_fan'] / b1:.1f} {L}, fan area {gg['S4_fan']:.1f} {F}); path position \"\n              f\"{gg['s4_cum'] - gg['cum'][1]:.2f} {L} behind S2.\")\n        print(f\"  S4 for Hornresp = {R['S4']:.1f} {F} (theoretical: straight chamber line to the built mouth area S5, extended back through the \"\n              f\"built exit area of bend 6; not the fan area).\")\n    if gg.get(\"s5_inert\") is not None and gg[\"s5_vol\"] > 0:\n        print(f\"S5 (Hornresp) = mean of the volume-equal S5 ({gg['s5_vol']:.1f}) and the inertance-equal S5 \"\n              f\"({gg['s5_inert']:.1f}); built S5 = {gg['S5_real']:.1f} {F}\")\n        if abs(gg[\"s5_vol\"] - gg[\"s5_inert\"]) / gg[\"s5_vol\"] > 0.02:\n            print(f\"  Note: volume and inertance give different S5 ({(gg['s5_inert'] / gg['s5_vol'] - 1) * 100:+.1f} % apart); \"\n                  f\"a straight Hornresp segment cannot match both.\")\n    v_hr = (R[\"S4\"] + R[\"S5\"]) / 2 * R[\"path_s4_s5\"]\n    print(f\"Volume S4-S5: built {liter(gg['v45_actual']):.2f} l, linear-area Par segment {liter(v_hr):.2f} l \"\n          f\"({(v_hr / gg['v45_actual'] - 1) * 100:+.1f} %)\")\n    if level6 == 2:\n        print(\"\\n\" + \"!\" * 78)\n        print(f\"WARNING: S4 lies in the curved part of bend 6, {-gg['s4_over_x0']:.1f} {L} before its exit,\")\n        print(\"         BEFORE the point B6. Constructionally this is unfavourable (the driver sits in the bend);\")\n        print(\"         the area S4 is a theoretical value there, the real channel has no such cross-section.\")\n        print(\"         Please reconsider DriverOffset, the S3 position or the box dimensions.\")\n        print(\"!\" * 78 + \"\\n\")\n    elif level6 == 1:\n        print(f\"Note: S4 lies inside bend 6, {-gg['s4_over_x0']:.1f} {L} before its exit (behind B6). \"\n              f\"S4 is a theoretical value there (see above); please check the drawing.\")\n    print(f\"Total path length:      {R['total']}\")\n    print(f\"Slope b  (S2 - S3) = {b:g}   (area gradient b1*b  = {b1 * b:.4g} {F}/{L})\")\n    print(f\"Slope b' (S3 - S4) = {R['b_after']:.5g}   (area gradient b1*b' = {b1 * R['b_after']:.4g} {F}/{L})\"\n          + (\"  (calculated from the box)\" if b_manual is None else \"  (specified)\"))\n    print(f\"Linear-area model (Par) S3 -> S4: uniform slope {R['b_cone']:.5g} \"\n          f\"(check: S3 + b1*b'*path = {R['S3'] + b1 * R['b_after'] * R['path_s3_s4']:.2f}, S4 = {R['S4']:.2f})\")\n    if s5_wanted is not None:\n        print(f\"S5 target {s5_wanted:g}: calculated S5 (Hornresp value) deviates by {R['S5'] - s5_wanted:+.2f} {F} \"\n              f\"({(R['S5'] / s5_wanted - 1) * 100:+.2f} %).\")\n    if hr_values:\n        print(f\"Hornresp lengths (comparison): L12 = {hr_values['L12']:g} (calc. {R['path_s1_s2']:.2f}), \"\n              f\"L34 = {hr_values['L34']:g} (calc. {R['path_s3_s4']:.2f}), \"\n              f\"L45 = {hr_values['L45']:g} (calc. {R['path_s4_s5']:.2f})\")\n    if s4_wanted is not None:\n        print(f\"S4 target {s4_wanted:g}: calculated S4 deviates by {R['S4'] - s4_wanted:+.2f} {F} \"\n              f\"({(R['S4'] / s4_wanted - 1) * 100:+.2f} %).\")\n\n    print(f\"\\nPath parts per bend (straight up to A + chord A-B + straight from B), in {L}:\")\n    for name_, w1_, w2_, th_, (a1_, ch_, b2_) in R[\"bends\"]:\n        print(f\"  {name_:<30}{th_:6.1f} deg   {w1_:7.2f} -> {w2_:7.2f}   \"\n              f\"{a1_:6.2f} + {ch_:6.2f} + {b2_:6.2f} = {a1_ + ch_ + b2_:7.2f}\")\n\n    if l23_wanted is not None:\n        print(f\"\\nNote: desired L23 = {l23_wanted:.3f}, calculated L23 = {R['l23']:.3f} \"\n              f\"(deviation {R['l23'] - l23_wanted:+.3f} {L}). \"\n              f\"In case of deviation, adjust S3/L23 if necessary or choose a different S3 position.\")\n\n    # --- Hornresp output file (the original is never overwritten) -----------------------------------\n    if hr_path is not None:\n        stem, ext = os.path.splitext(hr_path)\n        target = stem + \"_Hornfolding\" + (ext or \".txt\")\n        if args.output_dir is not None:\n            target = os.path.join(folder, os.path.basename(target))\n        hr_new = {\"S1\": R[\"geo\"][\"area\"][\"S1\"], \"S2\": S2, \"S3\": R[\"S3\"], \"S4\": R[\"S4\"], \"S5\": R[\"S5\"],\n                  \"L12\": R[\"path_s1_s2\"], \"L23\": R[\"l23\"], \"L34\": R[\"path_s3_s4\"], \"L45\": R[\"path_s4_s5\"]}\n        try:\n            write_hornresp(hr_path, target, hr_new)\n            print(f\"\\nHornresp file written: {target}\")\n            print(\"  changed: S1-S5 and the four lengths\"\n                  + \"; flare types and all other parameters preserved.\")\n        except (OSError, FoldingError) as error:\n            print(f\"\\nWARNING: Hornresp file could not be written: {error}\")\n\n    # --- SVG drawing (optional) -----------------------------------------\n    if with_svg:\n        g = {\n            \"unit\": L, \"a\": a, \"T\": depth, \"H\": height, \"L45\": driver_offset, \"b\": b, \"b1\": b1, \"W2\": W2,\n            \"S1\": S1, \"S2\": S2, \"Width\": width, \"k\": k, \"b_after\": R[\"b_after\"], \"geo\": R[\"geo\"],\n            \"l23_new\": R[\"l23\"], \"path_s1_s2\": R[\"path_s1_s2\"], \"path_s4_s5\": R[\"path_s4_s5\"],\n            \"path_s3_s4\": R[\"path_s3_s4\"], \"bends\": R[\"bends\"], \"total\": R[\"total\"],\n            # Target cone (a): input/Hornresp values; if a target value is missing, the script value applies\n            \"ref\": {\"S1\": S1, \"S2\": S2, \"S3\": S3_wanted if choice == \"1\" else R[\"S3\"],\n                    \"S4\": s4_wanted if s4_wanted is not None else R[\"S4\"],\n                    \"S5\": s5_wanted if s5_wanted is not None else R[\"S5\"],\n                    \"L12\": hr_values[\"L12\"] if hr_values else R[\"path_s1_s2\"],\n                    \"L23\": l23_wanted if l23_wanted is not None else R[\"l23\"],\n                    \"L34\": hr_values[\"L34\"] if hr_values else R[\"path_s3_s4\"],\n                    \"L45\": hr_values[\"L45\"] if hr_values else R[\"path_s4_s5\"],\n                    \"flares\": hr_values[\"flares\"] if hr_values else (\"Par\",) * 4},\n        }\n        filename = os.path.join(folder, \"horn_folding.svg\")\n        try:\n            checks, cutlist, _geo = draw_svg(g, filename)\n        except OSError:                       # script folder not writable\n            if args.output_dir is not None:\n                raise  # Never silently ignore an explicitly requested target.\n            filename = os.path.abspath(\"horn_folding.svg\")\n            checks, cutlist, _geo = draw_svg(g, filename)\n        print(f\"\\nDrawing written: {filename}\")\n        print(\"Drawing check:\")\n        for name, value in checks.items():\n            print(f\"  {name}: {value:+.3f} {F if 'area' in name else L}\")\n        d1u, d1o = _geo[\"d1\"]\n        print(\"\\nDriver centre: distance from the inner face of D1 along board a (for marking the cutouts):\")\n        print(f\"  Underside (channel side, S2): {d1u:.2f} {L}     Top side (chamber side, S4): {d1o:.2f} {L}\")\n        print(f\"\\nCheck: air volume of the drawing {liter(_geo['vol_air']):.2f} l \"\n              f\"(incl. mouth opening {liter(_geo['vol_mouth']):.2f} l; net width {b1:.2f} {L}); \"\n              f\"volume along the centreline (integral A ds) {liter(_geo['vol_path']):.2f} l \"\n              f\"= {_geo['vol_path'] / _geo['vol_air'] * 100:.1f} %\")\n        print(\"  (Close to 100 % means: the horn volume along the centreline matches the air space of the drawing; \"\n              \"the difference is due to bend corners and approximation.)\")\n        print(f\"  Same integral with the fan profile of the plot (peaks at the outer corners): \"\n              f\"{liter(_geo['vol_fans']):.2f} l = {_geo['vol_fans'] / _geo['vol_air'] * 100:.1f} %\")\n        print(\"  (Both are approximations of the drawn air volume; which is closer depends on the geometry \"\n              \"(the fan profile is usually closer, the linear interpolation for strongly widening bends).)\")\n        if _geo.get(\"fan_gaps\", 0) > 0:\n            print(f\"  Note: the fan profile has {_geo['fan_gaps']} gap(s) (no reliable construction); bridged by straight lines \"\n                  f\"in the fan volume / inertance.\")\n        print(f\"  Inertance integral ds/A = {_geo['inertia']:.5f} 1/{L} (stations), \"\n              f\"{_geo['inertia_fans']:.5f} 1/{L} (with fan profile)\")\n        for nm_, r_ in _geo[\"ratios\"]:\n            if r_ > RATIO_WARN:\n                print(f\"WARNING: {nm_}: cross-section ratio {r_:.2f} (exit/entry) is greater than {RATIO_WARN} - \"\n                      f\"the bend approximation (centreline across the corner) is unreliable there; path probably shorter than calculated.\")\n        print(f\"Note: The largest bend cross-section ({_geo['w_max']:.1f} {L}) corresponds to lambda/4 at approx. \"\n              f\"{lambda4_limit(_geo['w_max']):.0f} Hz (c = 344 m/s). The bend approximation (plane wavefront in the \"\n              f\"cross-section) is only valid well below that.\")\n        print(\"Note: The volume of the driver (and the braces) is not subtracted here. In reality it reduces the \"\n              \"chamber S4-S5 behind the driver. Hornresp has no parameter for this (Vtc is the volume in front of \"\n              \"the driver), so S4 would have to be adjusted by judgement.\")\n        print(f\"\\nCut list (length x width x thickness in {L}):\")\n        for entry in cutlist:\n            print(f\"  {entry[0]:<4}{entry[1]:<26}{_fmt_cut(entry)}\")\n        csv_name = os.path.join(os.path.dirname(filename), \"horn_cutlist.csv\")\n        try:\n            with open(csv_name, \"w\", encoding=\"utf-8-sig\") as fh:\n                fh.write(f\"Board;Name;Gross length ({L});Width ({L});Thickness ({L});Qty;End angle 1 (deg);\"\n                         f\"End angle 2 (deg);Long face\\n\")\n                for lab, name, l_, w_, d_, n_, a1_, a2_, fc_ in cutlist:\n                    if abs(a1_ - 90) < 0.05 and abs(a2_ - 90) < 0.05:\n                        fc_ = \"\"                              # square cut: no long face\n                    fh.write(f\"{lab};{name};{l_:.1f};{w_:.1f};{d_:g};{n_};{a1_:.1f};{a2_:.1f};{fc_}\\n\".replace(\".\", \",\"))\n            print(f\"Cut list written: {csv_name}\")\n        except OSError:\n            print(\"(Cut list could not be written as CSV.)\")\n\n\nif __name__ == \"__main__\":\n    try:\n        main()\n    except FoldingError as error:\n        print(f\"\\nERROR: {error}\")\n        sys.exit(1)\n    except (OSError, UnicodeError) as error:\n        print(f\"\\nERROR: File could not be read or written: {error}\")\n        sys.exit(1)\n    except (KeyboardInterrupt, EOFError):\n        print(\"\\nAborted.\")\n        sys.exit(1)\n"}