REED-SOLOMON IS LEAVING 40% OF YOUR PARITY ON THE TABLE?! I Searched 16,377 Payload Lengths and Found 97,612 Codes That Beat It — All 58 Polynomials + Full Source!

rssearch: a C search program that tested every payload length from 8 to 16,384 bytes for a polynomial more bit-efficient than Reed-Solomon. 97,612 finds, 58 polynomials, 35-56% less parity — all listed, with the full source code.

REED-SOLOMON IS LEAVING 40% OF YOUR PARITY ON THE TABLE?! I Searched 16,377 Payload Lengths and Found 97,612 Codes That Beat It — All 58 Polynomials + Full Source!
rssearch hero: binary digits flowing through a glowing polynomial curve, corrupted bits being repaired by parity symbols

I asked a simple question: is there a polynomial more bit-efficient than Reed-Solomon for a given payload? Reed-Solomon is the gold standard of error correction — it is MDS, it meets the Singleton bound, and for byte errors nothing beats it. But my payloads are bit streams, not byte streams, and for bit errors the rules change. So I wrote a search program, pointed it at every payload length from 8 to 16,384 bytes, let it use all four cores, and left it running.

It finished in 274.4 seconds. And the answer is: yes, almost everywhere.

THE HEADLINE NUMBERS

  • 97,612 finds out of 98,262 possible (length, t) pairs — 99.34% coverage.
  • 58 distinct generator polynomials, each with a 2-byte ID, all in finds.h.
  • 10,256,528 parity bits saved in total across all finds — about 1.28 MB of parity you never have to store or transmit.
  • Best single saving: 384 bits at L=16,384, t=32 (576 parity bits instead of Reed-Solomon's 960).
  • Best saving ratio: 56.2% at L=8, t=1 (7 parity bits instead of 16).
  • Every length from 8 to 16,384 bytes has a winning code at t=1. All 16,377 of them.
  • The 857-byte payload that started this project wins at all six t values, saving a clean 35% every time.

THE HARD TRUTH FIRST

Reed-Solomon is MDS — Maximum Distance Separable. It meets the Singleton bound d = n − k + 1 exactly, which means no code can beat it for arbitrary byte errors. If your error model is "up to t whole bytes can be wrong", Reed-Solomon is optimal and this search would find nothing. That is a theorem, not a challenge.

But my error model is bit errors: up to t individual bits can flip, anywhere in the payload. A bit error damages at most one byte, but a byte-oriented code has to budget for the worst case — t whole bytes — even though only t bits are actually wrong. That gap is where binary codes win. A binary BCH code correcting t bit errors needs roughly t·log₂(n) parity bits. Reed-Solomon needs 2·t·m bits, where m is the field size in bits. For a 16,384-byte payload (131,072 bits), BCH needs 18 parity bits per error and Reed-Solomon needs 30. That is the whole game: 18 vs 30, per error, at every length.

PRIOR ART — WHAT IS NEW HERE AND WHAT IS NOT

This section was added after publication, following a prior-art check. It corrects the article's framing: the polynomials are not new discoveries.

The polynomials are not new. Every one of the 58 is a narrow-sense primitive BCH generator polynomial — the standard construction of Bose, Chaudhuri and Hocquenghem (1959–1960). I verified this directly: each of the 58 equals the generator built from the defining set {1, …, 2t} under the search's own field, so all 58 are the textbook narrow-sense codes. The generators for the smaller parents are printed in published tables: Clark & Cain, Error-Correction Coding for Digital Communications (Springer, 1981), Appendix A Table A-1, prints them for N = 7…255, and Peterson & Weldon's irreducible-polynomial tables (complete through degree 16) let you construct every primitive BCH code through N = 65535. MathWorks' bchgenpoly covers the same range (M ≤ 16). Shortening primitive BCH codes to get better codes was itself published by Helgert & Stinaff in 1973 ("Shortened BCH codes", IEEE Transactions on Information Theory 19(6), 818–820), who showed shortened BCH codes with minimum distance "superior to any known previously". The (n, k, d) parameters also appear in Grassl's codetables.de — though that database only covers binary codes up to n = 256, so nearly all of these codes fall outside it, and the ones inside it are attributed to other constructions rather than labelled BCH.

Two things are new. First, the 12 polynomials for m = 17 and 18 (N = 131071 and 262143 — the 8192–16383-byte band and the 16384-byte length, IDs 002f–003a) are not in any of those tables. Peterson & Weldon gives only one minimum-weight primitive polynomial per degree for 17–34, not the full irreducible factorisation, so those generators cannot be looked up — they have to be computed. As far as I can verify, this article is the first place they are printed. Second, the systematic comparison itself: no published table I could find turns the BCH-versus-Reed-Solomon arithmetic into a per-(length, t) parity-savings table over 8–16384-byte payloads for bit errors. The arithmetic is textbook; the exhaustive grid, the exact savings, and the machine-readable finds.h are the new contribution.

One caveat about the hex strings. "The" generator polynomial is not unique — it depends on which primitive polynomial defines GF(2m). The textbooks each fix one specific primitive polynomial per m; this search picks its primitive root deterministically (smallest field element first), so the literal hex in the table below differs from the textbook tables while generating equivalent codes with identical parameters. If you compare against Clark & Cain or MathWorks, expect different bytes for the same code. The IDs, degrees, parents and savings are unaffected.

THE DEAD END I FOUND FIRST (AND WHY IT MATTERS)

The first design was wrong, and I caught it while writing the evaluator — before a single core was spent on it. The plan was to enumerate exact-length cyclic codes: generators g(x) dividing xn+1 where n is the payload length in bits, evaluated by the BCH bound. That design is mathematically invalid, and the proof is seven bits long.

Take the Hamming generator g = x³+x+1, a (7,4) code with distance 3. Put it at length n=14. The codeword 1+x⁹ is divisible by g (because g divides x⁹+1), and it has weight 2. So the distance is 2, not 3. In general, every squarefree exact-length cyclic code at even n has distance 2, because xo+1 (o the odd part of n) is always a weight-2 codeword. The BCH bound is only valid when the code length equals the modulus — and at even n it does not. The divisor table I computed first (95 million squarefree candidates, 451 million with multiplicities) was structural evidence for exactly this: at 857 bytes and 922 bytes there are only trivial codes, because the interesting factors have degree 428 and 460.

So the exact-length tier was deleted and replaced. The primary family is shortened BCH: take a parent cyclic BCH code of odd length N = 2m − 1 (where the BCH bound is valid), and shorten it to exactly n bits by deleting coordinates. Shortening preserves distance. That is the family that produced all 97,612 finds.

HOW THE SEARCH WORKS

For each payload length L (8 to 16,384 bytes, so n = 8L bits), and each t in {1, 2, 4, 8, 16, 32}:

  • Parents: every m from the smallest with 2m−1 ≥ n up to m=20 (N up to 1,048,575).
  • Defining set: the closure under ×2 (mod N) of a window of 2t consecutive residues {b..b+2t−1}. A sliding window over the parent finds the minimum-parity set in O(N) per (parent, t) — no exponential enumeration.
  • Distance: the BCH bound on the parent (a run of 2t consecutive residues gives d ≥ 2t+1), plus a stepped (multiplier) bound to raise the reported d when the cosets allow it.
  • Parity cap: r ≤ n/8, as specified — parity can be at most one eighth of the bitstream.
  • Find: a binary code with fewer parity bits than Reed-Solomon needs for the same (L, t), or equal parity with larger distance.
  • Recovery: g(x) is recovered from the defining set by computing minimal polynomials in GF(2D), cached by coset. Each distinct polynomial gets a sequential 2-byte (uint16_t) ID.

Two more tiers run alongside. Tier R evaluates exact repeated-root cyclic codes by exact minimum distance (not a bound) for n ≤ 64 bits, t ≤ 2 — a validation tier for the d=2 finding. Tier 3 is a gated polish: greedy single-coset removal on shortened-BCH bests that are not already finds. Tier R found zero finds in the whole crawl, which is itself a result: at tiny lengths the repeated-root codes never beat shortened BCH. All 97,612 finds are shortened BCH.

Work is distributed by atomic counter, one length per unit. The total work — 197,476,256,636 sliding-window steps — is computed at startup by the same counting loop as the search, so the ETA in the log is real, not a guess. A tail-able search.log prints a STATUS line every 60 seconds; status.json is rewritten every 10 seconds; state/done.bin checkpoints completed lengths so --resume picks up exactly where it stopped.

THE 857-BYTE PAYLOAD

The length that started this project. 857 bytes is 6,856 bits; 857 is prime, and ord₈₅₇(2) = 428, so x857+1 factors as (x+1) times two irreducible factors of degree 428. There is no interesting exact-length cyclic code at 857 bytes — the cosets are too big. But shortened BCH from parent N=8191 (m=13, coset size 13) wins at every t:

t (bit errors)BCH parity rRS paritybits savedsavingpoly IDg(x) hex
11320735%00174b29
226401435%0018cbff5e04
452802835%0019c3df8ed4442b1d
81041605635%001a87d69f6d66eaa8e8eada2a969e01
1620832011235%001b4deefd7f6908f0d3702d8ccf32d528b675c2535f294b445b2ca901
3241664022435%001c57199bb26e55ccaa5822d48f4f2374d9e3af102bc7dbf8c3ba29ce567483f8d3ac0b54f8fb992daff479d65f7b38172c6e098d0101

The pattern is exact: r = 13·t, because each error costs one cyclotomic coset of size 13. Reed-Solomon needs 20 bits per error (2·10, since 857 bytes needs a 10-bit field). 13 vs 20 is the 35%. And 857 is not special — the same band (L=512..1023, parent 8191) wins at every length in it, because the coset size is a property of the parent, not the payload.

THE RESULTS, BY LENGTH

Parity bits to correct 8 bit errors: Reed-Solomon vs shortened BCH, log-log
Parity saved vs Reed-Solomon in percent, for t=1, 8, 32

The structure is almost embarrassingly regular. Lengths fall into bands, one per parent, and within a band the answer is the same polynomial for every length:

payload band (bytes)parent Nmr per errorRS bits per errorsaving
8–15127771656%
16–31255881650%
32–63511991850%
64–127102310102050%
128–255204711112045%
256–511409512122450%
512–1023819113132035%
1024–20471638314142850%
2048–40953276715152846%
4096–81916553516162843%
8192–1638313107117172839%
1638426214318183040%

Two things to notice. First, the saving is always 35–56% — never marginal, never zero. Second, the bands are powers of two because the parent is the smallest Mersenne number above the payload, and the Reed-Solomon field is the smallest power of two above the payload in bytes. The gap between them is structural, not a coincidence of one length.

THE 650 THAT GOT AWAY

650 of the 98,262 pairs are not finds, and they are all small: payloads of 8 to 383 bytes at t ≥ 2. The reason is the parity cap. At L=8 (64 bits) the cap allows at most 8 parity bits, but correcting 2 bit errors needs at least 10 — so no code, binary or otherwise, can fit. At L=9..383 the same squeeze applies at larger t. These are not cases where Reed-Solomon wins; they are cases where nothing fits under the cap. Lift the cap and they fall too. The cap was my choice, not a property of the codes.

ALL 82 POLYNOMIALS

Every distinct generator the crawl found, with its 2-byte ID, degree, hex (LSB-first, as stored in finds.h), the payload range and t values it wins, its parent, and how many (L, t) pairs it covers. These are the polynomials — all of them. The first 58 (IDs 0001–003a) are the original crawl, payloads 8–16,384 bytes. The last 24 (IDs 003b–0052) are the extension — the sweep was continued to m = 22, payloads up to 524,287 bytes — and they are listed separately in the EXTENSION section below. Read the prior-art section above before calling them discoveries: 46 of the original 58 are the textbook narrow-sense generators, and 12 of them — IDs 002f–003a, the m = 17 and 18 bands — are not in any published table. The extension adds 24 more polynomials that are likewise not in any published table (IDs 003b–0052, m = 19–22), so 36 of the 82 are unprinted anywhere else. The section after the table explains what those 12 buy you in a bitstream and how to use them.

IDdeg (bits)bytesg(x) hex (LSB-first)payload L (bytes)tparent N# (L,t) winstotal bits saved
000171ef8–151127872
0002142ed6814–152127236
0003822b0116–31125516128
0004163e3cb0116–31225516256
000592e30332–63151132224
00061832d750532–63251132448
00073651dfe9b6d1e36–63451128784
00081024d0764–1271102364384
000920303571b64–1272102364768
000a40643b7ae4c150164–12741023641536
000b80118391a1eb3a6a1c949dd10180–12781023482304
000c112270e128–25512047128640
000d223174e75128–255220471281280
000e4465d363decb414128–255420471282560
000f881237230ea55373746947a7f801128–255820471285120
001017623b5a329b5a2db00c4dbecc3d0ceca75f7a9776f05a9f601176–255162047806400
00111224517256–511140952561536
00122442d04cb01256–511240952563072
0013487396a7d41b53701256–511440952566144
00149613f7c3d19d41a630002eb724f301256–5118409525612288
0015192253da144268477229a09cab5673401dddaac5d6274c61052f601256–51116409525624576
001638449f76914326269d6b7acc60e2905073165cd333cd81dac6024a25caf3da9a840b0a2648d93d1bf2012dc0dc3f88d4c235701384–51132409512824576
00171324b29512–1023181915123584
0018264cbff5e04512–1023281915127168
0019527c3df8ed4442b1d512–10234819151214336
001a1041487d69f6d66eaa8e8eada2a969e01512–10238819151228672
001b208274deefd7f6908f0d3702d8ccf32d528b675c2535f294b445b2ca901512–102316819151257344
001c4165357199bb26e55ccaa5822d48f4f2374d9e3af102bc7dbf8c3ba29ce567483f8d3ac0b54f8fb992daff479d65f7b38172c6e098d0101512–1023328191512114688
001d14227461024–204711638310248192
001e28427c805111024–2047216383102416384
001f56825fc123b8191ec011024–2047416383102432768
002011215b92eabb2d2bbf8a047fd7d2a00cb011024–2047816383102465536
002122429fd049e66edff49939712f48f9e394d266465fda12804cbc2afb66262011024–204716163831024131072
002244857c98112c4cd44d080ca90105e80d9b9f5e820d729bc9a86be4585289c4db9f1434be012a82845f192f052bc67d7ea3a6afecc8c04e53cfc92011024–204732163831024262144
0023152d7b32048–4095132767204818432
00243046720026a2048–4095232767204836864
0025608e7932b84afba26102048–4095432767204873728
002612016051fd1f812e5d6ad3cd154a397fcb3012048–40958327672048147456
00272403145cb06b3396a99b44684405588931d215e377f23f911b71bbd8061459ce2012048–409516327672048294912
002848061b555f074f3f5d1497789e2f34c704441b9e676d63be89002a21a7a07a7ff28b908e8de6dda6e93523e231bb88e50ea493d1d548804be263b7f63fd91012048–409532327672048589824
0029163bd5f014096–8191165535409640960
002a325035b0105014096–8191265535409681920
002b64983505cacd5fec9e9014096–81914655354096163840
002c1281791d9402a4af3c438add208565c52434f014096–81918655354096327680
002d256332984721be7db8057e1d5c2341a8d5feda7f703de8f596063c37d3b22df535e70014096–819116655354096655360
002e51265090ba04ccc6576270344d7608197d904849ff52a86847fd3038577312f14bb58d91d84ddfe27f68152ff4dd3ab06271dfc398ccdff99c235e34ecadefaf09d24014096–8191326553540961310720
002f173ad11038192–163831131071819290112
0030345afd97451048192–1638321310718192180224
0031689f5f7b2c44b42cbba108192–1638341310718192360448
00321361887e0089903fe48db80b45264a17abf95d9018192–1638381310718192720896
00332723523d03f79577af3fe09f56ef5616257e3d097e447d919e696016f505131b18fc38baf018192–163831613107181921441792
003454469d9da54e65f0a25b90354140fc2e89699fdd7ab75ec1ddbdc057198773af8f52e4040ca7ce47c97272d44f6287d2d9893545fde298f567d537540b46d663b98af532d84d3018192–163833213107181922883584
0035183cff00416384–32767126214316384196608
00363651108139d1b16384–32767226214316384393216
003772109178324736002dfdc10116384–32767426214316384786432
00381441941b8cf7fa2c8b959848b3fb06b3cb7d2475f0116384–327678262143163841572864
0039288377da99ef844c1cc28a86c18a00e35ab8cbf387d421822bf1c17a4c67979accd5991cec2bd0116384–3276716262143163843145728
003a57673bd1153c48f5ea88e8fd79d3fa0512406e2ef28951add2d3f7f7f329afdca7a842014e54ed7a55b184d5046f712fa89429bad6edba543c059bee559586eaccbc7ee10312480bad4b30116384–3276732262143163846291456
003b193d54d0a32768–65535152428732768425984
003c3858955ec414332768–65535252428732768851968
003d761003372786174242edec1732768–655354524287327681703936
003e1522079392f72a4e446a926f519e3e57be7b9ef45790132768–655358524287327683407872
003f304397144cb3aebc8503a212e9c14552b60e3aee21aff31225ae3c005fe3b00a6b03282b24ae4ed930132768–6553516524287327686815744
0040608776142c522be8c20effc040878de86d590a925994a095838ed78d2e4a79a6a82b8b7b1781b0be44addb9046a1e325108671fed3f0502ba7689b29999a51aa57ba83d7406e86af69f42c69b5cc90132768–65535325242873276813631488
0041203570a1765536–1310711104857565536917504
00424063f023786ad0165536–13107121048575655361835008
00438011854001775765e8925d280165536–13107141048575655363670016
004416021c547aba37fd88839ffb1cf8a3554f2a9b94d7cb00165536–13107181048575655367340032
0045320417b0eb61fa2d1103b4f4b670a5e573027327c9d0582456811ed60d9b34dc359543c2c46aea71f574b0165536–1310711610485756553614680064
004664081f5e641929ea970330f06dfb1f16318b676f3850cb5134fa2babac87015a93cce491a91d6bf38d9a36c1a824433138ff1733603e73bd912fade0e8d2064a1bd73d5be0c1b22d64c69df3ac38b8422cc880165536–1310713210485756553629360128
0047213d94f3d131072–262143120971511310721966080
00484262bc2a1fbec04131072–262143220971511310723932160
00498411436b640527536adbf74014131072–262143420971511310727864320
004a1682281c45ac240759516ff3539e047573114ef67159b4701131072–2621438209715113107215728640
004b3364335c3ac767238b3dd137baf03f216c441bc9100bee2255b41e3e973d9d5a5fbe5792ce99171307f9c732801131072–26214316209715113107231457280
004c67285abee1b0d0a8efc2d3957cafea7515c8611cd6452c045a55840d7c0d3633fced616f154f47785f70b15d88ca7ebca904cfcaf405820361daea3af93caf962fefa524fcfc59f6b3b26b9f31facdde1d20ebb4c21db01131072–26214332209715113107262914560
004d2239ddf45262144–524287141943032621444194304
004e446b30a65570915262144–524287241943032621448388608
004f88124b4157f08ea21cf6afcb9601262144–5242874419430326214416777216
0050176238f6eb620ef524f7e17e8ea65bd9c8f6b6a56e63a80d101262144–5242878419430326214433554432
00513524569312b7efb029c178186713c7d009fe7c32b6e7f6172a4fde2511f281aa0af3550e1e95269f2973a34048b7101262144–52428716419430326214467108864
0052704897995986f3fd23e6fd8f6fe5423a86e4c92270f3ed814945552cd0e971c17f95c3f9d96139dfa950d79eceb413fb677527e96361af6c8a3b1cbc30b8a0ec39dca02fda43db6b97808a4f4d7d0754de2b07f8083d7a479d96001262144–524287324194303262144134217728

The pattern in the table is the whole story in one glance: each band contributes one polynomial per t, the degree is exactly t·m, and the largest bands dominate the count because they cover the most lengths. The six polynomials of the 8192–16383 band (IDs 002f–0034) each win 8,192 pairs. The six of the final length, L=16384 alone (IDs 0035–003a), each win exactly one pair — the top of the range.

EXTENSION — THE SWEEP CONTINUES TO m = 22, AND DIRECT CONSTRUCTION TO m = 256

This section was added after publication. The original crawl stopped at m = 18 (payloads to 16,384 bytes) because the search program could not run past m = 20. The program was fixed and the sweep was continued, one m at a time, until a single m took four hours. This section reports that sweep, and a second, cheaper construction that reaches m = 256.

The exhaustive sweep, m = 19 to m = 22

The original program capped the parent at m = 20 in two places: a fixed coset cache (COSETS_MAXO = 1048576) and 32-bit shifts (1 << m, which overflows at m = 31). Both were fixed — the coset cache became a dynamic list, and the shifts and length/parent indices were widened to 64-bit — and the modified program was verified to reproduce the m = 19 and m = 20 bands exactly (same parents, same parity, same distances) before the sweep continued. Then each band was run on the same 4-core server, one m at a time:

mpayload band (bytes)parent Nlengthstimework (steps)
19 + 2016,385–65,536524,287 / 1,048,57549,152816 s (13.6 min)489,620,865,036
20 (fill-in)65,537–131,0711,048,57565,535959 s (16.0 min)412,310,175,750
21131,072–262,1432,097,151131,0723,057 s (51 min)1,649,266,655,232
22262,144–524,2874,194,303262,14410,966 s (3.04 h)6,597,068,193,792

The m = 20 fill-in closes a gap: the first extension run stopped at L = 65,536, but the m = 20 parent serves L = 65,536–131,071, so the remainder was run separately. Coverage is now complete and gapless: every payload length from 8 to 524,287 bytes (524,280 lengths, 512 KiB minus one byte) has been scanned at all six t values.

The new bands continue the same regular structure — one parent per band, one polynomial per t, r = t·m:

payload band (bytes)parent Nmr per errorRS bits per errorsaving
16,384–32,767262,14318183040%
32,768–65,535524,28719193240.6%
65,536–131,0711,048,57520203441.2%
131,072–262,1432,097,15121213641.7%
262,144–524,2874,194,30322223842.1%

Note the first row: the m = 18 parent's full band is 16,384–32,767 bytes, not just the single length 16,384 the original crawl reached. The extension filled in 16,385–32,767 with the same six m = 18 polynomials (IDs 0035–003a). The headline numbers for the whole table are now:

  • 82 distinct generator polynomials (58 original + 24 new), IDs 0001–0052.
  • 3,145,030 finds out of 3,145,680 possible (length, t) pairs — 99.979% coverage. The 650 non-finds are unchanged: still only the original small payloads (8–383 bytes at t ≥ 2), still only the parity cap. Every new band has 100% coverage — all 3,047,418 new pairs are finds.
  • 495,386,012 parity bits saved in total — about 59 MiB of parity you never have to store or transmit. The extension alone adds 485,129,484 bits saved.
  • Best single saving: 512 bits at L = 524,287, t = 32 (704 parity bits instead of Reed-Solomon's 1,216).
  • Every length from 8 to 524,287 bytes has a winning code at t = 1. All 524,280 of them.

The 24 new polynomials (IDs 003b–0052), each verified narrow-sense (defining set {1..2t} under the run's own field, checked independently in Python):

IDdeg (bits)bytesg(x) hex (LSB-first)payload L (bytes)tparent N# (L,t) winstotal bits saved
003b193d54d0a32768–65535152428732768425984
003c3858955ec414332768–65535252428732768851968
003d761003372786174242edec1732768–655354524287327681703936
003e1522079392f72a4e446a926f519e3e57be7b9ef45790132768–655358524287327683407872
003f304397144cb3aebc8503a212e9c14552b60e3aee21aff31225ae3c005fe3b00a6b03282b24ae4ed930132768–6553516524287327686815744
0040608776142c522be8c20effc040878de86d590a925994a095838ed78d2e4a79a6a82b8b7b1781b0be44addb9046a1e325108671fed3f0502ba7689b29999a51aa57ba83d7406e86af69f42c69b5cc90132768–65535325242873276813631488
0041203570a1765536–1310711104857565536917504
00424063f023786ad0165536–13107121048575655361835008
00438011854001775765e8925d280165536–13107141048575655363670016
004416021c547aba37fd88839ffb1cf8a3554f2a9b94d7cb00165536–13107181048575655367340032
0045320417b0eb61fa2d1103b4f4b670a5e573027327c9d0582456811ed60d9b34dc359543c2c46aea71f574b0165536–1310711610485756553614680064
004664081f5e641929ea970330f06dfb1f16318b676f3850cb5134fa2babac87015a93cce491a91d6bf38d9a36c1a824433138ff1733603e73bd912fade0e8d2064a1bd73d5be0c1b22d64c69df3ac38b8422cc880165536–1310713210485756553629360128
0047213d94f3d131072–262143120971511310721966080
00484262bc2a1fbec04131072–262143220971511310723932160
00498411436b640527536adbf74014131072–262143420971511310727864320
004a1682281c45ac240759516ff3539e047573114ef67159b4701131072–2621438209715113107215728640
004b3364335c3ac767238b3dd137baf03f216c441bc9100bee2255b41e3e973d9d5a5fbe5792ce99171307f9c732801131072–26214316209715113107231457280
004c67285abee1b0d0a8efc2d3957cafea7515c8611cd6452c045a55840d7c0d3633fced616f154f47785f70b15d88ca7ebca904cfcaf405820361daea3af93caf962fefa524fcfc59f6b3b26b9f31facdde1d20ebb4c21db01131072–26214332209715113107262914560
004d2239ddf45262144–524287141943032621444194304
004e446b30a65570915262144–524287241943032621448388608
004f88124b4157f08ea21cf6afcb9601262144–5242874419430326214416777216
0050176238f6eb620ef524f7e17e8ea65bd9c8f6b6a56e63a80d101262144–5242878419430326214433554432
00513524569312b7efb029c178186713c7d009fe7c32b6e7f6172a4fde2511f281aa0af3550e1e95269f2973a34048b7101262144–52428716419430326214467108864
0052704897995986f3fd23e6fd8f6fe5423a86e4c92270f3ed814945552cd0e971c17f95c3f9d96139dfa950d79eceb413fb677527e96361af6c8a3b1cbc30b8a0ec39dca02fda43db6b97808a4f4d7d0754de2b07f8083d7a479d96001262144–524287324194303262144134217728

Each of the six m = 22 polynomials (IDs 004d–0052) wins 262,144 (length, t) pairs — a quarter of a million lengths each. The six m = 21 polynomials win 131,072 each; m = 20 wins 65,536 each (counting both the first run and the fill-in); m = 19 wins 32,768 each. The largest band dominates, as before: the m = 22 band alone saves 264,241,152 parity bits, more than half the extension's total.

One caveat about the hex strings in this table, stronger than the one in the prior-art section. The generator polynomial for a given (parent, t) is not unique — it depends on which primitive polynomial defines GF(2m). The prior-art section already says the hex differs from the textbooks for that reason. What the extension runs showed is that the hex is not even reproducible between two runs of the same program: re-running the original crawl's m = 18 band produced the same six codes (same parents, same degrees, same parity, same distances) but different hex bytes, because the primitive element the program picks depends on the run. The parameters in this table — parent, degree, parity, distance, saving — are exact and reproducible. The hex is one valid generator for that code, the one this particular run produced. If you re-run the search and get different bytes for the same (parent, t), you have the same code, not a different one. The original 58 keep their original hex; the 24 new ones keep the hex of the run that found them.

Why the sweep stopped: m = 22 is the frontier

The stop rule was: run one m at a time, and stop when a single m's scan takes 4 hours (14,400 s). The measured times were 816 s (m = 19 + 20 together), 959 s (m = 20 fill-in), 3,057 s (m = 21), and 10,966 s (m = 22, 3.04 h). The band cost grows by almost exactly 4× per m — the work per band is about 6·22m−4 steps — so m = 23 (L = 524,288–1,048,575, 524,288 lengths, 2.64×1013 steps) would take about 12 hours at the m = 22 rate. That exceeds the 4-hour rule, so m = 23 was not run. Memory was never the limit: the coset table for m = 22 is 33.5 MB and the server had 2.7 GB free. The frontier is m = 22, exhaustively verified; m = 23 and beyond are reached only by the direct construction below, which is not an exhaustive proof.

Direct construction to m = 256 (not exhaustively verified)

Past the frontier, the exhaustive sliding-window search is infeasible (its cost is O(2m)), but the narrow-sense generators themselves are directly computable in O(t·m): take the parent N = 2m − 1, find a primitive polynomial for GF(2m), and multiply the minimal polynomials of the cyclotomic cosets of the odd residues 1..2t−1. A small C tool (gen_bch.c, in the source section below) does exactly that — orbit-only, never building a table over all N residues — and computed the generators for m = 23 to m = 256, all six t values, 1,404 rows, in about 30 minutes total. These are labelled direct construction: they are the narrow-sense generators, verified primitive and cross-checked against the exhaustive m = 18 and m = 21 polynomials (hex-exact, 12/12) and against an independent Python implementation (primitivity 234/234, hex spot-check 42/42) — but they are not exhaustively verified for optimality the way m ≤ 22 are. The exhaustive search proves no better code exists at those lengths; the direct construction only proves these codes exist and beat Reed-Solomon. Do not cite the m ≥ 23 rows as exhaustive results.

The saving keeps climbing toward the 50% asymptote — saving = 1 − m / (2(m−3)), independent of t — because Reed-Solomon pays 2(m−3) bits per error at these lengths while BCH pays m:

mpayload band (bytes)r per error (t = 32)RS bits per error (t = 32)bits saved (t = 32)saving
23524,288–1,048,5757361,28054442.5%
241,048,576–2,097,1517681,34457642.9%
2816,777,216–33,554,4318961,60070444.0%
32268,435,456–536,870,9111,0241,85683244.8%
4068,719,476,736–137,438,953,4711,2802,3681,08845.9%
4817,592,186,044,416–35,184,372,088,8311,5362,8801,34446.7%
641.15×1018–2.30×10182,0483,9041,85647.5%
964.97×1027–9.94×10273,0725,9522,88048.4%
1282.12×1037–4.25×10374,0968,0003,90448.8%
1609.07×1046–1.81×10475,12010,0484,92849.0%
1923.87×1056–7.75×10566,14412,0965,95249.2%
2241.65×1066–3.31×10667,16814,1446,97649.3%
2567.20×1075–1.44×10768,19216,1928,00049.4%

At m = 256, t = 32: a code correcting 32 bit errors needs 8,192 parity bits where Reed-Solomon needs 16,192 — a saving of 8,000 bits, 49.4%. The payloads at m = 256 are absurd (1075 bytes — no storage system will ever hold one), but the formula is the point: the saving approaches 50% and never crosses it, because BCH pays one coset per error and Reed-Solomon pays two symbols per error, and the coset size grows only logarithmically with the payload.

One of the 234 direct-construction rows needed a factorisation that did not exist when the sweep started: 2251 − 1. It was factored during the run (sympy, 331 s) into 503 × 54,217 × 178,230,287,214,063,289,511 × 61,676,882,198,695,257,501,367 × 12,070,396,178,249,893,039,969,681, product and primality verified — and m = 251 was then swept with the complete factor list, so no row in the table rests on a probable-primitive. The full 1,404-row table (bch_direct_m23_256.csv: m, N, t, r, RS parity, bits saved, saving %, hex, primitive polynomial, time) and the tool that produced it are in the source section below.

So the final accounting is: 82 polynomials exhaustively verified to m = 22 (payloads to 524,287 bytes, 3,145,030 finds, 495,386,012 parity bits saved), plus 1,404 direct-construction rows to m = 256 (labelled, not exhaustively verified, saving 42.5%–49.4%). The 36 polynomials for m = 17–22 (IDs 002f–0052) are not in any published table — the published tables stop at m = 16. The exhaustive frontier is m = 22 because a single m's scan takes 4 hours there, and m = 23 would take about 12.

THE 12 NEW POLYNOMIALS IN A BITSTREAM — WHAT YOU ACTUALLY GAIN AND HOW TO USE THEM

The 12 polynomials for m = 17 and 18 (IDs 002f–003a) are the ones that matter most in practice, for two reasons: they cover the largest payloads — 8 to 16 kilobytes, the block sizes you actually use to move bulk data — and they are the ones no published table contains. Here is what they buy you and how to put them on a wire.

What you gain

Payloadt (errors)BCH parityRS parityBits savedSaving
8192–16383 B117281139.3%
8192–16383 B234562239.3%
8192–16383 B4681124439.3%
8192–16383 B81362248839.3%
8192–16383 B1627244817639.3%
8192–16383 B3254489635239.3%
16384 B118301240.0%
16384 B236602440.0%
16384 B4721204840.0%
16384 B81442409640.0%
16384 B1628848019240.0%
16384 B3257696038440.0%

Take the biggest case: a 16,384-byte block, t = 32 (poly 003a, degree 576). Reed-Solomon needs 960 parity bits (120 bytes) to survive 32 scattered bit errors, because it must budget for 32 whole bytes being wrong. The shortened BCH code needs 576 parity bits (72 bytes) — the same 32 bit errors, corrected directly. You save 384 bits (48 bytes) per block, 40% less parity, and the overhead drops from 0.73% to 0.44%. At t = 1 the saving is 12 bits per block; at every t it is 40% at this length, and 39.3% across the whole 8192–16383-byte band (17 vs 28 parity bits per error). Summed over every (length, t) pair these two bands serve, the 12 polynomials save 5,677,812 parity bits — over half of the 10,256,528 bits the full 58-polynomial table saves. The ratio keeps improving with length and approaches 50% asymptotically, because Reed-Solomon always pays two symbols per error while BCH pays roughly log₂(block length in bits) per error.

Why the gap exists: a bit error damages at most one byte, but a byte-oriented code has to budget for the worst case — t scattered bit errors landing in t different bytes. So Reed-Solomon pays 2 × t × (bits per symbol) while BCH pays t × (bits to index a position in the block). For a 16 KB block that is 30 vs 18 bits per error.

How to use them on a bitstream

A bitstream is a continuous flow of bits, so you chop it into blocks and protect each block independently.

1. Frame the stream into blocks. Pick a payload length L in bytes (8192–16384 for these 12 polynomials) and a t (how many bit errors per block you want to survive). The codeword is n = 8L + r bits long, where r is the degree of the polynomial (the parity bits). Both ends must use the same L and t — the shortening (N − n positions dropped from the parent code) is fixed by L, and finds.h records len_bytes and parent_len for exactly this.

2. Encode systematically. Treat the L-byte payload as a polynomial m(x) of degree < 8L. The parity is the remainder of m(x)·xr divided by g(x), and the transmitted block is the payload followed by those r parity bits. In hardware or software this is a linear-feedback shift register with feedback taps given by g(x) — the hex in the table is LSB-first (bit i is the coefficient of xi), so the taps are read straight off it. The overhead is tiny: 72 bytes of parity on a 16 KB block at t = 32 (0.44%), 17 bits on an 8 KB block at t = 1 (0.03%).

3. Decode by syndrome. On receipt, compute the syndrome s(x) = received(x) mod g(x). Zero means no error detected. Nonzero means: run Berlekamp-Massey on the syndrome to get the error-locator polynomial, run a Chien search (evaluate the locator at αi for each bit position i) to find where the errors are, and flip those bits. Binary BCH needs no magnitude step — every error is a bit flip, so locating it is correcting it. It corrects any pattern of up to t bit errors anywhere in the block, including in the parity bits themselves.

4. Agree on the code. The transmitter and receiver need the same (L, t). Fix it per link, or send the 2-byte polynomial ID from finds.h in a header — the ID is unique per generator, so the receiver looks up the polynomial, its degree, its parent, and the payload length from the table. That is what the IDs are for.

5. Pick t from your channel's bit error rate. This is the step people get wrong. If the channel flips each bit independently with probability p (a binary symmetric channel), a block of n bits suffers on average n·p errors, and the count is Poisson. You want t comfortably above the average — the failure probability is the Poisson tail P(X > t).

Worked examples (block = 16,384 bytes = 131,072 bits):

  • BER 10−5 (a clean link): expect 1.3 errors per block. t = 8 is already plenty (failure ~10−5 per block); t = 4 fails 1.1% of blocks.
  • BER 10−4 (a noisy link): expect 13.1 errors per block. t = 32 fails only 2.8 × 10−6 of blocks (about 1 in 350,000). t = 16 is not enough — it fails 17% of blocks.
  • BER 10−3 (a bad link): expect 131 errors per block. t = 32 fails essentially every block. A 16 KB block is too big here — drop to a 128-byte block (1,024 bits, expect ~1 error) where t = 4 fails only 0.4% of blocks, or use a code with a larger t.

When not to use them. These codes correct scattered, independent bit flips. If your channel corrupts whole bytes at a time (burst errors — a fade that wipes out a run of bits, a scratched sector), Reed-Solomon or an interleaved BCH is the right tool, because a burst that hits many bits in one byte still only costs RS one symbol. BCH wins exactly when errors are scattered; RS wins when they cluster. Measure your channel before choosing.

HOW TO USE finds.h

The crawl writes finds.h into the run directory (now 155 MB, regenerated every 500 finds and at the end). It contains rssearch_poly_bytes[] (all 82 generators concatenated), rssearch_polys[] (id, degree, byte length, offset), and rssearch_finds[] (all 3,145,030 entries: length, t, parity bits, proven distance, poly id, family, parent, RS parity). Include it, pick the entry for your payload length and error count, and the generator polynomial is right there. The IDs are stable within a run and sequential from 1. (The original crawl's finds.h was 4.8 MB with 58 generators and 97,612 entries; the extension grew it to 82 generators and 3,145,030 entries.)

One caveat, stated plainly: the distance d is a proven lower bound (BCH bound plus stepped bound), not the exact minimum distance. The true distance can be higher — the Golay code is the famous example of a code whose BCH bound (5) is far below its true distance (7), and a bound-based search cannot see it for t=3. Nothing in this table overclaims: every entry's d is guaranteed, and the parity saving is exact.

WHAT IT COST

197,476,256,636 sliding-window steps in 274.4 seconds on 4 cores — about 720 million steps per second. The log's ETA said 222 seconds at the 20-second mark; the real finish was 274 seconds, the difference being the polynomial recovery (minimal-polynomial computation in large fields) that the step count does not include. The whole run, including the toy suite that validated the machinery first, took one evening. The "month" estimate from the design review assumed the exhaustive degree-32 coset enumeration; the sliding-window formulation made that enumeration unnecessary, and the search that actually ran is the one that finished in under five minutes.

LIMITATIONS, STATED HONESTLY

  • Bit errors only. For byte errors Reed-Solomon is optimal (Singleton bound) and this search finds nothing. Do not use these polynomials where whole bytes fail together.
  • Bound-based distances. d is a proven lower bound; exact distances may be higher. Codes whose BCH bound is loose (Golay) are invisible to this search at the t where they would matter.
  • Shortened BCH only, at scale. The exact repeated-root tier ran only for n ≤ 64, t ≤ 2 and found nothing. A full repeated-root search at large n would need the Castagnoli bound machinery, which was not implemented.
  • Parents capped at m=22 (exhaustive), m=256 (direct). Exhaustive parents (N up to 222−1) were searched; a longer parent could in principle give a smaller parity at some length, but the smallest fitting parent already wins everywhere, so larger parents only matter if you want to trade parity against something else. Past m=22 the generators are direct construction only (see the EXTENSION section), not exhaustively verified for optimality.
  • Decoding is your problem. These are generator polynomials and proven distances. A fast decoder (Berlekamp-Massey on the parent, then shortening) is standard BCH machinery and was not part of this build.

FULL SOURCE CODE

The complete program, exactly as it ran. One C file, one Makefile, one README. Build it with make, validate it with ./rssearch --toy (16 checks, all passing), run the crawl with ./rssearch --crawl.

rssearch.c

The whole program — GF(2) polynomials, GF(2^D) fields and minimal polynomials, cosets, BCH bounds, the sliding-window search, tier R and tier 3, threading, logging, checkpoint/resume, finds.h generation, and the toy suite. ~2,000 lines. This is the version with the dynamic coset cache and 64-bit indices used for the m = 21 and m = 22 bands; the original m &le; 20 version differs only in the fixed coset cache and 32-bit shifts.

/* rssearch.c — polynomial Reed-Solomon discovery.
 *
 * Crawls every byte length L = 8..16384 (n = 8L bits) and searches for binary
 * cyclic / shortened-BCH codes that beat Reed-Solomon for BIT errors.
 *
 * Error model: correct t random bit errors anywhere in the payload.
 * RS baseline for length L and t: RS over GF(2^m), m = smallest with
 * 2^m-1 >= L (m >= 8), must correct up to t byte errors (worst case one bit
 * per byte), so it needs 2t symbols = 2*t*m parity BITS. A binary code with
 * parity r bits and distance d >= 2t+1 is a FIND if r < 2*t*m (fewer parity
 * bits than RS), or r == 2*t*m and d > 2t+1 (same parity, more distance).
 *
 * Why binary can win: BCH needs ~t*ord_o(2) parity bits, RS needs 2*t*m.
 * At lengths where ord_o(2) is small relative to m, binary wins big; where
 * ord_o(2) is huge (e.g. L=857, ord=428), RS wins. The crawl maps exactly
 * where each side wins. For BYTE errors RS is optimal (Singleton bound) and
 * the search is expected to find nothing — that is a result too.
 *
 * Search tiers (per length n, odd part o, parity cap r <= n/8):
 *   Tier 1 (EXHAUSTIVE): all squarefree unions of cyclotomic cosets mod o
 *     with total degree <= 32. Every binary polynomial of degree <= 32 that
 *     divides x^n+1 is one such union, so this is exhaustive over ALL
 *     generator polynomials of degree <= 32. Non-squarefree (repeated-root)
 *     generators are never optimal for the minimum-parity objective: a
 *     repeated-root code is a subcode of its radical's code with the same
 *     BCH bound but higher parity, so squarefree dominates. Total over all
 *     lengths: 95,400,030 candidates (measured).
 *   Tier 2 (BCH-DESIGNED, r <= n/8): for each t and each starting offset b,
 *     the defining set = closure under *2 of {b..b+2t-1}; plus the same for
 *     shortened BCH from the two smallest parents N = 2^m-1 >= n. Sliding
 *     window keeps this O(N) per (parent, t). Distance >= 2t+1 by
 *     construction (BCH bound).
 *   Tier 3 (POLISH): greedy coset removal/swap on the best set per (L,t),
 *     only for small defining sets (|T| <= 256). Deterministic, bounded.
 * Evaluation is by LOWER BOUNDS on distance (BCH bound, plus a stepped /
 * multiplier bound for survivors). A find is only claimed when the proven
 * lower bound beats RS, never on an unproven true distance. Conservative
 * by design: true distances may be higher, never lower.
 *
 * Output:
 *   finds.txt — one line per (L,t) find (append-only, source of truth)
 *   polys.txt — distinct generator polynomials, each with a 2-byte id
 *   finds.h   — generated C header: poly table + finds table, ids uint16_t
 *   search.log — tail-able log with STATUS lines incl. ETA
 *   status.json — machine-readable progress (for the bihourly checker)
 *   state/done.bin — bitset of completed lengths (checkpoint / resume)
 *
 * Threads: pthreads, one length per work unit pulled from an atomic counter
 * (dynamic: per-length cost varies by 5 orders of magnitude). All cores.
 *
 * Honesty notes (see also the article): full exhaustion over ALL polynomials
 * of degree <= n/8 is impossible (2^(n/8) of them). The exhaustive tier is
 * degree <= 32 (--r1max raises it; the count grows combinatorially). Above
 * 32, only BCH-designed sets are covered exhaustively; the gap (non-BCH,
 * 32 < r <= n/8) is probed only by the tier-3 polish. This scope is stated
 * in the log at startup so the exhaustiveness claim is auditable.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <stdbool.h>
#include <stdarg.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <stdatomic.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

/* ---------------- config ---------------- */
typedef struct {
    int lmin, lmax;          /* byte lengths */
    int r1max;               /* tier-1 exhaustive degree cap */
    int tvals[8]; int nt;    /* t values */
    int nthreads;
    int mmax;                /* max parent m: shortened-BCH parents m0..mmax */
    int nparents;            /* shortened-BCH parents to try (smallest m first) */
    int tier3_max_elems;     /* polish only if |T| <= this */
    char dir[512];
    bool resume;
    bool verbose;
} cfg_t;
static cfg_t CFG;

static double T0;            /* monotonic start */
static volatile sig_atomic_t STOP = 0;
static void on_signal(int s) { (void)s; STOP = 1; }

/* ---------------- utils ---------------- */
static double now_mono(void) {
    struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec + ts.tv_nsec * 1e-9;
}
static void now_iso(char *buf, size_t n) {
    time_t t = time(NULL); struct tm tm;
    localtime_r(&t, &tm);
    strftime(buf, n, "%Y-%m-%d %H:%M:%S", &tm);
}
static void *xmalloc(size_t n) {
    void *p = malloc(n ? n : 1);
    if (!p) { fprintf(stderr, "OOM (%zu)\n", n); exit(2); }
    return p;
}
static void *xcalloc(size_t n, size_t s) {
    void *p = calloc(n ? n : 1, s ? s : 1);
    if (!p) { fprintf(stderr, "OOM\n"); exit(2); }
    return p;
}
static void *xrealloc(void *p, size_t n) {
    void *q = realloc(p, n ? n : 1);
    if (!q) { fprintf(stderr, "OOM\n"); exit(2); }
    return q;
}
static uint64_t rng_state = 0x9e3779b97f4a7c15ULL;
static uint64_t rng_next(void) {
    uint64_t x = rng_state;
    x ^= x << 13; x ^= x >> 7; x ^= x << 17;
    rng_state = x;
    return x;
}
static int gcd_int(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }

/* hex helpers (lowercase, no 0x) */
static void bytes_to_hex(char *out, const uint8_t *b, size_t n) {
    static const char h[] = "0123456789abcdef";
    for (size_t i = 0; i < n; i++) { out[2*i] = h[b[i] >> 4]; out[2*i+1] = h[b[i] & 15]; }
    out[2*n] = 0;
}
static int hex_to_bytes(uint8_t *out, const char *hex, size_t maxn) {
    size_t L = strlen(hex); if (L % 2) return -1; size_t n = L / 2;
    if (n > maxn) return -1;
    for (size_t i = 0; i < n; i++) {
        unsigned v; if (sscanf(hex + 2*i, "%2x", &v) != 1) return -1;
        out[i] = (uint8_t)v;
    }
    return (int)n;
}

/* ---------------- logging ---------------- */
static FILE *LOGFP = NULL;
static pthread_mutex_t LOG_MU = PTHREAD_MUTEX_INITIALIZER;
static void log_line(const char *fmt, ...) {
    char ts[32]; now_iso(ts, sizeof ts);
    char msg[4096];
    va_list ap; va_start(ap, fmt);
    vsnprintf(msg, sizeof msg, fmt, ap);
    va_end(ap);
    pthread_mutex_lock(&LOG_MU);
    fprintf(stdout, "[%s] %s\n", ts, msg); fflush(stdout);
    if (LOGFP) { fprintf(LOGFP, "[%s] %s\n", ts, msg); fflush(LOGFP); }
    pthread_mutex_unlock(&LOG_MU);
}

/* ---------------- RS baseline ---------------- */
static int rs_m_for_L(int L) {
    int m = 8;
    while (((1LL << m) - 1) < L) m++;
    return m; /* m <= 15 for L <= 16384 */
}
static int rs_parity_bits(int L, int t) { return 2 * t * rs_m_for_L(L); }

/* ---------------- GF(2) polynomials ----------------
 * Bit i (LSB-first) = coefficient of x^i. Polynomials are uint64_t arrays.
 * All functions take explicit word counts; caller owns buffers. */
/* carryless multiply: d (na+nb words) = a * b.
 * Portable shift-and-xor. The hot search loop never calls this (it uses
 * coset arithmetic); poly mul only runs on the rare recovery/verify paths,
 * where this is fast enough. */
static int HAVE_PCLMUL = 0;
static void detect_pclmul(void) { HAVE_PCLMUL = 0; }
static int p_deg(const uint64_t *a, int nw) {
    for (int i = nw - 1; i >= 0; i--) {
        if (a[i]) return i * 64 + 63 - __builtin_clzll(a[i]);
    }
    return -1;
}
static int p_nw_for_deg(int deg) { return deg / 64 + 1; }

/* carryless multiply: d (na+nb words) = a * b */
static void p_mul(uint64_t *d, const uint64_t *a, int na, const uint64_t *b, int nb) {
    memset(d, 0, (size_t)(na + nb) * 8);
    for (int i = 0; i < na; i++) {
        uint64_t aw = a[i];
        if (!aw) continue;
        for (int j = 0; j < 64; j++) {
            if ((aw >> j) & 1ULL) {
                int sh = 64 * i + j, w = sh / 64, bit = sh % 64;
                for (int k = 0; k < nb; k++) {
                    uint64_t bw = b[k];
                    d[w + k] ^= bw << bit;
                    if (bit) d[w + k + 1] ^= bw >> (64 - bit);
                }
            }
        }
    }
}
/* r = a mod m (m != 0). r has nm words. a has na words. */
static void p_mod(uint64_t *r, const uint64_t *a, int na, const uint64_t *m, int nm) {
    int dm = p_deg(m, nm);
    if (dm < 0) { memset(r, 0, (size_t)nm * 8); return; }
    /* work on a copy */
    int nw = na > nm ? na : nm;
    uint64_t *w = (uint64_t *)xmalloc((size_t)nw * 8);
    memset(w, 0, (size_t)nw * 8);
    memcpy(w, a, (size_t)na * 8);
    int da;
    while ((da = p_deg(w, nw)) >= dm) {
        int sh = da - dm, ww = sh / 64, bit = sh % 64;
        for (int k = 0; k < nm; k++) {
            uint64_t mw = m[k];
            w[ww + k] ^= mw << bit;
            if (bit && ww + k + 1 < nw) w[ww + k + 1] ^= mw >> (64 - bit);
        }
    }
    memcpy(r, w, (size_t)nm * 8);
    free(w);
}
/* q = a / m, r = a mod m. q has na words, r has nm words. */
static void p_divmod(uint64_t *q, uint64_t *r, const uint64_t *a, int na,
                     const uint64_t *m, int nm) {
    int dm = p_deg(m, nm);
    memset(q, 0, (size_t)na * 8);
    if (dm < 0) { memset(r, 0, (size_t)nm * 8); return; }
    int nw = na > nm ? na : nm;
    uint64_t *w = (uint64_t *)xmalloc((size_t)nw * 8);
    memset(w, 0, (size_t)nw * 8);
    memcpy(w, a, (size_t)na * 8);
    int da;
    while ((da = p_deg(w, nw)) >= dm) {
        int sh = da - dm, ww = sh / 64, bit = sh % 64;
        q[ww] |= 1ULL << bit;
        for (int k = 0; k < nm; k++) {
            uint64_t mw = m[k];
            w[ww + k] ^= mw << bit;
            if (bit && ww + k + 1 < nw) w[ww + k + 1] ^= mw >> (64 - bit);
        }
    }
    memcpy(r, w, (size_t)nm * 8);
    free(w);
}
/* r = base^exp mod mod. exp is a bit array (nbits, LSB-first). */
static void p_powmod(uint64_t *r, const uint64_t *base, int nb,
                     const uint64_t *exp, int enbits,
                     const uint64_t *mod, int nm) {
    int nw = nm > nb ? nm : nb;
    uint64_t *acc = (uint64_t *)xcalloc((size_t)(2 * nw + 2), 8);
    uint64_t *b = (uint64_t *)xcalloc((size_t)(2 * nw + 2), 8);
    uint64_t *tmp = (uint64_t *)xcalloc((size_t)(2 * nw + 2), 8);
    uint64_t *red = (uint64_t *)xcalloc((size_t)nm, 8);
    acc[0] = 1;
    memcpy(b, base, (size_t)nb * 8);
    /* reduce base mod mod first */
    p_mod(red, b, nb, mod, nm);
    memcpy(b, red, (size_t)nm * 8);
    for (int i = 0; i < enbits; i++) {
        if ((exp[i / 64] >> (i % 64)) & 1ULL) {
            p_mul(tmp, acc, nm, b, nm);
            p_mod(red, tmp, 2 * nm, mod, nm);
            memcpy(acc, red, (size_t)nm * 8);
        }
        p_mul(tmp, b, nm, b, nm);
        p_mod(red, tmp, 2 * nm, mod, nm);
        memcpy(b, red, (size_t)nm * 8);
    }
    memcpy(r, acc, (size_t)nm * 8);
    free(acc); free(b); free(tmp); free(red);
}
static void p_powmod_u64(uint64_t *r, const uint64_t *base, int nb,
                         uint64_t exp, const uint64_t *mod, int nm) {
    uint64_t e[1] = { exp };
    int nbits = exp ? 64 - __builtin_clzll(exp) : 0;
    p_powmod(r, base, nb, e, nbits, mod, nm);
}
/* gcd of a and b; returns degree of gcd, gcd written to g (nm words). */
static int p_gcd(uint64_t *g, const uint64_t *a, int na, const uint64_t *b, int nb) {
    int nw = na > nb ? na : nb;
    uint64_t *x = (uint64_t *)xcalloc((size_t)nw, 8);
    uint64_t *y = (uint64_t *)xcalloc((size_t)nw, 8);
    uint64_t *t = (uint64_t *)xcalloc((size_t)nw, 8);
    memcpy(x, a, (size_t)na * 8);
    memcpy(y, b, (size_t)nb * 8);
    while (p_deg(y, nw) >= 0) {
        p_mod(t, x, nw, y, nw);
        memcpy(x, y, (size_t)nw * 8);
        memcpy(y, t, (size_t)nw * 8);
    }
    int d = p_deg(x, nw);
    memcpy(g, x, (size_t)nw * 8);
    free(x); free(y); free(t);
    return d;
}
/* Rabin irreducibility test for monic p of degree deg (>= 1). */
static bool p_is_irreducible(const uint64_t *p, int deg) {
    int nm = p_nw_for_deg(deg);
    /* x^(2^deg) mod p must equal x */
    uint64_t *x = (uint64_t *)xcalloc((size_t)nm, 8);
    uint64_t *acc = (uint64_t *)xcalloc((size_t)nm, 8);
    uint64_t *tmp = (uint64_t *)xcalloc((size_t)(2 * nm), 8);
    uint64_t *red = (uint64_t *)xcalloc((size_t)nm, 8);
    uint64_t *g = (uint64_t *)xcalloc((size_t)nm, 8);
    uint64_t *xm = (uint64_t *)xcalloc((size_t)nm, 8);
    x[0] = 2; /* the polynomial x */
    p_mod(xm, x, nm, p, nm); /* x mod p (== x for deg >= 2, == 1 for deg == 1) */
    memcpy(acc, x, (size_t)nm * 8);
    for (int i = 0; i < deg; i++) {
        p_mul(tmp, acc, nm, acc, nm);
        p_mod(red, tmp, 2 * nm, p, nm);
        memcpy(acc, red, (size_t)nm * 8);
    }
    bool ok = (memcmp(acc, xm, (size_t)nm * 8) == 0);
    if (ok) {
        /* for each prime q | deg: gcd(p, x^(2^(deg/q)) - x) == 1 */
        int d = deg;
        /* factor deg by trial division (deg <= 16384) */
        int primes[16]; int np = 0;
        int t = d;
        for (int q = 2; q * q <= t && np < 16; q++) {
            if (t % q == 0) { primes[np++] = q; while (t % q == 0) t /= q; }
        }
        if (t > 1 && np < 16) primes[np++] = t;
        for (int i = 0; i < np && ok; i++) {
            int q = primes[i], e = deg / q;
            memcpy(acc, x, (size_t)nm * 8);
            for (int j = 0; j < e; j++) {
                p_mul(tmp, acc, nm, acc, nm);
                p_mod(red, tmp, 2 * nm, p, nm);
                memcpy(acc, red, (size_t)nm * 8);
            }
            /* acc - (x mod p) */
            for (int w = 0; w < nm; w++) acc[w] ^= xm[w];
            int gd = p_gcd(g, p, nm, acc, nm);
            if (gd != 0) ok = false; /* gcd degree > 0 means reducible */
        }
    }
    free(x); free(acc); free(tmp); free(red); free(g); free(xm);
    return ok;
}
static void p_rand_monic(uint64_t *p, int deg) {
    int nw = p_nw_for_deg(deg);
    for (int i = 0; i < nw; i++) p[i] = rng_next();
    p[deg / 64] |= 1ULL << (deg % 64);
    p[0] |= 1ULL; /* constant term 1 (else divisible by x) */
    /* clear bits above deg */
    int excess = nw * 64 - (deg + 1);
    if (excess > 0) p[nw - 1] &= (~0ULL >> excess);
    p[deg / 64] |= 1ULL << (deg % 64);
}
static int p_nbytes_for_deg(int deg) { return (deg + 8) / 8; }
static void p_to_bytes(uint8_t *out, const uint64_t *a, int nbytes) {
    for (int i = 0; i < nbytes; i++)
        out[i] = (uint8_t)(a[i / 8] >> ((i % 8) * 8));
}
static void p_from_bytes(uint64_t *a, int nw, const uint8_t *b, int nbytes) {
    memset(a, 0, (size_t)nw * 8);
    for (int i = 0; i < nbytes; i++)
        a[i / 8] |= (uint64_t)b[i] << ((i % 8) * 8);
}

/* ---------------- small-integer helpers ---------------- */
static int phi_int(int n) {
    int r = n, t = n;
    for (int p = 2; p * p <= t; p++) {
        if (t % p == 0) { while (t % p == 0) t /= p; r = r / p * (p - 1); }
    }
    if (t > 1) r = r / t * (t - 1);
    return r;
}
/* distinct prime factors of n (n >= 2) into out[], returns count */
static int prime_factors(int n, int *out, int maxout) {
    int np = 0, t = n;
    for (int p = 2; p * p <= t && np < maxout; p++) {
        if (t % p == 0) { out[np++] = p; while (t % p == 0) t /= p; }
    }
    if (t > 1 && np < maxout) out[np++] = t;
    return np;
}
/* multiplicative order of 2 modulo o (o odd, >= 1). o=1 -> 1. */
static int order_mod_2(int o) {
    if (o <= 1) return 1;
    int d = phi_int(o);
    int pr[16]; int np = prime_factors(d, pr, 16);
    for (int i = 0; i < np; i++) {
        int q = pr[i];
        while (d % q == 0) {
            long long pw = 1, base = 2; int e = d / q;
            long long b = 2; int ee = e;
            long long res = 1;
            while (ee) { if (ee & 1) res = res * b % o; b = b * b % o; ee >>= 1; }
            (void)pw; (void)base;
            if (res == 1) d /= q; else break;
        }
    }
    return d;
}

/* ---------------- GF(2^D) ---------------- */
#define GF_D_MAX 1024
typedef struct { int d; int nw; uint64_t *mod; } gf_t;
static gf_t *gf_cache[GF_D_MAX + 1];
static pthread_mutex_t GF_MU = PTHREAD_MUTEX_INITIALIZER;

static void gf_mul(const gf_t *F, uint64_t *dst, const uint64_t *a, const uint64_t *b) {
    int nw = F->nw;
    uint64_t *tmp = (uint64_t *)xcalloc((size_t)(2 * nw + 2), 8);
    uint64_t *red = (uint64_t *)xcalloc((size_t)nw, 8);
    p_mul(tmp, a, nw, b, nw);
    p_mod(red, tmp, 2 * nw, F->mod, nw);
    memcpy(dst, red, (size_t)nw * 8);
    free(tmp); free(red);
}
static void gf_sqr(const gf_t *F, uint64_t *dst, const uint64_t *a) { gf_mul(F, dst, a, a); }
static void gf_pow(const gf_t *F, uint64_t *dst, const uint64_t *a,
                   const uint64_t *exp, int enbits) {
    int nw = F->nw;
    uint64_t *acc = (uint64_t *)xcalloc((size_t)nw, 8);
    uint64_t *b = (uint64_t *)xcalloc((size_t)nw, 8);
    acc[0] = 1;
    memcpy(b, a, (size_t)nw * 8);
    for (int i = 0; i < enbits; i++) {
        if ((exp[i / 64] >> (i % 64)) & 1ULL) {
            uint64_t *t = (uint64_t *)xcalloc((size_t)nw, 8);
            gf_mul(F, t, acc, b);
            memcpy(acc, t, (size_t)nw * 8);
            free(t);
        }
        uint64_t *t = (uint64_t *)xcalloc((size_t)nw, 8);
        gf_mul(F, t, b, b);
        memcpy(b, t, (size_t)nw * 8);
        free(t);
    }
    memcpy(dst, acc, (size_t)nw * 8);
    free(acc); free(b);
}
static void gf_pow_u64(const gf_t *F, uint64_t *dst, const uint64_t *a, uint64_t exp) {
    uint64_t e[1] = { exp };
    int nbits = exp ? 64 - __builtin_clzll(exp) : 0;
    gf_pow(F, dst, a, e, nbits);
}
static bool gf_is_zero(const gf_t *F, const uint64_t *a) {
    for (int i = 0; i < F->nw; i++) if (a[i]) return false;
    return true;
}
static bool gf_is_one(const gf_t *F, const uint64_t *a) {
    if (a[0] != 1) return false;
    for (int i = 1; i < F->nw; i++) if (a[i]) return false;
    return true;
}
static gf_t *gf_get(int d) {
    if (d < 1 || d > GF_D_MAX) return NULL;
    pthread_mutex_lock(&GF_MU);
    if (gf_cache[d]) { pthread_mutex_unlock(&GF_MU); return gf_cache[d]; }
    gf_t *F = (gf_t *)xcalloc(1, sizeof(gf_t));
    F->d = d; F->nw = p_nw_for_deg(d);
    F->mod = (uint64_t *)xcalloc((size_t)F->nw, 8);
    bool found = false;
    for (int trial = 0; trial < 50 * d + 100 && !found; trial++) {
        p_rand_monic(F->mod, d);
        if (p_is_irreducible(F->mod, d)) found = true;
    }
    if (!found) { free(F->mod); free(F); pthread_mutex_unlock(&GF_MU); return NULL; }
    gf_cache[d] = F;
    pthread_mutex_unlock(&GF_MU);
    return F;
}
/* Find an element of exact order o in GF(2^D)*. Requires o | 2^D - 1. */
static bool gf_prim_root(const gf_t *F, int o, uint64_t *alpha) {
    int D = F->d;
    int enw = (D + 63) / 64;
    uint64_t *exp = (uint64_t *)xcalloc((size_t)enw, 8);
    long rem = 0;
    for (int i = D - 1; i >= 0; i--) {
        rem = rem * 2 + 1;
        if (rem / o) exp[i / 64] |= 1ULL << (i % 64);
        rem = rem % o;
    }
    if (rem != 0) { free(exp); return false; }
    int pr[16]; int np = prime_factors(o, pr, 16);
    uint64_t *g = (uint64_t *)xcalloc((size_t)F->nw, 8);
    uint64_t *h = (uint64_t *)xcalloc((size_t)F->nw, 8);
    uint64_t *t = (uint64_t *)xcalloc((size_t)F->nw, 8);
    bool ok = false;
    /* Deterministic first: try small field elements 2,3,4,... so every caller
     * gets the SAME primitive root for a given (F,o). minpoly_coset and the
     * field verifier must agree on alpha. */
    uint64_t vmax = (D < 13) ? ((1ULL << D) - 1) : 4096;
    for (uint64_t v = 2; v <= vmax && !ok; v++) {
        memset(g, 0, (size_t)F->nw * 8);
        g[0] = v;
        gf_pow(F, h, g, exp, D);
        if (gf_is_zero(F, h) || gf_is_one(F, h)) continue;
        gf_pow_u64(F, t, h, (uint64_t)o);
        if (!gf_is_one(F, t)) continue;
        ok = true;
        for (int i = 0; i < np && ok; i++) {
            gf_pow_u64(F, t, h, (uint64_t)(o / pr[i]));
            if (gf_is_one(F, t)) ok = false;
        }
        if (ok) memcpy(alpha, h, (size_t)F->nw * 8);
    }
    for (int trial = 0; trial < 200 && !ok; trial++) {
        for (int i = 0; i < F->nw; i++) g[i] = rng_next();
        int excess = F->nw * 64 - D;
        if (excess > 0) g[F->nw - 1] &= (~0ULL >> excess);
        if (gf_is_zero(F, g)) continue;
        gf_pow(F, h, g, exp, D);
        if (gf_is_zero(F, h) || gf_is_one(F, h)) continue;
        gf_pow_u64(F, t, h, (uint64_t)o);
        if (!gf_is_one(F, t)) continue;
        ok = true;
        for (int i = 0; i < np && ok; i++) {
            gf_pow_u64(F, t, h, (uint64_t)(o / pr[i]));
            if (gf_is_one(F, t)) ok = false;
        }
        if (ok) memcpy(alpha, h, (size_t)F->nw * 8);
    }
    free(exp); free(g); free(h); free(t);
    return ok;
}
/* minimal polynomial of the cyclotomic coset of s (mod o).
 * Writes the GF(2) polynomial as bytes (LSB-first), sets *out_deg.
 * Returns false if D is too large or the field/root cannot be built. */
typedef struct { int o, s; int deg; uint8_t *bytes; int nbytes; bool used; } minpoly_ent;
#define MINPOLY_CACHE_N 8192
static minpoly_ent minpoly_cache[MINPOLY_CACHE_N];
static pthread_mutex_t MINPOLY_MU = PTHREAD_MUTEX_INITIALIZER;
static unsigned minpoly_hash(int o, int s) {
    return (unsigned)(o * 2654435761u + s * 40503u) % MINPOLY_CACHE_N;
}
static bool minpoly_coset(int o, int s, uint8_t *out, int *out_deg, int *out_nbytes) {
    /* canonical representative: smallest element of the coset */
    int rep = s, x = s;
    do { x = (x * 2) % o; if (x < rep) rep = x; } while (x != s);
    s = rep;
    pthread_mutex_lock(&MINPOLY_MU);
    unsigned h = minpoly_hash(o, s);
    for (unsigned i = 0; i < MINPOLY_CACHE_N; i++) {
        unsigned j = (h + i) % MINPOLY_CACHE_N;
        if (minpoly_cache[j].used && minpoly_cache[j].o == o && minpoly_cache[j].s == s) {
            memcpy(out, minpoly_cache[j].bytes, (size_t)minpoly_cache[j].nbytes);
            *out_deg = minpoly_cache[j].deg;
            *out_nbytes = minpoly_cache[j].nbytes;
            pthread_mutex_unlock(&MINPOLY_MU);
            return true;
        }
        if (!minpoly_cache[j].used) break;
    }
    pthread_mutex_unlock(&MINPOLY_MU);
    int D = order_mod_2(o);
    if (D < 1 || D > GF_D_MAX) return false;
    gf_t *F = gf_get(D);
    if (!F) return false;
    uint64_t *alpha = (uint64_t *)xcalloc((size_t)F->nw, 8);
    if (!gf_prim_root(F, o, alpha)) { free(alpha); return false; }
    uint64_t *gamma = (uint64_t *)xcalloc((size_t)F->nw, 8);
    gf_pow_u64(F, gamma, alpha, (uint64_t)s);
    /* coset size d */
    int d = 0; x = s;
    do { x = (x * 2) % o; d++; } while (x != s);
    /* product P(x) = prod_j (x + gamma^(2^j)) over GF(2^D) */
    int nw = F->nw;
    /* P coeffs: (d+1) field elements, flat */
    uint64_t *P = (uint64_t *)xcalloc((size_t)(d + 1) * nw, 8);
    uint64_t *Pn = (uint64_t *)xcalloc((size_t)(d + 1) * nw, 8);
    uint64_t *gj = (uint64_t *)xcalloc((size_t)nw, 8);
    uint64_t *tmp = (uint64_t *)xcalloc((size_t)nw, 8);
    P[0] = 1; /* P = 1 */
    memcpy(gj, gamma, (size_t)nw * 8);
    int curdeg = 0;
    for (int j = 0; j < d; j++) {
        memset(Pn, 0, (size_t)(d + 1) * nw * 8);
        for (int k = 0; k <= curdeg + 1; k++) {
            /* Pn[k] = (k>0 ? P[k-1] : 0) + gj * (k<=curdeg ? P[k] : 0) */
            uint64_t *acc = Pn + (size_t)k * nw;
            if (k > 0) {
                uint64_t *pk1 = P + (size_t)(k - 1) * nw;
                for (int w = 0; w < nw; w++) acc[w] ^= pk1[w];
            }
            if (k <= curdeg) {
                uint64_t *pk = P + (size_t)k * nw;
                if (!gf_is_zero(F, pk)) {
                    gf_mul(F, tmp, gj, pk);
                    for (int w = 0; w < nw; w++) acc[w] ^= tmp[w];
                }
            }
        }
        memcpy(P, Pn, (size_t)(d + 1) * nw * 8);
        curdeg++;
        gf_sqr(F, gj, gj);
    }
    /* coefficients must be 0 or 1 in GF(2) */
    int nbytes = p_nbytes_for_deg(d);
    memset(out, 0, (size_t)nbytes);
    bool good = true;
    for (int k = 0; k <= d; k++) {
        uint64_t *c = P + (size_t)k * nw;
        if (gf_is_zero(F, c)) continue;
        if (gf_is_one(F, c)) { out[k / 8] |= 1u << (k % 8); continue; }
        good = false; break;
    }
    free(alpha); free(gamma); free(P); free(Pn); free(gj); free(tmp);
    if (!good) return false;
    *out_deg = d; *out_nbytes = nbytes;
    pthread_mutex_lock(&MINPOLY_MU);
    h = minpoly_hash(o, s);
    for (unsigned i = 0; i < MINPOLY_CACHE_N; i++) {
        unsigned j = (h + i) % MINPOLY_CACHE_N;
        if (!minpoly_cache[j].used) {
            minpoly_cache[j].used = true;
            minpoly_cache[j].o = o; minpoly_cache[j].s = s;
            minpoly_cache[j].deg = d; minpoly_cache[j].nbytes = nbytes;
            minpoly_cache[j].bytes = (uint8_t *)xmalloc((size_t)nbytes);
            memcpy(minpoly_cache[j].bytes, out, (size_t)nbytes);
            break;
        }
        if (minpoly_cache[j].o == o && minpoly_cache[j].s == s) break;
    }
    pthread_mutex_unlock(&MINPOLY_MU);
    return true;
}

/* ---------------- cyclotomic cosets (mod odd o) ----------------
 * Cosets of *2 on Z_o. Each coset = one irreducible factor of x^o+1 over
 * GF(2); its size is the degree of that factor. Cached by o. */
typedef struct {
    int o;
    int ncos;
    int *cdeg;      /* [ncos] sizes */
    int *coff;      /* [ncos+1] offsets into elems */
    int *elems;     /* flat, grouped by coset, ascending within coset */
    int *elem_cos;  /* [o] residue -> coset index */
} cosets_t;
/* Dynamic coset cache (no fixed cap). The old fixed array COSETS_MAXO=1048576
 * returned NULL for o>=2^20, i.e. parents m>=21. Only a handful of distinct
 * o values are ever used (one per parent + small tier-R moduli), so a
 * linear-search list is ample. o is kept as int inside cosets_t (arrays are
 * int-indexed); cosets_get takes long and rejects o > INT_MAX. */
typedef struct { long o; cosets_t *C; } cosets_cache_ent;
static cosets_cache_ent *cosets_cache = NULL;
static size_t cosets_cache_n = 0, cosets_cache_cap = 0;
static pthread_mutex_t COSETS_MU = PTHREAD_MUTEX_INITIALIZER;
static cosets_t *cosets_get(long o) {
    if (o < 1 || o > INT_MAX || (o % 2) == 0) return NULL;
    int oi = (int)o;
    pthread_mutex_lock(&COSETS_MU);
    for (size_t i = 0; i < cosets_cache_n; i++)
        if (cosets_cache[i].o == o) { cosets_t *C = cosets_cache[i].C; pthread_mutex_unlock(&COSETS_MU); return C; }
    cosets_t *C = (cosets_t *)xcalloc(1, sizeof(cosets_t));
    C->o = oi;
    C->elem_cos = (int *)xmalloc((size_t)oi * sizeof(int));
    for (int i = 0; i < oi; i++) C->elem_cos[i] = -1;
    int cap = 64;
    C->cdeg = (int *)xmalloc((size_t)cap * sizeof(int));
    C->coff = (int *)xmalloc((size_t)(cap + 1) * sizeof(int));
    C->elems = (int *)xmalloc((size_t)oi * sizeof(int));
    int nelem = 0, ncos = 0;
    for (int i = 0; i < oi; i++) {
        if (C->elem_cos[i] >= 0) continue;
        if (ncos >= cap) {
            cap *= 2;
            C->cdeg = (int *)xrealloc(C->cdeg, (size_t)cap * sizeof(int));
            C->coff = (int *)xrealloc(C->coff, (size_t)(cap + 1) * sizeof(int));
        }
        /* orbit of i under *2 mod o, collected then sorted */
        int start = nelem, x = i, cnt = 0;
        do {
            C->elem_cos[x] = ncos;
            C->elems[nelem++] = x; cnt++;
            x = (x * 2) % oi;
        } while (x != i);
        /* insertion sort the small coset */
        for (int a = start + 1; a < nelem; a++) {
            int v = C->elems[a], b = a - 1;
            while (b >= start && C->elems[b] > v) { C->elems[b + 1] = C->elems[b]; b--; }
            C->elems[b + 1] = v;
        }
        C->cdeg[ncos] = cnt;
        C->coff[ncos] = start;
        ncos++;
    }
    C->coff[ncos] = nelem;
    C->ncos = ncos;
    if (cosets_cache_n >= cosets_cache_cap) {
        cosets_cache_cap = cosets_cache_cap ? cosets_cache_cap * 2 : 16;
        cosets_cache = (cosets_cache_ent *)xrealloc(cosets_cache, cosets_cache_cap * sizeof(cosets_cache_ent));
    }
    cosets_cache[cosets_cache_n].o = o;
    cosets_cache[cosets_cache_n].C = C;
    cosets_cache_n++;
    pthread_mutex_unlock(&COSETS_MU);
    return C;
}

/* ---------------- BCH bound ----------------
 * VALIDITY: bch_bound_from_elems is only valid when the code length equals
 * the modulus o (odd length, roots are o-th roots of unity, defining set
 * subset of Z_o). It must NEVER be applied to a defining set mod o for a
 * code of length n > o (there the bound is false; squarefree generators
 * give d=2 via the x^o+1 weight-2 codeword). In this program it is used
 * only for PARENT BCH codes (length N, modulus N) and for the toy exact
 * checks at length == modulus. Shortened codes inherit the parent bound. */
static int bch_bound_from_elems(const int *elems, int m, int o) {
    if (m <= 0) return 1;
    if (m >= o) return o + 1; /* whole circle; caller must exclude k=0 codes */
    int best = 1, run = 1;
    for (int i = 1; i < m; i++) {
        if (elems[i] == elems[i - 1] + 1) run++;
        else { if (run > best) best = run; run = 1; }
    }
    if (run > best) best = run;
    /* wraparound: leading run + trailing run (only if not the whole circle) */
    if (elems[0] == 0 && elems[m - 1] == o - 1) {
        int lead = 1;
        for (int i = 1; i < m && elems[i] == elems[i - 1] + 1; i++) lead = i + 1;
        int trail = 1;
        for (int i = m - 2; i >= 0 && elems[i] == elems[i + 1] - 1; i--) trail = m - 1 - i;
        if (lead + trail > best && lead + trail < m) best = lead + trail;
        else if (lead + trail >= m) best = m; /* whole set consecutive cyclically */
    }
    return best + 1;
}
static int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}
/* Stepped (multiplier) bound: max over units s of the BCH bound of s*T.
 * Same validity condition as bch_bound_from_elems. Tries at most max_units
 * units (deterministic order). Returns the best bound found. */
static int bch_bound_stepped(const int *elems, int m, int o, int max_units) {
    int best = bch_bound_from_elems(elems, m, o);
    if (m <= 0 || m >= o) return best;
    int *tmp = (int *)xmalloc((size_t)m * sizeof(int));
    int tried = 0;
    for (int s = 2; s < o && tried < max_units; s++) {
        if (gcd_int(s, o) != 1) continue;
        tried++;
        for (int i = 0; i < m; i++) tmp[i] = (int)((long long)elems[i] * s % o);
        qsort(tmp, (size_t)m, sizeof(int), cmp_int);
        int b = bch_bound_from_elems(tmp, m, o);
        if (b > best) best = b;
    }
    free(tmp);
    return best;
}

/* ---------------- structural divisor count (for the log) ----------------
 * Number of squarefree divisors of x^n+1 of degree 1..rmax, from the coset
 * sizes of o (formula-based, no full cosets needed). This is a STRUCTURAL
 * fact about x^n+1, not a count of useful codes (see the BCH-validity note:
 * squarefree exact-length codes at even n have d=2). */
static long tier1_struct_count(int o, int rmax) {
    /* coset sizes via divisors of o */
    int divs[512]; int nd = 0;
    for (int d = 1; d * d <= o && nd < 512; d++) {
        if (o % d == 0) {
            divs[nd++] = d;
            if (d * d != o && nd < 512) divs[nd++] = o / d;
        }
    }
    /* count cosets by size: for each divisor d of o, phi(d)/ord_d(2) cosets */
    int sizes[512]; int nsizes = 0;
    for (int i = 0; i < nd; i++) {
        int d = divs[i];
        int od = order_mod_2(d);
        int cnt = phi_int(d) / od;
        for (int k = 0; k < cnt && nsizes < 512; k++) sizes[nsizes++] = od;
    }
    long dp[64]; for (int i = 0; i <= rmax && i < 64; i++) dp[i] = 0;
    dp[0] = 1;
    for (int i = 0; i < nsizes; i++) {
        int deg = sizes[i];
        for (int used = rmax - deg; used >= 0; used--) {
            if (dp[used]) dp[used + deg] += dp[used];
        }
    }
    long tot = 0;
    for (int i = 1; i <= rmax; i++) tot += dp[i];
    return tot;
}

/* ---------------- candidates ---------------- */
typedef struct {
    int r, d;          /* parity bits, distance lower bound (or exact for fam=0) */
    int fam;           /* 1 = shortened BCH (parent), 0 = exact repeated-root */
    int parent;        /* parent length N for fam=1, else 0 */
    int mod;           /* modulus of defining set: parent N (fam=1), odd part o (fam=0) */
    int *cos; int ncos;
    int *exp;          /* exponents parallel to cos (all 1 for fam=1) */
    uint8_t *poly; int poly_nbytes; /* explicit generator (fam=0), else NULL */
    bool valid;
} cand_t;
static void cand_init(cand_t *c) { memset(c, 0, sizeof *c); c->r = 1 << 30; c->d = 0; }
static void cand_free(cand_t *c) {
    free(c->cos); free(c->exp); free(c->poly);
    memset(c, 0, sizeof *c); c->r = 1 << 30;
}
static void cand_copy(cand_t *dst, const cand_t *src) {
    cand_free(dst);
    *dst = *src;
    dst->cos = NULL; dst->exp = NULL; dst->poly = NULL;
    if (src->ncos > 0) {
        dst->cos = (int *)xmalloc((size_t)src->ncos * sizeof(int));
        memcpy(dst->cos, src->cos, (size_t)src->ncos * sizeof(int));
        dst->exp = (int *)xmalloc((size_t)src->ncos * sizeof(int));
        memcpy(dst->exp, src->exp, (size_t)src->ncos * sizeof(int));
    }
    if (src->poly_nbytes > 0) {
        dst->poly = (uint8_t *)xmalloc((size_t)src->poly_nbytes);
        memcpy(dst->poly, src->poly, (size_t)src->poly_nbytes);
    }
}

/* Build g(x) = prod_i minpoly(mod, cos_i)^exp_i. Returns false on failure.
 * out must hold >= 4096 bytes; sets *out_deg and *out_nbytes. */
static bool poly_from_cosets(int mod, const int *cos, const int *exp, int ncos,
                             uint8_t *out, int *out_deg, int *out_nbytes) {
    /* accumulator as GF(2) poly words */
    int maxdeg = 0;
    for (int i = 0; i < ncos; i++) {
        cosets_t *C = cosets_get(mod);
        if (!C) return false;
        maxdeg += C->cdeg[cos[i]] * exp[i];
    }
    int nw = p_nw_for_deg(maxdeg) + 2;
    uint64_t *acc = (uint64_t *)xcalloc((size_t)nw, 8);
    uint64_t *fac = (uint64_t *)xcalloc((size_t)nw, 8);
    uint64_t *pw = (uint64_t *)xcalloc((size_t)nw, 8);
    uint64_t *tmp = (uint64_t *)xcalloc((size_t)(2 * nw + 2), 8);
    acc[0] = 1;
    int accdeg = 0;
    uint8_t *mp = (uint8_t *)xmalloc(8192);
    for (int i = 0; i < ncos; i++) {
        cosets_t *C = cosets_get(mod);
        int rep = C->elems[C->coff[cos[i]]]; /* smallest element = representative */
        int mdeg = 0, mnb = 0;
        if (!minpoly_coset(mod, rep, mp, &mdeg, &mnb)) {
            free(acc); free(fac); free(pw); free(tmp); free(mp);
            return false;
        }
        /* fac = minpoly^exp */
        memset(fac, 0, (size_t)nw * 8);
        fac[0] = 1;
        int facdeg = 0;
        for (int e = 0; e < exp[i]; e++) {
            memset(pw, 0, (size_t)nw * 8);
            p_from_bytes(pw, nw, mp, mnb);
            p_mul(tmp, fac, p_nw_for_deg(facdeg) + 1, pw, p_nw_for_deg(mdeg) + 1);
            int tnw = p_nw_for_deg(facdeg + mdeg) + 1;
            memcpy(fac, tmp, (size_t)tnw * 8);
            facdeg += mdeg;
        }
        /* acc *= fac */
        p_mul(tmp, acc, p_nw_for_deg(accdeg) + 1, fac, p_nw_for_deg(facdeg) + 1);
        int tnw = p_nw_for_deg(accdeg + facdeg) + 1;
        memcpy(acc, tmp, (size_t)tnw * 8);
        accdeg += facdeg;
    }
    free(fac); free(pw); free(tmp); free(mp);
    int deg = p_deg(acc, nw);
    int nbytes = p_nbytes_for_deg(deg);
    p_to_bytes(out, acc, nbytes);
    free(acc);
    *out_deg = deg; *out_nbytes = nbytes;
    return true;
}

/* BCH bound of a defining set given as coset indices (mod = length, valid
 * only when the parent length equals mod). Builds the element list. */
static int bch_bound_of_cosets(const cosets_t *C, const int *cos, int ncos) {
    int m = 0;
    for (int i = 0; i < ncos; i++) m += C->cdeg[cos[i]];
    if (m == 0) return 1;
    int *elems = (int *)xmalloc((size_t)m * sizeof(int));
    int k = 0;
    for (int i = 0; i < ncos; i++) {
        int c = cos[i];
        for (int j = C->coff[c]; j < C->coff[c + 1]; j++) elems[k++] = C->elems[j];
    }
    qsort(elems, (size_t)m, sizeof(int), cmp_int);
    int b = bch_bound_from_elems(elems, m, C->o);
    free(elems);
    return b;
}
/* Collect the defining-set element list for a coset set (caller frees). */
static int *coset_elems_list(const cosets_t *C, const int *cos, int ncos, int *out_m) {
    int m = 0;
    for (int i = 0; i < ncos; i++) m += C->cdeg[cos[i]];
    int *elems = (int *)xmalloc((size_t)(m ? m : 1) * sizeof(int));
    int k = 0;
    for (int i = 0; i < ncos; i++) {
        int c = cos[i];
        for (int j = C->coff[c]; j < C->coff[c + 1]; j++) elems[k++] = C->elems[j];
    }
    qsort(elems, (size_t)m, sizeof(int), cmp_int);
    *out_m = m;
    return elems;
}

/* ---------------- tier S: shortened BCH ----------------
 * For parent N and target t, find the min-parity defining set (closure of a
 * window of 2t consecutive residues) by a sliding window over b in 0..N-1.
 * Returns min r and the best b. O(N) per (parent, t). */
typedef struct {
    int *cnt; int cap;   /* per-coset window counts */
} worker_scratch;
static int tierS_best_b(const cosets_t *C, int t, worker_scratch *ws, int *out_best_b) {
    int N = C->o, W = 2 * t;
    if (W >= N) return 1 << 30;
    if (ws->cap < C->ncos) {
        ws->cnt = (int *)xrealloc(ws->cnt, (size_t)C->ncos * sizeof(int));
        ws->cap = C->ncos;
    }
    int *cnt = ws->cnt;
    memset(cnt, 0, (size_t)C->ncos * sizeof(int));
    int r_cur = 0;
    for (int j = 0; j < W; j++) {
        int c = C->elem_cos[j];
        if (cnt[c] == 0) r_cur += C->cdeg[c];
        cnt[c]++;
    }
    int best_r = r_cur, best_b = 0;
    int add_pos = W; /* residue to add next; advances by 1 (mod N) per step */
    for (int b = 1; b < N; b++) {
        int drop = C->elem_cos[b - 1];
        if (--cnt[drop] == 0) r_cur -= C->cdeg[drop];
        int c = C->elem_cos[add_pos];
        if (cnt[c] == 0) r_cur += C->cdeg[c];
        cnt[c]++;
        if (++add_pos == N) add_pos = 0;
        if (r_cur < best_r) { best_r = r_cur; best_b = b; }
    }
    *out_best_b = best_b;
    return best_r;
}
/* coset list of the window at b (closure). Returns count; cos[] filled. */
static int tierS_window_cosets(const cosets_t *C, int t, int b, int *cos_out, int maxcos) {
    int N = C->o, W = 2 * t;
    int n = 0;
    /* small local set via a timestamp array would be faster; N small enough
     * that a sort+unique is fine (called once per (parent,t) best). */
    int *tmp = (int *)xmalloc((size_t)W * sizeof(int));
    for (int j = 0; j < W; j++) tmp[j] = C->elem_cos[(b + j) % N];
    qsort(tmp, (size_t)W, sizeof(int), cmp_int);
    for (int j = 0; j < W; j++) {
        if (j == 0 || tmp[j] != tmp[j - 1]) {
            if (n < maxcos) cos_out[n++] = tmp[j];
        }
    }
    free(tmp);
    return n;
}

/* ---------------- exact distance (small n, via remainder) ---------------- */
static uint64_t rem_u64(uint64_t a, uint64_t g, int gdeg) {
    while (a) {
        int da = 63 - __builtin_clzll(a);
        if (da < gdeg) return a;
        a ^= g << (da - gdeg);
    }
    return 0;
}
/* Smallest w in 1..maxw such that a weight-w pattern is a codeword of the
 * cyclic code generated by g (deg gdeg), length n; else maxw+1. n <= 64. */
static int exact_dist_u64(uint64_t g, int gdeg, int n, int maxw) {
    uint64_t topmask = (n >= 64) ? ~0ULL : ((1ULL << n) - 1ULL);
    for (int w = 1; w <= maxw; w++) {
        if (w > n) break;
        uint64_t comb = (w >= 64) ? ~0ULL : ((1ULL << w) - 1ULL);
        while (comb != 0 && (comb & ~topmask) == 0) {
            if (rem_u64(comb, g, gdeg) == 0) return w;
            uint64_t c = comb & (~comb + 1ULL);
            uint64_t r = comb + c;
            if (r == 0) break;
            comb = (((r ^ comb) >> 2) / c) | r;
        }
    }
    return maxw + 1;
}

/* ---------------- tier R: exact repeated-root (n <= 64, t <= 2) ----------
 * Enumerate ALL generators g | x^n+1 (exponent vectors over the cosets of
 * the odd part o, each exponent 0..2^s, total degree <= n/8) and evaluate by
 * EXACT minimum distance. This is the only exact-length tier, and it is
 * deliberately confined to tiny n where exact evaluation is feasible.
 * Expected result: nothing (squarefree generators give d=2; repeated-root
 * generators at these sizes also fail to beat shortened BCH). */
static void tierR(worker_scratch *ws, int L, int n, int o, cand_t *best) {
    (void)ws; (void)L;
    int s = 0, t2 = n;
    while ((t2 % 2) == 0) { t2 /= 2; s++; }
    int mult = 1 << s;
    cosets_t *C = cosets_get(o);
    if (!C) return;
    int rcap = n / 8;
    int nc = C->ncos;
    /* DFS over exponent vectors */
    int *exp = (int *)xcalloc((size_t)nc, sizeof(int));
    int *cos = (int *)xmalloc((size_t)(nc ? nc : 1) * sizeof(int));
    int *exps = (int *)xmalloc((size_t)(nc ? nc : 1) * sizeof(int));
    uint8_t *gbytes = (uint8_t *)xmalloc(4096);
    /* iterative DFS using an explicit stack of (idx, degree) */
    /* simple recursion via a helper using a manual stack */
    typedef struct { int idx; int deg; int next_e; } frame_t;
    frame_t *st = (frame_t *)xmalloc((size_t)(nc + 1) * sizeof(frame_t));
    int sp = 0;
    st[sp++] = (frame_t){ 0, 0, 0 };
    while (sp > 0) {
        frame_t *f = &st[sp - 1];
        if (f->idx == nc) {
            /* leaf: evaluate the generator (if degree >= 1) */
            if (f->deg >= 1) {
                int ncos = 0;
                for (int i = 0; i < nc; i++)
                    if (exp[i] > 0) { cos[ncos] = i; exps[ncos] = exp[i]; ncos++; }
                int gdeg = 0, gnb = 0;
                if (poly_from_cosets(o, cos, exps, ncos, gbytes, &gdeg, &gnb) && gdeg == f->deg) {
                    /* build uint64 g for exact_dist (n <= 64, gdeg <= 8) */
                    uint64_t g = 0;
                    for (int i = 0; i < gnb; i++) g |= (uint64_t)gbytes[i] << (8 * i);
                    for (int ti = 0; ti < CFG.nt; ti++) {
                        int t = CFG.tvals[ti];
                        if (t > 2) continue;
                        if (2 * t + 1 > n) continue;
                        int d = exact_dist_u64(g, gdeg, n, 2 * t);
                        if (d >= 2 * t + 1 && (gdeg < best[ti].r ||
                            (gdeg == best[ti].r && d > best[ti].d))) {
                            cand_t c; cand_init(&c);
                            c.r = gdeg; c.d = d; c.fam = 0; c.parent = 0; c.mod = o;
                            c.ncos = ncos;
                            c.cos = (int *)xmalloc((size_t)ncos * sizeof(int));
                            memcpy(c.cos, cos, (size_t)ncos * sizeof(int));
                            c.exp = (int *)xmalloc((size_t)ncos * sizeof(int));
                            for (int i = 0, k = 0; i < nc; i++)
                                if (exp[i] > 0) c.exp[k++] = exp[i];
                            c.poly = (uint8_t *)xmalloc((size_t)gnb);
                            memcpy(c.poly, gbytes, (size_t)gnb);
                            c.poly_nbytes = gnb;
                            c.valid = true;
                            cand_copy(&best[ti], &c);
                            cand_free(&c);
                        }
                    }
                }
            }
            sp--;
            continue;
        }
        if (f->next_e <= mult) {
            int e = f->next_e++;
            int nd = f->deg + e * C->cdeg[f->idx];
            if (nd <= rcap) {
                exp[f->idx] = e;
                st[sp++] = (frame_t){ f->idx + 1, nd, 0 };
            }
        } else {
            exp[f->idx] = 0;
            sp--;
        }
    }
    free(exp); free(cos); free(exps); free(gbytes); free(st);
}

/* ---------------- tier 3: polish (gated) ----------------
 * Greedy single-coset removal on a shortened-BCH best set (parent modulus).
 * Only runs when the best is NOT already a find (r > RS baseline) and the
 * set is small. Returns true if r improved. */
static bool tier3_polish(cand_t *best, int t) {
    if (!best->valid || best->fam != 1 || best->ncos > 32) return false;
    cosets_t *C = cosets_get(best->parent);
    if (!C) return false;
    bool improved = false;
    for (int iter = 0; iter < 4; iter++) {
        bool any = false;
        for (int i = 0; i < best->ncos; i++) {
            /* try removing cos[i] */
            int *sub = (int *)xmalloc((size_t)(best->ncos ? best->ncos : 1) * sizeof(int));
            int ns = 0;
            for (int j = 0; j < best->ncos; j++) if (j != i) sub[ns++] = best->cos[j];
            int b = bch_bound_of_cosets(C, sub, ns);
            if (b >= 2 * t + 1) {
                int nr = 0;
                for (int j = 0; j < ns; j++) nr += C->cdeg[sub[j]];
                if (nr < best->r) {
                    free(best->cos); free(best->exp);
                    best->cos = sub; best->ncos = ns;
                    best->exp = (int *)xmalloc((size_t)(ns ? ns : 1) * sizeof(int));
                    for (int j = 0; j < ns; j++) best->exp[j] = 1;
                    best->r = nr; best->d = b;
                    any = true; improved = true;
                    break; /* restart the scan after a removal */
                }
            }
            free(sub);
        }
        if (!any) break;
    }
    return improved;
}

/* ---------------- finds ---------------- */
static pthread_mutex_t FIND_MU = PTHREAD_MUTEX_INITIALIZER;
static FILE *FINDS_FP = NULL, *POLYS_FP = NULL;
typedef struct { uint64_t hash; uint16_t id; int deg; int nbytes; uint8_t *bytes; bool used; } poly_ent;
static poly_ent *poly_tab = NULL;
static size_t poly_tab_cap = 0, poly_tab_n = 0;
static uint16_t next_poly_id = 1;
typedef struct { int L, t, n, r, d, fam, parent, poly_id, rsp; } find_rec;
static find_rec *finds_arr = NULL;
static size_t finds_cap = 0, finds_n = 0;
static atomic_long finds_count = 0;

static uint64_t poly_hash_bytes(const uint8_t *b, int n) {
    uint64_t h = 1469598103934665603ULL;
    for (int i = 0; i < n; i++) { h ^= b[i]; h *= 1099511628211ULL; }
    h ^= (uint64_t)n * 0x9e3779b97f4a7c15ULL;
    return h;
}
static void poly_tab_grow(void) {
    size_t ncap = poly_tab_cap ? poly_tab_cap * 2 : 1024;
    poly_ent *nt = (poly_ent *)xcalloc(ncap, sizeof(poly_ent));
    for (size_t i = 0; i < poly_tab_cap; i++) {
        if (!poly_tab[i].used) continue;
        size_t j = poly_tab[i].hash % ncap;
        while (nt[j].used) j = (j + 1) % ncap;
        nt[j] = poly_tab[i];
    }
    free(poly_tab);
    poly_tab = nt; poly_tab_cap = ncap;
}
/* Intern a generator poly; returns its 2-byte id (assigns a new one if new).
 * Must be called with FIND_MU held. Appends to polys.txt when new. */
static uint16_t poly_intern(const uint8_t *bytes, int nbytes, int deg) {
    uint64_t h = poly_hash_bytes(bytes, nbytes);
    if (poly_tab_n * 10 >= poly_tab_cap * 7) poly_tab_grow();
    size_t j = h % poly_tab_cap;
    while (poly_tab[j].used) {
        if (poly_tab[j].hash == h && poly_tab[j].nbytes == nbytes &&
            memcmp(poly_tab[j].bytes, bytes, (size_t)nbytes) == 0)
            return poly_tab[j].id;
        j = (j + 1) % poly_tab_cap;
    }
    uint16_t id = next_poly_id++;
    poly_tab[j].used = true;
    poly_tab[j].hash = h; poly_tab[j].id = id;
    poly_tab[j].deg = deg; poly_tab[j].nbytes = nbytes;
    poly_tab[j].bytes = (uint8_t *)xmalloc((size_t)nbytes);
    memcpy(poly_tab[j].bytes, bytes, (size_t)nbytes);
    poly_tab_n++;
    if (POLYS_FP) {
        char *hex = (char *)xmalloc((size_t)2 * nbytes + 1);
        bytes_to_hex(hex, bytes, (size_t)nbytes);
        fprintf(POLYS_FP, "POLY id=%04x deg=%d nbytes=%d hex=%s\n", id, deg, nbytes, hex);
        fflush(POLYS_FP);
        free(hex);
    }
    return id;
}
static void gen_finds_h(void) {
    /* called with FIND_MU held */
    char path[600];
    snprintf(path, sizeof path, "%s/finds.h", CFG.dir);
    char tmp[620];
    snprintf(tmp, sizeof tmp, "%s/finds.h.tmp", CFG.dir);
    FILE *f = fopen(tmp, "w");
    if (!f) return;
    char ts[32]; now_iso(ts, sizeof ts);
    fprintf(f, "/* rssearch finds — generated %s by rssearch.\n", ts);
    fprintf(f, " * %zu finds, %zu distinct polynomials. Each polynomial has a\n", finds_n, poly_tab_n);
    fprintf(f, " * 2-byte id (uint16_t). fam: 1 = shortened BCH (parent_len is the\n");
    fprintf(f, " * parent BCH length N), 0 = exact repeated-root cyclic code.\n");
    fprintf(f, " * r_bits = parity bits, d = proven distance lower bound (exact for\n");
    fprintf(f, " * fam=0), rs_parity_bits = what Reed-Solomon needs for the same\n");
    fprintf(f, " * (length, t) on bit errors. A find has r_bits < rs_parity_bits,\n");
    fprintf(f, " * or equal parity with d > 2t+1. */\n");
    fprintf(f, "#ifndef RSSEARCH_FINDS_H\n#define RSSEARCH_FINDS_H\n");
    fprintf(f, "#include <stdint.h>\n");
    fprintf(f, "#define RSSEARCH_FIND_COUNT %zu\n", finds_n);
    fprintf(f, "#define RSSEARCH_POLY_COUNT %zu\n", poly_tab_n);
    fprintf(f, "typedef struct { uint16_t id; uint16_t deg_bits; uint16_t nbytes; uint32_t off; } rssearch_poly_t;\n");
    /* poly bytes blob */
    fprintf(f, "static const uint8_t rssearch_poly_bytes[] = {");
    uint32_t off = 0;
    /* need polys in id order for the table; collect and sort by id */
    poly_ent **arr = (poly_ent **)xmalloc((poly_tab_n ? poly_tab_n : 1) * sizeof(poly_ent *));
    size_t an = 0;
    for (size_t i = 0; i < poly_tab_cap; i++)
        if (poly_tab[i].used) arr[an++] = &poly_tab[i];
    /* insertion sort by id (small n) */
    for (size_t i = 1; i < an; i++) {
        poly_ent *v = arr[i]; size_t j = i;
        while (j > 0 && arr[j - 1]->id > v->id) { arr[j] = arr[j - 1]; j--; }
        arr[j] = v;
    }
    for (size_t i = 0; i < an; i++) {
        for (int k = 0; k < arr[i]->nbytes; k++) {
            if ((off + k) % 16 == 0) fprintf(f, "\n    ");
            fprintf(f, "0x%02x,", arr[i]->bytes[k]);
        }
        off += (uint32_t)arr[i]->nbytes;
    }
    fprintf(f, "\n};\n");
    fprintf(f, "static const rssearch_poly_t rssearch_polys[] = {\n");
    off = 0;
    for (size_t i = 0; i < an; i++) {
        fprintf(f, "    { 0x%04x, %d, %d, %u },\n", arr[i]->id, arr[i]->deg,
                arr[i]->nbytes, off);
        off += (uint32_t)arr[i]->nbytes;
    }
    fprintf(f, "};\n");
    free(arr);
    fprintf(f, "typedef struct { uint16_t len_bytes; uint8_t t; uint16_t r_bits; uint16_t d; uint16_t poly_id; uint8_t fam; uint16_t parent_len; uint16_t rs_parity_bits; } rssearch_find_t;\n");
    fprintf(f, "static const rssearch_find_t rssearch_finds[] = {\n");
    for (size_t i = 0; i < finds_n; i++) {
        find_rec *fr = &finds_arr[i];
        fprintf(f, "    { %d, %d, %d, %d, 0x%04x, %d, %d, %d },\n",
                fr->L, fr->t, fr->r, fr->d, fr->poly_id, fr->fam, fr->parent, fr->rsp);
    }
    fprintf(f, "};\n#endif /* RSSEARCH_FINDS_H */\n");
    fclose(f);
    rename(tmp, path);
}
static void finalize_find(int L, int t, const cand_t *best) {
    uint8_t *gbytes = (uint8_t *)xmalloc(8192);
    int gdeg = 0, gnb = 0;
    bool ok = false;
    if (best->fam == 0 && best->poly) {
        gdeg = best->r; gnb = best->poly_nbytes;
        memcpy(gbytes, best->poly, (size_t)gnb);
        ok = true;
    } else {
        ok = poly_from_cosets(best->mod, best->cos, best->exp, best->ncos,
                              gbytes, &gdeg, &gnb);
    }
    pthread_mutex_lock(&FIND_MU);
    uint16_t pid = 0;
    if (ok && gdeg == best->r) {
        pid = poly_intern(gbytes, gnb, gdeg);
    }
    int n = 8 * L;
    int rsp = rs_parity_bits(L, t);
    if (finds_n >= finds_cap) {
        finds_cap = finds_cap ? finds_cap * 2 : 1024;
        finds_arr = (find_rec *)xrealloc(finds_arr, finds_cap * sizeof(find_rec));
    }
    finds_arr[finds_n++] = (find_rec){ L, t, n, best->r, best->d, best->fam,
        best->parent, pid, rsp };
    if (FINDS_FP) {
        char *hex = (char *)xmalloc((size_t)2 * gnb + 1);
        if (ok) bytes_to_hex(hex, gbytes, (size_t)gnb);
        else strcpy(hex, "DEFERRED");
        fprintf(FINDS_FP,
            "FIND L=%d t=%d n=%d r=%d d=%d fam=%s parent=%d poly=%04x rsp=%d save=%d hex=%s\n",
            L, t, n, best->r, best->d, best->fam ? "short" : "exact",
            best->parent, pid, rsp, rsp - best->r, hex);
        fflush(FINDS_FP);
        free(hex);
    }
    long fc = atomic_fetch_add(&finds_count, 1) + 1;
    if (fc % 500 == 0) gen_finds_h();
    pthread_mutex_unlock(&FIND_MU);
    if (ok && gdeg == best->r) {
        log_line("FIND L=%d t=%d r=%d d=%d fam=%s parent=%d poly=%04x rs=%d save=%d",
                 L, t, best->r, best->d, best->fam ? "short" : "exact",
                 best->parent, pid, rsp, rsp - best->r);
    } else {
        log_line("FIND L=%d t=%d r=%d d=%d fam=%s parent=%d poly=DEFERRED rs=%d save=%d",
                 L, t, best->r, best->d, best->fam ? "short" : "exact",
                 best->parent, rsp, rsp - best->r);
    }
    free(gbytes);
}

/* ---------------- progress / checkpoint / status ---------------- */
static atomic_long lengths_done = 0;
static atomic_long work_done = 0;
static long work_total = 0;
static long lengths_total = 0;
static uint8_t *done_bits = NULL;
static pthread_mutex_t STATE_MU = PTHREAD_MUTEX_INITIALIZER;
static bool is_done_len(int L) {
    int li = L - CFG.lmin;
    return (done_bits[li / 8] >> (li % 8)) & 1u;
}
static void mark_done_mem(int L) {
    int li = L - CFG.lmin;
    pthread_mutex_lock(&STATE_MU);
    done_bits[li / 8] |= 1u << (li % 8);
    pthread_mutex_unlock(&STATE_MU);
}
static void persist_state(void) {
    char tmp[640], path[640];
    snprintf(path, sizeof path, "%s/state/done.bin", CFG.dir);
    snprintf(tmp, sizeof tmp, "%s/state/done.bin.tmp", CFG.dir);
    pthread_mutex_lock(&STATE_MU);
    FILE *f = fopen(tmp, "wb");
    if (f) {
        fwrite(done_bits, 1, (size_t)(lengths_total + 7) / 8, f);
        fclose(f);
        rename(tmp, path);
    }
    pthread_mutex_unlock(&STATE_MU);
}
static long compute_work_total(void) {
    long tot = 0;
    for (int L = CFG.lmin; L <= CFG.lmax; L++) {
        int n = 8 * L;
        int m0 = 0; while (((1LL << m0) - 1) < n) m0++;
        for (int m = m0; m <= CFG.mmax; m++) {
            long N = (1LL << m) - 1;
            for (int ti = 0; ti < CFG.nt; ti++) {
                if (2 * CFG.tvals[ti] + 1 > n) continue;
                tot += N;
            }
        }
    }
    return tot;
}
static void write_status_json(bool running) {
    double el = now_mono() - T0;
    long wd = atomic_load(&work_done);
    long ld = atomic_load(&lengths_done);
    long fc = atomic_load(&finds_count);
    double rate = (el > 1) ? (double)wd / el : 0;
    double eta = (rate > 0 && wd < work_total) ? (double)(work_total - wd) / rate : -1;
    char tmp[640], path[640];
    snprintf(path, sizeof path, "%s/status.json", CFG.dir);
    snprintf(tmp, sizeof tmp, "%s/status.json.tmp", CFG.dir);
    FILE *f = fopen(tmp, "w");
    if (!f) return;
    fprintf(f, "{\"running\":%s,\"lengths_done\":%ld,\"lengths_total\":%ld,"
               "\"work_done\":%ld,\"work_total\":%ld,\"elapsed_s\":%.1f,"
               "\"eta_s\":%.1f,\"finds\":%ld,\"polys\":%zu,\"last_update\":\"",
            running ? "true" : "false", ld, lengths_total, wd, work_total,
            el, eta, fc, poly_tab_n);
    char ts[32]; now_iso(ts, sizeof ts);
    fprintf(f, "%s\"}\n", ts);
    fclose(f);
    rename(tmp, path);
}

/* ---------------- per-length driver ---------------- */
static void search_n(worker_scratch *ws, int n, int rcap, const int *rsbits, cand_t *best);
static void process_length(worker_scratch *ws, int L) {
    int n = 8 * L;
    cand_t best[8];
    for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
    int rsbits[8];
    for (int ti = 0; ti < CFG.nt; ti++) rsbits[ti] = rs_parity_bits(L, CFG.tvals[ti]);
    search_n(ws, n, n / 8, rsbits, best);
    for (int ti = 0; ti < CFG.nt; ti++) {
        int t = CFG.tvals[ti];
        if (!best[ti].valid) continue;
        int rsp = rsbits[ti];
        if (best[ti].r < rsp || (best[ti].r == rsp && best[ti].d > 2 * t + 1))
            finalize_find(L, t, &best[ti]);
    }
    for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
    atomic_fetch_add(&lengths_done, 1);
    mark_done_mem(L);
}

/* ---------------- resume loading ---------------- */
static void load_resume(void) {
    /* done.bin */
    char path[640];
    snprintf(path, sizeof path, "%s/state/done.bin", CFG.dir);
    FILE *f = fopen(path, "rb");
    long have = 0;
    if (f) {
        size_t got = fread(done_bits, 1, (size_t)(lengths_total + 7) / 8, f);
        (void)got;
        fclose(f);
    }
    for (long i = 0; i < lengths_total; i++)
        if ((done_bits[i / 8] >> (i % 8)) & 1u) have++;
    atomic_store(&lengths_done, have);
    /* polys.txt */
    snprintf(path, sizeof path, "%s/polys.txt", CFG.dir);
    f = fopen(path, "r");
    if (f) {
        char line[8192];
        while (fgets(line, sizeof line, f)) {
            unsigned id = 0; int deg = 0, nb = 0; char hex[8192];
            if (sscanf(line, "POLY id=%x deg=%d nbytes=%d hex=%8191s", &id, &deg, &nb, hex) == 4) {
                uint8_t *bytes = (uint8_t *)xmalloc((size_t)(nb ? nb : 1));
                if (hex_to_bytes(bytes, hex, (size_t)nb) == nb) {
                    pthread_mutex_lock(&FIND_MU);
                    if (poly_tab_n * 10 >= poly_tab_cap * 7) poly_tab_grow();
                    uint64_t h = poly_hash_bytes(bytes, nb);
                    size_t j = h % poly_tab_cap;
                    while (poly_tab[j].used) j = (j + 1) % poly_tab_cap;
                    poly_tab[j].used = true; poly_tab[j].hash = h;
                    poly_tab[j].id = (uint16_t)id; poly_tab[j].deg = deg;
                    poly_tab[j].nbytes = nb; poly_tab[j].bytes = bytes;
                    poly_tab_n++;
                    if (id >= next_poly_id) next_poly_id = (uint16_t)(id + 1);
                    pthread_mutex_unlock(&FIND_MU);
                } else free(bytes);
            }
        }
        fclose(f);
    }
    /* finds.txt */
    snprintf(path, sizeof path, "%s/finds.txt", CFG.dir);
    f = fopen(path, "r");
    if (f) {
        char line[8192];
        while (fgets(line, sizeof line, f)) {
            int L = 0, t = 0, n = 0, r = 0, d = 0, parent = 0, pid = 0, rsp = 0, save = 0;
            char fam[16] = {0}, hex[8192] = {0};
            if (sscanf(line,
                    "FIND L=%d t=%d n=%d r=%d d=%d fam=%15s parent=%d poly=%x rsp=%d save=%d hex=%8191s",
                    &L, &t, &n, &r, &d, fam, &parent, &pid, &rsp, &save, hex) >= 10) {
                pthread_mutex_lock(&FIND_MU);
                if (finds_n >= finds_cap) {
                    finds_cap = finds_cap ? finds_cap * 2 : 1024;
                    finds_arr = (find_rec *)xrealloc(finds_arr, finds_cap * sizeof(find_rec));
                }
                finds_arr[finds_n++] = (find_rec){ L, t, n, r, d,
                    (strcmp(fam, "short") == 0) ? 1 : 0, parent, pid, rsp };
                pthread_mutex_unlock(&FIND_MU);
            }
        }
        fclose(f);
        atomic_store(&finds_count, (long)finds_n);
    }
}

/* ---------------- threads ---------------- */
static atomic_long next_li = 0;
static void *worker_main(void *arg) {
    (void)arg;
    worker_scratch ws; memset(&ws, 0, sizeof ws);
    while (!STOP) {
        long li = atomic_fetch_add(&next_li, 1);
        if (li >= lengths_total) break;
        int L = CFG.lmin + (int)li;
        if (is_done_len(L)) continue;
        process_length(&ws, L);
    }
    free(ws.cnt);
    return NULL;
}

static void ensure_dir(void) {
    char p[640];
    mkdir(CFG.dir, 0755);
    snprintf(p, sizeof p, "%s/state", CFG.dir);
    mkdir(p, 0755);
}
static FILE *open_append(const char *name) {
    char p[640];
    snprintf(p, sizeof p, "%s/%s", CFG.dir, name);
    return fopen(p, "a");
}

/* ---------------- main / CLI ---------------- */
static void usage(const char *prog) {
    fprintf(stderr,
        "usage: %s --toy [--dir DIR]\n"
        "       %s --crawl [--lmin N] [--lmax N] [--mmax N] [--threads N]\n"
        "                  [--dir DIR] [--resume] [-t 1,2,4,8,16,32]\n"
        "       %s --status [--dir DIR]\n"
        "       %s --gen-header [--dir DIR]\n"
        "\n"
        "  --toy    run the toy suite (Hamming/Golay/BCH rediscovery, divisor\n"
        "           counts, L=128 known win, g(x) recovery, mini-crawl) and exit.\n"
        "  --crawl  run the full crawl over byte lengths lmin..lmax (default\n"
        "           8..16384), shortened-BCH parents up to 2^mmax-1 (default 20).\n"
        "  --status print the crawl status from status.json.\n"
        "  --gen-header regenerate finds.h from finds.txt + polys.txt.\n",
        prog, prog, prog, prog);
}
static int run_toys(void); /* chunk 7 */

int main(int argc, char **argv) {
    detect_pclmul();
    rng_state ^= (uint64_t)getpid() * 0x9e3779b97f4a7c15ULL ^ (uint64_t)time(NULL);
    memset(&CFG, 0, sizeof CFG);
    CFG.lmin = 8; CFG.lmax = 16384; CFG.mmax = 20;
    CFG.nthreads = (int)sysconf(_SC_NPROCESSORS_ONLN);
    if (CFG.nthreads < 1) CFG.nthreads = 1;
    CFG.tvals[0] = 1; CFG.tvals[1] = 2; CFG.tvals[2] = 4;
    CFG.tvals[3] = 8; CFG.tvals[4] = 16; CFG.tvals[5] = 32;
    CFG.nt = 6;
    CFG.nparents = 0; /* unused; parents are m0..mmax */
    CFG.tier3_max_elems = 256;
    snprintf(CFG.dir, sizeof CFG.dir, "/opt/rssearch");
    const char *cmd = NULL;
    for (int i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "--toy")) cmd = "toy";
        else if (!strcmp(argv[i], "--crawl")) cmd = "crawl";
        else if (!strcmp(argv[i], "--status")) cmd = "status";
        else if (!strcmp(argv[i], "--gen-header")) cmd = "gen-header";
        else if (!strcmp(argv[i], "--resume")) CFG.resume = true;
        else if (!strcmp(argv[i], "--lmin") && i + 1 < argc) CFG.lmin = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--lmax") && i + 1 < argc) CFG.lmax = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--mmax") && i + 1 < argc) CFG.mmax = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--threads") && i + 1 < argc) CFG.nthreads = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--dir") && i + 1 < argc) snprintf(CFG.dir, sizeof CFG.dir, "%s", argv[++i]);
        else if (!strcmp(argv[i], "-t") && i + 1 < argc) {
            CFG.nt = 0;
            char *s = argv[++i], *save = NULL;
            for (char *tok = strtok_r(s, ",", &save); tok && CFG.nt < 8; tok = strtok_r(NULL, ",", &save))
                CFG.tvals[CFG.nt++] = atoi(tok);
        } else { fprintf(stderr, "unknown arg: %s\n", argv[i]); usage(argv[0]); return 1; }
    }
    if (!cmd) { usage(argv[0]); return 1; }
    T0 = now_mono();
    signal(SIGINT, on_signal);
    signal(SIGTERM, on_signal);

    if (!strcmp(cmd, "toy")) {
        return run_toys();
    }
    if (!strcmp(cmd, "status")) {
        char p[640];
        snprintf(p, sizeof p, "%s/status.json", CFG.dir);
        FILE *f = fopen(p, "r");
        if (!f) { printf("no status.json in %s (crawl never ran?)\n", CFG.dir); return 1; }
        char buf[4096]; size_t n = fread(buf, 1, sizeof buf - 1, f);
        buf[n] = 0; fclose(f);
        printf("%s", buf);
        return 0;
    }
    ensure_dir();
    if (!strcmp(cmd, "gen-header")) {
        lengths_total = CFG.lmax - CFG.lmin + 1;
        done_bits = (uint8_t *)xcalloc((size_t)(lengths_total + 7) / 8, 1);
        poly_tab_cap = 1024;
        poly_tab = (poly_ent *)xcalloc(poly_tab_cap, sizeof(poly_ent));
        load_resume();
        pthread_mutex_lock(&FIND_MU);
        gen_finds_h();
        pthread_mutex_unlock(&FIND_MU);
        printf("finds.h regenerated: %zu finds, %zu polys\n", finds_n, poly_tab_n);
        return 0;
    }
    /* --crawl */
    lengths_total = CFG.lmax - CFG.lmin + 1;
    done_bits = (uint8_t *)xcalloc((size_t)(lengths_total + 7) / 8, 1);
    poly_tab_cap = 1024;
    poly_tab = (poly_ent *)xcalloc(poly_tab_cap, sizeof(poly_ent));
    {
        char p[640];
        snprintf(p, sizeof p, "%s/search.log", CFG.dir);
        LOGFP = fopen(p, "a");
        if (!LOGFP) { fprintf(stderr, "cannot open %s\n", p); return 1; }
    }
    FINDS_FP = open_append("finds.txt");
    POLYS_FP = open_append("polys.txt");
    if (CFG.resume) load_resume();
    work_total = compute_work_total();
    log_line("START crawl L=%d..%d nthreads=%d mmax=%d pclmul=%d resume=%d "
             "lengths_total=%ld work_total=%ld already_done=%ld finds=%zu polys=%zu",
             CFG.lmin, CFG.lmax, CFG.nthreads, CFG.mmax, HAVE_PCLMUL,
             CFG.resume, lengths_total, work_total,
             atomic_load(&lengths_done), finds_n, poly_tab_n);
    log_line("SCOPE tier-S shortened BCH (parents m0..%d, all b, sliding window), "
             "tier-R exact repeated-root (n<=64, t<=2), tier-3 polish (gated). "
             "Exact-length cyclic codes at even n have d=2 for squarefree "
             "generators (x^o+1 weight-2 codeword), so no tier-1 coset-union "
             "search is run; BCH bounds are applied only at parent length.",
             CFG.mmax);
    log_line("RS baseline: bit errors, RS over GF(2^m) m=smallest with 2^m-1>=L, "
             "parity 2*t*m bits. Find iff binary r < RS parity (or equal r, larger d).");
    pthread_t *ths = (pthread_t *)xmalloc((size_t)CFG.nthreads * sizeof(pthread_t));
    for (int i = 0; i < CFG.nthreads; i++)
        pthread_create(&ths[i], NULL, worker_main, NULL);
    double last_status = now_mono(), last_persist = now_mono();
    while (1) {
        struct timespec ts = { 0, 200 * 1000 * 1000 };
        nanosleep(&ts, NULL);
        double now = now_mono();
        if (now - last_persist >= 10) { persist_state(); write_status_json(true); last_persist = now; }
        if (now - last_status >= 60) {
            long wd = atomic_load(&work_done);
            long ld = atomic_load(&lengths_done);
            double el = now - T0;
            double rate = (el > 1) ? (double)wd / el : 0;
            double eta = (rate > 0 && wd < work_total) ? (double)(work_total - wd) / rate : -1;
            char etabuf[64];
            if (eta < 0) snprintf(etabuf, sizeof etabuf, "n/a");
            else snprintf(etabuf, sizeof etabuf, "%.0fs (%.1f min)", eta, eta / 60.0);
            log_line("STATUS lengths %ld/%ld (%.1f%%) work %ld/%ld (%.1f%%) "
                     "rate %.0f steps/s elapsed %.0fs ETA %s finds %ld polys %zu",
                     ld, lengths_total, 100.0 * ld / lengths_total,
                     wd, work_total, 100.0 * wd / work_total, rate, el,
                     etabuf, atomic_load(&finds_count), poly_tab_n);
            last_status = now;
        }
        long done = 0;
        /* check if all workers finished: next_li exhausted and lengths_done==total */
        if (atomic_load(&next_li) >= lengths_total &&
            atomic_load(&lengths_done) >= lengths_total)
            done = 1;
        if (STOP) {
            log_line("STOP requested; waiting for workers to finish current lengths...");
            /* workers check STOP each loop; wait for them */
            for (int i = 0; i < CFG.nthreads; i++) pthread_join(ths[i], NULL);
            break;
        }
        if (done) break;
    }
    for (int i = 0; i < CFG.nthreads; i++) {
        /* join any not yet joined (STOP path already joined) */
        if (!STOP) pthread_join(ths[i], NULL);
    }
    persist_state();
    pthread_mutex_lock(&FIND_MU);
    gen_finds_h();
    pthread_mutex_unlock(&FIND_MU);
    write_status_json(false);
    double el = now_mono() - T0;
    log_line("DONE lengths %ld/%ld work %ld/%ld elapsed %.1fs finds %ld polys %zu",
             atomic_load(&lengths_done), lengths_total,
             atomic_load(&work_done), work_total, el,
             atomic_load(&finds_count), poly_tab_n);
    if (FINDS_FP) fclose(FINDS_FP);
    if (POLYS_FP) fclose(POLYS_FP);
    if (LOGFP) fclose(LOGFP);
    return 0;
}

