/*
 * Exact Discrete Dirichlet Laplacian Eigensolver on Gordon-Webb-Wolpert Drums
 * ===========================================================================
 * Builds the 5-point discrete Laplacian L_h on an arbitrary union of 7 right-
 * isosceles lattice triangles at resolution N (grid spacing h = 1/N). Because
 * every boundary leg lies on grid axes and every hypotenuse lies on exact 45-deg
 * grid diagonals, the mesh has ZERO staircasing and preserves exact reflection
 * symmetry across all triangle edges — so Buser's Fano-plane transplantation is
 * an EXACT algebraic intertwiner of the discrete matrix L_h itself!
 *
 * Solver: exact band Cholesky factorization L_h = R^T R + shift-invert Lanczos
 * with full double Gram-Schmidt (DGKS) reorthogonalization + symmetric
 * tridiagonal QL (tql2). Finds the lowest K eigenpairs to ~1e-13 accuracy in
 * a fraction of a second, and explicitly checks residual ||L u - lam u|| / lam
 * plus connected nodal-domain counts via 4-neighbor BFS flood fill.
 *
 * Usage:
 *   ./drum_solver <N> <K> <seed> <out_prefix>
 *
 * Compile:
 *   gcc -O3 -march=native -Wall -Wextra drum_solver.c -lm -o drum_solver
 */

#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int x0, y0, x1, y1, x2, y2; /* V0 = right angle, V1 = leg-a end, V2 = leg-b end */
} Tri;

/*
 * Canonical GL(3, F_2) / Fano-plane Gordon-Webb-Wolpert pair (derived directly
 * from the unique zero-slit, zero-pinch 7-triangle right-isosceles pair).
 * Vertex order (V0, V1, V2) preserves the exact edge-color correspondence:
 *   V0 = right angle, edge V0-V1 = color a, edge V0-V2 = color b, V1-V2 = color c (hypotenuse).
 */
static const Tri DRUM_A[7] = {
    { 0,  0,  1,  0,  0,  1}, /* p0, parity +1 */
    { 0,  0, -1,  0,  0, -1}, /* p1, parity +1 */
    { 1, -1,  1, -2,  0, -1}, /* p2, parity -1 */
    { 0,  0,  1,  0,  0, -1}, /* p3, parity -1 */
    { 1, -1,  1,  0,  0, -1}, /* p4, parity +1 */
    { 1, -1,  1, -2,  2, -1}, /* p5, parity +1 */
    { 2, -2,  1, -2,  2, -1}, /* p6, parity -1 */
};
static const int PARITY_A[7] = { 1, 1, -1, -1, 1, 1, -1 };

static const Tri DRUM_B[7] = {
    { 0,  0,  1,  0,  0,  1}, /* l0, parity +1 */
    { 0,  0, -1,  0,  0, -1}, /* l1, parity +1 */
    { 1,  1,  1,  2,  0,  1}, /* l2, parity +1 */
    { 0,  0,  1,  0,  0, -1}, /* l3, parity -1 */
    { 1,  1,  1,  0,  0,  1}, /* l4, parity -1 */
    { 1,  1,  1,  2,  2,  1}, /* l5, parity -1 */
    { 0,  2,  1,  2,  0,  1}, /* l6, parity -1 */
};
static const int PARITY_B[7] = { 1, 1, 1, -1, -1, -1, -1 };

/* Fano incidence matrix I[l][p] = 1 iff dot(l, p) == 0 mod 2 (1-indexed vectors 1..7) */
static int fano_inc(int l, int p) {
    int lv = l + 1, pv = p + 1;
    int d = (((lv >> 2) & 1) * ((pv >> 2) & 1)
           + ((lv >> 1) & 1) * ((pv >> 1) & 1)
           + (lv & 1) * (pv & 1)) & 1;
    return d == 0 ? 1 : 0;
}

/* Check if grid point (gx, gy) (representing (gx/N, gy/N)) lies inside or on closed triangle t.
 * Also returns barycentric (s, t_b) in [0, N] along V0->V1 and V0->V2 via out pointers. */
