#!/usr/bin/env python3
# Generate explanatory SVG diagrams (and optional PNG previews) for
# docs/ALGORITHM.md, overlaying exact v5_stable st-Gilbert paths from
# ref/c/stgfull with sub-box decompositions, cuts, junctions, and ports.
#
import os
import subprocess
import sys

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch, Rectangle
import numpy as np

SCRIPT_DIR  = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT   = os.path.dirname(SCRIPT_DIR)
STGFULL_BIN = os.path.join(REPO_ROOT, "ref", "c", "stgfull")
FIGS_DIR    = os.path.join(SCRIPT_DIR, "figs")
PREVIEW_DIR = "/tmp/stgilbert_fig_preview"

# Shared visual palette matching docs/style.css.
#
COL_CORNER  = "#e0f2fe"
EDG_CORNER  = "#0284c7"
COL_ONE     = "#dcfce7"
EDG_ONE     = "#16a34a"
COL_TWO     = "#fef3c7"
EDG_TWO     = "#d97706"
COL_EXC     = "#f3e8ff"
EDG_EXC     = "#7e22ce"
COL_IPS     = "#fee2e2"
EDG_IPS     = "#dc2626"

COL_PATH    = "#1e3a5f"
COL_CUT     = "#dc2626"
COL_START   = "#16a34a"
COL_END     = "#7c3aed"
COL_JUNC    = "#d97706"


# Run ref/c/stgfull and return list of (x, y) integer tuples.
#
def run_stg(w, h, s, t):
  cmd = [
    STGFULL_BIN,
    str(w), str(h),
    str(s[0]), str(s[1]),
    str(t[0]), str(t[1]),
  ]
  res   = subprocess.run(cmd, capture_output=True, text=True, check=True)
  lines = res.stdout.strip().splitlines()
  pts   = []
  for ln in lines:
    a, b = ln.split()
    pts.append((int(a), int(b)))
  if len(pts) != (w * h):
    raise RuntimeError(f"stgfull failed for {w}x{h} {s}->{t}: got {len(pts)} cells")
  return pts


# Save figure as crisp SVG in docs/figs/ and optionally PNG preview.
#
def save_fig(fig, name, preview=False):
  os.makedirs(FIGS_DIR, exist_ok=True)
  svg_path = os.path.join(FIGS_DIR, name + ".svg")
  fig.savefig(svg_path, format="svg", bbox_inches="tight", facecolor="#ffffff")
  if preview:
    os.makedirs(PREVIEW_DIR, exist_ok=True)
    png_path = os.path.join(PREVIEW_DIR, name + ".png")
    fig.savefig(png_path, format="png", dpi=150, bbox_inches="tight", facecolor="#ffffff")
  plt.close(fig)
  print("Wrote", svg_path)


# Helper to draw a shaded sub-box in grid cell coordinates [x0, x0+bw) x [y0, y0+bh).
#
def draw_box(ax, x0, y0, bw, bh, fc, ec="#475569", lw=1.2, ls="-", alpha=0.85, zorder=1):
  rect = Rectangle(
    (x0 - 0.5, y0 - 0.5), bw, bh,
    facecolor=fc, edgecolor=ec, linewidth=lw, linestyle=ls, alpha=alpha, zorder=zorder,
  )
  ax.add_patch(rect)


# Helper to draw a real path with start/end dots and optional cut-crossing markers.
#
def draw_path(ax, w, h, P, s, t, lw=1.4, ms=5.0, path_color=COL_PATH, zorder=4):
  segs = [[P[i], P[i + 1]] for i in range(len(P) - 1)]
  ax.add_collection(LineCollection(segs, colors=path_color, linewidths=lw, capstyle="round", zorder=zorder))
  ax.plot(s[0], s[1], "o", color=COL_START, ms=ms, mec="#ffffff", mew=0.8, zorder=zorder + 2)
  ax.plot(t[0], t[1], "o", color=COL_END,   ms=ms, mec="#ffffff", mew=0.8, zorder=zorder + 2)
  ax.set_aspect("equal")
  ax.set_xlim(-0.85, w - 0.15)
  ax.set_ylim(-0.85, h - 0.15)
  ax.set_xticks([])
  ax.set_yticks([])
  for sp in ax.spines.values():
    sp.set_visible(False)


# Find all edges of P crossing a vertical cut x = c (between c-1 and c)
# or horizontal cut y = r (between r-1 and r) within an optional span.
#
def find_crossings_v(P, c, y_lo=0, y_hi=10000):
  hits = []
  for i in range(len(P) - 1):
    x1, y1 = P[i]
    x2, y2 = P[i + 1]
    if (y1 == y2) and (y_lo <= y1 < y_hi):
      if ((x1 == (c - 1)) and (x2 == c)) or ((x2 == (c - 1)) and (x1 == c)):
        hits.append(((x1 + x2) / 2.0, float(y1)))
  return hits


def find_crossings_h(P, r, x_lo=0, x_hi=10000):
  hits = []
  for i in range(len(P) - 1):
    x1, y1 = P[i]
    x2, y2 = P[i + 1]
    if (x1 == x2) and (x_lo <= x1 < x_hi):
      if ((y1 == (r - 1)) and (y2 == r)) or ((y2 == (r - 1)) and (y1 == r)):
        hits.append((float(x1), (y1 + y2) / 2.0))
  return hits


# Draw junction diamonds at crossing midpoints.
#
def draw_junctions(ax, pts, ms=6.0):
  for jx, jy in pts:
    ax.plot(jx, jy, "D", color=COL_JUNC, ms=ms, mec="#ffffff", mew=0.8, zorder=8)


# Add a subtle crisp pill label inside a box.
#
def box_label(ax, cx, cy, text, color="#0f172a", fontsize=8.5):
  ax.text(
    cx, cy, text,
    ha="center", va="center", fontsize=fontsize, fontweight="bold", color=color,
    bbox=dict(boxstyle="round,pad=0.22", facecolor="#ffffff", edgecolor="#cbd5e1", alpha=0.88, lw=0.7),
    zorder=9,
  )


# ---------------------------------------------------------------------------
# Figure A: Why a Space-Filling Curve (Not Just Any Hamiltonian Path)
# ---------------------------------------------------------------------------
def make_fig_sfc(preview):
  fig, axes = plt.subplots(1, 2, figsize=(10.2, 4.3))
  fig.suptitle("Hamiltonian Path vs. Hilbert-Like Space-Filling Curve on 16x16", fontsize=11.4, fontweight="bold", y=1.01)

  w, h, s, t = 16, 16, (0, 0), (15, 0)

  # Left: naive lawnmower (boustrophedon) Hamiltonian path from (0,0) to (15,0)
  # Wait: column-by-column snake goes up col 0, down col 1, ..., down col 15 -> ends at (15,0)!
  #
  P_snake = []
  for x in range(w):
    ys = range(h) if ((x % 2) == 0) else range(h - 1, -1, -1)
    for y in ys:
      P_snake.append((x, y))
  ax = axes[0]
  draw_box(ax, 0, 0, w, h, "#fef2f2", "#fca5a5", lw=1.2)
  draw_path(ax, w, h, P_snake, s, t, lw=1.6, ms=5.5, path_color="#991b1b")
  ax.text(7.5, -1.65, "Valid Hamiltonian path, terrible space-filling curve:\nmaxRun = 16 (grows with grid), turns = 12%, bad 2D locality",
          ha="center", va="top", fontsize=8.4, color="#7f1d1d")
  ax.set_ylim(-2.5, h - 0.15)
  ax.set_title("(a) Naive Hamiltonian Snake", fontsize=9.8, fontweight="bold", pad=6)

  # Right: exact 16x16 v5_stable (Hilbert) curve
  #
  P_hilb = run_stg(w, h, s, t)
  ax = axes[1]
  draw_box(ax, 0, 0, w, h, "#f0f9ff", "#7dd3fc", lw=1.2)
  draw_path(ax, w, h, P_hilb, s, t, lw=1.6, ms=5.5, path_color=COL_PATH)
  ax.text(7.5, -1.65, "Hilbert-like space-filling curve (st-Gilbert v5_stable):\nmaxRun = 4, turns = 80%, D2 = 4.32 (tight 2D locality)",
          ha="center", va="top", fontsize=8.4, color="#0c4a6e")
  ax.set_ylim(-2.5, h - 0.15)
  ax.set_title("(b) Space-Filling Curve (st-Gilbert)", fontsize=9.8, fontweight="bold", pad=6)

  plt.tight_layout()
  save_fig(fig, "fig_sfc_vs_snake", preview)