/* ---------------- reusable per-length search (any bit-length n) -------- */
static void search_n(worker_scratch *ws, int n, int rcap, const int *rsbits, cand_t *best) {
    int o = n; while ((o % 2) == 0) o /= 2;
    int m0 = 0; while (((1LL << m0) - 1) < n) m0++;
    for (int m = m0; m <= CFG.mmax; m++) {
        long N = (1LL << m) - 1;
        cosets_t *C = cosets_get(N);
        if (!C) continue;
        for (int ti = 0; ti < CFG.nt; ti++) {
            int t = CFG.tvals[ti];
            if (2 * t + 1 > n) continue;
            int best_b = 0;
            int r = tierS_best_b(C, t, ws, &best_b);
            atomic_fetch_add(&work_done, N);
            if (r > rcap) continue;
            if (r < best[ti].r || (r == best[ti].r && N < best[ti].parent)) {
                int *cos_tmp = (int *)xmalloc((size_t)(2 * t + 1) * sizeof(int));
                int nc = tierS_window_cosets(C, t, best_b, cos_tmp, 2 * t + 1);
                cand_t c; cand_init(&c);
                c.r = r;
                c.d = bch_bound_of_cosets(C, cos_tmp, nc);
                c.fam = 1; c.parent = N; c.mod = N; c.ncos = nc;
                c.cos = cos_tmp;
                c.exp = (int *)xmalloc((size_t)(nc ? nc : 1) * sizeof(int));
                for (int j = 0; j < nc; j++) c.exp[j] = 1;
                c.valid = true;
                cand_copy(&best[ti], &c);
                cand_free(&c);
            }
        }
    }
    if (n <= 64) tierR(ws, 0, n, o, best);
    if (rsbits) {
        for (int ti = 0; ti < CFG.nt; ti++) {
            int t = CFG.tvals[ti];
            if (best[ti].valid && best[ti].fam == 1 &&
                best[ti].r > rsbits[ti] && best[ti].ncos <= 32)
                tier3_polish(&best[ti], t);
        }
    }
    /* stepped bound for shortened bests (parent length == modulus: valid) */
    for (int ti = 0; ti < CFG.nt; ti++) {
        if (!best[ti].valid || best[ti].fam != 1) continue;
        cosets_t *C = cosets_get(best[ti].parent);
        if (!C) continue;
        int m = 0;
        int *elems = coset_elems_list(C, best[ti].cos, best[ti].ncos, &m);
        int sb = bch_bound_stepped(elems, m, C->o, 512);
        if (sb > best[ti].d) best[ti].d = sb;
        free(elems);
    }
}