static int pt_in_tri(const Tri *t, int N, int gx, int gy, int *out_s, int *out_tb) {
    int ax = t->x1 - t->x0, ay = t->y1 - t->y0; /* unit vector along leg a */
    int bx = t->x2 - t->x0, by = t->y2 - t->y0; /* unit vector along leg b */
    int dx = gx - t->x0 * N;
    int dy = gy - t->y0 * N;
    /* Since a, b are orthonormal lattice vectors: s = d.a, tb = d.b */
    int s = dx * ax + dy * ay;
    int tb = dx * bx + dy * by;
    if (s >= 0 && tb >= 0 && s + tb <= N) {
        if (out_s) *out_s = s;
        if (out_tb) *out_tb = tb;
        return 1;
    }
    return 0;
}

typedef struct {
    int N;
    int min_gx, max_gx, min_gy, max_gy, W, H;
    int M;           /* number of strictly interior grid nodes */
    int *grid_id;    /* size W*H: interior node index [0..M-1], or -1 if outside/boundary */
    int *node_gx;    /* size M */
    int *node_gy;    /* size M */
    int *node_tri;   /* size M: triangle index 0..6 (for interior) or -1 if on interior shared edge */
    int bw;          /* half-bandwidth of L_h */
    double *chol;    /* band Cholesky factor R (row-major, M * (bw+1)) */
} DrumGrid;

static int in_union(const Tri tris[7], int N, int gx, int gy) {
    for (int k = 0; k < 7; k++) {
        if (pt_in_tri(&tris[k], N, gx, gy, NULL, NULL)) return 1;
    }
    return 0;
}

/* Strictly interior: (gx, gy) is in the union AND all 8 surrounding half-grid points
 * (2*gx +/- 1, 2*gy +/- 1) at scale 2*N lie inside the union!
 * Wait: on a right-isosceles polygon, a point (gx, gy) is strictly interior to the open
 * polygon iff all 8 octant probes (4*gx + dx, 4*gy + dy) for (dx, dy) in {+-1, +-2} ...
 * Simplest exact test: a lattice point (gx, gy) is strictly interior iff all 8 small
 * probes at radius 1/4 (i.e. scale 4*N: (4*gx + ox, 4*gy + oy) for (ox,oy) in
 * {(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)}) lie in the closed union! */
static int strictly_interior(const Tri tris[7], int N, int gx, int gy) {
    static const int ox[8] = { 2, -2,  0,  0,  1, -1,  1, -1 };
    static const int oy[8] = { 0,  0,  2, -2,  1,  1, -1, -1 };
    for (int d = 0; d < 8; d++) {
        if (!in_union(tris, 4 * N, 4 * gx + ox[d], 4 * gy + oy[d])) return 0;
    }
    return 1;
}