# ---------------------------------------------------------------------------
# Figure B: The Three Universal Moves (Separate, Zoom, Peel)
# ---------------------------------------------------------------------------
def make_fig_moves(preview):
  fig, axes = plt.subplots(1, 3, figsize=(12.6, 3.8))
  fig.suptitle("The Three Universal Moves That Reduce Every Job Toward Corner Jobs", fontsize=11.4, fontweight="bold", y=1.02)

  def setup(ax, title):
    ax.set_aspect("equal")
    ax.set_xlim(-0.8, 12.8)
    ax.set_ylim(-0.8, 8.8)
    ax.set_xticks([])
    ax.set_yticks([])
    for sp in ax.spines.values():
      sp.set_visible(False)
    ax.set_title(title, fontsize=9.3, fontweight="bold", pad=6)

  # 1. Separate (sep)
  #
  ax = axes[0]
  draw_box(ax, 0, 0, 6, 8, COL_ONE, EDG_ONE, lw=1.7)
  draw_box(ax, 6, 0, 6, 8, COL_ONE, EDG_ONE, lw=1.7)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=2.0, ls="--", zorder=5)
  ax.plot([2.5, 5.0, 6.0, 9.0], [4.0, 0.4, 0.4, 4.5], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  draw_junctions(ax, [(5.5, 0.4)], ms=6.0)
  ax.plot(2.5, 4.0, "o", color=COL_START, ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.plot(9.0, 4.5, "o", color=COL_END,   ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  box_label(ax, 2.7, 6.2, "Left half\n(holds s)", fontsize=7.9)
  box_label(ax, 8.7, 6.2, "Right half\n(holds t)", fontsize=7.9)
  box_label(ax, 5.5, 2.2, "1 crossing\n(0 in 2-path)", color="#b45309", fontsize=7.4)
  setup(ax, "1. Separate (sep)\nCut straight between s and t")

  # 2. Zoom (zoom)
  #
  ax = axes[1]
  draw_box(ax, 0, 0, 6, 4.5, COL_TWO,    EDG_TWO,    lw=1.7)
  draw_box(ax, 6, 0, 6, 8.0, COL_CORNER, EDG_CORNER, lw=1.7)
  draw_box(ax, 0, 4.5, 6, 3.5, COL_CORNER, EDG_CORNER, lw=1.7)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=2.0, ls="--", zorder=5)
  ax.plot([-0.5, 5.5], [4.0, 4.0], color=COL_CUT, lw=2.0, ls="--", zorder=5)
  ax.plot([2.0, 5.0, 9.0, 9.0, 2.5, 0.4, 3.6], [1.6, 0.4, 0.4, 6.5, 6.5, 4.0, 2.4],
          color=COL_PATH, lw=1.9, ls=":", zorder=4)
  draw_junctions(ax, [(5.5, 0.4), (5.5, 6.5), (0.4, 4.0)], ms=5.5)
  ax.plot(2.0, 1.6, "o", color=COL_START, ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.plot(3.6, 2.4, "o", color=COL_END,   ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  box_label(ax, 2.7, 0.7,  "2-Path Quad", fontsize=7.4)
  box_label(ax, 8.7, 3.6,  "Outer\nCorner R1", fontsize=7.7)
  box_label(ax, 2.7, 5.9,  "Corner R2", fontsize=7.6)
  setup(ax, "2. Zoom (zoom)\nFence close ends; 3/4 is Corner bulk")

  # 3. Peel (peel)
  #
  ax = axes[2]
  draw_box(ax, 0, 0, 6, 8, COL_TWO,    EDG_TWO,    lw=1.7)
  draw_box(ax, 6, 0, 6, 8, COL_CORNER, EDG_CORNER, lw=1.7)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=2.0, ls="--", zorder=5)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5],  [7.5, 7.5],  color="#0284c7", lw=4.5, zorder=6)
  ax.plot([5.5, 5.5],   [-0.5, 1.5], color="#d97706", lw=4.5, zorder=6)
  ax.annotate("", xy=(5.7, 0.5), xytext=(11.0, 0.5),
              arrowprops=dict(arrowstyle="->", lw=2.0, color="#0369a1"))
  ax.plot(2.0, 4.8, "o", color=COL_START, ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.plot(3.8, 2.6, "o", color=COL_END,   ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  box_label(ax, 2.7, 6.2, "Smaller\n2-Path Box", fontsize=7.7)
  box_label(ax, 8.7, 4.2, "Empty Side\n-> Corner Job", fontsize=7.7)
  ax.text(8.4, 1.2, "port shifts inward", ha="center", fontsize=7.3, fontweight="bold", color="#0369a1")
  setup(ax, "3. Peel (peel, inside 2-path)\nSlice off empty side; shrink toward sep")

  plt.tight_layout()
  save_fig(fig, "fig_moves", preview)


# ---------------------------------------------------------------------------
# Figure C: Ports & Free Pairing Flag (Why flag = false vs flag = true Matters)
# ---------------------------------------------------------------------------
def make_fig_ports(preview):
  fig, axes = plt.subplots(1, 2, figsize=(11.8, 4.1))
  fig.suptitle("What Ports Are & Why Free Pairing (flag = false vs. flag = true) Works", fontsize=11.4, fontweight="bold", y=1.02)

  for idx, flag in enumerate([False, True]):
    ax = axes[idx]
    draw_box(ax, 0, 0, 7, 5, COL_TWO,    EDG_TWO,    lw=1.7)
    draw_box(ax, 7, 0, 6, 9, COL_CORNER, EDG_CORNER, lw=1.7)
    draw_box(ax, 0, 5, 7, 4, COL_CORNER, EDG_CORNER, lw=1.7)
    ax.plot([6.5, 6.5], [-0.5, 8.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
    ax.plot([-0.5, 6.5], [4.5, 4.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)

    # Port A (right edge of Q) & Port B (top edge of Q)
    #
    ax.plot([6.5, 6.5], [-0.5, 1.5], color=COL_JUNC, lw=5.0, zorder=6)
    ax.plot([-0.5, 1.5], [4.5, 4.5], color="#0284c7", lw=5.0, zorder=6)
    ax.plot(2.0, 1.8, "o", color=COL_START, ms=7.0, mec="#ffffff", mew=0.8, zorder=8)
    ax.plot(4.6, 3.0, "o", color=COL_END,   ms=7.0, mec="#ffffff", mew=0.8, zorder=8)
    ax.text(1.5, 1.8, "s", ha="right", va="center", fontsize=8.8, fontweight="bold", color=COL_START)
    ax.text(5.1, 3.0, "t", ha="left",  va="center", fontsize=8.8, fontweight="bold", color=COL_END)
    ax.text(6.1, 0.4, "port A", ha="right", va="center", fontsize=7.8, fontweight="bold", color="#92400e")
    ax.text(0.8, 3.95, "port B", ha="left", va="top",    fontsize=7.8, fontweight="bold", color="#0369a1")

    if not flag:
      # flag = false: s -> port A -> R1 -> R2 -> port B -> t (outer bridge FORWARD)
      #
      ax.annotate("", xy=(6.2, 0.5), xytext=(2.4, 1.7),
                  arrowprops=dict(arrowstyle="->", lw=2.2, color="#15803d"))
      ax.annotate("", xy=(9.6, 7.6), xytext=(7.0, 0.6),
                  arrowprops=dict(arrowstyle="->", lw=2.3, color="#0369a1", connectionstyle="arc3,rad=0.12"))
      ax.annotate("", xy=(0.6, 4.9), xytext=(9.2, 7.6),
                  arrowprops=dict(arrowstyle="->", lw=2.3, color="#0369a1", connectionstyle="arc3,rad=0.15"))
      ax.annotate("", xy=(4.3, 3.2), xytext=(0.6, 4.2),
                  arrowprops=dict(arrowstyle="->", lw=2.2, color="#6d28d9"))
      box_label(ax, 9.6, 4.2, "Outer bridge\nR1 -> R2\n(FORWARD)", fontsize=7.9, color="#0c4a6e")
      ax.set_title("(a) Pairing flag = false  (s -> port A,  port B -> t)\nGlue outer bridge FORWARD:  P1 + R1 + R2 + P2", fontsize=9.2, fontweight="bold", pad=6)
    else:
      # flag = true: s -> port B -> rev(R2) -> rev(R1) -> port A -> t (outer bridge REVERSED)
      #
      ax.annotate("", xy=(0.5, 4.2), xytext=(1.9, 2.2),
                  arrowprops=dict(arrowstyle="->", lw=2.2, color="#15803d"))
      ax.annotate("", xy=(9.2, 7.6), xytext=(0.7, 4.9),
                  arrowprops=dict(arrowstyle="->", lw=2.3, color="#b45309", connectionstyle="arc3,rad=-0.15"))
      ax.annotate("", xy=(7.0, 0.6), xytext=(9.6, 7.5),
                  arrowprops=dict(arrowstyle="->", lw=2.3, color="#b45309", connectionstyle="arc3,rad=-0.12"))
      ax.annotate("", xy=(4.8, 2.7), xytext=(6.2, 0.6),
                  arrowprops=dict(arrowstyle="->", lw=2.2, color="#6d28d9"))
      box_label(ax, 9.6, 4.2, "Outer bridge\nrev(R2) -> rev(R1)\n(REVERSED)", fontsize=7.9, color="#92400e")
      ax.set_title("(b) Pairing flag = true  (s -> port B,  port A -> t)\nGlue outer bridge REVERSED:  P1 + rev(R2) + rev(R1) + P2", fontsize=9.2, fontweight="bold", pad=6)

    ax.set_aspect("equal"); ax.set_xlim(-0.8, 13.0); ax.set_ylim(-0.8, 9.0)
    ax.set_xticks([]); ax.set_yticks([])
    for sp in ax.spines.values(): sp.set_visible(False)

  plt.tight_layout()
  save_fig(fig, "fig_ports_and_pairing", preview)


# ---------------------------------------------------------------------------
# Figure D: The Three Shared Conventions (ShapeOK, 2-Cell Junction, Mid-Out Cuts)
# ---------------------------------------------------------------------------
def make_fig_conventions(preview):
  fig, axes = plt.subplots(1, 3, figsize=(12.6, 3.6))
  fig.suptitle("The Three Shared Conventions Used Across All Core Layers", fontsize=11.4, fontweight="bold", y=1.02)

  # 1. Well-shaped boxes (ShapeOK: min >= 4, aspect <= 3)
  #
  ax = axes[0]
  draw_box(ax, 0, 4.2, 8, 4, COL_ONE, EDG_ONE, lw=1.7)
  box_label(ax, 3.5, 6.0, "Well-shaped\n(aspect 2 <= 3, min >= 4)", fontsize=7.6, color="#14532d")
  draw_box(ax, 0, 0.0, 12, 2.2, COL_IPS, EDG_IPS, lw=1.7, ls="--")
  box_label(ax, 5.5, 0.85, "Too thin! (aspect > 3 or min < 4)", fontsize=7.5, color="#991b1b")
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 12.2); ax.set_ylim(-0.8, 8.8)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("1. Well-Shaped Sub-Boxes (ShapeOK)\nSides >= 4 and aspect ratio <= 3", fontsize=9.1, fontweight="bold", pad=6)

  # 2. Parity-matching 2-cell corner junction (pickC / flipK)
  #
  ax = axes[1]
  for x in range(8):
    for y in range(6):
      fc = "#e2e8f0" if (((x + y) % 2) == 0) else "#ffffff"
      ax.add_patch(Rectangle((x - 0.5, y - 0.5), 1, 1, facecolor=fc, edgecolor="#94a3b8", lw=0.6, zorder=1))
  ax.plot([3.5, 3.5], [-0.5, 5.5], color=COL_CUT, lw=2.2, ls="--", zorder=4)
  # Highlight the 2 adjacent crossing pairs at the bottom of the cut: y=0 and y=1
  #
  ax.add_patch(Rectangle((2.5, -0.5), 1, 2, facecolor="#fef3c7", edgecolor="#d97706", lw=2.0, alpha=0.75, zorder=3))
  ax.add_patch(Rectangle((3.5, -0.5), 1, 2, facecolor="#e0f2fe", edgecolor="#0284c7", lw=2.0, alpha=0.75, zorder=3))
  ax.plot([3.1, 3.9], [0, 0], color="#d97706", lw=2.6, zorder=5)
  ax.plot([3.1, 3.9], [1, 1], color="#0284c7", lw=2.6, zorder=5)
  ax.text(2.25, 0.0, "light", ha="right", va="center", fontsize=7.6, fontweight="bold", color="#92400e", zorder=6)
  ax.text(2.25, 1.0, "dark",  ha="right", va="center", fontsize=7.6, fontweight="bold", color="#0369a1", zorder=6)
  ax.text(3.5, 3.8, "2 adjacent corner cells\n= 1 dark + 1 light\n=> always matches parity!", ha="center", va="center",
          fontsize=7.6, fontweight="bold", color="#0f172a",
          bbox=dict(boxstyle="round,pad=0.25", facecolor="#ffffff", edgecolor="#cbd5e1", alpha=0.92), zorder=7)
  ax.set_aspect("equal"); ax.set_xlim(-0.7, 7.7); ax.set_ylim(-0.7, 5.7)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("2. Parity-Matching Junctions\nOffset 0 or 1 picks exact colour needed", fontsize=9.1, fontweight="bold", pad=6)

  # 3. Centered middle-out cuts in middle third [L/3, 2L/3]
  #
  ax = axes[2]
  draw_box(ax, 0, 0, 12, 7, "#f8fafc", "#475569", lw=1.6)
  draw_box(ax, 4, 0, 4, 7, "#dbeafe", "#2563eb", lw=1.4, alpha=0.7)
  cuts = [(6.0, "1st", 0), (7.0, "2nd", 1), (5.0, "3rd", 2), (8.0, "4th", 3), (4.0, "5th", 4)]
  for cx, lbl, k in cuts:
    lw = 2.2 if (k == 0) else 1.2
    ax.plot([cx - 0.5, cx - 0.5], [-0.5, 6.5], color=COL_CUT if (k == 0) else "#2563eb",
            lw=lw, ls="--" if (k > 0) else "-", zorder=5)
    ax.text(cx - 0.5, 6.75 + (0.72 * (k % 2)), lbl, ha="center", va="bottom",
            fontsize=7.5, fontweight="bold", color="#dc2626" if (k == 0) else "#1e40af", zorder=6)
  ax.text(5.5, -1.0, "middle third [L/3, 2L/3]", ha="center", va="top", fontsize=8.0, fontweight="bold", color="#1e40af")
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 12.2); ax.set_ylim(-1.6, 8.6)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("3. Centered Middle-Out Cuts (midOut)\nTry nearest L/2 first inside [L/3, 2L/3]", fontsize=9.1, fontweight="bold", pad=6)

  plt.tight_layout()
  save_fig(fig, "fig_conventions", preview)


# ---------------------------------------------------------------------------
# Figure 0: The Four Job Types & How They Call Each Other (Big Picture Map)
# ---------------------------------------------------------------------------
def make_fig00(preview):
  fig, axes = plt.subplots(1, 4, figsize=(13.0, 3.4))
  fig.suptitle("The Four Building-Block Job Types (Every Cut Reduces Toward Corner Jobs)", fontsize=11.3, fontweight="bold", y=1.03)

  def setup(ax, title):
    ax.set_aspect("equal")
    ax.set_xlim(-0.8, 10.8)
    ax.set_ylim(-0.8, 8.8)
    ax.set_xticks([])
    ax.set_yticks([])
    for sp in ax.spines.values():
      sp.set_visible(False)
    ax.set_title(title, fontsize=9.0, pad=5)

  # 1. Corner job
  #
  ax = axes[0]
  draw_box(ax, 0, 0, 10, 8, COL_CORNER, EDG_CORNER, lw=1.8)
  ax.plot([0, 0, 9, 9], [0, 7, 7, 0], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(0, 0, "o", color=COL_START, ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.plot(9, 0, "o", color=COL_END,   ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  box_label(ax, 4.5, 3.8, "Corner Job\n(stPath)\nHilbert bulk", fontsize=8.0)
  setup(ax, "1. Corner Job\nBoth ends near corners")

  # 2. One-interior job
  #
  ax = axes[1]
  draw_box(ax, 0, 0, 10, 8, COL_ONE, EDG_ONE, lw=1.8)
  ax.plot([0, 2, 6], [0, 5, 4.5], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(0, 0,   "o", color=COL_START, ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.plot(6, 4.5, "o", color=COL_END,   ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  box_label(ax, 4.5, 1.8, "One-Interior\n(onePath / S)", fontsize=8.0)
  setup(ax, "2. One-Interior Job\nOne end near corner, one inside")

  # 3. Two-interior job
  #
  ax = axes[2]
  draw_box(ax, 0, 0, 10, 8, "#e0e7ff", "#4f46e5", lw=1.8)
  ax.plot([2.5, 4.5, 7.0], [3.0, 5.5, 4.2], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(2.5, 3.0, "o", color=COL_START, ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.plot(7.0, 4.2, "o", color=COL_END,   ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  box_label(ax, 4.5, 1.5, "Two-Interior\n(tCan / T)", fontsize=8.0)
  setup(ax, "3. Two-Interior Job\nBoth ends anywhere inside")

  # 4. Two-path job (Z or W)
  #
  ax = axes[3]
  draw_box(ax, 0, 0, 10, 8, COL_TWO, EDG_TWO, lw=1.8)
  ax.plot([9.5, 9.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5], [7.5, 7.5], color="#0284c7", lw=4.5, zorder=6)
  ax.plot([2.8, 0.5], [3.5, 7.2], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot([6.2, 9.2], [4.5, 0.4], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(2.8, 3.5, "o", color=COL_START, ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.plot(6.2, 4.5, "o", color=COL_END,   ms=6.5, mec="#ffffff", mew=0.8, zorder=7)
  ax.text(1.8, 7.2, "port B", fontsize=7.6, fontweight="bold", color="#0369a1", va="top")
  ax.text(9.0, 0.6, "port A", fontsize=7.6, fontweight="bold", color="#92400e", ha="right")
  box_label(ax, 4.5, 1.5, "Two-Path (Z / W)\nfree pairing to ports", fontsize=7.7)
  setup(ax, "4. Two-Path Job (Z or W)\n2 disjoint paths to border ports")

  plt.tight_layout()
  save_fig(fig, "fig00_four_job_types", preview)


# ---------------------------------------------------------------------------
# Figure 1: Checkerboard Colour Parity & Thin-Strip IPS Obstruction
# ---------------------------------------------------------------------------
def make_fig01(preview):
  fig, axes = plt.subplots(1, 3, figsize=(11.5, 3.6))
  fig.suptitle("Checkerboard Colour Compatibility (Compat) and Thin-Strip Obstruction (IpsAcc)", fontsize=11.5, fontweight="bold", y=1.01)

  # Helper to draw checkerboard cells.
  #
  def draw_board(ax, w, h):
    for x in range(w):
      for y in range(h):
        fc = "#e2e8f0" if (((x + y) % 2) == 0) else "#ffffff"
        ax.add_patch(Rectangle((x - 0.5, y - 0.5), 1, 1, facecolor=fc, edgecolor="#94a3b8", lw=0.7, zorder=1))
    ax.add_patch(Rectangle((-0.5, -0.5), w, h, facecolor="none", edgecolor="#334155", lw=1.6, zorder=2))
    ax.set_aspect("equal")
    ax.set_xlim(-0.7, w - 0.3)
    ax.set_ylim(-0.7, h - 0.3)
    ax.set_xticks([])
    ax.set_yticks([])
    for sp in ax.spines.values():
      sp.set_visible(False)

  # (a) Odd grid 5x5: 13 dark (col 0), 12 light (col 1) -> both ends must be dark.
  #
  ax = axes[0]
  draw_board(ax, 5, 5)
  P = run_stg(5, 5, (0, 0), (4, 4))
  draw_path(ax, 5, 5, P, (0, 0), (4, 4), lw=2.0, ms=6.5)
  ax.set_title("(a) Odd area (5x5: 13 dark, 12 light)\nValid: both ends dark (col = 0)", fontsize=9.2, pad=6)

  # (b) Even grid 6x4: 12 dark, 12 light -> ends must have opposite colours.
  #
  ax = axes[1]
  draw_board(ax, 6, 4)
  P = run_stg(6, 4, (0, 0), (4, 3))
  draw_path(ax, 6, 4, P, (0, 0), (4, 3), lw=2.0, ms=6.5)
  ax.set_title("(b) Even area (6x4: 12 dark, 12 light)\nValid: opposite colours (col 0 vs 1)", fontsize=9.2, pad=6)

  # (c) Thin-strip obstruction: 3x6 with colour-compatible (1,1) and (2,0)
  # Wait: check 2x6 with (2,0) and (2,1) (adjacent vertical separator cutting 2x6!).
  #
  ax = axes[2]
  draw_board(ax, 6, 2)
  # Highlight the left 2x2 component disconnected from right 2x3 component.
  #
  ax.add_patch(Rectangle((-0.5, -0.5), 2, 2, facecolor="#fee2e2", edgecolor="#dc2626", lw=1.5, alpha=0.55, zorder=2))
  ax.add_patch(Rectangle((2.5, -0.5), 3, 2, facecolor="#fef3c7", edgecolor="#d97706", lw=1.5, alpha=0.55, zorder=2))
  ax.plot(2, 0, "o", color=COL_START, ms=7.5, mec="#ffffff", mew=0.9, zorder=6)
  ax.plot(2, 1, "o", color=COL_END,   ms=7.5, mec="#ffffff", mew=0.9, zorder=6)
  ax.text(0.5, 0.5, "isolated\nleft", ha="center", va="center", fontsize=8.5, fontweight="bold", color="#991b1b", zorder=7)
  ax.text(4.0, 0.5, "isolated\nright", ha="center", va="center", fontsize=8.5, fontweight="bold", color="#92400e", zorder=7)
  ax.set_title("(c) Thin obstruction (2x6, min <= 3)\nColour-compatible, yet IPS-forbidden", fontsize=9.2, pad=6)

  plt.tight_layout()
  save_fig(fig, "fig01_checkerboard_parity", preview)


# ---------------------------------------------------------------------------
# Figure 2: Top-Level Dispatch Map in (short side u, aspect ratio alpha) Space
# ---------------------------------------------------------------------------
def make_fig02(preview):
  fig, ax = plt.subplots(figsize=(9.5, 4.6))

  # Draw 4 dispatch zones on u in [1, 45], alpha in [1, 6.5].
  #
  # 1) u <= 3.5 (min <= 3): ipsBox
  #
  ax.add_patch(Rectangle((0.5, 1.0), 3.0, 5.5, facecolor=COL_IPS, edgecolor=EDG_IPS, lw=1.6, alpha=0.85))
  ax.text(2.0, 3.75, "min <= 3\nipsBox\n(IPS solver)", ha="center", va="center",
          fontsize=9.2, fontweight="bold", color="#991b1b", rotation=90)

  # 2) u >= 4, alpha <= 9/4 = 2.25: stgPath
  # Split visually at u = 20 to show proved-no-fallback boundary.
  #
  ax.add_patch(Rectangle((3.5, 1.0), 16.0, 1.25, facecolor="#dbeafe", edgecolor="#2563eb", lw=1.6, alpha=0.85))
  ax.add_patch(Rectangle((19.5, 1.0), 25.5, 1.25, facecolor=COL_CORNER, edgecolor=EDG_CORNER, lw=1.6, alpha=0.9))
  ax.axvline(19.5, ymin=0.0, ymax=1.0, color="#475569", lw=1.2, ls="--")
  ax.text(11.5, 1.62, "stgPath (4 <= u <= 19, asp <= 9/4)\nstgRules + ipsBox fallback\nD2 <= 56, run <= 42",
          ha="center", va="center", fontsize=8.6, fontweight="bold", color="#1e3a8a")
  ax.text(32.2, 1.62, "stgPath (u >= 20, asp <= 9/4)\nstgRules ONLY (no fallback proved!)\nD2 <= 56, run <= 22 (12 corner / 17 one-int)",
          ha="center", va="center", fontsize=9.0, fontweight="bold", color="#0c4a6e")

  # 3) 4 <= u <= 19, alpha > 9/4: narrowPath
  #
  ax.add_patch(Rectangle((3.5, 2.25), 16.0, 4.25, facecolor=COL_EXC, edgecolor=EDG_EXC, lw=1.6, alpha=0.85))
  ax.text(11.5, 4.38, "narrowPath\n(4 <= u <= 19, asp > 9/4)\n\nnCore + excTile\ncorner-edge splices\nrun <= 41\nD2 <= 94 + 197(1 + asp)",
          ha="center", va="center", fontsize=9.0, fontweight="bold", color="#581c87")

  # 4) u >= 20, alpha > 9/4: longPath
  #
  ax.add_patch(Rectangle((19.5, 2.25), 25.5, 4.25, facecolor=COL_ONE, edgecolor=EDG_ONE, lw=1.6, alpha=0.85))
  ax.text(32.2, 4.38, "longPath\n(u >= 20, asp > 9/4)\n\nlcGo / lsGo / ltCan\n(ltSplit, bandCan, ringO / ringP)\nrun <= 24\nD2 <= 94 + 197(1 + asp)",
          ha="center", va="center", fontsize=9.2, fontweight="bold", color="#14532d")

  # Threshold annotations.
  #
  ax.axhline(2.25, color="#dc2626", lw=1.8, ls="-")
  ax.text(44.6, 2.34, "aspect = 9/4 = 2.25", ha="right", va="bottom", fontsize=8.8, fontweight="bold", color="#dc2626")

  ax.set_xlim(0.5, 45.0)
  ax.set_ylim(1.0, 6.5)
  ax.set_xticks([1, 3.5, 10, 19.5, 30, 40])
  ax.set_xticklabels(["1", "3 | 4", "10", "19 | 20", "30", "40+"])
  ax.set_yticks([1.0, 1.5, 2.25, 3.0, 4.0, 5.0, 6.0])
  ax.set_yticklabels(["1.0", "1.5", "2.25\n(9/4)", "3.0", "4.0", "5.0", "6.0+"])
  ax.set_xlabel("Short side  u = min(w, h)", fontsize=10, fontweight="bold")
  ax.set_ylabel("Aspect ratio  alpha = max(w, h) / min(w, h)", fontsize=10, fontweight="bold")
  ax.set_title("Top-Level Dispatch Regimes of stgFull(B, s, t)", fontsize=11.5, fontweight="bold", pad=10)
  ax.spines["top"].set_visible(False)
  ax.spines["right"].set_visible(False)

  plt.tight_layout()
  save_fig(fig, "fig02_dispatch_map", preview)


# ---------------------------------------------------------------------------
# Figure 3: Layer 1 (stPath) — Corner Control Paths on Real v5_stable Curves
# ---------------------------------------------------------------------------
def make_fig03(preview):
  fig, axes = plt.subplots(2, 2, figsize=(11.2, 8.2))
  fig.suptitle("Layer 1 (stPath): Corner Job Decomposition Rules (Real v5_stable Curves)", fontsize=11.5, fontweight="bold", y=0.995)

  # (a) Rule 3 (case3): 16x16, (0,0)->(15,0), r3h(16)=8, w/2=8.
  #
  ax = axes[0, 0]
  w, h, s, t = 16, 16, (0, 0), (15, 0)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0, 0, 8,  8, COL_CORNER, EDG_CORNER)
  draw_box(ax, 8, 0, 8,  8, COL_CORNER, EDG_CORNER)
  draw_box(ax, 0, 8, 16, 8, COL_ONE,    EDG_ONE)
  ax.plot([-0.5, 15.5], [7.5, 7.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  ax.plot([7.5, 7.5], [-0.5, 7.5],  color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.55, ms=5.5)
  draw_junctions(ax, find_crossings_h(P, 8))
  box_label(ax, 3.5, 3.5,  "B1 (w/2 x r)")
  box_label(ax, 11.5, 3.5, "B3 (rem x r)")
  box_label(ax, 7.5, 11.5, "B2 (w x (h - r))")
  ax.set_title("(a) Rule 3 (case3): same bottom edge, 2w <= 3h\n16x16 (0,0)->(15,0), cut r = 8, w/2 = 8", fontsize=9.3, pad=6)

  # (b) Rule 3 transposed: 16x12, (0,0)->(0,11) (same left edge, 2*16 <= 3*12).
  # In B.T (12x16), r3h(16)=8 along x, w_T/2=6 along y -> x=8, y=6 on left.
  #
  ax = axes[0, 1]
  w, h, s, t = 16, 12, (0, 0), (0, 11)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0, 0, 8, 6,  COL_CORNER, EDG_CORNER)
  draw_box(ax, 0, 6, 8, 6,  COL_CORNER, EDG_CORNER)
  draw_box(ax, 8, 0, 8, 12, COL_ONE,    EDG_ONE)
  ax.plot([7.5, 7.5], [-0.5, 11.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  ax.plot([-0.5, 7.5], [5.5, 5.5],  color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.55, ms=5.5)
  draw_junctions(ax, find_crossings_v(P, 8))
  box_label(ax, 3.5, 2.5,  "B1")
  box_label(ax, 3.5, 8.5,  "B3")
  box_label(ax, 11.5, 5.5, "B2 (full h)")
  ax.set_title("(b) Rule 3 transposed: same left edge, 2w <= 3h\n16x12 (0,0)->(0,11), cut x = 8, y = 6", fontsize=9.3, pad=6)

  # (c) Rule 1 (case1): 24x12, (0,0)->(23,0), 2w > 3h -> cut1(24,12) = 12.
  #
  ax = axes[1, 0]
  w, h, s, t = 24, 12, (0, 0), (23, 0)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0,  0, 12, 12, COL_CORNER, EDG_CORNER)
  draw_box(ax, 12, 0, 12, 12, COL_ONE,    EDG_ONE)
  ax.plot([11.5, 11.5], [-0.5, 11.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.45, ms=5.5)
  draw_junctions(ax, find_crossings_v(P, 12))
  box_label(ax, 5.5, 6.0,  "Left (cut1 x h)")
  box_label(ax, 17.5, 6.0, "Right ((w - cut1) x h)")
  ax.set_title("(c) Rule 1 (case1): opposite sides, 2w > 3h\n24x12 (0,0)->(23,0), cut c = 12, bottom junction", fontsize=9.3, pad=6)

  # (d) Rule 2b (case2b): 24x12? Wait: 2*24=48 > 3*12=36! cs2b(24,12) = min(12, 18) = 12.
  # Since cs2b=12 > 11, left strip is split horizontally at h/2 = 6.
  #
  ax = axes[1, 1]
  w, h, s, t = 24, 12, (0, 0), (0, 11)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0,  0, 12, 6,  COL_CORNER, EDG_CORNER)
  draw_box(ax, 0,  6, 12, 6,  COL_CORNER, EDG_CORNER)
  draw_box(ax, 12, 0, 12, 12, COL_TWO,    EDG_TWO)
  ax.plot([11.5, 11.5], [-0.5, 11.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  ax.plot([-0.5, 11.5], [5.5, 5.5],   color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.45, ms=5.5)
  draw_junctions(ax, find_crossings_v(P, 12))
  box_label(ax, 5.5, 2.5,  "Strip lo")
  box_label(ax, 5.5, 8.5,  "Strip hi")
  box_label(ax, 17.5, 5.5, "Rest ((w - cs) x h)")
  ax.set_title("(d) Rule 2b (case2b): same short side, 2w > 3h\n24x12 (0,0)->(0,11), even strip cs = 12 + rest", fontsize=9.3, pad=6)

  plt.tight_layout(rect=[0, 0, 1, 0.96])
  save_fig(fig, "fig03_corner_rules", preview)


# ---------------------------------------------------------------------------
# Figure 4: Why Rule 3 (3 boxes) + Rule 1 (2 boxes) = Exact 4-Quadrant Hilbert
# ---------------------------------------------------------------------------
def make_fig04(preview):
  fig, axes = plt.subplots(1, 3, figsize=(11.5, 3.8))
  fig.suptitle("Why 3-Box Rule 3 + 2-Box Rule 1 Produces the Exact 4-Quadrant 2D Hilbert Curve", fontsize=11.2, fontweight="bold", y=1.01)

  # Stage 1: Rule 3 on 2^k x 2^k
  #
  ax = axes[0]
  draw_box(ax, 0, 0, 8,  8, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 8, 0, 8,  8, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 8, 16, 8, COL_TWO,    EDG_TWO,    lw=1.6)
  ax.plot([0, 0, 15, 15], [0, 8.5, 8.5, 0], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(0, 0, "o", color=COL_START, ms=6.5, zorder=6)
  ax.plot(15, 0, "o", color=COL_END, ms=6.5, zorder=6)
  draw_junctions(ax, [(0, 7.5), (15, 7.5)], ms=6.5)
  box_label(ax, 3.5, 3.5, "Q0\n(2^(k-1))^2")
  box_label(ax, 11.5, 3.5, "Q3\n(2^(k-1))^2")
  box_label(ax, 7.5, 11.5, "B2: 2^k x 2^(k-1)\n(aspect 2 > 3/2!)")
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 15.8); ax.set_ylim(-0.8, 15.8)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("Step 1: Rule 3 (case3)\nSplits 2^k x 2^k into Q0, B2, Q3", fontsize=9.2, pad=6)

  # Stage 2: B2 has aspect 2 > 3/2 -> immediately triggers Rule 1 (case1)
  #
  ax = axes[1]
  draw_box(ax, 0, 0, 8, 8, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 8, 0, 8, 8, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 8, 8, 8, COL_ONE,    EDG_ONE,    lw=1.6)
  draw_box(ax, 8, 8, 8, 8, COL_ONE,    EDG_ONE,    lw=1.6)
  ax.plot([7.5, 7.5], [7.5, 15.5], color=COL_CUT, lw=2.2, ls="--", zorder=5)
  ax.plot([0, 0, 7, 8, 15, 15], [0, 8, 8, 8, 8, 0], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(0, 0, "o", color=COL_START, ms=6.5, zorder=6)
  ax.plot(15, 0, "o", color=COL_END, ms=6.5, zorder=6)
  draw_junctions(ax, [(0, 7.5), (7.5, 8.0), (15, 7.5)], ms=6.5)
  box_label(ax, 3.5, 3.5,  "Q0 (rot)")
  box_label(ax, 3.5, 11.5, "Q1")
  box_label(ax, 11.5, 11.5,"Q2")
  box_label(ax, 11.5, 3.5, "Q3 (rot)")
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 15.8); ax.set_ylim(-0.8, 15.8)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("Step 2: Rule 1 (case1) on B2\nYields 4 exact Hilbert quadrants", fontsize=9.2, pad=6)

  # Stage 3: Actual 16x16 v5_stable output with quadrant grid
  #
  ax = axes[2]
  P = run_stg(16, 16, (0, 0), (15, 0))
  draw_box(ax, 0, 0, 8, 8, COL_CORNER, EDG_CORNER, alpha=0.45)
  draw_box(ax, 8, 0, 8, 8, COL_CORNER, EDG_CORNER, alpha=0.45)
  draw_box(ax, 0, 8, 8, 8, COL_ONE,    EDG_ONE,    alpha=0.45)
  draw_box(ax, 8, 8, 8, 8, COL_ONE,    EDG_ONE,    alpha=0.45)
  draw_path(ax, 16, 16, P, (0, 0), (15, 0), lw=1.7, ms=5.5)
  draw_junctions(ax, [(0, 7.5), (7.5, 8.0), (15, 7.5)], ms=6.0)
  ax.set_title("Step 3: Actual 16x16 stPath output\nExact classic 2D Hilbert curve", fontsize=9.2, pad=6)

  plt.tight_layout()
  save_fig(fig, "fig04_hilbert_recursion", preview)


# ---------------------------------------------------------------------------
# Figure 5: Layer 2 (onePath) — All 4 S-Job Control Paths
# ---------------------------------------------------------------------------
def make_fig05(preview):
  fig, axes = plt.subplots(2, 2, figsize=(11.2, 8.4))
  fig.suptitle("Layer 2 (onePath): S-Job Control Paths (One Corner End pi, One Interior End x)", fontsize=11.5, fontweight="bold", y=0.995)

  # (a) S lsplit: 16x16, pi=(0,0), x=(4,11) -> bottom-left C1 [0,8)x[0,8),
  # right C2 [8,16)x[0,16), top-left S [0,8)x[8,16) containing x.
  #
  ax = axes[0, 0]
  w, h, s, t = 16, 16, (0, 0), (4, 11)
  P = run_stg(w, h, s, t)
  c8  = find_crossings_v(P, 8)
  r8l = find_crossings_h(P, 8, 0, 8)
  assert (len(c8) == 2) and (len(r8l) == 0), f"Unexpected crossings for lsplit: {c8}, {r8l}"
  draw_box(ax, 0, 0, 8, 8,  COL_CORNER, EDG_CORNER)
  draw_box(ax, 8, 0, 8, 16, COL_CORNER, EDG_CORNER)
  draw_box(ax, 0, 8, 8, 8,  COL_ONE,    EDG_ONE)
  ax.plot([7.5, 7.5], [-0.5, 15.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  ax.plot([-0.5, 7.5], [7.5, 7.5],  color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.55, ms=5.5)
  draw_junctions(ax, c8)
  box_label(ax, 3.5, 3.5,  "C1 (Corner)")
  box_label(ax, 11.5, 7.5, "C2 (Corner)")
  box_label(ax, 3.5, 13.5, "S (pi'->x)")
  ax.set_title("(a) S lsplit (near-square priority, 2 max <= 3 min)\n16x16 pi=(0,0), x=(4,11): C1 -> C2 -> S", fontsize=9.2, pad=6)

  # (b) S sep: elongated box 24x12 (2*24 > 3*12), pi=(0,0), x=(17,6) -> vertical sep at c=12.
  #
  ax = axes[0, 1]
  w, h, s, t = 24, 12, (0, 0), (17, 6)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0,  0, 12, 12, COL_CORNER, EDG_CORNER)
  draw_box(ax, 12, 0, 12, 12, COL_ONE,    EDG_ONE)
  ax.plot([11.5, 11.5], [-0.5, 11.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.45, ms=5.5)
  draw_junctions(ax, find_crossings_v(P, 12))
  box_label(ax, 5.5, 5.5,  "Corner C")
  box_label(ax, 17.5, 9.0, "S (j -> x)")
  ax.set_title("(b) S sep (elongated box, 2 max > 3 min)\n24x12 pi=(0,0), x=(17,6): cut c = 12, C -> S", fontsize=9.2, pad=6)

  # (c) S zoom: 16x16, pi=(0,0), x=(3,3) -> x in bottom-left [0,8)x[0,8), so lsplit & sep fail
  # on [0,8)x[0,8) and S zoom fires! Verify crossings at x=8 and y=8.
  #
  ax = axes[1, 0]
  w, h, s, t = 16, 16, (0, 0), (3, 4)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0, 0, 8, 8,  COL_TWO,    EDG_TWO)
  draw_box(ax, 8, 0, 8, 16, COL_CORNER, EDG_CORNER)
  draw_box(ax, 0, 8, 8, 8,  COL_CORNER, EDG_CORNER)
  ax.plot([7.5, 7.5], [-0.5, 15.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  ax.plot([-0.5, 7.5], [7.5, 7.5],  color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.55, ms=5.5)
  draw_junctions(ax, find_crossings_v(P, 8) + find_crossings_h(P, 8, 0, 8))
  box_label(ax, 3.8, 5.8,  "Z (2-path)")
  box_label(ax, 11.5, 7.5, "PR (Corner)")
  box_label(ax, 3.5, 11.5, "PT (Corner)")
  ax.set_title("(c) S zoom (x near pi's corner, no sep/lsplit)\n16x16 pi=(0,0), x=(3,4): Z + PR + PT", fontsize=9.2, pad=6)

  # (d) S uturn: schematic of thin-box U-turn (left zLeaf strip + right Corner).
  #
  ax = axes[1, 1]
  draw_box(ax, 0, 0, 6, 7, COL_TWO,    EDG_TWO,    lw=1.6)
  draw_box(ax, 6, 0, 10, 7, COL_CORNER, EDG_CORNER, lw=1.6)
  ax.plot([5.5, 5.5], [-0.5, 6.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([0, 5, 6, 14, 14, 6, 5, 2], [0, 0, 0, 0, 6, 6, 6, 3], color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(0, 0, "o", color=COL_START, ms=6.5, zorder=6)
  ax.plot(2, 3, "o", color=COL_END,   ms=6.5, zorder=6)
  draw_junctions(ax, [(5.5, 0.0), (5.5, 6.0)], ms=6.5)
  box_label(ax, 2.5, 4.6,  "tabZs\n(2-path leaf)")
  box_label(ax, 10.5, 3.0, "PR (Corner job)")
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 15.8); ax.set_ylim(-0.8, 6.8)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("(d) S uturn (thin box fallback, e.g. 16x7)\nLeft even zLeaf strip (tabZs) + right Corner PR", fontsize=9.2, pad=6)

  plt.tight_layout(rect=[0, 0, 1, 0.96])
  save_fig(fig, "fig05_one_s_rules", preview)


# ---------------------------------------------------------------------------
# Figure 6: Layer 2 — Z Two-Path Rules & Colour-Bit Invariance
# ---------------------------------------------------------------------------
def make_fig06(preview):
  fig, axes = plt.subplots(1, 5, figsize=(13.5, 2.9))
  fig.suptitle("Layer 2 (Z Jobs): Two-Path Decomposition Rules on Even U x V (U >= V)", fontsize=11.0, fontweight="bold", y=1.03)

  def setup(ax, title):
    ax.set_aspect("equal")
    ax.set_xlim(-0.8, 12.8)
    ax.set_ylim(-0.8, 8.8)
    ax.set_xticks([])
    ax.set_yticks([])
    for sp in ax.spines.values(): sp.set_visible(False)
    ax.set_title(title, fontsize=8.8, pad=5)

  def ports_and_pi(ax):
    ax.plot(0, 0, "o", color=COL_START, ms=5.5, zorder=7)
    ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.0, zorder=6)
    ax.plot([-0.5, 1.5], [7.5, 7.5],   color=COL_JUNC, lw=4.0, zorder=6)
    ax.text(11.1, 0.5, "E1", ha="right", va="center", fontsize=7.5, fontweight="bold", color="#92400e", zorder=8)
    ax.text(0.8, 6.9,  "E2", ha="left",  va="top",    fontsize=7.5, fontweight="bold", color="#92400e", zorder=8)

  # 1. hsplit
  #
  ax = axes[0]
  draw_box(ax, 0, 0, 12, 4, COL_CORNER, EDG_CORNER)
  draw_box(ax, 0, 4, 12, 4, COL_ONE,    EDG_ONE)
  ax.plot([-0.5, 11.5], [3.5, 3.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  ports_and_pi(ax)
  ax.plot(9.6, 5.8, "o", color=COL_END, ms=5.5, zorder=7)
  box_label(ax, 5.5, 1.5, "C (pi->E1)", fontsize=7.6)
  box_label(ax, 5.2, 5.5, "S (E2->x)",  fontsize=7.6)
  setup(ax, "1. hsplit (t=false)\n[!zWide, r <= x.y]")

  # 2. vsplit
  #
  ax = axes[1]
  draw_box(ax, 0, 0, 6, 8, COL_CORNER, EDG_CORNER)
  draw_box(ax, 6, 0, 6, 8, COL_ONE,    EDG_ONE)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  ports_and_pi(ax)
  ax.plot(9, 4, "o", color=COL_END, ms=5.5, zorder=7)
  box_label(ax, 2.5, 3.5, "C\n(pi->E2)", fontsize=7.4)
  box_label(ax, 8.5, 5.8, "S\n(E1->x)",  fontsize=7.4)
  setup(ax, "2. vsplit (t=true)\n[c <= x.x]")

  # 3. zoom
  #
  ax = axes[2]
  draw_box(ax, 0, 0, 6, 4, COL_TWO,    EDG_TWO)
  draw_box(ax, 6, 0, 6, 8, COL_CORNER, EDG_CORNER)
  draw_box(ax, 0, 4, 6, 4, COL_CORNER, EDG_CORNER)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  ax.plot([-0.5, 5.5], [3.5, 3.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  ports_and_pi(ax)
  ax.plot(3.9, 2.3, "o", color=COL_END, ms=5.5, zorder=7)
  draw_junctions(ax, [(5.5, 0.2), (0.2, 3.5)], ms=5.0)
  box_label(ax, 2.0, 1.3, "Z", fontsize=7.6)
  box_label(ax, 8.5, 4.0, "PR", fontsize=7.6)
  box_label(ax, 2.8, 5.5, "PT", fontsize=7.6)
  setup(ax, "3. zoom (recurse Z)\n[!zWide, x in quad]")

  # 4. vpeel
  #
  ax = axes[3]
  draw_box(ax, 0, 0, 6, 8, COL_TWO,    EDG_TWO)
  draw_box(ax, 6, 0, 6, 8, COL_CORNER, EDG_CORNER)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  ports_and_pi(ax)
  ax.plot(3, 5, "o", color=COL_END, ms=5.5, zorder=7)
  draw_junctions(ax, [(5.5, 0.2)], ms=5.0)
  box_label(ax, 2.5, 3.0, "Z'", fontsize=7.6)
  box_label(ax, 8.5, 4.0, "PR\n(Corner)", fontsize=7.4)
  setup(ax, "4. vpeel (right)\n[x.x < c]")

  # 5. hpeel
  #
  ax = axes[4]
  draw_box(ax, 0, 0, 12, 4, COL_TWO,    EDG_TWO)
  draw_box(ax, 0, 4, 12, 4, COL_CORNER, EDG_CORNER)
  ax.plot([-0.5, 11.5], [3.5, 3.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  ports_and_pi(ax)
  ax.plot(7, 1.8, "o", color=COL_END, ms=5.5, zorder=7)
  draw_junctions(ax, [(0.2, 3.5)], ms=5.0)
  box_label(ax, 5.5, 1.5, "Z'", fontsize=7.6)
  box_label(ax, 6.0, 5.5, "PT (Corner)", fontsize=7.6)
  setup(ax, "5. hpeel (top)\n[!zWide, x.y < r]")

  plt.tight_layout()
  save_fig(fig, "fig06_one_z_rules", preview)


# ---------------------------------------------------------------------------
# Figure 7: Layer 3 (wGo) — W Layouts O & P, Trapped Corners, Sep & Peel
# ---------------------------------------------------------------------------
def make_fig07(preview):
  fig, axes = plt.subplots(1, 4, figsize=(12.8, 3.3))
  fig.suptitle("Layer 3 (wGo): Canonical W Layouts, Trapped Corners (wTrap), and Sep / Peel Steps", fontsize=11.0, fontweight="bold", y=1.03)

  def setup(ax, title):
    ax.set_aspect("equal")
    ax.set_xlim(-0.8, 12.8)
    ax.set_ylim(-0.8, 8.8)
    ax.set_xticks([])
    ax.set_yticks([])
    for sp in ax.spines.values(): sp.set_visible(False)
    ax.set_title(title, fontsize=8.8, pad=5)

  # (a) Layout O vs Layout P + trapped corner illustration
  #
  ax = axes[0]
  draw_box(ax, 0, 0, 12, 8, COL_TWO, EDG_TWO, lw=1.6)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5], [7.5, 7.5],   color="#0284c7", lw=4.5, zorder=6)
  ax.plot([-0.5, -0.5], [5.5, 7.5],  color="#7e22ce", lw=4.5, zorder=6)
  # Trapped corner (0,0) pinched by s=(1,0) and t=(0,1).
  #
  ax.add_patch(Rectangle((-0.5, -0.5), 1, 1, facecolor="#fee2e2", edgecolor="#dc2626", lw=1.6, zorder=5))
  ax.plot(1, 0, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(0, 1, "o", color=COL_END,   ms=6.0, zorder=7)
  ax.text(2.0, 0.2, "trapped\ncorner!", fontsize=7.6, fontweight="bold", color="#991b1b", va="bottom")
  ax.text(11.1, 0.6, "pa", ha="right", fontsize=8.0, fontweight="bold", color="#92400e")
  ax.text(1.7, 7.2, "pb (O)", ha="left", va="top", fontsize=7.8, fontweight="bold", color="#0369a1")
  ax.text(0.1, 5.4, "pb (P)", ha="left", va="top", fontsize=7.8, fontweight="bold", color="#6b21a8")
  setup(ax, "(a) Layouts O/P & wTrap\nBoth ends cannot pinch a corner")

  # (b) W sepx
  #
  ax = axes[1]
  draw_box(ax, 0, 0, 6, 8, COL_ONE, EDG_ONE)
  draw_box(ax, 6, 0, 6, 8, COL_ONE, EDG_ONE)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5], [7.5, 7.5],   color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot(2.5, 3.0, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(8.5, 4.5, "o", color=COL_END,   ms=6.0, zorder=7)
  box_label(ax, 2.5, 5.2, "onePath\n(pb->s)", fontsize=7.6)
  box_label(ax, 8.5, 2.2, "onePath\n(pa->t)", fontsize=7.6)
  setup(ax, "(b) W sepx / sepy\nSeparates s, t into two onePath")

  # (c) W peelx (ends right -> corner job left from pb, child P on right)
  #
  ax = axes[2]
  draw_box(ax, 0, 0, 6, 8, COL_CORNER, EDG_CORNER)
  draw_box(ax, 6, 0, 6, 8, COL_TWO,    EDG_TWO)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5], [7.5, 7.5],   color=COL_JUNC, lw=4.5, zorder=6)
  draw_junctions(ax, [(5.5, 7.0)], ms=5.5)
  ax.plot(8.0, 2.5, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(9.5, 5.0, "o", color=COL_END,   ms=6.0, zorder=7)
  box_label(ax, 2.5, 3.5, "PR\n(Corner)", fontsize=7.6)
  box_label(ax, 8.8, 6.8, "Child W\n(Layout P)", fontsize=7.3)
  setup(ax, "(c) W peelx (ends right)\nPeel left -> child becomes P")

  # (d) W peely (ends bottom -> corner job top from pb, child O on bottom)
  #
  ax = axes[3]
  draw_box(ax, 0, 0, 12, 4, COL_TWO,    EDG_TWO)
  draw_box(ax, 0, 4, 12, 4, COL_CORNER, EDG_CORNER)
  ax.plot([-0.5, 11.5], [3.5, 3.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5], [7.5, 7.5],   color=COL_JUNC, lw=4.5, zorder=6)
  draw_junctions(ax, [(0.2, 3.5)], ms=5.5)
  ax.plot(4.0, 1.5, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(8.0, 2.2, "o", color=COL_END,   ms=6.0, zorder=7)
  box_label(ax, 6.0, 5.8, "PR (Corner)", fontsize=7.6)
  box_label(ax, 6.0, 1.2, "Child W (O)", fontsize=7.6)
  setup(ax, "(d) W peely (ends bottom)\nPeel top -> child stays O")

  plt.tight_layout()
  save_fig(fig, "fig07_two_w_rules", preview)


# ---------------------------------------------------------------------------
# Figure 8: Layer 3 (tCan) — 3 T-Job Control Paths & 6-Pass Defect Localization
# ---------------------------------------------------------------------------
def make_fig08(preview):
  fig, axes = plt.subplots(1, 3, figsize=(12.2, 4.4))
  fig.suptitle("Layer 3 (tCan): T-Job Control Paths & 6-Pass Defect Localization", fontsize=11.5, fontweight="bold", y=1.01)

  # (a) Pass 1: Centered aspect-safe sep (24x24, s=(5,8), t=(18,16)).
  #
  ax = axes[0]
  w, h, s, t = 24, 24, (5, 8), (18, 16)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0,  0, 12, 24, COL_ONE, EDG_ONE)
  draw_box(ax, 12, 0, 12, 24, COL_ONE, EDG_ONE)
  ax.plot([11.5, 11.5], [-0.5, 23.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.25, ms=5.0)
  draw_junctions(ax, find_crossings_v(P, 12))
  box_label(ax, 5.5, 19.5,  "onePath (left)")
  box_label(ax, 17.5, 4.5,  "onePath (right)")
  ax.set_title("(a) Pass 1: Centered tSep (real 24x24)\ns=(5,8), t=(18,16) | cut c=12, far-edge j", fontsize=9.1, pad=6)

  # (b) Pass 2: Centered quadrant zoom (24x24, s=(5,5), t=(6,5)) -> isolated in [0,12)x[0,12)!
  #
  ax = axes[1]
  w, h, s, t = 24, 24, (5, 5), (6, 5)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0,  0,  12, 12, COL_TWO,    EDG_TWO)
  draw_box(ax, 12, 0,  12, 24, COL_CORNER, EDG_CORNER)
  draw_box(ax, 0,  12, 12, 12, COL_CORNER, EDG_CORNER)
  ax.plot([11.5, 11.5], [-0.5, 23.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  ax.plot([-0.5, 11.5], [11.5, 11.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.25, ms=5.0)
  draw_junctions(ax, find_crossings_v(P, 12) + find_crossings_h(P, 12, 0, 12))
  box_label(ax, 5.5, 9.0,  "W quadrant")
  box_label(ax, 17.5, 11.5,"R1 (Corner)")
  box_label(ax, 5.5, 17.5, "R2 (Corner)")
  ax.set_title("(b) Pass 2: Centered tZoom (real 24x24)\ns=(5,5), t=(6,5) | 3/4 untouched Hilbert bulk", fontsize=9.1, pad=6)

  # (c) Pass 6: tUturn schematic (left corner strip Rs + right split B0, B1).
  #
  ax = axes[2]
  draw_box(ax, 0,  0, 10, 24, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 10, 0, 14, 12, COL_ONE,    EDG_ONE,    lw=1.6)
  draw_box(ax, 10, 12, 14, 12, COL_ONE,   EDG_ONE,    lw=1.6)
  ax.plot([9.5, 9.5], [-0.5, 23.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([9.5, 23.5], [11.5, 11.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([16, 10, 9, 2, 2, 9, 10, 17], [5, 0.5, 0.5, 0.5, 22.5, 22.5, 22.5, 17],
          color=COL_PATH, lw=2.0, ls=":", zorder=4)
  ax.plot(16, 5,  "o", color=COL_START, ms=6.5, zorder=6)
  ax.plot(17, 17, "o", color=COL_END,   ms=6.5, zorder=6)
  draw_junctions(ax, [(9.5, 0.5), (9.5, 22.5)], ms=6.0)
  box_label(ax, 4.5, 11.5, "Rs\n(Corner)")
  box_label(ax, 16.5, 8.5, "B0 (onePath)")
  box_label(ax, 16.5, 14.5,"B1 (onePath)")
  ax.set_aspect("equal"); ax.set_xlim(-0.85, 23.15); ax.set_ylim(-0.85, 23.15)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("(c) Pass 6: tUturn (schematic)\nCorner strip Rs + two onePath halves B0, B1", fontsize=9.1, pad=6)

  plt.tight_layout()
  save_fig(fig, "fig08_two_t_rules", preview)


# ---------------------------------------------------------------------------
# Figure 9: Layer 4 (longPath) — Long-Box Control Paths (min >= 20, asp > 9/4)
# ---------------------------------------------------------------------------
def make_fig09(preview):
  fig = plt.figure(figsize=(12.6, 6.2))
  gs  = fig.add_gridspec(2, 3, width_ratios=[1.25, 1.25, 1.0], height_ratios=[1.0, 1.0])
  fig.suptitle("Layer 4 (longPath, min >= 20, aspect > 9/4): Long-Box Control Paths", fontsize=11.5, fontweight="bold", y=0.995)

  # (a) Real ltSplit: 50x20, s=(12,7), t=(37,13) -> long side is horizontal (50),
  # lsw rotates to 20x50, ltSplit cuts at m=25 -> vertical cut x=25 in world coords!
  #
  ax = fig.add_subplot(gs[0, 0])
  w, h, s, t = 50, 20, (12, 7), (37, 13)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0,  0, 25, 20, COL_ONE, EDG_ONE)
  draw_box(ax, 25, 0, 25, 20, COL_ONE, EDG_ONE)
  ax.plot([24.5, 24.5], [-0.5, 19.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.05, ms=4.8)
  draw_junctions(ax, find_crossings_v(P, 25), ms=5.5)
  box_label(ax, 12.0, 15.0, "lsGo (left)")
  box_label(ax, 37.0, 5.0,  "lsGo (right)")
  ax.set_title("(a) ltSplit (real 50x20): cut across middle\nTwo long one-interior jobs (lsGo)", fontsize=9.0, pad=5)

  # (b) Real lcGo (same short edge): 60x20, s=(0,0), t=(0,19) -> splits along long axis into two 60x10 lanes!
  #
  ax = fig.add_subplot(gs[0, 1])
  w, h, s, t = 60, 20, (0, 0), (0, 19)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0, 0,  60, 10, COL_CORNER, EDG_CORNER)
  draw_box(ax, 0, 10, 60, 10, COL_CORNER, EDG_CORNER)
  ax.plot([-0.5, 59.5], [9.5, 9.5], color=COL_CUT, lw=1.8, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=0.95, ms=4.8)
  draw_junctions(ax, find_crossings_h(P, 10), ms=5.5)
  box_label(ax, 30.0, 4.5,  "lcGo lane 1 (out)")
  box_label(ax, 30.0, 14.5, "lcGo lane 2 (back)")
  ax.set_title("(b) lcGo same-edge (real 60x20): 2 parallel lanes\nJoined at far end; each recurses to aspect <= 3", fontsize=9.0, pad=5)

  # (c) bandCan schematic (3-column mid-band when s, t at similar long-axis height).
  #
  ax = fig.add_subplot(gs[1, 0])
  draw_box(ax, 0,  0, 18, 20, COL_ONE,    EDG_ONE,    lw=1.4)
  draw_box(ax, 18, 0, 16, 7,  COL_ONE,    EDG_ONE,    lw=1.4)
  draw_box(ax, 18, 7, 16, 6,  COL_CORNER, EDG_CORNER, lw=1.4)
  draw_box(ax, 18, 13, 16, 7, COL_ONE,    EDG_ONE,    lw=1.4)
  draw_box(ax, 34, 0, 16, 20, COL_ONE,    EDG_ONE,    lw=1.4)
  for xv in [17.5, 33.5]:
    ax.plot([xv, xv], [-0.5, 19.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  for yv in [6.5, 12.5]:
    ax.plot([17.5, 33.5], [yv, yv], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot(24, 3.0,  "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(26, 16.5, "o", color=COL_END,   ms=6.0, zorder=7)
  draw_junctions(ax, [(33.5, 1.0), (33.5, 11.5), (17.5, 7.5), (17.5, 18.5)], ms=5.0)
  box_label(ax, 8.5, 9.5,  "lsGo\n(below)", fontsize=7.8)
  box_label(ax, 41.5, 9.5, "lsGo\n(above)", fontsize=7.8)
  box_label(ax, 25.5, 9.5, "Corner", fontsize=7.6)
  box_label(ax, 29.0, 3.0, "1-int", fontsize=7.4)
  box_label(ax, 22.0, 16.5,"1-int", fontsize=7.4)
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 49.8); ax.set_ylim(-0.8, 19.8)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("(c) bandCan (3-column mid-band, schematic)\ns -> 1-int -> lsGo -> Corner -> lsGo -> 1-int -> t", fontsize=9.0, pad=5)

  # (d) ringO schematic (two-path box M at bottom + strip S + top cap A).
  #
  ax = fig.add_subplot(gs[1, 1])
  draw_box(ax, 0,  0,  16, 12, COL_TWO,    EDG_TWO,    lw=1.4)
  draw_box(ax, 16, 0,  34, 12, COL_CORNER, EDG_CORNER, lw=1.4)
  draw_box(ax, 0,  12, 50, 8,  COL_CORNER, EDG_CORNER, lw=1.4)
  ax.plot([15.5, 15.5], [-0.5, 11.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot([-0.5, 49.5], [11.5, 11.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot(6, 5, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(10, 7, "o", color=COL_END,  ms=6.0, zorder=7)
  draw_junctions(ax, [(1.0, 11.5), (48.5, 11.5), (15.5, 1.0)], ms=5.0)
  box_label(ax, 8.0, 8.8,  "M (W, O)", fontsize=7.6)
  box_label(ax, 32.5, 5.5, "A (lcGo cap)", fontsize=7.8)
  box_label(ax, 25.0, 15.5,"S (lcGo strip)", fontsize=7.8)
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 49.8); ax.set_ylim(-0.8, 19.8)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("(d) ringO (M at end, schematic)\nOuter lcGo path wraps S -> A around W box M", fontsize=9.0, pad=5)

  # (e) ringP schematic (vertical orientation: bottom cap D, mid M, strip S, top cap A).
  #
  ax = fig.add_subplot(gs[:, 2])
  draw_box(ax, 0,  0,  12, 14, COL_CORNER, EDG_CORNER, lw=1.4)
  draw_box(ax, 0,  14, 12, 14, COL_TWO,    EDG_TWO,    lw=1.4)
  draw_box(ax, 0,  28, 12, 16, COL_CORNER, EDG_CORNER, lw=1.4)
  draw_box(ax, 12, 0,  8,  44, COL_CORNER, EDG_CORNER, lw=1.4)
  ax.plot([11.5, 11.5], [-0.5, 43.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot([-0.5, 11.5], [13.5, 13.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot([-0.5, 11.5], [27.5, 27.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot(4.5, 19.0, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(7.5, 22.5, "o", color=COL_END,   ms=6.0, zorder=7)
  draw_junctions(ax, [(1.0, 13.5), (11.5, 1.0), (11.5, 42.5), (10.5, 27.5)], ms=5.0)
  box_label(ax, 5.5, 6.5,  "D (lcGo)", fontsize=8.0)
  box_label(ax, 5.5, 24.5, "M (W, P)", fontsize=7.8)
  box_label(ax, 5.5, 35.5, "A (lcGo)", fontsize=8.0)
  box_label(ax, 15.5, 21.5,"S\n(lcGo\nstrip)", fontsize=7.8)
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 19.8); ax.set_ylim(-0.8, 43.8)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("(e) ringP (mid-box M)\nWraps D -> S -> A\naround layout-P W box", fontsize=9.0, pad=5)

  plt.tight_layout(rect=[0, 0, 1, 0.96])
  save_fig(fig, "fig09_long_rules", preview)


# ---------------------------------------------------------------------------
# Figure 10: Layer 5 (narrowPath) — Corner-Edge Splice, excTile, & Assembly
# ---------------------------------------------------------------------------
def make_fig10(preview):
  fig = plt.figure(figsize=(12.4, 6.6))
  gs  = fig.add_gridspec(2, 2, height_ratios=[1.15, 0.95])
  fig.suptitle("Layer 5 (narrowPath, 4 <= min <= 19): Corner-Edge Splicing & Tiled Excursions", fontsize=11.5, fontweight="bold", y=0.995)

  # (a) Topological proof of corner-edge splice (before -> after).
  #
  ax = fig.add_subplot(gs[0, 0])
  # Left diagram: before splice.
  #
  draw_box(ax, 0, 0, 4, 3, COL_ONE, EDG_ONE, lw=1.4)
  draw_box(ax, 0, 3, 4, 3, COL_EXC, EDG_EXC, lw=1.4, ls="--")
  ax.plot([2, 3, 3], [2, 2, 1], color=COL_PATH, lw=2.6, zorder=5)
  ax.plot([2, 3], [2, 2], color="#dc2626", lw=3.6, zorder=6)
  ax.plot(3, 2, "s", color="#dc2626", ms=8.5, zorder=7)
  ax.text(3.0, 2.0, "c", ha="center", va="center", fontsize=8.0, fontweight="bold", color="#ffffff", zorder=8)
  ax.text(1.75, 2.0, "c'", ha="right", va="center", fontsize=8.5, fontweight="bold", color="#0f172a")
  ax.text(3.0, 0.65, "d", ha="center", va="top", fontsize=8.5, fontweight="bold", color="#0f172a")
  ax.text(1.5, 4.5, "Excursion Q\n(starts at r,\nends at r')", ha="center", va="center", fontsize=8.0, color="#581c87")
  ax.text(1.5, -0.95, "Before: c not an end\n=> edge (c, c') forced!", ha="center", va="top", fontsize=8.2, fontweight="bold", color="#0f172a")

  # Arrow between before & after.
  #
  ax.annotate("", xy=(5.6, 2.5), xytext=(4.2, 2.5),
              arrowprops=dict(arrowstyle="->", lw=2.2, color="#475569"))

  # Right diagram: after splice (shifted by x = +6).
  #
  ox = 6.2
  draw_box(ax, ox, 0, 4, 3, COL_ONE, EDG_ONE, lw=1.4)
  draw_box(ax, ox, 3, 4, 3, COL_EXC, EDG_EXC, lw=1.4)
  ax.plot([ox + 3, ox + 3], [1, 2], color=COL_PATH, lw=2.6, zorder=5)
  ax.plot([ox + 3, ox + 3, ox + 3, ox + 0.4, ox + 0.4, ox + 2, ox + 2],
          [2, 3, 5.2, 5.2, 3.2, 3.2, 2], color="#7e22ce", lw=2.4, zorder=6)
  ax.plot(ox + 3, 2, "s", color="#dc2626", ms=8.5, zorder=7)
  ax.text(ox + 3, 2, "c", ha="center", va="center", fontsize=8.0, fontweight="bold", color="#ffffff", zorder=8)
  ax.text(ox + 1.8, 2.0, "c'", ha="right", va="center", fontsize=8.5, fontweight="bold", color="#0f172a")
  ax.text(ox + 3.25, 3.05, "r",  ha="left",  va="bottom", fontsize=8.4, fontweight="bold", color="#581c87")
  ax.text(ox + 2.25, 2.75, "r'", ha="left",  va="bottom", fontsize=8.4, fontweight="bold", color="#581c87")
  ax.text(ox + 1.5, -0.95, "After spliceAt:\nc -> r .. Q .. r' -> c'", ha="center", va="top", fontsize=8.2, fontweight="bold", color="#581c87")

  ax.set_aspect("equal"); ax.set_xlim(-0.8, 10.6); ax.set_ylim(-2.1, 6.0)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("(a) Why corner-edge splicing (spliceAt) always works", fontsize=9.3, pad=5)

  # (b) Real excTile recursive alternating-mirror tiling:
  # Run narrowPath on 6x30 with s=(0,0), t=(1,0)? Wait: on 6x30 (30x6),
  # s=(0,0), t=(1,0) has y0=0, y1 = 0+5+(30-5)%2 = 6, so [6,30) is pure excTile(6, 24)!
  # Let's draw horizontal 30x6 (transposed from 6x30) showing the alternating tiles of width 6!
  #
  ax = fig.add_subplot(gs[0, 1])
  w, h, s, t = 30, 6, (0, 0), (0, 1)
  P = run_stg(w, h, s, t)
  # Core is [0,6), then excTile(6, 24) splits into tiles of width h0=6: [6,12), [12,18), [18,24), [24,30)!
  # Wait: singleMax(6) = min(18, max(8, 9)) = 9, so 24 -> 6 + 18 -> 6 + 6 + 12 -> 6 + 6 + 6 + 6!
  #
  draw_box(ax, 0,  0, 6, 6, COL_ONE, EDG_ONE)
  for k_idx, x0 in enumerate([6, 12, 18, 24]):
    fc = COL_EXC if ((k_idx % 2) == 0) else "#ede9fe"
    draw_box(ax, x0, 0, 6, 6, fc, EDG_EXC)
    ax.plot([x0 - 0.5, x0 - 0.5], [-0.5, 5.5], color=COL_CUT, lw=1.5, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.45, ms=5.0)
  for x0 in [6, 12, 18, 24]:
    draw_junctions(ax, find_crossings_v(P, x0), ms=4.8)
  box_label(ax, 2.5,  2.5, "Core", fontsize=7.6)
  box_label(ax, 8.5,  2.5, "Tile 1", fontsize=7.4)
  box_label(ax, 14.5, 2.5, "Tile 2\n(mir)", fontsize=7.0)
  box_label(ax, 20.5, 2.5, "Tile 3", fontsize=7.4)
  box_label(ax, 26.5, 2.5, "Tile 4\n(mir)", fontsize=7.0)
  ax.set_title("(b) Real excTile(6, 24) inside 30x6 (0,0)->(0,1)\nNear-square 6x6 tiles spliced at alternating corners", fontsize=9.3, pad=5)

  # (c) Full narrowPath assembly on real 48x8 with interior endpoints s=(16,3), t=(33,5):
  # Horizontal 48x8 -> lsw makes 8x48, s'=(3,16), t'=(5,33), t'.y - s'.y = 17 > 12 (far ends!).
  # Compute exact ny0, ny1, na, nb for U=8, V=48, sy=16, ty=33:
  # minExcH(8) = 4, ny0 = 16-4 = 12; ny1 = 33+5+(48-33-5)%2 = 38;
  # na = 16+4+(20-12)%2 = 20; nb = 33-3-(30-20)%2 = 30.
  #
  ax = fig.add_subplot(gs[1, :])
  w, h, s, t = 48, 8, (16, 3), (33, 5)
  P = run_stg(w, h, s, t)
  draw_box(ax, 0,  0, 12, 8, COL_EXC,    EDG_EXC)
  draw_box(ax, 12, 0, 8,  8, COL_ONE,    EDG_ONE)
  draw_box(ax, 20, 0, 10, 8, COL_CORNER, EDG_CORNER)
  draw_box(ax, 30, 0, 8,  8, COL_ONE,    EDG_ONE)
  draw_box(ax, 38, 0, 10, 8, COL_EXC,    EDG_EXC)
  for xv in [12, 20, 30, 38]:
    ax.plot([xv - 0.5, xv - 0.5], [-0.5, 7.5], color=COL_CUT, lw=1.7, ls="--", zorder=6)
  draw_path(ax, w, h, P, s, t, lw=1.35, ms=5.5)
  for xv in [12, 20, 30, 38]:
    draw_junctions(ax, find_crossings_v(P, xv), ms=5.2)
  box_label(ax, 5.5,  3.5, "excLow [0, 12)", fontsize=8.2)
  box_label(ax, 15.5, 6.2, "stgPath", fontsize=7.6)
  box_label(ax, 24.5, 3.5, "lcGo [20, 30)", fontsize=8.0)
  box_label(ax, 33.5, 1.4, "stgPath", fontsize=7.6)
  box_label(ax, 42.5, 3.5, "excHigh [38, 48)", fontsize=8.2)
  ax.set_title("(c) Full narrowPath assembly (real 48x8, s=(16,3), t=(33,5), far ends): excLow + [stgPath | lcGo | stgPath] + excHigh", fontsize=9.4, pad=5)

  plt.tight_layout(rect=[0, 0, 1, 0.96])
  save_fig(fig, "fig10_narrow_splice", preview)


# ---------------------------------------------------------------------------
# Figure 11: Endpoint Stability & Bulk Preservation Across Incremental Shifts
# ---------------------------------------------------------------------------
def make_fig11(preview):
  fig, axes = plt.subplots(1, 4, figsize=(12.6, 3.5))
  fig.suptitle("Stability & Defect Localization: Moving End t Inward from Exact 16x16 Hilbert (s = (0, 0) Fixed)", fontsize=11.0, fontweight="bold", y=1.03)

  ends = [(15, 0), (14, 1), (12, 3), (9, 6)]
  w, h, s = 16, 16, (0, 0)
  P0 = run_stg(w, h, s, ends[0])
  edges0 = set()
  for i in range(len(P0) - 1):
    a, b = P0[i], P0[i + 1]
    edges0.add((a, b) if (a < b) else (b, a))

  for idx, t in enumerate(ends):
    ax = axes[idx]
    P  = run_stg(w, h, s, t)
    segs_same = []
    segs_diff = []
    for i in range(len(P) - 1):
      a, b = P[i], P[i + 1]
      key = (a, b) if (a < b) else (b, a)
      if (idx == 0) or (key in edges0):
        segs_same.append([a, b])
      else:
        segs_diff.append([a, b])
    draw_box(ax, 0, 0, w, h, "#fafafa", "#cbd5e1", lw=1.0)
    if segs_same:
      ax.add_collection(LineCollection(segs_same, colors=COL_PATH, linewidths=1.5, capstyle="round", zorder=4))
    if segs_diff:
      ax.add_collection(LineCollection(segs_diff, colors="#ea580c", linewidths=1.9, capstyle="round", zorder=5))
    ax.plot(s[0], s[1], "o", color=COL_START, ms=6.0, mec="#ffffff", mew=0.8, zorder=7)
    ax.plot(t[0], t[1], "o", color=COL_END,   ms=6.0, mec="#ffffff", mew=0.8, zorder=7)
    ax.set_aspect("equal"); ax.set_xlim(-0.8, w - 0.2); ax.set_ylim(-0.8, h - 0.2)
    ax.set_xticks([]); ax.set_yticks([])
    for sp in ax.spines.values(): sp.set_visible(False)

    same_pct = (100.0 * len(segs_same)) / max(1, len(P) - 1)
    lbl = "Exact 2D Hilbert" if (idx == 0) else f"{same_pct:.1f}% edges unchanged"
    ax.set_title(f"t = {t}\n{lbl}", fontsize=9.0, pad=5)

  plt.tight_layout()
  save_fig(fig, "fig11_stability_endpoints", preview)


# ---------------------------------------------------------------------------
# Figure 12: Detailed W Peel Frame Transitions (O <-> P) & Colour Propagation
# ---------------------------------------------------------------------------
def make_fig12(preview):
  fig, axes = plt.subplots(2, 2, figsize=(12.2, 7.6))
  fig.suptitle("Detailed W-Peel Mechanics: All 4 Peel Directions, Port-Colour Preservation, and O <-> P Transitions", fontsize=11.3, fontweight="bold", y=0.995)

  def setup_p(ax, title):
    ax.set_aspect("equal")
    ax.set_xlim(-0.8, 12.8)
    ax.set_ylim(-0.8, 8.8)
    ax.set_xticks([])
    ax.set_yticks([])
    for sp in ax.spines.values():
      sp.set_visible(False)
    ax.set_title(title, fontsize=9.1, pad=5)

  # (a) peelx(c), ends RIGHT (c <= s.x, t.x): left peeled -> child ALWAYS Layout P
  #
  ax = axes[0, 0]
  draw_box(ax, 0, 0, 6, 8, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 6, 0, 6, 8, COL_TWO,    EDG_TWO,    lw=1.6)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  # Parent ports: pa (right), pb (top-left, O or P)
  #
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5],  [7.5, 7.5],  color="#0284c7", lw=4.5, zorder=6)
  # New port np on left edge of right child (col = col(pb)) & junction jc in left box (1 - col(pb))
  #
  ax.plot([5.5, 5.5], [5.5, 7.5], color="#7e22ce", lw=4.5, zorder=6)
  ax.plot(5.0, 6.8, "s", color="#0284c7", ms=5.5, zorder=7)
  ax.plot(6.0, 6.8, "D", color="#7e22ce", ms=5.5, zorder=7)
  ax.plot([5.0, 6.0], [6.8, 6.8], color="#dc2626", lw=2.0, zorder=6)
  ax.plot(8.2, 2.5, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(9.6, 4.8, "o", color=COL_END,   ms=6.0, zorder=7)
  ax.text(0.6, 6.9, "pb", fontsize=8.0, fontweight="bold", color="#0369a1", va="top")
  ax.text(4.8, 6.3, "jc\n(1-c)", ha="right", va="top", fontsize=7.3, fontweight="bold", color="#0369a1")
  ax.text(6.3, 6.3, "np\n(col=c)", ha="left", va="top", fontsize=7.3, fontweight="bold", color="#6b21a8")
  ax.text(11.1, 0.5, "pa", ha="right", fontsize=8.0, fontweight="bold", color="#92400e")
  box_label(ax, 2.6, 3.4, "Corner PR\n(pb -> jc)", fontsize=7.8)
  box_label(ax, 8.9, 1.0, "Child: Layout P\n(shift x - c)", fontsize=7.6)
  setup_p(ax, "(a) peelx(c), ends RIGHT -> ALWAYS Layout P\nEven PR valid for both col(pb); np on left vertical edge")

  # (b) peelx(c), ends LEFT (s.x, t.x < c): right peeled -> KEEPS parent layout lp
  #
  ax = axes[0, 1]
  draw_box(ax, 0, 0, 6, 8, COL_TWO,    EDG_TWO,    lw=1.6)
  draw_box(ax, 6, 0, 6, 8, COL_CORNER, EDG_CORNER, lw=1.6)
  ax.plot([5.5, 5.5], [-0.5, 7.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5],  [7.5, 7.5],  color="#0284c7", lw=4.5, zorder=6)
  ax.plot([5.5, 5.5],   [-0.5, 1.5], color="#d97706", lw=4.5, zorder=6)
  ax.plot(5.0, 0.4, "D", color="#d97706", ms=5.5, zorder=7)
  ax.plot(6.0, 0.4, "s", color="#0284c7", ms=5.5, zorder=7)
  ax.plot([5.0, 6.0], [0.4, 0.4], color="#dc2626", lw=2.0, zorder=6)
  ax.plot(2.0, 4.8, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(3.6, 2.6, "o", color=COL_END,   ms=6.0, zorder=7)
  ax.text(0.6, 6.9, "pb (kept)", fontsize=7.8, fontweight="bold", color="#0369a1", va="top")
  ax.text(4.8, 1.5, "np\n(col=c)", ha="right", va="bottom", fontsize=7.3, fontweight="bold", color="#92400e")
  ax.text(6.3, 1.1, "jc\n(1-c)", ha="left", va="bottom", fontsize=7.3, fontweight="bold", color="#0369a1")
  ax.text(11.1, 0.5, "pa", ha="right", fontsize=8.0, fontweight="bold", color="#92400e")
  box_label(ax, 8.8, 4.0, "Corner PR\n(pa -> jc)", fontsize=7.8)
  box_label(ax, 2.0, 0.8, "Child: SAME lp\n(no transform)", fontsize=7.5)
  setup_p(ax, "(b) peelx(c), ends LEFT -> KEEPS Layout lp (O->O, P->P)\nnp replaces pa on right vertical edge of left child")

  # (c) peely(r), ends TOP (r <= s.y, t.y): bottom peeled -> FLIPS O <-> P!
  #
  ax = axes[1, 0]
  draw_box(ax, 0, 0, 12, 4, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 4, 12, 4, COL_TWO,    EDG_TWO,    lw=1.6)
  ax.plot([-0.5, 11.5], [3.5, 3.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5],  [7.5, 7.5],  color="#0284c7", lw=4.5, zorder=6)
  ax.plot([9.5, 11.5],  [3.5, 3.5],  color="#7e22ce", lw=4.5, zorder=6)
  ax.plot(10.6, 3.0, "s", color="#0284c7", ms=5.5, zorder=7)
  ax.plot(10.6, 4.0, "D", color="#7e22ce", ms=5.5, zorder=7)
  ax.plot([10.6, 10.6], [3.0, 4.0], color="#dc2626", lw=2.0, zorder=6)
  ax.plot(3.8, 5.8, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(7.5, 6.2, "o", color=COL_END,   ms=6.0, zorder=7)
  ax.text(1.7, 7.3, "pb (O: top / P: left)", fontsize=7.6, fontweight="bold", color="#0369a1", va="top")
  ax.text(10.8, 4.6, "np\n(bottom)", ha="center", va="bottom", fontsize=7.3, fontweight="bold", color="#6b21a8")
  ax.text(10.1, 2.7, "jc", ha="right", va="top", fontsize=7.5, fontweight="bold", color="#0369a1")
  ax.text(11.1, 0.5, "pa", ha="right", fontsize=8.0, fontweight="bold", color="#92400e")
  box_label(ax, 5.2, 1.6, "Corner PR (pa -> jc)", fontsize=7.8)
  box_label(ax, 4.4, 4.6, "Child: FLIPS !lp [k=(lp,lp), sw=!lp]", fontsize=7.3)
  setup_p(ax, "(c) peely(r), ends TOP -> FLIPS Layout (O->P via T, P->O via 180 deg)\npb becomes child's pa; np becomes child's pb (flag inverted)")

  # (d) peely(r), ends BOTTOM (s.y, t.y < r): top peeled -> ALWAYS Layout O
  #
  ax = axes[1, 1]
  draw_box(ax, 0, 0, 12, 4, COL_TWO,    EDG_TWO,    lw=1.6)
  draw_box(ax, 0, 4, 12, 4, COL_CORNER, EDG_CORNER, lw=1.6)
  ax.plot([-0.5, 11.5], [3.5, 3.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5],  [7.5, 7.5],  color="#0284c7", lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5],  [3.5, 3.5],  color="#0284c7", lw=4.5, zorder=6)
  ax.plot(0.4, 3.0, "D", color="#0284c7", ms=5.5, zorder=7)
  ax.plot(0.4, 4.0, "s", color="#0284c7", ms=5.5, zorder=7)
  ax.plot([0.4, 0.4], [3.0, 4.0], color="#dc2626", lw=2.0, zorder=6)
  ax.plot(4.2, 1.6, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(8.2, 2.0, "o", color=COL_END,   ms=6.0, zorder=7)
  ax.text(0.6, 6.9, "pb", fontsize=8.0, fontweight="bold", color="#0369a1", va="top")
  ax.text(1.0, 4.2, "jc (1-c)", ha="left", va="bottom", fontsize=7.4, fontweight="bold", color="#0369a1")
  ax.text(1.0, 2.8, "np (col=c)", ha="left", va="top", fontsize=7.4, fontweight="bold", color="#0369a1")
  ax.text(11.1, 0.5, "pa (kept)", ha="right", fontsize=7.8, fontweight="bold", color="#92400e")
  box_label(ax, 6.2, 5.8, "Corner PR (pb -> jc)", fontsize=7.8)
  box_label(ax, 4.7, 0.7, "Child: ALWAYS Layout O (no transform)", fontsize=7.5)
  setup_p(ax, "(d) peely(r), ends BOTTOM -> ALWAYS Layout O\nnp replaces pb on top horizontal edge of bottom child")

  plt.tight_layout(rect=[0, 0, 1, 0.96])
  save_fig(fig, "fig12_w_peel_transitions", preview)


# ---------------------------------------------------------------------------
# Figure 13: Why Colour-Bit Look-Ahead Works Without Backtracking Inside Z/W
# ---------------------------------------------------------------------------
def make_fig13(preview):
  fig, axes = plt.subplots(1, 3, figsize=(12.6, 3.9))
  fig.suptitle("Why Trying Only Colour Bit a = 0 Then a = 1 at the Top Zoom Always Succeeds", fontsize=11.3, fontweight="bold", y=1.02)

  # Panel 1: Zoom picks bit a -> fixes outer corner jobs R1, R2 -> passes port colours (cA, cB) to Q
  #
  ax = axes[0]
  draw_box(ax, 0, 0, 6, 5, COL_TWO,    EDG_TWO,    lw=1.6)
  draw_box(ax, 6, 0, 6, 9, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 5, 6, 4, COL_CORNER, EDG_CORNER, lw=1.6)
  ax.plot([5.5, 5.5], [-0.5, 8.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  ax.plot([-0.5, 5.5], [4.5, 4.5], color=COL_CUT, lw=1.6, ls="--", zorder=5)
  draw_junctions(ax, [(5.5, 0.2), (5.5, 8.0), (0.2, 4.5)], ms=5.5)
  ax.annotate("", xy=(9.0, 7.6), xytext=(9.0, 0.8),
              arrowprops=dict(arrowstyle="->", lw=1.8, color="#0369a1"))
  ax.annotate("", xy=(0.8, 7.2), xytext=(4.8, 7.2),
              arrowprops=dict(arrowstyle="->", lw=1.8, color="#0369a1"))
  box_label(ax, 2.8, 2.2, "Quadrant Q\n(Z or W)\nports (cA, cB)", fontsize=7.6)
  box_label(ax, 8.6, 4.2, "R1 (even)\nparity\npropagates", fontsize=7.4)
  box_label(ax, 2.8, 6.8, "R2 (even)", fontsize=7.5)
  ax.text(5.7, 0.8, "bit a", fontsize=7.8, fontweight="bold", color="#b45309")
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 12.2); ax.set_ylim(-0.8, 9.2)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("Step 1: Top zoom picks bit a in {0, 1}\nOuter even boxes R1, R2 fix ports (cA, cB)", fontsize=9.0, pad=5)

  # Panel 2: Peel chain preserves (cA, cB) unchanged and follows same geometry for both bits!
  #
  ax = axes[1]
  draw_box(ax, 0, 0, 12, 9, COL_CORNER, EDG_CORNER, lw=1.2, alpha=0.55)
  draw_box(ax, 0, 0, 8,  9, COL_CORNER, EDG_CORNER, lw=1.2, alpha=0.75)
  draw_box(ax, 0, 0, 8,  6, COL_TWO,    EDG_TWO,    lw=1.6)
  ax.plot([7.5, 7.5], [-0.5, 8.5], color=COL_CUT, lw=1.5, ls="--", zorder=5)
  ax.plot([-0.5, 7.5], [5.5, 5.5], color=COL_CUT, lw=1.5, ls="--", zorder=5)
  draw_junctions(ax, [(7.5, 0.3), (0.3, 5.5)], ms=5.5)
  box_label(ax, 9.6, 4.2, "Peel 1\n(even)\nworks for\nboth bits!", fontsize=7.4)
  box_label(ax, 3.6, 7.0, "Peel 2 (even)\nworks for both bits!", fontsize=7.2)
  box_label(ax, 3.6, 2.6, "Shrunk box Q'\nsame (cA, cB)!\nsame cut tree!", fontsize=7.5)
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 12.2); ax.set_ylim(-0.8, 9.2)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("Step 2: Every peel is colour-blind\nSame cut sequence; (cA, cB) passes unchanged", fontsize=9.0, pad=5)

  # Panel 3: Terminal sep or leaf decides which bit fits; at least one of {0, 1} matches!
  #
  ax = axes[2]
  draw_box(ax, 0, 0, 6, 9, COL_ONE, EDG_ONE, lw=1.6)
  draw_box(ax, 6, 0, 6, 9, COL_ONE, EDG_ONE, lw=1.6)
  ax.plot([5.5, 5.5], [-0.5, 8.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  ax.plot(2.5, 4.2, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(8.8, 4.8, "o", color=COL_END,   ms=6.0, zorder=7)
  ax.plot([11.5, 11.5], [-0.5, 1.5], color=COL_JUNC, lw=4.5, zorder=6)
  ax.plot([-0.5, 1.5],  [8.5, 8.5],  color="#0284c7", lw=4.5, zorder=6)
  box_label(ax, 2.7, 6.8, "onePath\nneeds cB", fontsize=7.6)
  box_label(ax, 8.7, 2.4, "onePath\nneeds cA", fontsize=7.6)
  box_label(ax, 5.6, 0.8, "a = 0 or a = 1\nalways matches!", fontsize=7.5, color="#15803d")
  ax.set_aspect("equal"); ax.set_xlim(-0.8, 12.2); ax.set_ylim(-0.8, 9.2)
  ax.set_xticks([]); ax.set_yticks([])
  for sp in ax.spines.values(): sp.set_visible(False)
  ax.set_title("Step 3: Terminal sep (or leaf table)\nOne of a in {0, 1} matches -> glue R1, R2 by flag f", fontsize=9.0, pad=5)

  plt.tight_layout()
  save_fig(fig, "fig13_colour_bit_pipeline", preview)


# ---------------------------------------------------------------------------
# Figure 14: Layer 4 — Long One-Interior (lsGo) Control Paths (4 Patterns)
# ---------------------------------------------------------------------------
def make_fig14(preview):
  fig, axes = plt.subplots(1, 4, figsize=(12.8, 4.3))
  fig.suptitle("Layer 4 (lsGo): Long One-Interior Control Paths (p Near Bottom-Left, x Anywhere, U <= V)", fontsize=11.1, fontweight="bold", y=1.02)

  def setup(ax, title):
    ax.set_aspect("equal")
    ax.set_xlim(-0.8, 12.8)
    ax.set_ylim(-0.8, 28.8)
    ax.set_xticks([])
    ax.set_yticks([])
    for sp in ax.spines.values():
      sp.set_visible(False)
    ax.set_title(title, fontsize=8.8, pad=5)

  # 1. Top cap (lcGo below + onePath top)
  #
  ax = axes[0]
  draw_box(ax, 0, 0,  12, 14, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 14, 12, 14, COL_ONE,    EDG_ONE,    lw=1.6)
  ax.plot([-0.5, 11.5], [13.5, 13.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  draw_junctions(ax, [(10.8, 13.5)], ms=5.5)
  ax.plot(0.2, 0.2, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(6.5, 22.0,"o", color=COL_END,   ms=6.0, zorder=7)
  box_label(ax, 5.6, 6.8,  "lcGo\n(>= abL)", fontsize=7.8)
  box_label(ax, 5.6, 18.2, "onePath\n(top cap)", fontsize=7.8)
  setup(ax, "Step 2: Top Cap\nx high enough for\nonePath cap <= 3U")

  # 2. Bottom ringO (M at y=0 holding p and x)
  #
  ax = axes[1]
  draw_box(ax, 0, 0,  6, 12, COL_TWO,    EDG_TWO,    lw=1.6)
  draw_box(ax, 6, 0,  6, 28, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 12, 6, 16, COL_CORNER, EDG_CORNER, lw=1.6)
  ax.plot([5.5, 5.5], [-0.5, 27.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot([-0.5, 5.5], [11.5, 11.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  draw_junctions(ax, [(5.5, 0.5), (5.5, 26.8), (0.5, 11.5)], ms=5.0)
  ax.plot(0.2, 0.2, "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(2.8, 6.2, "o", color=COL_END,   ms=6.0, zorder=7)
  box_label(ax, 2.8, 9.2,  "M (W)", fontsize=7.4)
  box_label(ax, 2.8, 19.5, "A\n(lcGo)", fontsize=7.5)
  box_label(ax, 8.6, 14.0, "S\n(lcGo\nstrip)", fontsize=7.5)
  setup(ax, "Step 3: Bottom ringO\nx in left lower part;\nM holds both p and x")

  # 3. Mid ringO over lcGo
  #
  ax = axes[2]
  draw_box(ax, 0, 0,  12, 9,  COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 9,  6,  9,  COL_TWO,    EDG_TWO,    lw=1.6)
  draw_box(ax, 6, 9,  6,  19, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 0, 18, 6,  10, COL_CORNER, EDG_CORNER, lw=1.6)
  ax.plot([-0.5, 11.5], [8.5, 8.5],   color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot([5.5, 5.5],   [8.5, 27.5],  color=COL_CUT, lw=1.7, ls="--", zorder=5)
  ax.plot([-0.5, 5.5],  [17.5, 17.5], color=COL_CUT, lw=1.7, ls="--", zorder=5)
  draw_junctions(ax, [(0.5, 8.5), (5.5, 9.5), (5.5, 26.8), (0.5, 17.5)], ms=4.8)
  ax.plot(0.2, 0.2,  "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(2.8, 13.5, "o", color=COL_END,   ms=6.0, zorder=7)
  box_label(ax, 5.6, 4.2,  "lcGo below", fontsize=7.6)
  box_label(ax, 2.8, 15.8, "M (W)", fontsize=7.2)
  box_label(ax, 2.8, 22.8, "A", fontsize=7.6)
  box_label(ax, 8.6, 18.0, "S\n(lcGo)", fontsize=7.5)
  setup(ax, "Step 4: Mid ringO\nlcGo below + ringO\naround middle x")

  # 4. Single-level column split (lcGo up left, lsGo1 down right)
  #
  ax = axes[3]
  draw_box(ax, 0, 0, 6, 28, COL_CORNER, EDG_CORNER, lw=1.6)
  draw_box(ax, 6, 0, 6, 28, COL_ONE,    EDG_ONE,    lw=1.6)
  ax.plot([5.5, 5.5], [-0.5, 27.5], color=COL_CUT, lw=1.8, ls="--", zorder=5)
  draw_junctions(ax, [(5.5, 26.8)], ms=5.5)
  ax.plot(0.2, 0.2,  "o", color=COL_START, ms=6.0, zorder=7)
  ax.plot(9.0, 7.5,  "o", color=COL_END,   ms=6.0, zorder=7)
  box_label(ax, 2.6, 14.0, "lcGo\n(up left)", fontsize=7.5)
  box_label(ax, 8.6, 16.0, "lsGo1\n(no 2nd\ncol split)", fontsize=7.3)
  setup(ax, "Step 5: Column Split\nFallback when x is\nin right half (c <= x.x)")

  plt.tight_layout()
  save_fig(fig, "fig14_long_one_interior", preview)


def main():
  preview = ("--preview" in sys.argv)
  if not os.path.exists(STGFULL_BIN):
    raise SystemExit(f"Missing binary {STGFULL_BIN}; build with: make -C ref/c")

  make_fig_sfc(preview)
  make_fig_moves(preview)
  make_fig_ports(preview)
  make_fig_conventions(preview)
  make_fig00(preview)
  make_fig01(preview)
  make_fig02(preview)
  make_fig03(preview)
  make_fig04(preview)
  make_fig05(preview)
  make_fig06(preview)
  make_fig07(preview)
  make_fig08(preview)
  make_fig09(preview)
  make_fig10(preview)
  make_fig11(preview)
  make_fig12(preview)
  make_fig13(preview)
  make_fig14(preview)
  print("Generated all 19 figures in", FIGS_DIR)


if __name__ == "__main__":
  main()