/* ---------------- toys ---------------- */
static int toy_fail = 0;
static void toy_check(const char *name, bool ok, const char *detail) {
    printf("  [%s] %s%s%s\n", ok ? "PASS" : "FAIL", name, detail ? ": " : "", detail ? detail : "");
    fflush(stdout);
    if (!ok) toy_fail++;
}
/* Independent field verification of a parent BCH bound claim: build
 * GF(2^D), D=ord_N(2), primitive N-th root alpha; evaluate g(alpha^i) for
 * i=0..N-1; return the longest run of zeros + 1 (or -1 on failure). */
static int verify_bch_field(const uint8_t *gbytes, int gdeg, int N) {
    int D = order_mod_2(N);
    if (D < 1 || D > GF_D_MAX) return -1;
    gf_t *F = gf_get(D);
    if (!F) return -1;
    uint64_t *alpha = (uint64_t *)xcalloc((size_t)F->nw, 8);
    if (!gf_prim_root(F, N, alpha)) { free(alpha); return -1; }
    int gnw = p_nw_for_deg(gdeg);
    uint64_t *g = (uint64_t *)xcalloc((size_t)gnw, 8);
    p_from_bytes(g, gnw, gbytes, p_nbytes_for_deg(gdeg));
    uint64_t *powi = (uint64_t *)xcalloc((size_t)F->nw, 8);
    uint64_t *res = (uint64_t *)xcalloc((size_t)F->nw, 8);
    uint64_t *tmp = (uint64_t *)xcalloc((size_t)F->nw, 8);
    powi[0] = 1;
    /* Collect the zero set Z = { i : g(alpha^i) == 0 }. Because alpha is
     * deterministic (see gf_prim_root), Z is the defining set itself; but
     * even for a different primitive root it is a unit multiple of it, so
     * the stepped bound on Z equals the stepped bound of the defining set,
     * which is what the claimed d is (max of BCH and stepped). */
    int *zeros = (int *)xmalloc((size_t)(N ? N : 1) * sizeof(int));
    int nz = 0;
    for (int i = 0; i < N; i++) {
        /* Horner: res = g(powi) */
        memset(res, 0, (size_t)F->nw * 8);
        for (int j = gdeg; j >= 0; j--) {
            gf_mul(F, tmp, res, powi);
            memcpy(res, tmp, (size_t)F->nw * 8);
            if ((g[j / 64] >> (j % 64)) & 1ULL) res[0] ^= 1ULL;
        }
        if (gf_is_zero(F, res)) zeros[nz++] = i;
        /* powi *= alpha */
        gf_mul(F, tmp, powi, alpha);
        memcpy(powi, tmp, (size_t)F->nw * 8);
    }
    int fb = bch_bound_stepped(zeros, nz, N, 4096);
    free(alpha); free(g); free(powi); free(res); free(tmp); free(zeros);
    return fb;
}
static bool poly_divides_xn_plus_1(const uint8_t *gbytes, int gdeg, int n) {
    int gnw = p_nw_for_deg(gdeg);
    uint64_t *g = (uint64_t *)xcalloc((size_t)gnw, 8);
    p_from_bytes(g, gnw, gbytes, p_nbytes_for_deg(gdeg));
    uint64_t *x = (uint64_t *)xcalloc((size_t)gnw, 8);
    uint64_t *r = (uint64_t *)xcalloc((size_t)gnw, 8);
    x[0] = 2;
    p_powmod_u64(r, x, gnw, (uint64_t)n, g, gnw);
    bool ok = (r[0] == 1);
    for (int i = 1; i < gnw; i++) if (r[i]) ok = false;
    free(g); free(x); free(r);
    return ok;
}
static int run_toys(void) {
    printf("rssearch toy suite\n");
    worker_scratch ws; memset(&ws, 0, sizeof ws);
    /* T1: Hamming (7,4), t=1 */
    {
        cand_t best[8];
        for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
        search_n(&ws, 7, 7, NULL, best);
        int ti = 0; /* t=1 */
        char det[256];
        snprintf(det, sizeof det, "r=%d d=%d (want r=3 d=3)", best[ti].r, best[ti].d);
        toy_check("T1 Hamming(7,4) t=1", best[ti].valid && best[ti].r == 3 && best[ti].d == 3, det);
        /* recover g and check it is x^3+x+1 (0x0b) and exact distance 3 */
        uint8_t gb[8192]; int gd = 0, gnb = 0;
        bool ok = poly_from_cosets(best[ti].mod, best[ti].cos, best[ti].exp,
                                   best[ti].ncos, gb, &gd, &gnb);
        uint64_t g = 0;
        for (int i = 0; i < gnb; i++) g |= (uint64_t)gb[i] << (8 * i);
        int ed = exact_dist_u64(g, gd, 7, 4);
        /* 0x0b and 0x0d are reciprocal primitive polys; both are Hamming gens */
        snprintf(det, sizeof det, "g=0x%llx exact_d=%d (want 0xb/0xd, 3)", (unsigned long long)g, ed);
        toy_check("T1 g(x) is Hamming, exact d=3", ok && (g == 0x0b || g == 0x0d) && ed == 3, det);
        for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
    }
    /* T2: (23,13,5) at t=2. The Golay code (r=11) is NOT the best here: a
     * shortened BCH from parent N=31 gives r=10, d=5, which wins on parity.
     * The Golay code itself is tested separately below at t=3. */
    {
        cand_t best[8];
        for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
        search_n(&ws, 23, 23, NULL, best);
        int ti = 1; /* t=2 */
        char det[256];
        snprintf(det, sizeof det, "r=%d d=%d (want r=10 d>=5)", best[ti].r, best[ti].d);
        toy_check("T2 (23,13,5) t=2 finds r=10 d>=5", best[ti].valid && best[ti].r == 10 && best[ti].d >= 5, det);
        uint8_t gb[8192]; int gd = 0, gnb = 0;
        bool ok = poly_from_cosets(best[ti].mod, best[ti].cos, best[ti].exp,
                                   best[ti].ncos, gb, &gd, &gnb);
        uint64_t g = 0;
        for (int i = 0; i < gnb; i++) g |= (uint64_t)gb[i] << (8 * i);
        int ed = exact_dist_u64(g, gd, 23, 6);
        bool div = poly_divides_xn_plus_1(gb, gd, best[ti].parent);
        snprintf(det, sizeof det, "g=0x%llx exact_d=%d divides x^N+1=%d (want d=5, div=1)", (unsigned long long)g, ed, div);
        toy_check("T2 g(x) valid, exact d=5", ok && ed == 5 && div, det);
        for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
    }
    /* T2b: t=3 (d>=7) at n=23. NOTE: the Golay code (r=11, true d=7) is NOT
     * found here, and that is correct for a bound-based search: Golay's BCH
     * bound is only 5 (longest consecutive run in its defining set is 4),
     * so no bound-based evaluator can certify it for t=3. The search finds
     * the best code provable by bound: shortened BCH from N=31, r=15, d=7.
     * Golay is outside the search's families for t>=3 (it is a native
     * length-23 cyclic code, not a shortened BCH code). Documented limit. */
    {
        int save_tvals[8]; int save_nt = CFG.nt;
        memcpy(save_tvals, CFG.tvals, sizeof save_tvals);
        CFG.nt = 1; CFG.tvals[0] = 3;
        cand_t best[8];
        for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
        search_n(&ws, 23, 23, NULL, best);
        char det[256];
        snprintf(det, sizeof det, "r=%d d=%d (want r=15 d>=7)", best[0].r, best[0].d);
        toy_check("T2b t=3 best-by-bound r=15 d>=7", best[0].valid && best[0].r == 15 && best[0].d >= 7, det);
        uint8_t gb[8192]; int gd = 0, gnb = 0;
        bool ok = poly_from_cosets(best[0].mod, best[0].cos, best[0].exp,
                                   best[0].ncos, gb, &gd, &gnb);
        uint64_t g = 0;
        for (int i = 0; i < gnb; i++) g |= (uint64_t)gb[i] << (8 * i);
        int ed = exact_dist_u64(g, gd, 23, 6);
        bool div = poly_divides_xn_plus_1(gb, gd, best[0].parent);
        snprintf(det, sizeof det, "g=0x%llx exact_d=%d divides x^N+1=%d (want d=7, div=1)", (unsigned long long)g, ed, div);
        toy_check("T2b g(x) valid, exact d=7", ok && ed == 7 && div, det);
        for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
        memcpy(CFG.tvals, save_tvals, sizeof save_tvals);
        CFG.nt = save_nt;
    }
    /* T3: BCH (15,7,5), t=2 */
    {
        cand_t best[8];
        for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
        search_n(&ws, 15, 15, NULL, best);
        int ti = 1; /* t=2 */
        char det[256];
        snprintf(det, sizeof det, "r=%d d=%d (want r=8 d>=5)", best[ti].r, best[ti].d);
        toy_check("T3 BCH(15,7) t=2", best[ti].valid && best[ti].r == 8 && best[ti].d >= 5, det);
        uint8_t gb[8192]; int gd = 0, gnb = 0;
        bool ok = poly_from_cosets(best[ti].mod, best[ti].cos, best[ti].exp,
                                   best[ti].ncos, gb, &gd, &gnb);
        uint64_t g = 0;
        for (int i = 0; i < gnb; i++) g |= (uint64_t)gb[i] << (8 * i);
        int ed = exact_dist_u64(g, gd, 15, 4);
        bool div = poly_divides_xn_plus_1(gb, gd, 15);
        snprintf(det, sizeof det, "g=0x%llx exact_d=%d divides x^15+1=%d (want deg 8, d=5, div=1)", (unsigned long long)g, ed, div);
        toy_check("T3 g(x) deg 8, exact d=5", ok && gd == 8 && ed == 5 && div, det);
        for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
    }
    /* T4: BCH (31,21,5), t=2 */
    {
        cand_t best[8];
        for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
        search_n(&ws, 31, 31, NULL, best);
        int ti = 1; /* t=2 */
        char det[256];
        snprintf(det, sizeof det, "r=%d d=%d (want r=10 d>=5)", best[ti].r, best[ti].d);
        toy_check("T4 BCH(31,21) t=2", best[ti].valid && best[ti].r == 10 && best[ti].d >= 5, det);
        uint8_t gb[8192]; int gd = 0, gnb = 0;
        bool ok = poly_from_cosets(best[ti].mod, best[ti].cos, best[ti].exp,
                                   best[ti].ncos, gb, &gd, &gnb);
        uint64_t g = 0;
        for (int i = 0; i < gnb; i++) g |= (uint64_t)gb[i] << (8 * i);
        int ed = exact_dist_u64(g, gd, 31, 4);
        snprintf(det, sizeof det, "g=0x%llx exact_d=%d (want d=5)", (unsigned long long)g, ed);
        toy_check("T4 exact d=5", ok && ed == 5, det);
        for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
    }
    /* T5: divisor counts (formula) vs hardcoded Python values, plus a
     * coset-based cross-check for o=255 and o=1413. */
    {
        struct { int L; long want; } cases[] = {
            { 8, 1 }, { 128, 1 }, { 255, 119456 }, { 857, 1 },
            { 922, 1 }, { 1000, 7 }, { 1024, 1 }, { 1413, 7 },
        };
        bool allok = true;
        for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
            int o = cases[i].L;
            while ((o % 2) == 0) o /= 2;
            long got = tier1_struct_count(o, 32);
            if (got != cases[i].want) {
                printf("  T5 L=%d: got %ld want %ld\n", cases[i].L, got, cases[i].want);
                allok = false;
            }
        }
        toy_check("T5 divisor counts (formula vs Python)", allok, "8 cases");
        /* coset-based cross-check: count squarefree subsets of degree<=32
         * directly from cosets_get for o=255 and o=1413 */
        bool ok2 = true;
        for (int oi = 0; oi < 2; oi++) {
            int o = oi == 0 ? 255 : 1413;
            cosets_t *C = cosets_get(o);
            long dp[64] = {0}; dp[0] = 1;
            for (int c = 0; c < C->ncos; c++) {
                int deg = C->cdeg[c];
                for (int u = 32 - deg; u >= 0; u--) if (dp[u]) dp[u + deg] += dp[u];
            }
            long tot = 0; for (int i = 1; i <= 32; i++) tot += dp[i];
            long want = (o == 255) ? 119456 : 7;
            if (tot != want) { printf("  T5 coset DP o=%d: got %ld want %ld\n", o, tot, want); ok2 = false; }
        }
        toy_check("T5 divisor counts (coset DP cross-check)", ok2, "o=255,1413");
    }
    /* T6: known win L=128, t=1 -> shortened Hamming r=11 beats RS 16 */
    {
        cand_t best[8];
        for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
        search_n(&ws, 1024, 128, NULL, best);
        int ti = 0; /* t=1 */
        int rsp = rs_parity_bits(128, 1);
        char det[256];
        snprintf(det, sizeof det, "r=%d d=%d rs=%d (want r=11 < 16)", best[ti].r, best[ti].d, rsp);
        toy_check("T6 L=128 t=1 Hamming r=11 beats RS", best[ti].valid && best[ti].r == 11 && rsp == 16, det);
        for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
    }
    /* T7: g(x) recovery is exercised by T1-T4 already (poly_from_cosets +
     * exact distance). Here: ord_8191(2) must be 13 (not 856). */
    {
        int od = order_mod_2(8191);
        char det[64];
        snprintf(det, sizeof det, "ord_8191(2)=%d (want 13)", od);
        toy_check("T7 ord_8191(2)=13", od == 13, det);
        int od2 = order_mod_2(857);
        snprintf(det, sizeof det, "ord_857(2)=%d (want 428)", od2);
        toy_check("T7 ord_857(2)=428", od2 == 428, det);
    }
    /* T8: mini-crawl L=8..16, field-verify every best's BCH bound claim. */
    {
        bool allok = true;
        for (int L = 8; L <= 16; L++) {
            cand_t best[8];
            for (int i = 0; i < CFG.nt; i++) cand_init(&best[i]);
            search_n(&ws, 8 * L, L, NULL, best);
            for (int ti = 0; ti < CFG.nt; ti++) {
                int t = CFG.tvals[ti];
                if (!best[ti].valid || best[ti].fam != 1) continue;
                uint8_t gb[8192]; int gd = 0, gnb = 0;
                bool ok = poly_from_cosets(best[ti].mod, best[ti].cos, best[ti].exp,
                                           best[ti].ncos, gb, &gd, &gnb);
                if (!ok || gd != best[ti].r) { allok = false; printf("  T8 L=%d t=%d: g recovery failed\n", L, t); continue; }
                if (!poly_divides_xn_plus_1(gb, gd, best[ti].parent)) { allok = false; printf("  T8 L=%d t=%d: g does not divide x^N+1\n", L, t); continue; }
                int fb = verify_bch_field(gb, gd, best[ti].parent);
                if (fb < best[ti].d) {
                    allok = false;
                    printf("  T8 L=%d t=%d: field bound %d < claimed d %d\n", L, t, fb, best[ti].d);
                }
            }
            for (int i = 0; i < CFG.nt; i++) cand_free(&best[i]);
        }
        toy_check("T8 mini-crawl L=8..16 field-verified", allok, "all bests");
    }
    free(ws.cnt);
    printf("toy suite: %s\n", toy_fail ? "FAILURES PRESENT" : "ALL PASS");
    return toy_fail ? 1 : 0;
}