static void build_grid(DrumGrid *G, const Tri tris[7], int N) {
    G->N = N;
    int minx = 100, maxx = -100, miny = 100, maxy = -100;
    for (int k = 0; k < 7; k++) {
        int xs[3] = { tris[k].x0, tris[k].x1, tris[k].x2 };
        int ys[3] = { tris[k].y0, tris[k].y1, tris[k].y2 };
        for (int j = 0; j < 3; j++) {
            if (xs[j] < minx) minx = xs[j];
            if (xs[j] > maxx) maxx = xs[j];
            if (ys[j] < miny) miny = ys[j];
            if (ys[j] > maxy) maxy = ys[j];
        }
    }
    G->min_gx = minx * N; G->max_gx = maxx * N;
    G->min_gy = miny * N; G->max_gy = maxy * N;
    G->W = G->max_gx - G->min_gx + 1;
    G->H = G->max_gy - G->min_gy + 1;
    G->grid_id = (int *)malloc((size_t)G->W * (size_t)G->H * sizeof(int));
    for (int i = 0; i < G->W * G->H; i++) G->grid_id[i] = -1;

    /* Order along the shorter axis to minimize band Cholesky half-bandwidth! */
    int sweep_y_outer = (G->W <= G->H);
    int M = 0;
    if (sweep_y_outer) {
        for (int gy = G->min_gy; gy <= G->max_gy; gy++) {
            for (int gx = G->min_gx; gx <= G->max_gx; gx++) {
                if (strictly_interior(tris, N, gx, gy)) {
                    G->grid_id[(gy - G->min_gy) * G->W + (gx - G->min_gx)] = M++;
                }
            }
        }
    } else {
        for (int gx = G->min_gx; gx <= G->max_gx; gx++) {
            for (int gy = G->min_gy; gy <= G->max_gy; gy++) {
                if (strictly_interior(tris, N, gx, gy)) {
                    G->grid_id[(gy - G->min_gy) * G->W + (gx - G->min_gx)] = M++;
                }
            }
        }
    }
    G->M = M;
    G->node_gx = (int *)malloc((size_t)M * sizeof(int));
    G->node_gy = (int *)malloc((size_t)M * sizeof(int));
    G->node_tri = (int *)malloc((size_t)M * sizeof(int));
    for (int gy = G->min_gy; gy <= G->max_gy; gy++) {
        for (int gx = G->min_gx; gx <= G->max_gx; gx++) {
            int id = G->grid_id[(gy - G->min_gy) * G->W + (gx - G->min_gx)];
            if (id >= 0) {
                G->node_gx[id] = gx;
                G->node_gy[id] = gy;
                int found = -1, cnt = 0;
                for (int k = 0; k < 7; k++) {
                    if (pt_in_tri(&tris[k], N, gx, gy, NULL, NULL)) {
                        found = k;
                        cnt++;
                    }
                }
                G->node_tri[id] = (cnt == 1) ? found : -1;
            }
        }
    }

    /* Compute half-bandwidth */
    int bw = 0;
    static const int dx4[4] = { 1, -1, 0, 0 };
    static const int dy4[4] = { 0, 0, 1, -1 };
    for (int i = 0; i < M; i++) {
        int gx = G->node_gx[i], gy = G->node_gy[i];
        for (int d = 0; d < 4; d++) {
            int nx = gx + dx4[d], ny = gy + dy4[d];
            if (nx < G->min_gx || nx > G->max_gx || ny < G->min_gy || ny > G->max_gy) continue;
            int j = G->grid_id[(ny - G->min_gy) * G->W + (nx - G->min_gx)];
            if (j > i && j - i > bw) bw = j - i;
        }
    }
    G->bw = bw;

    /* Assemble upper band of unscaled 5-point Laplacian A (diag=4, neighbor=-1) and factor A = R^T R */
    int stride = bw + 1;
    double *R = (double *)calloc((size_t)M * (size_t)stride, sizeof(double));
    for (int i = 0; i < M; i++) {
        R[(size_t)i * stride + 0] = 4.0;
        int gx = G->node_gx[i], gy = G->node_gy[i];
        for (int d = 0; d < 4; d++) {
            int nx = gx + dx4[d], ny = gy + dy4[d];
            if (nx < G->min_gx || nx > G->max_gx || ny < G->min_gy || ny > G->max_gy) continue;
            int j = G->grid_id[(ny - G->min_gy) * G->W + (nx - G->min_gx)];
            if (j > i) {
                R[(size_t)i * stride + (j - i)] = -1.0;
            }
        }
    }

    /* In-place band Cholesky factorization: A = R^T R (R stored upper banded) */
    for (int i = 0; i < M; i++) {
        double *Ri = R + (size_t)i * stride;
        double diag = Ri[0];
        if (diag <= 0.0) {
            fprintf(stderr, "Cholesky failed at row %d (diag=%.3e)\n", i, diag);
            exit(1);
        }
        double rii = sqrt(diag);
        Ri[0] = rii;
        double inv_rii = 1.0 / rii;
        int kmax = (i + bw < M) ? bw : (M - 1 - i);
        for (int k = 1; k <= kmax; k++) {
            Ri[k] *= inv_rii;
        }
        for (int k = 1; k <= kmax; k++) {
            double rik = Ri[k];
            if (rik == 0.0) continue;
            double *Rik_row = R + (size_t)(i + k) * stride;
            int jmax = kmax - k;
            for (int j = 0; j <= jmax; j++) {
                Rik_row[j] -= rik * Ri[k + j];
            }
        }
    }
    G->chol = R;
}

