#!/usr/bin/env python3
"""
Render high-resolution Chladni eigenfunction comparisons and spectral plots
for the Gordon-Webb-Wolpert (1992) isospectral drums.

Reads drum_solver outputs (or compiles & runs drum_solver.c if needed) and writes:
  - gww_drums_chladni.png       (4-mode x 2-drum Chladni nodal gallery at N=96)
  - gww_nodal_and_convergence.svg (nodal-domain splits k=1..50 & O(h^4/3) vs O(h^2) convergence)

Pure Python + Pillow (zero numpy/scipy dependency).
"""

from __future__ import annotations

import math
import struct
import subprocess
import tempfile
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

HERE = Path(__file__).resolve().parent

DRUM_A_TRIS = [
    ((0, 0), (1, 0), (0, 1)),
    ((0, 0), (-1, 0), (0, -1)),
    ((1, -1), (1, -2), (0, -1)),
    ((0, 0), (1, 0), (0, -1)),
    ((1, -1), (1, 0), (0, -1)),
    ((1, -1), (1, -2), (2, -1)),
    ((2, -2), (1, -2), (2, -1)),
]
DRUM_B_TRIS = [
    ((0, 0), (1, 0), (0, 1)),
    ((0, 0), (-1, 0), (0, -1)),
    ((1, 1), (1, 2), (0, 1)),
    ((0, 0), (1, 0), (0, -1)),
    ((1, 1), (1, 0), (0, 1)),
    ((1, 1), (1, 2), (2, 1)),
    ((0, 2), (1, 2), (0, 1)),
]
DRUM_A_POLY = [(1, 0), (0, 1), (0, 0), (-1, 0), (1, -2), (2, -2), (2, -1), (1, -1)]
DRUM_B_POLY = [(0, 0), (-1, 0), (0, -1), (1, 0), (1, 1), (2, 1), (1, 2), (0, 2)]

# Interior glued edges (shared by 2 triangles)
def internal_edges(tris):
    counts: dict[tuple[tuple[int, int], tuple[int, int]], int] = {}
    for t in tris:
        for k in range(3):
            a, b = t[k], t[(k + 1) % 3]
            key = (a, b) if a < b else (b, a)
            counts[key] = counts.get(key, 0) + 1
    return [e for e, c in counts.items() if c == 2]


INT_A = internal_edges(DRUM_A_TRIS)
INT_B = internal_edges(DRUM_B_TRIS)


def load_font(size: int, bold: bool = False):
    candidates = (
        [
            "/usr/share/fonts/google-noto/NotoSans-Bold.ttf",
            "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf",
            "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Bold.ttf",
        ]
        if bold
        else [
            "/usr/share/fonts/google-noto/NotoSans-Regular.ttf",
            "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
            "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Regular.ttf",
        ]
    )
    for p in candidates:
        if Path(p).exists():
            return ImageFont.truetype(p, size)
    return ImageFont.load_default()


def diverging_color(val: float) -> tuple[int, int, int]:
    """
    Diverging blue (-) / charcoal (0) / warm gold-amber (+) palette with smooth gamma,
    giving glowing high-contrast positive & negative vibration lobes separated by crisp nodal lines.
    val in [-1, 1].
    """
    v = max(-1.0, min(1.0, val))
    # Gentle nonlinear stretch so subtle lobes remain clearly readable
    mag = abs(v) ** 0.72
    if v >= 0.0:
        # Warm gold / coral-orange positive lobe
        stops = [
            (0.00, (24, 28, 38)),
            (0.25, (148, 86, 36)),
            (0.60, (232, 152, 54)),
            (1.00, (255, 232, 150)),
        ]
    else:
        # Deep cobalt / electric cyan negative lobe
        stops = [
            (0.00, (24, 28, 38)),
            (0.25, (34, 88, 154)),
            (0.60, (66, 158, 236)),
            (1.00, (186, 238, 255)),
        ]
    for k in range(len(stops) - 1):
        t0, c0 = stops[k]
        t1, c1 = stops[k + 1]
        if mag <= t1:
            f = (mag - t0) / (t1 - t0) if t1 > t0 else 0.0
            return (
                int(round(c0[0] + f * (c1[0] - c0[0]))),
                int(round(c0[1] + f * (c1[1] - c0[1]))),
                int(round(c0[2] + f * (c1[2] - c0[2]))),
            )
    return stops[-1][1]