Makefile

Build rules.

CC      ?= gcc
CFLAGS  ?= -O2 -march=native -Wall -Wextra -Wno-unused-parameter
LDFLAGS ?= -lpthread -lm

all: rssearch

rssearch: rssearch.c
	$(CC) $(CFLAGS) -o $@ rssearch.c $(LDFLAGS)

toy: rssearch
	./rssearch --toy

clean:
	rm -f rssearch

.PHONY: all toy clean

README.md

Usage, design notes, and the honest limitations.

# rssearch — polynomial Reed-Solomon discovery

Crawls every byte length L = 8..16384 (n = 8L bits) and searches for binary
codes that beat Reed-Solomon for **bit errors** (correct t random bit errors).

## The key mathematical correction

Exact-length cyclic codes at **even** lengths are a dead end: any squarefree
generator dividing x^o+1 (o = odd part of n) gives the weight-2 codeword
x^o+1 at length n > o, so d = 2. (Example: the Hamming generator x^3+x+1
gives the codeword 1+x^7 at length 14.) The search therefore uses
**shortened BCH** as its primary family: a parent cyclic BCH code of odd
length N = 2^m-1, shortened to exactly n bits. Shortening preserves
distance, and the BCH bound is applied only at the parent length, where it
is valid. A small exact repeated-root tier (n <= 64, t <= 2) is evaluated
by exact minimum distance, not by a bound.