/* Solve A * y = x using precomputed band Cholesky R^T R y = x */
static void solve_invA(const DrumGrid *G, const double *x, double *y) {
    int M = G->M, bw = G->bw, stride = bw + 1;
    const double *R = G->chol;
    memcpy(y, x, (size_t)M * sizeof(double));

    /* Forward solve R^T z = x */
    for (int i = 0; i < M; i++) {
        const double *Ri = R + (size_t)i * stride;
        double zi = y[i] / Ri[0];
        y[i] = zi;
        int kmax = (i + bw < M) ? bw : (M - 1 - i);
        for (int k = 1; k <= kmax; k++) {
            y[i + k] -= Ri[k] * zi;
        }
    }
    /* Back solve R y = z */
    for (int i = M - 1; i >= 0; i--) {
        const double *Ri = R + (size_t)i * stride;
        double sum = y[i];
        int kmax = (i + bw < M) ? bw : (M - 1 - i);
        for (int k = 1; k <= kmax; k++) {
            sum -= Ri[k] * y[i + k];
        }
        y[i] = sum / Ri[0];
    }
}

/* Multiply y = (N^2 * A) * x */
static void apply_L(const DrumGrid *G, const double *x, double *y) {
    int M = G->M;
    double scale = (double)G->N * (double)G->N;
    static const int dx4[4] = { 1, -1, 0, 0 };
    static const int dy4[4] = { 0, 0, 1, -1 };
    for (int i = 0; i < M; i++) {
        double acc = 4.0 * x[i];
        int gx = G->node_gx[i], gy = G->node_gy[i];
        for (int d = 0; d < 4; d++) {
            int nx = gx + dx4[d], ny = gy + dy4[d];
            if (nx < G->min_gx || nx > G->max_gx || ny < G->min_gy || ny > G->max_gy) continue;
            int j = G->grid_id[(ny - G->min_gy) * G->W + (nx - G->min_gx)];
            if (j >= 0) acc -= x[j];
        }
        y[i] = scale * acc;
    }
}

/* EISPACK tql2: eigenvalues and eigenvectors of symmetric tridiagonal matrix (d[0..n-1], e[1..n-1]) */
static void tql2(int n, double *d, double *e, double *z) {
    for (int i = 1; i < n; i++) e[i - 1] = e[i];
    e[n - 1] = 0.0;
    double f = 0.0, tst1 = 0.0;
    const double eps = 2.220446049250313e-16;
    for (int l = 0; l < n; l++) {
        double h = fabs(d[l]) + fabs(e[l]);
        if (tst1 < h) tst1 = h;
        int m = l;
        while (m < n) {
            if (fabs(e[m]) <= eps * tst1) break;
            m++;
        }
        if (m > l) {
            int iter = 0;
            do {
                iter++;
                if (iter > 100) { fprintf(stderr, "tql2 did not converge\n"); exit(1); }
                double g = d[l];
                double p = (d[l + 1] - g) / (2.0 * e[l]);
                double r = hypot(p, 1.0);
                if (p < 0.0) r = -r;
                d[l] = e[l] / (p + r);
                d[l + 1] = e[l] * (p + r);
                double dl1 = d[l + 1];
                double h0 = g - d[l];
                for (int i = l + 2; i < n; i++) d[i] -= h0;
                f += h0;

                p = d[m];
                double c = 1.0, c2 = 1.0, c3 = 1.0;
                double el1 = e[l + 1];
                double s = 0.0, s2 = 0.0;
                for (int i = m - 1; i >= l; i--) {
                    c3 = c2; c2 = c; s2 = s;
                    g = c * e[i];
                    h = c * p;
                    r = hypot(p, e[i]);
                    e[i + 1] = s * r;
                    s = e[i] / r;
                    c = p / r;
                    p = c * d[i] - s * g;
                    d[i + 1] = h + s * (c * g + s * d[i]);
                    for (int k = 0; k < n; k++) {
                        double zk1 = z[k * n + (i + 1)];
                        double zk0 = z[k * n + i];
                        z[k * n + (i + 1)] = s * zk0 + c * zk1;
                        z[k * n + i] = c * zk0 - s * zk1;
                    }
                }
                p = -s * s2 * c3 * el1 * e[l] / dl1;
                e[l] = s * p;
                d[l] = c * p;
            } while (fabs(e[l]) > eps * tst1);
        }
        d[l] += f;
        e[l] = 0.0;
    }
    /* Sort descending by d[] (largest eigenvalues of A^{-1} = smallest eigenvalues of L_h) */
    for (int i = 0; i < n - 1; i++) {
        int k = i;
        double p = d[i];
        for (int j = i + 1; j < n; j++) {
            if (d[j] > p) { k = j; p = d[j]; }
        }
        if (k != i) {
            d[k] = d[i]; d[i] = p;
            for (int j = 0; j < n; j++) {
                double tmp = z[j * n + i];
                z[j * n + i] = z[j * n + k];
                z[j * n + k] = tmp;
            }
        }
    }
}