def load_mode_bin(path: Path):
    with open(path, "rb") as f:
        N, W, H, min_gx, min_gy, k1 = struct.unpack("<6i", f.read(24))
        lam, = struct.unpack("<d", f.read(8))
        grid = struct.unpack(f"<{W * H}d", f.read(8 * W * H))
    return N, W, H, min_gx, min_gy, k1, lam, grid


def draw_dashed_line(draw: ImageDraw.ImageDraw, p0, p1, color, dash=6, gap=5, width=1):
    x0, y0 = p0
    x1, y1 = p1
    dist = math.hypot(x1 - x0, y1 - y0)
    if dist < 1e-6:
        return
    ux, uy = (x1 - x0) / dist, (y1 - y0) / dist
    s = 0.0
    while s < dist:
        e = min(dist, s + dash)
        draw.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=color, width=width)
        s += dash + gap


def render_mode_tile(bin_path: Path, poly, int_edges, tile_w: int, tile_h: int, scale_px: float):
    N, W, H, min_gx, min_gy, k1, lam, grid = load_mode_bin(bin_path)
    # Bounding box in unit coordinates
    xs = [p[0] for p in poly]
    ys = [p[1] for p in poly]
    cx = 0.5 * (min(xs) + max(xs))
    cy = 0.5 * (min(ys) + max(ys))

    # Peak amplitude for normalization (and ensure positive ground state)
    maxv = 0.0
    sum_signed = 0.0
    for v in grid:
        if not math.isnan(v):
            if abs(v) > maxv:
                maxv = abs(v)
            sum_signed += v
    sign = -1.0 if (k1 == 1 and sum_signed < 0.0) else 1.0
    if maxv <= 0.0:
        maxv = 1.0

    CARD_BG = (11, 14, 21)
    tile = Image.new("RGB", (tile_w, tile_h), CARD_BG)
    pix = tile.load()

    def to_px(x: float, y: float) -> tuple[float, float]:
        return (tile_w * 0.5 + (x - cx) * scale_px, tile_h * 0.5 - (y - cy) * scale_px)

    # Bilinear sample from grid + crisp Chladni zero-contour detection
    def sample_grid(fx: float, fy: float) -> float | None:
        gx = fx * N - min_gx
        gy = fy * N - min_gy
        ix = int(math.floor(gx))
        iy = int(math.floor(gy))
        if ix < 0 or iy < 0 or ix >= W - 1 or iy >= H - 1:
            return None
        tx = gx - ix
        ty = gy - iy
        v00 = grid[iy * W + ix]
        v10 = grid[iy * W + ix + 1]
        v01 = grid[(iy + 1) * W + ix]
        v11 = grid[(iy + 1) * W + ix + 1]
        # Treat NaN boundary neighbors as 0 (Dirichlet boundary condition!) only if inside polygon
        # Check point-in-polygon via exact winding/even-odd test? Faster: if ALL 4 are NaN -> outside.
        # Even cleaner: exact point-in-polygon check first!
        c00 = 0.0 if math.isnan(v00) else v00
        c10 = 0.0 if math.isnan(v10) else v10
        c01 = 0.0 if math.isnan(v01) else v01
        c11 = 0.0 if math.isnan(v11) else v11
        return sign * ((1 - tx) * (1 - ty) * c00 + tx * (1 - ty) * c10 + (1 - tx) * ty * c01 + tx * ty * c11) / maxv

    def point_in_poly(x: float, y: float) -> bool:
        inside = False
        n = len(poly)
        j = n - 1
        for i in range(n):
            xi, yi = poly[i]
            xj, yj = poly[j]
            if ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi):
                inside = not inside
            j = i
        return inside

    # Evaluate scalar field on pixel grid
    field: list[float | None] = [None] * (tile_w * tile_h)
    for py in range(tile_h):
        y = cy + (tile_h * 0.5 - (py + 0.5)) / scale_px
        ro = py * tile_w
        for px in range(tile_w):
            x = cx + ((px + 0.5) - tile_w * 0.5) / scale_px
            if point_in_poly(x, y):
                field[ro + px] = sample_grid(x, y)

    # Shade pixels + highlight Chladni nodal lines (sign change across adjacent interior pixels)
    for py in range(tile_h):
        ro = py * tile_w
        for px in range(tile_w):
            v = field[ro + px]
            if v is None:
                continue
            # Check for zero-crossing with right/down/left/up interior neighbors
            nodal = False
            if k1 > 1:
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    nx, ny = px + dx, py + dy
                    if 0 <= nx < tile_w and 0 <= ny < tile_h:
                        nv = field[ny * tile_w + nx]
                        if nv is not None and ((v > 0.0 and nv <= 0.0) or (v < 0.0 and nv >= 0.0)):
                            # Only light up the side closer to zero for a crisp 1.5px nodal line
                            if abs(v) <= abs(nv) * 1.15:
                                nodal = True
                                break
            if nodal:
                pix[px, py] = (248, 250, 255)
            else:
                pix[px, py] = diverging_color(v)

    draw = ImageDraw.Draw(tile)
    # Faint dashed internal triangle creases
    for a, b in int_edges:
        draw_dashed_line(draw, to_px(a[0], a[1]), to_px(b[0], b[1]), (185, 195, 215), dash=4, gap=4, width=1)

    # Crisp outer polygon boundary
    pts_px = [to_px(x, y) for x, y in poly]
    draw.polygon(pts_px, outline=(235, 240, 250))
    for i in range(len(pts_px)):
        draw.line([pts_px[i], pts_px[(i + 1) % len(pts_px)]], fill=(235, 240, 250), width=2)

    return tile, lam