## Families

- **Tier S (primary, exhaustive):** shortened BCH. All parents m0..mmax
  (m0 = smallest m with 2^m-1 >= n), all starting offsets b, via an O(N)
  sliding window per (parent, t). Distance >= 2t+1 by the BCH bound on the
  parent.
- **Tier R (exact, n <= 64, t <= 2):** all generators g | x^n+1, evaluated
  by exact minimum distance (pattern/remainder method).
- **Tier 3 (polish):** greedy coset removal on shortened bests, gated to
  non-finds with small defining sets.

## RS baseline

For length L and t bit errors, RS over GF(2^m) (m = smallest with
2^m-1 >= L, m >= 8) must correct up to t byte errors, needing 2t symbols =
2*t*m parity bits. A find is a binary code with fewer parity bits (or equal
parity with larger distance).

## Usage

```
make            # build
./rssearch --toy                       # toy suite (must ALL PASS)
./rssearch --crawl --dir /opt/rssearch --resume   # full crawl
./rssearch --status --dir /opt/rssearch
./rssearch --gen-header --dir /opt/rssearch
```

## Outputs (in --dir)

- `search.log` — tail-able log with STATUS lines incl. ETA
- `status.json` — machine-readable progress
- `finds.txt` — one line per (L,t) find (append-only)
- `polys.txt` — distinct generator polynomials, each with a 2-byte id
- `finds.h` — generated C header (poly table + finds table)
- `state/done.bin` — checkpoint bitset (resume with --resume)