/* Shift-invert Lanczos on A^{-1} with full DGKS reorthogonalization.
 * Returns K lowest eigenvalues of L_h in evals[0..K-1] and unit eigenvectors in evecs[k*M + i]. */
static void solve_eig(const DrumGrid *G, int K, uint64_t seed, double *evals, double *evecs) {
    int M = G->M;
    int m = K * 2 + 45;
    if (m > M) m = M;

    double *Q = (double *)malloc((size_t)m * (size_t)M * sizeof(double));
    double *alpha = (double *)calloc((size_t)m, sizeof(double));
    double *beta = (double *)calloc((size_t)(m + 1), sizeof(double));
    double *w = (double *)malloc((size_t)M * sizeof(double));

    /* Deterministic splitmix64 random start vector */
    uint64_t st = seed;
    double nrm = 0.0;
    for (int i = 0; i < M; i++) {
        st += 0x9e3779b97f4a7c15ULL;
        uint64_t z = st;
        z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
        z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
        z = z ^ (z >> 31);
        double v = ((double)(int64_t)z) / 9.223372036854776e18;
        Q[i] = v;
        nrm += v * v;
    }
    nrm = sqrt(nrm);
    for (int i = 0; i < M; i++) Q[i] /= nrm;

    int steps = m;
    for (int j = 0; j < m; j++) {
        const double *qj = Q + (size_t)j * M;
        solve_invA(G, qj, w);
        if (j > 0) {
            const double *qprev = Q + (size_t)(j - 1) * M;
            double bj = beta[j];
            for (int i = 0; i < M; i++) w[i] -= bj * qprev[i];
        }
        double aj = 0.0;
        for (int i = 0; i < M; i++) aj += qj[i] * w[i];
        alpha[j] = aj;
        for (int i = 0; i < M; i++) w[i] -= aj * qj[i];

        /* Full DGKS (two-pass classical Gram-Schmidt) reorthogonalization */
        for (int pass = 0; pass < 2; pass++) {
            for (int t = 0; t <= j; t++) {
                const double *qt = Q + (size_t)t * M;
                double dot = 0.0;
                for (int i = 0; i < M; i++) dot += qt[i] * w[i];
                for (int i = 0; i < M; i++) w[i] -= dot * qt[i];
            }
        }
        double bnext = 0.0;
        for (int i = 0; i < M; i++) bnext += w[i] * w[i];
        bnext = sqrt(bnext);
        if (bnext < 1e-14 || j == m - 1) {
            steps = j + 1;
            break;
        }
        beta[j + 1] = bnext;
        double *qnext = Q + (size_t)(j + 1) * M;
        double inv_b = 1.0 / bnext;
        for (int i = 0; i < M; i++) qnext[i] = w[i] * inv_b;
    }

    double *Z = (double *)calloc((size_t)steps * (size_t)steps, sizeof(double));
    for (int i = 0; i < steps; i++) Z[i * steps + i] = 1.0;
    double *d = (double *)malloc((size_t)steps * sizeof(double));
    double *e = (double *)malloc((size_t)steps * sizeof(double));
    memcpy(d, alpha, (size_t)steps * sizeof(double));
    memcpy(e, beta, (size_t)steps * sizeof(double));

    tql2(steps, d, e, Z);

    double scale = (double)G->N * (double)G->N;
    for (int k = 0; k < K; k++) {
        evals[k] = scale / d[k];
        double *uk = evecs + (size_t)k * M;
        memset(uk, 0, (size_t)M * sizeof(double));
        for (int j = 0; j < steps; j++) {
            double c = Z[j * steps + k];
            const double *qj = Q + (size_t)j * M;
            for (int i = 0; i < M; i++) uk[i] += c * qj[i];
        }
        /* Canonicalize sign (largest-magnitude entry positive) and normalize */
        double n2 = 0.0, maxv = 0.0;
        int maxi = 0;
        for (int i = 0; i < M; i++) {
            n2 += uk[i] * uk[i];
            if (fabs(uk[i]) > maxv) { maxv = fabs(uk[i]); maxi = i; }
        }
        double inv = (uk[maxi] >= 0.0 ? 1.0 : -1.0) / sqrt(n2);
        for (int i = 0; i < M; i++) uk[i] *= inv;
    }

    free(Q); free(alpha); free(beta); free(w); free(Z); free(d); free(e);
}