def build_chladni_plate(prefix: str, out_png: Path):
    spec = {}
    with open(f"{prefix}_spectrum.tsv") as f:
        f.readline()
        for line in f:
            p = line.strip().split("\t")
            spec[int(p[0])] = (float(p[1]), int(p[7]), int(p[8]), float(p[10]))

    modes = [
        (1, "Mode k = 1 · Ground State", "Single positive lobe; hub A[3] holds 51%, B[1] = 0.08%"),
        (4, "Mode k = 4 · First Nodal Split", "Drum B is Courant-sharp (4), Drum A is not (3)"),
        (9, "Mode k = 9 · Tiled Base Triangle (5π²)", "Zero along every crease; O(h²), scale = 3"),
        (20, "Mode k = 20 · Widest Split (6 vs 9)", "Identical pitch to 10⁻¹⁴, 3-domain gap"),
    ]

    tile_w, tile_h = 340, 320
    scale_px = 86.0  # identical geometric scale for BOTH Drum A and Drum B!
    pad_x = 24
    gap_x = 18
    top_hdr = 82
    col_hdr = 52
    row_gap = 22
    left_lbl = 36
    footer_h = 44

    W = pad_x + left_lbl + 4 * tile_w + 3 * gap_x + pad_x
    H = top_hdr + col_hdr + 2 * tile_h + row_gap + footer_h

    BG = (8, 10, 15)
    BORDER = (36, 44, 62)
    FG = (234, 240, 250)
    MUTED = (148, 160, 182)
    ACCENT = (126, 186, 255)
    GOLD = (248, 200, 104)

    img = Image.new("RGB", (W, H), BG)
    draw = ImageDraw.Draw(img)

    f_title = load_font(22, bold=True)
    f_sub = load_font(13, bold=False)
    f_col = load_font(14, bold=True)
    f_meta = load_font(12, bold=False)
    f_badge = load_font(12, bold=True)
    f_row = load_font(14, bold=True)

    draw.text(
        (pad_x, 16),
        "Can You Hear the Shape of a Drum? Gordon-Webb-Wolpert Isospectral Polygons (N = 96)",
        fill=FG,
        font=f_title,
    )
    draw.text(
        (pad_x, 46),
        "Same area (3.5), same perimeter (6 + 3*sqrt(2)), identical Dirichlet spectrum to 10^-13 — yet 20/50 modes split into different Chladni nodal counts",
        fill=MUTED,
        font=f_sub,
    )

    y_rowA = top_hdr + col_hdr
    y_rowB = y_rowA + tile_h + row_gap

    # Row tags on left margin
    draw.text((pad_x, y_rowA + tile_h // 2 - 20), "A", fill=ACCENT, font=load_font(22, bold=True))
    draw.text((pad_x, y_rowB + tile_h // 2 - 20), "B", fill=GOLD, font=load_font(22, bold=True))

    for ci, (k, title, note) in enumerate(modes):
        x0 = pad_x + left_lbl + ci * (tile_w + gap_x)
        lam, nA, nB, tscale = spec[k]
        lam_d = lam / 4.0  # Driscoll scaling (leg = 2)

        draw.text((x0 + 2, top_hdr + 2), title, fill=FG, font=f_col)
        split_tag = f"SPLIT: {nA} vs {nB}" if nA != nB else f"matched: {nA} vs {nB}"
        draw.text(
            (x0 + 2, top_hdr + 21),
            f"λ/4 = {lam_d:.4f}  ·  {split_tag}",
            fill=(GOLD if nA != nB else ACCENT),
            font=f_meta,
        )
        draw.text((x0 + 2, top_hdr + 36), note, fill=MUTED, font=load_font(11, bold=False))

        tileA, _ = render_mode_tile(Path(f"{prefix}_mode{k}_A.bin"), DRUM_A_POLY, INT_A, tile_w, tile_h, scale_px)
        tileB, _ = render_mode_tile(Path(f"{prefix}_mode{k}_B.bin"), DRUM_B_POLY, INT_B, tile_w, tile_h, scale_px)

        img.paste(tileA, (x0, y_rowA))
        draw.rectangle([x0, y_rowA, x0 + tile_w - 1, y_rowA + tile_h - 1], outline=BORDER, width=1)
        draw.text((x0 + 10, y_rowA + 8), f"Drum A · ν = {nA}", fill=FG, font=f_badge)

        img.paste(tileB, (x0, y_rowB))
        draw.rectangle([x0, y_rowB, x0 + tile_w - 1, y_rowB + tile_h - 1], outline=BORDER, width=1)
        draw.text((x0 + 10, y_rowB + 8), f"Drum B · ν = {nB}", fill=FG, font=f_badge)

    draw.text(
        (pad_x, H - 28),
        "Gold = positive lobe (+u) · Blue = negative lobe (-u) · White curves = Chladni nodal lines (u = 0) · Dashed lines = 7-triangle Fano tiling · Equal Euclidean scale across all panels",
        fill=MUTED,
        font=f_meta,
    )

    img.save(out_png, optimize=True)
    print(f"Wrote {out_png} ({W}x{H})")


def build_svg(work_dir: Path, out_svg: Path):
    """2-panel SVG: (Left) Nodal domain counts nu_A(k) vs nu_B(k) for k=1..50 vs Courant bound;
    (Right) Non-monotonic O(h^4/3) vs O(h^2) convergence of modes k=1,2,3 vs tiled mode k=9."""
    spec96 = {}
    with open(work_dir / "drum_N96_spectrum.tsv") as f:
        f.readline()
        for line in f:
            p = line.strip().split("\t")
            spec96[int(p[0])] = (float(p[1]) / 4.0, int(p[7]), int(p[8]), float(p[10]))

    Ns = [16, 24, 32, 48, 64, 96]
    conv = {k: [] for k in (1, 2, 3, 9)}
    for N in Ns:
        with open(work_dir / f"drum_N{N}_spectrum.tsv") as f:
            f.readline()
            for line in f:
                p = line.strip().split("\t")
                k = int(p[0])
                if k in conv:
                    conv[k].append(float(p[1]) / 4.0)

    # Driscoll (1997) / exact 5*pi^2/4 references
    refs = {
        1: 2.5379439998,
        2: 3.6555097135,
        3: 5.1755593562,
        9: 5.0 * math.pi * math.pi / 4.0,
    }

    W, H = 980, 420
    # Left plot box: x=[64..470], y=[64..355]
    # Right plot box: x=[555..945], y=[64..355]
    parts = [
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}">',
        '<rect width="100%" height="100%" fill="#0b0e15"/>',
        '<style>',
        'text { font-family: "Noto Sans", "DejaVu Sans", sans-serif; }',
        '.t { fill: #eaf0fa; font-size: 15px; font-weight: 700; }',
        '.s { fill: #94a0b6; font-size: 11px; }',
        '.ax { stroke: #364058; stroke-width: 1; }',
        '.gr { stroke: #1b2232; stroke-width: 1; }',
        '.lbl { fill: #a8b4ca; font-size: 11px; }',
        '</style>',
    ]

    # Left panel: Nodal domain counts k=1..50
    lx0, lx1, ly0, ly1 = 62, 468, 68, 354
    parts.append(f'<text x="{lx0}" y="30" class="t">Nodal Domain Counts ν(k): Hearing Fails, Seeing Splits</text>')
    parts.append(f'<text x="{lx0}" y="48" class="s">First 50 Dirichlet modes (N=96): 20/50 splits stable across N=48..96</text>')

    def lx(k): return lx0 + (k - 1) / 49.0 * (lx1 - lx0)
    def ly(v): return ly1 - (v / 32.0) * (ly1 - ly0)

    for v in (0, 5, 10, 15, 20, 25, 30):
        y = ly(v)
        parts.append(f'<line x1="{lx0}" y1="{y:.1f}" x2="{lx1}" y2="{y:.1f}" class="gr"/>')
        parts.append(f'<text x="{lx0 - 8}" y="{y + 4:.1f}" text-anchor="end" class="lbl">{v}</text>')
    for k in (1, 10, 20, 30, 40, 50):
        x = lx(k)
        parts.append(f'<line x1="{x:.1f}" y1="{ly0}" x2="{x:.1f}" y2="{ly1}" class="gr"/>')
        parts.append(f'<text x="{x:.1f}" y="{ly1 + 16}" text-anchor="middle" class="lbl">{k}</text>')
    parts.append(f'<rect x="{lx0}" y="{ly0}" width="{lx1 - lx0}" height="{ly1 - ly0}" fill="none" class="ax"/>')
    parts.append(f'<text x="{(lx0+lx1)/2:.1f}" y="{ly1 + 36}" text-anchor="middle" class="lbl">Mode index k</text>')
    parts.append(f'<text x="20" y="{(ly0+ly1)/2:.1f}" text-anchor="middle" transform="rotate(-90 20 {(ly0+ly1)/2:.1f})" class="lbl">Connected nodal domains ν(k)</text>')

    # Courant bound line ν = k (clipped to ν <= 32)
    parts.append(f'<line x1="{lx(1):.1f}" y1="{ly(1):.1f}" x2="{lx(32):.1f}" y2="{ly(32):.1f}" stroke="#4e5c78" stroke-dasharray="4 4" stroke-width="1.2"/>')
    parts.append(f'<text x="{lx(21):.1f}" y="{ly(25):.1f}" class="s">Courant bound ν ≤ k</text>')

    # Pleijel asymptotic line (2/j0)^2 * k ≈ 0.6917 k? No, wait: Pleijel is limsup <= 0.6917 k; draw vertical split bars + dots!
    for k in range(1, 51):
        _, nA, nB, tscale = spec96[k]
        x = lx(k)
        yA, yB = ly(nA), ly(nB)
        if nA != nB:
            parts.append(f'<line x1="{x:.1f}" y1="{yA:.1f}" x2="{x:.1f}" y2="{yB:.1f}" stroke="#ffffff" stroke-opacity="0.45" stroke-width="1.5"/>')
        if tscale > 2.0:
            # Tiled base-triangle mode diamond
            parts.append(f'<circle cx="{x:.1f}" cy="{yA:.1f}" r="4.6" fill="none" stroke="#9ef0b0" stroke-width="1.5"/>')
        parts.append(f'<circle cx="{x:.1f}" cy="{yA:.1f}" r="3.0" fill="#5aa8ff"/>')
        parts.append(f'<circle cx="{x:.1f}" cy="{yB:.1f}" r="3.0" fill="#f5b952"/>')

    # Annotate k=4, k=9, k=20, k=44
    parts.append(f'<text x="{lx(4)+6:.1f}" y="{ly(4)-6:.1f}" class="s">k=4 (3 vs 4)</text>')
    parts.append(f'<text x="{lx(20)+5:.1f}" y="{ly(9)-6:.1f}" class="s">k=20 (6 vs 9)</text>')
    parts.append(f'<text x="{lx(44)-4:.1f}" y="{ly(28)-9:.1f}" text-anchor="end" class="s">k=44 tiled (28)</text>')

    # Legend left
    parts.append(f'<circle cx="{lx0+12}" cy="{ly0+16}" r="3.5" fill="#5aa8ff"/><text x="{lx0+21}" y="{ly0+20}" class="lbl">Drum A</text>')
    parts.append(f'<circle cx="{lx0+82}" cy="{ly0+16}" r="3.5" fill="#f5b952"/><text x="{lx0+91}" y="{ly0+20}" class="lbl">Drum B</text>')
    parts.append(f'<circle cx="{lx0+154}" cy="{ly0+16}" r="4.5" fill="none" stroke="#9ef0b0" stroke-width="1.5"/><text x="{lx0+164}" y="{ly0+20}" class="lbl">Tiled T₀ mode</text>')

    # Right panel: Signed discretization error (lam_h - lam_true) / lam_true vs h = 1/N
    rx0, rx1, ry0, ry1 = 556, 954, 68, 354
    parts.append(f'<text x="{rx0}" y="30" class="t">Signed Error: +h⁴/³ Corner Singularity vs. -h² Stencil</text>')
    parts.append(f'<text x="{rx0}" y="48" class="s">Modes k=2,3 cross zero non-monotonically; tiled k=9 has zero singularity</text>')

    def rx(h): return rx0 + (h / 0.066) * (rx1 - rx0)
    # Signed relative error in percent: [-1.2%, +0.3%]
    ymin, ymax = -1.2, 0.35
    def ry(pct): return ry1 - ((pct - ymin) / (ymax - ymin)) * (ry1 - ry0)

    for pct in (-1.0, -0.5, 0.0, 0.25):
        y = ry(pct)
        cls = "ax" if pct == 0.0 else "gr"
        parts.append(f'<line x1="{rx0}" y1="{y:.1f}" x2="{rx1}" y2="{y:.1f}" class="{cls}"/>')
        parts.append(f'<text x="{rx0 - 8}" y="{y + 4:.1f}" text-anchor="end" class="lbl">{pct:+.2f}%</text>')
    for N in (96, 48, 32, 24, 16):
        x = rx(1.0 / N)
        parts.append(f'<line x1="{x:.1f}" y1="{ry0}" x2="{x:.1f}" y2="{ry1}" class="gr"/>')
        parts.append(f'<text x="{x:.1f}" y="{ry1 + 16}" text-anchor="middle" class="lbl">1/{N}</text>')
    parts.append(f'<rect x="{rx0}" y="{ry0}" width="{rx1 - rx0}" height="{ry1 - ry0}" fill="none" class="ax"/>')
    parts.append(f'<text x="{(rx0+rx1)/2:.1f}" y="{ry1 + 36}" text-anchor="middle" class="lbl">Grid spacing h = 1/N</text>')
    parts.append(f'<text x="506" y="{(ry0+ry1)/2:.1f}" text-anchor="middle" transform="rotate(-90 506 {(ry0+ry1)/2:.1f})" class="lbl">Relative error (λ_h − λ_true) / λ_true</text>')

    styles = {
        1: ("#5aa8ff", "k=1 (+h⁴/³ dominates)"),
        2: ("#f5b952", "k=2 (arch turnaround)"),
        3: ("#ff7a90", "k=3 (arch turnaround)"),
        9: ("#9ef0b0", "k=9 tiled (pure -h²)"),
    }
    for idx_m, k in enumerate((1, 2, 3, 9)):
        col, lbl = styles[k]
        pts_s = []
        for N, v in zip(Ns, conv[k]):
            pct = 100.0 * (v - refs[k]) / refs[k]
            pts_s.append((rx(1.0 / N), ry(pct)))
        # Include origin (0, 0)
        d = f"M {rx(0):.1f},{ry(0):.1f} " + " ".join(f"L {x:.1f},{y:.1f}" for x, y in reversed(pts_s))
        parts.append(f'<path d="{d}" fill="none" stroke="{col}" stroke-width="2.0"/>')
        for x, y in pts_s:
            parts.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="3.2" fill="{col}"/>')
        ly_leg = ry1 - 74 + idx_m * 17
        parts.append(f'<line x1="{rx0+12}" y1="{ly_leg}" x2="{rx0+28}" y2="{ly_leg}" stroke="{col}" stroke-width="2.2"/>')
        parts.append(f'<text x="{rx0+34}" y="{ly_leg+4}" class="lbl">{lbl}</text>')

    parts.append("</svg>")
    out_svg.write_text("\n".join(parts) + "\n")
    print(f"Wrote {out_svg}")


def main():
    with tempfile.TemporaryDirectory(prefix="gww_drums_") as td:
        work = Path(td)
        exe = work / "drum_solver"
        subprocess.run(
            ["gcc", "-O3", "-march=native", "-Wall", "-Wextra", str(HERE / "drum_solver.c"), "-lm", "-o", str(exe)],
            check=True,
        )
        for N in (16, 24, 32, 48, 64):
            subprocess.run([str(exe), str(N), "50", str(work / f"drum_N{N}")], check=True)
        subprocess.run([str(exe), "96", "50", str(work / "drum_N96"), "1,4,9,20"], check=True)
        build_chladni_plate(str(work / "drum_N96"), HERE / "gww_drums_chladni.png")
        build_svg(work, HERE / "gww_nodal_and_convergence.svg")


if __name__ == "__main__":
    main()