## Scope / honesty

Full exhaustion over all polynomials of degree <= n/8 is impossible
(2^(n/8) of them). The exhaustive tier is the shortened-BCH family (all
parents, all offsets). Above the BCH-designed family, non-BCH codes with
large parity are probed only by the tier-3 polish. The log states this
scope at startup.

gen_bch.c

The direct-construction tool for m = 23 to m = 256: orbit-only narrow-sense BCH generators (no O(N) scan). Finds a primitive polynomial per m, then multiplies the minimal polynomials of the cosets of the odd residues 1..2t-1. Modes: verify (reproduce the m = 18 and m = 21 polys hex-exact), single, checkprim, sweep (writes bch_direct_m23_256.csv).

/* gen_bch.c -- direct narrow-sense primitive BCH generator polynomials.
 *
 * Orbit-only construction (no O(N) scan): for each (m,t) walk ONLY the
 * cyclotomic cosets of the odd residues 1,3,...,2t-1 under *2 mod N=2^m-1,
 * take each coset's minimal polynomial over GF(2^m), multiply them over GF(2).
 * Field GF(2^m) = GF(2)[x]/(P), P a primitive polynomial of degree m.
 * Elements are uint64_t arrays (5 words: field elements are < 2^m, but P
 * itself has bit m set, so m=256 needs a 5th word); shift-and-xor multiply.
 *
 * Modes:
 *   gen_bch single m t [prim_hex] [factors_file]
 *       one (m,t); prim_hex (LSB-first hex, as in finds.h) forces P.
 *   gen_bch verify
 *       reproduce m=18 (polys.txt ids 0035-003a) and m=21 (modified-rssearch
 *       values) for all 6 t, using each m's t=1 hex as P; PASS/FAIL per row.
 *   gen_bch sweep lo hi factors_file csv_out
 *       m=lo..hi, t in {1,2,4,8,16,32}; appends CSV rows; progress on stderr.
 *
 * Factors file (text, one line per m):
 *   m complete_flag nprimes p_hex ...
 * p_hex is the prime in plain hex (MSB first, no 0x), any size <= 256 bits.
 * complete_flag=1 means the distinct prime factors of 2^m-1 are complete;
 * 0 means only the known ones are listed -> P is "probable-primitive".
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <time.h>

#define MAXM 256
#define FW 5                 /* field words: 5*64 = 320 bits (P needs bit m) */
#define GW 136               /* g(x) words: 136*64 = 8704 bits > 8192 */
#define MAXPRIMES 64