/* Count connected nodal domains (4-connected components of u > tol and u < -tol). */
static int count_nodal_domains(const DrumGrid *G, const double *u, int *out_pos, int *out_neg) {
    int M = G->M;
    double maxv = 0.0;
    for (int i = 0; i < M; i++) if (fabs(u[i]) > maxv) maxv = fabs(u[i]);
    double tol = 1e-9 * maxv;

    uint8_t *vis = (uint8_t *)calloc((size_t)M, 1);
    int *queue = (int *)malloc((size_t)M * sizeof(int));
    static const int dx4[4] = { 1, -1, 0, 0 };
    static const int dy4[4] = { 0, 0, 1, -1 };
    int pos = 0, neg = 0;
    for (int start = 0; start < M; start++) {
        if (vis[start]) continue;
        int sgn = (u[start] > tol) ? 1 : (u[start] < -tol ? -1 : 0);
        if (sgn == 0) continue;
        if (sgn > 0) pos++; else neg++;
        int qh = 0, qt = 0;
        vis[start] = 1;
        queue[qt++] = start;
        while (qh < qt) {
            int cur = queue[qh++];
            int gx = G->node_gx[cur], gy = G->node_gy[cur];
            for (int d = 0; d < 4; d++) {
                int nx = gx + dx4[d], ny = gy + dy4[d];
                if (nx < G->min_gx || nx > G->max_gx || ny < G->min_gy || ny > G->max_gy) continue;
                int nb = G->grid_id[(ny - G->min_gy) * G->W + (nx - G->min_gx)];
                if (nb < 0 || vis[nb]) continue;
                int ns = (u[nb] > tol) ? 1 : (u[nb] < -tol ? -1 : 0);
                if (ns == sgn) {
                    vis[nb] = 1;
                    queue[qt++] = nb;
                }
            }
        }
    }
    free(vis); free(queue);
    if (out_pos) *out_pos = pos;
    if (out_neg) *out_neg = neg;
    return pos + neg;
}

/* Map point (s, tb) inside base triangle -> grid node index on drum G for triangle tri_idx */
static int tri_point_to_node(const DrumGrid *G, const Tri tris[7], int tri_idx, int s, int tb) {
    const Tri *t = &tris[tri_idx];
    int gx = t->x0 * G->N + s * (t->x1 - t->x0) + tb * (t->x2 - t->x0);
    int gy = t->y0 * G->N + s * (t->y1 - t->y0) + tb * (t->y2 - t->y0);
    if (gx < G->min_gx || gx > G->max_gx || gy < G->min_gy || gy > G->max_gy) return -1;
    return G->grid_id[(gy - G->min_gy) * G->W + (gx - G->min_gx)];
}

/* Apply exact Fano-plane transplantation v_B = (S_B * I * S_A) u_A on strictly-interior triangle points
 * and measure cosine similarity + exact L2 scaling factor against u_B! */
static void check_transplantation(
    const DrumGrid *GA, const DrumGrid *GB,
    const double *uA, const double *uB,
    double *out_scale, double *out_rel_err, double *out_parity_sum_ratio
) {
    int N = GA->N;
    double num_dot = 0.0, vB_n2 = 0.0, uB_n2 = 0.0;
    double psum_n2 = 0.0, uA_in_n2 = 0.0;
    /* Iterate over strictly interior points of the base triangle: s > 0, tb > 0, s + tb < N */
    for (int s = 1; s < N; s++) {
        for (int tb = 1; s + tb < N; tb++) {
            double valsA[7];
            double psum = 0.0;
            for (int p = 0; p < 7; p++) {
                int idA = tri_point_to_node(GA, DRUM_A, p, s, tb);
                valsA[p] = (idA >= 0) ? uA[idA] : 0.0;
                psum += PARITY_A[p] * valsA[p];
                uA_in_n2 += valsA[p] * valsA[p];
            }
            psum_n2 += psum * psum;
            for (int l = 0; l < 7; l++) {
                double acc = 0.0;
                for (int p = 0; p < 7; p++) {
                    if (fano_inc(l, p)) {
                        acc += (double)(PARITY_B[l] * PARITY_A[p]) * valsA[p];
                    }
                }
                int idB = tri_point_to_node(GB, DRUM_B, l, s, tb);
                double ub = (idB >= 0) ? uB[idB] : 0.0;
                vB_n2 += acc * acc;
                uB_n2 += ub * ub;
                num_dot += acc * ub;
            }
        }
    }
    double scale = sqrt(vB_n2 / uA_in_n2);
    double sign = (num_dot >= 0.0) ? 1.0 : -1.0;
    double cos_sim = fabs(num_dot) / sqrt(vB_n2 * uB_n2);
    /* Relative L2 error between normalized transplanted vector and uB */
    double rel_err = sqrt(fmax(0.0, 2.0 * (1.0 - cos_sim)));
    (void)sign;
    *out_scale = scale;
    *out_rel_err = rel_err;
    *out_parity_sum_ratio = sqrt(psum_n2 / uA_in_n2);
}