typedef uint64_t fe[FW];     /* GF(2^m) element, bit i = coeff of x^i */
typedef uint64_t bw[GW];     /* binary polynomial, bit i = coeff of x^i */

static const fe FE_X = {2, 0, 0, 0, 0};
static const fe FE_ONE = {1, 0, 0, 0, 0};

static double now_s(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec + ts.tv_nsec * 1e-9;
}

/* ---------- small bigint helpers (LE uint64 arrays, FW words) ---------- */
static int bi_bits(const uint64_t *a, int nw) {
    for (int i = nw - 1; i >= 0; i--)
        if (a[i]) return i * 64 + 64 - __builtin_clzll(a[i]);
    return 0;
}
static int bi_cmp(const uint64_t *a, const uint64_t *b, int nw) {
    for (int i = nw - 1; i >= 0; i--) {
        if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1;
    }
    return 0;
}
/* d = a - b, assumes a >= b */
static void bi_sub(uint64_t *d, const uint64_t *a, const uint64_t *b, int nw) {
    uint64_t borrow = 0;
    for (int i = 0; i < nw; i++) {
        __uint128_t cur = (__uint128_t)a[i] - b[i] - borrow;
        d[i] = (uint64_t)cur;
        borrow = (cur >> 64) ? 1 : 0;
    }
}
/* quotient = (2^m - 1) / p, p a big int of FW words (p > 1). Bit-by-bit long
 * division; m <= 256 so at most 256 steps of FW-word compare/subtract. */
static void bi_div_Nminus1_by(const uint64_t *p, int m, uint64_t *q) {
    /* dividend N = 2^m - 1: bit i set for i < m */
    uint64_t rem[FW] = {0};
    memset(q, 0, FW * sizeof(uint64_t));
    for (int i = m - 1; i >= 0; i--) {
        /* rem = 2*rem + bit_i(N) = 2*rem + 1 */
        uint64_t carry = 1;
        for (int w = 0; w < FW; w++) {
            uint64_t nc = rem[w] >> 63;
            rem[w] = (rem[w] << 1) | carry;
            carry = nc;
        }
        if (bi_cmp(rem, p, FW) >= 0) {
            bi_sub(rem, rem, p, FW);
            q[i / 64] |= 1ULL << (i % 64);
        }
    }
}

/* ---------- GF(2^m) arithmetic mod P (P: fe, degree m) ---------- */
static void fe_mul(const fe a, const fe b, const fe P, int m, fe r) {
    /* carryless multiply into 8-word accumulator, then reduce */
    uint64_t acc[8] = {0};
    for (int i = 0; i < m; i++) {
        if ((b[i / 64] >> (i % 64)) & 1ULL) {
            int wshift = i / 64, bshift = i % 64;
            uint64_t carry = 0;
            for (int w = 0; w < FW; w++) {
                int t = w + wshift;
                if (t >= 8) break;
                uint64_t v = (a[w] << bshift) | carry;
                acc[t] ^= v;
                carry = bshift ? (a[w] >> (64 - bshift)) : 0;
            }
            if (wshift + FW < 8 && carry) acc[wshift + FW] ^= carry;
        }
    }
    /* reduce: for i = 2m-2 .. m: if bit i set, acc ^= P << (i-m).
     * P<<(i-m) has its top bit at i, so this clears bit i. */
    for (int i = 2 * m - 2; i >= m; i--) {
        if ((acc[i / 64] >> (i % 64)) & 1ULL) {
            int sh = i - m;
            int wshift = sh / 64, bshift = sh % 64;
            uint64_t carry = 0;
            for (int w = 0; w < FW; w++) {
                int t = w + wshift;
                if (t >= 8) break;
                uint64_t v = (P[w] << bshift) | carry;
                acc[t] ^= v;
                carry = bshift ? (P[w] >> (64 - bshift)) : 0;
            }
        }
    }
    memcpy(r, acc, FW * sizeof(uint64_t));
    int top = (m + 63) / 64;
    for (int w = top; w < FW; w++) r[w] = 0;
}
static void fe_sqr(const fe a, const fe P, int m, fe r) { fe_mul(a, a, P, m, r); }

/* r = base^e mod P; e is a big int of FW words */
static void fe_pow(const fe base, const uint64_t *e, const fe P, int m, fe r) {
    fe res = {0}, cur;
    res[0] = 1;
    memcpy(cur, base, sizeof(fe));
    int nb = bi_bits(e, FW);
    for (int i = 0; i < nb; i++) {
        if ((e[i / 64] >> (i % 64)) & 1ULL) {
            fe t; fe_mul(res, cur, P, m, t); memcpy(res, t, sizeof(fe));
        }
        if (i + 1 < nb) { fe t; fe_sqr(cur, P, m, t); memcpy(cur, t, sizeof(fe)); }
    }
    memcpy(r, res, sizeof(fe));
}
/* r = x^(2^k) mod P by repeated squaring */
static void fe_pow_x_2k(int k, const fe P, int m, fe r) {
    fe cur;
    memcpy(cur, FE_X, sizeof(fe));
    for (int i = 0; i < k; i++) { fe t; fe_sqr(cur, P, m, t); memcpy(cur, t, sizeof(fe)); }
    memcpy(r, cur, sizeof(fe));
}

/* ---------- binary polynomials (degree <= 256, FW words) ---------- */
static int poly_deg(const fe a) {
    for (int i = FW - 1; i >= 0; i--)
        if (a[i]) return i * 64 + 64 - __builtin_clzll(a[i]) - 1;
    return -1;
}
static void poly_mod(fe r, const fe a, const fe b) {
    /* r = a mod b (binary polynomials) */
    fe t; memcpy(t, a, sizeof(fe));
    int db = poly_deg(b);
    if (db < 0) { memset(r, 0, sizeof(fe)); return; }
    int dt;
    while ((dt = poly_deg(t)) >= db && dt >= 0) {
        int sh = dt - db;
        for (int w = 0; w < FW; w++) {
            uint64_t v = 0;
            int src = w - sh / 64;
            if (src >= 0 && src < FW) {
                v = b[src] << (sh % 64);
                if ((sh % 64) && src > 0) v |= b[src - 1] >> (64 - (sh % 64));
            }
            t[w] ^= v;
        }
    }
    memcpy(r, t, sizeof(fe));
}
static int poly_gcd_is_one(const fe a, const fe b) {
    fe u, v, t;
    memcpy(u, a, sizeof(fe)); memcpy(v, b, sizeof(fe));
    while (poly_deg(v) >= 0) {
        poly_mod(t, u, v);
        memcpy(u, v, sizeof(fe)); memcpy(v, t, sizeof(fe));
    }
    return poly_deg(u) == 0;   /* gcd == 1 */
}

/* ---------- primitivity ---------- */
static int prime_divisors_small(int m, int *qs) {
    int n = 0, t = m;
    for (int p = 2; p * p <= t; p++) {
        if (t % p == 0) { qs[n++] = p; while (t % p == 0) t /= p; }
    }
    if (t > 1) qs[n++] = t;
    return n;
}

/* P irreducible? x^(2^m)==x mod P and gcd(x^(2^(m/q))-x, P)==1 for q|m prime */
static int is_irreducible(const fe P, int m) {
    fe h;
    fe_pow_x_2k(m, P, m, h);
    if (memcmp(h, FE_X, sizeof(fe)) != 0) return 0;
    int qs[16];
    int nq = prime_divisors_small(m, qs);
    for (int i = 0; i < nq; i++) {
        fe_pow_x_2k(m / qs[i], P, m, h);
        h[0] ^= 2;   /* h - x in char 2 */
        if (!poly_gcd_is_one(h, P)) return 0;
    }
    return 1;
}

/* P primitive? irreducible and x^((2^m-1)/p) != 1 mod P for every prime p|N.
 * primes: array of big ints (FW words each), nprimes of them. */
static int is_primitive(const fe P, int m, const uint64_t *primes, int nprimes) {
    if (!is_irreducible(P, m)) return 0;
    for (int i = 0; i < nprimes; i++) {
        uint64_t e[FW];
        bi_div_Nminus1_by(primes + (size_t)i * FW, m, e);
        fe h; fe_pow(FE_X, e, P, m, h);
        if (memcmp(h, FE_ONE, sizeof(fe)) == 0) return 0;
    }
    return 1;
}