int main(int argc, char **argv) {
    if (argc < 4) {
        fprintf(stderr, "Usage: %s <N> <K> <out_prefix> [dump_modes_csv]\n", argv[0]);
        return 1;
    }
    int N = atoi(argv[1]);
    int K = atoi(argv[2]);
    const char *prefix = argv[3];
    const char *dump_csv = (argc >= 5) ? argv[4] : NULL;

    DrumGrid GA, GB;
    build_grid(&GA, DRUM_A, N);
    build_grid(&GB, DRUM_B, N);
    fprintf(stderr, "N=%d: M_A=%d (bw=%d), M_B=%d (bw=%d)\n", N, GA.M, GA.bw, GB.M, GB.bw);

    double *evA = (double *)malloc((size_t)K * sizeof(double));
    double *evB = (double *)malloc((size_t)K * sizeof(double));
    double *evA2 = (double *)malloc((size_t)K * sizeof(double));
    double *uA = (double *)malloc((size_t)K * (size_t)GA.M * sizeof(double));
    double *uB = (double *)malloc((size_t)K * (size_t)GB.M * sizeof(double));
    double *uA2 = (double *)malloc((size_t)K * (size_t)GA.M * sizeof(double));
    double *tmpA = (double *)malloc((size_t)GA.M * sizeof(double));
    double *tmpB = (double *)malloc((size_t)GB.M * sizeof(double));

    solve_eig(&GA, K, 0x123456789abcdef0ULL, evA, uA);
    solve_eig(&GB, K, 0xfedcba9876543210ULL, evB, uB);
    /* Second independent random seed on A to detect any exact degeneracies! */
    solve_eig(&GA, K, 0xdeadbeefcafebabeULL, evA2, uA2);

    char tsv_path[512];
    snprintf(tsv_path, sizeof(tsv_path), "%s_spectrum.tsv", prefix);
    FILE *fp = fopen(tsv_path, "w");
    fprintf(fp, "k\tlam_A\tlam_B\tabs_diff\trel_diff\tres_A\tres_B\tnodal_A\tnodal_B\tsplit\ttrans_scale\ttrans_err\tparity_sum\tsimple_cos\n");

    double max_rel_diff = 0.0;
    int split_count = 0;
    for (int k = 0; k < K; k++) {
        const double *ua = uA + (size_t)k * GA.M;
        const double *ub = uB + (size_t)k * GB.M;
        const double *ua2 = uA2 + (size_t)k * GA.M;
        apply_L(&GA, ua, tmpA);
        apply_L(&GB, ub, tmpB);
        double rA = 0.0, rB = 0.0, scos = 0.0;
        for (int i = 0; i < GA.M; i++) {
            double d = tmpA[i] - evA[k] * ua[i];
            rA += d * d;
            scos += ua[i] * ua2[i];
        }
        for (int i = 0; i < GB.M; i++) {
            double d = tmpB[i] - evB[k] * ub[i];
            rB += d * d;
        }
        rA = sqrt(rA) / evA[k];
        rB = sqrt(rB) / evB[k];

        int pA, nA, pB, nB;
        int ndA = count_nodal_domains(&GA, ua, &pA, &nA);
        int ndB = count_nodal_domains(&GB, ub, &pB, &nB);
        if (ndA != ndB) split_count++;

        double tscale = 0.0, terr = 0.0, psum = 0.0;
        check_transplantation(&GA, &GB, ua, ub, &tscale, &terr, &psum);

        double adiff = fabs(evA[k] - evB[k]);
        double rdiff = adiff / evA[k];
        if (rdiff > max_rel_diff) max_rel_diff = rdiff;

        fprintf(fp, "%d\t%.12f\t%.12f\t%.3e\t%.3e\t%.3e\t%.3e\t%d\t%d\t%d\t%.6f\t%.3e\t%.3e\t%.12f\n",
                k + 1, evA[k], evB[k], adiff, rdiff, rA, rB, ndA, ndB,
                ndA != ndB ? 1 : 0, tscale, terr, psum, fabs(scos));
    }
    fclose(fp);
    fprintf(stderr, "Done! max_rel_diff=%.3e, nodal_splits=%d/%d -> %s\n", max_rel_diff, split_count, K, tsv_path);

    /* Optionally dump requested modes (1-based CSV) as raw binary grid arrays for plotting */
    if (dump_csv && dump_csv[0]) {
        char buf[512];
        strncpy(buf, dump_csv, sizeof(buf) - 1);
        buf[sizeof(buf) - 1] = '\0';
        for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) {
            int k1 = atoi(tok);
            if (k1 < 1 || k1 > K) continue;
            int k = k1 - 1;
            const DrumGrid *Gs[2] = { &GA, &GB };
            const double *Us[2] = { uA + (size_t)k * GA.M, uB + (size_t)k * GB.M };
            const char *tags[2] = { "A", "B" };
            for (int d = 0; d < 2; d++) {
                char mpath[512];
                snprintf(mpath, sizeof(mpath), "%s_mode%d_%s.bin", prefix, k1, tags[d]);
                FILE *mf = fopen(mpath, "wb");
                int hdr[6] = { Gs[d]->N, Gs[d]->W, Gs[d]->H, Gs[d]->min_gx, Gs[d]->min_gy, k1 };
                fwrite(hdr, sizeof(int), 6, mf);
                double lam = (d == 0) ? evA[k] : evB[k];
                fwrite(&lam, sizeof(double), 1, mf);
                double *img = (double *)malloc((size_t)Gs[d]->W * (size_t)Gs[d]->H * sizeof(double));
                for (int i = 0; i < Gs[d]->W * Gs[d]->H; i++) {
                    int id = Gs[d]->grid_id[i];
                    img[i] = (id >= 0) ? Us[d][id] : NAN;
                }
                fwrite(img, sizeof(double), (size_t)Gs[d]->W * (size_t)Gs[d]->H, mf);
                fclose(mf);
                free(img);
            }
        }
    }

    free(evA); free(evB); free(evA2); free(uA); free(uB); free(uA2); free(tmpA); free(tmpB);
    free(GA.grid_id); free(GA.node_gx); free(GA.node_gy); free(GA.node_tri); free(GA.chol);
    free(GB.grid_id); free(GB.node_gx); free(GB.node_gy); free(GB.node_tri); free(GB.chol);
    return 0;
}