/* ---------- deterministic RNG (xorshift64*) ---------- */
static uint64_t rng_state;
static uint64_t rng_next(void) {
    uint64_t x = rng_state;
    x ^= x >> 12; x ^= x << 25; x ^= x >> 27;
    rng_state = x;
    return x * 0x2545F4914F6CDD1DULL;
}
static int rng_below(int n) { return (int)(rng_next() % (uint64_t)n); }

/* find a primitive poly of degree m. Tries trinomials, then random
 * pentanomials, then random heptanomials. Returns 1 on success. */
static int find_primitive(int m, const uint64_t *primes, int nprimes,
                          fe Pout, long *tries_out) {
    long tries = 0;
    fe P;
    /* trinomials x^m + x^k + 1 */
    for (int k = 1; k < m; k++) {
        memset(P, 0, sizeof(fe));
        P[m / 64] |= 1ULL << (m % 64);
        P[k / 64] |= 1ULL << (k % 64);
        P[0] |= 1ULL;
        tries++;
        if (is_primitive(P, m, primes, nprimes)) {
            memcpy(Pout, P, sizeof(fe)); *tries_out = tries; return 1;
        }
    }
    rng_state = 0x9E3779B97F4A7C15ULL ^ (0xA0761D6478BD642FULL * (uint64_t)m);
    for (int nterms = 5; nterms <= 7; nterms += 2) {
        long cap = (nterms == 5) ? 200000L : 100000L;
        for (long it = 0; it < cap; it++) {
            memset(P, 0, sizeof(fe));
            P[m / 64] |= 1ULL << (m % 64);
            P[0] |= 1ULL;
            int need = nterms - 2, picked = 0, guard = 0;
            while (picked < need && guard++ < 1000) {
                int k = 1 + rng_below(m - 1);
                if ((P[k / 64] >> (k % 64)) & 1ULL) continue;
                P[k / 64] |= 1ULL << (k % 64);
                picked++;
            }
            if (picked < need) continue;
            tries++;
            if (is_primitive(P, m, primes, nprimes)) {
                memcpy(Pout, P, sizeof(fe)); *tries_out = tries; return 1;
            }
        }
    }
    *tries_out = tries;
    return 0;
}

/* ---------- narrow-sense generator ---------- */
/* double a residue mod N = 2^m - 1 (value < N, FW words).
 * 2x >= 2^m iff old bit m-1 set; then 2x - N = (2x mod 2^m) + 1. */
static void res_double(uint64_t *a, int m) {
    int overflow = (a[(m - 1) / 64] >> ((m - 1) % 64)) & 1ULL;
    uint64_t carry = 0;
    for (int w = 0; w < FW; w++) {
        uint64_t nc = a[w] >> 63;
        a[w] = (a[w] << 1) | carry;
        carry = nc;
    }
    int top = (m + 63) / 64;
    if (m % 64) a[top - 1] &= (1ULL << (m % 64)) - 1;
    for (int w = top; w < FW; w++) a[w] = 0;
    if (overflow) {
        uint64_t c = 1;
        for (int w = 0; w < FW && c; w++) {
            uint64_t s = a[w] + c;
            c = (s < a[w]) ? 1 : 0;
            a[w] = s;
        }
    }
}

/* binary poly multiply: r = a*b over GF(2); degrees da, db */
static void bw_mul(const bw a, int da, const bw b, int db, bw r) {
    memset(r, 0, GW * sizeof(uint64_t));
    for (int i = 0; i <= db; i++) {
        if ((b[i / 64] >> (i % 64)) & 1ULL) {
            int wshift = i / 64, bshift = i % 64;
            uint64_t carry = 0;
            for (int w = 0; w <= da / 64; w++) {
                int t = w + wshift;
                if (t >= GW) break;
                uint64_t v = (a[w] << bshift) | carry;
                r[t] ^= v;
                carry = bshift ? (a[w] >> (64 - bshift)) : 0;
            }
            if (carry) {
                int t = (da / 64) + wshift + 1;
                if (t < GW) r[t] ^= carry;
            }
        }
    }
}
static int bw_deg(const bw a) {
    for (int i = GW - 1; i >= 0; i--)
        if (a[i]) return i * 64 + 64 - __builtin_clzll(a[i]) - 1;
    return -1;
}

/* minima of the distinct cosets, kept across calls within one process run */
static uint64_t g_minima[32][FW];

/* g(x) for (m,t); returns degree r, g in bits. Also returns ncosets. */
static int narrow_g(int m, int t, const fe P, bw g, int *ncos_out) {
    /* distinct cosets of odd residues 1,3,...,2t-1 */
    int ncos = 0;
    int osz[32];
    for (int a = 1; a < 2 * t; a += 2) {
        uint64_t cur[FW] = {0}, start[FW] = {0};
        cur[0] = (uint64_t)a; start[0] = (uint64_t)a;
        uint64_t minv[FW];
        memcpy(minv, cur, sizeof(minv));
        int n = 0;
        while (1) {
            if (bi_cmp(cur, minv, FW) < 0) memcpy(minv, cur, sizeof(minv));
            n++;
            res_double(cur, m);
            if (memcmp(cur, start, sizeof(uint64_t) * FW) == 0) break;
            if (n >= MAXM) { fprintf(stderr, "orbit overflow m=%d a=%d\n", m, a); exit(1); }
        }
        int dup = 0;
        for (int i = 0; i < ncos; i++)
            if (memcmp(g_minima[i], minv, sizeof(minv)) == 0) dup = 1;
        if (dup) continue;
        memcpy(g_minima[ncos], minv, sizeof(minv));
        osz[ncos] = n;
        ncos++;
    }
    /* g = product of minpolys */
    bw gg; memset(gg, 0, sizeof(bw)); gg[0] = 1;
    int dg = 0;
    for (int c = 0; c < ncos; c++) {
        int s_orb = osz[c];
        /* betas: alpha^(s*2^j), s = min of orbit = g_minima[c];
         * e starts at s, doubles (mod N) each step */
        uint64_t e[FW];
        memcpy(e, g_minima[c], sizeof(e));
        fe coef[MAXM + 1];
        int dc = 0;
        memset(coef, 0, sizeof(coef));
        coef[0][0] = 1;
        for (int j = 0; j < s_orb; j++) {
            fe beta;
            fe_pow(FE_X, e, P, m, beta);
            /* multiply coef by (X + beta) */
            fe ncoef[MAXM + 1];
            memset(ncoef, 0, sizeof(ncoef));
            for (int i = 0; i <= dc + 1; i++) {
                fe t1 = {0}, t2 = {0};
                if (i <= dc) fe_mul(coef[i], beta, P, m, t1);
                if (i > 0) memcpy(t2, coef[i - 1], sizeof(fe));
                for (int w = 0; w < FW; w++) ncoef[i][w] = t1[w] ^ t2[w];
            }
            dc++;
            memcpy(coef, ncoef, sizeof(coef));
            res_double(e, m);
        }
        /* minpoly must be binary: extract bits */
        bw mp; memset(mp, 0, sizeof(bw));
        int dm = -1;
        for (int i = 0; i <= dc; i++) {
            if (coef[i][0] == 1 && coef[i][1] == 0 && coef[i][2] == 0 &&
                coef[i][3] == 0 && coef[i][4] == 0) {
                mp[i / 64] |= 1ULL << (i % 64);
                dm = i;
            } else if (coef[i][0] || coef[i][1] || coef[i][2] || coef[i][3] || coef[i][4]) {
                fprintf(stderr, "non-binary minpoly coeff m=%d t=%d coset=%d i=%d\n",
                        m, t, c, i);
                exit(1);
            }
        }
        bw ng;
        bw_mul(gg, dg, mp, dm, ng);
        memcpy(gg, ng, sizeof(bw));
        dg += dm;
    }
    memcpy(g, gg, sizeof(bw));
    *ncos_out = ncos;
    return bw_deg(gg);
}

/* ---------- hex / decimal helpers ---------- */
/* parse LSB-first hex: byte i (2 hex chars) = bits 8i..8i+7. */
static void parse_hex_lsb(const char *s, uint64_t *out, int maxwords) {
    memset(out, 0, maxwords * sizeof(uint64_t));
    int len = strlen(s), nbytes = (len + 1) / 2;
    for (int i = 0; i < nbytes; i++) {
        char c0 = s[2 * i], c1 = (2 * i + 1 < len) ? s[2 * i + 1] : '0';
        int hi = isdigit((unsigned char)c0) ? c0 - '0' : (tolower((unsigned char)c0) - 'a' + 10);
        int lo = isdigit((unsigned char)c1) ? c1 - '0' : (tolower((unsigned char)c1) - 'a' + 10);
        int byte = hi * 16 + lo;
        int bit = 8 * i;
        out[bit / 64] |= (uint64_t)byte << (bit % 64);
    }
}
/* LSB-first hex string of a bit array (nbits bits), malloc'd */
static char *to_hex_lsb(const uint64_t *a, int nbits) {
    int nbytes = (nbits + 7) / 8;
    char *s = malloc(2 * nbytes + 1);
    static const char *H = "0123456789abcdef";
    for (int i = 0; i < nbytes; i++) {
        int bit = 8 * i;
        int byte = (int)((a[bit / 64] >> (bit % 64)) & 0xffULL);
        s[2 * i] = H[byte >> 4]; s[2 * i + 1] = H[byte & 15];
    }
    s[2 * nbytes] = 0;
    return s;
}
/* decimal string of 2^m - 1, malloc'd */
static char *dec_Nminus1(int m) {
    uint32_t d[16] = {1}; int nd = 1;
    for (int i = 0; i < m; i++) {
        uint64_t c = 0;
        for (int j = 0; j < nd; j++) { uint64_t v = (uint64_t)d[j] * 2 + c; d[j] = v % 1000000000U; c = v / 1000000000U; }
        if (c) d[nd++] = (uint32_t)c;
    }
    d[0] -= 1;   /* 2^m - 1; lowest limb is nonzero (2^m not divisible by 5^9) */
    char *s = malloc(nd * 9 + 2);
    int pos = 0;
    pos += sprintf(s + pos, "%u", d[nd - 1]);
    for (int j = nd - 2; j >= 0; j--) pos += sprintf(s + pos, "%09u", d[j]);
    return s;
}
/* parse plain MSB-first hex into FW words (LE). Returns 1 on success. */
static int parse_hex_msb(const char *s, uint64_t *out) {
    memset(out, 0, FW * sizeof(uint64_t));
    int len = strlen(s);
    if (len == 0 || len > 64) return 0;
    int bit = 0;
    for (int i = len - 1; i >= 0; i--) {
        char c = s[i];
        int v = isdigit((unsigned char)c) ? c - '0' : (tolower((unsigned char)c) - 'a' + 10);
        if (v < 0 || v > 15) return 0;
        out[bit / 64] |= (uint64_t)v << (bit % 64);
        bit += 4;
    }
    return 1;
}

/* ---------- factors file ---------- */
static int load_factors(const char *path, int m, uint64_t *primes, int *complete_out) {
    FILE *f = fopen(path, "r");
    if (!f) return -1;
    char line[8192];
    int found = -1;
    while (fgets(line, sizeof(line), f)) {
        int mm, comp, np;
        if (sscanf(line, "%d %d %d", &mm, &comp, &np) != 3) continue;
        if (mm != m) continue;
        char *p = line;
        for (int k = 0; k < 3; k++) { while (*p && !isspace((unsigned char)*p)) p++; while (*p && isspace((unsigned char)*p)) p++; }
        int ok = 1;
        for (int i = 0; i < np; i++) {
            char tok[128]; int ti = 0;
            while (*p && !isspace((unsigned char)*p) && ti < 120) tok[ti++] = *p++;
            tok[ti] = 0;
            while (*p && isspace((unsigned char)*p)) p++;
            if (!parse_hex_msb(tok, primes + (size_t)i * FW)) ok = 0;
        }
        *complete_out = comp;
        found = ok ? np : -2;
        break;
    }
    fclose(f);
    return found;
}

/* RS baseline: m_RS = smallest k with 2^k - 1 >= floor((2^m-1)/8) */
static int rs_m(int m) {
    uint64_t L[FW] = {0};
    for (int i = 0; i < m - 3; i++) L[i / 64] |= 1ULL << (i % 64);
    for (int k = 1; k <= m; k++) {
        uint64_t two_k_1[FW] = {0};
        for (int i = 0; i < k; i++) two_k_1[i / 64] |= 1ULL << (i % 64);
        if (bi_cmp(two_k_1, L, FW) >= 0) return k;
    }
    return m;
}

/* ---------- expected verification data ---------- */
static const char *exp18[6] = {
    "cff004",
    "1108139d1b",
    "9178324736002dfdc101",
    "41b8cf7fa2c8b959848b3fb06b3cb7d2475f01",
    "7da99ef844c1cc28a86c18a00e35ab8cbf387d421822bf1c17a4c67979accd5991cec2bd01",
    "bd1153c48f5ea88e8fd79d3fa0512406e2ef28951add2d3f7f7f329afdca7a842014e54ed7a55b184d5046f712fa89429bad6edba543c059bee559586eaccbc7ee10312480bad4b301"
};
static const char *exp21[6] = {
    "8f8230",
    "0d26009cac04",
    "379583a084558d8cb1321c",
    "a3fb5c65ecde67c431aac86b7676e39ad028bab98301",
    "23a37fd36b4b284b0ee76ba573c3a811f25942e884cddc17d6f45ee21f44a0740c3c9275d3d42b91e41a01",
    "6579dff16c87ad50e1dfa2f92a12d85a46ed565df57d79f7f2897478fd74a9c1f8ed7e310dabcf80526e4639b056c70ad08e80af12bd846a7f8e8681869e86341dd7589c4e18965f8a4f57878d49791e112552ba01"
};
static const int tvals[6] = {1, 2, 4, 8, 16, 32};

static int verify_one(int m, const char *prim_hex, const char **exp) {
    fe P;
    memset(P, 0, sizeof(fe));
    parse_hex_lsb(prim_hex, P, FW);
    int allok = 1;
    for (int i = 0; i < 6; i++) {
        bw g; int ncos;
        double t0 = now_s();
        int r = narrow_g(m, tvals[i], P, g, &ncos);
        double dt = now_s() - t0;
        char *hex = to_hex_lsb(g, r + 1);
        int ok = strcmp(hex, exp[i]) == 0;
        int rok = (r == tvals[i] * m);
        printf("m=%d t=%2d r=%4d (expect %4d) ncos=%d hex_match=%s %s  %.3fs\n",
               m, tvals[i], r, tvals[i] * m, ncos, ok ? "YES" : "NO",
               rok ? "" : "R-MISMATCH", dt);
        if (!ok) { printf("  got: %s\n  exp: %s\n", hex, exp[i]); allok = 0; }
        if (!rok) allok = 0;
        free(hex);
    }
    return allok;
}

int main(int argc, char **argv) {
    if (argc >= 2 && strcmp(argv[1], "verify") == 0) {
        printf("== m=18 (P = t=1 poly cff004) ==\n");
        int ok18 = verify_one(18, exp18[0], exp18);
        printf("== m=21 (P = t=1 poly 8f8230) ==\n");
        int ok21 = verify_one(21, exp21[0], exp21);
        printf("VERIFY m=18: %s   m=21: %s\n", ok18 ? "PASS" : "FAIL", ok21 ? "PASS" : "FAIL");
        return (ok18 && ok21) ? 0 : 1;
    }
    if (argc >= 2 && strcmp(argv[1], "checkprim") == 0) {
        if (argc < 5) { fprintf(stderr, "usage: checkprim m prim_hex factors\n"); return 2; }
        int m = atoi(argv[2]);
        fe P;
        memset(P, 0, sizeof(fe));
        parse_hex_lsb(argv[3], P, FW);
        uint64_t primes[MAXPRIMES * FW];
        int complete = 0;
        int nprimes = load_factors(argv[4], m, primes, &complete);
        if (nprimes < 0) { fprintf(stderr, "no factors for m=%d\n", m); return 1; }
        double t0 = now_s();
        int ok = is_primitive(P, m, primes, nprimes);
        printf("m=%d prim=%s %s (complete=%d, %.2fs)\n",
               m, argv[3], ok ? "PRIMITIVE" : "NOT-PRIMITIVE", complete, now_s() - t0);
        return ok ? 0 : 1;
    }
    if (argc >= 2 && strcmp(argv[1], "single") == 0) {
        if (argc < 4) { fprintf(stderr, "usage: single m t [prim_hex] [factors]\n"); return 2; }
        int m = atoi(argv[2]), t = atoi(argv[3]);
        fe P;
        memset(P, 0, sizeof(fe));
        int have_prim = 0;
        const char *fpath = "factors.txt";
        if (argc >= 5) {
            /* argv[4]: a hex string -> primitive poly; an existing file -> factors */
            FILE *probe = fopen(argv[4], "r");
            if (probe) { fclose(probe); fpath = argv[4]; }
            else { parse_hex_lsb(argv[4], P, FW); have_prim = 1; }
        }
        if (argc >= 6) fpath = argv[5];
        uint64_t primes[MAXPRIMES * FW];
        int nprimes = 0, complete = 0;
        if (!have_prim) {
            nprimes = load_factors(fpath, m, primes, &complete);
            if (nprimes < 0) { fprintf(stderr, "no factors for m=%d in %s\n", m, fpath); return 1; }
            long tries; double t0 = now_s();
            if (!find_primitive(m, primes, nprimes, P, &tries)) {
                fprintf(stderr, "no primitive poly found for m=%d\n", m); return 1;
            }
            fprintf(stderr, "m=%d primitive found in %.2fs (%ld tries, complete=%d)\n",
                    m, now_s() - t0, tries, complete);
        }
        bw g; int ncos;
        double t0 = now_s();
        int r = narrow_g(m, t, P, g, &ncos);
        double dt = now_s() - t0;
        char *hex = to_hex_lsb(g, r + 1);
        char *phex = to_hex_lsb(P, m + 1);
        printf("m=%d t=%d r=%d ncos=%d hex=%s prim=%s %.3fs\n", m, t, r, ncos, hex, phex, dt);
        free(hex); free(phex);
        return 0;
    }
    if (argc >= 2 && strcmp(argv[1], "sweep") == 0) {
        if (argc < 6) { fprintf(stderr, "usage: sweep lo hi factors_file csv_out\n"); return 2; }
        int lo = atoi(argv[2]), hi = atoi(argv[3]);
        const char *fpath = argv[4], *csv = argv[5];
        FILE *out = fopen(csv, "w");
        if (!out) { perror("csv"); return 1; }
        fprintf(out, "m,N,t,r_bits,rs_parity_bits,saving_bits,saving_pct,hex,primitive_poly_hex,time_s\n");
        double t_all = now_s();
        for (int m = lo; m <= hi; m++) {
            uint64_t primes[MAXPRIMES * FW];
            int nprimes = 0, complete = 0;
            nprimes = load_factors(fpath, m, primes, &complete);
            if (nprimes < 0) {
                fprintf(stderr, "m=%d: NO FACTORS -- skipping (record as missing)\n", m);
                continue;
            }
            fe P; long tries = 0;
            double tp0 = now_s();
            int found = find_primitive(m, primes, nprimes, P, &tries);
            double tp = now_s() - tp0;
            if (!found) {
                fprintf(stderr, "m=%d: NO PRIMITIVE FOUND (%ld tries) -- skipping\n", m, tries);
                continue;
            }
            char *phex = to_hex_lsb(P, m + 1);
            char *Ndec = dec_Nminus1(m);
            int mrs = rs_m(m);
            for (int i = 0; i < 6; i++) {
                int t = tvals[i];
                bw g; int ncos;
                double t0 = now_s();
                int r = narrow_g(m, t, P, g, &ncos);
                double dt = now_s() - t0;
                int rs_par = 2 * t * mrs;
                int saving = rs_par - r;
                double pct = 100.0 * saving / rs_par;
                char *hex = to_hex_lsb(g, r + 1);
                fprintf(out, "%d,%s,%d,%d,%d,%d,%.4f,%s,%s,%.3f\n",
                        m, Ndec, t, r, rs_par, saving, pct, hex, phex, dt);
                fflush(out);
                free(hex);
                if (r != t * m)
                    fprintf(stderr, "m=%d t=%d: WARNING r=%d != t*m=%d (ncos=%d)\n",
                            m, t, r, t * m, ncos);
            }
            fprintf(stderr, "m=%d done prim=%.2fs tries=%ld complete=%d %s (elapsed %.1fs)\n",
                    m, tp, tries, complete, complete ? "" : "PROBABLE-PRIMITIVE",
                    now_s() - t_all);
            free(phex); free(Ndec);
        }
        fclose(out);
        fprintf(stderr, "SWEEP DONE lo=%d hi=%d total %.1fs -> %s\n", lo, hi, now_s() - t_all, csv);
        return 0;
    }
    fprintf(stderr, "usage: %s {verify|single m t [prim_hex] [factors]|sweep lo hi factors csv}\n", argv[0]);
    return 2;
}

Run it yourself: ./rssearch --crawl --lmin 8 --lmax 16384 --threads 4 --dir /opt/rssearch --resume. It will take about five minutes and reproduce the original crawl's numbers. To reproduce the extension, build the modified program (dynamic coset cache, 64-bit indices — the version in the source section below) and run one band at a time: ./rssearch --crawl --lmin 16385 --lmax 65536 --mmax 20 --threads 4 --dir /opt/rssearch19 (14 min), ./rssearch --crawl --lmin 131072 --lmax 262143 --mmax 21 --threads 4 --dir /opt/rssearch21 (51 min), ./rssearch --crawl --lmin 262144 --lmax 524287 --mmax 22 --threads 4 --dir /opt/rssearch22 (3 h). For the direct construction to m = 256, build gen_bch.c and run ./gen_bch sweep (about 30 minutes).