checksmix 0.3.10

A simplified MMIX simulator - Donald Knuth's hypothetical computer for teaching and learning assembly language programming.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
use std::any::Any;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write, stderr, stdout};
use std::time::SystemTime;

use tracing::{debug, instrument, trace};

/// Macro for register-register binary operations
macro_rules! binop_rr {
    ($cpu:expr, $x:expr, $y:expr, $z:expr, $f:expr) => {{
        let a = $cpu.get_register($y);
        let b = $cpu.get_register($z);
        $cpu.set_register($x, $f(a, b));
        $cpu.advance_pc();
        true
    }};
}

/// Macro for register-immediate binary operations
macro_rules! binop_ri {
    ($cpu:expr, $x:expr, $y:expr, $z:expr, $f:expr) => {{
        let a = $cpu.get_register($y);
        let b = $z as u64;
        $cpu.set_register($x, $f(a, b));
        $cpu.advance_pc();
        true
    }};
}

/// Macro for comparison operations (register-register)
macro_rules! cmp_rr {
    ($cpu:expr, $x:expr, $y:expr, $z:expr, $conv:expr) => {{
        let a = $conv($cpu.get_register($y));
        let b = $conv($cpu.get_register($z));
        let result = if a < b {
            (-1i64) as u64
        } else if a == b {
            0
        } else {
            1
        };
        $cpu.set_register($x, result);
        $cpu.advance_pc();
        true
    }};
}

/// Macro for comparison operations (register-immediate)
macro_rules! cmp_ri {
    ($cpu:expr, $x:expr, $y:expr, $z:expr, $conv_y:expr, $conv_z:expr) => {{
        let a = $conv_y($cpu.get_register($y));
        let b = $conv_z($z);
        let result = if a < b {
            (-1i64) as u64
        } else if a == b {
            0
        } else {
            1
        };
        $cpu.set_register($x, result);
        $cpu.advance_pc();
        true
    }};
}

/// Macro for multiply-add operations: $X = $Y * N + $Z (register-register)
macro_rules! muladd_rr {
    ($cpu:expr, $x:expr, $y:expr, $z:expr, $n:expr) => {{
        let sum = $cpu
            .get_register($y)
            .wrapping_mul($n)
            .wrapping_add($cpu.get_register($z));
        $cpu.set_register($x, sum);
        $cpu.advance_pc();
        true
    }};
}

/// Macro for multiply-add operations: $X = $Y * N + Z (register-immediate)
macro_rules! muladd_ri {
    ($cpu:expr, $x:expr, $y:expr, $z:expr, $n:expr) => {{
        let sum = $cpu
            .get_register($y)
            .wrapping_mul($n)
            .wrapping_add($z as u64);
        $cpu.set_register($x, sum);
        $cpu.advance_pc();
        true
    }};
}

/// Macro for int-to-float conversions (register). `$signed` reinterprets `$Z`
/// as `i64`. `$mnem` names the instruction in the `Y > 4` diagnostic.
macro_rules! i2f_conv_rr {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr, $signed:expr, $mnem:expr) => {{
        let mode = match $cpu.resolved_round_mode($y) {
            Ok(m) => m,
            Err(()) => return $cpu.illegal_round_mode($mnem, $y),
        };
        // Y is the rounding-mode field, not a register operand.
        let y_val = $y as u64;
        let z_val = $cpu.get_register($z);
        let negative = $signed && (z_val as i64) < 0;
        let magnitude = if negative {
            (z_val as i64).unsigned_abs()
        } else {
            z_val
        };
        let (result, flags) = $cpu.int_to_f64_rounded(negative, magnitude, mode);
        $cpu.set_register($x, MMix::f64_to_u64(result));
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for int-to-float conversions (immediate). Every 8-bit operand
/// converts exactly, so the rounding mode can never change the result — `Y`
/// is still checked, since `Y > 4` halts regardless.
macro_rules! i2f_conv_ri {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr, $signed:expr, $mnem:expr) => {{
        let mode = match $cpu.resolved_round_mode($y) {
            Ok(m) => m,
            Err(()) => return $cpu.illegal_round_mode($mnem, $y),
        };
        // Y is the rounding-mode field and Z the literal operand, neither a
        // register.
        let y_val = $y as u64;
        let z_val = $z as u64;
        // Z is 8-bit immediate value to convert
        let v = if $signed {
            ($z as i8) as i64
        } else {
            $z as i64
        };
        let (result, flags) = $cpu.int_to_f64_rounded(v < 0, v.unsigned_abs(), mode);
        $cpu.set_register($x, MMix::f64_to_u64(result));
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for floating point comparison/test operations
macro_rules! fcmp_rr {
    ($cpu:expr, $x:expr, $y:expr, $z:expr, $test:expr) => {{
        let y_val = MMix::u64_to_f64($cpu.get_register($y));
        let z_val = MMix::u64_to_f64($cpu.get_register($z));
        let result = $test(y_val, z_val);
        $cpu.set_register($x, result);
        $cpu.advance_pc();
        true
    }};
}

/// Macro for signed multiplication with overflow detection (register-register)
macro_rules! mul_rr {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        let z_val = $cpu.get_register($z);
        let a = y_val as i64;
        let b = z_val as i64;
        let product = (a as i128) * (b as i128);
        $cpu.set_register($x, product as u64);
        let sign_ext = if (product as u64) as i64 >= 0 {
            0i64
        } else {
            -1i64
        };
        let flags = if (product >> 64) as i64 != sign_ext {
            RA_V
        } else {
            0
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for signed multiplication with overflow detection (register-immediate)
macro_rules! mul_ri {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        // Z is the literal operand, not a register.
        let z_val = $z as u64;
        let a = y_val as i64;
        let b = $z as i64;
        let product = (a as i128) * (b as i128);
        $cpu.set_register($x, product as u64);
        let sign_ext = if (product as u64) as i64 >= 0 {
            0i64
        } else {
            -1i64
        };
        let flags = if (product >> 64) as i64 != sign_ext {
            RA_V
        } else {
            0
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for unsigned multiplication (register-register)
macro_rules! mulu_rr {
    ($cpu:expr, $x:expr, $y:expr, $z:expr) => {{
        let a = $cpu.get_register($y) as u128;
        let b = $cpu.get_register($z) as u128;
        let product = a * b;
        $cpu.set_register($x, product as u64);
        $cpu.set_special(SpecialReg::RH, (product >> 64) as u64);
        $cpu.advance_pc();
        true
    }};
}

/// Macro for unsigned multiplication (register-immediate)
macro_rules! mulu_ri {
    ($cpu:expr, $x:expr, $y:expr, $z:expr) => {{
        let a = $cpu.get_register($y) as u128;
        let b = $z as u128;
        let product = a * b;
        $cpu.set_register($x, product as u64);
        $cpu.set_special(SpecialReg::RH, (product >> 64) as u64);
        $cpu.advance_pc();
        true
    }};
}

/// Macro for signed division (register-register)
macro_rules! div_rr {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        let z_val = $cpu.get_register($z);
        let dividend = y_val as i64;
        let divisor = z_val as i64;
        let flags = if divisor == 0 {
            $cpu.set_register($x, 0);
            $cpu.set_special(SpecialReg::RR, y_val);
            RA_D
        } else if dividend == i64::MIN && divisor == -1 {
            // The only quotient outside the signed range; it wraps to itself.
            $cpu.set_register($x, i64::MIN as u64);
            $cpu.set_special(SpecialReg::RR, 0);
            RA_V
        } else {
            // MMIX floors the quotient, so the remainder takes the divisor's
            // sign; Rust truncates toward zero.
            let mut quotient = dividend / divisor;
            let mut remainder = dividend % divisor;
            if remainder != 0 && (remainder < 0) != (divisor < 0) {
                quotient -= 1;
                remainder += divisor;
            }
            $cpu.set_register($x, quotient as u64);
            $cpu.set_special(SpecialReg::RR, remainder as u64);
            0
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for signed division (register-immediate)
macro_rules! div_ri {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        // Z is the literal operand, not a register.
        let z_val = $z as u64;
        let dividend = y_val as i64;
        let divisor = $z as i64;
        let flags = if divisor == 0 {
            $cpu.set_register($x, 0);
            $cpu.set_special(SpecialReg::RR, y_val);
            RA_D
        } else if dividend == i64::MIN && divisor == -1 {
            // Z is a byte, so the divisor is in `0..=255` and this arm is
            // unreachable from the immediate encoding. It mirrors div_rr,
            // where the quotient leaves the signed range and wraps to itself.
            $cpu.set_register($x, i64::MIN as u64);
            $cpu.set_special(SpecialReg::RR, 0);
            RA_V
        } else {
            // MMIX floors the quotient, so the remainder takes the divisor's
            // sign; Rust truncates toward zero.
            let mut quotient = dividend / divisor;
            let mut remainder = dividend % divisor;
            if remainder != 0 && (remainder < 0) != (divisor < 0) {
                quotient -= 1;
                remainder += divisor;
            }
            $cpu.set_register($x, quotient as u64);
            $cpu.set_special(SpecialReg::RR, remainder as u64);
            0
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for unsigned division (register-register)
macro_rules! divu_rr {
    ($cpu:expr, $x:expr, $y:expr, $z:expr) => {{
        let dividend_low = $cpu.get_register($y);
        let dividend_high = $cpu.get_special(SpecialReg::RD);
        let dividend = ((dividend_high as u128) << 64) | (dividend_low as u128);
        let divisor = $cpu.get_register($z) as u128;
        // The quotient is defined only when u($Z) > u(rD); otherwise it would
        // not fit an octabyte. Divide by zero is that case, and is not an
        // event: rD is a definition, not a divide check.
        if divisor <= dividend_high as u128 {
            $cpu.set_register($x, dividend_high);
            $cpu.set_special(SpecialReg::RR, dividend_low);
        } else {
            let quotient = dividend / divisor;
            let remainder = dividend % divisor;
            $cpu.set_register($x, quotient as u64);
            $cpu.set_special(SpecialReg::RR, remainder as u64);
        }
        $cpu.advance_pc();
        true
    }};
}

/// Macro for unsigned division (register-immediate)
macro_rules! divu_ri {
    ($cpu:expr, $x:expr, $y:expr, $z:expr) => {{
        let dividend_low = $cpu.get_register($y);
        let dividend_high = $cpu.get_special(SpecialReg::RD);
        let dividend = ((dividend_high as u128) << 64) | (dividend_low as u128);
        let divisor = $z as u128;
        // The quotient is defined only when u($Z) > u(rD); otherwise it would
        // not fit an octabyte. Divide by zero is that case, and is not an
        // event: rD is a definition, not a divide check.
        if divisor <= dividend_high as u128 {
            $cpu.set_register($x, dividend_high);
            $cpu.set_special(SpecialReg::RR, dividend_low);
        } else {
            let quotient = dividend / divisor;
            let remainder = dividend % divisor;
            $cpu.set_register($x, quotient as u64);
            $cpu.set_special(SpecialReg::RR, remainder as u64);
        }
        $cpu.advance_pc();
        true
    }};
}

/// Macro for signed addition with overflow detection (register-register)
macro_rules! add_rr {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        let z_val = $cpu.get_register($z);
        let a = y_val as i64;
        let b = z_val as i64;
        let flags = match a.checked_add(b) {
            Some(result) => {
                $cpu.set_register($x, result as u64);
                0
            }
            None => {
                $cpu.set_register($x, a.wrapping_add(b) as u64);
                RA_V
            }
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for signed addition with overflow detection (register-immediate)
macro_rules! add_ri {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        // Z is the literal operand, not a register.
        let z_val = $z as u64;
        let a = y_val as i64;
        let b = $z as i64;
        let flags = match a.checked_add(b) {
            Some(result) => {
                $cpu.set_register($x, result as u64);
                0
            }
            None => {
                $cpu.set_register($x, a.wrapping_add(b) as u64);
                RA_V
            }
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for signed subtraction with overflow detection (register-register)
macro_rules! sub_rr {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        let z_val = $cpu.get_register($z);
        let a = y_val as i64;
        let b = z_val as i64;
        let flags = match a.checked_sub(b) {
            Some(result) => {
                $cpu.set_register($x, result as u64);
                0
            }
            None => {
                $cpu.set_register($x, a.wrapping_sub(b) as u64);
                RA_V
            }
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// Macro for signed subtraction with overflow detection (register-immediate)
macro_rules! sub_ri {
    ($cpu:expr, $op:expr, $x:expr, $y:expr, $z:expr) => {{
        let y_val = $cpu.get_register($y);
        // Z is the literal operand, not a register.
        let z_val = $z as u64;
        let a = y_val as i64;
        let b = $z as i64;
        let flags = match a.checked_sub(b) {
            Some(result) => {
                $cpu.set_register($x, result as u64);
                0
            }
            None => {
                $cpu.set_register($x, a.wrapping_sub(b) as u64);
                RA_V
            }
        };
        return $cpu.raise_exceptions(flags, $op, $x, $y, $z, y_val, z_val);
    }};
}

/// rA event-flag bits, matching the predefined symbols `D_BIT` through
/// `X_BIT`. Layout (low → high): X Z U O I W V D.
///
/// `V` and `D` are the integer events; the other six are floating-point.
/// MMIX has no denormalized-operand event — a subnormal operand raises
/// nothing, and `D` means divide check.
pub const RA_X: u64 = 0x01; // floating inexact
pub const RA_Z: u64 = 0x02; // floating divide by zero
pub const RA_U: u64 = 0x04; // floating underflow
pub const RA_O: u64 = 0x08; // floating overflow
pub const RA_I: u64 = 0x10; // floating invalid operation
pub const RA_W: u64 = 0x20; // float-to-fix overflow
pub const RA_V: u64 = 0x40; // integer overflow
pub const RA_D: u64 = 0x80; // integer divide check

/// Bit position of rA's two-bit rounding-mode field, the top of the register.
pub const RA_ROUND_SHIFT: u32 = 16;

/// Widest value `PUT` may write to rA: the register holds 18 bits.
pub const RA_MAX: u64 = 0x3FFFF;

/// TRAP code identifiers for MMIX.
/// These codes are used in TRAP instructions to invoke system calls.
/// The TRAP instruction format is: TRAP X, Y, Z where:
/// - X is unused (typically 0)
/// - Y is the trap code
/// - Z is an argument (varies by trap code)
///
/// More trap codes may be added in future releases, so downstream matches
/// must carry a wildcard arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum TrapCode {
    Halt = 0,    // Stop execution
    Trip = 1,    // Cause a trip (not implemented)
    Fopen = 2,   // Open file
    Fclose = 3,  // Close file
    Fread = 4,   // Read from file
    Fgets = 5,   // Read line from file
    Fgetws = 6,  // Read wide string from file
    Fwrite = 7,  // Write to file
    Fputs = 8,   // Write null-terminated string
    Fputc = 9,   // Write character
    Fputws = 10, // Write wide string
    Fseek = 11,  // Seek in file
    Ftell = 12,  // Get file position
    Time = 13,   // current time in microseconds since Unix epoch
}

impl TrapCode {
    /// Convert a u8 to a TrapCode variant
    pub fn from_u8(n: u8) -> Option<Self> {
        match n {
            0 => Some(TrapCode::Halt),
            1 => Some(TrapCode::Trip),
            2 => Some(TrapCode::Fopen),
            3 => Some(TrapCode::Fclose),
            4 => Some(TrapCode::Fread),
            5 => Some(TrapCode::Fgets),
            6 => Some(TrapCode::Fgetws),
            7 => Some(TrapCode::Fwrite),
            8 => Some(TrapCode::Fputs),
            9 => Some(TrapCode::Fputc),
            10 => Some(TrapCode::Fputws),
            11 => Some(TrapCode::Fseek),
            12 => Some(TrapCode::Ftell),
            13 => Some(TrapCode::Time),
            _ => None,
        }
    }
}

/// Special register identifiers for MMIX.
/// These 32 special registers control various aspects of MMIX operation.
/// Per TAOCP specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum SpecialReg {
    RB = 0,   // rB - Bootstrap register
    RD = 1,   // rD - Dividend register
    RE = 2,   // rE - Epsilon register
    RH = 3,   // rH - Himult register
    RJ = 4,   // rJ - Return-jump register
    RM = 5,   // rM - Multiplex mask register
    RR = 6,   // rR - Remainder register
    RBB = 7,  // rBB - Bootstrap register (kernel)
    RC = 8,   // rC - Continuation register
    RN = 9,   // rN - Serial number
    RO = 10,  // rO - Register stack offset
    RS = 11,  // rS - Register stack pointer
    RI = 12,  // rI - Interval counter
    RT = 13,  // rT - Trap address register
    RTT = 14, // rTT - Dynamic trap address register
    RK = 15,  // rK - Interrupt mask register
    RQ = 16,  // rQ - Interrupt request register
    RU = 17,  // rU - Usage counter
    RV = 18,  // rV - Virtual translation register
    RG = 19,  // rG - Global threshold register
    RL = 20,  // rL - Local threshold register
    RA = 21,  // rA - Arithmetic status register
    RF = 22,  // rF - Failure location register
    RP = 23,  // rP - Prediction register
    RW = 24,  // rW - Where-interrupted register (user)
    RX = 25,  // rX - Execution register (user)
    RY = 26,  // rY - Y operand (user)
    RZ = 27,  // rZ - Z operand (user)
    RWW = 28, // rWW - Where-interrupted register (kernel)
    RXX = 29, // rXX - Execution register (kernel)
    RYY = 30, // rYY - Y operand (kernel)
    RZZ = 31, // rZZ - Z operand (kernel)
}

impl SpecialReg {
    /// The MMIXAL spelling of this register, as the assembler predefines it,
    /// the debugger resolves it and the state dump labels it.
    pub fn name(self) -> &'static str {
        match self {
            SpecialReg::RB => "rB",
            SpecialReg::RD => "rD",
            SpecialReg::RE => "rE",
            SpecialReg::RH => "rH",
            SpecialReg::RJ => "rJ",
            SpecialReg::RM => "rM",
            SpecialReg::RR => "rR",
            SpecialReg::RBB => "rBB",
            SpecialReg::RC => "rC",
            SpecialReg::RN => "rN",
            SpecialReg::RO => "rO",
            SpecialReg::RS => "rS",
            SpecialReg::RI => "rI",
            SpecialReg::RT => "rT",
            SpecialReg::RTT => "rTT",
            SpecialReg::RK => "rK",
            SpecialReg::RQ => "rQ",
            SpecialReg::RU => "rU",
            SpecialReg::RV => "rV",
            SpecialReg::RG => "rG",
            SpecialReg::RL => "rL",
            SpecialReg::RA => "rA",
            SpecialReg::RF => "rF",
            SpecialReg::RP => "rP",
            SpecialReg::RW => "rW",
            SpecialReg::RX => "rX",
            SpecialReg::RY => "rY",
            SpecialReg::RZ => "rZ",
            SpecialReg::RWW => "rWW",
            SpecialReg::RXX => "rXX",
            SpecialReg::RYY => "rYY",
            SpecialReg::RZZ => "rZZ",
        }
    }

    /// Convert a u8 register number to a SpecialReg variant
    pub fn from_u8(n: u8) -> Option<Self> {
        match n {
            0 => Some(SpecialReg::RB),
            1 => Some(SpecialReg::RD),
            2 => Some(SpecialReg::RE),
            3 => Some(SpecialReg::RH),
            4 => Some(SpecialReg::RJ),
            5 => Some(SpecialReg::RM),
            6 => Some(SpecialReg::RR),
            7 => Some(SpecialReg::RBB),
            8 => Some(SpecialReg::RC),
            9 => Some(SpecialReg::RN),
            10 => Some(SpecialReg::RO),
            11 => Some(SpecialReg::RS),
            12 => Some(SpecialReg::RI),
            13 => Some(SpecialReg::RT),
            14 => Some(SpecialReg::RTT),
            15 => Some(SpecialReg::RK),
            16 => Some(SpecialReg::RQ),
            17 => Some(SpecialReg::RU),
            18 => Some(SpecialReg::RV),
            19 => Some(SpecialReg::RG),
            20 => Some(SpecialReg::RL),
            21 => Some(SpecialReg::RA),
            22 => Some(SpecialReg::RF),
            23 => Some(SpecialReg::RP),
            24 => Some(SpecialReg::RW),
            25 => Some(SpecialReg::RX),
            26 => Some(SpecialReg::RY),
            27 => Some(SpecialReg::RZ),
            28 => Some(SpecialReg::RWW),
            29 => Some(SpecialReg::RXX),
            30 => Some(SpecialReg::RYY),
            31 => Some(SpecialReg::RZZ),
            _ => None,
        }
    }
}

/// The special registers `SAVE` writes to the register stack and `UNSAVE`
/// reads back, in the order the SAVE page's diagram lays them out.
const SAVE_SPECIALS: [SpecialReg; 12] = [
    SpecialReg::RB,
    SpecialReg::RD,
    SpecialReg::RE,
    SpecialReg::RH,
    SpecialReg::RJ,
    SpecialReg::RM,
    SpecialReg::RR,
    SpecialReg::RP,
    SpecialReg::RW,
    SpecialReg::RX,
    SpecialReg::RY,
    SpecialReg::RZ,
];

/// Base of the register stack: `rO`/`rS` start here, and
/// [`MMix::call_depth`]'s walk stops here. `src/mmixal.rs` seeds the
/// `Stack_Segment` predefined symbol from this same constant.
pub(crate) const STACK_SEGMENT_START: u64 = 0x6000000000000000;

/// What [`MMix::pop_frame`] found at `rO`.
enum PopFrame {
    /// A frame popped cleanly; the branch target follows.
    Frame(u64),
    /// `rO` was at or below the stack base — `POP`'s fallback.
    NoFrame,
    /// `rO` named an impossible placement; already rejected with a
    /// diagnostic and the machine left unchanged.
    Rejected,
}

/// Addresses below a saved context's packed octa, in the layout
/// [`MMix::save_context`] wrote: the twelve specials, the `rg_saved`
/// globals, the marker holding the saved local count, and the locals below
/// it.
struct SaveContextLayout {
    specials_base: u64,
    globals_base: u64,
    global_count: u64,
    local_count: u64,
    locals_base: u64,
}

/// Routes every process-level effect an `MMix` produces: writes to fd 1/2,
/// the wall clock, and diagnostic messages that today go to stderr.
///
/// `MMix::new()` installs `StdHost`, reproducing today's process behavior
/// exactly. `MMix::with_host` accepts any `Host`, which is how an embedder
/// (a wasm host with no stdout, a test harness that wants to inspect bytes
/// rather than print them) captures what the machine emits instead of
/// losing it to the process.
///
/// File-descriptor traps (`Fopen`/`Fclose`/`Fread`/`Fgets`/`Fgetws`/
/// `Fwrite`/`Fseek`/`Ftell`, and fd 3+ of `Fputs`/`Fputc`/`Fputws`) do not go
/// through the host — they keep using `std::fs` directly and fail naturally
/// on platforms without a filesystem.
///
/// `flush` and `trap` have no-op defaults, so an embedder implements only
/// what it needs. The trait is object-safe — `MMix` stores it as
/// `Box<dyn Host>` — and any method added in a future release will carry a
/// default, so implementors do not break.
///
/// `MMix::with_host` consumes the host and offers no way to get it back. A
/// host that wants its caller to read what it captured owns its buffers
/// behind a shared handle — `Rc<RefCell<Vec<u8>>>` or similar — cloned
/// *before* the host is moved in, so the caller keeps one clone and the
/// `MMix` owns the other.
///
/// Because `MMix` stores the host as `Box<dyn Host>`, it is none of `Send`,
/// `Sync`, `UnwindSafe`, or `RefUnwindSafe`. The intended embedders are
/// single-threaded — a browser playground, a test harness — and capture into
/// `Rc<RefCell<_>>`; see the [`MMix`] docs.
///
/// ```
/// use checksmix::{Host, MMix, TrapCode};
/// use std::cell::RefCell;
/// use std::rc::Rc;
///
/// struct Capture(Rc<RefCell<Vec<u8>>>);
///
/// impl Host for Capture {
///     fn write(&mut self, _fd: u8, bytes: &[u8]) -> std::io::Result<()> {
///         self.0.borrow_mut().extend_from_slice(bytes);
///         Ok(())
///     }
///     fn now_micros(&mut self) -> u64 { 0 }
///     fn diagnostic(&mut self, _msg: &str) {}
///     fn trap(&mut self, code: TrapCode, _arg: u8, _before: u64, _after: u64) {
///         // TrapCode is #[non_exhaustive]: a wildcard arm is required
///         match code {
///             TrapCode::Fputc => {}
///             _ => {}
///         }
///     }
/// }
///
/// // Keep one clone of the buffer; the machine owns the other.
/// let out = Rc::new(RefCell::new(Vec::new()));
/// let mut mmix = MMix::with_host(Capture(out.clone()));
///
/// mmix.set_register(255, u64::from(b'X'));
/// mmix.write_tetra(0, 0x00000901); // TRAP 0, Fputc (9), fd 1
/// mmix.execute_instruction();
///
/// assert_eq!(&*out.borrow(), b"X");
/// ```
pub trait Host: Any {
    /// Write raw bytes to file descriptor `fd` (only 1 or 2 reach the
    /// host — see the trait docs). Returns `Ok(())` on success, matching
    /// `write_all` rather than reporting a partial-write count. On success
    /// `Fputs` and `Fputws` store `bytes.len()` in `$255`; `Fputc` stores 0.
    fn write(&mut self, fd: u8, bytes: &[u8]) -> std::io::Result<()>;

    /// Flush any buffered output. `Halt` is the only event that calls this,
    /// mirroring the process exiting without running destructors — a
    /// program that stops via register-form `TRAP` or the `TRIP`
    /// instruction never reaches it, and `MMix` has no `Drop`. A host must
    /// not rely on `flush` for correctness. No-op by default.
    fn flush(&mut self) {}

    /// The current time in microseconds since the Unix epoch. The only
    /// clock primitive `MMix` needs — `handle_time` derives seconds and
    /// milliseconds from it by division.
    fn now_micros(&mut self) -> u64;

    /// Report an operator-facing diagnostic message (an unhandled trap
    /// code, a truncated string, a HALT/TRIP notice). `StdHost` sends these
    /// to stderr via `eprintln!`.
    fn diagnostic(&mut self, msg: &str);

    /// Observe a trap after `handle_trap`'s dispatch has run, with `$255`
    /// captured both before and after. No-op by default.
    ///
    /// Only recognized trap codes reach this hook. An unhandled code, the
    /// register form of `TRAP` (`X != 0`, which halts the machine), and the
    /// `TRIP` instruction all report through `diagnostic` instead.
    ///
    /// `arg255` and `result255` do not mean the same thing for every trap:
    /// - `Halt` never writes `$255`, so `result255` is simply the exit code
    ///   the program supplied in `$255` before the trap, echoed back.
    /// - `Trip` never writes `$255` either, so `arg255` and `result255` are
    ///   both whatever `$255` happened to hold — before and after are equal.
    /// - `Time` takes its unit in `arg` (the Z operand), not in `$255`, so
    ///   `arg255` is stale on entry and only `result255` reflects the trap.
    /// - `Fputc` and `Fclose` leave a status in `result255` (0 on success,
    ///   `-1` as an unsigned octabyte on failure), not a count or a value.
    ///
    /// An embedder rendering a trap log should read these four cases
    /// before trusting `arg255`/`result255` at face value.
    fn trap(&mut self, code: TrapCode, arg: u8, arg255: u64, result255: u64) {
        let _ = (code, arg, arg255, result255);
    }
}

/// Lets a caller that already holds a boxed host — one selected at runtime
/// from several types, say — pass it to `MMix::with_host` directly.
///
/// There is deliberately no matching impl for `&mut H`. Both `Box` and `&mut`
/// are `#[fundamental]`, so downstream may implement `Host` for either and a
/// blanket impl added later could collide — but `with_host` takes `H: 'static`
/// by value, so a borrowed host is only usable when the borrow is `'static`,
/// which is rare enough not to buy the surface.
impl<H: Host + ?Sized> Host for Box<H> {
    fn write(&mut self, fd: u8, bytes: &[u8]) -> std::io::Result<()> {
        (**self).write(fd, bytes)
    }

    fn flush(&mut self) {
        (**self).flush()
    }

    fn now_micros(&mut self) -> u64 {
        (**self).now_micros()
    }

    fn diagnostic(&mut self, msg: &str) {
        (**self).diagnostic(msg)
    }

    fn trap(&mut self, code: TrapCode, arg: u8, arg255: u64, result255: u64) {
        (**self).trap(code, arg, arg255, result255)
    }
}

/// The `Host` behind `MMix::new()`: reproduces today's process I/O exactly
/// — locked `stdout`/`stderr` writes, `stdout().flush()` on halt,
/// `SystemTime` for the clock, and `eprintln!` for diagnostics.
///
/// `write_bytes_to_fd` only ever calls `Host::write` with fd 1 or 2 (fd 3+
/// stays on `file_handles`), but `StdHost` is a general `Host`
/// implementation, so it treats any other fd as an error rather than
/// assuming that invariant.
pub struct StdHost;

impl Host for StdHost {
    fn write(&mut self, fd: u8, bytes: &[u8]) -> std::io::Result<()> {
        match fd {
            1 => stdout().lock().write_all(bytes),
            2 => stderr().lock().write_all(bytes),
            _ => Err(std::io::Error::other(format!(
                "StdHost: unsupported file descriptor {fd}"
            ))),
        }
    }

    fn flush(&mut self) {
        let _ = stdout().flush();
    }

    fn now_micros(&mut self) -> u64 {
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64
    }

    fn diagnostic(&mut self, msg: &str) {
        eprintln!("{msg}");
    }
}

/// The MMIX computer architecture.
///
/// MMIX has:
/// - 256 general-purpose registers ($0-$255), each holding 64 bits (an octabyte)
/// - 32 special-purpose registers (rA-rZ, rBB, rTT, rWW, rXX, rYY, rZZ)
/// - 2^64 bytes of virtual memory
///
/// Instructions are tetrybytes (4 bytes) with format: OP X Y Z
/// where OP is the opcode and X, Y, Z are operands.
///
/// # Thread safety
///
/// `MMix` owns a [`Host`] as `Box<dyn Host>` and is therefore none of `Send`,
/// `Sync`, `UnwindSafe`, or `RefUnwindSafe` — a change from 0.2.23, where it
/// was all four. This is deliberate: the intended embedders are
/// single-threaded and capture into `Rc<RefCell<_>>`, which a `Send` bound
/// would forbid. Move the program, not the machine — construct an `MMix` on
/// the thread that runs it, and wrap it in `std::panic::AssertUnwindSafe` to
/// put one through `catch_unwind`.
pub struct MMix {
    /// 256 general-purpose registers, each 64 bits
    general_regs: [u64; 256],

    /// 32 special-purpose registers, each 64 bits
    /// Indexed by SpecialReg enum values
    special_regs: [u64; 32],

    /// Virtual memory
    /// this should use paging/segmentation
    /// Key is the memory address, value is the byte
    /// Iteration order is unspecified; [`MMix::occupied`] sorts it.
    memory: HashMap<u64, u8>,

    /// Program counter (location of next instruction)
    pc: u64,

    /// Open file handles for TRAP calls
    /// Maps file descriptor numbers to File objects
    /// 0 = stdin, 1 = stdout, 2 = stderr, 3+ = user-opened files
    file_handles: HashMap<u8, File>,

    /// Counter for allocating new file descriptors
    next_fd: u8,

    /// Exit code from HALT trap (to be returned as process exit code)
    exit_code: u64,

    /// Where process-level effects (writes, the clock, diagnostics, trap
    /// events) go. `MMix::new()` installs `StdHost`; `MMix::with_host`
    /// installs anything else.
    host: Box<dyn Host>,

    /// Whether [`MMix::write_byte`] records the address it touches. Survives
    /// [`MMix::reset`]; see [`MMix::set_journal`].
    journal_enabled: bool,

    /// Addresses [`MMix::write_byte`] has touched since the last
    /// [`MMix::take_journal`], while the journal is enabled.
    journal: HashSet<u64>,

    /// Addresses `write_image` loaded, zero byte or not. Only
    /// [`MMix::write_loaded_byte`] records into this; plain
    /// [`MMix::write_byte`] calls (including everything a running program
    /// does after load) never touch it. Backs [`MMix::loaded_extent`].
    loaded: BTreeSet<u64>,
}

impl Default for MMix {
    fn default() -> Self {
        Self::new()
    }
}

impl MMix {
    /// Create a new MMIX computer with all registers and memory initialized
    /// to zero, and process I/O routed through `StdHost` — today's behavior,
    /// unchanged.
    pub fn new() -> Self {
        Self::with_host(StdHost)
    }

    /// Create a new MMIX computer with all registers and memory initialized
    /// to zero, routing every process-level write, the clock, diagnostics,
    /// and trap events through `host` instead of the process.
    ///
    /// The resulting `MMix` is none of `Send`, `Sync`, `UnwindSafe`, or
    /// `RefUnwindSafe` — see the [`MMix`] docs.
    pub fn with_host<H: Host + 'static>(host: H) -> Self {
        Self::blank(Box::new(host))
    }

    /// A machine in its starting state, owning `host`. The single place every
    /// field is named, so construction and [`MMix::reset`] cannot disagree
    /// about what "fresh" means — adding a field to `MMix` fails to compile
    /// here rather than silently surviving a reset.
    fn blank(host: Box<dyn Host>) -> Self {
        let mut mmix = Self {
            general_regs: [0; 256],
            special_regs: [0; 32],
            memory: HashMap::new(),
            pc: 0,
            file_handles: HashMap::new(),
            next_fd: 3, // 0, 1, 2 are reserved for stdin, stdout, stderr
            exit_code: 0,
            host,
            journal_enabled: false,
            journal: HashSet::new(),
            loaded: BTreeSet::new(),
        };
        mmix.initialize();
        mmix
    }

    /// Return the machine to its freshly-constructed state — every register,
    /// all of memory, the program counter, the call-frame stack, open file
    /// handles, the next descriptor to allocate, and the exit code — while
    /// keeping the installed [`Host`].
    ///
    /// A caller that injected a host to capture output needs this: dropping
    /// the machine and building another would take the host with it, and only
    /// the machine's state is stale between runs. The host's own buffers are
    /// untouched, so a host that accumulates sees successive runs appended;
    /// clear them through your own handle if that is not what you want.
    ///
    /// The journal's enabled flag (see [`MMix::set_journal`]) survives; the
    /// accumulated buffer does not, since a fresh machine has written
    /// nothing yet.
    pub fn reset(&mut self) {
        let host = std::mem::replace(&mut self.host, Box::new(StdHost));
        let journal_enabled = self.journal_enabled;
        *self = Self::blank(host);
        self.journal_enabled = journal_enabled;
    }

    /// The installed [`Host`], for a caller that needs to reach it after
    /// construction rather than keeping a shared handle.
    ///
    /// [`Host`] requires [`Any`], so an embedder can recover its concrete
    /// host type:
    ///
    /// ```
    /// # use checksmix::{Host, MMix};
    /// # use std::any::Any;
    /// # struct Capture(Vec<u8>);
    /// # impl Host for Capture {
    /// #     fn write(&mut self, _fd: u8, b: &[u8]) -> std::io::Result<()> {
    /// #         self.0.extend_from_slice(b); Ok(())
    /// #     }
    /// #     fn now_micros(&mut self) -> u64 { 0 }
    /// #     fn diagnostic(&mut self, _m: &str) {}
    /// # }
    /// let mut mmix = MMix::with_host(Capture(Vec::new()));
    /// let host: &mut dyn Any = mmix.host_mut();
    /// let capture = host.downcast_mut::<Capture>().expect("our own host type");
    /// capture.0.clear();
    /// ```
    pub fn host_mut(&mut self) -> &mut dyn Host {
        &mut *self.host
    }

    /// Consume the machine and return its [`Host`], for a caller that wants
    /// what the host captured once the program is done.
    pub fn into_host(self) -> Box<dyn Host> {
        self.host
    }

    /// The special-register values a machine starts life with.
    fn initialize(&mut self) {
        // Initialize rN (serial number register) to a default value
        // The MMIX specification says this should be a unique machine serial number
        self.set_special(SpecialReg::RN, 2009);
        // Initialize rG (global threshold register) - registers $rG..$255 are global
        // With no GREG declarations, rG=32
        self.set_special(SpecialReg::RG, 32);
        // Initialize rL (local threshold register) - number of local registers in use
        // Start with 0, will be updated by PUSHJ/POP
        self.set_special(SpecialReg::RL, 0);
        // rO and rS both start at the register stack's base, segment 6 per
        // MMIX convention. PUSHJ/POP store eagerly, so the two stay equal
        // and move together for the life of the machine.
        self.set_special(SpecialReg::RO, STACK_SEGMENT_START);
        self.set_special(SpecialReg::RS, STACK_SEGMENT_START);
    }

    /// Get the value of a general-purpose register.
    pub fn get_register(&self, reg: u8) -> u64 {
        self.general_regs[reg as usize]
    }

    /// Set the value of a general-purpose register.
    ///
    /// Writing to a local register $i with i >= rL grows rL to i+1 and zeroes
    /// every register the growth exposes, so a register between the old and
    /// new rL never reads a stale value.
    pub fn set_register(&mut self, reg: u8, value: u64) {
        self.claim_local(reg);
        self.general_regs[reg as usize] = value;
    }

    /// Raise rL to cover `reg` when it names a marginal local register,
    /// zeroing every register from the old rL through `reg`. A no-op when
    /// `reg` is already local or is a global register (`reg >= rG`).
    fn claim_local(&mut self, reg: u8) {
        // UNSAVE restores rL and rG straight from guest memory, so either can
        // name a register the file does not have. Compare at full width: a
        // truncated rL would read as a low register and drop live locals.
        let rg = self.special_regs[SpecialReg::RG as usize];
        if (reg as u64) >= rg {
            return;
        }
        let rl = self.special_regs[SpecialReg::RL as usize];
        if (reg as u64) < rl {
            return;
        }
        let rl = rl as u8;
        for marginal in rl..=reg {
            self.general_regs[marginal as usize] = 0;
        }
        self.special_regs[SpecialReg::RL as usize] = (reg as u64) + 1;
    }

    /// True when `op_byte`'s X field names a general-register destination:
    /// the floating-point and integer arithmetic and compare instructions,
    /// the conditional- and zero-set instructions, the loads, GO, PUSHGO,
    /// the bitwise and SETL-family instructions, PUSHJ, GETA, SAVE and GET.
    /// Branches read a register as a source (not a destination) and are excluded.
    /// Stores, PUT, POP, UNSAVE and the opcodes with no register operand are not.
    fn writes_general_register_x(op_byte: u8) -> bool {
        matches!(
            op_byte,
            0x01..=0x3F | 0x60..=0x99 | 0x9E..=0x9F | 0xBE..=0xEF | 0xF2..=0xF5 | 0xFA | 0xFE
        )
    }

    /// Push a frame onto the register stack in memory and slide the window
    /// down.
    ///
    /// `PUSHJ $X` (`X < rG`) pushes `X+1` entries at the current `rO`:
    /// `M8[rO+8i] = $i` for `i < X`, and `M8[rO+8X] = X` — the hole, which
    /// `POP` reads back to know how much to restore. `rO` and `rS` both
    /// advance to `rO + 8(X+1)`; nothing else on the stack is written.
    /// `X ≥ rG` pushes all of `$0..$(rL-1)` instead, with `rL` as the hole.
    ///
    /// The live window then slides: caller's `$(X+1)..$(rL-1)` become
    /// callee's `$0..`, every vacated slot up through `rG-1` zeroes so a
    /// fresh local reads zero, and `rJ := pc + 4`.
    fn push_frame(&mut self, x: u8) {
        let rg = self.get_special(SpecialReg::RG) as u8;
        let rl_old = self.get_special(SpecialReg::RL) as u8;
        // PUSHJ $X with X >= rG pushes all of $0..$(rL-1) and starts the
        // callee at rL = 0; the hole for the later POP is rL, not X.
        let x = if x >= rg { rl_old } else { x };
        let ro = self.get_special(SpecialReg::RO);

        for i in 0..x {
            let addr = ro.wrapping_add((i as u64).wrapping_mul(8));
            self.write_octa(addr, self.general_regs[i as usize]);
        }
        let hole_addr = ro.wrapping_add((x as u64).wrapping_mul(8));
        self.write_octa(hole_addr, x as u64);

        // Slide live window: caller's $(x+1)..$(rL-1) become callee's $0.. .
        let new_rl = rl_old.saturating_sub(x).saturating_sub(1);
        for i in 0..new_rl {
            let src = (x as usize) + 1 + (i as usize);
            self.general_regs[i as usize] = self.general_regs[src];
        }
        for i in (new_rl as usize)..(rg as usize) {
            self.general_regs[i] = 0;
        }

        let new_ro = ro.wrapping_add((x as u64 + 1).wrapping_mul(8));
        self.set_special(SpecialReg::RO, new_ro);
        self.set_special(SpecialReg::RS, new_ro);
        self.set_special(SpecialReg::RL, new_rl as u64);
        self.set_special(SpecialReg::RJ, self.pc.wrapping_add(4));
    }

    /// Why `rO` above [`STACK_SEGMENT_START`] cannot hold a frame: `None`
    /// when it is a plain in-segment address, otherwise the reason
    /// [`MMix::pop_frame`] rejects it with.
    fn ro_placement_violation(ro: u64) -> Option<&'static str> {
        if !ro.is_multiple_of(8) {
            Some("is misaligned")
        } else if ro >= 0x8000000000000000 {
            Some("is outside the register stack segment")
        } else {
            None
        }
    }

    /// Pop a frame from the register stack in memory and slide return
    /// values back. `rO` at or below [`STACK_SEGMENT_START`] means no
    /// frame remains: [`PopFrame::NoFrame`], the fallback `POP` takes.
    /// Any other placement outside the stack segment, or a misaligned
    /// `rO`, can only come from a forged [`MMix::set_special`] — the
    /// reference would raise a protection fault there, so this halts
    /// through [`MMix::reject`] instead: [`PopFrame::Rejected`].
    ///
    /// Otherwise the hole comes from memory: `x = M8[rO-8] mod 256`. The
    /// caller's `$0..$(x-1)` restore from `M8[rO-8(x+1)..]`, skipping any
    /// index at or above the current `rG`. `rO` and `rS` retract to
    /// `rO - 8(x+1)` — exactly where the matching `PUSHJ` found them. `rJ`
    /// is left unchanged.
    fn pop_frame(&mut self, n: u8, yz: u16) -> PopFrame {
        let ro = self.get_special(SpecialReg::RO);
        if ro <= STACK_SEGMENT_START {
            return PopFrame::NoFrame;
        }
        if let Some(reason) = Self::ro_placement_violation(ro) {
            self.reject(&format!(
                "POP {n},{yz}: rO={ro:#018x} {reason}; the reference would \
                 raise a protection fault at PC={:#018x}",
                self.pc
            ));
            return PopFrame::Rejected;
        }

        let rg = self.get_special(SpecialReg::RG) as u8;
        let l = self.get_special(SpecialReg::RL) as u16;

        let x = (self.read_octa(ro.wrapping_sub(8)) % 256) as u8;

        // If X > L, X becomes L+1 and the hole gets zero regardless of what
        // the callee left there.
        let clamped = (n as u16) > l;
        let count = if clamped { l + 1 } else { n as u16 };

        // Snapshot the callee's $0..$(count-1) before the frame is torn down.
        let mut returns = [0u64; 256];
        returns[..count as usize].copy_from_slice(&self.general_regs[..count as usize]);

        let new_ro = ro.wrapping_sub((x as u64 + 1).wrapping_mul(8));

        // Every register from the new rL through rG-1 is marginal — clear
        // the whole local range before restoring or writing anything back.
        for i in 0..(rg as usize) {
            self.general_regs[i] = 0;
        }

        // Restore caller's $0..$(x-1) from memory, skipping any index at or
        // above the current rG.
        for i in 0..x {
            if (i as usize) < rg as usize {
                let addr = new_ro.wrapping_add((i as u64).wrapping_mul(8));
                self.general_regs[i as usize] = self.read_octa(addr);
            }
        }

        // The hole $x gets the last output; the rest,
        // $(x+1)..$(x+count-1), get the callee's remaining outputs in order.
        let hole = if count == 0 || clamped {
            0
        } else {
            returns[(count - 1) as usize]
        };
        if (x as usize) < rg as usize {
            self.general_regs[x as usize] = hole;
        }
        for i in 1..count {
            let dst = (x as u16) + i;
            if dst < rg as u16 {
                self.general_regs[dst as usize] = returns[(i - 1) as usize];
            }
        }

        let new_rl = std::cmp::min((x as u16) + count, rg as u16) as u64;

        self.set_special(SpecialReg::RO, new_ro);
        self.set_special(SpecialReg::RS, new_ro);
        self.set_special(SpecialReg::RL, new_rl);

        let return_pc = self.get_special(SpecialReg::RJ);

        PopFrame::Frame(return_pc.wrapping_add((yz as u64) * 4))
    }

    /// Push the machine's context onto the register stack, growing upward
    /// from the current `rO`. From lowest address to highest: the `rL`
    /// local registers `$0..$(rL-1)`, a marker octa holding `rL`, the
    /// global registers `$rG..$255`, the twelve `SAVE_SPECIALS` in order,
    /// and one packed octa with `rG` in its top byte and `rA` in its low
    /// bits. `$X` receives the packed octa's address; `rO` and `rS` both
    /// become the address of the byte after it, and `rL` becomes 0. `rJ` is
    /// saved as data among the specials, never written live: `SAVE` opens
    /// no call frame.
    ///
    /// `X` must already be global (`X >= rG`) — a local destination halts
    /// with the machine unchanged. `writes_general_register_x` would
    /// otherwise pre-claim a local `X` as a side effect of dispatch before
    /// this check ever runs; the preamble in `execute_instruction` skips
    /// that pre-claim for `SAVE` so a rejected `SAVE` truly touches
    /// nothing.
    fn save_context(&mut self, x: u8) -> bool {
        let rg = self.get_special(SpecialReg::RG) as u8;
        if x < rg {
            return self.reject(&format!(
                "SAVE $X,0: X={x} must name a global (rG={rg}) at PC={:#018x}",
                self.pc
            ));
        }

        let rl = self.get_special(SpecialReg::RL);
        let ra = self.get_special(SpecialReg::RA);
        let ro = self.get_special(SpecialReg::RO);

        for i in 0..rl {
            let addr = ro.wrapping_add(i.wrapping_mul(8));
            self.write_octa(addr, self.general_regs[i as usize]);
        }
        let marker_addr = ro.wrapping_add(rl.wrapping_mul(8));
        self.write_octa(marker_addr, rl);

        let globals_base = marker_addr.wrapping_add(8);
        let global_count = 256 - rg as u64;
        for i in 0..global_count {
            let addr = globals_base.wrapping_add(i.wrapping_mul(8));
            self.write_octa(addr, self.general_regs[(rg as u64 + i) as usize]);
        }

        let specials_base = globals_base.wrapping_add(global_count.wrapping_mul(8));
        for (i, reg) in SAVE_SPECIALS.iter().enumerate() {
            let addr = specials_base.wrapping_add((i as u64).wrapping_mul(8));
            self.write_octa(addr, self.get_special(*reg));
        }

        let packed_addr = specials_base.wrapping_add((SAVE_SPECIALS.len() as u64).wrapping_mul(8));
        self.write_octa(packed_addr, (rg as u64) << 56 | ra);

        for reg in 0..rg {
            self.general_regs[reg as usize] = 0;
        }
        self.set_register(x, packed_addr);
        self.set_special(SpecialReg::RL, 0);
        let new_ro = packed_addr.wrapping_add(8);
        self.set_special(SpecialReg::RO, new_ro);
        self.set_special(SpecialReg::RS, new_ro);
        true
    }

    /// Restore the context whose topmost (packed) octa `packed_addr`
    /// addresses, in the layout [`MMix::save_context`] wrote. Validated
    /// whole before any register or memory change: a packed `rG` outside
    /// `32..=255`, a packed `rA` above `RA_MAX`, or a saved local count
    /// above the packed `rG` all halt with the machine unchanged.
    /// Afterward `rL` is the saved local count and `rO = rS` = the address
    /// of the first restored local — where `rO` stood before the matching
    /// `SAVE`.
    fn unsave_context(&mut self, packed_addr: u64) -> bool {
        let packed = self.read_octa(packed_addr);
        let rg_saved = (packed >> 56) as u8;
        let ra_saved = packed & !(0xFFu64 << 56);

        if !(32..=255).contains(&rg_saved) {
            return self.reject(&format!(
                "UNSAVE 0,$Z: saved rG={rg_saved} outside 32..=255 at PC={:#018x}",
                self.pc
            ));
        }
        if ra_saved > RA_MAX {
            return self.reject(&format!(
                "UNSAVE 0,$Z: saved rA={ra_saved:#x} exceeds {RA_MAX:#x} at PC={:#018x}",
                self.pc
            ));
        }

        let layout = match self.save_context_layout(packed_addr, rg_saved) {
            Ok(layout) => layout,
            Err(local_count) => {
                return self.reject(&format!(
                    "UNSAVE 0,$Z: saved local count {local_count} exceeds saved \
                     rG={rg_saved} at PC={:#018x}",
                    self.pc
                ));
            }
        };

        for reg in 0..rg_saved {
            self.general_regs[reg as usize] = 0;
        }
        for i in 0..layout.local_count {
            let addr = layout.locals_base.wrapping_add(i.wrapping_mul(8));
            self.general_regs[i as usize] = self.read_octa(addr);
        }
        for i in 0..layout.global_count {
            let addr = layout.globals_base.wrapping_add(i.wrapping_mul(8));
            self.general_regs[(rg_saved as u64 + i) as usize] = self.read_octa(addr);
        }
        for (i, reg) in SAVE_SPECIALS.iter().enumerate() {
            let addr = layout
                .specials_base
                .wrapping_add((i as u64).wrapping_mul(8));
            let value = self.read_octa(addr);
            self.set_special(*reg, value);
        }

        self.set_special(SpecialReg::RG, rg_saved as u64);
        self.set_special(SpecialReg::RA, ra_saved);
        self.set_special(SpecialReg::RL, layout.local_count);
        self.set_special(SpecialReg::RO, layout.locals_base);
        self.set_special(SpecialReg::RS, layout.locals_base);
        true
    }

    /// The arithmetic below a saved context's packed octa at `packed_addr`,
    /// given its already-extracted `rg_saved`: specials, globals, the
    /// marker and the locals, in the layout [`MMix::save_context`] wrote.
    /// `Err` carries the saved local count when it exceeds `rg_saved` —
    /// corrupt or forged memory, never something `SAVE` itself would
    /// write. Both [`MMix::unsave_context`] and [`MMix::call_depth`] rely
    /// on this bound: it is what keeps the latter's walk from stepping
    /// somewhere memory content, not address arithmetic, decided.
    fn save_context_layout(
        &self,
        packed_addr: u64,
        rg_saved: u8,
    ) -> Result<SaveContextLayout, u64> {
        let specials_base = packed_addr.wrapping_sub((SAVE_SPECIALS.len() as u64).wrapping_mul(8));
        let global_count = 256 - rg_saved as u64;
        let globals_base = specials_base.wrapping_sub(global_count.wrapping_mul(8));
        let marker_addr = globals_base.wrapping_sub(8);
        let local_count = self.read_octa(marker_addr);
        if local_count > rg_saved as u64 {
            return Err(local_count);
        }
        let locals_base = marker_addr.wrapping_sub(local_count.wrapping_mul(8));
        Ok(SaveContextLayout {
            specials_base,
            globals_base,
            global_count,
            local_count,
            locals_base,
        })
    }

    /// Get the value of a special-purpose register.
    pub fn get_special(&self, reg: SpecialReg) -> u64 {
        self.special_regs[reg as usize]
    }

    /// Set the value of a special-purpose register.
    pub fn set_special(&mut self, reg: SpecialReg, value: u64) {
        self.special_regs[reg as usize] = value;
    }

    /// Emit a diagnostic and report the halt `execute_instruction` should
    /// propagate: no register or memory change and no PC advance, on the
    /// caller's promise that it made none before calling this. Every
    /// `PUT`/`PUTI` rejection and `SAVE`/`UNSAVE`'s validation failures route
    /// through this one diagnose-then-refuse path.
    fn reject(&mut self, message: &str) -> bool {
        self.host.diagnostic(message);
        false
    }

    /// Apply a `PUT`/`PUTI` write, enforcing every rule MMIX places on the
    /// destination special register
    /// (mmix.cs.hm.edu/doc/instructions/put.html). `X ≥ 32` names no
    /// register; `rC rN rO rS rI rT rTT rK rQ rU rV` (8–18) are read-only in
    /// user mode; `rG` and `rA` each bound the value they accept. A write
    /// the reference calls impermissible halts with a diagnostic naming the
    /// instruction, the register, the value and the interrupt it raises;
    /// the PC does not advance and no register changes. Returns whether the
    /// write succeeded.
    fn put_special(&mut self, mnemonic: &str, x: u8, value: u64) -> bool {
        let Some(reg) = SpecialReg::from_u8(x) else {
            return self.reject(&format!(
                "{mnemonic} X={x},{value}: no special register above 31 at PC={:#018x}",
                self.pc
            ));
        };
        match reg {
            SpecialReg::RC
            | SpecialReg::RI
            | SpecialReg::RK
            | SpecialReg::RQ
            | SpecialReg::RT
            | SpecialReg::RU
            | SpecialReg::RV
            | SpecialReg::RTT => self.reject(&format!(
                "{mnemonic} {},{value}: privileged-operation interrupt at PC={:#018x}",
                reg.name(),
                self.pc
            )),
            SpecialReg::RN | SpecialReg::RO | SpecialReg::RS => self.reject(&format!(
                "{mnemonic} {},{value}: illegal-instruction interrupt at PC={:#018x}",
                reg.name(),
                self.pc
            )),
            SpecialReg::RG => {
                let rl = self.get_special(SpecialReg::RL);
                if value < 32 || value < rl || value > 255 {
                    return self.reject(&format!(
                        "{mnemonic} rG,{value}: illegal-instruction interrupt \
                         (rG must be 32-255 and >= rL={rl}) at PC={:#018x}",
                        self.pc
                    ));
                }
                self.put_rg(value);
                true
            }
            SpecialReg::RL => {
                self.put_rl(value);
                true
            }
            SpecialReg::RA if value > RA_MAX => self.reject(&format!(
                "{mnemonic} rA,{value:#x}: illegal-instruction interrupt \
                 (rA holds at most 18 bits, max {RA_MAX:#x}) at PC={:#018x}",
                self.pc
            )),
            _ => {
                self.set_special(reg, value);
                true
            }
        }
    }

    /// `PUT rL,z` only ever lowers rL, to `min(z, rL)`. The registers the
    /// drop excludes from the local range become marginal and must read
    /// zero.
    fn put_rl(&mut self, z: u64) {
        let rl_old = self.get_special(SpecialReg::RL);
        let rl_new = z.min(rl_old);
        // Only the local range goes marginal: the globals $rG.. keep their
        // values, and an rL restored from guest memory can name a register
        // the file does not have.
        let rg = self.get_special(SpecialReg::RG);
        let drop_end = rl_old.min(rg).min(self.general_regs.len() as u64);
        for marginal in rl_new..drop_end {
            self.general_regs[marginal as usize] = 0;
        }
        self.set_special(SpecialReg::RL, rl_new);
    }

    /// `PUT rG,z` moves the boundary between the local and global register
    /// ranges. Every register between the old and new `rG` changes class —
    /// global to local/marginal when raising, local/marginal to global when
    /// lowering — and must read zero afterward; registers outside that span
    /// keep their values. A stale `rG` beyond the register file (reachable
    /// only through an unvalidated `UNSAVE`) is clamped so the sweep never
    /// indexes past it.
    fn put_rg(&mut self, z: u64) {
        let rg_old = self.get_special(SpecialReg::RG);
        let (lo, hi) = if z > rg_old { (rg_old, z) } else { (z, rg_old) };
        let hi = hi.min(self.general_regs.len() as u64);
        for reg in lo..hi {
            self.general_regs[reg as usize] = 0;
        }
        self.set_special(SpecialReg::RG, z);
    }

    /// Read a byte from memory at the given address.
    /// Uninitialized memory reads as zero.
    #[instrument(skip(self), level = "trace")]
    pub fn read_byte(&self, addr: u64) -> u8 {
        let value = *self.memory.get(&addr).unwrap_or(&0);
        trace!(
            addr = format!("0x{:X}", addr),
            value, "Read byte from memory"
        );
        value
    }

    /// Write a byte to memory at the given address.
    #[instrument(skip(self), level = "trace")]
    pub fn write_byte(&mut self, addr: u64, value: u8) {
        trace!(
            addr = format!("0x{:X}", addr),
            value, "Writing byte to memory"
        );
        if value == 0 {
            self.memory.remove(&addr); // Don't store zeros (sparse memory)
        } else {
            self.memory.insert(addr, value);
        }
        if self.journal_enabled {
            self.journal.insert(addr);
        }
    }

    /// Every address with a nonzero byte, in ascending address order — the
    /// sparse memory's contents for a caller that wants to display or diff
    /// them, since the underlying map's iteration order is unspecified.
    pub fn occupied(&self) -> impl Iterator<Item = (u64, u8)> {
        let mut addrs: Vec<u64> = self.memory.keys().copied().collect();
        addrs.sort_unstable();
        addrs.into_iter().map(|addr| (addr, self.memory[&addr]))
    }

    /// [`MMix::write_byte`], plus recording `addr` into `loaded` regardless
    /// of value. `write_image`'s per-byte loop calls this in place of
    /// `write_byte` so that a zero byte the loaded program actually placed
    /// stays visible to [`MMix::loaded_extent`] even after the sparse-memory
    /// write drops it from `self.memory`. Not for general writes: a running
    /// program's own stores (register-stack spills, `STO`, ...) must go
    /// through plain `write_byte`, or `loaded_extent` would degrade into the
    /// write journal's noise.
    pub(crate) fn write_loaded_byte(&mut self, addr: u64, value: u8) {
        self.write_byte(addr, value);
        self.loaded.insert(addr);
    }

    /// Every address `write_image` loaded, in ascending order, paired with
    /// its **current** byte value (a later overwrite during execution shows
    /// the new value here, same as [`MMix::occupied`] would if that value is
    /// nonzero).
    ///
    /// Unlike [`MMix::occupied`], this includes a byte that the loaded
    /// program set to zero — sparse memory drops a zero-write from
    /// `self.memory`, so `occupied` can't tell "loaded and zero" from
    /// "never written." This can, so it is what a caller wants for the
    /// real loaded extent instead of a set with silent holes.
    pub fn loaded_extent(&self) -> impl Iterator<Item = (u64, u8)> + '_ {
        self.loaded.iter().map(|&addr| (addr, self.read_byte(addr)))
    }

    /// Enable or disable the write journal. While enabled, every
    /// [`MMix::write_byte`] call records its address (including a
    /// zero-write, which removes the address from [`MMix::occupied`] — that
    /// removal is itself a state change worth journaling). Survives
    /// [`MMix::reset`]; the accumulated addresses do not.
    pub fn set_journal(&mut self, on: bool) {
        self.journal_enabled = on;
    }

    /// Drain the journal, returning every address written since the last
    /// call, deduplicated and in ascending order — matching
    /// [`MMix::occupied`]'s ordering.
    pub fn take_journal(&mut self) -> Vec<u64> {
        let mut addrs: Vec<u64> = self.journal.drain().collect();
        addrs.sort_unstable();
        addrs
    }

    /// Read a wyde (2 bytes) from memory at the address rounded down to a
    /// multiple of 2: `M_2[A] = M_2[2*floor(A/2)]`.
    /// Example: a wyde at #103 reads bytes #102..#103.
    pub fn read_wyde(&self, addr: u64) -> u16 {
        let addr = addr & !1;
        let b0 = self.read_byte(addr) as u16;
        let b1 = self.read_byte(addr.wrapping_add(1)) as u16;
        (b0 << 8) | b1
    }

    /// Write a wyde (2 bytes) to memory at the address rounded down to a
    /// multiple of 2: `M_2[A] = M_2[2*floor(A/2)]`.
    pub fn write_wyde(&mut self, addr: u64, value: u16) {
        let addr = addr & !1;
        self.write_byte(addr, (value >> 8) as u8);
        self.write_byte(addr.wrapping_add(1), value as u8);
    }

    /// Read a tetra (4 bytes) from memory at the address rounded down to a
    /// multiple of 4: `M_4[A] = M_4[4*floor(A/4)]`.
    pub fn read_tetra(&self, addr: u64) -> u32 {
        let addr = addr & !3;
        let b0 = self.read_byte(addr) as u32;
        let b1 = self.read_byte(addr.wrapping_add(1)) as u32;
        let b2 = self.read_byte(addr.wrapping_add(2)) as u32;
        let b3 = self.read_byte(addr.wrapping_add(3)) as u32;
        (b0 << 24) | (b1 << 16) | (b2 << 8) | b3
    }

    /// Write a tetra (4 bytes) to memory at the address rounded down to a
    /// multiple of 4: `M_4[A] = M_4[4*floor(A/4)]`.
    pub fn write_tetra(&mut self, addr: u64, value: u32) {
        let addr = addr & !3;
        self.write_byte(addr, (value >> 24) as u8);
        self.write_byte(addr.wrapping_add(1), (value >> 16) as u8);
        self.write_byte(addr.wrapping_add(2), (value >> 8) as u8);
        self.write_byte(addr.wrapping_add(3), value as u8);
    }

    /// Read an octa (8 bytes) from memory at the address rounded down to a
    /// multiple of 8: `M_8[A] = M_8[8*floor(A/8)]`.
    /// Example: any address in #100..#107 reads bytes #100..#107.
    pub fn read_octa(&self, addr: u64) -> u64 {
        let addr = addr & !7;
        let b0 = self.read_byte(addr) as u64;
        let b1 = self.read_byte(addr.wrapping_add(1)) as u64;
        let b2 = self.read_byte(addr.wrapping_add(2)) as u64;
        let b3 = self.read_byte(addr.wrapping_add(3)) as u64;
        let b4 = self.read_byte(addr.wrapping_add(4)) as u64;
        let b5 = self.read_byte(addr.wrapping_add(5)) as u64;
        let b6 = self.read_byte(addr.wrapping_add(6)) as u64;
        let b7 = self.read_byte(addr.wrapping_add(7)) as u64;
        (b0 << 56) | (b1 << 48) | (b2 << 40) | (b3 << 32) | (b4 << 24) | (b5 << 16) | (b6 << 8) | b7
    }

    /// Write an octa (8 bytes) to memory at the address rounded down to a
    /// multiple of 8: `M_8[A] = M_8[8*floor(A/8)]`.
    pub fn write_octa(&mut self, addr: u64, value: u64) {
        let addr = addr & !7;
        self.write_byte(addr, (value >> 56) as u8);
        self.write_byte(addr.wrapping_add(1), (value >> 48) as u8);
        self.write_byte(addr.wrapping_add(2), (value >> 40) as u8);
        self.write_byte(addr.wrapping_add(3), (value >> 32) as u8);
        self.write_byte(addr.wrapping_add(4), (value >> 24) as u8);
        self.write_byte(addr.wrapping_add(5), (value >> 16) as u8);
        self.write_byte(addr.wrapping_add(6), (value >> 8) as u8);
        self.write_byte(addr.wrapping_add(7), value as u8);
    }

    /// Fetch the next instruction from memory and decode it.
    /// Returns (OP, X, Y, Z) where:
    /// - OP is the opcode
    /// - X, Y, Z are the operand bytes
    pub fn fetch_instruction(&self) -> (u8, u8, u8, u8) {
        let instruction = self.read_tetra(self.pc);
        let op = (instruction >> 24) as u8;
        let x = (instruction >> 16) as u8;
        let y = (instruction >> 8) as u8;
        let z = instruction as u8;
        (op, x, y, z)
    }

    /// Get the current program counter.
    pub fn get_pc(&self) -> u64 {
        self.pc
    }

    /// Set the program counter.
    pub fn set_pc(&mut self, pc: u64) {
        self.pc = pc;
    }

    /// Advance the program counter by 4 bytes (one instruction).
    pub fn advance_pc(&mut self) {
        self.pc = self.pc.wrapping_add(4);
    }

    /// Get the exit code set by TRAP 0 (Halt).
    pub fn get_exit_code(&self) -> u64 {
        self.exit_code
    }

    /// Current call depth: the number of PUSHJ/PUSHGO frames not yet
    /// popped. Walks the register stack down from `rO` to
    /// [`STACK_SEGMENT_START`]: a marker octa below 256 closes out a
    /// frame and counts; a `SAVE` context — its topmost octa never below
    /// 256 — is skipped whole and does not count. Stops, returning the
    /// count so far, if `rO` is ever misaligned or outside the stack
    /// segment, or if a step's target does not lie strictly below where it
    /// started — the walk trusts address arithmetic, never a value read
    /// from memory, to bound itself, so no stack content can make it loop.
    pub fn call_depth(&self) -> usize {
        let mut ro = self.get_special(SpecialReg::RO);
        let mut depth = 0;
        while ro > STACK_SEGMENT_START && ro < 0x8000000000000000 && ro.is_multiple_of(8) {
            let top = self.read_octa(ro.wrapping_sub(8));
            let next = if top < 256 {
                depth += 1;
                ro.wrapping_sub((top + 1).wrapping_mul(8))
            } else {
                let rg_saved = (top >> 56) as u8;
                match self.save_context_layout(ro.wrapping_sub(8), rg_saved) {
                    Ok(layout) => layout.locals_base,
                    Err(_) => break,
                }
            };
            if next >= ro {
                break;
            }
            ro = next;
        }
        depth
    }

    // ========== Internal Helpers ==========

    /// Conditional branch forward: if cond, PC = PC + 4*YZ.
    #[inline]
    fn branch_forward(&mut self, cond: bool, y: u8, z: u8) {
        if cond {
            let yz = ((y as u16) << 8) | (z as u16);
            self.pc = self.pc.wrapping_add((yz as u64) * 4);
        } else {
            self.advance_pc();
        }
    }

    /// Conditional branch backward: if cond, PC = PC + 4*(YZ - 65536).
    #[inline]
    fn branch_backward(&mut self, cond: bool, y: u8, z: u8) {
        if cond {
            // YZ is unsigned in both directions; the backward opcode carries the
            // sign, so YZ = 0 is -65536 tetras and YZ = 65535 is -1.
            let yz = ((y as u16) << 8) | (z as u16);
            let offset = yz as i64 - 65536;
            self.pc = self.pc.wrapping_add((offset * 4) as u64);
        } else {
            self.advance_pc();
        }
    }

    /// Conditional set: if cond($Y), $X = $Z, else do nothing
    #[inline]
    fn cond_set_rr(&mut self, x: u8, _y: u8, z: u8, cond: bool) {
        if cond {
            let val_z = self.get_register(z);
            self.set_register(x, val_z);
        }
        self.advance_pc();
    }

    /// Conditional set with immediate: if cond($Y), $X = Z, else do nothing
    #[inline]
    fn cond_set_ri(&mut self, x: u8, _y: u8, z: u8, cond: bool) {
        if cond {
            self.set_register(x, z as u64);
        }
        self.advance_pc();
    }

    /// Convert u64 to f64 (reinterpret bits)
    #[inline]
    fn u64_to_f64(value: u64) -> f64 {
        f64::from_bits(value)
    }

    /// Convert f64 to u64 (reinterpret bits)
    #[inline]
    fn f64_to_u64(value: f64) -> u64 {
        value.to_bits()
    }

    /// Floating point comparison: `$X <- [f($Y) > f($Z)] - [f($Y) < f($Z)]`, so
    /// -1, 0 or +1 and nothing else. Both predicates are false on an unordered
    /// pair, which therefore answers 0 — `FCMP` cannot distinguish unordered
    /// from equal, and `FUN` is what does.
    #[inline]
    fn fcmp(y: f64, z: f64) -> u64 {
        if y < z {
            (-1i64) as u64
        } else if y > z {
            1
        } else {
            0
        }
    }

    /// `u ∈ Nε(v)`: `|u − v| ≤ 2^(e−1022)·ε`, where `e` is `v`'s biased
    /// exponent field for a normal `v` and is taken as `1` for a
    /// subnormal `v` (radius `2^−1021·ε`). `Nε(0) = {0}`. `Nε(+∞)` is
    /// `{+∞}` when `ε < 1`, everything except `−∞` when `1 ≤ ε < 2`, and
    /// everything when `ε ≥ 2`; `Nε(−∞)` mirrors it. Example: `v = 1.0`
    /// has `e = 1023`, so with `ε = 0.5` the radius is `1.0` and `u =
    /// 1.9 ∈ Nε(1.0)`. Callers exclude NaN operands and a NaN or
    /// negative `ε` beforehand (the shared exception condition,
    /// `epsilon_exceptional`) — `v` and `ε` are never NaN here.
    #[inline]
    fn in_epsilon_neighborhood(u: f64, v: f64, epsilon: f64) -> bool {
        if v.is_infinite() {
            if epsilon < 1.0 {
                u == v
            } else if epsilon < 2.0 {
                u != -v
            } else {
                true
            }
        } else if v == 0.0 {
            u == 0.0
        } else {
            let e = (v.to_bits() >> 52) & 0x7FF;
            let scale = if e == 0 { -1021 } else { e as i32 - 1022 };
            // `2f64.powi(scale)` overflows to `inf` at the top binade
            // (scale == 1024), turning a finite radius into "everything" or,
            // with epsilon == 0.0, into NaN. Scale the difference down by
            // `2^-scale` instead of scaling epsilon up by `2^scale` — but a
            // single `2f64.powi(-scale)` has its own top-binade failure:
            // at `-scale == -1024`, `f64::powi`'s squaring chain overflows
            // an intermediate power to `inf`, and the final reciprocal turns
            // that `inf` into `0.0` — a total loss, not a rounding error.
            // Splitting `-scale` into two halves keeps each `powi` call's
            // result within the normal exponent range, so multiplying
            // `diff` by each half in turn never hits that collapse.
            let half = -scale / 2;
            let rest = -scale - half;
            (u - v).abs() * 2f64.powi(half) * 2f64.powi(rest) <= epsilon
        }
    }

    /// The shared exceptional condition for `FCMPE`/`FEQLE`/`FUNE`: either
    /// compared value is NaN, or `rE` is NaN or negative. `-0.0 < 0.0` is
    /// `false`, so `rE = -0.0` is not negative.
    #[inline]
    fn epsilon_exceptional(y_val: f64, z_val: f64, epsilon: f64) -> bool {
        y_val.is_nan() || z_val.is_nan() || epsilon.is_nan() || epsilon < 0.0
    }

    /// Route every bit `flags` raises through rA's enable byte
    /// (gitraptrip.html "General"; §1 rules 1-2). A raised bit whose enable
    /// is clear sets its event bit and execution continues normally. The
    /// leftmost raised bit in `D V W I O U Z X` priority whose enable is set
    /// instead trips to its handler; any other raised bit that is enabled
    /// but not leftmost is dropped — no event, no trip (owner, 2026-09-18).
    ///
    /// `op_byte`, `x`, `y`, `z` are the raising instruction's own fields, and
    /// `y_val`/`z_val` its `$Y`/`$Z`, captured by the caller before any
    /// destination write — in `ADD $5,$5,$3` the destination is also a
    /// source. This call owns the program counter: it advances it when
    /// nothing trips, and otherwise leaves it to [`MMix::trip`]. Returns
    /// whether execution continues.
    #[allow(clippy::too_many_arguments)]
    fn raise_exceptions(
        &mut self,
        flags: u64,
        op_byte: u8,
        x: u8,
        y: u8,
        z: u8,
        y_val: u64,
        z_val: u64,
    ) -> bool {
        if flags == 0 {
            self.advance_pc();
            return true;
        }
        let enable = (self.get_special(SpecialReg::RA) >> 8) & 0xFF;
        let mut tripped = None;
        let mut events = 0u64;
        for bit in [RA_D, RA_V, RA_W, RA_I, RA_O, RA_U, RA_Z, RA_X] {
            if flags & bit == 0 {
                continue;
            }
            if tripped.is_none() && enable & bit != 0 {
                tripped = Some(bit);
            } else if enable & bit == 0 {
                events |= bit;
            }
        }
        if events != 0 {
            let ra = self.get_special(SpecialReg::RA);
            self.set_special(SpecialReg::RA, ra | events);
        }
        match tripped {
            Some(bit) => {
                let (vector, label) = Self::arithmetic_vector(bit);
                self.trip(vector, label, op_byte, x, y, z, y_val, z_val)
            }
            None => {
                self.advance_pc();
                true
            }
        }
    }

    /// Handler vector and diagnostic label for a tripped rA exception bit:
    /// `D V W I O U Z X` to `#10 #20 #30 #40 #50 #60 #70 #80`
    /// (gitraptrip.html, "TRIP" section).
    fn arithmetic_vector(bit: u64) -> (u64, &'static str) {
        match bit {
            RA_D => (0x10, "D"),
            RA_V => (0x20, "V"),
            RA_W => (0x30, "W"),
            RA_I => (0x40, "I"),
            RA_O => (0x50, "O"),
            RA_U => (0x60, "U"),
            RA_Z => (0x70, "Z"),
            RA_X => (0x80, "X"),
            _ => unreachable!("raise_exceptions only ever passes an rA exception bit"),
        }
    }

    /// `RA_V` when a store's value, read as signed, does not fit `lo..=hi`,
    /// the destination width's range; otherwise no flag.
    fn store_overflow_flag(value: u64, lo: i64, hi: i64) -> u64 {
        if (lo..=hi).contains(&(value as i64)) {
            0
        } else {
            RA_V
        }
    }

    /// The aligned octabyte containing `addr`, read after a store has
    /// written it: the stored bytes in place, the rest as memory holds them
    /// (gitraptrip.html "General"). A store trip's `rZ` per §1 rule 3.
    fn merged_store_octa(&self, addr: u64) -> u64 {
        self.read_octa(addr)
    }

    /// Whether every byte of the tetra at `addr` came from `write_image` (or
    /// a test's `write_loaded_byte`) rather than reading as zero by default.
    /// Backs the unloaded-vector halt in [`MMix::trip`]: unassembled memory
    /// decodes as `TRAP 0,0,0`, a silent zero-exit halt that would hide the
    /// fault a trip to that vector was supposed to report.
    fn vector_loaded(&self, addr: u64) -> bool {
        (0..4).all(|offset| self.loaded.contains(&(addr + offset)))
    }

    /// Transfer control to a `TRIP` or arithmetic-exception handler
    /// (gitraptrip.html "TRIP"; §1 rule 3): `rB` takes `$255`, `$255` takes
    /// `rJ`, `rW` takes the address following the raising instruction, `rX`
    /// takes `#80000000` with that instruction's own opcode/X/Y/Z, and
    /// `rY`/`rZ` take `y_val`/`z_val`. PC then jumps to `vector`.
    ///
    /// A vector nothing ever loaded halts with a diagnostic naming `label`
    /// and `vector`, PC unmoved and a nonzero exit code, after every
    /// register above is set — so a debugger sees why. This does not route
    /// through [`MMix::reject`]: that helper promises no prior state change,
    /// which does not hold here by design.
    #[allow(clippy::too_many_arguments)]
    fn trip(
        &mut self,
        vector: u64,
        label: &str,
        op_byte: u8,
        x: u8,
        y: u8,
        z: u8,
        y_val: u64,
        z_val: u64,
    ) -> bool {
        let next_pc = self.pc.wrapping_add(4);
        self.set_special(SpecialReg::RB, self.get_register(255));
        self.set_register(255, self.get_special(SpecialReg::RJ));
        self.set_special(SpecialReg::RW, next_pc);
        let rx = 0x8000_0000_0000_0000u64
            | ((op_byte as u64) << 24)
            | ((x as u64) << 16)
            | ((y as u64) << 8)
            | z as u64;
        self.set_special(SpecialReg::RX, rx);
        self.set_special(SpecialReg::RY, y_val);
        self.set_special(SpecialReg::RZ, z_val);
        if !self.vector_loaded(vector) {
            self.exit_code = 1;
            self.host.diagnostic(&format!(
                "{label} trip to unloaded vector {vector:#04x} at PC={:#018x}",
                self.pc
            ));
            return false;
        }
        self.pc = vector;
        true
    }

    /// True iff `x` is a signaling NaN per IEEE 754 binary64 (exponent all 1s,
    /// mantissa nonzero, high mantissa bit clear).
    #[inline]
    fn is_signaling_nan(x: f64) -> bool {
        let bits = x.to_bits();
        let exp = (bits >> 52) & 0x7FF;
        let mant = bits & 0x000F_FFFF_FFFF_FFFF;
        exp == 0x7FF && mant != 0 && (mant & (1u64 << 51)) == 0
    }

    /// Force any NaN to its quiet form by setting the high mantissa bit. Leaves
    /// non-NaN values unchanged. Used to suppress sNaN propagation per IEEE 754.
    #[inline]
    fn quiet_nan(x: f64) -> f64 {
        if x.is_nan() {
            f64::from_bits(x.to_bits() | (1u64 << 51))
        } else {
            x
        }
    }

    /// Compute rA event flags for a binary IEEE 754 operation. The X flag is
    /// reported by callers that supply an exact residual (`finalize_fp_binop`).
    /// No U: the only caller is `FREM`, and the IEEE remainder is exact by
    /// definition, so it can neither round nor underflow.
    #[inline]
    fn fp_arith_flags(a: f64, b: f64, result: f64) -> u64 {
        let mut flags = 0u64;
        if Self::is_signaling_nan(a) || Self::is_signaling_nan(b) {
            flags |= RA_I;
        }
        if !a.is_nan() && !b.is_nan() && result.is_nan() {
            flags |= RA_I;
        } else if a.is_finite() && b.is_finite() && result.is_infinite() {
            flags |= RA_O;
        }
        flags
    }

    /// Veltkamp-Knuth 2Sum: returns `(s, err)` such that `s + err == a + b`
    /// exactly, where `s = a + b` rounded to nearest-even. Valid for all
    /// finite operands (no overflow case here — caller checks `s.is_finite()`).
    #[inline]
    fn two_sum(a: f64, b: f64) -> (f64, f64) {
        let s = a + b;
        let bb = s - a;
        let err = (a - (s - bb)) + (b - bb);
        (s, err)
    }

    /// Apply MMIX rA rounding mode to `r` (the round-to-nearest-even result of
    /// some op) given an exact residual `err` whose sign equals
    /// `sign(true_result - r)`. `err == 0` means the result is exact.
    #[inline]
    fn apply_directed_rounding(r: f64, err: f64, mode: u64) -> f64 {
        if err == 0.0 || !r.is_finite() {
            return r;
        }
        match mode & 0x3 {
            0 => r,
            1 => {
                if r > 0.0 && err < 0.0 {
                    r.next_down()
                } else if r < 0.0 && err > 0.0 {
                    r.next_up()
                } else {
                    r
                }
            }
            2 => {
                if err > 0.0 {
                    r.next_up()
                } else {
                    r
                }
            }
            3 => {
                if err < 0.0 {
                    r.next_down()
                } else {
                    r
                }
            }
            _ => r,
        }
    }

    /// On overflow (finite operands → infinite hardware result), directed
    /// rounding modes ROUND_OFF and the "wrong-sign" infinity for ±∞ modes
    /// must clamp to ±MAX instead of leaving ±Inf.
    #[inline]
    fn clamp_overflow_for_mode(r: f64, mode: u64) -> f64 {
        if !r.is_infinite() {
            return r;
        }
        match (r.is_sign_positive(), mode & 0x3) {
            (true, 1) | (true, 3) => f64::MAX,
            (false, 1) | (false, 2) => -f64::MAX,
            _ => r,
        }
    }

    /// Finalize a binary FP op given the round-to-nearest-even result `r_near`
    /// and an exact residual `err` (`sign(err) == sign(true - r_near)`, `err==0`
    /// means exact). Returns `(adjusted_result, flags)`. Centralizes sNaN
    /// quieting, overflow clamping per rA mode, X / I / O / U detection.
    ///
    /// `true_result_is_zero` resolves a zero delivered result: U means the
    /// result was too small to represent, so a true result of exactly zero is
    /// never an underflow. Only the caller knows which its zero was.
    fn finalize_fp_binop(
        &self,
        a: f64,
        b: f64,
        r_near: f64,
        err: f64,
        true_result_is_zero: bool,
    ) -> (f64, u64) {
        let mode = (self.get_special(SpecialReg::RA) >> RA_ROUND_SHIFT) & 0x3;
        let operands_finite = a.is_finite() && b.is_finite();
        let mut flags = 0u64;
        if Self::is_signaling_nan(a) || Self::is_signaling_nan(b) {
            flags |= RA_I;
        }
        let result = if r_near.is_nan() {
            if !a.is_nan() && !b.is_nan() {
                flags |= RA_I;
            }
            Self::quiet_nan(r_near)
        } else if r_near.is_infinite() && operands_finite {
            flags |= RA_O | RA_X;
            Self::clamp_overflow_for_mode(r_near, mode)
        } else if r_near.is_finite() {
            // A non-finite operand yields an exact result — ±0, ±inf or NaN —
            // and its residual is meaningless: `(-0.0).mul_add(inf, 1.0)` is
            // NaN. Neither X nor directed rounding applies there.
            let err = if operands_finite { err } else { 0.0 };
            if err != 0.0 {
                flags |= RA_X;
            }
            Self::apply_directed_rounding(r_near, err, mode)
        } else {
            r_near
        };
        if operands_finite
            && a != 0.0
            && b != 0.0
            && (result.is_subnormal() || (result == 0.0 && !true_result_is_zero))
        {
            flags |= RA_U;
        }
        (result, flags)
    }

    /// Finalize a unary FP op (FSQRT). Same shape as `finalize_fp_binop`.
    ///
    /// No U: the only caller is `FSQRT`, and the square root of a nonzero
    /// finite operand is neither zero nor subnormal — the root of the smallest
    /// subnormal is about `2^-537`.
    fn finalize_fp_unop(&self, a: f64, r_near: f64, err: f64, mode: u64) -> (f64, u64) {
        let mut flags = 0u64;
        if Self::is_signaling_nan(a) {
            flags |= RA_I;
        }
        let result = if r_near.is_nan() {
            if !a.is_nan() {
                flags |= RA_I;
            }
            Self::quiet_nan(r_near)
        } else if r_near.is_infinite() && a.is_finite() {
            flags |= RA_O | RA_X;
            Self::clamp_overflow_for_mode(r_near, mode)
        } else if r_near.is_finite() {
            if err != 0.0 {
                flags |= RA_X;
            }
            Self::apply_directed_rounding(r_near, err, mode)
        } else {
            r_near
        };
        (result, flags)
    }

    /// IEEE 754 floating-point remainder: `r = a − round-half-to-even(a/b) · b`.
    /// Rust's `%` operator is truncated remainder; this is the rounded remainder
    /// required by the MMIX FREM spec.
    ///
    /// A zero remainder takes the sign of the dividend, per IEEE 754. The
    /// subtraction cannot produce it: `x - x` is `+0.0` under every rounding
    /// mode but ROUND_DOWN.
    #[inline]
    fn ieee_remainder(a: f64, b: f64) -> f64 {
        if a.is_nan() || b.is_nan() || a.is_infinite() || b == 0.0 {
            return f64::NAN;
        }
        if b.is_infinite() {
            return a;
        }
        let n = (a / b).round_ties_even();
        let r = a - n * b;
        if r == 0.0 { 0.0f64.copysign(a) } else { r }
    }

    /// Resolve the `Y` rounding-mode override that `FIX`, `FIXU`, `FSQRT`,
    /// `FINT`, and the `FLOT`/`SFLOT` families carry.
    /// `Y == 0` defers to rA's own persistent mode (`RA_ROUND_SHIFT`); `Y`
    /// in `1..=4` forces a mode via `Y & 3` — this maps `Y=4` (`ROUND_NEAR`)
    /// onto rA's mode `0`, since the two numberings are not related by a
    /// simple offset (`MMIX.md`'s rounding-mode table). `Y > 4` is the
    /// illegal-instruction condition; `Err` and the caller halts.
    #[inline]
    fn resolved_round_mode(&self, y: u8) -> Result<u64, ()> {
        match y {
            0 => Ok((self.get_special(SpecialReg::RA) >> RA_ROUND_SHIFT) & 0x3),
            1..=4 => Ok((y & 3) as u64),
            _ => Err(()),
        }
    }

    /// `Y > 4` on an instruction that takes a rounding-mode override is an
    /// illegal-instruction interrupt this VM has no vector for. Mirrors
    /// `Opcode::TRIP`'s halt-with-diagnostic precedent.
    fn illegal_round_mode(&mut self, mnemonic: &str, y: u8) -> bool {
        self.host.diagnostic(&format!(
            "{mnemonic}: illegal Y={y} at PC={:#018x} (Y must be 0-4)",
            self.pc
        ));
        false
    }

    /// MMIX rounding mode (rA bits 17-16): 0=NEAR (default), 1=OFF (trunc), 2=UP
    /// (ceil toward +∞), 3=DOWN (floor toward −∞). Applies to FINT and to the
    /// f64→f32 conversion in SFLOT/STSF.
    #[inline]
    fn round_with_mode(value: f64, mode: u64) -> f64 {
        match mode & 0x3 {
            0 => value.round_ties_even(),
            1 => value.trunc(),
            2 => value.ceil(),
            3 => value.floor(),
            _ => unreachable!(),
        }
    }

    /// Reduce an integral finite `f64` to the low 64 bits of its exact value,
    /// as `FIXU` requires: `u($X) <- int(f($Z)) mod 2^64`. A magnitude whose
    /// ulp reaches `2^64` therefore yields zero.
    ///
    /// Read out of the bit pattern because neither Rust cast will do it: `as
    /// u64` saturates at the range ends instead of wrapping, and the wrapping
    /// `to_int_unchecked` is `unsafe`.
    #[inline]
    fn wrap_to_u64(value: f64) -> u64 {
        let bits = value.to_bits();
        let exponent = ((bits >> 52) & 0x7FF) as i32 - 1023;
        // A zero or subnormal encoding has no integral part; the caller has
        // already rounded, so any |value| < 1 is ±0.
        if exponent < 0 {
            return 0;
        }
        let significand = (bits & 0x000F_FFFF_FFFF_FFFF) | (1u64 << 52);
        let magnitude = if exponent < 52 {
            significand >> (52 - exponent)
        } else if exponent < 116 {
            // Bits above 2^64 fall off the left, which is the reduction itself.
            significand << (exponent - 52)
        } else {
            0
        };
        if value.is_sign_negative() {
            magnitude.wrapping_neg()
        } else {
            magnitude
        }
    }

    /// Exact residual of rounding `magnitude` to `f64`, that is
    /// `magnitude - (magnitude as f64)` — an integer below `2^11` in magnitude,
    /// since at most eleven bits fall off a 64-bit value.
    ///
    /// A round trip through the float cannot recover it: `u64::MAX as f64` is
    /// `2^64`, whose cast back saturates to `u64::MAX` and so reports a
    /// conversion that lost eleven bits as exact.
    #[inline]
    fn u64_to_f64_residual(magnitude: u64) -> i64 {
        let significant = 64 - magnitude.leading_zeros();
        if significant <= 53 {
            return 0;
        }
        let dropped = significant - 53;
        let low = magnitude & ((1u64 << dropped) - 1);
        let half = 1u64 << (dropped - 1);
        // Round-to-nearest-even, matching Rust's integer-to-float cast.
        let up = low > half || (low == half && (magnitude >> dropped) & 1 == 1);
        if up {
            low as i64 - (1i64 << dropped)
        } else {
            low as i64
        }
    }

    /// X for the integer-to-`f64` step of the `SFLOT` family, whose narrowing to
    /// `f32` reports its own flags through `f64_to_f32_rounded`. That first step
    /// can lose bits above `2^53` and said nothing about it.
    #[inline]
    fn int_to_f64_inexact(magnitude: u64) -> u64 {
        if Self::u64_to_f64_residual(magnitude) != 0 {
            RA_X
        } else {
            0
        }
    }

    /// Convert an exact integer to `f64` under the given rounding mode,
    /// reporting X when the conversion loses bits. The value is given as
    /// sign and magnitude so the residual stays in integer arithmetic.
    #[inline]
    fn int_to_f64_rounded(&self, negative: bool, magnitude: u64, mode: u64) -> (f64, u64) {
        let residual = Self::u64_to_f64_residual(magnitude) as f64;
        let (r_near, err) = if negative {
            (-(magnitude as f64), -residual)
        } else {
            (magnitude as f64, residual)
        };
        let flags = if err != 0.0 { RA_X } else { 0 };
        (Self::apply_directed_rounding(r_near, err, mode), flags)
    }

    /// Convert f64 → f32 under the given rounding mode, reporting flags.
    /// Returns `(narrowed_as_f64, flags)`. `STSF`/`STSFI` always pass rA's
    /// own mode; `SFLOT`'s family passes its resolved `Y` override.
    #[inline]
    fn f64_to_f32_rounded(&self, value: f64, mode: u64) -> (f64, u64) {
        let near = value as f32; // hardware default: round-to-nearest-even
        let narrowed = if !value.is_finite() || (near as f64) == value {
            near
        } else {
            let near_high = (near as f64) > value;
            match mode {
                0 => near,
                1 => {
                    // ROUND_OFF: toward zero
                    if (near as f64).abs() > value.abs() {
                        if near > 0.0 {
                            near.next_down()
                        } else {
                            near.next_up()
                        }
                    } else {
                        near
                    }
                }
                2 => {
                    // ROUND_UP: toward +∞
                    if near_high { near } else { near.next_up() }
                }
                3 => {
                    // ROUND_DOWN: toward -∞
                    if near_high { near.next_down() } else { near }
                }
                _ => near,
            }
        };
        let result = narrowed as f64;
        let mut flags = 0u64;
        if !value.is_nan() && narrowed.is_nan() {
            flags |= RA_I;
        }
        if value.is_finite() && narrowed.is_infinite() {
            flags |= RA_O;
        }
        if !value.is_nan() && value != 0.0 && (narrowed == 0.0 || narrowed.is_subnormal()) {
            flags |= RA_U;
        }
        if !value.is_nan() && !value.is_infinite() && result != value {
            flags |= RA_X;
        }
        (result, flags)
    }

    /// Zero or set with register: if cond($Y), $X = $Z, else $X = 0
    #[inline]
    fn zero_set_rr(&mut self, x: u8, _y: u8, z: u8, cond: bool) {
        let result = if cond { self.get_register(z) } else { 0 };
        self.set_register(x, result);
        self.advance_pc();
    }

    /// Zero or set with immediate: if cond($Y), $X = Z, else $X = 0
    #[inline]
    fn zero_set_ri(&mut self, x: u8, _y: u8, z: u8, cond: bool) {
        let result = if cond { z as u64 } else { 0 };
        self.set_register(x, result);
        self.advance_pc();
    }

    /// Handle TRAP system calls
    /// Returns true if execution should continue, false if halted
    fn handle_trap(&mut self, trap_code: TrapCode, arg: u8) -> bool {
        let arg255 = self.get_register(255);
        let result = match trap_code {
            TrapCode::Halt => self.handle_halt(arg),
            TrapCode::Trip => self.handle_trip(arg),
            TrapCode::Fopen => self.handle_fopen(arg),
            TrapCode::Fclose => self.handle_fclose(arg),
            TrapCode::Fread => self.handle_fread(arg),
            TrapCode::Fgets => self.handle_fgets(arg),
            TrapCode::Fgetws => self.handle_fgetws(arg),
            TrapCode::Fwrite => self.handle_fwrite(arg),
            TrapCode::Fputs => self.handle_fputs(arg),
            TrapCode::Fputc => self.handle_fputc(arg),
            TrapCode::Fputws => self.handle_fputws(arg),
            TrapCode::Fseek => self.handle_fseek(arg),
            TrapCode::Ftell => self.handle_ftell(arg),
            TrapCode::Time => self.handle_time(arg),
        };
        let result255 = self.get_register(255);
        self.host.trap(trap_code, arg, arg255, result255);
        result
    }

    /// TRAP 0: Halt - stop execution
    /// Parameter in $255: exit code (though typically ignored, could use Z parameter)
    fn handle_halt(&mut self, _arg: u8) -> bool {
        debug!("TRAP: Halt");
        let exit_code = self.get_register(255);
        self.exit_code = exit_code;
        // Halt is the machine's last chance to signal the host: the caller
        // exits without running destructors, so buffered output from earlier
        // Fputs/Fputc/Fputws calls would otherwise be discarded.
        self.host.flush();
        self.host.diagnostic(&format!(
            "HALT trap at PC={:#018x}, exit code={}",
            self.pc, exit_code
        ));
        self.advance_pc();
        false
    }

    /// TRAP 1: Trip - cause a dynamic trap
    /// This saves state and jumps to the handler at rTT (if set)
    fn handle_trip(&mut self, arg: u8) -> bool {
        debug!("TRAP: Trip");

        let handler_addr = self.get_special(SpecialReg::RTT);

        if handler_addr == 0 {
            self.host.diagnostic(&format!(
                "TRIP trap at PC={:#018x} - rTT not set, treating as NOP",
                self.pc
            ));
            self.advance_pc();
            return true;
        }

        // Save interrupted state to special registers
        // rW: where interrupted (PC of next instruction)
        self.set_special(SpecialReg::RW, self.pc.wrapping_add(4));
        // rX: execution register (would be the instruction being executed)
        // rY, rZ: operands (Y and Z fields, with X and opcode in high bits)
        self.set_special(SpecialReg::RY, 0);
        self.set_special(SpecialReg::RZ, arg as u64);

        // Jump to trap handler
        debug!("Jumping to TRIP handler at {:#018x}", handler_addr);
        self.pc = handler_addr;
        true
    }

    /// TRAP 2: Fopen - open a file
    /// Parameters in $255: filename address
    /// Auxiliary parameter: mode (0=read, 1=write, 2=append)
    /// Returns file descriptor in $255, or -1 on error
    fn handle_fopen(&mut self, mode: u8) -> bool {
        let filename_addr = self.get_register(255);
        let filename = self.read_cstring(filename_addr, 256);

        debug!(filename = %filename, mode, "TRAP: Fopen");

        let result = match mode {
            0 => File::open(&filename).ok(),
            1 => OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&filename)
                .ok(),
            2 => OpenOptions::new()
                .create(true)
                .append(true)
                .open(&filename)
                .ok(),
            _ => {
                debug!("Invalid file open mode: {}", mode);
                None
            }
        };

        match result {
            Some(file) => {
                let fd = self.next_fd;
                self.file_handles.insert(fd, file);
                self.next_fd = self.next_fd.wrapping_add(1);
                if self.next_fd < 3 {
                    self.next_fd = 3;
                }
                self.set_register(255, fd as u64);
                debug!(fd, "File opened successfully");
            }
            None => {
                self.set_register(255, (-1i64) as u64);
                debug!("File open failed");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 3: Fclose - close a file
    /// Parameter in $255: file descriptor
    /// Returns 0 on success, -1 on error in $255
    fn handle_fclose(&mut self, _arg: u8) -> bool {
        let fd = self.get_register(255) as u8;
        debug!(fd, "TRAP: Fclose");

        match self.file_handles.remove(&fd) {
            Some(_) => {
                self.set_register(255, 0);
                debug!(fd, "File closed successfully");
            }
            None => {
                self.set_register(255, -1i64 as u64);
                debug!(fd, "File not open");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 4: Fread - read from file
    /// Parameter in $255: address of parameter block containing:
    ///   OCTA 0: file descriptor
    ///   OCTA 1: buffer address
    ///   OCTA 2: number of bytes to read
    /// Returns number of bytes read in $255, or -1 on error
    fn handle_fread(&mut self, _arg: u8) -> bool {
        let param_addr = self.get_register(255);
        let fd = self.read_octa(param_addr) as u8;
        let buffer_addr = self.read_octa(param_addr.wrapping_add(8));
        let size = self.read_octa(param_addr.wrapping_add(16)) as usize;

        debug!(
            fd,
            buffer_addr = format!("0x{:X}", buffer_addr),
            size,
            "TRAP: Fread"
        );

        match self.file_handles.get_mut(&fd) {
            Some(file) => {
                let mut buffer = vec![0u8; size];
                match file.read(&mut buffer) {
                    Ok(bytes_read) => {
                        for (i, &byte) in buffer[..bytes_read].iter().enumerate() {
                            self.write_byte(buffer_addr.wrapping_add(i as u64), byte);
                        }
                        self.set_register(255, bytes_read as u64);
                        debug!(bytes_read, "Read successful");
                    }
                    Err(_) => {
                        self.set_register(255, (-1i64) as u64);
                        debug!("Read failed");
                    }
                }
            }
            None => {
                self.set_register(255, (-1i64) as u64);
                debug!(fd, "File not open for read");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 5: Fgets - read a line from file (up to newline)
    /// Parameter in $255: address of parameter block containing:
    ///   OCTA 0: buffer address
    ///   OCTA 1: maximum buffer size
    /// Auxiliary parameter (Z): file descriptor (0=stdin)
    /// Returns number of bytes read in $255, or -1 on error
    fn handle_fgets(&mut self, fd: u8) -> bool {
        let param_addr = self.get_register(255);
        let buffer_addr = self.read_octa(param_addr);
        let max_size = self.read_octa(param_addr.wrapping_add(8)) as usize;

        debug!(
            fd,
            buffer_addr = format!("0x{:X}", buffer_addr),
            max_size,
            "TRAP: Fgets"
        );

        match self.file_handles.get_mut(&fd) {
            Some(file) => {
                let mut buffer = Vec::new();
                let mut one_byte = [0u8; 1];
                let mut bytes_read = 0;

                while bytes_read < max_size - 1 {
                    match file.read_exact(&mut one_byte) {
                        Ok(_) => {
                            buffer.push(one_byte[0]);
                            bytes_read += 1;
                            if one_byte[0] == b'\n' {
                                break;
                            }
                        }
                        Err(_) => break,
                    }
                }

                if bytes_read > 0 || !buffer.is_empty() {
                    for (i, &byte) in buffer.iter().enumerate() {
                        self.write_byte(buffer_addr.wrapping_add(i as u64), byte);
                    }
                    self.write_byte(buffer_addr.wrapping_add(bytes_read as u64), 0);
                    self.set_register(255, bytes_read as u64);
                    debug!(bytes_read, "Fgets successful");
                } else {
                    self.set_register(255, 0);
                    debug!("EOF reached");
                }
            }
            None => {
                self.set_register(255, (-1i64) as u64);
                debug!(fd, "File not open for read");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 6: Fgetws - read a wide string from file (same as Fgets for now)
    /// Parameter in $255: address of parameter block containing:
    ///   OCTA 0: buffer address
    ///   OCTA 1: maximum buffer size
    /// Auxiliary parameter (Z): file descriptor
    /// Returns number of bytes read in $255, or -1 on error
    fn handle_fgetws(&mut self, fd: u8) -> bool {
        let param_addr = self.get_register(255);
        let buffer_addr = self.read_octa(param_addr);
        let max_size = self.read_octa(param_addr.wrapping_add(8)) as usize;

        debug!(
            fd,
            buffer_addr = format!("0x{:X}", buffer_addr),
            max_size,
            "TRAP: Fgetws"
        );

        match self.file_handles.get_mut(&fd) {
            Some(file) => {
                let mut buffer = Vec::new();
                let mut one_byte = [0u8; 1];
                let mut bytes_read = 0;

                while bytes_read < max_size - 1 {
                    match file.read_exact(&mut one_byte) {
                        Ok(_) => {
                            buffer.push(one_byte[0]);
                            bytes_read += 1;
                            if one_byte[0] == b'\n' {
                                break;
                            }
                        }
                        Err(_) => break,
                    }
                }

                if bytes_read > 0 || !buffer.is_empty() {
                    for (i, &byte) in buffer.iter().enumerate() {
                        self.write_byte(buffer_addr.wrapping_add(i as u64), byte);
                    }
                    self.write_byte(buffer_addr.wrapping_add(bytes_read as u64), 0);
                    self.set_register(255, bytes_read as u64);
                    debug!(bytes_read, "Fgetws successful");
                } else {
                    self.set_register(255, 0);
                    debug!("EOF reached");
                }
            }
            None => {
                self.set_register(255, (-1i64) as u64);
                debug!(fd, "File not open for read");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 7: Fwrite - write to file
    /// Parameter in $255: address of parameter block containing:
    ///   OCTA 0: file descriptor
    ///   OCTA 1: buffer address
    ///   OCTA 2: number of bytes to write
    /// Returns number of bytes written in $255, or -1 on error
    fn handle_fwrite(&mut self, _arg: u8) -> bool {
        let param_addr = self.get_register(255);
        let fd = self.read_octa(param_addr) as u8;
        let buffer_addr = self.read_octa(param_addr.wrapping_add(8));
        let size = self.read_octa(param_addr.wrapping_add(16)) as usize;

        debug!(
            fd,
            buffer_addr = format!("0x{:X}", buffer_addr),
            size,
            "TRAP: Fwrite"
        );

        let mut buffer = Vec::with_capacity(size);
        for i in 0..size {
            buffer.push(self.read_byte(buffer_addr.wrapping_add(i as u64)));
        }

        match self.file_handles.get_mut(&fd) {
            Some(file) => match file.write_all(&buffer) {
                Ok(_) => {
                    self.set_register(255, size as u64);
                    debug!(size, "Write successful");
                }
                Err(_) => {
                    self.set_register(255, (-1i64) as u64);
                    debug!("Write failed");
                }
            },
            None => {
                self.set_register(255, (-1i64) as u64);
                debug!(fd, "File not open for write");
            }
        }
        self.advance_pc();
        true
    }

    /// Read a NUL-terminated byte string from memory starting at `addr`.
    /// Bytes are returned verbatim (no UTF-8 widening). Truncated at `max_len`
    /// bytes if no NUL is found, with a warning. Walks memory using wrapping
    /// arithmetic so str_addr near u64::MAX cannot panic.
    fn read_byte_string(&mut self, str_addr: u64, max_len: usize, label: &str) -> Vec<u8> {
        let mut bytes = Vec::new();
        let mut addr = str_addr;
        loop {
            let byte = self.read_byte(addr);
            if byte == 0 {
                break;
            }
            bytes.push(byte);
            if bytes.len() >= max_len {
                self.host
                    .diagnostic(&format!("Warning: {} string too long, truncating", label));
                break;
            }
            addr = addr.wrapping_add(1);
        }
        bytes
    }

    /// Write raw bytes to the destination identified by an MMIX file
    /// descriptor: 1 and 2 go through the installed `Host` (locked
    /// stdout/stderr writes for `StdHost`); anything else is looked up in
    /// `file_handles`, whose retry and locking behavior is `std::fs::File`'s.
    fn write_bytes_to_fd(&mut self, fd: u8, bytes: &[u8]) -> std::io::Result<()> {
        match fd {
            1 | 2 => self.host.write(fd, bytes),
            _ => match self.file_handles.get_mut(&fd) {
                Some(file) => file.write_all(bytes),
                None => Err(std::io::Error::other("file descriptor not open")),
            },
        }
    }

    /// TRAP 8: Fputs - write null-terminated string
    /// Parameter in $255: string address
    /// Auxiliary parameter (Z): file descriptor (1=stdout, 2=stderr, or
    /// a handle previously returned by Fopen)
    /// Returns byte count written in $255, or -1 on error
    fn handle_fputs(&mut self, fd: u8) -> bool {
        let str_addr = self.get_register(255);
        let bytes = self.read_byte_string(str_addr, 10000, "Fputs");
        debug!(fd, str_addr = format!("0x{:X}", str_addr), "TRAP: Fputs");
        match self.write_bytes_to_fd(fd, &bytes) {
            Ok(_) => self.set_register(255, bytes.len() as u64),
            Err(_) => {
                debug!(fd, "Fputs write failed");
                self.set_register(255, (-1i64) as u64);
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 9: Fputc - write a character
    /// Parameter in $255: character code (low 8 bits)
    /// Auxiliary parameter (Z): file descriptor (1=stdout, 2=stderr, or
    /// a handle previously returned by Fopen)
    /// Returns 0 on success, -1 on error in $255
    fn handle_fputc(&mut self, fd: u8) -> bool {
        let ch = (self.get_register(255) & 0xFF) as u8;
        debug!(fd, ch = format!("0x{:02X}", ch), "TRAP: Fputc");
        match self.write_bytes_to_fd(fd, &[ch]) {
            Ok(_) => self.set_register(255, 0),
            Err(_) => {
                debug!(fd, "Fputc write failed");
                self.set_register(255, (-1i64) as u64);
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 10: Fputws - write a wide string to file (same as Fputs for now)
    /// Parameter in $255: string address
    /// Auxiliary parameter (Z): file descriptor (1=stdout, 2=stderr, or
    /// a handle previously returned by Fopen)
    /// Returns byte count written in $255, or -1 on error
    fn handle_fputws(&mut self, fd: u8) -> bool {
        let str_addr = self.get_register(255);
        let bytes = self.read_byte_string(str_addr, 10000, "Fputws");
        debug!(fd, str_addr = format!("0x{:X}", str_addr), "TRAP: Fputws");
        match self.write_bytes_to_fd(fd, &bytes) {
            Ok(_) => self.set_register(255, bytes.len() as u64),
            Err(_) => {
                debug!(fd, "Fputws write failed");
                self.set_register(255, (-1i64) as u64);
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 11: Fseek - seek in file
    /// Parameter in $255: address of parameter block containing:
    ///   OCTA 0: file descriptor
    ///   OCTA 1: offset (as i64)
    ///   OCTA 2: whence (0=start, 1=current, 2=end)
    /// Returns new position in $255, or -1 on error
    fn handle_fseek(&mut self, _arg: u8) -> bool {
        let param_addr = self.get_register(255);
        let fd = self.read_octa(param_addr) as u8;
        let offset = self.read_octa(param_addr.wrapping_add(8)) as i64;
        let whence = self.read_octa(param_addr.wrapping_add(16)) as u8;

        debug!(fd, offset, whence, "TRAP: Fseek");

        match self.file_handles.get_mut(&fd) {
            Some(file) => {
                let seek_from = match whence {
                    0 => SeekFrom::Start(offset as u64),
                    1 => SeekFrom::Current(offset),
                    2 => SeekFrom::End(offset),
                    _ => {
                        debug!("Invalid seek whence: {}", whence);
                        self.set_register(255, (-1i64) as u64);
                        self.advance_pc();
                        return true;
                    }
                };

                match file.seek(seek_from) {
                    Ok(pos) => {
                        self.set_register(255, pos);
                        debug!(pos, "Seek successful");
                    }
                    Err(_) => {
                        self.set_register(255, (-1i64) as u64);
                        debug!("Seek failed");
                    }
                }
            }
            None => {
                self.set_register(255, (-1i64) as u64);
                debug!(fd, "File not open");
            }
        }
        self.advance_pc();
        true
    }

    /// TRAP 12: Ftell - get file position
    /// Parameter in $255: file descriptor
    /// Returns current position in $255, or -1 on error
    fn handle_ftell(&mut self, _arg: u8) -> bool {
        let fd = self.get_register(255) as u8;

        debug!(fd, "TRAP: Ftell");

        match self.file_handles.get_mut(&fd) {
            Some(file) => match file.stream_position() {
                Ok(pos) => {
                    self.set_register(255, pos);
                    debug!(pos, "Ftell successful");
                }
                Err(_) => {
                    self.set_register(255, (-1i64) as u64);
                    debug!("Ftell failed");
                }
            },
            None => {
                self.set_register(255, (-1i64) as u64);
                debug!(fd, "File not open");
            }
        }
        self.advance_pc();
        true
    }

    fn handle_time(&mut self, unit: u8) -> bool {
        let micros = self.host.now_micros();

        let time_value = match unit {
            0 => micros / 1_000_000, // Seconds (default)
            1 => micros / 1_000,     // Milliseconds
            2 => micros,             // Microseconds
            _ => {
                debug!("Invalid time unit: {}", unit);
                0
            }
        };
        debug!("TRAP: Time (unit={}) => {}", unit, time_value);
        self.set_register(255, time_value);
        self.advance_pc();
        true
    }

    /// Helper function to read a null-terminated C string from memory
    fn read_cstring(&self, addr: u64, max_len: usize) -> String {
        let mut result = String::new();
        for i in 0..max_len {
            let byte = self.read_byte(addr.wrapping_add(i as u64));
            if byte == 0 {
                break;
            }
            result.push(byte as char);
        }
        result
    }

    // ========== Instruction Execution ==========

    /// Execute a single instruction at the current program counter.
    /// Returns true if execution should continue, false if halted.
    #[instrument(skip(self), fields(pc = format!("0x{:X}", self.pc)))]
    pub fn execute_instruction(&mut self) -> bool {
        let (op_byte, x, y, z) = self.fetch_instruction();
        debug!(
            op = format!("0x{:02X}", op_byte),
            x, y, z, "Executing instruction"
        );

        use crate::mmixal::Opcode;
        let opcode = Opcode::try_from(op_byte).unwrap_or_else(|_| {
            panic!("Invalid opcode {:#04x} at PC {:#018x}", op_byte, self.pc);
        });

        self.dispatch(opcode, op_byte, x, y, z)
    }

    /// Decode and run one instruction given its already-resolved opcode and
    /// fields. Split out of [`MMix::execute_instruction`] so `RESUME` can run
    /// the instruction carried in `rX` (§1 rule 4) as if fetched at a chosen
    /// address, with no real memory read.
    fn dispatch(
        &mut self,
        opcode: crate::mmixal::Opcode,
        op_byte: u8,
        x: u8,
        y: u8,
        z: u8,
    ) -> bool {
        use crate::mmixal::Opcode;

        // Operands are read before the destination raises rL. A marginal $Y
        // or $Z still reads as zero when the instruction executes.
        //
        // SAVE is excluded even though its X is a genuine destination: X
        // must already be global, so a legal SAVE never needs this claim,
        // and claiming a local X here would raise rL before SAVE's own
        // rejection runs, breaking its promise to leave a rejected machine
        // unchanged. SAVE's arm validates X itself.
        if Self::writes_general_register_x(op_byte) && opcode != Opcode::SAVE {
            self.claim_local(x);
        }

        match opcode {
            // Floating Point instructions
            Opcode::TRAP => {
                // TRAP X, YZ or TRAP X, Y, Z - Force trap interrupt
                // X = 0 for immediate (YZ), X > 0 for register ($Y, $Z)
                // For immediate form: Y is the trap number, Z is an argument
                if x == 0 {
                    // Immediate TRAP - handle system calls
                    match TrapCode::from_u8(y) {
                        Some(trap) => self.handle_trap(trap, z),
                        None => {
                            debug!(trap_code = y, arg = z, "TRAP: Unhandled trap code");
                            self.host.diagnostic(&format!(
                                "Unhandled TRAP code {} at PC={:#018x}",
                                y, self.pc
                            ));
                            self.advance_pc();
                            true
                        }
                    }
                } else {
                    // Register form - not commonly used for syscalls
                    let trap_val = {
                        let y_val = self.get_register(y);
                        let z_val = self.get_register(z);
                        (y_val << 32) | z_val
                    };
                    self.host.diagnostic(&format!(
                        "Register TRAP x={} y=$ {} z=$ {} val=0x{:016X} at PC={:#018x}",
                        x, y, z, trap_val, self.pc
                    ));
                    self.set_special(SpecialReg::RBB, trap_val);
                    self.advance_pc();
                    false // Halt by default for unhandled register traps
                }
            }
            Opcode::FCMP => {
                // FCMP $X, $Y, $Z - Floating compare. Raises I when an operand is NaN.
                let y_raw = self.get_register(y);
                let z_raw = self.get_register(z);
                let y_val = Self::u64_to_f64(y_raw);
                let z_val = Self::u64_to_f64(z_raw);
                let flags = if y_val.is_nan() || z_val.is_nan() {
                    RA_I
                } else {
                    0
                };
                self.set_register(x, Self::fcmp(y_val, z_val));
                self.raise_exceptions(flags, op_byte, x, y, z, y_raw, z_raw)
            }
            Opcode::FUN => {
                // FUN $X, $Y, $Z - Floating unordered (no exception flag)
                fcmp_rr!(
                    self,
                    x,
                    y,
                    z,
                    |y: f64, z: f64| if y.is_nan() || z.is_nan() { 1 } else { 0 }
                )
            }
            Opcode::FEQL => {
                // FEQL $X, $Y, $Z - Floating equal to (no exception flag)
                fcmp_rr!(self, x, y, z, |y: f64, z: f64| if y == z { 1 } else { 0 })
            }
            Opcode::FADD => {
                let y_val = self.get_register(y);
                let z_val = self.get_register(z);
                let a = Self::u64_to_f64(y_val);
                let b = Self::u64_to_f64(z_val);
                let r_near = a + b;
                let (_, err) = Self::two_sum(a, b);
                // `two_sum` is exact for finite operands, so a zero sum with a
                // zero residual is exact cancellation, not an underflow.
                let (r, flags) = self.finalize_fp_binop(a, b, r_near, err, err == 0.0);
                self.set_register(x, Self::f64_to_u64(r));
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FIX => {
                // FIX $X, Y, $Z - Convert floating to fixed (signed). Raises X
                // on inexact and W when the value is out of i64 range or NaN/Inf.
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("FIX", y),
                };
                // Y is the rounding-mode field, not a register operand.
                let y_val = y as u64;
                let z_val = self.get_register(z);
                let f = Self::u64_to_f64(z_val);
                let rounded = Self::round_with_mode(f, mode);
                let mut flags = 0u64;
                let value = if !f.is_finite() {
                    flags |= RA_W;
                    if f.is_nan() {
                        flags |= RA_I;
                    }
                    0u64
                } else if rounded > i64::MAX as f64 || rounded < i64::MIN as f64 {
                    flags |= RA_W;
                    rounded as i64 as u64
                } else {
                    rounded as i64 as u64
                };
                if rounded != f && f.is_finite() {
                    flags |= RA_X;
                }
                self.set_register(x, value);
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FSUB => {
                let y_val = self.get_register(y);
                let z_val = self.get_register(z);
                let a = Self::u64_to_f64(y_val);
                let b = Self::u64_to_f64(z_val);
                let r_near = a - b;
                let (_, err) = Self::two_sum(a, -b);
                let (r, flags) = self.finalize_fp_binop(a, b, r_near, err, err == 0.0);
                self.set_register(x, Self::f64_to_u64(r));
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FIXU => {
                // FIXU $X, Y, $Z - Convert floating to fixed unsigned
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("FIXU", y),
                };
                // Y is the rounding-mode field, not a register operand.
                let y_val = y as u64;
                let z_val = self.get_register(z);
                let f = Self::u64_to_f64(z_val);
                let rounded = Self::round_with_mode(f, mode);
                let mut flags = 0u64;
                let value = if !f.is_finite() {
                    flags |= RA_W;
                    if f.is_nan() {
                        flags |= RA_I;
                    }
                    0u64
                } else {
                    Self::wrap_to_u64(rounded)
                };
                if rounded != f && f.is_finite() {
                    flags |= RA_X;
                }
                self.set_register(x, value);
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FLOT => {
                // FLOT $X, Y, $Z - Convert fixed to floating (signed)
                i2f_conv_rr!(self, op_byte, x, y, z, true, "FLOT")
            }
            Opcode::FLOTI => {
                // FLOTI $X, Y, Z - Convert fixed to floating immediate (signed)
                i2f_conv_ri!(self, op_byte, x, y, z, true, "FLOTI")
            }
            Opcode::FLOTU => {
                // FLOTU $X, Y, $Z - Convert fixed unsigned to floating
                i2f_conv_rr!(self, op_byte, x, y, z, false, "FLOTU")
            }
            Opcode::FLOTUI => {
                // FLOTUI $X, Y, Z - Convert fixed unsigned to floating immediate
                i2f_conv_ri!(self, op_byte, x, y, z, false, "FLOTUI")
            }
            Opcode::SFLOT => {
                // SFLOT $X, Y, $Z - Convert signed integer to f32 (in f64 register)
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("SFLOT", y),
                };
                // Y is the rounding-mode field, not a register operand.
                let y_val = y as u64;
                let z_val = self.get_register(z);
                let v = z_val as i64;
                let flags = Self::int_to_f64_inexact(v.unsigned_abs());
                let (narrowed, narrow_flags) = self.f64_to_f32_rounded(v as f64, mode);
                self.set_register(x, Self::f64_to_u64(narrowed));
                self.raise_exceptions(flags | narrow_flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::SFLOTI => {
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("SFLOTI", y),
                };
                // Y is the rounding-mode field and Z the literal operand,
                // neither a register.
                let y_val = y as u64;
                let z_val = z as u64;
                let v = (z as i8) as i64;
                let flags = Self::int_to_f64_inexact(v.unsigned_abs());
                let (narrowed, narrow_flags) = self.f64_to_f32_rounded(v as f64, mode);
                self.set_register(x, Self::f64_to_u64(narrowed));
                self.raise_exceptions(flags | narrow_flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::SFLOTU => {
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("SFLOTU", y),
                };
                // Y is the rounding-mode field, not a register operand.
                let y_val = y as u64;
                let v = self.get_register(z);
                let flags = Self::int_to_f64_inexact(v);
                let (narrowed, narrow_flags) = self.f64_to_f32_rounded(v as f64, mode);
                self.set_register(x, Self::f64_to_u64(narrowed));
                self.raise_exceptions(flags | narrow_flags, op_byte, x, y, z, y_val, v)
            }
            Opcode::SFLOTUI => {
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("SFLOTUI", y),
                };
                // Y is the rounding-mode field and Z the literal operand,
                // neither a register.
                let y_val = y as u64;
                let z_val = z as u64;
                let flags = Self::int_to_f64_inexact(z as u64);
                let (narrowed, narrow_flags) = self.f64_to_f32_rounded(z as f64, mode);
                self.set_register(x, Self::f64_to_u64(narrowed));
                self.raise_exceptions(flags | narrow_flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FMUL => {
                let y_val = self.get_register(y);
                let z_val = self.get_register(z);
                let a = Self::u64_to_f64(y_val);
                let b = Self::u64_to_f64(z_val);
                let r_near = a * b;
                // FMA gives the exact residual: a*b - r_near.
                let err = a.mul_add(b, -r_near);
                // A product of nonzero finite operands is never mathematically
                // zero, and the residual cannot witness that: for operands near
                // MIN_POSITIVE the exact product lies below the subnormal range,
                // so the FMA rounds the residual to zero on a real underflow.
                let (r, flags) = self.finalize_fp_binop(a, b, r_near, err, false);
                self.set_register(x, Self::f64_to_u64(r));
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FCMPE => {
                // FCMPE $X, $Y, $Z - the ε-relation: −1 (≺), 0 (∼, an
                // epsilon-close pair), or +1 (≻). Forces 0 and raises I on
                // an exceptional input; never both -1/+1 and I.
                let y_raw = self.get_register(y);
                let z_raw = self.get_register(z);
                let y_val = Self::u64_to_f64(y_raw);
                let z_val = Self::u64_to_f64(z_raw);
                let epsilon = Self::u64_to_f64(self.get_special(SpecialReg::RE));
                let exceptional = Self::epsilon_exceptional(y_val, z_val, epsilon);
                let result = if exceptional
                    || Self::in_epsilon_neighborhood(y_val, z_val, epsilon)
                    || Self::in_epsilon_neighborhood(z_val, y_val, epsilon)
                {
                    0
                } else if y_val < z_val {
                    (-1i64) as u64
                } else {
                    1
                };
                self.set_register(x, result);
                let flags = if exceptional { RA_I } else { 0 };
                self.raise_exceptions(flags, op_byte, x, y, z, y_raw, z_raw)
            }
            Opcode::FUNE => {
                // FUNE $X, $Y, $Z - reports only whether $Y, $Z, or rE is
                // exceptional (NaN operand, or rE NaN/negative); says
                // nothing about proximity, unlike FCMPE/FEQLE's ∼. Exempt
                // from the invalid exception FCMPE/FEQLE raise on that same
                // condition — raises no flag either way.
                let y_val = Self::u64_to_f64(self.get_register(y));
                let z_val = Self::u64_to_f64(self.get_register(z));
                let epsilon = Self::u64_to_f64(self.get_special(SpecialReg::RE));
                let result = if Self::epsilon_exceptional(y_val, z_val, epsilon) {
                    1
                } else {
                    0
                };
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::FEQLE => {
                // FEQLE $X, $Y, $Z - ≈: both directions of Nε membership
                // must hold, stronger than FCMPE's ∼.
                let y_raw = self.get_register(y);
                let z_raw = self.get_register(z);
                let y_val = Self::u64_to_f64(y_raw);
                let z_val = Self::u64_to_f64(z_raw);
                let epsilon = Self::u64_to_f64(self.get_special(SpecialReg::RE));
                let exceptional = Self::epsilon_exceptional(y_val, z_val, epsilon);
                let result = if exceptional {
                    0
                } else if Self::in_epsilon_neighborhood(y_val, z_val, epsilon)
                    && Self::in_epsilon_neighborhood(z_val, y_val, epsilon)
                {
                    1
                } else {
                    0
                };
                self.set_register(x, result);
                let flags = if exceptional { RA_I } else { 0 };
                self.raise_exceptions(flags, op_byte, x, y, z, y_raw, z_raw)
            }
            Opcode::FDIV => {
                let y_val = self.get_register(y);
                let z_val = self.get_register(z);
                let a = Self::u64_to_f64(y_val);
                let b = Self::u64_to_f64(z_val);
                let div_by_zero = if b == 0.0 && !a.is_nan() && a != 0.0 {
                    RA_Z
                } else {
                    0
                };
                let r_near = a / b;
                // residual = a - r_near*b is exact via FMA.
                // sign(true - r_near) = sign(residual) * sign(b).
                let residual = (-r_near).mul_add(b, a);
                let err = if b.is_sign_negative() {
                    -residual
                } else {
                    residual
                };
                // A quotient of nonzero finite operands is never mathematically
                // zero, so a zero result from such operands underflowed.
                let (r, flags) = self.finalize_fp_binop(a, b, r_near, err, false);
                self.set_register(x, Self::f64_to_u64(r));
                self.raise_exceptions(div_by_zero | flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FSQRT => {
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("FSQRT", y),
                };
                // Y is the rounding-mode field, not a register operand.
                let y_val = y as u64;
                let z_val = self.get_register(z);
                let a = Self::u64_to_f64(z_val);
                let r_near = a.sqrt();
                // residual = a - r_near^2, exact via FMA.
                // sign(true - r_near) = sign(residual) when r_near >= 0 (always
                // true here since sqrt returns ≥0 or NaN).
                let err = (-r_near).mul_add(r_near, a);
                let (r, flags) = self.finalize_fp_unop(a, r_near, err, mode);
                self.set_register(x, Self::f64_to_u64(r));
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FREM => {
                // FREM $X, $Y, $Z - IEEE 754 floating remainder.
                let y_val = self.get_register(y);
                let z_val = self.get_register(z);
                let a = Self::u64_to_f64(y_val);
                let b = Self::u64_to_f64(z_val);
                let r = Self::ieee_remainder(a, b);
                let flags = Self::fp_arith_flags(a, b, r);
                self.set_register(x, Self::f64_to_u64(r));
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::FINT => {
                // FINT $X, Y, $Z — Integerize under Y's rounding-mode
                // override, or rA's own mode when Y is 0.
                let mode = match self.resolved_round_mode(y) {
                    Ok(m) => m,
                    Err(()) => return self.illegal_round_mode("FINT", y),
                };
                // Y is the rounding-mode field, not a register operand.
                let y_val = y as u64;
                let z_val = self.get_register(z);
                let v = Self::u64_to_f64(z_val);
                let r = if v.is_finite() {
                    Self::round_with_mode(v, mode)
                } else {
                    v
                };
                let mut flags = 0u64;
                if v.is_nan() {
                    flags |= RA_I;
                } else if v.is_finite() && r != v {
                    flags |= RA_X;
                }
                self.set_register(x, Self::f64_to_u64(r));
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }

            // Load instructions
            Opcode::LDB => {
                // LDB $X, $Y, $Z - Load byte signed
                // s($X) <- s(M[$Y + $Z])
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let byte = self.read_byte(addr);
                let value = (byte as i8) as i64 as u64; // Sign extend
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDBI => {
                // LDB $X, $Y, Z - Load byte signed (immediate)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let byte = self.read_byte(addr);
                let value = (byte as i8) as i64 as u64; // Sign extend
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDBU => {
                // LDBU $X, $Y, $Z - Load byte unsigned
                // u($X) <- M[$Y + $Z]
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let byte = self.read_byte(addr);
                self.set_register(x, byte as u64);
                self.advance_pc();
                true
            }
            Opcode::LDBUI => {
                // LDBU $X, $Y, Z - Load byte unsigned (immediate)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let byte = self.read_byte(addr);
                self.set_register(x, byte as u64);
                self.advance_pc();
                true
            }
            Opcode::LDW => {
                // LDW $X, $Y, $Z - Load wyde signed
                // s($X) <- s(M2[$Y + $Z])
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let wyde = self.read_wyde(addr);
                let value = (wyde as i16) as i64 as u64; // Sign extend
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDWI => {
                // LDW $X, $Y, Z - Load wyde signed (immediate)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let wyde = self.read_wyde(addr);
                let value = (wyde as i16) as i64 as u64; // Sign extend
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDWU => {
                // LDWU $X, $Y, $Z - Load wyde unsigned
                // u($X) <- M2[$Y + $Z]
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let wyde = self.read_wyde(addr);
                self.set_register(x, wyde as u64);
                self.advance_pc();
                true
            }
            Opcode::LDWUI => {
                // LDWU $X, $Y, Z - Load wyde unsigned (immediate)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let wyde = self.read_wyde(addr);
                self.set_register(x, wyde as u64);
                self.advance_pc();
                true
            }
            Opcode::LDT => {
                // LDT $X, $Y, $Z - Load tetra signed
                // s($X) <- s(M4[$Y + $Z])
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let tetra = self.read_tetra(addr);
                let value = (tetra as i32) as i64 as u64; // Sign extend
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDTI => {
                // LDT $X, $Y, Z - Load tetra signed (immediate)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let tetra = self.read_tetra(addr);
                let value = (tetra as i32) as i64 as u64; // Sign extend
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDTU => {
                // LDTU $X, $Y, $Z - Load tetra unsigned
                // u($X) <- M4[$Y + $Z]
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let tetra = self.read_tetra(addr);
                self.set_register(x, tetra as u64);
                self.advance_pc();
                true
            }
            Opcode::LDTUI => {
                // LDTU $X, $Y, Z - Load tetra unsigned (immediate)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let tetra = self.read_tetra(addr);
                self.set_register(x, tetra as u64);
                self.advance_pc();
                true
            }
            Opcode::LDO => {
                // LDO $X, $Y, $Z - Load octa
                // u($X) <- M8[$Y + $Z]
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let octa = self.read_octa(addr);
                self.set_register(x, octa);
                self.advance_pc();
                true
            }
            Opcode::LDOI => {
                // LDO $X, $Y, Z - Load octa (immediate)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let octa = self.read_octa(addr);
                self.set_register(x, octa);
                self.advance_pc();
                true
            }
            Opcode::LDOU => {
                // LDOU $X, $Y, $Z - Load octa unsigned (same as LDO)
                // u($X) <- M8[$Y + $Z]
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let octa = self.read_octa(addr);
                self.set_register(x, octa);
                self.advance_pc();
                true
            }
            Opcode::LDOUI => {
                // LDOU $X, $Y, Z - Load octa unsigned (immediate, same as LDO)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let octa = self.read_octa(addr);
                self.set_register(x, octa);
                self.advance_pc();
                true
            }
            Opcode::LDSF => {
                // LDSF $X, $Y, $Z - Load short float (32-bit float to 64-bit)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let tetra = self.read_tetra(addr);
                let short_float = f32::from_bits(tetra);
                let value = short_float as f64;
                self.set_register(x, Self::f64_to_u64(value));
                self.advance_pc();
                true
            }
            Opcode::LDSFI => {
                // LDSFI $X, $Y, Z - Load short float immediate (32-bit float to 64-bit)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let tetra = self.read_tetra(addr);
                let short_float = f32::from_bits(tetra);
                let value = short_float as f64;
                self.set_register(x, Self::f64_to_u64(value));
                self.advance_pc();
                true
            }
            Opcode::ADDU => {
                // ADDU $X, $Y, $Z
                binop_rr!(self, x, y, z, u64::wrapping_add)
            }
            Opcode::ADDUI => {
                // ADDUI $X, $Y, Z
                binop_ri!(self, x, y, z, u64::wrapping_add)
            }
            // Opcodes 0xE0-0xE3. Each places YZ in its own wyde and zeroes the
            // other 48 bits; the INC/OR/ANDN families below preserve them.
            Opcode::SETH => {
                // SETH $X, YZ - u($X) <- YZ * 2^48
                let yz = ((y as u64) << 8) | (z as u64);
                self.set_register(x, yz << 48);
                self.advance_pc();
                true
            }
            Opcode::SETMH => {
                // SETMH $X, YZ - u($X) <- YZ * 2^32
                let yz = ((y as u64) << 8) | (z as u64);
                self.set_register(x, yz << 32);
                self.advance_pc();
                true
            }
            Opcode::SETML => {
                // SETML $X, YZ - u($X) <- YZ * 2^16
                let yz = ((y as u64) << 8) | (z as u64);
                self.set_register(x, yz << 16);
                self.advance_pc();
                true
            }
            Opcode::SETL => {
                // SETL $X, YZ - u($X) <- YZ
                let yz = ((y as u64) << 8) | (z as u64);
                self.set_register(x, yz);
                self.advance_pc();
                true
            }
            Opcode::INCH => {
                // INCH $X, YZ - Increase by high wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let value = yz << 48;
                let current = self.get_register(x);
                self.set_register(x, current.wrapping_add(value));
                self.advance_pc();
                true
            }
            Opcode::INCMH => {
                // INCMH $X, YZ - Increase by medium high wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let value = yz << 32;
                let current = self.get_register(x);
                self.set_register(x, current.wrapping_add(value));
                self.advance_pc();
                true
            }
            Opcode::INCML => {
                // INCML $X, YZ - Increase by medium low wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let value = yz << 16;
                let current = self.get_register(x);
                self.set_register(x, current.wrapping_add(value));
                self.advance_pc();
                true
            }
            Opcode::INCL => {
                // INCL $X, YZ - Increase by low wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let current = self.get_register(x);
                self.set_register(x, current.wrapping_add(yz));
                self.advance_pc();
                true
            }
            Opcode::ORH => {
                // ORH $X, YZ - OR with high wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let value = yz << 48;
                let current = self.get_register(x);
                self.set_register(x, current | value);
                self.advance_pc();
                true
            }
            Opcode::ORMH => {
                // ORMH $X, YZ - OR with medium high wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let value = yz << 32;
                let current = self.get_register(x);
                self.set_register(x, current | value);
                self.advance_pc();
                true
            }
            Opcode::ORML => {
                // ORML $X, YZ - OR with medium low wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let value = yz << 16;
                let current = self.get_register(x);
                self.set_register(x, current | value);
                self.advance_pc();
                true
            }
            Opcode::ORL => {
                // ORL $X, YZ - OR with low wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let current = self.get_register(x);
                self.set_register(x, current | yz);
                self.advance_pc();
                true
            }
            Opcode::ANDNH => {
                // ANDNH $X, YZ - AND-NOT with high wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let mask = !(yz << 48);
                let current = self.get_register(x);
                self.set_register(x, current & mask);
                self.advance_pc();
                true
            }
            Opcode::ANDNMH => {
                // ANDNMH $X, YZ - AND-NOT with medium high wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let mask = !(yz << 32);
                let current = self.get_register(x);
                self.set_register(x, current & mask);
                self.advance_pc();
                true
            }
            Opcode::ANDNML => {
                // ANDNML $X, YZ - AND-NOT with medium low wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let mask = !(yz << 16);
                let current = self.get_register(x);
                self.set_register(x, current & mask);
                self.advance_pc();
                true
            }
            Opcode::ANDNL => {
                // ANDNL $X, YZ - AND-NOT with low wyde
                let yz = ((y as u64) << 8) | (z as u64);
                let mask = !yz;
                let current = self.get_register(x);
                self.set_register(x, current & mask);
                self.advance_pc();
                true
            }

            // Special Load/Store instructions (0x92-0x9F)
            Opcode::LDHT => {
                // LDHT $X, $Y, $Z - Load high tetra
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let tetra = self.read_tetra(addr);
                let value = (tetra as u64) << 32;
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDHTI => {
                // LDHTI $X, $Y, Z - Load high tetra immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let tetra = self.read_tetra(addr);
                let value = (tetra as u64) << 32;
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::CSWAP => {
                // CSWAP $X, $Y, $Z - Compare and swap octabytes
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let mem_value = self.read_octa(addr);
                let compare_value = self.get_special(SpecialReg::RP);
                if mem_value == compare_value {
                    // Values match, perform swap
                    self.write_octa(addr, self.get_register(x));
                    self.set_register(x, 1); // Success
                } else {
                    // Values don't match: on failure rP <- M8[$Y+$Z], giving the
                    // caller the current value to retry with.
                    self.set_special(SpecialReg::RP, mem_value);
                    self.set_register(x, 0); // Failure
                }
                self.advance_pc();
                true
            }
            Opcode::CSWAPI => {
                // CSWAPI $X, $Y, Z - Compare and swap octabytes immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let mem_value = self.read_octa(addr);
                let compare_value = self.get_special(SpecialReg::RP);
                if mem_value == compare_value {
                    // Values match, perform swap
                    self.write_octa(addr, self.get_register(x));
                    self.set_register(x, 1); // Success
                } else {
                    // Values don't match: on failure rP <- M8[$Y+Z], giving the
                    // caller the current value to retry with.
                    self.set_special(SpecialReg::RP, mem_value);
                    self.set_register(x, 0); // Failure
                }
                self.advance_pc();
                true
            }
            Opcode::LDUNC => {
                // LDUNC $X, $Y, $Z - Load uncached (treat as normal load)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.read_octa(addr);
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDUNCI => {
                // LDUNCI $X, $Y, Z - Load uncached immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.read_octa(addr);
                self.set_register(x, value);
                self.advance_pc();
                true
            }
            Opcode::LDVTS => {
                // LDVTS $X, $Y, $Z - Load virtual translation status (simplified)
                // In a full implementation, this would interact with virtual memory
                // For now, return 0 (no translation)
                self.set_register(x, 0);
                self.advance_pc();
                true
            }
            Opcode::LDVTSI => {
                // LDVTSI $X, $Y, Z - Load virtual translation status immediate
                self.set_register(x, 0);
                self.advance_pc();
                true
            }
            Opcode::PRELD => {
                // PRELD $X, $Y, $Z - Preload data (hint, no-op in simulation)
                self.advance_pc();
                true
            }
            Opcode::PRELDI => {
                // PRELDI $X, $Y, Z - Preload data immediate (hint, no-op)
                self.advance_pc();
                true
            }
            Opcode::PREGO => {
                // PREGO $X, $Y, $Z - Preload to go (hint, no-op in simulation)
                self.advance_pc();
                true
            }
            Opcode::PREGOI => {
                // PREGOI $X, $Y, Z - Preload to go immediate (hint, no-op)
                self.advance_pc();
                true
            }
            Opcode::GO => {
                // GO $X, $Y, $Z - Go to location
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                self.set_register(x, self.pc + 4); // Save return address
                self.pc = addr;
                true
            }
            Opcode::GOI => {
                // GOI $X, $Y, Z - Go to location immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                self.set_register(x, self.pc + 4); // Save return address
                self.pc = addr;
                true
            }

            // Store instructions
            Opcode::STB => {
                // STB $X, $Y, $Z - Store byte (with overflow check). A trip
                // sets rY to the address and rZ to the merged octabyte after
                // the store.
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                let flags = Self::store_overflow_flag(value, i8::MIN as i64, i8::MAX as i64);
                self.write_byte(addr, value as u8);
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STBI => {
                // STB $X, $Y, Z - Store byte immediate (with overflow check)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                let flags = Self::store_overflow_flag(value, i8::MIN as i64, i8::MAX as i64);
                self.write_byte(addr, value as u8);
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STBU => {
                // STBU $X, $Y, $Z - Store byte unsigned (no overflow check)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                self.write_byte(addr, value as u8);
                self.advance_pc();
                true
            }
            Opcode::STBUI => {
                // STBU $X, $Y, Z - Store byte unsigned immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                self.write_byte(addr, value as u8);
                self.advance_pc();
                true
            }
            Opcode::STW => {
                // STW $X, $Y, $Z - Store wyde (with overflow check). A trip
                // sets rY to the address and rZ to the merged octabyte after
                // the store.
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                let flags = Self::store_overflow_flag(value, i16::MIN as i64, i16::MAX as i64);
                self.write_wyde(addr, value as u16);
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STWI => {
                // STW $X, $Y, Z - Store wyde immediate (with overflow check)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                let flags = Self::store_overflow_flag(value, i16::MIN as i64, i16::MAX as i64);
                self.write_wyde(addr, value as u16);
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STWU => {
                // STWU $X, $Y, $Z - Store wyde unsigned (no overflow check)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                self.write_wyde(addr, value as u16);
                self.advance_pc();
                true
            }
            Opcode::STWUI => {
                // STWU $X, $Y, Z - Store wyde unsigned immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                self.write_wyde(addr, value as u16);
                self.advance_pc();
                true
            }
            Opcode::STT => {
                // STT $X, $Y, $Z - Store tetra (with overflow check). A trip
                // sets rY to the address and rZ to the merged octabyte after
                // the store.
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                let flags = Self::store_overflow_flag(value, i32::MIN as i64, i32::MAX as i64);
                self.write_tetra(addr, value as u32);
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STTI => {
                // STT $X, $Y, Z - Store tetra immediate (with overflow check)
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                let flags = Self::store_overflow_flag(value, i32::MIN as i64, i32::MAX as i64);
                self.write_tetra(addr, value as u32);
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STTU => {
                // STTU $X, $Y, $Z - Store tetra unsigned (no overflow check)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                self.write_tetra(addr, value as u32);
                self.advance_pc();
                true
            }
            Opcode::STTUI => {
                // STTU $X, $Y, Z - Store tetra unsigned immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                self.write_tetra(addr, value as u32);
                self.advance_pc();
                true
            }
            Opcode::STO => {
                // STO $X, $Y, $Z - Store octa
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                self.write_octa(addr, value);
                self.advance_pc();
                true
            }
            Opcode::STOI => {
                // STO $X, $Y, Z - Store octa immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                self.write_octa(addr, value);
                self.advance_pc();
                true
            }
            Opcode::STOU => {
                // STOU $X, $Y, $Z - Store octa unsigned (same as STO)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                self.write_octa(addr, value);
                self.advance_pc();
                true
            }
            Opcode::STOUI => {
                // STOU $X, $Y, Z - Store octa unsigned immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                self.write_octa(addr, value);
                self.advance_pc();
                true
            }
            Opcode::STSF => {
                // STSF $X, $Y, $Z - Narrow $X to f32 using rA mode and store at $Y+$Z.
                // No Y-operand override: STSF takes no rounding-mode field.
                // A store trip, so a trip sets rY to the address and rZ to
                // the merged octabyte after the store, per §1 rule 3.
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = Self::u64_to_f64(self.get_register(x));
                let mode = (self.get_special(SpecialReg::RA) >> RA_ROUND_SHIFT) & 0x3;
                let (narrowed, flags) = self.f64_to_f32_rounded(value, mode);
                self.write_tetra(addr, (narrowed as f32).to_bits());
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STSFI => {
                // A store trip: rY takes the address, rZ the merged octabyte
                // after the store, per §1 rule 3.
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = Self::u64_to_f64(self.get_register(x));
                let mode = (self.get_special(SpecialReg::RA) >> RA_ROUND_SHIFT) & 0x3;
                let (narrowed, flags) = self.f64_to_f32_rounded(value, mode);
                self.write_tetra(addr, (narrowed as f32).to_bits());
                let merged = self.merged_store_octa(addr);
                self.raise_exceptions(flags, op_byte, x, y, z, addr, merged)
            }
            Opcode::STHT => {
                // STHT $X, $Y, $Z - Store high tetra
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                let high_tetra = (value >> 32) as u32;
                self.write_tetra(addr, high_tetra);
                self.advance_pc();
                true
            }
            Opcode::STHTI => {
                // STHTI $X, $Y, Z - Store high tetra immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                let high_tetra = (value >> 32) as u32;
                self.write_tetra(addr, high_tetra);
                self.advance_pc();
                true
            }
            Opcode::STCO => {
                // STCO X, $Y, $Z - Store constant octabyte (X is immediate value)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                self.write_octa(addr, x as u64);
                self.advance_pc();
                true
            }
            Opcode::STCOI => {
                // STCOI X, $Y, Z - Store constant octabyte immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                self.write_octa(addr, x as u64);
                self.advance_pc();
                true
            }
            Opcode::STUNC => {
                // STUNC $X, $Y, $Z - Store uncached (treat as normal store)
                let addr = self.get_register(y).wrapping_add(self.get_register(z));
                let value = self.get_register(x);
                self.write_octa(addr, value);
                self.advance_pc();
                true
            }
            Opcode::STUNCI => {
                // STUNCI $X, $Y, Z - Store uncached immediate
                let addr = self.get_register(y).wrapping_add(z as u64);
                let value = self.get_register(x);
                self.write_octa(addr, value);
                self.advance_pc();
                true
            }
            Opcode::SYNCD => {
                // SYNCD X, $Y, $Z - Synchronize data (no-op in simulation)
                self.advance_pc();
                true
            }
            Opcode::SYNCDI => {
                // SYNCDI X, $Y, Z - Synchronize data immediate (no-op)
                self.advance_pc();
                true
            }
            Opcode::PREST => {
                // PREST X, $Y, $Z - Prestore (hint, no-op in simulation)
                self.advance_pc();
                true
            }
            Opcode::PRESTI => {
                // PRESTI X, $Y, Z - Prestore immediate (hint, no-op)
                self.advance_pc();
                true
            }
            Opcode::SYNCID => {
                // SYNCID X, $Y, $Z - Synchronize instruction data (no-op in simulation)
                self.advance_pc();
                true
            }
            Opcode::SYNCIDI => {
                // SYNCIDI X, $Y, Z - Synchronize instruction data immediate (no-op)
                self.advance_pc();
                true
            }
            Opcode::PUSHGO => {
                // PUSHGO $X, $Y, $Z - Push registers and go (absolute target $Y+$Z)
                let target = self.get_register(y).wrapping_add(self.get_register(z));
                self.push_frame(x);
                self.set_pc(target);
                true
            }
            Opcode::PUSHGOI => {
                // PUSHGOI $X, $Y, Z - Push registers and go (absolute target $Y+Z)
                let target = self.get_register(y).wrapping_add(z as u64);
                self.push_frame(x);
                self.set_pc(target);
                true
            }
            // Arithmetic instructions - MUL/DIV opcodes 0x18-0x1F
            Opcode::MUL => {
                // MUL $X, $Y, $Z - Multiply signed with overflow
                mul_rr!(self, op_byte, x, y, z)
            }
            Opcode::MULI => {
                // MULI $X, $Y, Z - Multiply signed immediate with overflow
                mul_ri!(self, op_byte, x, y, z)
            }
            Opcode::MULU => {
                // MULU $X, $Y, $Z - Multiply unsigned
                mulu_rr!(self, x, y, z)
            }
            Opcode::MULUI => {
                // MULUI $X, $Y, Z - Multiply unsigned immediate
                mulu_ri!(self, x, y, z)
            }
            Opcode::DIV => {
                // DIV $X, $Y, $Z - Divide signed
                div_rr!(self, op_byte, x, y, z)
            }
            Opcode::DIVI => {
                // DIVI $X, $Y, Z - Divide signed immediate
                div_ri!(self, op_byte, x, y, z)
            }
            Opcode::DIVU => {
                // DIVU $X, $Y, $Z - Divide unsigned
                divu_rr!(self, x, y, z)
            }
            Opcode::DIVUI => {
                // DIVUI $X, $Y, Z - Divide unsigned immediate
                divu_ri!(self, x, y, z)
            }
            // ADD/SUB and variants - opcodes 0x20-0x2F
            Opcode::ADD => {
                // ADD $X, $Y, $Z - Add signed with overflow check
                add_rr!(self, op_byte, x, y, z)
            }
            Opcode::ADDI => {
                // ADDI $X, $Y, Z - Add signed immediate with overflow check
                add_ri!(self, op_byte, x, y, z)
            }
            // 0x22 and 0x23 are ADDU/ADDUI, already implemented above
            Opcode::SUB => {
                // SUB $X, $Y, $Z - Subtract signed with overflow check
                sub_rr!(self, op_byte, x, y, z)
            }
            Opcode::SUBI => {
                // SUBI $X, $Y, Z - Subtract signed immediate with overflow check
                sub_ri!(self, op_byte, x, y, z)
            }
            Opcode::SUBU => {
                // SUBU $X, $Y, $Z
                binop_rr!(self, x, y, z, u64::wrapping_sub)
            }
            Opcode::SUBUI => {
                // SUBUI $X, $Y, Z
                binop_ri!(self, x, y, z, u64::wrapping_sub)
            }
            Opcode::ADDU2 => {
                // 2ADDU $X, $Y, $Z
                muladd_rr!(self, x, y, z, 2)
            }
            Opcode::ADDU2I => {
                // 2ADDUI $X, $Y, Z
                muladd_ri!(self, x, y, z, 2)
            }
            Opcode::ADDU4 => {
                // 4ADDU $X, $Y, $Z
                muladd_rr!(self, x, y, z, 4)
            }
            Opcode::ADDU4I => {
                // 4ADDUI $X, $Y, Z
                muladd_ri!(self, x, y, z, 4)
            }
            Opcode::ADDU8 => {
                // 8ADDU $X, $Y, $Z
                muladd_rr!(self, x, y, z, 8)
            }
            Opcode::ADDU8I => {
                // 8ADDUI $X, $Y, Z
                muladd_ri!(self, x, y, z, 8)
            }
            Opcode::ADDU16 => {
                // 16ADDU $X, $Y, $Z
                muladd_rr!(self, x, y, z, 16)
            }
            Opcode::ADDU16I => {
                // 16ADDUI $X, $Y, Z
                muladd_ri!(self, x, y, z, 16)
            }
            // CMP instructions - opcodes 0x30-0x33
            Opcode::CMP => {
                // CMP $X, $Y, $Z
                cmp_rr!(self, x, y, z, |v| v as i64)
            }
            Opcode::CMPI => {
                // CMPI $X, $Y, Z
                cmp_ri!(self, x, y, z, |v| v as i64, |v| v as i64)
            }
            Opcode::CMPU => {
                // CMPU $X, $Y, $Z
                cmp_rr!(self, x, y, z, |v| v)
            }
            Opcode::CMPUI => {
                // CMPUI $X, $Y, Z
                cmp_ri!(self, x, y, z, |v| v, |v| v as u64)
            }
            Opcode::NEG => {
                // NEG $X, Y, $Z - Negate with overflow check
                // Y is immediate constant, $Z is register
                let y_val = y as u64;
                let z_val = self.get_register(z);
                let a = y as i64;
                let b = z_val as i64;
                let flags = match a.checked_sub(b) {
                    Some(result) => {
                        self.set_register(x, result as u64);
                        0
                    }
                    None => {
                        self.set_register(x, a.wrapping_sub(b) as u64);
                        RA_V
                    }
                };
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::NEGI => {
                // NEG $X, Y, Z - Negate immediate with overflow check
                // Both Y and Z are immediate constants
                let y_val = y as u64;
                let z_val = z as u64;
                let a = y as i64;
                let b = z as i64;
                let flags = match a.checked_sub(b) {
                    Some(result) => {
                        self.set_register(x, result as u64);
                        0
                    }
                    // Y and Z are bytes, so a - b lies in [-255, 255] and this
                    // arm is unreachable from the immediate encoding. It mirrors
                    // NEG, where s($Z) can carry the difference out of range.
                    None => {
                        self.set_register(x, a.wrapping_sub(b) as u64);
                        RA_V
                    }
                };
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::NEGU => {
                // NEGU $X, Y, $Z - Negate unsigned
                let a = y as u64;
                let b = self.get_register(z);
                self.set_register(x, a.wrapping_sub(b));
                self.advance_pc();
                true
            }
            Opcode::NEGUI => {
                // NEGU $X, Y, Z - Negate unsigned immediate
                let a = y as u64;
                let b = z as u64;
                self.set_register(x, a.wrapping_sub(b));
                self.advance_pc();
                true
            }
            // Shift instructions - opcodes 0x38-0x3F
            Opcode::SL => {
                // SL $X, $Y, $Z - Shift left with overflow check
                let y_val = self.get_register(y);
                let z_val = self.get_register(z);
                let val_y = y_val as i64;
                let shift = z_val;
                let flags = if shift >= 64 {
                    // Shift by 64 or more: result is 0, overflow unless Y was 0
                    self.set_register(x, 0);
                    if val_y != 0 { RA_V } else { 0 }
                } else {
                    let result = (val_y as u64) << shift;
                    self.set_register(x, result);
                    // Overflow exactly when s($Y)·2^u($Z) leaves the signed
                    // range, which is when shifting back does not restore $Y.
                    if ((result as i64) >> shift) != val_y {
                        RA_V
                    } else {
                        0
                    }
                };
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::SLI => {
                // SLI $X, $Y, Z - Shift left immediate with overflow check
                let y_val = self.get_register(y);
                // Z is the literal shift amount, not a register.
                let z_val = z as u64;
                let val_y = y_val as i64;
                let shift = z as u64;
                let flags = if shift >= 64 {
                    self.set_register(x, 0);
                    if val_y != 0 { RA_V } else { 0 }
                } else {
                    let result = (val_y as u64) << shift;
                    self.set_register(x, result);
                    if ((result as i64) >> shift) != val_y {
                        RA_V
                    } else {
                        0
                    }
                };
                self.raise_exceptions(flags, op_byte, x, y, z, y_val, z_val)
            }
            Opcode::SLU => {
                // SLU $X, $Y, $Z - Shift left unsigned (no overflow check)
                let val_y = self.get_register(y);
                let shift = self.get_register(z);
                let result = if shift >= 64 { 0 } else { val_y << shift };
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::SLUI => {
                // SLUI $X, $Y, Z - Shift left unsigned immediate (no overflow check)
                let val_y = self.get_register(y);
                let shift = z as u64;
                let result = if shift >= 64 { 0 } else { val_y << shift };
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::SR => {
                // SR $X, $Y, $Z - Shift right (arithmetic)
                let val_y = self.get_register(y) as i64;
                let shift = self.get_register(z);
                let result = if shift >= 64 {
                    if val_y < 0 { -1i64 as u64 } else { 0 }
                } else {
                    (val_y >> shift) as u64
                };
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::SRI => {
                // SRI $X, $Y, Z - Shift right immediate (arithmetic)
                let val_y = self.get_register(y) as i64;
                let shift = z as u64;
                let result = if shift >= 64 {
                    if val_y < 0 { -1i64 as u64 } else { 0 }
                } else {
                    (val_y >> shift) as u64
                };
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::SRU => {
                // SRU $X, $Y, $Z - Shift right unsigned (logical)
                let val_y = self.get_register(y);
                let shift = self.get_register(z);
                let result = if shift >= 64 { 0 } else { val_y >> shift };
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::SRUI => {
                // SRUI $X, $Y, Z - Shift right unsigned immediate (logical)
                let val_y = self.get_register(y);
                let shift = z as u64;
                let result = if shift >= 64 { 0 } else { val_y >> shift };
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            // Branch instructions - opcodes 0x40-0x5F
            Opcode::BN => {
                // BN $X, $Y, Z - Branch if negative
                let cond = (self.get_register(x) as i64) < 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BNB => {
                // BNB $X, $Y, Z - Branch if negative (backward)
                let cond = (self.get_register(x) as i64) < 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::BZ => {
                // BZ $X, $Y, Z - Branch if zero
                let cond = self.get_register(x) == 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BZB => {
                // BZB $X, $Y, Z - Branch if zero (backward)
                let cond = self.get_register(x) == 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::BP => {
                // BP $X, $Y, Z - Branch if positive
                let cond = (self.get_register(x) as i64) > 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BPB => {
                // BPB $X, $Y, Z - Branch if positive (backward)
                let cond = (self.get_register(x) as i64) > 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::BOD => {
                // BOD $X, $Y, Z - Branch if odd
                let cond = (self.get_register(x) & 1) != 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BODB => {
                // BODB $X, $Y, Z - Branch if odd (backward)
                let cond = (self.get_register(x) & 1) != 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::BNN => {
                // BNN $X, $Y, Z - Branch if non-negative
                let cond = (self.get_register(x) as i64) >= 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BNNB => {
                // BNNB $X, $Y, Z - Branch if non-negative (backward)
                let cond = (self.get_register(x) as i64) >= 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::BNZ => {
                // BNZ $X, $Y, Z - Branch if non-zero
                let cond = self.get_register(x) != 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BNZB => {
                // BNZB $X, $Y, Z - Branch if non-zero (backward)
                let cond = self.get_register(x) != 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::BNP => {
                // BNP $X, $Y, Z - Branch if non-positive
                let cond = (self.get_register(x) as i64) <= 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BNPB => {
                // BNPB $X, $Y, Z - Branch if non-positive (backward)
                let cond = (self.get_register(x) as i64) <= 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::BEV => {
                // BEV $X, $Y, Z - Branch if even
                let cond = (self.get_register(x) & 1) == 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::BEVB => {
                // BEVB $X, $Y, Z - Branch if even (backward)
                let cond = (self.get_register(x) & 1) == 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBN => {
                // PBN $X, $Y, Z - Probable branch if negative
                let cond = (self.get_register(x) as i64) < 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBNB => {
                // PBNB $X, $Y, Z - Probable branch if negative (backward)
                let cond = (self.get_register(x) as i64) < 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBZ => {
                // PBZ $X, $Y, Z - Probable branch if zero
                let cond = self.get_register(x) == 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBZB => {
                // PBZB $X, $Y, Z - Probable branch if zero (backward)
                let cond = self.get_register(x) == 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBP => {
                // PBP $X, $Y, Z - Probable branch if positive
                let cond = (self.get_register(x) as i64) > 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBPB => {
                // PBPB $X, $Y, Z - Probable branch if positive (backward)
                let cond = (self.get_register(x) as i64) > 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBOD => {
                // PBOD $X, $Y, Z - Probable branch if odd
                let cond = (self.get_register(x) & 1) != 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBODB => {
                // PBODB $X, $Y, Z - Probable branch if odd (backward)
                let cond = (self.get_register(x) & 1) != 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBNN => {
                // PBNN $X, $Y, Z - Probable branch if non-negative
                let cond = (self.get_register(x) as i64) >= 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBNNB => {
                // PBNNB $X, $Y, Z - Probable branch if non-negative (backward)
                let cond = (self.get_register(x) as i64) >= 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBNZ => {
                // PBNZ $X, $Y, Z - Probable branch if non-zero
                let cond = self.get_register(x) != 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBNZB => {
                // PBNZB $X, $Y, Z - Probable branch if non-zero (backward)
                let cond = self.get_register(x) != 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBNP => {
                // PBNP $X, $Y, Z - Probable branch if non-positive
                let cond = (self.get_register(x) as i64) <= 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBNPB => {
                // PBNPB $X, $Y, Z - Probable branch if non-positive (backward)
                let cond = (self.get_register(x) as i64) <= 0;
                self.branch_backward(cond, y, z);
                true
            }
            Opcode::PBEV => {
                // PBEV $X, $Y, Z - Probable branch if even
                let cond = (self.get_register(x) & 1) == 0;
                self.branch_forward(cond, y, z);
                true
            }
            Opcode::PBEVB => {
                // PBEVB $X, $Y, Z - Probable branch if even (backward)
                let cond = (self.get_register(x) & 1) == 0;
                self.branch_backward(cond, y, z);
                true
            }
            // Conditional Set instructions - opcodes 0x60-0x6F
            Opcode::CSN => {
                // CSN $X, $Y, $Z - Conditional Set if Negative (checks $Y)
                let cond = (self.get_register(y) as i64) < 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSNI => {
                // CSNI $X, $Y, Z - Conditional Set if Negative (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) < 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }
            Opcode::CSZ => {
                // CSZ $X, $Y, $Z - Conditional Set if Zero (checks $Y)
                let cond = self.get_register(y) == 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSZI => {
                // CSZI $X, $Y, Z - Conditional Set if Zero (immediate, checks $Y)
                let cond = self.get_register(y) == 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }
            Opcode::CSP => {
                // CSP $X, $Y, $Z - Conditional Set if Positive (checks $Y)
                let cond = (self.get_register(y) as i64) > 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSPI => {
                // CSPI $X, $Y, Z - Conditional Set if Positive (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) > 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }
            Opcode::CSOD => {
                // CSOD $X, $Y, $Z - Conditional Set if Odd (checks $Y)
                let cond = (self.get_register(y) & 1) != 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSODI => {
                // CSODI $X, $Y, Z - Conditional Set if Odd (immediate, checks $Y)
                let cond = (self.get_register(y) & 1) != 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }
            Opcode::CSNN => {
                // CSNN $X, $Y, $Z - Conditional Set if Non-Negative (checks $Y)
                let cond = (self.get_register(y) as i64) >= 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSNNI => {
                // CSNNI $X, $Y, Z - Conditional Set if Non-Negative (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) >= 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }
            Opcode::CSNZ => {
                // CSNZ $X, $Y, $Z - Conditional Set if Non-Zero (checks $Y)
                let cond = self.get_register(y) != 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSNZI => {
                // CSNZI $X, $Y, Z - Conditional Set if Non-Zero (immediate, checks $Y)
                let cond = self.get_register(y) != 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }
            Opcode::CSNP => {
                // CSNP $X, $Y, $Z - Conditional Set if Non-Positive (checks $Y)
                let cond = (self.get_register(y) as i64) <= 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSNPI => {
                // CSNPI $X, $Y, Z - Conditional Set if Non-Positive (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) <= 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }
            Opcode::CSEV => {
                // CSEV $X, $Y, $Z - Conditional Set if Even (checks $Y)
                let cond = (self.get_register(y) & 1) == 0;
                self.cond_set_rr(x, y, z, cond);
                true
            }
            Opcode::CSEVI => {
                // CSEVI $X, $Y, Z - Conditional Set if Even (immediate, checks $Y)
                let cond = (self.get_register(y) & 1) == 0;
                self.cond_set_ri(x, y, z, cond);
                true
            }

            // Zero or Set instructions (0x70-0x7F)
            Opcode::ZSN => {
                // ZSN $X, $Y, $Z - Zero or Set if Negative (checks $Y)
                let cond = (self.get_register(y) as i64) < 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSNI => {
                // ZSNI $X, $Y, Z - Zero or Set if Negative (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) < 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }
            Opcode::ZSZ => {
                // ZSZ $X, $Y, $Z - Zero or Set if Zero (checks $Y)
                let cond = self.get_register(y) == 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSZI => {
                // ZSZI $X, $Y, Z - Zero or Set if Zero (immediate, checks $Y)
                let cond = self.get_register(y) == 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }
            Opcode::ZSP => {
                // ZSP $X, $Y, $Z - Zero or Set if Positive (checks $Y)
                let cond = (self.get_register(y) as i64) > 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSPI => {
                // ZSPI $X, $Y, Z - Zero or Set if Positive (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) > 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }
            Opcode::ZSOD => {
                // ZSOD $X, $Y, $Z - Zero or Set if Odd (checks $Y)
                let cond = (self.get_register(y) & 1) != 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSODI => {
                // ZSODI $X, $Y, Z - Zero or Set if Odd (immediate, checks $Y)
                let cond = (self.get_register(y) & 1) != 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }
            Opcode::ZSNN => {
                // ZSNN $X, $Y, $Z - Zero or Set if Non-Negative (checks $Y)
                let cond = (self.get_register(y) as i64) >= 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSNNI => {
                // ZSNNI $X, $Y, Z - Zero or Set if Non-Negative (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) >= 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }
            Opcode::ZSNZ => {
                // ZSNZ $X, $Y, $Z - Zero or Set if Non-Zero (checks $Y)
                let cond = self.get_register(y) != 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSNZI => {
                // ZSNZI $X, $Y, Z - Zero or Set if Non-Zero (immediate, checks $Y)
                let cond = self.get_register(y) != 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }
            Opcode::ZSNP => {
                // ZSNP $X, $Y, $Z - Zero or Set if Non-Positive (checks $Y)
                let cond = (self.get_register(y) as i64) <= 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSNPI => {
                // ZSNPI $X, $Y, Z - Zero or Set if Non-Positive (immediate, checks $Y)
                let cond = (self.get_register(y) as i64) <= 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }
            Opcode::ZSEV => {
                // ZSEV $X, $Y, $Z - Zero or Set if Even (checks $Y)
                let cond = (self.get_register(y) & 1) == 0;
                self.zero_set_rr(x, y, z, cond);
                true
            }
            Opcode::ZSEVI => {
                // ZSEVI $X, $Y, Z - Zero or Set if Even (immediate, checks $Y)
                let cond = (self.get_register(y) & 1) == 0;
                self.zero_set_ri(x, y, z, cond);
                true
            }

            // Bitwise operations - opcodes 0xC0-0xCF, 0xD8-0xD9
            Opcode::OR => {
                // OR $X, $Y, $Z
                binop_rr!(self, x, y, z, |a, b| a | b)
            }
            Opcode::ORI => {
                // ORI $X, $Y, Z
                binop_ri!(self, x, y, z, |a, b| a | b)
            }
            Opcode::ORN => {
                // ORN $X, $Y, $Z
                binop_rr!(self, x, y, z, |a: u64, b: u64| a | !b)
            }
            Opcode::ORNI => {
                // ORNI $X, $Y, Z
                binop_ri!(self, x, y, z, |a: u64, b: u64| a | !b)
            }
            Opcode::NOR => {
                // NOR $X, $Y, $Z
                binop_rr!(self, x, y, z, |a: u64, b: u64| !(a | b))
            }
            Opcode::NORI => {
                // NORI $X, $Y, Z
                binop_ri!(self, x, y, z, |a: u64, b: u64| !(a | b))
            }
            Opcode::XOR => {
                // XOR $X, $Y, $Z
                binop_rr!(self, x, y, z, |a, b| a ^ b)
            }
            Opcode::XORI => {
                // XORI $X, $Y, Z
                binop_ri!(self, x, y, z, |a, b| a ^ b)
            }
            Opcode::AND => {
                // AND $X, $Y, $Z
                binop_rr!(self, x, y, z, |a, b| a & b)
            }
            Opcode::ANDI => {
                // ANDI $X, $Y, Z
                binop_ri!(self, x, y, z, |a, b| a & b)
            }
            Opcode::ANDN => {
                // ANDN $X, $Y, $Z
                binop_rr!(self, x, y, z, |a: u64, b: u64| a & !b)
            }
            Opcode::ANDNI => {
                // ANDNI $X, $Y, Z
                binop_ri!(self, x, y, z, |a: u64, b: u64| a & !b)
            }
            Opcode::NAND => {
                // NAND $X, $Y, $Z
                binop_rr!(self, x, y, z, |a: u64, b: u64| !(a & b))
            }
            Opcode::NANDI => {
                // NANDI $X, $Y, Z
                binop_ri!(self, x, y, z, |a: u64, b: u64| !(a & b))
            }
            Opcode::NXOR => {
                // NXOR $X, $Y, $Z
                binop_rr!(self, x, y, z, |a: u64, b: u64| !(a ^ b))
            }
            Opcode::NXORI => {
                // NXORI $X, $Y, Z
                binop_ri!(self, x, y, z, |a: u64, b: u64| !(a ^ b))
            }
            // Bit fiddling operations - opcodes 0xD0-0xDF
            Opcode::BDIF => {
                // BDIF $X, $Y, $Z - Byte difference
                let val_y = self.get_register(y);
                let val_z = self.get_register(z);
                let mut result: u64 = 0;
                for i in 0..8 {
                    let byte_y = ((val_y >> (i * 8)) & 0xFF) as u8;
                    let byte_z = ((val_z >> (i * 8)) & 0xFF) as u8;
                    let diff = byte_y.saturating_sub(byte_z);
                    result |= (diff as u64) << (i * 8);
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::BDIFI => {
                // BDIFI $X, $Y, Z - Byte difference immediate
                let val_y = self.get_register(y);
                let mut result: u64 = 0;
                for i in 0..8 {
                    let byte_y = ((val_y >> (i * 8)) & 0xFF) as u8;
                    let diff = byte_y.saturating_sub(z);
                    result |= (diff as u64) << (i * 8);
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::WDIF => {
                // WDIF $X, $Y, $Z - Wyde difference
                let val_y = self.get_register(y);
                let val_z = self.get_register(z);
                let mut result: u64 = 0;
                for i in 0..4 {
                    let wyde_y = ((val_y >> (i * 16)) & 0xFFFF) as u16;
                    let wyde_z = ((val_z >> (i * 16)) & 0xFFFF) as u16;
                    let diff = wyde_y.saturating_sub(wyde_z);
                    result |= (diff as u64) << (i * 16);
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::WDIFI => {
                // WDIFI $X, $Y, Z - Wyde difference immediate
                let val_y = self.get_register(y);
                let z_wyde = z as u16;
                let mut result: u64 = 0;
                for i in 0..4 {
                    let wyde_y = ((val_y >> (i * 16)) & 0xFFFF) as u16;
                    let diff = wyde_y.saturating_sub(z_wyde);
                    result |= (diff as u64) << (i * 16);
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::TDIF => {
                // TDIF $X, $Y, $Z - Tetra difference
                let val_y = self.get_register(y);
                let val_z = self.get_register(z);
                let mut result: u64 = 0;
                for i in 0..2 {
                    let tetra_y = ((val_y >> (i * 32)) & 0xFFFFFFFF) as u32;
                    let tetra_z = ((val_z >> (i * 32)) & 0xFFFFFFFF) as u32;
                    let diff = tetra_y.saturating_sub(tetra_z);
                    result |= (diff as u64) << (i * 32);
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::TDIFI => {
                // TDIFI $X, $Y, Z - Tetra difference immediate
                let val_y = self.get_register(y);
                let z_tetra = z as u32;
                let mut result: u64 = 0;
                for i in 0..2 {
                    let tetra_y = ((val_y >> (i * 32)) & 0xFFFFFFFF) as u32;
                    let diff = tetra_y.saturating_sub(z_tetra);
                    result |= (diff as u64) << (i * 32);
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::ODIF => {
                // ODIF $X, $Y, $Z
                binop_rr!(self, x, y, z, u64::saturating_sub)
            }
            Opcode::ODIFI => {
                // ODIFI $X, $Y, Z
                binop_ri!(self, x, y, z, u64::saturating_sub)
            }
            Opcode::SADD => {
                // SADD $X, $Y, $Z
                binop_rr!(self, x, y, z, |a: u64, b: u64| (a & !b).count_ones() as u64)
            }
            Opcode::SADDI => {
                // SADDI $X, $Y, Z
                binop_ri!(self, x, y, z, |a: u64, b: u64| (a & !b).count_ones() as u64)
            }
            Opcode::MOR => {
                // MOR $X, $Y, $Z - Multiple or (Boolean matrix multiplication)
                let val_y = self.get_register(y);
                let val_z = self.get_register(z);
                let mut result: u64 = 0;
                for i in 0..8 {
                    for j in 0..8 {
                        let mut bit = false;
                        for k in 0..8 {
                            let y_bit = (val_y >> (k * 8 + j)) & 1;
                            let z_bit = (val_z >> (i * 8 + k)) & 1;
                            if y_bit != 0 && z_bit != 0 {
                                bit = true;
                                break;
                            }
                        }
                        if bit {
                            result |= 1 << (i * 8 + j);
                        }
                    }
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::MORI => {
                // MORI $X, $Y, Z - Multiple or immediate
                let val_y = self.get_register(y);
                let mut result: u64 = 0;
                // For immediate form, only bottom byte of result is non-zero
                for j in 0..8 {
                    let mut bit = false;
                    for k in 0..8 {
                        let y_bit = (val_y >> (k * 8 + j)) & 1;
                        let z_bit = (z >> k) & 1;
                        if y_bit != 0 && z_bit != 0 {
                            bit = true;
                            break;
                        }
                    }
                    if bit {
                        result |= 1 << j;
                    }
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::MXOR => {
                // MXOR $X, $Y, $Z - Multiple exclusive-or (matrix product over GF(2))
                let val_y = self.get_register(y);
                let val_z = self.get_register(z);
                let mut result: u64 = 0;
                for i in 0..8 {
                    for j in 0..8 {
                        let mut bit = false;
                        for k in 0..8 {
                            let y_bit = (val_y >> (k * 8 + j)) & 1;
                            let z_bit = (val_z >> (i * 8 + k)) & 1;
                            if y_bit != 0 && z_bit != 0 {
                                bit = !bit;
                            }
                        }
                        if bit {
                            result |= 1 << (i * 8 + j);
                        }
                    }
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::MXORI => {
                // MXORI $X, $Y, Z - Multiple exclusive-or immediate
                let val_y = self.get_register(y);
                let mut result: u64 = 0;
                for j in 0..8 {
                    let mut bit = false;
                    for k in 0..8 {
                        let y_bit = (val_y >> (k * 8 + j)) & 1;
                        let z_bit = (z >> k) & 1;
                        if y_bit != 0 && z_bit != 0 {
                            bit = !bit;
                        }
                    }
                    if bit {
                        result |= 1 << j;
                    }
                }
                self.set_register(x, result);
                self.advance_pc();
                true
            }
            Opcode::MUX => {
                // MUX $X, $Y, $Z - Bitwise multiplex
                let val_y = self.get_register(y);
                let val_z = self.get_register(z);
                let mask = self.special_regs[SpecialReg::RM as usize];
                self.set_register(x, (val_y & mask) | (val_z & !mask));
                self.advance_pc();
                true
            }
            Opcode::MUXI => {
                // MUXI $X, $Y, Z - Bitwise multiplex immediate
                let val_y = self.get_register(y);
                let mask = self.special_regs[SpecialReg::RM as usize];
                self.set_register(x, (val_y & mask) | ((z as u64) & !mask));
                self.advance_pc();
                true
            }
            // Jump/Stack/System instructions - opcodes 0xF0-0xFF
            Opcode::JMP => {
                // JMP XYZ - Jump to PC + 4*XYZ.
                let xyz = ((x as u32) << 16) | ((y as u32) << 8) | (z as u32);
                self.pc = self.pc.wrapping_add((xyz as u64) * 4);
                true
            }
            Opcode::JMPB => {
                // JMPB XYZ - Jump to PC + 4*(XYZ - 2^24).
                let xyz = ((x as u32) << 16) | ((y as u32) << 8) | (z as u32);
                let offset = xyz as i64 - (1 << 24);
                self.pc = self.pc.wrapping_add((offset * 4) as u64);
                true
            }
            Opcode::PUSHJ => {
                // PUSHJ $X, YZ - Push registers and jump to PC + 4*YZ.
                let pc_at_inst = self.pc;
                self.push_frame(x);
                let yz = ((y as u16) << 8) | z as u16;
                self.pc = pc_at_inst.wrapping_add((yz as u64) * 4);
                true
            }
            Opcode::PUSHJB => {
                // PUSHJB $X, YZ - Push registers and jump to PC + 4*(YZ - 65536).
                let pc_at_inst = self.pc;
                self.push_frame(x);
                let yz = ((y as u16) << 8) | z as u16;
                let offset = yz as i64 - 65536;
                self.pc = pc_at_inst.wrapping_add((offset * 4) as u64);
                true
            }
            Opcode::GETA => {
                // GETA $X, YZ - Address PC + 4*YZ.
                let yz = ((y as u16) << 8) | z as u16;
                let addr = self.pc.wrapping_add((yz as u64) * 4);
                self.set_register(x, addr);
                self.advance_pc();
                true
            }
            Opcode::GETAB => {
                // GETAB $X, YZ - Address PC + 4*(YZ - 65536).
                let yz = ((y as u16) << 8) | z as u16;
                let offset = yz as i64 - 65536;
                let addr = self.pc.wrapping_add((offset * 4) as u64);
                self.set_register(x, addr);
                self.advance_pc();
                true
            }
            Opcode::PUT => {
                // PUT X, $Z - Put $Z into special register X.
                let value = self.get_register(z);
                if !self.put_special("PUT", x, value) {
                    return false;
                }
                self.advance_pc();
                true
            }
            Opcode::PUTI => {
                // PUT X, Z - Put immediate Z into special register X. Y is
                // ignored; the value is Z alone, eight bits.
                if !self.put_special("PUTI", x, z as u64) {
                    return false;
                }
                self.advance_pc();
                true
            }
            Opcode::POP => {
                // POP X, YZ - Pop frame and return.
                // Puts the callee's last output in the hole and the rest
                // above it in order, restores caller's locals below the
                // hole, and branches to rJ + 4·YZ. rJ itself is untouched;
                // a subroutine that calls another must save and restore it.
                let yz = ((y as u16) << 8) | z as u16;
                match self.pop_frame(x, yz) {
                    PopFrame::Frame(target) => {
                        self.pc = target;
                        true
                    }
                    PopFrame::NoFrame => {
                        // No frame to pop: branch via current rJ as a defensive fallback.
                        self.pc = self
                            .get_special(SpecialReg::RJ)
                            .wrapping_add((yz as u64) * 4);
                        true
                    }
                    PopFrame::Rejected => false,
                }
            }
            Opcode::RESUME => {
                // RESUME Z (gitraptrip.html "RESUME"; §1 rule 4): X and Y
                // are always zero, so only Z varies. Z != 0 is RESUME 1,
                // which restores from the kernel's rWW/rXX/rYY/rZZ and is
                // privileged. rX < 0 resumes at rW. Otherwise rX's top byte
                // is the ropcode: 0 inserts rX's instruction as if it stood
                // at rW-4 and resumes at rW; 1 substitutes rY/rZ into an
                // interruptible instruction; 2 serves forced-trap emulation;
                // 3 inserts a page-table entry. checksmix has no
                // interruptible instruction, no emulated opcode and no page
                // table, so ropcodes 1-3 never arise legitimately. Each
                // unsupported form halts through the shared MMix::reject
                // path: diagnostic, false, PC unmoved.
                if z != 0 {
                    return self.reject(&format!(
                        "RESUME {z}: privileged form (RESUME 1) at PC={:#018x}",
                        self.pc
                    ));
                }
                let rx = self.get_special(SpecialReg::RX);
                if (rx as i64) < 0 {
                    self.pc = self.get_special(SpecialReg::RW);
                    return true;
                }
                let ropcode = rx >> 56;
                if ropcode != 0 {
                    return self.reject(&format!(
                        "RESUME: ropcode {ropcode} at PC={:#018x} \
                         (only ropcode 0 and rX < 0 are supported)",
                        self.pc
                    ));
                }
                let word = rx as u32;
                let ins_op = (word >> 24) as u8;
                let ins_x = (word >> 16) as u8;
                let ins_y = (word >> 8) as u8;
                let ins_z = word as u8;
                let ins_opcode = match Opcode::try_from(ins_op) {
                    Ok(op) => op,
                    Err(_) => {
                        return self.reject(&format!(
                            "RESUME: invalid opcode {ins_op:#04x} in rX at PC={:#018x}",
                            self.pc
                        ));
                    }
                };
                self.pc = self.get_special(SpecialReg::RW).wrapping_sub(4);
                self.dispatch(ins_opcode, ins_op, ins_x, ins_y, ins_z)
            }
            Opcode::SAVE => {
                // SAVE $X,0 - push the machine's context onto the register
                // stack. See MMix::save_context.
                if !self.save_context(x) {
                    return false;
                }
                self.advance_pc();
                true
            }
            Opcode::UNSAVE => {
                // UNSAVE 0,$Z - restore the context $Z addresses. See
                // MMix::unsave_context.
                let packed_addr = self.get_register(z);
                if !self.unsave_context(packed_addr) {
                    return false;
                }
                self.advance_pc();
                true
            }
            Opcode::SYNC => {
                // SYNC XYZ - Synchronize
                // Memory synchronization barrier
                // For a simulator, this is typically a no-op
                self.advance_pc();
                true
            }
            Opcode::SWYM => {
                // SWYM XYZ - Sympathize with your machinery (no-op)
                self.advance_pc();
                true
            }
            Opcode::GET => {
                // GET $X, $Z - Get from special register
                let special_reg_num = z;
                if let Some(special_reg) = SpecialReg::from_u8(special_reg_num) {
                    let value = self.get_special(special_reg);
                    self.set_register(x, value);
                }
                self.advance_pc();
                true
            }
            Opcode::TRIP => {
                // TRIP X,Y,Z: user trip to the handler at #00 (trip.html;
                // §1 rule 3).
                let y_val = self.get_register(y);
                let z_val = self.get_register(z);
                self.trip(0x00, "TRIP", op_byte, x, y, z, y_val, z_val)
            }
        }
    }

    /// Execute instructions starting from the current PC until a halt condition.
    /// Returns the number of instructions executed.
    #[instrument(skip(self))]
    pub fn run(&mut self) -> usize {
        self.run_bounded(usize::MAX).0
    }

    /// Execute instructions starting from the current PC until the machine
    /// halts or `budget` instructions have run, whichever comes first.
    /// Returns the instruction count and which condition stopped it.
    ///
    /// `MMix` has no breakpoint concept, so the result is never
    /// [`Stop::Breakpoint`] — that variant exists for [`crate::Debugger`]'s
    /// use.
    #[instrument(skip(self))]
    pub fn run_bounded(&mut self, budget: usize) -> (usize, Stop) {
        debug!("Starting MMIX execution");
        let mut count = 0;
        let stop = loop {
            if count >= budget {
                break Stop::BudgetExhausted;
            }
            if !self.execute_instruction() {
                break Stop::Halted;
            }
            count += 1;
        };
        match stop {
            Stop::Halted => self.host.diagnostic(&format!(
                "Execution stopped at PC={:#018x} after {} instructions",
                self.pc, count
            )),
            Stop::BudgetExhausted => self.host.diagnostic(&format!(
                "Execution paused at PC={:#018x} after {} instructions (budget exhausted)",
                self.pc, count
            )),
            Stop::Breakpoint(_) => unreachable!("run_bounded never returns Stop::Breakpoint"),
        }
        debug!(instruction_count = count, "Execution completed");
        (count, stop)
    }
}

/// Why [`MMix::run_bounded`] or a [`crate::Debugger`] step loop stopped.
///
/// More variants may be added in future releases, so downstream matches
/// must carry a wildcard arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Stop {
    /// The machine halted (TRAP 0, an unhandled TRIP, or an unhandled
    /// register trap — `execute_instruction` returning `false` covers all
    /// three with no finer distinction).
    Halted,
    /// The instruction budget ran out before the machine halted. The
    /// machine is unchanged; resuming from here is calling the same
    /// bounded-run method again.
    BudgetExhausted,
    /// A breakpoint address was reached. `MMix` itself has no breakpoint
    /// concept, so [`MMix::run_bounded`] never produces this — it exists for
    /// [`crate::Debugger`], which owns the breakpoint set.
    Breakpoint(u64),
}

impl fmt::Display for MMix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_with_mode(f, ValueFormat::Signed)
    }
}

#[derive(Copy, Clone)]
pub enum ValueFormat {
    Signed,
    Unsigned,
}

pub struct MMixDisplay<'a> {
    mmix: &'a MMix,
    format: ValueFormat,
}

fn display_value(value: u64, format: ValueFormat) -> String {
    match format {
        ValueFormat::Signed => (value as i64).to_string(),
        ValueFormat::Unsigned => value.to_string(),
    }
}

impl<'a> fmt::Display for MMixDisplay<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.mmix.fmt_with_mode(f, self.format)
    }
}

impl MMix {
    pub fn display_with(&self, format: ValueFormat) -> MMixDisplay<'_> {
        MMixDisplay { mmix: self, format }
    }

    fn fmt_with_mode(&self, f: &mut fmt::Formatter<'_>, format: ValueFormat) -> fmt::Result {
        writeln!(f, "MMIX Computer State:")?;
        writeln!(f, "  PC = {:#018x}", self.pc)?;
        writeln!(f)?;

        // Display non-zero general registers
        writeln!(f, "General Registers:")?;
        let mut any_nonzero = false;
        for (i, &value) in self.general_regs.iter().enumerate() {
            if value != 0 {
                writeln!(
                    f,
                    "  ${:<3} = {:#018x} ({})",
                    i,
                    value,
                    display_value(value, format)
                )?;
                any_nonzero = true;
            }
        }
        if !any_nonzero {
            writeln!(f, "  (all zero)")?;
        }
        writeln!(f)?;

        // Display non-zero special registers
        writeln!(f, "Special Registers:")?;
        any_nonzero = false;
        for (i, &value) in self.special_regs.iter().enumerate() {
            if value != 0 {
                let name = match SpecialReg::from_u8(i as u8) {
                    Some(reg) => reg.name(),
                    // No register carries this number; still show the value.
                    None => "r??",
                };
                writeln!(
                    f,
                    "  {:<4} = {:#018x} ({})",
                    name,
                    value,
                    display_value(value, format)
                )?;
                any_nonzero = true;
            }
        }
        if !any_nonzero {
            writeln!(f, "  (all zero)")?;
        }
        writeln!(f)?;

        // Display memory usage
        writeln!(f, "Memory: {} bytes used", self.memory.len())?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;

    /// What a `CaptureHost` records, shared with the test via `CaptureHandle`.
    #[derive(Default)]
    struct CaptureLog {
        stdout: Vec<u8>,
        stderr: Vec<u8>,
        diagnostics: Vec<String>,
        traps: Vec<(TrapCode, u8, u64, u64)>,
        flushes: usize,
    }

    /// A clone of a `CaptureHost`'s buffers, held by the test after the host
    /// is moved into `MMix::with_host`.
    #[derive(Clone, Default)]
    struct CaptureHandle(Rc<RefCell<CaptureLog>>);

    impl CaptureHandle {
        fn stdout(&self) -> Vec<u8> {
            self.0.borrow().stdout.clone()
        }

        fn stderr(&self) -> Vec<u8> {
            self.0.borrow().stderr.clone()
        }

        fn diagnostics(&self) -> Vec<String> {
            self.0.borrow().diagnostics.clone()
        }

        fn traps(&self) -> Vec<(TrapCode, u8, u64, u64)> {
            self.0.borrow().traps.clone()
        }

        fn flushes(&self) -> usize {
            self.0.borrow().flushes
        }
    }

    /// A `Host` that records writes, diagnostics, and trap events instead of
    /// sending them to the process, and reports a fixed clock rather than
    /// `SystemTime::now()`.
    struct CaptureHost {
        log: Rc<RefCell<CaptureLog>>,
        clock_micros: u64,
    }

    impl CaptureHost {
        fn new() -> (Self, CaptureHandle) {
            let log = Rc::new(RefCell::new(CaptureLog::default()));
            let handle = CaptureHandle(log.clone());
            (
                Self {
                    log,
                    clock_micros: 0,
                },
                handle,
            )
        }

        fn with_clock(clock_micros: u64) -> (Self, CaptureHandle) {
            let (mut host, handle) = Self::new();
            host.clock_micros = clock_micros;
            (host, handle)
        }
    }

    impl Host for CaptureHost {
        fn write(&mut self, fd: u8, bytes: &[u8]) -> std::io::Result<()> {
            let mut log = self.log.borrow_mut();
            match fd {
                1 => log.stdout.extend_from_slice(bytes),
                2 => log.stderr.extend_from_slice(bytes),
                _ => return Err(std::io::Error::other("CaptureHost: unsupported fd")),
            }
            Ok(())
        }

        fn flush(&mut self) {
            self.log.borrow_mut().flushes += 1;
        }

        fn now_micros(&mut self) -> u64 {
            self.clock_micros
        }

        fn diagnostic(&mut self, msg: &str) {
            self.log.borrow_mut().diagnostics.push(msg.to_string());
        }

        fn trap(&mut self, code: TrapCode, arg: u8, arg255: u64, result255: u64) {
            self.log
                .borrow_mut()
                .traps
                .push((code, arg, arg255, result255));
        }
    }

    #[test]
    fn test_mmix_new() {
        let mmix = MMix::new();
        assert_eq!(mmix.get_register(0), 0);
        assert_eq!(mmix.get_register(255), 0);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
        assert_eq!(mmix.get_pc(), 0);
    }

    #[test]
    fn test_general_registers() {
        let mut mmix = MMix::new();
        mmix.set_register(1, 0x123456789ABCDEF0);
        assert_eq!(mmix.get_register(1), 0x123456789ABCDEF0);
        assert_eq!(mmix.get_register(2), 0);
    }

    #[test]
    fn test_special_registers() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RR, 42);
        assert_eq!(mmix.get_special(SpecialReg::RR), 42);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
    }

    #[test]
    fn test_memory_byte() {
        let mut mmix = MMix::new();
        mmix.write_byte(0x1000, 0x42);
        assert_eq!(mmix.read_byte(0x1000), 0x42);
        assert_eq!(mmix.read_byte(0x1001), 0);
    }

    #[test]
    fn test_memory_wyde() {
        let mut mmix = MMix::new();
        mmix.write_wyde(0x1000, 0x1234);
        assert_eq!(mmix.read_wyde(0x1000), 0x1234);
        assert_eq!(mmix.read_byte(0x1000), 0x12);
        assert_eq!(mmix.read_byte(0x1001), 0x34);
    }

    #[test]
    fn test_memory_tetra() {
        let mut mmix = MMix::new();
        mmix.write_tetra(0x1000, 0x12345678);
        assert_eq!(mmix.read_tetra(0x1000), 0x12345678);
    }

    #[test]
    fn test_memory_octa() {
        let mut mmix = MMix::new();
        mmix.write_octa(0x1000, 0x123456789ABCDEF0);
        assert_eq!(mmix.read_octa(0x1000), 0x123456789ABCDEF0);
    }

    #[test]
    fn test_fetch_instruction() {
        let mut mmix = MMix::new();
        // Store instruction #20010203 (ADD $1, $2, $3)
        mmix.write_tetra(0, 0x20010203);
        let (op, x, y, z) = mmix.fetch_instruction();
        assert_eq!(op, 0x20);
        assert_eq!(x, 0x01);
        assert_eq!(y, 0x02);
        assert_eq!(z, 0x03);
    }

    #[test]
    fn test_pc_operations() {
        let mut mmix = MMix::new();
        assert_eq!(mmix.get_pc(), 0);
        mmix.set_pc(0x1000);
        assert_eq!(mmix.get_pc(), 0x1000);
        mmix.advance_pc();
        assert_eq!(mmix.get_pc(), 0x1004);
    }

    #[test]
    fn test_sparse_memory() {
        let mut mmix = MMix::new();
        mmix.write_byte(0x1000, 0x42);
        mmix.write_byte(0x1000, 0); // Writing zero should remove it
        assert_eq!(mmix.memory.len(), 0);
    }

    #[test]
    fn test_register_stack_initialization() {
        let mmix = MMix::new();
        assert_eq!(mmix.get_special(SpecialReg::RO), STACK_SEGMENT_START);
        assert_eq!(mmix.get_special(SpecialReg::RS), STACK_SEGMENT_START);
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);
        assert_eq!(mmix.get_special(SpecialReg::RG), 32);
        assert_eq!(mmix.call_depth(), 0);
    }

    #[test]
    fn test_pushj_basic() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 100);
        mmix.set_register(1, 101);
        mmix.set_register(2, 102);
        mmix.set_special(SpecialReg::RL, 3);
        let ro = mmix.get_special(SpecialReg::RO);

        // PUSHJ $3, +1 pushes X+1 = 4 entries: $0..$2 and the hole marker.
        mmix.write_tetra(0x100, 0xF2030001);
        mmix.execute_instruction();

        // rO and rS both advance by X+1 = 4 octas.
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 32);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro + 32);
        // new rL = max(0, rL_old - X - 1) = max(0, 3-3-1) = 0
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x104);
        assert_eq!(mmix.get_pc(), 0x104);

        // Saved frame in memory: $0, $1, $2, then the hole marker = X.
        assert_eq!(mmix.read_octa(ro), 100);
        assert_eq!(mmix.read_octa(ro + 8), 101);
        assert_eq!(mmix.read_octa(ro + 16), 102);
        assert_eq!(mmix.read_octa(ro + 24), 3); // hole marker = X

        // Live register file: caller's $0..$2 zeroed (no slide source above $X here).
        assert_eq!(mmix.get_register(0), 0);
        assert_eq!(mmix.get_register(1), 0);
        assert_eq!(mmix.get_register(2), 0);

        assert_eq!(mmix.call_depth(), 1);
    }

    /// The only test pinning part 1's destination rise through PUSHJ:
    /// writing to a marginal $X raises rL and zeroes $rL..$X before
    /// push_frame runs, so the spill holds zeros, not whatever the flat
    /// array held from an earlier, unrelated frame.
    #[test]
    fn test_pushj_spills_zero_not_stale_content_when_caller_rl_is_zero() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        // Dirty the register file directly, then drop rL to 0 without
        // going through claim_local, so $0..$2 are marginal but the
        // physical array still holds the dirty values.
        mmix.set_register(0, 0xDEAD);
        mmix.set_register(1, 0xBEEF);
        mmix.set_register(2, 0xCAFE);
        mmix.set_special(SpecialReg::RL, 0);
        let ro = mmix.get_special(SpecialReg::RO);

        // PUSHJ $2, +1: X=2, caller's rL = 0.
        mmix.write_tetra(0x100, 0xF2020001);
        mmix.execute_instruction();

        // The destination rise zeroes $0..$2 before the spill runs, so
        // memory holds zeros, not the dirty values.
        assert_eq!(mmix.read_octa(ro), 0);
        assert_eq!(mmix.read_octa(ro + 8), 0);
        assert_eq!(mmix.read_octa(ro + 16), 2); // hole marker = X
        // The entries are fixed by X, not by the raised rL: the new rL
        // settles back at 0 either way.
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);
    }

    /// `POP` reads its hole from `M8[rO-8]` at the moment it runs, not from
    /// any count `PUSHJ` cached. Rewriting that word between the two changes
    /// how far `POP` retracts: no implementation that ignores memory can
    /// pass this.
    #[test]
    fn test_pop_reads_the_hole_from_memory_even_when_rewritten() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 100);
        mmix.set_register(1, 101);
        mmix.set_register(2, 102);
        mmix.set_special(SpecialReg::RL, 3);
        let ro = mmix.get_special(SpecialReg::RO);

        // PUSHJ $3, +1: hole marker 3 lands at ro+24; rO advances to ro+32.
        mmix.write_tetra(0x100, 0xF2030001);
        mmix.execute_instruction();
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 32);

        // Overwrite the hole in memory: POP must read this value, 1, not
        // the pushed x = 3.
        mmix.write_octa(ro + 24, 1);

        // POP 0, 0
        mmix.write_tetra(0x104, 0xF8000000);
        mmix.execute_instruction();

        // Reading x = 3 (the pushed value) would retract by 4 octas,
        // landing back at ro. Reading the rewritten hole (1) retracts by
        // only 2, landing short of it -- proof POP read memory, not a
        // cached count.
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 16);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro + 16);
    }

    #[test]
    fn test_pushj_window_slide_argument_passing() {
        // Stage an arg at $5; PUSHJ $4 should make it visible to the callee at $0.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(5, 0xAA);
        mmix.set_special(SpecialReg::RL, 8); // 8 active locals

        // PUSHJ $4, +1
        mmix.write_tetra(0x100, 0xF2040001);
        mmix.execute_instruction();

        // Callee sees caller's $5 as $0 (slid down by X+1 = 5).
        assert_eq!(mmix.get_register(0), 0xAA);
        // rL = 8 - 5 = 3
        assert_eq!(mmix.get_special(SpecialReg::RL), 3);

        // POP 0,0 — no output reaches $5, so it is marginal and reads zero.
        mmix.write_tetra(0x104, 0xF8000000);
        mmix.execute_instruction();
        assert_eq!(mmix.get_special(SpecialReg::RL), 4);
        assert_eq!(mmix.get_register(5), 0);
        // $4 was the marginal hole — it's consumed by PUSHJ and reads as zero
        // after POP 0 since no return value lands there.
        assert_eq!(mmix.get_register(4), 0);
    }

    #[test]
    fn test_pushj_window_slide_return_value() {
        // POP 1 lands the single return value at the caller's hole position $X.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_special(SpecialReg::RL, 5);

        // PUSHJ $4, +1
        mmix.write_tetra(0x100, 0xF2040001);
        mmix.execute_instruction();

        // Callee writes 0xBB into $0 as the return value.
        mmix.set_register(0, 0xBB);

        // POP 1, 0
        mmix.write_tetra(0x104, 0xF8010000);
        mmix.execute_instruction();

        // Return value lands at caller's $4 (the hole).
        assert_eq!(mmix.get_register(4), 0xBB);
        // rL = min(x+n, rG) = min(4+1, 32) = 5
        assert_eq!(mmix.get_special(SpecialReg::RL), 5);
    }

    #[test]
    fn test_pushj_zeros_freshly_allocated_locals() {
        // After PUSHJ, callee locals beyond the slide window must read as zero.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        for i in 0..8u8 {
            mmix.set_register(i, 1000 + i as u64);
        }
        mmix.set_special(SpecialReg::RL, 8);

        // PUSHJ $4, +1
        mmix.write_tetra(0x100, 0xF2040001);
        mmix.execute_instruction();

        // Slid-down values: caller $5..$7 → callee $0..$2.
        assert_eq!(mmix.get_register(0), 1005);
        assert_eq!(mmix.get_register(1), 1006);
        assert_eq!(mmix.get_register(2), 1007);
        // Vacated tail must be zero.
        assert_eq!(mmix.get_register(3), 0);
        assert_eq!(mmix.get_register(4), 0);
        assert_eq!(mmix.get_register(5), 0);
        assert_eq!(mmix.get_register(7), 0);
    }

    #[test]
    fn test_pop_with_return_value_shift() {
        // PUSHJ $3 + POP 2: the last output lands in the hole.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_special(SpecialReg::RL, 4);

        // PUSHJ $3, +1
        mmix.write_tetra(0x100, 0xF2030001);
        mmix.execute_instruction();

        mmix.set_register(0, 0x111);
        mmix.set_register(1, 0x222);

        // POP 2, 0
        mmix.write_tetra(0x104, 0xF8020000);
        mmix.execute_instruction();

        // x=3, n=2: the hole $3 gets the last output (0x222); $4 gets 0x111.
        assert_eq!(mmix.get_register(3), 0x222);
        assert_eq!(mmix.get_register(4), 0x111);
        // rL = min(x+n, rG) = min(3+2, 32) = 5
        assert_eq!(mmix.get_special(SpecialReg::RL), 5);
        // Caller's $0..$2 are restored from memory (originally zero).
        assert_eq!(mmix.get_register(0), 0);
        assert_eq!(mmix.get_register(1), 0);
        assert_eq!(mmix.get_register(2), 0);
    }

    #[test]
    fn test_pushgo_pop_basic() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 10);
        mmix.set_register(1, 11);
        // Target address: $3 + $4 = 0x200
        mmix.set_register(3, 0x200);
        mmix.set_register(4, 0);
        mmix.set_special(SpecialReg::RL, 2);
        let ro = mmix.get_special(SpecialReg::RO);

        // PUSHGO $2, $3, $4
        mmix.write_tetra(0x100, 0xBE020304);
        mmix.execute_instruction();

        // X=2: rO and rS both advance by X+1 = 3 octas.
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 24);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro + 24);
        // new rL = saturating_sub(2, 3) = 0
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x104);
        assert_eq!(mmix.get_pc(), 0x200);

        // Saved $0, $1, then the hole marker = X.
        assert_eq!(mmix.read_octa(ro), 10);
        assert_eq!(mmix.read_octa(ro + 8), 11);
        assert_eq!(mmix.read_octa(ro + 16), 2);
        assert_eq!(mmix.call_depth(), 1);

        // POP 0,0 at target
        mmix.write_tetra(0x200, 0xF8000000);
        mmix.execute_instruction();

        // Caller's $0,$1 restored from memory.
        assert_eq!(mmix.get_register(0), 10);
        assert_eq!(mmix.get_register(1), 11);
        assert_eq!(mmix.get_special(SpecialReg::RO), ro);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro);
        assert_eq!(mmix.get_special(SpecialReg::RL), 2);
        assert_eq!(mmix.get_pc(), 0x104);
        assert_eq!(mmix.call_depth(), 0);
    }

    #[test]
    fn test_pop_basic() {
        // PUSHJ $3 + POP 0: caller's $0..$2 fully restored, rL back to 3.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 100);
        mmix.set_register(1, 101);
        mmix.set_register(2, 102);
        mmix.set_special(SpecialReg::RL, 3);
        let ro = mmix.get_special(SpecialReg::RO);

        // PUSHJ $3, +1
        mmix.write_tetra(0x100, 0xF2030001);
        mmix.execute_instruction();

        // Callee scribbles over its locals.
        mmix.set_register(0, 200);
        mmix.set_register(1, 201);
        mmix.set_register(2, 202);

        // POP 0, 0
        mmix.write_tetra(0x104, 0xF8000000);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(0), 100);
        assert_eq!(mmix.get_register(1), 101);
        assert_eq!(mmix.get_register(2), 102);
        assert_eq!(mmix.get_special(SpecialReg::RO), ro);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro);
        assert_eq!(mmix.get_special(SpecialReg::RL), 3);
        assert_eq!(mmix.get_pc(), 0x104);
        assert_eq!(mmix.call_depth(), 0);
    }

    #[test]
    fn test_pop_with_return_values() {
        // PUSHJ $4 + POP 3: callee's $0..$2 land at caller's $4..$6.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        for i in 0..8u8 {
            mmix.set_register(i, 100 + i as u64);
        }
        mmix.set_special(SpecialReg::RL, 8);

        // PUSHJ $4, +1
        mmix.write_tetra(0x100, 0xF2040001);
        mmix.execute_instruction();

        // Callee sets 3 return values.
        mmix.set_register(0, 300);
        mmix.set_register(1, 301);
        mmix.set_register(2, 302);

        // POP 3, 0
        mmix.write_tetra(0x104, 0xF8030000);
        mmix.execute_instruction();

        // The hole $4 gets the last output (302); $5, $6 get 300, 301 in order.
        assert_eq!(mmix.get_register(4), 302);
        assert_eq!(mmix.get_register(5), 300);
        assert_eq!(mmix.get_register(6), 301);
        // Caller's $0..$3 restored from memory.
        assert_eq!(mmix.get_register(0), 100);
        assert_eq!(mmix.get_register(1), 101);
        assert_eq!(mmix.get_register(2), 102);
        assert_eq!(mmix.get_register(3), 103);
        // rL = min(x+n, rG) = min(4+3, 32) = 7
        assert_eq!(mmix.get_special(SpecialReg::RL), 7);
    }

    #[test]
    fn test_pop_no_return_values() {
        // PUSHJ $5 + POP 0: caller's $0..$4 are restored; $5..$9 are
        // marginal after POP and read zero.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        for i in 0..10u8 {
            mmix.set_register(i, 100 + i as u64);
        }
        mmix.set_special(SpecialReg::RL, 10);

        // PUSHJ $5, +1
        mmix.write_tetra(0x100, 0xF2050001);
        mmix.execute_instruction();

        // Callee scribbles over its locals.
        mmix.set_register(0, 999);
        mmix.set_register(1, 888);
        mmix.set_register(2, 777);

        // POP 0, 0
        mmix.write_tetra(0x104, 0xF8000000);
        mmix.execute_instruction();

        // Caller's $0..$4 restored from memory.
        for i in 0..5u8 {
            assert_eq!(mmix.get_register(i), 100 + i as u64);
        }
        // $5 was the marginal hole — it's consumed by PUSHJ and reads as zero
        // after POP 0 since no return value lands there.
        assert_eq!(mmix.get_register(5), 0);
        // Slots above the hole are marginal after POP — they read zero, not
        // their stale pre-call values.
        for i in 6..10u8 {
            assert_eq!(mmix.get_register(i), 0);
        }
        assert_eq!(mmix.get_special(SpecialReg::RL), 5);
    }

    #[test]
    fn test_pop_mmixware_program1_matches_measured_values() {
        // Measured on MMIXware and checksmix at 91d207f (see MMIX.md's
        // register stack table). Caller's $1..$5 read zero after POP, and
        // the callee's sole return value lands at the hole $0.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(1, 111);
        mmix.set_register(2, 222);
        mmix.set_register(3, 333);
        mmix.set_register(4, 444);
        mmix.set_register(5, 555);

        // PUSHJ $0, +1
        mmix.write_tetra(0x100, 0xF2000001);
        mmix.execute_instruction();

        // Callee sets its return values.
        mmix.set_register(0, 999);
        mmix.set_register(1, 777);

        // POP 1, 0
        mmix.write_tetra(0x104, 0xF8010000);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(0), 999);
        for i in 1..=5u8 {
            assert_eq!(mmix.get_register(i), 0);
        }
        assert_eq!(mmix.get_special(SpecialReg::RL), 1);
    }

    #[test]
    fn test_pop_mmixware_program2_matches_measured_values() {
        // Measured on MMIXware and checksmix at 91d207f. POP 2 puts the
        // callee's last output ($1) in the hole and the first ($0) above
        // it, and registers above the outputs read zero rather than their
        // pre-call values.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 10);
        mmix.set_register(1, 20);
        mmix.set_register(2, 30);
        mmix.set_register(3, 40);
        mmix.set_register(4, 50);
        mmix.set_register(5, 60);
        mmix.set_register(6, 70);

        // PUSHJ $3, +1
        mmix.write_tetra(0x100, 0xF2030001);
        mmix.execute_instruction();

        // Callee sets its three return values.
        mmix.set_register(0, 801);
        mmix.set_register(1, 802);
        mmix.set_register(2, 803);

        // POP 2, 0
        mmix.write_tetra(0x104, 0xF8020000);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(0), 10);
        assert_eq!(mmix.get_register(1), 20);
        assert_eq!(mmix.get_register(2), 30);
        assert_eq!(mmix.get_register(3), 802);
        assert_eq!(mmix.get_register(4), 801);
        assert_eq!(mmix.get_register(5), 0);
        assert_eq!(mmix.get_register(6), 0);
        assert_eq!(mmix.get_special(SpecialReg::RL), 5);
    }

    #[test]
    fn test_pop_0_0_leaves_hole_and_everything_above_it_zero() {
        // POP 0,0 leaves the hole marginal: rL becomes x, and every
        // register from there through rG-1 reads zero.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 10);
        mmix.set_register(1, 20);
        mmix.set_register(2, 30);
        mmix.set_register(3, 40);
        mmix.set_special(SpecialReg::RL, 4);

        // PUSHJ $2, +1
        mmix.write_tetra(0x100, 0xF2020001);
        mmix.execute_instruction();

        // Callee scribbles over its one local.
        mmix.set_register(0, 999);

        // POP 0, 0
        mmix.write_tetra(0x104, 0xF8000000);
        mmix.execute_instruction();

        // Caller's $0, $1 restored; $2 (the hole) and everything above it,
        // through rG-1, is marginal and reads zero.
        assert_eq!(mmix.get_register(0), 10);
        assert_eq!(mmix.get_register(1), 20);
        for i in 2..32u8 {
            assert_eq!(mmix.get_register(i), 0);
        }
        assert_eq!(mmix.get_special(SpecialReg::RL), 2);
    }

    #[test]
    fn test_pop_x_greater_than_l_clamps_and_zeros_the_hole() {
        // If X > L, X becomes L+1 and the hole gets zero regardless of what
        // the callee left there.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 100);
        mmix.set_register(2, 200);
        mmix.set_special(SpecialReg::RL, 3);

        // PUSHJ $1, +1 — callee's rL is 1 (only $0 is a valid local).
        mmix.write_tetra(0x100, 0xF2010001);
        mmix.execute_instruction();
        assert_eq!(mmix.get_special(SpecialReg::RL), 1);

        // Callee sets its one local as a return value.
        mmix.set_register(0, 555);

        // POP 3, 0 — X (3) exceeds L (1), so X clamps to L+1 = 2.
        mmix.write_tetra(0x104, 0xF8030000);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(0), 100);
        // The hole reads zero, not the callee's $0.
        assert_eq!(mmix.get_register(1), 0);
        // The clamp still delivers the callee's one real output, one slot up.
        assert_eq!(mmix.get_register(2), 555);
        assert_eq!(mmix.get_special(SpecialReg::RL), 3);
    }

    #[test]
    fn test_pushj_x_at_or_above_rg_saves_all_locals_and_pops_at_the_hole() {
        // PUSHJ $X with X >= rG pushes $0..$(rL-1), the callee starts at
        // rL = 0, and the hole for POP is the caller's rL, not X.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_special(SpecialReg::RG, 10);
        mmix.set_register(0, 1000);
        mmix.set_register(1, 1001);
        mmix.set_register(2, 1002);
        mmix.set_register(3, 1003);
        mmix.set_register(4, 1004);
        mmix.set_special(SpecialReg::RL, 5);
        mmix.set_register(50, 0xBEEF); // a global, above rG

        let rs_before = mmix.get_special(SpecialReg::RS);

        // PUSHJ $255, +1
        mmix.write_tetra(0x100, 0xF2FF0001);
        mmix.execute_instruction();
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);

        // Callee computes its result in its one local.
        mmix.set_register(0, 777);

        // POP 1, 0
        mmix.write_tetra(0x104, 0xF8010000);
        mmix.execute_instruction();

        // Caller's $0..$4 restored, the output lands at $rL (the hole), and
        // rL becomes min(rL+1, rG).
        assert_eq!(mmix.get_register(0), 1000);
        assert_eq!(mmix.get_register(1), 1001);
        assert_eq!(mmix.get_register(2), 1002);
        assert_eq!(mmix.get_register(3), 1003);
        assert_eq!(mmix.get_register(4), 1004);
        assert_eq!(mmix.get_register(5), 777);
        assert_eq!(mmix.get_special(SpecialReg::RL), 6);
        // Globals are untouched throughout.
        assert_eq!(mmix.get_register(50), 0xBEEF);
        // POP retracts rO and rS to exactly the address PUSHJ found them
        // at: a spill sized by rL, not the hole read back from memory,
        // would retract by the wrong amount and land somewhere else.
        assert_eq!(mmix.get_special(SpecialReg::RS), rs_before);
    }

    #[test]
    fn test_pushgoi_pop_basic() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x300);
        mmix.set_register(0, 42);
        mmix.set_register(1, 43);
        mmix.set_register(5, 0x310);
        mmix.set_special(SpecialReg::RL, 2);
        let ro = mmix.get_special(SpecialReg::RO);

        // PUSHGOI $2, $5, #0x10  → target = $5 + 0x10 = 0x320
        mmix.write_tetra(0x300, 0xBF020510);
        mmix.execute_instruction();

        // X=2: rO and rS both advance by X+1 = 3 octas.
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 24);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro + 24);
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x304);
        assert_eq!(mmix.get_pc(), 0x320);

        assert_eq!(mmix.read_octa(ro), 42);
        assert_eq!(mmix.read_octa(ro + 8), 43);
        assert_eq!(mmix.read_octa(ro + 16), 2); // hole marker = X
        assert_eq!(mmix.call_depth(), 1);

        // POP 0,0 at target — restore caller's $0,$1.
        mmix.write_tetra(0x320, 0xF8000000);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(0), 42);
        assert_eq!(mmix.get_register(1), 43);
        assert_eq!(mmix.get_special(SpecialReg::RO), ro);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro);
        assert_eq!(mmix.get_special(SpecialReg::RL), 2);
        assert_eq!(mmix.get_pc(), 0x304);
        assert_eq!(mmix.call_depth(), 0);
    }

    #[test]
    fn test_pushj_pop_nested() {
        // Two-level nested call exercises arg passing in both directions
        // and that the two frames stack contiguously in memory.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 10);
        mmix.set_register(1, 11);
        mmix.set_register(2, 0xCAFE); // arg for inner call: caller's $2
        mmix.set_special(SpecialReg::RL, 5);
        let ro = mmix.get_special(SpecialReg::RO);

        // Outer PUSHJ $2, +1 — saves $0,$1; slides $3,$4 to callee's $0,$1; arg at $2 → callee $0? No —
        // PUSHJ $X saves $0..$X-1 (here $0,$1) and the marginal at $X. Caller's $X+1, $X+2, ...
        // become callee's $0, $1, ... .  So $2 (the marginal) is *not* an arg; it becomes X.
        // To pass an arg via slide, stage at $X+1 = $3.
        mmix.set_register(3, 0xCAFE);
        mmix.write_tetra(0x100, 0xF2020001);
        mmix.execute_instruction();

        // Outer callee sees arg at $0.
        assert_eq!(mmix.get_register(0), 0xCAFE);
        assert_eq!(mmix.call_depth(), 1);
        // Outer frame: X+1 = 3 entries.
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 24);

        // Outer callee stages an arg at $1 then nested PUSHJ $0, +1 (X=0: nothing saved, slide $1→$0).
        mmix.set_register(1, 0xBEEF);
        mmix.write_tetra(0x104, 0xF2000001);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(0), 0xBEEF);
        assert_eq!(mmix.call_depth(), 2);
        // Inner frame starts exactly where the outer frame's entries end.
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 32);

        // Inner POP 1, 0 — return 0xD00D at $0; lands at outer callee's $0 (hole=0).
        mmix.set_register(0, 0xD00D);
        mmix.write_tetra(0x108, 0xF8010000);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(0), 0xD00D);
        assert_eq!(mmix.call_depth(), 1);
        // Popping the inner frame retracts rO to exactly where it started.
        assert_eq!(mmix.get_special(SpecialReg::RO), ro + 24);

        // Outer POP 1, 0 — return 0xD00D, lands at top-level caller's $2 (hole=2).
        mmix.write_tetra(0x10C, 0xF8010000);
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(2), 0xD00D);
        // Caller's $0, $1 restored.
        assert_eq!(mmix.get_register(0), 10);
        assert_eq!(mmix.get_register(1), 11);
        assert_eq!(mmix.get_special(SpecialReg::RO), ro);
        assert_eq!(mmix.call_depth(), 0);
    }

    /// `POP` never writes `rJ`: it only reads it for the branch target.
    /// Set a distinct, nonzero `rJ` before the call so a restore, if `POP`
    /// still did one, would be visible.
    #[test]
    fn test_pop_leaves_rj_as_pushj_set_it() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_special(SpecialReg::RJ, 0x999);
        mmix.write_tetra(0x100, 0xF2000002); // PUSHJ $0,2 -> 0x108, rJ := 0x104
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x104);

        mmix.write_tetra(0x108, 0xF8000000); // POP 0,0
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RJ),
            0x104,
            "POP must leave rJ exactly as PUSHJ set it, not restore 0x999"
        );
        assert_eq!(mmix.get_pc(), 0x104);
    }

    /// A callee that makes a nested call without saving `rJ` first has its
    /// own `POP` branch to the address after the *nested* `PUSHJ`, not back
    /// to its own caller: a subroutine that calls another must save and
    /// restore `rJ` itself.
    #[test]
    fn test_pop_without_saving_rj_returns_to_the_nested_call_site() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        // Top-level caller: PUSHJ $0,2 -> callee at 0x108; rJ := 0x104.
        mmix.write_tetra(0x100, 0xF2000002);
        assert!(mmix.execute_instruction());

        // Callee makes a nested call without saving rJ: PUSHJ $0,4 ->
        // nested callee at 0x118; rJ := 0x10C.
        mmix.write_tetra(0x108, 0xF2000004);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x10C);

        // Nested callee returns immediately: POP 0,0 branches to rJ + 0,
        // landing back at 0x10C.
        mmix.write_tetra(0x118, 0xF8000000);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x10C);

        // The callee's own POP, resumed right there, reads the SAME stale
        // rJ (0x10C) and branches to it again -- the address after its
        // nested PUSHJ, not the address after the top-level PUSHJ (0x104).
        mmix.write_tetra(0x10C, 0xF8000000);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x10C);
        assert_eq!(mmix.call_depth(), 0);
    }

    /// A callee that saves `rJ` before its nested call and restores it
    /// after, before its own `POP`, returns correctly to its own caller.
    #[test]
    fn test_pop_returns_correctly_when_rj_is_saved_and_restored() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        // Top-level caller: PUSHJ $0,2 -> callee at 0x108; rJ := 0x104.
        mmix.write_tetra(0x100, 0xF2000002);
        assert!(mmix.execute_instruction());

        // Callee saves rJ: GET $1,rJ.
        mmix.write_tetra(0x108, 0xFE010004);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0x104);

        // Callee makes a nested call: PUSHJ $2,3 -- the hole must clear
        // rJ's stash at $1, or the slide swallows it into the nested
        // callee's own $0 -- nested callee at 0x118; rJ := 0x110.
        mmix.write_tetra(0x10C, 0xF2020003);
        assert!(mmix.execute_instruction());

        // Nested callee returns immediately: POP 0,0 branches to rJ + 0,
        // landing back at 0x110.
        mmix.write_tetra(0x118, 0xF8000000);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x110);

        // Callee restores rJ: PUT rJ,$1.
        mmix.write_tetra(0x110, 0xF6040001);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x104);

        // Callee's own POP now branches to the address after the
        // top-level PUSHJ, not the nested one.
        mmix.write_tetra(0x114, 0xF8010000);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x104);
        assert_eq!(mmix.call_depth(), 0);
    }

    #[test]
    fn test_incl_instruction() {
        let mut mmix = MMix::new();
        // INCL $1, YZ=0x0203 - opcode 0xE7, X=1, YZ=0x0203
        mmix.write_tetra(0, 0xE7010203);
        mmix.set_register(1, 50);

        let result = mmix.execute_instruction();
        assert!(result); // Should continue
        assert_eq!(mmix.get_register(1), 50 + 0x0203); // 50 + YZ value
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_incl_with_zero() {
        let mut mmix = MMix::new();
        // INCL $2, YZ=0
        mmix.write_tetra(0, 0xE7020000);
        mmix.set_register(2, 42);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(2), 42); // No change
    }

    #[test]
    fn test_incl_overflow() {
        let mut mmix = MMix::new();
        // INCL $3, YZ=0x0405
        mmix.write_tetra(0, 0xE7030405);
        mmix.set_register(3, u64::MAX - 5);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(3), (u64::MAX - 5).wrapping_add(0x0405)); // Wraps around
    }

    #[test]
    fn test_incl_large_values() {
        let mut mmix = MMix::new();
        // INCL $1, YZ=0x0203
        mmix.write_tetra(0, 0xE7010203);
        mmix.set_register(1, 100);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 100 + 0x0203);
    }

    #[test]
    fn test_incl_register_255() {
        let mut mmix = MMix::new();
        // INCL $255, YZ=0x0102 - should modify $255 like any other register
        mmix.write_tetra(0, 0xE7FF0102);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(255), 0x0102); // Should have the immediate value
    }

    #[test]
    fn test_incl_using_255() {
        let mut mmix = MMix::new();
        // INCL $1, YZ=0xFF02
        mmix.write_tetra(0, 0xE701FF02);
        mmix.set_register(1, 100);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 100 + 0xFF02);
    }

    #[test]
    fn test_run_multiple_incl() {
        let mut mmix = MMix::new();
        // Program: 3 INCL instructions followed by TRAP (halt)
        mmix.write_tetra(0, 0xE7010000); // INCL $1, YZ=0 (no change)
        mmix.write_tetra(4, 0xE7010203); // INCL $1, YZ=0x0203
        mmix.write_tetra(8, 0xE7010203); // INCL $1, YZ=0x0203
        mmix.write_tetra(12, 0xFF000000); // TRIP (halt)

        let count = mmix.run();
        assert_eq!(count, 3);
        assert_eq!(mmix.get_register(1), 0x0203 * 2); // 0 + 0x0203 + 0x0203
        assert_eq!(mmix.get_pc(), 12);
    }

    #[test]
    fn test_trip_to_unloaded_vector_halts_with_diagnostic_and_nonzero_exit() {
        // #00 reads zero, which decodes as TRAP 0,0,0 — the case the
        // unloaded-vector halt exists to catch instead of hiding.
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_pc(0x100);
        mmix.write_tetra(0x100, 0xFF000000); // TRIP 0,0,0
        let result = mmix.execute_instruction();
        assert!(!result);
        assert_eq!(mmix.get_pc(), 0x100, "PC stays on the tripping instruction");
        assert_eq!(mmix.get_exit_code(), 1);
        // Registers are set before the halt is detected, so a debugger sees why.
        assert_eq!(mmix.get_special(SpecialReg::RW), 0x104);
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("TRIP"));
    }

    // Load instruction tests

    #[test]
    fn test_ldb_signed_positive() {
        let mut mmix = MMix::new();
        // LDB $1, $2, $3 - Load signed byte (positive)
        mmix.write_tetra(0, 0x80010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_byte(150, 127); // Max positive signed byte

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 127);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldb_signed_negative() {
        let mut mmix = MMix::new();
        // LDB $1, $2, $3 - Load signed byte (negative)
        mmix.write_tetra(0, 0x80010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_byte(150, 0xFF); // -1 in signed byte

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -1);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldb_immediate() {
        let mut mmix = MMix::new();
        // LDB $1, $2, 10 - Load signed byte with immediate offset
        mmix.write_tetra(0, 0x8101020A);
        mmix.set_register(2, 100);
        mmix.write_byte(110, 0x80); // -128 in signed byte

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -128);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldbu_unsigned() {
        let mut mmix = MMix::new();
        // LDBU $1, $2, $3 - Load unsigned byte
        mmix.write_tetra(0, 0x82010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_byte(150, 0xFF); // 255 unsigned

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 255);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldbu_immediate() {
        let mut mmix = MMix::new();
        // LDBU $1, $2, 20 - Load unsigned byte with immediate
        mmix.write_tetra(0, 0x83010214);
        mmix.set_register(2, 100);
        mmix.write_byte(120, 200);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 200);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldw_signed_positive() {
        let mut mmix = MMix::new();
        // LDW $1, $2, $3 - Load signed wyde (positive)
        mmix.write_tetra(0, 0x84010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_wyde(150, 32767); // Max positive signed wyde

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 32767);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldw_signed_negative() {
        let mut mmix = MMix::new();
        // LDW $1, $2, $3 - Load signed wyde (negative)
        mmix.write_tetra(0, 0x84010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_wyde(150, 0xFFFF); // -1 in signed wyde

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -1);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldw_immediate() {
        let mut mmix = MMix::new();
        // LDW $1, $2, 10 - Load signed wyde with immediate
        mmix.write_tetra(0, 0x8501020A);
        mmix.set_register(2, 100);
        mmix.write_wyde(110, 0x8000); // -32768 in signed wyde

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -32768);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldwu_unsigned() {
        let mut mmix = MMix::new();
        // LDWU $1, $2, $3 - Load unsigned wyde
        mmix.write_tetra(0, 0x86010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_wyde(150, 0xFFFF); // 65535 unsigned

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 65535);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldwu_immediate() {
        let mut mmix = MMix::new();
        // LDWU $1, $2, 30 - Load unsigned wyde with immediate
        mmix.write_tetra(0, 0x8701021E);
        mmix.set_register(2, 100);
        mmix.write_wyde(130, 50000);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 50000);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldt_signed_positive() {
        let mut mmix = MMix::new();
        // LDT $1, $2, $3 - Load signed tetra (positive)
        mmix.write_tetra(0, 0x88010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_tetra(150, 2_147_483_647); // Max positive signed tetra

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 2_147_483_647);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldt_signed_negative() {
        let mut mmix = MMix::new();
        // LDT $1, $2, $3 - Load signed tetra (negative)
        mmix.write_tetra(0, 0x88010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_tetra(150, 0xFFFFFFFF); // -1 in signed tetra

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -1);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldt_immediate() {
        let mut mmix = MMix::new();
        // LDT $1, $2, 20 - Load signed tetra with immediate
        mmix.write_tetra(0, 0x89010214);
        mmix.set_register(2, 100);
        mmix.write_tetra(120, 0x80000000); // -2147483648 in signed tetra

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -2147483648);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldtu_unsigned() {
        let mut mmix = MMix::new();
        // LDTU $1, $2, $3 - Load unsigned tetra
        mmix.write_tetra(0, 0x8A010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_tetra(150, 0xFFFFFFFF); // 4294967295 unsigned

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 4294967295);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldtu_immediate() {
        let mut mmix = MMix::new();
        // LDTU $1, $2, 40 - Load unsigned tetra with immediate
        mmix.write_tetra(0, 0x8B010228);
        mmix.set_register(2, 100);
        mmix.write_tetra(140, 3_000_000_000);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 3_000_000_000);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldo_load_octa() {
        let mut mmix = MMix::new();
        // LDO $1, $2, $3 - Load octa
        mmix.write_tetra(0, 0x8C010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_octa(150, 0x123456789ABCDEF0);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0x123456789ABCDEF0);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldo_immediate() {
        let mut mmix = MMix::new();
        // LDO $1, $2, 16 - Load octa with immediate
        mmix.write_tetra(0, 0x8D010210);
        mmix.set_register(2, 100);
        mmix.write_octa(116, 0xFEDCBA9876543210);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0xFEDCBA9876543210);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldou_same_as_ldo() {
        let mut mmix = MMix::new();
        // LDOU $1, $2, $3 - Load octa unsigned (same as LDO)
        mmix.write_tetra(0, 0x8E010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_octa(150, 0x123456789ABCDEF0);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0x123456789ABCDEF0);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldou_immediate() {
        let mut mmix = MMix::new();
        // LDOU $1, $2, 8 - Load octa unsigned with immediate
        mmix.write_tetra(0, 0x8F010208);
        mmix.set_register(2, 1000);
        mmix.write_octa(1008, 0xFFFFFFFFFFFFFFFF);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0xFFFFFFFFFFFFFFFF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldsf_short_float() {
        let mut mmix = MMix::new();
        // LDSF $1, $2, $3 - Load short float (32-bit to 64-bit)
        mmix.write_tetra(0, 0x90010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        // Write a 32-bit float (e.g., 3.14159 in IEEE 754 single precision)
        let float_val = std::f32::consts::PI;
        mmix.write_tetra(150, float_val.to_bits());

        mmix.execute_instruction();
        // Should be converted to 64-bit float
        let result_f64 = MMix::u64_to_f64(mmix.get_register(1));
        assert!((result_f64 - std::f64::consts::PI).abs() < 0.0001);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_ldsfi_immediate() {
        let mut mmix = MMix::new();
        // LDSFI $1, $2, 12 - Load short float with immediate offset
        mmix.write_tetra(0, 0x9101020C);
        mmix.set_register(2, 200);
        // Write a 32-bit float (e.g., -2.5 in IEEE 754 single precision)
        let float_val = -2.5f32;
        mmix.write_tetra(212, float_val.to_bits());

        mmix.execute_instruction();
        let result_f64 = MMix::u64_to_f64(mmix.get_register(1));
        assert_eq!(result_f64, -2.5);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_lda_load_address() {
        let mut mmix = MMix::new();
        // LDA $1, $2, $3 - Load address (same as ADDU)
        mmix.write_tetra(0, 0x22010203);
        mmix.set_register(2, 0x1000);
        mmix.set_register(3, 0x500);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0x1500);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_lda_immediate() {
        let mut mmix = MMix::new();
        // LDA $1, $2, 64 - Load address with immediate (same as ADDU)
        mmix.write_tetra(0, 0x23010240);
        mmix.set_register(2, 0x2000);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0x2040);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_load_from_uninitialized_memory() {
        let mut mmix = MMix::new();
        // LDBU $1, $0, 100 - Load from uninitialized memory (should be 0)
        mmix.write_tetra(0, 0x83010064);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_load_address_wraparound() {
        let mut mmix = MMix::new();
        // LDA $1, $2, $3 - Test address wraparound
        mmix.write_tetra(0, 0x22010203);
        mmix.set_register(2, u64::MAX - 100);
        mmix.set_register(3, 200);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 99); // Wraps around
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_wyde_set_replaces_whole_register() {
        // SETH, SETMH, SETML, SETL each deposit YZ in one wyde and zero the
        // other 48 bits. The all-ones preload is what distinguishes a set
        // from a merge.
        for (opcode, shift) in [(0xE0_u32, 48_u32), (0xE1, 32), (0xE2, 16), (0xE3, 0)] {
            let mut mmix = MMix::new();
            mmix.set_register(1, u64::MAX);
            mmix.write_tetra(0, (opcode << 24) | (1 << 16) | 0xABCD);

            mmix.execute_instruction();

            let reg = mmix.get_register(1);
            assert_eq!((reg >> shift) & 0xFFFF, 0xABCD, "opcode {opcode:#04X} wyde");
            assert_eq!(
                reg & !(0xFFFF_u64 << shift),
                0,
                "opcode {opcode:#04X} residue"
            );
            assert_eq!(mmix.get_pc(), 4);
        }
    }

    #[test]
    fn test_setl_zero_clears_whole_register() {
        let mut mmix = MMix::new();
        mmix.set_register(1, u64::MAX);
        // SETL $1, 0 - a one-instruction register clear
        mmix.write_tetra(0, 0xE3010000);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0);
    }

    /// Assemble `source`, load its image and execute `steps` instructions
    /// from the first assembled address.
    fn assemble_and_run(source: &str, steps: usize) -> MMix {
        use crate::debugger::write_image;
        use crate::mmixal::MMixAssembler;

        let mut asm = MMixAssembler::new(source, "<test>");
        asm.parse().expect("test source must assemble");
        let start = asm.instructions[0].0;

        let mut mmix = MMix::new();
        write_image(&mut mmix, &asm);
        mmix.set_pc(start);
        for _ in 0..steps {
            mmix.execute_instruction();
        }
        mmix
    }

    #[test]
    fn test_seti_lands_a_wide_constant() {
        let mmix = assemble_and_run("SETI $1,#0123456789ABCDEF", 4);
        assert_eq!(mmix.get_register(1), 0x0123456789ABCDEF);
    }

    #[test]
    fn test_lda_large_address_lands_whole_address() {
        // LDA $X,Label above #FF expands to the same four tetras SETI uses;
        // examples/hello_world.mms gets its string pointer this way.
        let mmix = assemble_and_run("\tLOC\t#2000000000001234\nMain\tLDA\t$255,Main\n", 4);
        assert_eq!(mmix.get_register(255), 0x2000_0000_0000_1234);
    }

    #[test]
    fn test_inc_and_or_wydes_preserve_the_others() {
        let mut mmix = MMix::new();
        mmix.set_register(1, 0x1111_2222_3333_4444);

        // INCML $1, 0x0001
        mmix.write_tetra(0, 0xE6010001);
        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0x1111_2222_3334_4444);

        // ORL $1, 0x000F
        mmix.set_pc(4);
        mmix.write_tetra(4, 0xEB01000F);
        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0x1111_2222_3334_444F);
    }

    #[test]
    fn test_incl_has_multiple_tests() {
        // INCL is already tested in:
        // - test_incl_instruction
        // - test_incl_with_zero
        // - test_incl_overflow
        // - test_incl_large_values
        // - test_incl_register_255
        // - test_incl_using_255
        // - test_run_multiple_incl
        // This test just confirms coverage
        let mut mmix = MMix::new();
        mmix.write_tetra(0, 0xE7010203);
        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0x0203);
    }

    // Store instruction tests

    #[test]
    fn test_stb_store_byte() {
        let mut mmix = MMix::new();
        // STB $1, $2, $3 - Store byte
        mmix.write_tetra(0, 0xA0010203);
        mmix.set_register(1, 0x42); // Value to store
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_byte(150), 0x42);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stb_immediate() {
        let mut mmix = MMix::new();
        // STB $1, $2, 10 - Store byte immediate
        mmix.write_tetra(0, 0xA101020A);
        mmix.set_register(1, 0x7F); // Max positive signed byte
        mmix.set_register(2, 200);

        mmix.execute_instruction();
        assert_eq!(mmix.read_byte(210), 0x7F);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stbu_store_byte_unsigned() {
        let mut mmix = MMix::new();
        // STBU $1, $2, $3 - Store byte unsigned
        mmix.write_tetra(0, 0xA2010203);
        mmix.set_register(1, 0xFF); // 255 unsigned
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_byte(150), 0xFF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stbu_immediate() {
        let mut mmix = MMix::new();
        // STBU $1, $2, 20 - Store byte unsigned immediate
        mmix.write_tetra(0, 0xA3010214);
        mmix.set_register(1, 0xAB);
        mmix.set_register(2, 1000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_byte(1020), 0xAB);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stw_store_wyde() {
        let mut mmix = MMix::new();
        // STW $1, $2, $3 - Store wyde
        mmix.write_tetra(0, 0xA4010203);
        mmix.set_register(1, 0x1234);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_wyde(150), 0x1234);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stw_immediate() {
        let mut mmix = MMix::new();
        // STW $1, $2, 30 - Store wyde immediate
        mmix.write_tetra(0, 0xA501021E);
        mmix.set_register(1, 0x7FFF); // Max positive signed wyde
        mmix.set_register(2, 2000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_wyde(2030), 0x7FFF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stwu_store_wyde_unsigned() {
        let mut mmix = MMix::new();
        // STWU $1, $2, $3 - Store wyde unsigned
        mmix.write_tetra(0, 0xA6010203);
        mmix.set_register(1, 0xFFFF); // 65535 unsigned
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_wyde(150), 0xFFFF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stwu_immediate() {
        let mut mmix = MMix::new();
        // STWU $1, $2, 40 - Store wyde unsigned immediate
        mmix.write_tetra(0, 0xA7010228);
        mmix.set_register(1, 0xABCD);
        mmix.set_register(2, 5000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_wyde(5040), 0xABCD);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stt_store_tetra() {
        let mut mmix = MMix::new();
        // STT $1, $2, $3 - Store tetra
        mmix.write_tetra(0, 0xA8010203);
        mmix.set_register(1, 0x12345678);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_tetra(150), 0x12345678);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stt_immediate() {
        let mut mmix = MMix::new();
        // STT $1, $2, 50 - Store tetra immediate
        mmix.write_tetra(0, 0xA9010232);
        mmix.set_register(1, 0x7FFFFFFF); // Max positive signed tetra
        mmix.set_register(2, 10000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_tetra(10050), 0x7FFFFFFF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_sttu_store_tetra_unsigned() {
        let mut mmix = MMix::new();
        // STTU $1, $2, $3 - Store tetra unsigned
        mmix.write_tetra(0, 0xAA010203);
        mmix.set_register(1, 0xFFFFFFFF); // 4294967295 unsigned
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_tetra(150), 0xFFFFFFFF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_sttu_immediate() {
        let mut mmix = MMix::new();
        // STTU $1, $2, 60 - Store tetra unsigned immediate
        mmix.write_tetra(0, 0xAB01023C);
        mmix.set_register(1, 0xDEADBEEF);
        mmix.set_register(2, 20000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_tetra(20060), 0xDEADBEEF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_sto_store_octa() {
        let mut mmix = MMix::new();
        // STO $1, $2, $3 - Store octa
        mmix.write_tetra(0, 0xAC010203);
        mmix.set_register(1, 0x123456789ABCDEF0);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_octa(150), 0x123456789ABCDEF0);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_sto_immediate() {
        let mut mmix = MMix::new();
        // STO $1, $2, 70 - Store octa immediate
        mmix.write_tetra(0, 0xAD010246);
        mmix.set_register(1, 0xFEDCBA9876543210);
        mmix.set_register(2, 30000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_octa(30070), 0xFEDCBA9876543210);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stou_same_as_sto() {
        let mut mmix = MMix::new();
        // STOU $1, $2, $3 - Store octa unsigned (same as STO)
        mmix.write_tetra(0, 0xAE010203);
        mmix.set_register(1, 0xFFFFFFFFFFFFFFFF);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_octa(150), 0xFFFFFFFFFFFFFFFF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stou_immediate() {
        let mut mmix = MMix::new();
        // STOU $1, $2, 80 - Store octa unsigned immediate
        mmix.write_tetra(0, 0xAF010250);
        mmix.set_register(1, 0x0123456789ABCDEF);
        mmix.set_register(2, 40000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_octa(40080), 0x0123456789ABCDEF);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stco_store_constant() {
        let mut mmix = MMix::new();
        // STCO 42, $2, $3 - Store constant octabyte
        mmix.write_tetra(0, 0xB42A0203); // X=42 (0x2A)
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_octa(150), 42);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stco_immediate() {
        let mut mmix = MMix::new();
        // STCO 255, $2, 90 - Store constant octabyte immediate
        mmix.write_tetra(0, 0xB5FF025A); // X=255 (0xFF)
        mmix.set_register(2, 50000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_octa(50090), 255);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stht_store_high_tetra() {
        let mut mmix = MMix::new();
        // STHT $1, $2, $3 - Store high tetra
        mmix.write_tetra(0, 0xB2010203);
        mmix.set_register(1, 0xDEADBEEF12345678);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.read_tetra(150), 0xDEADBEEF); // High 32 bits
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_stht_immediate() {
        let mut mmix = MMix::new();
        // STHT $1, $2, 100 - Store high tetra immediate
        mmix.write_tetra(0, 0xB3010264);
        mmix.set_register(1, 0xABCD123456789ABC);
        mmix.set_register(2, 60000);

        mmix.execute_instruction();
        assert_eq!(mmix.read_tetra(60100), 0xABCD1234); // High 32 bits
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_store_and_load_roundtrip() {
        let mut mmix = MMix::new();
        let test_addr = 5000u64;

        // Store a value
        mmix.set_register(1, 0x123456789ABCDEF0);
        mmix.set_register(2, test_addr);
        mmix.write_tetra(0, 0xAD010200); // STO $1, $2, 0
        mmix.execute_instruction();

        // Load it back
        mmix.set_pc(4);
        mmix.write_tetra(4, 0x8D030200); // LDO $3, $2, 0
        mmix.execute_instruction();

        assert_eq!(mmix.get_register(3), 0x123456789ABCDEF0);
    }

    #[test]
    fn test_all_store_instructions_have_tests() {
        // Verify all store instructions are covered
        let mut mmix = MMix::new();

        // STB $1, $2, $3
        mmix.write_tetra(0, 0xA0010203);
        mmix.set_register(1, 0x5A);
        mmix.set_register(2, 300);
        mmix.set_register(3, 12);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_byte(312), 0x5A);

        // STBU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xA2010203);
        mmix.set_register(1, 0xE1);
        mmix.set_register(2, 300);
        mmix.set_register(3, 13);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_byte(313), 0xE1);

        // STW $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xA4010203);
        mmix.set_register(1, 0x4321);
        mmix.set_register(2, 400);
        mmix.set_register(3, 14);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_wyde(414), 0x4321);

        // STWU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xA6010203);
        mmix.set_register(1, 0xBEEF);
        mmix.set_register(2, 400);
        mmix.set_register(3, 16);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_wyde(416), 0xBEEF);

        // STT $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xA8010203);
        mmix.set_register(1, 0x87654321);
        mmix.set_register(2, 500);
        mmix.set_register(3, 20);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_tetra(520), 0x87654321);

        // STTU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xAA010203);
        mmix.set_register(1, 0xCAFEBABE);
        mmix.set_register(2, 500);
        mmix.set_register(3, 24);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_tetra(524), 0xCAFEBABE);

        // STO $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xAC010203);
        mmix.set_register(1, 0x0F1E2D3C4B5A6978);
        mmix.set_register(2, 600);
        mmix.set_register(3, 30);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(630), 0x0F1E2D3C4B5A6978);

        // STOU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xAE010203);
        mmix.set_register(1, 0x1122334455667788);
        mmix.set_register(2, 600);
        mmix.set_register(3, 40);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(640), 0x1122334455667788);

        // STCO 17, $2, $3 - Store constant octabyte
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xB4110203); // X=17 (0x11)
        mmix.set_register(2, 700);
        mmix.set_register(3, 5);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(705), 17);

        // STHT $1, $2, $3 - Store high tetra
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xB2010203);
        mmix.set_register(1, 0x1357924600000000);
        mmix.set_register(2, 800);
        mmix.set_register(3, 8);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_tetra(808), 0x13579246); // High 32 bits
    }

    // Arithmetic instruction tests - Add and Subtract

    #[test]
    fn test_add_positive_numbers() {
        let mut mmix = MMix::new();
        // ADD $1, $2, $3
        mmix.write_tetra(0, 0x20010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 150);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_add_immediate() {
        let mut mmix = MMix::new();
        // ADD $1, $2, 75
        mmix.write_tetra(0, 0x2101024B);
        mmix.set_register(2, 25);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 100);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_add_negative_numbers() {
        let mut mmix = MMix::new();
        // ADD $1, $2, $3
        mmix.write_tetra(0, 0x20010203);
        mmix.set_register(2, (-50i64) as u64);
        mmix.set_register(3, (-30i64) as u64);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -80);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_addu_wrapping() {
        let mut mmix = MMix::new();
        // ADDU $1, $2, $3 (already tested as LDA, but verify here)
        mmix.write_tetra(0, 0x22010203);
        mmix.set_register(2, u64::MAX);
        mmix.set_register(3, 1);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 0); // Wraps around
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_addu_immediate() {
        let mut mmix = MMix::new();
        // ADDU $1, $2, 100
        mmix.write_tetra(0, 0x23010264);
        mmix.set_register(2, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 150);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_2addu_register() {
        let mut mmix = MMix::new();
        // 2ADDU $1, $2, $3
        mmix.write_tetra(0, 0x28010203);
        mmix.set_register(2, 10);
        mmix.set_register(3, 5);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 25); // 2*10 + 5 = 25
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_2addu_immediate() {
        let mut mmix = MMix::new();
        // 2ADDU $1, $2, 7
        mmix.write_tetra(0, 0x29010207);
        mmix.set_register(2, 12);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 31); // 2*12 + 7 = 31
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_4addu_register() {
        let mut mmix = MMix::new();
        // 4ADDU $1, $2, $3
        mmix.write_tetra(0, 0x2A010203);
        mmix.set_register(2, 10);
        mmix.set_register(3, 5);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 45); // 4*10 + 5 = 45
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_4addu_immediate() {
        let mut mmix = MMix::new();
        // 4ADDU $1, $2, 8
        mmix.write_tetra(0, 0x2B010208);
        mmix.set_register(2, 10);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 48); // 4*10 + 8 = 48
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_8addu_register() {
        let mut mmix = MMix::new();
        // 8ADDU $1, $2, $3
        mmix.write_tetra(0, 0x2C010203);
        mmix.set_register(2, 10);
        mmix.set_register(3, 5);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 85); // 8*10 + 5 = 85
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_8addu_immediate() {
        let mut mmix = MMix::new();
        // 8ADDU $1, $2, 15
        mmix.write_tetra(0, 0x2D01020F);
        mmix.set_register(2, 10);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 95); // 8*10 + 15 = 95
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_16addu_register() {
        let mut mmix = MMix::new();
        // 16ADDU $1, $2, $3
        mmix.write_tetra(0, 0x2E010203);
        mmix.set_register(2, 10);
        mmix.set_register(3, 5);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 165); // 16*10 + 5 = 165
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_16addu_immediate() {
        let mut mmix = MMix::new();
        // 16ADDU $1, $2, 20
        mmix.write_tetra(0, 0x2F010214);
        mmix.set_register(2, 10);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 180); // 16*10 + 20 = 180
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_sub_positive_result() {
        let mut mmix = MMix::new();
        // SUB $1, $2, $3
        mmix.write_tetra(0, 0x24010203);
        mmix.set_register(2, 100);
        mmix.set_register(3, 30);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 70);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_sub_negative_result() {
        let mut mmix = MMix::new();
        // SUB $1, $2, $3
        mmix.write_tetra(0, 0x24010203);
        mmix.set_register(2, 30);
        mmix.set_register(3, 100);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -70);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_sub_immediate() {
        let mut mmix = MMix::new();
        // SUB $1, $2, 25
        mmix.write_tetra(0, 0x25010219);
        mmix.set_register(2, 100);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 75);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_subu_wrapping() {
        let mut mmix = MMix::new();
        // SUBU $1, $2, $3
        mmix.write_tetra(0, 0x26010203);
        mmix.set_register(2, 10);
        mmix.set_register(3, 20);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), u64::MAX - 9); // 10 - 20 wraps
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_subu_immediate() {
        let mut mmix = MMix::new();
        // SUBU $1, $2, 30
        mmix.write_tetra(0, 0x2701021E);
        mmix.set_register(2, 100);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 70);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_neg_zero_minus_value() {
        let mut mmix = MMix::new();
        // NEG $1, 0, $3 - effectively 0 - $3
        mmix.write_tetra(0, 0x34010003);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -50);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_neg_immediate_both() {
        let mut mmix = MMix::new();
        // NEG $1, 10, 3 - effectively 10 - 3
        mmix.write_tetra(0, 0x35010A03);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 7);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_neg_one_minus_two() {
        let mut mmix = MMix::new();
        // NEG $1, 1, 2 - effectively 1 - 2 = -1
        mmix.write_tetra(0, 0x35010102);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1) as i64, -1);
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_negu_register() {
        let mut mmix = MMix::new();
        // NEGU $1, 0, $3
        mmix.write_tetra(0, 0x36010003);
        mmix.set_register(3, 50);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), u64::MAX - 49); // 0 - 50 wraps
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_negu_immediate() {
        let mut mmix = MMix::new();
        // NEGU $1, 100, 30
        mmix.write_tetra(0, 0x3701641E);

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 70); // 100 - 30 = 70
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_multiply_add_for_array_indexing() {
        let mut mmix = MMix::new();
        // Common pattern: 8ADDU for array of 64-bit values
        // base_addr + index * 8
        mmix.write_tetra(0, 0x2C010203);
        mmix.set_register(2, 5); // index
        mmix.set_register(3, 1000); // base address

        mmix.execute_instruction();
        assert_eq!(mmix.get_register(1), 1040); // 1000 + 5*8
    }

    #[test]
    fn test_all_arithmetic_instructions_have_tests() {
        let mut mmix = MMix::new();

        // ADD $1, $2, $3
        mmix.write_tetra(0, 0x20010203);
        mmix.set_register(2, 200);
        mmix.set_register(3, 44);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 244);

        // ADDU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x22010203);
        mmix.set_register(2, 900);
        mmix.set_register(3, 33);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 933);

        // 2ADDU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x28010203);
        mmix.set_register(2, 7);
        mmix.set_register(3, 9);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 23); // 2*7 + 9 = 23

        // 4ADDU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x2A010203);
        mmix.set_register(2, 7);
        mmix.set_register(3, 9);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 37); // 4*7 + 9 = 37

        // 8ADDU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x2C010203);
        mmix.set_register(2, 7);
        mmix.set_register(3, 9);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 65); // 8*7 + 9 = 65

        // 16ADDU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x2E010203);
        mmix.set_register(2, 7);
        mmix.set_register(3, 9);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 121); // 16*7 + 9 = 121

        // SUB $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x24010203);
        mmix.set_register(2, 500);
        mmix.set_register(3, 120);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 380);

        // SUBU $1, $2, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x26010203);
        mmix.set_register(2, 5);
        mmix.set_register(3, 8);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), u64::MAX - 2); // 5 - 8 wraps

        // NEG $1, 0, $3 - effectively 0 - $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x34010003);
        mmix.set_register(3, 77);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -77);

        // NEGU $1, 0, $3
        mmix.set_pc(0);
        mmix.write_tetra(0, 0x36010003);
        mmix.set_register(3, 77);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), u64::MAX - 76); // 0 - 77 wraps
    }

    #[test]
    fn test_bitwise_operations() {
        let mut mmix = MMix::new();

        // AND: 0xFF & 0x0F = 0x0F
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 0x0F);
        mmix.write_tetra(0, 0xC8030102); // AND $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x0F);

        // ANDI: 0xFF & 0x0F = 0x0F
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.write_tetra(0, 0xC903010F); // ANDI $3,$1,0x0F
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x0F);

        // OR: 0xF0 | 0x0F = 0xFF
        mmix.set_pc(0);
        mmix.set_register(1, 0xF0);
        mmix.set_register(2, 0x0F);
        mmix.write_tetra(0, 0xC0030102); // OR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFF);

        // ORI: 0xF0 | 0x0F = 0xFF
        mmix.set_pc(0);
        mmix.set_register(1, 0xF0);
        mmix.write_tetra(0, 0xC103010F); // ORI $3,$1,0x0F
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFF);

        // XOR: 0xFF ^ 0xAA = 0x55
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 0xAA);
        mmix.write_tetra(0, 0xC6030102); // XOR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x55);

        // XORI: 0xFF ^ 0xAA = 0x55
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.write_tetra(0, 0xC70301AA); // XORI $3,$1,0xAA
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x55);

        // ANDN: 0xFF & !0x0F = 0xF0
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 0x0F);
        mmix.write_tetra(0, 0xCA030102); // ANDN $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xF0);

        // ANDNI: 0xFF & !0x0F = 0xF0
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.write_tetra(0, 0xCB03010F); // ANDNI $3,$1,0x0F
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xF0);

        // ORN: 0x00 | !0x0F = 0xFFFFFFFFFFFFFFF0
        mmix.set_pc(0);
        mmix.set_register(1, 0x00);
        mmix.set_register(2, 0x0F);
        mmix.write_tetra(0, 0xC2030102); // ORN $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFFF0);

        // ORNI: 0x00 | !0x0F = 0xFFFFFFFFFFFFFFF0
        mmix.set_pc(0);
        mmix.set_register(1, 0x00);
        mmix.write_tetra(0, 0xC303010F); // ORNI $3,$1,0x0F
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFFF0);

        // NAND: !(0xFF & 0xFF) = 0xFFFFFFFFFFFFFF00
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 0xFF);
        mmix.write_tetra(0, 0xCC030102); // NAND $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFF00);

        // NANDI: !(0xFF & 0xFF) = 0xFFFFFFFFFFFFFF00
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.write_tetra(0, 0xCD0301FF); // NANDI $3,$1,0xFF
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFF00);

        // NOR: !(0x00 | 0x00) = 0xFFFFFFFFFFFFFFFF
        mmix.set_pc(0);
        mmix.set_register(1, 0x00);
        mmix.set_register(2, 0x00);
        mmix.write_tetra(0, 0xC4030102); // NOR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFFFF);

        // NORI: !(0x00 | 0x00) = 0xFFFFFFFFFFFFFFFF
        mmix.set_pc(0);
        mmix.set_register(1, 0x00);
        mmix.write_tetra(0, 0xC5030100); // NORI $3,$1,0x00
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFFFF);

        // NXOR: !(0xFF ^ 0xFF) = 0xFFFFFFFFFFFFFFFF
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 0xFF);
        mmix.write_tetra(0, 0xCE030102); // NXOR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFFFF);

        // NXORI: !(0xFF ^ 0xFF) = 0xFFFFFFFFFFFFFFFF
        mmix.set_pc(0);
        mmix.set_register(1, 0xFF);
        mmix.write_tetra(0, 0xCF0301FF); // NXORI $3,$1,0xFF
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFFFFFFFFFFFFFF);

        // MUX: mask=0xF0, Y=0xFF, Z=0x00 -> (0xFF & 0xF0) | (0x00 & !0xF0) = 0xF0
        mmix.set_pc(0);
        mmix.set_special(SpecialReg::RM, 0xF0);
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 0x00);
        mmix.write_tetra(0, 0xD8030102); // MUX $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xF0);

        // MUXI: mask=0xAA, Y=0xFF, Z=0x55 -> (0xFF & 0xAA) | (0x55 & !0xAA) = 0xFF
        mmix.set_pc(0);
        mmix.set_special(SpecialReg::RM, 0xAA);
        mmix.set_register(1, 0xFF);
        mmix.write_tetra(0, 0xD9030155); // MUXI $3,$1,0x55
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFF);
    }

    #[test]
    fn test_bdif() {
        let mut mmix = MMix::new();
        // BDIF: byte difference - each byte independently
        mmix.set_register(1, 0xFF20_3040_5060_7080);
        mmix.set_register(2, 0x1010_1010_1010_1010);
        mmix.write_tetra(0, 0xD0030102); // BDIF $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xEF10_2030_4050_6070);
    }

    #[test]
    fn test_bdifi() {
        let mut mmix = MMix::new();
        // BDIFI: byte difference immediate
        mmix.set_register(1, 0x2020_2020_2020_2020);
        mmix.write_tetra(0, 0xD1030110); // BDIFI $3,$1,0x10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x1010_1010_1010_1010);
    }

    #[test]
    fn test_wdif() {
        let mut mmix = MMix::new();
        // WDIF: wyde difference
        mmix.set_register(1, 0xFFFF_2000_3000_4000);
        mmix.set_register(2, 0x1000_1000_1000_1000);
        mmix.write_tetra(0, 0xD2030102); // WDIF $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xEFFF_1000_2000_3000);
    }

    #[test]
    fn test_wdifi() {
        let mut mmix = MMix::new();
        // WDIFI: wyde difference immediate
        mmix.set_register(1, 0x1000_2000_3000_4000);
        mmix.write_tetra(0, 0xD3030105); // WDIFI $3,$1,5
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x0FFB_1FFB_2FFB_3FFB);
    }

    #[test]
    fn test_tdif() {
        let mut mmix = MMix::new();
        // TDIF: tetra difference
        mmix.set_register(1, 0xFFFFFFFF_20000000);
        mmix.set_register(2, 0x10000000_10000000);
        mmix.write_tetra(0, 0xD4030102); // TDIF $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xEFFFFFFF_10000000);
    }

    #[test]
    fn test_tdifi() {
        let mut mmix = MMix::new();
        // TDIFI: tetra difference immediate
        mmix.set_register(1, 0x10000000_20000000);
        mmix.write_tetra(0, 0xD503010A); // TDIFI $3,$1,10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x0FFFFFF6_1FFFFFF6);
    }

    #[test]
    fn test_odif() {
        let mut mmix = MMix::new();
        // ODIF: octa difference (unsigned)
        mmix.set_register(1, 1000);
        mmix.set_register(2, 300);
        mmix.write_tetra(0, 0xD6030102); // ODIF $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 700);

        // Test clipping to zero
        mmix.set_pc(0);
        mmix.set_register(1, 100);
        mmix.set_register(2, 500);
        mmix.write_tetra(0, 0xD6030102); // ODIF $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
    }

    #[test]
    fn test_odifi() {
        let mut mmix = MMix::new();
        // ODIFI: octa difference immediate
        mmix.set_register(1, 255);
        mmix.write_tetra(0, 0xD70301FF); // ODIFI $3,$1,255
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
    }

    #[test]
    fn test_sadd() {
        let mut mmix = MMix::new();
        // SADD: sideways add (population count of Y \ Z)
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 0x0F);
        mmix.write_tetra(0, 0xDA030102); // SADD $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 4); // 0xFF & !0x0F = 0xF0 has 4 ones
    }

    #[test]
    fn test_saddi_population_count() {
        let mut mmix = MMix::new();
        // SADDI with Z=0 gives population count
        mmix.set_register(1, 0b10101010);
        mmix.write_tetra(0, 0xDB030100); // SADDI $3,$1,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 4); // 4 ones in 10101010
    }

    #[test]
    fn test_mor() {
        let mut mmix = MMix::new();
        // MOR: multiple or (Boolean matrix multiplication)
        // Example: byte reversal with Z = 0x0102040810204080
        mmix.set_register(1, 0x0123456789ABCDEF);
        mmix.set_register(2, 0x0102040810204080);
        mmix.write_tetra(0, 0xDC030102); // MOR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xEFCDAB8967452301); // byte-reversed
    }

    #[test]
    fn test_mori() {
        let mut mmix = MMix::new();
        // MORI: multiple or immediate
        mmix.set_register(1, 0xFF00FF00FF00FF00);
        mmix.write_tetra(0, 0xDD0301FF); // MORI $3,$1,255
        assert!(mmix.execute_instruction());
        // Result should be in bottom byte
        assert_eq!(mmix.get_register(3) & 0xFF, 0xFF);
    }

    #[test]
    fn test_mxor() {
        let mut mmix = MMix::new();
        // MXOR: multiple exclusive-or (matrix product over GF(2))
        // Simple test: identity matrix behavior
        mmix.set_register(1, 0x00);
        mmix.set_register(2, 0x00);
        mmix.write_tetra(0, 0xDE030102); // MXOR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
    }

    #[test]
    fn test_mxori() {
        let mut mmix = MMix::new();
        // MXORI: multiple exclusive-or immediate
        mmix.set_register(1, 0x00);
        mmix.write_tetra(0, 0xDF030100); // MXORI $3,$1,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
    }

    // Shift instruction tests
    #[test]
    fn test_sl() {
        let mut mmix = MMix::new();
        // SL: shift left - 0xFF << 4 = 0xFF0
        mmix.set_register(1, 0xFF);
        mmix.set_register(2, 4);
        mmix.write_tetra(0, 0x38030102); // SL $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFF0);
    }

    #[test]
    fn test_sli() {
        let mut mmix = MMix::new();
        // SLI: shift left immediate - 0x123 << 8 = 0x12300
        mmix.set_register(1, 0x123);
        mmix.write_tetra(0, 0x39030108); // SLI $3,$1,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x12300);
    }

    #[test]
    fn test_sl_overflow() {
        let mut mmix = MMix::new();
        // SL with overflow: shifting out non-sign bits sets overflow
        mmix.set_register(1, 0x8000_0000_0000_0000);
        mmix.set_register(2, 1);
        mmix.write_tetra(0, 0x38030102); // SL $3,$1,$2
        assert!(mmix.execute_instruction());
        // Check that overflow bit is set in rA
        assert!((mmix.get_special(SpecialReg::RA) & RA_V) != 0);
    }

    #[test]
    fn test_sl_large_shift() {
        let mut mmix = MMix::new();
        // SL with shift >= 64 results in 0
        mmix.set_register(1, 0xFFFF_FFFF_FFFF_FFFF);
        mmix.set_register(2, 64);
        mmix.write_tetra(0, 0x38030102); // SL $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
    }

    #[test]
    fn test_slu() {
        let mut mmix = MMix::new();
        // SLU: shift left unsigned - no overflow check
        mmix.set_register(1, 0xFFFF_FFFF_FFFF_FFFF);
        mmix.set_register(2, 8);
        mmix.write_tetra(0, 0x3A030102); // SLU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFF_FFFF_FFFF_FF00);
    }

    #[test]
    fn test_slui() {
        let mut mmix = MMix::new();
        // SLUI: shift left unsigned immediate
        mmix.set_register(1, 0x1);
        mmix.write_tetra(0, 0x3B030110); // SLUI $3,$1,16
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x10000);
    }

    #[test]
    fn test_sr() {
        let mut mmix = MMix::new();
        // SR: arithmetic shift right - negative number stays negative
        mmix.set_register(1, 0xFFFF_FFFF_FFFF_FFF0u64); // -16 as u64
        mmix.set_register(2, 4);
        mmix.write_tetra(0, 0x3C030102); // SR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFF_FFFF_FFFF_FFFFu64); // -1 as u64
    }

    #[test]
    fn test_sri() {
        let mut mmix = MMix::new();
        // SRI: arithmetic shift right immediate - positive number
        mmix.set_register(1, 0x1000);
        mmix.write_tetra(0, 0x3D030104); // SRI $3,$1,4
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x100);
    }

    #[test]
    fn test_sr_large_shift_negative() {
        let mut mmix = MMix::new();
        // SR with large shift on negative number results in -1
        mmix.set_register(1, 0x8000_0000_0000_0000);
        mmix.set_register(2, 100);
        mmix.write_tetra(0, 0x3C030102); // SR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0xFFFF_FFFF_FFFF_FFFF);
    }

    #[test]
    fn test_sr_large_shift_positive() {
        let mut mmix = MMix::new();
        // SR with large shift on positive number results in 0
        mmix.set_register(1, 0x7FFF_FFFF_FFFF_FFFF);
        mmix.set_register(2, 100);
        mmix.write_tetra(0, 0x3C030102); // SR $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
    }

    #[test]
    fn test_sru() {
        let mut mmix = MMix::new();
        // SRU: logical shift right - fills with zeros
        mmix.set_register(1, 0xFFFF_FFFF_FFFF_FFFF);
        mmix.set_register(2, 4);
        mmix.write_tetra(0, 0x3E030102); // SRU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x0FFF_FFFF_FFFF_FFFF);
    }

    #[test]
    fn test_srui() {
        let mut mmix = MMix::new();
        // SRUI: logical shift right immediate
        mmix.set_register(1, 0x8000_0000_0000_0000);
        mmix.write_tetra(0, 0x3F030101); // SRUI $3,$1,1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x4000_0000_0000_0000);
    }

    #[test]
    fn test_sru_large_shift() {
        let mut mmix = MMix::new();
        // SRU with shift >= 64 results in 0
        mmix.set_register(1, 0xFFFF_FFFF_FFFF_FFFF);
        mmix.set_register(2, 64);
        mmix.write_tetra(0, 0x3E030102); // SRU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
    }

    #[test]
    fn test_bn_taken() {
        let mut mmix = MMix::new();
        // BN $1, 0, 5 - Branch if $1 is negative, offset = 5
        mmix.set_register(1, (-42i64) as u64);
        mmix.write_tetra(0, 0x40010005); // BN $1,0,5
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 20); // PC = 0 + 5*4 = 20
    }

    #[test]
    fn test_bn_not_taken() {
        let mut mmix = MMix::new();
        // BN $1, 0, 5 - Branch if $1 is negative, offset = 5
        mmix.set_register(1, 42);
        mmix.write_tetra(0, 0x40010005); // BN $1,0,5
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advances normally
    }

    #[test]
    fn test_bnb_taken() {
        let mut mmix = MMix::new();
        // BNB $1, 0xFFFD - Branch backward if $1 is negative (-3 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, (-42i64) as u64);
        mmix.write_tetra(100, 0x4101FFFD); // BNB $1,0,0xFFFD (offset -3)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 88); // PC = 100 + 4*(-3) = 88
    }

    #[test]
    fn test_bz_taken() {
        let mut mmix = MMix::new();
        // BZ $1, 0, 10 - Branch if $1 is zero
        mmix.set_register(1, 0);
        mmix.write_tetra(0, 0x4201000A); // BZ $1,0,10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 40); // PC = 0 + 10*4 = 40
    }

    #[test]
    fn test_bz_not_taken() {
        let mut mmix = MMix::new();
        // BZ $1, 0, 10 - Branch if $1 is zero
        mmix.set_register(1, 1);
        mmix.write_tetra(0, 0x4201000A); // BZ $1,0,10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bzb_taken() {
        let mut mmix = MMix::new();
        // BZB $1, 0xFFFB - Branch backward if $1 is zero (-5 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x4301FFFB); // BZB $1,0,0xFFFB (offset -5)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 80); // PC = 100 + 4*(-5) = 80
    }

    #[test]
    fn test_bp_taken() {
        let mut mmix = MMix::new();
        // BP $1, 0, 8 - Branch if $1 is positive
        mmix.set_register(1, 42);
        mmix.write_tetra(0, 0x44010008); // BP $1,0,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 32); // PC = 0 + 8*4 = 32
    }

    #[test]
    fn test_bp_not_taken_zero() {
        let mut mmix = MMix::new();
        // BP $1, 0, 8 - Branch if $1 is positive (zero is not positive)
        mmix.set_register(1, 0);
        mmix.write_tetra(0, 0x44010008); // BP $1,0,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bp_not_taken_negative() {
        let mut mmix = MMix::new();
        // BP $1, 0, 8 - Branch if $1 is positive
        mmix.set_register(1, (-1i64) as u64);
        mmix.write_tetra(0, 0x44010008); // BP $1,0,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bpb_taken() {
        let mut mmix = MMix::new();
        // BPB $1, 0xFFFE - Branch backward if $1 is positive (-2 tetras)
        mmix.set_pc(200);
        mmix.set_register(1, 100);
        mmix.write_tetra(200, 0x4501FFFE); // BPB $1,0,0xFFFE (offset -2)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 192); // PC = 200 + 4*(-2) = 192
    }

    #[test]
    fn test_bod_taken() {
        let mut mmix = MMix::new();
        // BOD $1, 0, 3 - Branch if $1 is odd
        mmix.set_register(1, 7);
        mmix.write_tetra(0, 0x46010003); // BOD $1,0,3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 12); // PC = 0 + 3*4 = 12
    }

    #[test]
    fn test_bod_not_taken() {
        let mut mmix = MMix::new();
        // BOD $1, 0, 3 - Branch if $1 is odd
        mmix.set_register(1, 8);
        mmix.write_tetra(0, 0x46010003); // BOD $1,0,3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bodb_taken() {
        let mut mmix = MMix::new();
        // BODB $1, 0xFFFC - Branch backward if $1 is odd (-4 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 15);
        mmix.write_tetra(100, 0x4701FFFC); // BODB $1,0,0xFFFC (offset -4)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 84); // PC = 100 + 4*(-4) = 84
    }

    #[test]
    fn test_bnn_taken_positive() {
        let mut mmix = MMix::new();
        // BNN $1, 0, 6 - Branch if $1 is non-negative (>= 0)
        mmix.set_register(1, 42);
        mmix.write_tetra(0, 0x48010006); // BNN $1,0,6
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 24); // PC = 0 + 6*4 = 24
    }

    #[test]
    fn test_bnn_taken_zero() {
        let mut mmix = MMix::new();
        // BNN $1, 0, 6 - Branch if $1 is non-negative (includes zero)
        mmix.set_register(1, 0);
        mmix.write_tetra(0, 0x48010006); // BNN $1,0,6
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 24);
    }

    #[test]
    fn test_bnn_not_taken() {
        let mut mmix = MMix::new();
        // BNN $1, 0, 6 - Branch if $1 is non-negative
        mmix.set_register(1, (-1i64) as u64);
        mmix.write_tetra(0, 0x48010006); // BNN $1,0,6
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bnnb_taken() {
        let mut mmix = MMix::new();
        // BNNB $1, 0xFFFD - Branch backward if $1 is non-negative (-3 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x4901FFFD); // BNNB $1,0,0xFFFD (offset -3)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 88); // PC = 100 + 4*(-3) = 88
    }

    #[test]
    fn test_bnz_taken() {
        let mut mmix = MMix::new();
        // BNZ $1, 0, 7 - Branch if $1 is non-zero
        mmix.set_register(1, 1);
        mmix.write_tetra(0, 0x4A010007); // BNZ $1,0,7
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 28); // PC = 0 + 7*4 = 28
    }

    #[test]
    fn test_bnz_not_taken() {
        let mut mmix = MMix::new();
        // BNZ $1, 0, 7 - Branch if $1 is non-zero
        mmix.set_register(1, 0);
        mmix.write_tetra(0, 0x4A010007); // BNZ $1,0,7
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bnzb_taken() {
        let mut mmix = MMix::new();
        // BNZB $1, 0xFFF6 - Branch backward if $1 is non-zero (-10 tetras)
        mmix.set_pc(200);
        mmix.set_register(1, 99);
        mmix.write_tetra(200, 0x4B01FFF6); // BNZB $1,0,0xFFF6 (offset -10)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 160); // PC = 200 + 4*(-10) = 160
    }

    #[test]
    fn test_bnp_taken_negative() {
        let mut mmix = MMix::new();
        // BNP $1, 0, 4 - Branch if $1 is non-positive (<= 0)
        mmix.set_register(1, (-5i64) as u64);
        mmix.write_tetra(0, 0x4C010004); // BNP $1,0,4
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 16); // PC = 0 + 4*4 = 16
    }

    #[test]
    fn test_bnp_taken_zero() {
        let mut mmix = MMix::new();
        // BNP $1, 0, 4 - Branch if $1 is non-positive (includes zero)
        mmix.set_register(1, 0);
        mmix.write_tetra(0, 0x4C010004); // BNP $1,0,4
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 16);
    }

    #[test]
    fn test_bnp_not_taken() {
        let mut mmix = MMix::new();
        // BNP $1, 0, 4 - Branch if $1 is non-positive
        mmix.set_register(1, 1);
        mmix.write_tetra(0, 0x4C010004); // BNP $1,0,4
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bnpb_taken() {
        let mut mmix = MMix::new();
        // BNPB $1, 0xFFFF - Branch backward if $1 is non-positive (-1 tetra)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x4D01FFFF); // BNPB $1,0,0xFFFF (offset -1)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 96); // PC = 100 + 4*(-1) = 96
    }

    #[test]
    fn test_bev_taken() {
        let mut mmix = MMix::new();
        // BEV $1, 0, 12 - Branch if $1 is even
        mmix.set_register(1, 8);
        mmix.write_tetra(0, 0x4E01000C); // BEV $1,0,12
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 48); // PC = 0 + 12*4 = 48
    }

    #[test]
    fn test_bev_not_taken() {
        let mut mmix = MMix::new();
        // BEV $1, 0, 12 - Branch if $1 is even
        mmix.set_register(1, 7);
        mmix.write_tetra(0, 0x4E01000C); // BEV $1,0,12
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_bevb_taken() {
        let mut mmix = MMix::new();
        // BEVB $1, 0xFFFE - Branch backward if $1 is even (-2 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x4F01FFFE); // BEVB $1,0,0xFFFE (offset -2)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 92); // PC = 100 + 4*(-2) = 92
    }

    #[test]
    fn test_pbn_taken() {
        let mut mmix = MMix::new();
        // PBN $1, 0, 5 - Probable branch if $1 is negative
        mmix.set_register(1, (-10i64) as u64);
        mmix.write_tetra(0, 0x50010005); // PBN $1,0,5
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 20); // PC = 0 + 5*4 = 20
    }

    #[test]
    fn test_pbnb_taken() {
        let mut mmix = MMix::new();
        // PBNB $1, 0xFFFD - Probable branch backward if $1 is negative (-3 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, (-1i64) as u64);
        mmix.write_tetra(100, 0x5101FFFD); // PBNB $1,0,0xFFFD (offset -3)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 88); // PC = 100 + 4*(-3) = 88
    }

    #[test]
    fn test_pbz_taken() {
        let mut mmix = MMix::new();
        // PBZ $1, 0, 6 - Probable branch if $1 is zero
        mmix.set_register(1, 0);
        mmix.write_tetra(0, 0x52010006); // PBZ $1,0,6
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 24); // PC = 0 + 6*4 = 24
    }

    #[test]
    fn test_pbzb_taken() {
        let mut mmix = MMix::new();
        // PBZB $1, 0xFFFC - Probable branch backward if $1 is zero (-4 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x5301FFFC); // PBZB $1,0,0xFFFC (offset -4)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 84); // PC = 100 + 4*(-4) = 84
    }

    #[test]
    fn test_pbp_taken() {
        let mut mmix = MMix::new();
        // PBP $1, 0, 8 - Probable branch if $1 is positive
        mmix.set_register(1, 50);
        mmix.write_tetra(0, 0x54010008); // PBP $1,0,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 32); // PC = 0 + 8*4 = 32
    }

    #[test]
    fn test_pbpb_taken() {
        let mut mmix = MMix::new();
        // PBPB $1, 0xFFFE - Probable branch backward if $1 is positive (-2 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 1);
        mmix.write_tetra(100, 0x5501FFFE); // PBPB $1,0,0xFFFE (offset -2)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 92); // PC = 100 + 4*(-2) = 92
    }

    #[test]
    fn test_pbod_taken() {
        let mut mmix = MMix::new();
        // PBOD $1, 0, 3 - Probable branch if $1 is odd
        mmix.set_register(1, 11);
        mmix.write_tetra(0, 0x56010003); // PBOD $1,0,3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 12); // PC = 0 + 3*4 = 12
    }

    #[test]
    fn test_pbodb_taken() {
        let mut mmix = MMix::new();
        // PBODB $1, 0xFFFB - Probable branch backward if $1 is odd (-5 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 99);
        mmix.write_tetra(100, 0x5701FFFB); // PBODB $1,0,0xFFFB (offset -5)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 80); // PC = 100 + 4*(-5) = 80
    }

    #[test]
    fn test_pbnn_taken() {
        let mut mmix = MMix::new();
        // PBNN $1, 0, 7 - Probable branch if $1 is non-negative
        mmix.set_register(1, 100);
        mmix.write_tetra(0, 0x58010007); // PBNN $1,0,7
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 28); // PC = 0 + 7*4 = 28
    }

    #[test]
    fn test_pbnnb_taken() {
        let mut mmix = MMix::new();
        // PBNNB $1, 0xFFFF - Probable branch backward if $1 is non-negative (-1 tetra)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x5901FFFF); // PBNNB $1,0,0xFFFF (offset -1)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 96); // PC = 100 + 4*(-1) = 96
    }

    #[test]
    fn test_pbnz_taken() {
        let mut mmix = MMix::new();
        // PBNZ $1, 0, 9 - Probable branch if $1 is non-zero
        mmix.set_register(1, 42);
        mmix.write_tetra(0, 0x5A010009); // PBNZ $1,0,9
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 36); // PC = 0 + 9*4 = 36
    }

    #[test]
    fn test_pbnzb_taken() {
        let mut mmix = MMix::new();
        // PBNZB $1, 0xFFFA - Probable branch backward if $1 is non-zero (-6 tetras)
        mmix.set_pc(200);
        mmix.set_register(1, 1);
        mmix.write_tetra(200, 0x5B01FFFA); // PBNZB $1,0,0xFFFA (offset -6)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 176); // PC = 200 + 4*(-6) = 176
    }

    #[test]
    fn test_pbnp_taken() {
        let mut mmix = MMix::new();
        // PBNP $1, 0, 4 - Probable branch if $1 is non-positive
        mmix.set_register(1, (-100i64) as u64);
        mmix.write_tetra(0, 0x5C010004); // PBNP $1,0,4
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 16); // PC = 0 + 4*4 = 16
    }

    #[test]
    fn test_pbnpb_taken() {
        let mut mmix = MMix::new();
        // PBNPB $1, 0xFFF8 - Probable branch backward if $1 is non-positive (-8 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x5D01FFF8); // PBNPB $1,0,0xFFF8 (offset -8)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 68); // PC = 100 + 4*(-8) = 68
    }

    #[test]
    fn test_pbev_taken() {
        let mut mmix = MMix::new();
        // PBEV $1, 0, 10 - Probable branch if $1 is even
        mmix.set_register(1, 100);
        mmix.write_tetra(0, 0x5E01000A); // PBEV $1,0,10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 40); // PC = 0 + 10*4 = 40
    }

    #[test]
    fn test_pbevb_taken() {
        let mut mmix = MMix::new();
        // PBEVB $1, 0xFFF9 - Probable branch backward if $1 is even (-7 tetras)
        mmix.set_pc(100);
        mmix.set_register(1, 0);
        mmix.write_tetra(100, 0x5F01FFF9); // PBEVB $1,0,0xFFF9 (offset -7)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 72); // PC = 100 + 4*(-7) = 72
    }

    #[test]
    fn test_jmp_forward() {
        let mut mmix = MMix::new();
        // JMP +10 (offset = 10)
        mmix.write_tetra(0, 0xF000000A); // JMP 0,0,10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 40); // PC = 0 + 10*4 = 40
    }

    #[test]
    fn test_jmp_large_forward_offset() {
        let mut mmix = MMix::new();
        mmix.set_pc(100);
        // XYZ is unsigned in the forward opcode: 0xFFFFFB is 16777211, not -5.
        mmix.write_tetra(100, 0xF0FFFFFB); // JMP 0xFFFFFB
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 100 + 16777211 * 4); // PC = 100 + 16777211*4
    }

    #[test]
    fn test_jmpb() {
        let mut mmix = MMix::new();
        mmix.set_pc(100);
        // XYZ = 0xFFFFFB is 0xFFFFFB - 2^24 = -5 tetras.
        mmix.write_tetra(100, 0xF1FFFFFB); // JMPB 0xFFFFFB
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 80); // PC = 100 - 5*4 = 80
    }

    #[test]
    fn test_pushj() {
        let mut mmix = MMix::new();
        // PUSHJ $0, 0, 10 - Push and jump to relative offset 10
        mmix.write_tetra(0, 0xF200000A); // PUSHJ $0,0,10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 40); // PC = 0 + 10*4 = 40
        assert_eq!(mmix.get_special(SpecialReg::RJ), 4); // Return address saved
    }

    #[test]
    fn test_pushjb() {
        let mut mmix = MMix::new();
        mmix.set_pc(100);
        // YZ = 0xFFFB is 0xFFFB - 65536 = -5 tetras.
        mmix.write_tetra(100, 0xF300FFFB); // PUSHJB $0,0xFFFB
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 80); // PC = 100 - 5*4 = 80
        assert_eq!(mmix.get_special(SpecialReg::RJ), 104); // Return address saved
    }

    #[test]
    fn test_geta() {
        let mut mmix = MMix::new();
        mmix.set_pc(100);
        // GETA $1, 0, 10 - Get address at relative offset 10
        mmix.write_tetra(100, 0xF401000A); // GETA $1,0,10
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 140); // Addr = 100 + 10*4 = 140
        assert_eq!(mmix.get_pc(), 104); // PC advances normally
    }

    #[test]
    fn test_getab() {
        let mut mmix = MMix::new();
        mmix.set_pc(100);
        // YZ = 0xFFFB is 0xFFFB - 65536 = -5 tetras.
        mmix.write_tetra(100, 0xF501FFFB); // GETAB $1,0xFFFB
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 80); // Addr = 100 - 5*4 = 80
        assert_eq!(mmix.get_pc(), 104);
    }

    /// Assemble a whole program, load it and run it to HALT, returning $255.
    /// Zeroed memory decodes as TRAP 0,Halt,0, so a mis-jump halts with 0
    /// rather than hanging -- which is what makes these assertions bite.
    fn run_to_halt(source: &str) -> u64 {
        use crate::debugger::{entry_point, write_image};
        use crate::mmixal::MMixAssembler;

        let mut asm = MMixAssembler::new(source, "<test>");
        asm.parse().expect("program must assemble");
        let mut mmix = MMix::new();
        write_image(&mut mmix, &asm);
        mmix.set_pc(entry_point(&asm));
        mmix.run();
        mmix.get_register(255)
    }

    #[test]
    fn pop_returns_a_callee_computed_remainder_to_the_hole() {
        // Each case: dividend, and its Euclidean remainder mod 100.
        let cases = [
            (42, 42),
            (142, 42),
            (-58, 42),
            (-194, 6),
            (0, 0),
            (100, 0),
            (-100, 0),
            (-1, 99),
        ];
        for (dividend, expected) in cases {
            let source = format!(
                "\
\tLOC\t#100
Main\tSETI\t$1,{dividend}
\tSET\t$2,100
\tPUSHJ\t$0,RemEuclid
\tSET\t$255,$0
\tTRAP\t0,Halt,0
RemEuclid\tDIV\t$2,$0,$1
\tMUL\t$3,$2,$1
\tSUB\t$0,$0,$3
\tBNN\t$0,Done
\tADDU\t$0,$0,$1
Done\tPOP\t1,0
"
            );
            assert_eq!(run_to_halt(&source), expected, "{dividend} mod 100");
        }
    }

    #[test]
    fn pushjb_reaches_a_backward_callee() {
        // The PUSHJB sits ten tetras past AddFunc, so YZ is 65536 - 10.
        // Read as a magnitude that lands in zeroed memory and halts with 0.
        let source = "\
\tLOC\t#100
AddFunc\tADDU\t$0,$0,$1
\tPOP\t1,0
Main\tSETI\t$1,40
\tSETI\t$2,2
\tPUSHJB\t$0,AddFunc
\tSET\t$255,$0
\tTRAP\t0,Halt,0
";
        assert_eq!(run_to_halt(source), 42);
    }

    #[test]
    fn forward_branch_past_half_the_field_still_goes_forward() {
        // BZ's YZ is 32768; sign extension reads it as -32768.
        let source = "\
\tLOC\t#100
Start\tSETI\t$1,0
\tBZ\t$1,Far
\tSETI\t$255,1
\tTRAP\t0,Halt,0
\tLOC\t#20110
Far\tSETI\t$255,42
\tTRAP\t0,Halt,0
";
        assert_eq!(run_to_halt(source), 42);
    }

    #[test]
    fn backward_branch_past_half_the_field_still_goes_backward() {
        // BZB's YZ is 32764, which is 32764 - 65536 = -32772 tetras.
        // Sign extension reads it as +32764.
        let source = "\
\tLOC\t#100
Back\tSETI\t$255,42
\tTRAP\t0,Halt,0
\tLOC\t#20100
Main\tSETI\t$1,0
\tBZB\t$1,Back
\tSETI\t$255,1
\tTRAP\t0,Halt,0
";
        assert_eq!(run_to_halt(source), 42);
    }

    #[test]
    fn pushj_forward_past_half_the_field_still_goes_forward() {
        // PUSHJ's YZ is 32772; sign extension reads it as -32764.
        let source = "\
\tLOC\t#100
Main\tSETI\t$1,40
\tPUSHJ\t$0,Far
\tSET\t$255,$0
\tTRAP\t0,Halt,0
\tLOC\t#20120
Far\tSETI\t$0,42
\tPOP\t1,0
";
        assert_eq!(run_to_halt(source), 42);
    }

    #[test]
    fn incl_adds_its_immediate() {
        let source = "\
\tLOC\t#100
Main\tSETI\t$1,100
\tINCL\t$1,#203
\tSET\t$255,$1
\tTRAP\t0,Halt,0
";
        assert_eq!(run_to_halt(source), 100 + 0x203);
    }

    #[test]
    fn test_geta_forward_field_above_half_the_range() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        // YZ = 0xC000 is 49152 tetras forward, not -16384.
        mmix.write_tetra(0x100, 0xF401C000); // GETA $1,0xC000
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0x100 + 49152 * 4);
    }

    #[test]
    fn test_jmpb_small_field_is_a_far_backward_jump() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x4000000);
        // XYZ = 5 is 5 - 2^24 tetras, the far end of JMPB's reach.
        mmix.write_tetra(0x4000000, 0xF1000005); // JMPB 5
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x4000000 - (16777216 - 5) * 4);
    }

    #[test]
    fn test_getab_small_field_is_a_far_backward_address() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x40000);
        // YZ = 5 is 5 - 65536 tetras, the far end of GETAB's reach.
        mmix.write_tetra(0x40000, 0xF5010005); // GETAB $1,5
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0x40000 - (65536 - 5) * 4);
    }

    #[test]
    fn test_pop_frame_yz_above_half_the_field_resumes_forward() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.write_tetra(0x100, 0xF2000004); // PUSHJ $0,4 -> 0x110, rJ = 0x104
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x104);
        // POP resumes at rJ + 4*YZ, unsigned: 0x8000 is forward, not -32768.
        mmix.write_tetra(0x110, 0xF8008000); // POP 0,0x8000
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x104 + 32768 * 4);
    }

    #[test]
    fn test_pop_without_a_frame_resumes_forward_from_rj() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_special(SpecialReg::RJ, 0x200);
        mmix.write_tetra(0x100, 0xF8008000); // POP 0,0x8000
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x200 + 32768 * 4);
    }

    #[test]
    fn test_put_get() {
        let mut mmix = MMix::new();
        // PUT rR, $1 - Put value from $1 into rR (special register 6)
        mmix.set_register(1, 0x123456789ABCDEF0);
        mmix.write_tetra(0, 0xF6060001); // PUT X=6 (rR), Y=0, Z=1 ($1)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RR), 0x123456789ABCDEF0);

        // GET $2, rR - Get value from rR into $2
        mmix.write_tetra(4, 0xFE020006); // GET X=2 ($2), Y=0, Z=6 (rR)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(2), 0x123456789ABCDEF0);
    }

    #[test]
    fn test_puti_ignores_y_and_stores_z_alone() {
        let mut mmix = MMix::new();
        // PUTI rH, YZ=0x1234 - Y is ignored; only Z=0x34 reaches rH.
        mmix.write_tetra(0, 0xF7031234); // PUTI X=3 (rH), Y=0x12, Z=0x34
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RH), 0x34);
    }

    #[test]
    fn test_put_x_at_32_names_no_special_register() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(1, 42);
        mmix.write_tetra(0, 0xF6200001); // PUT X=32,$1 -- no register above 31
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
    }

    #[test]
    fn test_put_rc_is_rejected_with_a_privileged_operation_interrupt() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(1, 222);
        mmix.write_tetra(0, 0xF6080001); // PUT X=8 (rC), $1
        assert!(!mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RC),
            0,
            "the write did not land"
        );
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rC"));
        assert!(handle.diagnostics()[0].contains("privileged"));
    }

    #[test]
    fn test_put_rn_is_rejected_with_an_illegal_instruction_interrupt() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_special(SpecialReg::RN, 111);
        mmix.set_register(1, 222);
        mmix.write_tetra(0, 0xF6090001); // PUT X=9 (rN), $1
        assert!(!mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RN),
            111,
            "the write did not land"
        );
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rN"));
    }

    #[test]
    fn test_put_ro_is_rejected_with_an_illegal_instruction_interrupt() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        let ro = mmix.get_special(SpecialReg::RO);
        mmix.set_register(1, 222);
        mmix.write_tetra(0, 0xF60A0001); // PUT X=10 (rO), $1
        assert!(!mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RO),
            ro,
            "the write did not land"
        );
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rO"));
    }

    #[test]
    fn test_put_rs_is_rejected_with_an_illegal_instruction_interrupt() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        let rs = mmix.get_special(SpecialReg::RS);
        mmix.set_register(1, 222);
        mmix.write_tetra(0, 0xF60B0001); // PUT X=11 (rS), $1
        assert!(!mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RS),
            rs,
            "the write did not land"
        );
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rS"));
    }

    #[test]
    fn test_put_rg_below_32_is_rejected() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(1, 31);
        mmix.write_tetra(0, 0xF6130001); // PUT X=19 (rG), $1
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RG), 32, "rG unchanged");
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rG"));
    }

    #[test]
    fn test_put_rg_below_rl_is_rejected() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_special(SpecialReg::RL, 40);
        mmix.set_register(1, 35); // >= 32, but < rL
        mmix.write_tetra(0, 0xF6130001); // PUT X=19 (rG), $1
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RG), 32, "rG unchanged");
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
    }

    #[test]
    fn test_put_rg_above_255_is_rejected() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(1, 256);
        mmix.write_tetra(0, 0xF6130001); // PUT X=19 (rG), $1
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RG), 32, "rG unchanged");
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
    }

    #[test]
    fn test_put_rg_accepts_the_low_boundary_32() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RG, 60);
        mmix.set_register(1, 32);
        mmix.write_tetra(0, 0xF6130001); // PUT X=19 (rG), $1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RG), 32);
    }

    #[test]
    fn test_put_rg_accepts_the_high_boundary_255() {
        let mut mmix = MMix::new();
        mmix.set_register(1, 255);
        mmix.write_tetra(0, 0xF6130001); // PUT X=19 (rG), $1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RG), 255);
    }

    #[test]
    fn test_put_rg_accepts_a_value_equal_to_rl() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RL, 40);
        mmix.set_register(1, 40);
        mmix.write_tetra(0, 0xF6130001); // PUT X=19 (rG), $1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RG), 40);
    }

    #[test]
    fn test_put_rg_raising_zeroes_the_newly_local_span() {
        let mut mmix = MMix::new();
        mmix.set_register(40, 0xDEAD); // global while rG = 32
        mmix.set_register(70, 777); // outside the raised span; stays global

        mmix.write_tetra(0, 0xF713003C); // PUTI rG,60
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_special(SpecialReg::RG), 60);
        assert_eq!(
            mmix.get_register(40),
            0,
            "reclassified into the local/marginal range reads zero"
        );
        assert_eq!(
            mmix.get_register(70),
            777,
            "outside the span keeps its value"
        );
    }

    #[test]
    fn test_put_rg_lowering_zeroes_the_newly_global_span() {
        let mut mmix = MMix::new();
        mmix.set_register(40, 0xDEAD); // global while rG = 32
        mmix.set_special(SpecialReg::RG, 60); // raw raise: $40 goes stale-marginal
        mmix.set_register(70, 777); // outside the lowered span; stays global

        mmix.write_tetra(0, 0xF7130020); // PUTI rG,32
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_special(SpecialReg::RG), 32);
        assert_eq!(
            mmix.get_register(40),
            0,
            "reclassified back into the global range reads zero"
        );
        assert_eq!(
            mmix.get_register(70),
            777,
            "outside the span keeps its value"
        );
    }

    #[test]
    fn test_put_rg_zeroes_a_reclassified_register_end_to_end() {
        // SET $40,#DEAD / PUT rG,60 / PUT rG,32 / ADD $5,$40,$0 -- C6's
        // adversarial review (2026-09-17) found this left $5 = #DEAD;
        // MMIXware gives 0.
        let mut mmix = MMix::new();
        mmix.set_register(40, 0xDEAD); // global while rG = 32

        mmix.write_tetra(0, 0xF713003C); // PUTI rG,60
        assert!(mmix.execute_instruction());
        mmix.write_tetra(4, 0xF7130020); // PUTI rG,32
        assert!(mmix.execute_instruction());
        mmix.write_tetra(8, 0x20052800); // ADD $5,$40,$0
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_register(5), 0);
    }

    #[test]
    fn test_set_register_zeros_a_stale_marginal_gap() {
        // Raising rG is a raw write with no rL rules of its own, so it can
        // leave a stale value in a register that becomes marginal. Writing
        // a higher register must still zero it out when the write claims
        // the range.
        let mut mmix = MMix::new();
        mmix.set_register(40, 0xDEAD); // global while rG = 32
        mmix.set_special(SpecialReg::RG, 50); // $40 is now marginal, still 0xDEAD

        mmix.set_register(45, 123);

        assert_eq!(mmix.get_register(40), 0, "the gap zeros out");
        assert_eq!(mmix.get_register(45), 123);
        assert_eq!(mmix.get_special(SpecialReg::RL), 46);
    }

    #[test]
    fn test_put_rl_with_a_larger_z_leaves_rl_unchanged() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RL, 5);

        // PUTI rL,10 - z > rL, so rL stays at min(10, 5) = 5.
        mmix.write_tetra(0, 0xF714000A);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RL), 5);
    }

    #[test]
    fn test_put_rl_zeros_the_registers_it_drops() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RL, 6);
        mmix.set_register(4, 777);

        // PUTI rL,3 - drops $3..$5 out of the local range.
        mmix.write_tetra(0, 0xF7140003);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RL), 3);

        // ADD $1,$4,$0 reads the dropped $4 with no intervening write: zero.
        // $1 is already local (1 < 3), so its own destination rise is a
        // no-op and does not confound this read.
        mmix.write_tetra(4, 0x20010400);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
    }

    #[test]
    fn test_put_rl_survives_an_rl_beyond_the_register_file() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RL, u64::MAX);
        mmix.set_register(200, 42); // global at rG = 32

        // PUTI rL,3
        mmix.write_tetra(0, 0xF7140003);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_special(SpecialReg::RL), 3);
        assert_eq!(mmix.get_register(200), 42, "a global is not a local");
    }

    /// `UNSAVE` can no longer produce an rG/rL pair this far out of range —
    /// its own validation now refuses a packed rG above 255 or a local
    /// count above the packed rG — so this state is planted directly
    /// through `set_special`, which stays raw by design.
    #[test]
    fn test_put_rl_after_an_out_of_range_state_naming_more_registers_than_the_file_holds() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RG, 1000); // beyond the register file
        mmix.set_special(SpecialReg::RL, 500);

        // PUTI rL,3
        mmix.write_tetra(0, 0xF7140003);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_special(SpecialReg::RL), 3);
    }

    /// UNSAVE restores rG from guest memory, so rG can name a register the
    /// file does not have. `claim_local` must compare against it at full
    /// width: a byte-narrowed comparison turns a real local, sitting below
    /// the true rG but above its truncated low byte, into a global that is
    /// never claimed. `PUT rG` carries no validation yet, so this state is
    /// reachable today; C7's validation may close it later.
    #[test]
    fn test_register_claims_local_when_rg_names_no_real_register() {
        let mut mmix = MMix::new();
        mmix.set_register(150, 0xDEAD); // global while rG = 32 (the default)
        mmix.set_special(SpecialReg::RG, 300); // beyond the register file
        mmix.set_special(SpecialReg::RL, 3);

        // $150 is now marginal (3 <= 150 < 300); claiming $200 sweeps it.
        mmix.set_register(200, 777);

        assert_eq!(mmix.get_special(SpecialReg::RL), 201);
        assert_eq!(
            mmix.get_register(150),
            0,
            "the claim zeroed the marginal range"
        );
        assert_eq!(mmix.get_register(200), 777);
    }

    /// `SAVE`'s own X < rG rejection, and proof that `writes_general_register_x`'s
    /// pre-claim (real for every other destination-writing opcode) is
    /// skipped for `SAVE`: were it not, claiming a marginal $45 here would
    /// raise rL and zero $40 before this arm ever ran.
    #[test]
    fn test_save_rejects_a_destination_below_rg_leaving_the_machine_unchanged() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(40, 0xDEAD); // global while rG = 32
        mmix.set_special(SpecialReg::RG, 50);
        mmix.set_special(SpecialReg::RL, 3);

        // SAVE $45,0 - $45 < rG (50): a local, rejected.
        mmix.write_tetra(0, 0xFA2D0000);
        assert!(!mmix.execute_instruction());

        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(mmix.get_special(SpecialReg::RL), 3, "rL is untouched");
        assert_eq!(
            mmix.get_register(40),
            0xDEAD,
            "the destination-rise pre-claim never ran"
        );
        assert_eq!(mmix.get_register(45), 0, "the rejected SAVE wrote nothing");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("SAVE"));
    }

    /// `writes_general_register_x` decides, for every opcode byte, whether
    /// the instruction's X field becomes a live local before the
    /// instruction runs. This table is derived independently from
    /// `MMIX.md` and from `Opcode`, never from the predicate itself, so a
    /// single misclassified byte fails as itself rather than surviving in
    /// an aggregate comparison.
    #[test]
    fn test_destination_predicate_matches_an_independent_table_at_every_byte() {
        use crate::mmixal::Opcode;

        // (byte, mnemonic, is a general-register destination before the
        // instruction runs). PRELD, PREGO, PREST, SYNCD and SYNCID parse X
        // as a register in checksmix but take an immediate byte count in
        // the specification, so all ten forms are false. PUSHJ and PUSHGO
        // write nothing to $X directly, but $X is the call hole and must be
        // local first, so both are true. PUT's X names a special register,
        // POP's X is a count, UNSAVE's X is fixed at 0, and TRAP/TRIP/SYNC/
        // SWYM/RESUME/JMP/JMPB/HALT carry no general-register operand in X.
        let table: [(u8, Opcode, bool); 256] = [
            (0x00, Opcode::TRAP, false),
            (0x01, Opcode::FCMP, true),
            (0x02, Opcode::FUN, true),
            (0x03, Opcode::FEQL, true),
            (0x04, Opcode::FADD, true),
            (0x05, Opcode::FIX, true),
            (0x06, Opcode::FSUB, true),
            (0x07, Opcode::FIXU, true),
            (0x08, Opcode::FLOT, true),
            (0x09, Opcode::FLOTI, true),
            (0x0A, Opcode::FLOTU, true),
            (0x0B, Opcode::FLOTUI, true),
            (0x0C, Opcode::SFLOT, true),
            (0x0D, Opcode::SFLOTI, true),
            (0x0E, Opcode::SFLOTU, true),
            (0x0F, Opcode::SFLOTUI, true),
            (0x10, Opcode::FMUL, true),
            (0x11, Opcode::FCMPE, true),
            (0x12, Opcode::FUNE, true),
            (0x13, Opcode::FEQLE, true),
            (0x14, Opcode::FDIV, true),
            (0x15, Opcode::FSQRT, true),
            (0x16, Opcode::FREM, true),
            (0x17, Opcode::FINT, true),
            (0x18, Opcode::MUL, true),
            (0x19, Opcode::MULI, true),
            (0x1A, Opcode::MULU, true),
            (0x1B, Opcode::MULUI, true),
            (0x1C, Opcode::DIV, true),
            (0x1D, Opcode::DIVI, true),
            (0x1E, Opcode::DIVU, true),
            (0x1F, Opcode::DIVUI, true),
            (0x20, Opcode::ADD, true),
            (0x21, Opcode::ADDI, true),
            (0x22, Opcode::ADDU, true),
            (0x23, Opcode::ADDUI, true),
            (0x24, Opcode::SUB, true),
            (0x25, Opcode::SUBI, true),
            (0x26, Opcode::SUBU, true),
            (0x27, Opcode::SUBUI, true),
            (0x28, Opcode::ADDU2, true),
            (0x29, Opcode::ADDU2I, true),
            (0x2A, Opcode::ADDU4, true),
            (0x2B, Opcode::ADDU4I, true),
            (0x2C, Opcode::ADDU8, true),
            (0x2D, Opcode::ADDU8I, true),
            (0x2E, Opcode::ADDU16, true),
            (0x2F, Opcode::ADDU16I, true),
            (0x30, Opcode::CMP, true),
            (0x31, Opcode::CMPI, true),
            (0x32, Opcode::CMPU, true),
            (0x33, Opcode::CMPUI, true),
            (0x34, Opcode::NEG, true),
            (0x35, Opcode::NEGI, true),
            (0x36, Opcode::NEGU, true),
            (0x37, Opcode::NEGUI, true),
            (0x38, Opcode::SL, true),
            (0x39, Opcode::SLI, true),
            (0x3A, Opcode::SLU, true),
            (0x3B, Opcode::SLUI, true),
            (0x3C, Opcode::SR, true),
            (0x3D, Opcode::SRI, true),
            (0x3E, Opcode::SRU, true),
            (0x3F, Opcode::SRUI, true),
            (0x40, Opcode::BN, false),
            (0x41, Opcode::BNB, false),
            (0x42, Opcode::BZ, false),
            (0x43, Opcode::BZB, false),
            (0x44, Opcode::BP, false),
            (0x45, Opcode::BPB, false),
            (0x46, Opcode::BOD, false),
            (0x47, Opcode::BODB, false),
            (0x48, Opcode::BNN, false),
            (0x49, Opcode::BNNB, false),
            (0x4A, Opcode::BNZ, false),
            (0x4B, Opcode::BNZB, false),
            (0x4C, Opcode::BNP, false),
            (0x4D, Opcode::BNPB, false),
            (0x4E, Opcode::BEV, false),
            (0x4F, Opcode::BEVB, false),
            (0x50, Opcode::PBN, false),
            (0x51, Opcode::PBNB, false),
            (0x52, Opcode::PBZ, false),
            (0x53, Opcode::PBZB, false),
            (0x54, Opcode::PBP, false),
            (0x55, Opcode::PBPB, false),
            (0x56, Opcode::PBOD, false),
            (0x57, Opcode::PBODB, false),
            (0x58, Opcode::PBNN, false),
            (0x59, Opcode::PBNNB, false),
            (0x5A, Opcode::PBNZ, false),
            (0x5B, Opcode::PBNZB, false),
            (0x5C, Opcode::PBNP, false),
            (0x5D, Opcode::PBNPB, false),
            (0x5E, Opcode::PBEV, false),
            (0x5F, Opcode::PBEVB, false),
            (0x60, Opcode::CSN, true),
            (0x61, Opcode::CSNI, true),
            (0x62, Opcode::CSZ, true),
            (0x63, Opcode::CSZI, true),
            (0x64, Opcode::CSP, true),
            (0x65, Opcode::CSPI, true),
            (0x66, Opcode::CSOD, true),
            (0x67, Opcode::CSODI, true),
            (0x68, Opcode::CSNN, true),
            (0x69, Opcode::CSNNI, true),
            (0x6A, Opcode::CSNZ, true),
            (0x6B, Opcode::CSNZI, true),
            (0x6C, Opcode::CSNP, true),
            (0x6D, Opcode::CSNPI, true),
            (0x6E, Opcode::CSEV, true),
            (0x6F, Opcode::CSEVI, true),
            (0x70, Opcode::ZSN, true),
            (0x71, Opcode::ZSNI, true),
            (0x72, Opcode::ZSZ, true),
            (0x73, Opcode::ZSZI, true),
            (0x74, Opcode::ZSP, true),
            (0x75, Opcode::ZSPI, true),
            (0x76, Opcode::ZSOD, true),
            (0x77, Opcode::ZSODI, true),
            (0x78, Opcode::ZSNN, true),
            (0x79, Opcode::ZSNNI, true),
            (0x7A, Opcode::ZSNZ, true),
            (0x7B, Opcode::ZSNZI, true),
            (0x7C, Opcode::ZSNP, true),
            (0x7D, Opcode::ZSNPI, true),
            (0x7E, Opcode::ZSEV, true),
            (0x7F, Opcode::ZSEVI, true),
            (0x80, Opcode::LDB, true),
            (0x81, Opcode::LDBI, true),
            (0x82, Opcode::LDBU, true),
            (0x83, Opcode::LDBUI, true),
            (0x84, Opcode::LDW, true),
            (0x85, Opcode::LDWI, true),
            (0x86, Opcode::LDWU, true),
            (0x87, Opcode::LDWUI, true),
            (0x88, Opcode::LDT, true),
            (0x89, Opcode::LDTI, true),
            (0x8A, Opcode::LDTU, true),
            (0x8B, Opcode::LDTUI, true),
            (0x8C, Opcode::LDO, true),
            (0x8D, Opcode::LDOI, true),
            (0x8E, Opcode::LDOU, true),
            (0x8F, Opcode::LDOUI, true),
            (0x90, Opcode::LDSF, true),
            (0x91, Opcode::LDSFI, true),
            (0x92, Opcode::LDHT, true),
            (0x93, Opcode::LDHTI, true),
            (0x94, Opcode::CSWAP, true),
            (0x95, Opcode::CSWAPI, true),
            (0x96, Opcode::LDUNC, true),
            (0x97, Opcode::LDUNCI, true),
            (0x98, Opcode::LDVTS, true),
            (0x99, Opcode::LDVTSI, true),
            (0x9A, Opcode::PRELD, false),
            (0x9B, Opcode::PRELDI, false),
            (0x9C, Opcode::PREGO, false),
            (0x9D, Opcode::PREGOI, false),
            (0x9E, Opcode::GO, true),
            (0x9F, Opcode::GOI, true),
            (0xA0, Opcode::STB, false),
            (0xA1, Opcode::STBI, false),
            (0xA2, Opcode::STBU, false),
            (0xA3, Opcode::STBUI, false),
            (0xA4, Opcode::STW, false),
            (0xA5, Opcode::STWI, false),
            (0xA6, Opcode::STWU, false),
            (0xA7, Opcode::STWUI, false),
            (0xA8, Opcode::STT, false),
            (0xA9, Opcode::STTI, false),
            (0xAA, Opcode::STTU, false),
            (0xAB, Opcode::STTUI, false),
            (0xAC, Opcode::STO, false),
            (0xAD, Opcode::STOI, false),
            (0xAE, Opcode::STOU, false),
            (0xAF, Opcode::STOUI, false),
            (0xB0, Opcode::STSF, false),
            (0xB1, Opcode::STSFI, false),
            (0xB2, Opcode::STHT, false),
            (0xB3, Opcode::STHTI, false),
            (0xB4, Opcode::STCO, false),
            (0xB5, Opcode::STCOI, false),
            (0xB6, Opcode::STUNC, false),
            (0xB7, Opcode::STUNCI, false),
            (0xB8, Opcode::SYNCD, false),
            (0xB9, Opcode::SYNCDI, false),
            (0xBA, Opcode::PREST, false),
            (0xBB, Opcode::PRESTI, false),
            (0xBC, Opcode::SYNCID, false),
            (0xBD, Opcode::SYNCIDI, false),
            (0xBE, Opcode::PUSHGO, true),
            (0xBF, Opcode::PUSHGOI, true),
            (0xC0, Opcode::OR, true),
            (0xC1, Opcode::ORI, true),
            (0xC2, Opcode::ORN, true),
            (0xC3, Opcode::ORNI, true),
            (0xC4, Opcode::NOR, true),
            (0xC5, Opcode::NORI, true),
            (0xC6, Opcode::XOR, true),
            (0xC7, Opcode::XORI, true),
            (0xC8, Opcode::AND, true),
            (0xC9, Opcode::ANDI, true),
            (0xCA, Opcode::ANDN, true),
            (0xCB, Opcode::ANDNI, true),
            (0xCC, Opcode::NAND, true),
            (0xCD, Opcode::NANDI, true),
            (0xCE, Opcode::NXOR, true),
            (0xCF, Opcode::NXORI, true),
            (0xD0, Opcode::BDIF, true),
            (0xD1, Opcode::BDIFI, true),
            (0xD2, Opcode::WDIF, true),
            (0xD3, Opcode::WDIFI, true),
            (0xD4, Opcode::TDIF, true),
            (0xD5, Opcode::TDIFI, true),
            (0xD6, Opcode::ODIF, true),
            (0xD7, Opcode::ODIFI, true),
            (0xD8, Opcode::MUX, true),
            (0xD9, Opcode::MUXI, true),
            (0xDA, Opcode::SADD, true),
            (0xDB, Opcode::SADDI, true),
            (0xDC, Opcode::MOR, true),
            (0xDD, Opcode::MORI, true),
            (0xDE, Opcode::MXOR, true),
            (0xDF, Opcode::MXORI, true),
            (0xE0, Opcode::SETH, true),
            (0xE1, Opcode::SETMH, true),
            (0xE2, Opcode::SETML, true),
            (0xE3, Opcode::SETL, true),
            (0xE4, Opcode::INCH, true),
            (0xE5, Opcode::INCMH, true),
            (0xE6, Opcode::INCML, true),
            (0xE7, Opcode::INCL, true),
            (0xE8, Opcode::ORH, true),
            (0xE9, Opcode::ORMH, true),
            (0xEA, Opcode::ORML, true),
            (0xEB, Opcode::ORL, true),
            (0xEC, Opcode::ANDNH, true),
            (0xED, Opcode::ANDNMH, true),
            (0xEE, Opcode::ANDNML, true),
            (0xEF, Opcode::ANDNL, true),
            (0xF0, Opcode::JMP, false),
            (0xF1, Opcode::JMPB, false),
            (0xF2, Opcode::PUSHJ, true),
            (0xF3, Opcode::PUSHJB, true),
            (0xF4, Opcode::GETA, true),
            (0xF5, Opcode::GETAB, true),
            (0xF6, Opcode::PUT, false),
            (0xF7, Opcode::PUTI, false),
            (0xF8, Opcode::POP, false),
            (0xF9, Opcode::RESUME, false),
            (0xFA, Opcode::SAVE, true),
            (0xFB, Opcode::UNSAVE, false),
            (0xFC, Opcode::SYNC, false),
            (0xFD, Opcode::SWYM, false),
            (0xFE, Opcode::GET, true),
            (0xFF, Opcode::TRIP, false),
        ];

        assert_eq!(table.len(), 256, "the table must cover every opcode byte");

        for (i, (byte, mnemonic, expected)) in table.iter().enumerate() {
            assert_eq!(
                *byte, i as u8,
                "row {i} is out of place: carries byte {byte:#04X}"
            );
            assert_eq!(
                Opcode::try_from(*byte).unwrap(),
                *mnemonic,
                "row {byte:#04X} names {mnemonic:?}, but Opcode disagrees"
            );
            let actual = MMix::writes_general_register_x(*byte);
            assert_eq!(
                actual, *expected,
                "byte {byte:#04X} ({mnemonic:?}): predicate says {actual}, table says {expected}"
            );
        }
    }

    #[test]
    fn test_put_rl_keeps_the_globals_in_a_state_mmix_rejects() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RG, 60);
        mmix.set_register(55, 777); // local while rG = 60, so rL rises to 56
        mmix.set_special(SpecialReg::RG, 32); // $55 is global now

        // PUTI rL,3
        mmix.write_tetra(0, 0xF7140003);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_special(SpecialReg::RL), 3);
        assert_eq!(mmix.get_register(55), 777, "a global keeps its value");
    }

    #[test]
    fn test_get_of_rl_into_a_marginal_destination_sees_the_raised_value() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RG, 32);
        mmix.set_special(SpecialReg::RL, 5);

        // GET $10,rL
        mmix.write_tetra(0, 0xFE0A0014);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_register(10), 11);
        assert_eq!(mmix.get_special(SpecialReg::RL), 11);
    }

    #[test]
    fn test_arithmetic_destination_rise_leaves_a_marginal_source_reading_zero() {
        let mut mmix = MMix::new();
        mmix.set_register(40, 0xDEAD); // global while rG = 32
        mmix.set_special(SpecialReg::RG, 50);
        mmix.set_special(SpecialReg::RL, 3);

        // ADD $45,$40,$0
        mmix.write_tetra(0, 0x202D2800);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_register(45), 0);
        assert_eq!(mmix.get_register(40), 0);
        assert_eq!(mmix.get_special(SpecialReg::RL), 46);
    }

    #[test]
    fn test_a_conditional_set_that_stores_nothing_still_raises_rl() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RL, 3);

        // CSN $8,$6,$7 - $6 is zero, so nothing is stored.
        mmix.write_tetra(0, 0x60080607);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_special(SpecialReg::RL), 9);
    }

    #[test]
    fn test_a_read_modify_write_destination_reads_its_own_rise_as_zero() {
        let mut mmix = MMix::new();
        mmix.set_register(40, 777); // global while rG = 32
        mmix.set_special(SpecialReg::RG, 50);
        mmix.set_special(SpecialReg::RL, 3);

        // INCL $40,5
        mmix.write_tetra(0, 0xE7280005);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_register(40), 5);
        assert_eq!(mmix.get_special(SpecialReg::RL), 41);
    }

    #[test]
    fn test_go_claims_its_destination_before_reading_its_address() {
        let mut mmix = MMix::new();
        mmix.set_register(40, 0xDEAD); // global while rG = 32
        mmix.set_special(SpecialReg::RG, 50);
        mmix.set_special(SpecialReg::RL, 3);

        // GO $45,$40,4
        mmix.write_tetra(0, 0x9F2D2804);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_pc(), 4, "$40 reads zero, so the target is 0+4");
        assert_eq!(mmix.get_register(45), 4, "the tetra after the GO");
        assert_eq!(mmix.get_special(SpecialReg::RL), 46);
    }

    #[test]
    fn test_a_store_does_not_claim_its_x_register() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RL, 3);

        // STO $8,$0,0
        mmix.write_tetra(0, 0xAD080000);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_special(SpecialReg::RL), 3);
    }

    #[test]
    fn test_pop_rg_guard_preserves_a_global_set_after_a_mid_call_shrink() {
        // Caller has rG=40, rL=38 and calls PUSHJ $36; the callee shrinks
        // rG to 32 with PUT rG, then sets the newly-global $34 before
        // POP 0,0. Without the rG guard, POP would restore the caller's
        // stale $34 from the spilled frame and clobber the callee's global
        // write.
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_special(SpecialReg::RG, 40);
        mmix.set_special(SpecialReg::RL, 38);

        // PUSHJ $36, +1
        mmix.write_tetra(0x100, 0xF2240001);
        assert!(mmix.execute_instruction());

        // PUTI rG,32
        mmix.write_tetra(0x104, 0xF7130020);
        assert!(mmix.execute_instruction());

        // SETL $34,999
        mmix.write_tetra(0x108, 0xE32203E7);
        assert!(mmix.execute_instruction());

        // POP 0,0
        mmix.write_tetra(0x10C, 0xF8000000);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_register(34), 999);
        assert_eq!(mmix.get_special(SpecialReg::RG), 32);
        assert_eq!(mmix.get_special(SpecialReg::RL), 32);
    }

    #[test]
    fn test_pop() {
        let mut mmix = MMix::new();
        // Set return address in rJ
        mmix.set_special(SpecialReg::RJ, 200);
        // POP 0, 0 - Return to address in rJ
        mmix.write_tetra(0, 0xF8000000); // POP 0,0,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 200); // PC = rJ value
    }

    #[test]
    fn test_swym() {
        let mut mmix = MMix::new();
        // SWYM - no-op
        mmix.write_tetra(0, 0xFD000000); // SWYM 0,0,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advances normally
    }

    /// Write `value`'s four bytes as loaded, the way `write_image` does, so a
    /// trip landing here does not read the address as an unloaded vector.
    fn load_tetra(mmix: &mut MMix, addr: u64, value: u32) {
        for i in 0..4 {
            let shift = 24 - 8 * i;
            mmix.write_loaded_byte(addr + i as u64, (value >> shift) as u8);
        }
    }

    #[test]
    fn test_trip() {
        // TRIP X,Y,Z sets rX/rY/rZ/rB/$255/rW (§1 rule 3) and lands at #00.
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x00, 0xFD000000); // vector loaded: SWYM
        mmix.set_pc(0x100);
        mmix.set_register(255, 0xAAAA);
        mmix.set_register(2, 0x2222);
        mmix.set_register(3, 0x3333);
        mmix.set_special(SpecialReg::RJ, 0xBEEF);
        mmix.write_tetra(0x100, 0xFF110203); // TRIP X=0x11, Y=2, Z=3

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x00);
        assert_eq!(mmix.get_special(SpecialReg::RW), 0x104);
        assert_eq!(mmix.get_special(SpecialReg::RX), 0x80000000FF110203);
        assert_eq!(mmix.get_special(SpecialReg::RY), 0x2222);
        assert_eq!(mmix.get_special(SpecialReg::RZ), 0x3333);
        assert_eq!(mmix.get_special(SpecialReg::RB), 0xAAAA);
        assert_eq!(mmix.get_register(255), 0xBEEF);
    }

    #[test]
    fn test_sync() {
        let mut mmix = MMix::new();
        // SYNC - memory barrier (no-op in simulator)
        mmix.write_tetra(0, 0xFC000000); // SYNC 0,0,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_resume_with_negative_rx_continues_at_rw() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_special(SpecialReg::RX, 0x8000000000000000); // negative
        mmix.set_special(SpecialReg::RW, 0x200);
        mmix.write_tetra(0x100, 0xF9000000); // RESUME 0

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x200);
    }

    #[test]
    fn test_resume_ropcode_0_runs_rxs_instruction_and_continues_at_rw() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(2, 10);
        mmix.set_register(3, 20);
        // rX (nonnegative, ropcode 0): ADD $1,$2,$3.
        mmix.set_special(SpecialReg::RX, 0x20010203);
        mmix.set_special(SpecialReg::RW, 0x300);
        mmix.write_tetra(0x100, 0xF9000000); // RESUME 0

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 30);
        assert_eq!(mmix.get_pc(), 0x300);
    }

    #[test]
    fn test_resume_ropcodes_1_to_3_halt() {
        for ropcode in 1u64..=3 {
            let (host, handle) = CaptureHost::new();
            let mut mmix = MMix::with_host(host);
            mmix.set_pc(0x100);
            mmix.set_special(SpecialReg::RX, ropcode << 56);
            mmix.set_special(SpecialReg::RW, 0x300);
            mmix.write_tetra(0x100, 0xF9000000); // RESUME 0

            assert!(!mmix.execute_instruction(), "ropcode {ropcode}");
            assert_eq!(mmix.get_pc(), 0x100, "PC unmoved for ropcode {ropcode}");
            assert_eq!(handle.diagnostics().len(), 1);
        }
    }

    #[test]
    fn test_resume_with_nonzero_z_halts() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_pc(0x100);
        mmix.write_tetra(0x100, 0xF9000001); // RESUME 1 - privileged

        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x100, "PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
    }

    #[test]
    fn test_divide_check_trips_when_enabled() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x10, 0xFD000000); // D's vector loaded
        mmix.set_special(SpecialReg::RA, RA_D << 8); // enable D only
        mmix.set_pc(0x100);
        mmix.set_register(2, 7);
        mmix.set_register(3, 0);
        mmix.write_tetra(0x100, 0x1C010203); // DIV $1,$2,$3

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x10, "trips to D's vector");
        assert_eq!(
            mmix.get_register(1),
            0,
            "DIV's own zero result is written first"
        );
        assert_eq!(mmix.get_special(SpecialReg::RY), 7);
        assert_eq!(
            mmix.get_special(SpecialReg::RA) & RA_D,
            0,
            "a tripped exception's own event bit stays clear"
        );
    }

    #[test]
    fn test_integer_overflow_trips_and_the_handler_sees_the_pre_write_operand() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x20, 0xFD000000); // V's vector loaded
        mmix.set_special(SpecialReg::RA, RA_V << 8); // enable V only
        mmix.set_pc(0x100);
        mmix.set_register(5, i64::MAX as u64);
        mmix.set_register(3, 1);
        mmix.write_tetra(0x100, 0x20050503); // ADD $5,$5,$3 - destination aliases a source

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x20);
        assert_eq!(
            mmix.get_register(5),
            i64::MIN as u64,
            "the wrapped result is written before the trip"
        );
        assert_eq!(
            mmix.get_special(SpecialReg::RY),
            i64::MAX as u64,
            "rY holds $5's value from before ADD overwrote it"
        );
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_V, 0);
    }

    #[test]
    fn test_immediate_overflow_trip_reports_the_literal_z() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x20, 0xFD000000); // V's vector loaded
        mmix.set_special(SpecialReg::RA, RA_V << 8); // enable V only
        mmix.set_pc(0x100);
        mmix.set_register(2, i64::MAX as u64);
        // $5 holds a value distinct from the literal Z=5: a revert that reads
        // get_register(5) instead of the literal would report this instead.
        mmix.set_register(5, 0xDEAD_BEEF);
        mmix.write_tetra(0x100, 0x21030205); // ADDI $3,$2,5

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x20);
        assert_eq!(
            mmix.get_special(SpecialReg::RZ),
            5,
            "rZ holds the literal Z, not $5's contents"
        );
    }

    #[test]
    fn test_store_overflow_trip_reports_address_and_stored_value() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x20, 0xFD000000); // V's vector loaded
        mmix.set_special(SpecialReg::RA, RA_V << 8); // enable V only
        mmix.set_pc(0x100);
        mmix.set_register(1, 200); // out of signed byte range: overflows
        mmix.set_register(2, 0x4000);
        mmix.set_register(3, 8);
        // A nonzero neighbouring byte in the target octabyte: rZ must be the
        // merged octabyte memory now holds, not the raw stored byte alone.
        mmix.write_byte(0x4009, 0xAB);
        mmix.write_tetra(0x100, 0xA0010203); // STB $1,$2,$3

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x20);
        assert_eq!(
            mmix.get_special(SpecialReg::RY),
            0x4008,
            "rY holds the computed address, not raw $Y"
        );
        assert_eq!(
            mmix.get_special(SpecialReg::RZ),
            0xC8AB_0000_0000_0000,
            "rZ holds the aligned octabyte after the store: the stored byte \
             (200 = 0xC8) in place, the neighbouring byte and the rest of \
             memory unchanged"
        );
    }

    #[test]
    fn test_stsf_overflow_trip_reports_address_and_merged_octa() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x50, 0xFD000000); // O's vector loaded
        mmix.set_special(SpecialReg::RA, RA_O << 8); // enable O only
        mmix.set_pc(0x100);
        mmix.set_register(1, f64::MAX.to_bits()); // narrows to +inf: overflow
        mmix.set_register(2, 0x4000);
        mmix.set_register(3, 8);
        // A nonzero byte past the stored tetra, in the same octabyte: rZ
        // must be the merged octabyte, not the plain $Y/$Z operands.
        mmix.write_byte(0x400C, 0xAB);
        mmix.write_tetra(0x100, 0xB0010203); // STSF $1,$2,$3

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x50);
        assert!(f32::from_bits(mmix.read_tetra(0x4008)).is_infinite());
        assert_eq!(
            mmix.get_special(SpecialReg::RY),
            0x4008,
            "rY holds the computed address, not raw $Y — catches a revert \
             to the plain $Y/$Z operands"
        );
        assert_eq!(
            mmix.get_special(SpecialReg::RZ),
            0x7F80_0000_AB00_0000,
            "rZ holds the aligned octabyte after the store: the stored \
             +inf tetra in place, the neighbouring byte unchanged — catches \
             a revert to the plain $Y/$Z operands"
        );
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_O, 0);
    }

    #[test]
    fn test_float_to_fix_overflow_trips_when_enabled() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x30, 0xFD000000); // W's vector loaded
        mmix.set_special(SpecialReg::RA, RA_W << 8); // enable W only
        mmix.set_pc(0x100);
        mmix.set_register(2, f64::INFINITY.to_bits());
        mmix.write_tetra(0x100, 0x05010002); // FIX $1,0,$2

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x30);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_W, 0);
    }

    #[test]
    fn test_invalid_operation_trips_when_enabled() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x40, 0xFD000000); // I's vector loaded
        mmix.set_special(SpecialReg::RA, RA_I << 8); // enable I only
        mmix.set_pc(0x100);
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 0);
        mmix.write_tetra(0x100, 0x01010203); // FCMP $1,$2,$3 - $2 is NaN

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x40);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_I, 0);
    }

    #[test]
    fn test_floating_overflow_trips_and_the_unenabled_inexact_still_sets_its_event_bit() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x50, 0xFD000000); // O's vector loaded
        mmix.set_special(SpecialReg::RA, RA_O << 8); // enable O only, not X
        mmix.set_pc(0x100);
        mmix.set_register(2, f64::MAX.to_bits());
        mmix.set_register(3, f64::MAX.to_bits());
        mmix.write_tetra(0x100, 0x10010203); // FMUL $1,$2,$3 overflows (raises O and X)

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x50);
        let ra = mmix.get_special(SpecialReg::RA);
        assert_eq!(ra & RA_O, 0, "O tripped: its own event bit stays clear");
        assert_eq!(
            ra & RA_X,
            RA_X,
            "X was raised but not enabled: it still sets its event bit"
        );
    }

    #[test]
    fn test_two_enabled_exceptions_trip_to_the_leftmost_and_drop_the_other_silently() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x50, 0xFD000000); // O's vector loaded
        mmix.set_special(SpecialReg::RA, (RA_O << 8) | (RA_X << 8)); // both enabled
        mmix.set_pc(0x100);
        mmix.set_register(2, f64::MAX.to_bits());
        mmix.set_register(3, f64::MAX.to_bits());
        mmix.write_tetra(0x100, 0x10010203); // FMUL $1,$2,$3 overflows (raises O and X)

        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.get_pc(),
            0x50,
            "trips to O, the leftmost enabled exception"
        );
        assert_eq!(
            mmix.get_special(SpecialReg::RA) & 0xFF,
            0,
            "O tripped and X was enabled but not leftmost: neither sets an event bit"
        );
    }

    #[test]
    fn test_floating_underflow_trips_when_enabled() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x60, 0xFD000000); // U's vector loaded
        mmix.set_special(SpecialReg::RA, RA_U << 8); // enable U only
        mmix.set_pc(0x100);
        mmix.set_register(2, f64::MIN_POSITIVE.to_bits());
        mmix.set_register(3, f64::MIN_POSITIVE.to_bits());
        mmix.write_tetra(0x100, 0x10010203); // FMUL $1,$2,$3 underflows to zero

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x60);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_U, 0);
    }

    #[test]
    fn test_floating_divide_by_zero_trips_when_enabled() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x70, 0xFD000000); // Z's vector loaded
        mmix.set_special(SpecialReg::RA, RA_Z << 8); // enable Z only
        mmix.set_pc(0x100);
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 0.0f64.to_bits());
        mmix.write_tetra(0x100, 0x14010203); // FDIV $1,$2,$3

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x70);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_Z, 0);
    }

    #[test]
    fn test_floating_inexact_trips_when_enabled() {
        let mut mmix = MMix::new();
        load_tetra(&mut mmix, 0x80, 0xFD000000); // X's vector loaded
        mmix.set_special(SpecialReg::RA, RA_X << 8); // enable X only
        mmix.set_pc(0x100);
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 1e-30f64.to_bits());
        mmix.write_tetra(0x100, 0x04010203); // FADD $1,$2,$3 rounds 1e-30 away

        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0x80);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_X, 0);
    }

    #[test]
    fn test_save() {
        let mut mmix = MMix::new();
        // SAVE $40,0 - $40 is global while rG = 32.
        mmix.write_tetra(0, 0xFA280000); // SAVE $40,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4);
    }

    #[test]
    fn test_unsave() {
        let mut mmix = MMix::new();
        // UNSAVE 0,$1 - $1 holds 0, so the packed octa read from address 0
        // is all zero: a packed rG of 0 is outside 32..=255 and rejects.
        mmix.write_tetra(0, 0xFB000001); // UNSAVE 0,$1
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0);
    }

    /// After `SAVE`, the register stack holds — lowest address to highest
    /// — the locals, a marker octa of their count, the globals, the
    /// twelve specials in `SAVE_SPECIALS` order, and a packed octa of
    /// `rG << 56 | rA`. `$X`, `rO`, `rS` and `rL` land where §1 says.
    /// Reverting `SAVE` to the old fixed-address format turns every
    /// assertion here red.
    #[test]
    fn test_save_writes_the_documented_layout() {
        let mut mmix = MMix::new();
        mmix.set_register(0, 0x1111);
        mmix.set_register(1, 0x2222);
        mmix.set_register(2, 0x3333); // rL becomes 3
        mmix.set_special(SpecialReg::RG, 250); // six globals: $250..$255
        for i in 250u8..=255 {
            mmix.set_register(i, 0x9000 + i as u64);
        }
        for (i, reg) in SAVE_SPECIALS.iter().enumerate() {
            mmix.set_special(*reg, 0x7000 + i as u64);
        }
        mmix.set_special(SpecialReg::RA, 0x2A);
        let ro_before = mmix.get_special(SpecialReg::RO);

        // SAVE $250,0 - $250 is global (== rG).
        mmix.write_tetra(0, 0xFAFA0000);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.read_octa(ro_before), 0x1111);
        assert_eq!(mmix.read_octa(ro_before + 8), 0x2222);
        assert_eq!(mmix.read_octa(ro_before + 16), 0x3333);
        let marker_addr = ro_before + 24;
        assert_eq!(mmix.read_octa(marker_addr), 3, "the marker holds rL");

        let globals_base = marker_addr + 8;
        for i in 0u64..6 {
            assert_eq!(
                mmix.read_octa(globals_base + i * 8),
                0x9000 + 250 + i,
                "global {}",
                250 + i
            );
        }

        let specials_base = globals_base + 6 * 8;
        for i in 0..SAVE_SPECIALS.len() as u64 {
            assert_eq!(
                mmix.read_octa(specials_base + i * 8),
                0x7000 + i,
                "special at index {i}"
            );
        }

        let packed_addr = specials_base + (SAVE_SPECIALS.len() as u64) * 8;
        assert_eq!(mmix.read_octa(packed_addr), (250u64 << 56) | 0x2A);

        assert_eq!(
            mmix.get_register(250),
            packed_addr,
            "$X holds the packed octa's address"
        );
        assert_eq!(mmix.get_special(SpecialReg::RO), packed_addr + 8);
        assert_eq!(mmix.get_special(SpecialReg::RS), packed_addr + 8);
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);
    }

    /// `SAVE`, clobber every register class, `UNSAVE`: everything lands
    /// back exactly where it was, and `rO = rS` returns to where `SAVE`
    /// found them. Dropping any restoration in `UNSAVE`'s arm turns one of
    /// these assertions red.
    #[test]
    fn test_save_unsave_round_trips_every_register_class() {
        let mut mmix = MMix::new();
        mmix.set_register(0, 0x1111); // local
        mmix.set_register(1, 0x2222); // local
        mmix.set_register(60, 0x3333); // global
        mmix.set_special(SpecialReg::RJ, 0x4444);
        mmix.set_special(SpecialReg::RM, 0x5555);
        mmix.set_special(SpecialReg::RA, 0x2A);
        let rl_before = mmix.get_special(SpecialReg::RL);
        let ro_before = mmix.get_special(SpecialReg::RO);

        // SAVE $70,0 - $70 is global.
        mmix.write_tetra(0, 0xFA460000);
        assert!(mmix.execute_instruction());

        // Clobber every register class SAVE just captured.
        mmix.set_register(0, 0);
        mmix.set_register(1, 0);
        mmix.set_register(60, 0);
        mmix.set_special(SpecialReg::RJ, 0);
        mmix.set_special(SpecialReg::RM, 0);
        mmix.set_special(SpecialReg::RA, 0);
        mmix.set_special(SpecialReg::RG, 200);
        mmix.set_special(SpecialReg::RL, 0);

        // UNSAVE 0,$70.
        mmix.write_tetra(4, 0xFB000046);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_register(0), 0x1111);
        assert_eq!(mmix.get_register(1), 0x2222);
        assert_eq!(mmix.get_register(60), 0x3333);
        assert_eq!(mmix.get_special(SpecialReg::RJ), 0x4444);
        assert_eq!(mmix.get_special(SpecialReg::RM), 0x5555);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0x2A);
        assert_eq!(mmix.get_special(SpecialReg::RG), 32);
        assert_eq!(mmix.get_special(SpecialReg::RL), rl_before);
        assert_eq!(mmix.get_special(SpecialReg::RO), ro_before);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro_before);
    }

    /// A `SAVE`/`UNSAVE` pair inside a call is transparent to the call
    /// itself: the enclosing `PUSHJ`/`POP` retract exactly as if the pair
    /// had never run.
    #[test]
    fn test_save_unsave_inside_a_call_leaves_the_caller_frame_intact() {
        let mut mmix = MMix::new();
        mmix.set_pc(0x100);
        mmix.set_register(0, 888); // caller's own local, must survive the call
        mmix.set_special(SpecialReg::RL, 3); // $0..$2 real locals; $2 is PUSHJ's hole
        let ro_before_call = mmix.get_special(SpecialReg::RO);

        // PUSHJ $2,+1 pushes $0,$1 and the hole ($2); the callee starts
        // with rL = 0.
        mmix.write_tetra(0x100, 0xF2020001);
        assert!(mmix.execute_instruction());
        let ro_in_callee = mmix.get_special(SpecialReg::RO);
        assert_eq!(mmix.get_special(SpecialReg::RL), 0);

        // Callee's own local, then SAVE $40,0 ($40 is global).
        mmix.set_register(0, 0xABC);
        mmix.write_tetra(0x104, 0xFA280000);
        assert!(mmix.execute_instruction());

        // Clobber everything SAVE just captured.
        mmix.set_register(0, 0xDEAD);
        mmix.set_special(SpecialReg::RM, 0xBAD);

        // UNSAVE 0,$40.
        mmix.write_tetra(0x108, 0xFB000028);
        assert!(mmix.execute_instruction());

        assert_eq!(
            mmix.get_register(0),
            0xABC,
            "the callee's own local round-trips"
        );
        assert_eq!(
            mmix.get_special(SpecialReg::RM),
            0,
            "rM round-trips to its pre-SAVE value"
        );
        assert_eq!(mmix.get_special(SpecialReg::RO), ro_in_callee);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro_in_callee);
        assert_eq!(
            mmix.get_special(SpecialReg::RL),
            1,
            "the callee's own single local"
        );

        // POP 0,0 returns to the caller.
        mmix.write_tetra(0x10C, 0xF8000000);
        assert!(mmix.execute_instruction());

        assert_eq!(
            mmix.get_register(0),
            888,
            "caller's $0, pushed by PUSHJ, survives the call"
        );
        assert_eq!(mmix.get_special(SpecialReg::RO), ro_before_call);
        assert_eq!(mmix.get_special(SpecialReg::RS), ro_before_call);
        assert_eq!(mmix.call_depth(), 0);
    }

    /// The register-stack review's reproduction: a `SAVE` before a call,
    /// a nested `PUSHJ`, then an `UNSAVE` inside the callee that rewinds
    /// `rO` clear past the frame the `PUSHJ` just opened. Reintroducing a
    /// counter `POP` trusts over `rO` turns this test red: it would still
    /// think the frame was open and read a hole from dead memory instead
    /// of taking the fallback `rO` now calls for.
    #[test]
    fn test_call_depth_and_pop_follow_ro_through_save_pushj_unsave() {
        let mut mmix = MMix::new();
        let base = mmix.get_special(SpecialReg::RO);
        assert_eq!(mmix.call_depth(), 0);

        // SAVE $40,0 at top level -- a context, not a frame.
        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xFA280000);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 0, "a SAVE context is not a frame");

        // PUSHJ $0,+1 opens a frame inside what becomes the callee.
        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xF2000001);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 1, "PUSHJ opened one frame");

        // UNSAVE 0,$40 inside the callee rewinds rO past that frame, back
        // to where SAVE found it -- the frame PUSHJ opened is now dead
        // memory below rO.
        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xFB000028);
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RO),
            base,
            "UNSAVE rewinds rO to where SAVE found it"
        );
        assert_eq!(
            mmix.call_depth(),
            0,
            "rO names the top level again; the dead frame does not count"
        );

        // POP 1,0 acts on what rO now names: the top level, so it takes
        // the no-frame fallback, branching via rJ -- restored by UNSAVE
        // to 0, its value when SAVE captured it. The fallback touches no
        // register or memory, so rO and rL, unlike a real pop, do not move.
        let rl_before_pop = mmix.get_special(SpecialReg::RL);
        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xF8010000);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0, "POP took the no-frame fallback");
        assert_eq!(
            mmix.get_special(SpecialReg::RO),
            base,
            "the fallback leaves rO alone"
        );
        assert_eq!(
            mmix.get_special(SpecialReg::RL),
            rl_before_pop,
            "the fallback leaves rL alone"
        );
        assert_eq!(mmix.call_depth(), 0);
    }

    /// A `SAVE`/`UNSAVE` pair inside a call leaves `call_depth` at the
    /// call's own count throughout: the context never counts as a second
    /// frame. Making `call_depth` count a `SAVE` context as a frame turns
    /// the middle assertion here red (2, not 1).
    #[test]
    fn test_call_depth_reads_one_across_a_save_inside_a_call() {
        let mut mmix = MMix::new();
        assert_eq!(mmix.call_depth(), 0);

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xF2000001); // PUSHJ $0,+1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 1);

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xFA280000); // SAVE $40,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 1, "the SAVE context does not count");

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xFB000028); // UNSAVE 0,$40
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 1, "still just the one open call");
    }

    /// Three nested `PUSHJ`s deep and back, `call_depth` 0→3→0, with a
    /// `SAVE`/`UNSAVE` pair at depth 2 in between.
    #[test]
    fn test_call_depth_nests_three_deep_with_a_save_unsave_pair_at_depth_two() {
        let mut mmix = MMix::new();
        assert_eq!(mmix.call_depth(), 0);

        for depth in 1..=2u64 {
            let pc = mmix.get_pc();
            mmix.write_tetra(pc, 0xF2000001); // PUSHJ $0,+1
            assert!(mmix.execute_instruction());
            assert_eq!(mmix.call_depth(), depth as usize);
        }

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xFA280000); // SAVE $40,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 2);

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xFB000028); // UNSAVE 0,$40
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 2);

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xF2000001); // PUSHJ $0,+1 -- depth 3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 3);

        for depth in (0..=2u64).rev() {
            let pc = mmix.get_pc();
            mmix.write_tetra(pc, 0xF8000000); // POP 0,0
            assert!(mmix.execute_instruction());
            assert_eq!(mmix.call_depth(), depth as usize);
        }
    }

    /// `POP` does not recognize a `SAVE` context: at top level after a
    /// bare `SAVE`, it reads the packed octa's low byte as a real hole
    /// count and retracts `rO` accordingly, rather than taking the
    /// no-frame fallback (which would leave `rO` untouched).
    #[test]
    fn test_pop_after_a_bare_save_reads_the_packed_octas_low_byte_as_a_hole() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RA, 5); // packed octa's low byte becomes 5

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xFA280000); // SAVE $40,0
        assert!(mmix.execute_instruction());
        let ro_after_save = mmix.get_special(SpecialReg::RO);
        assert!(ro_after_save > STACK_SEGMENT_START);

        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xF8000000); // POP 0,0
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RO),
            ro_after_save - 48,
            "rO retracted by 8*(5+1), the packed octa's low byte read as a hole"
        );
    }

    /// `rO` at or below the stack base — the fresh-machine case, and a
    /// forged one further below, only reachable through `set_special` —
    /// both take `POP`'s no-frame fallback, and `call_depth` reads 0
    /// without looping either way.
    #[test]
    fn test_pop_and_call_depth_at_or_below_the_base_take_the_fallback() {
        let mut mmix = MMix::new();
        assert_eq!(mmix.get_special(SpecialReg::RO), STACK_SEGMENT_START);
        assert_eq!(mmix.call_depth(), 0);

        mmix.set_special(SpecialReg::RJ, 0x200);
        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xF8008000); // POP 0,0x8000
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.get_pc(),
            0x200 + 32768 * 4,
            "at the base: the fallback fired"
        );

        mmix.set_special(SpecialReg::RO, STACK_SEGMENT_START - 8);
        assert_eq!(mmix.call_depth(), 0);
        mmix.set_special(SpecialReg::RJ, 0x300);
        mmix.set_pc(0);
        mmix.write_tetra(0, 0xF8000000); // POP 0,0
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.get_pc(),
            0x300,
            "below the base: the fallback fired too"
        );
    }

    /// A misaligned `rO` — only reachable through a forged `set_special`,
    /// since every legal instruction keeps it a multiple of 8 — halts
    /// `POP` with a diagnostic and leaves the machine unchanged, since the
    /// reference would raise a protection fault checksmix has no vector
    /// for. `call_depth` stops at 0 without looping.
    #[test]
    fn test_pop_halts_on_a_misaligned_ro() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_special(SpecialReg::RO, STACK_SEGMENT_START + 3);
        mmix.set_register(0, 0xFEED);

        assert_eq!(
            mmix.call_depth(),
            0,
            "the walk stops at once on a misaligned rO"
        );

        mmix.write_tetra(0, 0xF8000000); // POP 0,0
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0, "no PC advance on a halt");
        assert_eq!(mmix.get_register(0), 0xFEED, "no register change on a halt");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rO"));
    }

    /// An `rO` above the register-stack segment — only reachable through a
    /// forged `set_special` — halts `POP` the same way, and `call_depth`
    /// again stops at once without looping.
    #[test]
    fn test_pop_halts_on_an_ro_above_the_stack_segment() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_special(SpecialReg::RO, 0x8000000000000000);
        mmix.set_register(0, 0xFEED);

        assert_eq!(
            mmix.call_depth(),
            0,
            "the walk stops at once outside the segment"
        );

        mmix.write_tetra(0, 0xF8000000); // POP 0,0
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 0);
        assert_eq!(mmix.get_register(0), 0xFEED);
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rO"));
    }

    /// The review's non-forged reproduction: a real top-level `SAVE $40,0`,
    /// then an ordinary `write_octa` overwrites the marker octa `SAVE`
    /// wrote with a local count chosen so the walk's own arithmetic maps
    /// `locals_base` back to `ro` itself -- a fixed point, no forged `rO`
    /// anywhere. Without the saved-local-count bound in
    /// `save_context_layout`, `call_depth` recomputes this same address
    /// forever and the test never returns; with it, the count (far above
    /// the saved `rG`) is rejected and the walk stops at once.
    #[test]
    fn test_call_depth_does_not_loop_on_a_marker_mapping_back_to_itself() {
        let mut mmix = MMix::new();

        // SAVE $40,0 at top level.
        mmix.write_tetra(0, 0xFA280000);
        assert!(mmix.execute_instruction());
        let packed_addr = mmix.get_register(40);
        let ro = mmix.get_special(SpecialReg::RO);
        assert_eq!(ro, packed_addr + 8);

        let global_count = 256u64 - 32; // rG = 32 at SAVE time
        let marker_addr = packed_addr - (SAVE_SPECIALS.len() as u64) * 8 - global_count * 8 - 8;

        // Solve for a count with locals_base == marker_addr - count*8 == ro.
        let diff = marker_addr.wrapping_sub(ro);
        assert_eq!(diff % 8, 0, "sanity: layout offsets are all multiples of 8");
        mmix.write_octa(marker_addr, diff / 8);

        assert_eq!(
            mmix.call_depth(),
            0,
            "the corrupted local count exceeds the saved rG; the walk stops \
             instead of looping back to where it started"
        );
    }

    /// A `SAVE` executed with a nonzero `rL` and `rG != 32` -- the review's
    /// coverage gap. `call_depth` must step over the whole context, globals
    /// and locals alike, using the saved (not the machine's current) `rG`.
    #[test]
    fn test_call_depth_walks_a_save_context_with_nonzero_rl_and_rg_ne_32() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RG, 50);
        mmix.set_special(SpecialReg::RL, 3);
        mmix.set_register(0, 0x111);
        mmix.set_register(1, 0x222);
        mmix.set_register(2, 0x333);

        // SAVE $60,0 -- $60 is global (rG=50).
        mmix.write_tetra(0, 0xFA3C0000);
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.call_depth(),
            0,
            "the context alone, locals and all, is not a frame"
        );

        // PUSHJ $0,+1 opens a frame above the context.
        let pc = mmix.get_pc();
        mmix.write_tetra(pc, 0xF2000001);
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.call_depth(),
            1,
            "the walk steps over the saved rL=3, rG=50 context uncounted \
             and still finds the one PUSHJ frame beneath it"
        );
    }

    /// `SAVE`'s Y and Z, and `UNSAVE`'s X and Y, are must-be-zero fields the
    /// machine never reads. A nonzero value there behaves exactly as zero.
    #[test]
    fn test_save_and_unsave_ignore_their_must_be_zero_fields() {
        let mut mmix = MMix::new();
        mmix.set_register(0, 0x1234); // a local
        mmix.set_register(50, 0xABCD); // a global

        // SAVE $60,255,255 - Y and Z both nonzero.
        mmix.write_tetra(0, 0xFA3CFFFF);
        assert!(mmix.execute_instruction());

        mmix.set_register(0, 0);
        mmix.set_register(50, 0);

        // UNSAVE 255,255,$60 - X and Y both nonzero; the address still
        // comes from $Z alone.
        mmix.write_tetra(4, 0xFBFFFF3C);
        assert!(mmix.execute_instruction());

        assert_eq!(mmix.get_register(0), 0x1234);
        assert_eq!(mmix.get_register(50), 0xABCD);
    }

    /// Two independent machines run the same `SAVE`; `$X` lands on the same
    /// address in both. The old fixed-address format shared one process-
    /// global counter across every `MMix`, so two machines (or two tests
    /// running in parallel) handed out interleaved addresses instead.
    #[test]
    fn test_save_is_deterministic_across_instances() {
        let mut a = MMix::new();
        let mut b = MMix::new();

        a.write_tetra(0, 0xFA280000); // SAVE $40,0
        b.write_tetra(0, 0xFA280000);
        assert!(a.execute_instruction());
        assert!(b.execute_instruction());

        assert_eq!(a.get_register(40), b.get_register(40));
    }

    /// `UNSAVE` rejects a packed rG below 32 (above 255 cannot occur — it
    /// is one byte), before touching any register or memory.
    #[test]
    fn test_unsave_rejects_a_packed_rg_below_32() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(0, 0xFEED); // survives iff UNSAVE never runs

        let context = 0x2000u64;
        mmix.write_octa(context, 31u64 << 56); // packed rG = 31, rA = 0
        mmix.set_register(60, context);

        // UNSAVE 0,$60
        mmix.write_tetra(0, 0xFB00003C);
        assert!(!mmix.execute_instruction());

        assert_eq!(mmix.get_pc(), 0);
        assert_eq!(mmix.get_register(0), 0xFEED);
        assert_eq!(mmix.get_special(SpecialReg::RG), 32);
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rG"));
    }

    /// `UNSAVE` rejects a packed rA above `RA_MAX`.
    #[test]
    fn test_unsave_rejects_a_packed_ra_above_ra_max() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(0, 0xFEED);

        let context = 0x2000u64;
        mmix.write_octa(context, (32u64 << 56) | (RA_MAX + 1));
        mmix.set_register(60, context);

        // UNSAVE 0,$60
        mmix.write_tetra(0, 0xFB00003C);
        assert!(!mmix.execute_instruction());

        assert_eq!(mmix.get_pc(), 0);
        assert_eq!(mmix.get_register(0), 0xFEED);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rA"));
    }

    /// `UNSAVE` rejects a saved local count greater than the packed rG. A
    /// real `SAVE` gives a well-formed context; only its marker is
    /// corrupted.
    #[test]
    fn test_unsave_rejects_a_saved_local_count_above_the_packed_rg() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_special(SpecialReg::RL, 0);

        // SAVE $40,0 with no locals: the marker holds 0.
        mmix.write_tetra(0, 0xFA280000);
        assert!(mmix.execute_instruction());
        let context = mmix.get_register(40);

        let global_count = 256u64 - 32; // rg = 32
        let marker_addr = context - (SAVE_SPECIALS.len() as u64) * 8 - global_count * 8 - 8;
        assert_eq!(
            mmix.read_octa(marker_addr),
            0,
            "sanity: 0 locals were saved"
        );
        mmix.write_octa(marker_addr, 33); // 33 > rG (32)

        mmix.set_register(0, 0xFEED); // survives iff UNSAVE never runs

        // UNSAVE 0,$40
        mmix.write_tetra(4, 0xFB000028);
        assert!(!mmix.execute_instruction());

        assert_eq!(mmix.get_pc(), 4);
        assert_eq!(mmix.get_register(0), 0xFEED);
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("local count"));
    }

    #[test]
    fn test_csn_condition_true() {
        let mut mmix = MMix::new();
        // CSN $1, $2, $3 - If $2 < 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, (-10i64) as u64);
        mmix.set_register(3, 50);
        mmix.write_tetra(0, 0x60010203); // CSN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 50); // Condition true: $3
    }

    #[test]
    fn test_csn_condition_false() {
        let mut mmix = MMix::new();
        // CSN $1, $2, $3 - If $2 >= 0, do nothing
        mmix.set_register(1, 99); // Initial value
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_tetra(0, 0x60010203); // CSN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 99); // Condition false: unchanged
    }

    #[test]
    fn test_csni() {
        let mut mmix = MMix::new();
        // CSNI $1, $2, 50 - If $2 < 0, set $1 = 50, else $1 = $2
        mmix.set_register(2, (-1i64) as u64);
        mmix.write_tetra(0, 0x61010232); // CSNI $1,$2,50
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 50); // Condition true: 50
    }

    #[test]
    fn test_csz_condition_true() {
        let mut mmix = MMix::new();
        // CSZ $1, $2, $3 - If $2 == 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, 0);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x62010203); // CSZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 20); // Condition true: $3
    }

    #[test]
    fn test_csz_condition_false() {
        let mut mmix = MMix::new();
        // CSZ $1, $2, $3 - If $2 != 0, do nothing
        mmix.set_register(1, 88); // Initial value
        mmix.set_register(2, 10);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x62010203); // CSZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 88); // Condition false: unchanged
    }

    #[test]
    fn test_cszi() {
        let mut mmix = MMix::new();
        // CSZI $1, $2, 15 - If $2 == 0, set $1 = 15, else $1 = $2
        mmix.set_register(2, 0);
        mmix.write_tetra(0, 0x6301020F); // CSZI $1,$2,15
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 15); // Condition true: 15
    }

    #[test]
    fn test_csp_condition_true() {
        let mut mmix = MMix::new();
        // CSP $1, $2, $3 - If $2 > 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, 5);
        mmix.set_register(3, 7);
        mmix.write_tetra(0, 0x64010203); // CSP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 7); // Condition true: $3
    }

    #[test]
    fn test_csp_condition_false_zero() {
        let mut mmix = MMix::new();
        // CSP $1, $2, $3 - If $2 <= 0, do nothing
        mmix.set_register(1, 77); // Initial value
        mmix.set_register(2, 0);
        mmix.set_register(3, 7);
        mmix.write_tetra(0, 0x64010203); // CSP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 77); // Condition false: unchanged
    }

    #[test]
    fn test_cspi() {
        let mut mmix = MMix::new();
        // CSPI $1, $2, 25 - If $2 > 0, set $1 = 25, else $1 = $2
        mmix.set_register(2, 50);
        mmix.write_tetra(0, 0x65010219); // CSPI $1,$2,25
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 25); // Condition true: 25
    }

    #[test]
    fn test_csod_condition_true() {
        let mut mmix = MMix::new();
        // CSOD $1, $2, $3 - If $2 is odd, set $1 = $3, else $1 = $2
        mmix.set_register(2, 7);
        mmix.set_register(3, 15);
        mmix.write_tetra(0, 0x66010203); // CSOD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 15); // Condition true: $3
    }

    #[test]
    fn test_csod_condition_false() {
        let mut mmix = MMix::new();
        // CSOD $1, $2, $3 - If $2 is even, do nothing
        mmix.set_register(1, 66); // Initial value
        mmix.set_register(2, 8);
        mmix.set_register(3, 15);
        mmix.write_tetra(0, 0x66010203); // CSOD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 66); // Condition false: unchanged
    }

    #[test]
    fn test_csodi() {
        let mut mmix = MMix::new();
        // CSODI $1, $2, 11 - If $2 is odd, set $1 = 11, else $1 = $2
        mmix.set_register(2, 99);
        mmix.write_tetra(0, 0x6701020B); // CSODI $1,$2,11
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 11); // Condition true: 11
    }

    #[test]
    fn test_csnn_condition_true_positive() {
        let mut mmix = MMix::new();
        // CSNN $1, $2, $3 - If $2 >= 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, 30);
        mmix.set_register(3, 40);
        mmix.write_tetra(0, 0x68010203); // CSNN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 40); // Condition true: $3
    }

    #[test]
    fn test_csnn_condition_true_zero() {
        let mut mmix = MMix::new();
        // CSNN $1, $2, $3 - If $2 >= 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, 0);
        mmix.set_register(3, 40);
        mmix.write_tetra(0, 0x68010203); // CSNN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 40); // Condition true: $3
    }

    #[test]
    fn test_csnn_condition_false() {
        let mut mmix = MMix::new();
        // CSNN $1, $2, $3 - If $2 < 0, do nothing
        mmix.set_register(1, 55); // Initial value
        mmix.set_register(2, (-5i64) as u64);
        mmix.set_register(3, 40);
        mmix.write_tetra(0, 0x68010203); // CSNN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 55); // Condition false: unchanged
    }

    #[test]
    fn test_csnni() {
        let mut mmix = MMix::new();
        // CSNNI $1, $2, 8 - If $2 >= 0, set $1 = 8, else $1 = $2
        mmix.set_register(2, 92);
        mmix.write_tetra(0, 0x69010208); // CSNNI $1,$2,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 8); // Condition true: 8
    }

    #[test]
    fn test_csnz_condition_true() {
        let mut mmix = MMix::new();
        // CSNZ $1, $2, $3 - If $2 != 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, 100);
        mmix.set_register(3, 200);
        mmix.write_tetra(0, 0x6A010203); // CSNZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 200); // Condition true: $3
    }

    #[test]
    fn test_csnz_condition_false() {
        let mut mmix = MMix::new();
        // CSNZ $1, $2, $3 - If $2 == 0, do nothing
        mmix.set_register(1, 44); // Initial value
        mmix.set_register(2, 0);
        mmix.set_register(3, 200);
        mmix.write_tetra(0, 0x6A010203); // CSNZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 44); // Condition false: unchanged
    }

    #[test]
    fn test_csnzi() {
        let mut mmix = MMix::new();
        // CSNZI $1, $2, 33 - If $2 != 0, set $1 = 33, else $1 = $2
        mmix.set_register(2, 67);
        mmix.write_tetra(0, 0x6B010221); // CSNZI $1,$2,33
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 33); // Condition true: 33
    }

    #[test]
    fn test_csnp_condition_true_negative() {
        let mut mmix = MMix::new();
        // CSNP $1, $2, $3 - If $2 <= 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, (-100i64) as u64);
        mmix.set_register(3, 25);
        mmix.write_tetra(0, 0x6C010203); // CSNP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 25); // Condition true: $3
    }

    #[test]
    fn test_csnp_condition_true_zero() {
        let mut mmix = MMix::new();
        // CSNP $1, $2, $3 - If $2 == 0, set $1 = $3, else $1 = $2
        mmix.set_register(2, 0);
        mmix.set_register(3, 25);
        mmix.write_tetra(0, 0x6C010203); // CSNP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 25); // Condition true: $3
    }

    #[test]
    fn test_csnp_condition_false() {
        let mut mmix = MMix::new();
        // CSNP $1, $2, $3 - If $2 > 0, do nothing
        mmix.set_register(1, 33); // Initial value
        mmix.set_register(2, 50);
        mmix.set_register(3, 25);
        mmix.write_tetra(0, 0x6C010203); // CSNP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 33); // Condition false: unchanged
    }

    #[test]
    fn test_csnpi() {
        let mut mmix = MMix::new();
        // CSNPI $1, $2, 44 - If $2 <= 0, set $1 = 44, else $1 = $2
        mmix.set_register(2, 0);
        mmix.write_tetra(0, 0x6D01022C); // CSNPI $1,$2,44
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 44); // Condition true: 44
    }

    #[test]
    fn test_csev_condition_true() {
        let mut mmix = MMix::new();
        // CSEV $1, $2, $3 - If $2 is even, set $1 = $3, else $1 = $2
        mmix.set_register(2, 80);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x6E010203); // CSEV $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 20); // Condition true: $3
    }

    #[test]
    fn test_csev_condition_false() {
        let mut mmix = MMix::new();
        // CSEV $1, $2, $3 - If $2 is odd, do nothing
        mmix.set_register(1, 22); // Initial value
        mmix.set_register(2, 7);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x6E010203); // CSEV $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 22); // Condition false: unchanged
    }

    #[test]
    fn test_csevi() {
        let mut mmix = MMix::new();
        // CSEVI $1, $2, 12 - If $2 is even, set $1 = 12, else $1 = $2
        mmix.set_register(2, 88);
        mmix.write_tetra(0, 0x6F01020C); // CSEVI $1,$2,12
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 12); // Condition true: 12
    }

    // ========== Floating Point Tests ==========

    #[test]
    fn test_fcmp_less_than() {
        let mut mmix = MMix::new();
        // FCMP $1, $2, $3 - Compare 2.5 < 5.0
        mmix.set_register(2, 2.5f64.to_bits());
        mmix.set_register(3, 5.0f64.to_bits());
        mmix.write_tetra(0, 0x01010203); // FCMP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1); // Less than
    }

    #[test]
    fn test_fcmp_greater_than() {
        let mut mmix = MMix::new();
        // FCMP $1, $2, $3 - Compare 10.0 > 3.0
        mmix.set_register(2, 10.0f64.to_bits());
        mmix.set_register(3, 3.0f64.to_bits());
        mmix.write_tetra(0, 0x01010203); // FCMP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1); // Greater than
    }

    #[test]
    fn test_fcmp_equal() {
        let mut mmix = MMix::new();
        // FCMP $1, $2, $3 - Compare 7.5 == 7.5
        mmix.set_register(2, 7.5f64.to_bits());
        mmix.set_register(3, 7.5f64.to_bits());
        mmix.write_tetra(0, 0x01010203); // FCMP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Equal
    }

    #[test]
    fn test_fcmp_unordered() {
        let mut mmix = MMix::new();
        // FCMP computes $X = [$Y > $Z] − [$Y < $Z]; with a NaN operand
        // both brackets are 0, so $X = 0, and I reports the NaN.
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 5.0f64.to_bits());
        mmix.write_tetra(0, 0x01010203); // FCMP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_cmp_cmpu_signed_unsigned_divergence() {
        let mut mmix = MMix::new();
        // $2 has its top bit set: negative as i64, huge as u64. $3 is a
        // small positive value. Signed and unsigned 3-way compare disagree.
        mmix.set_register(2, 0x8000000000000000);
        mmix.set_register(3, 1);
        mmix.write_tetra(0, 0x30010203); // CMP $1,$2,$3
        mmix.write_tetra(4, 0x32040203); // CMPU $4,$2,$3
        assert!(mmix.execute_instruction());
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1); // signed: $2 < $3
        assert_eq!(mmix.get_register(4) as i64, 1); // unsigned: $2 > $3
    }

    #[test]
    fn test_feql() {
        let mut mmix = MMix::new();
        // FEQL $1, $2, $3 - Test 4.0 == 4.0
        mmix.set_register(2, 4.0f64.to_bits());
        mmix.set_register(3, 4.0f64.to_bits());
        mmix.write_tetra(0, 0x03010203); // FEQL $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1); // Equal
    }

    #[test]
    fn test_feql_not_equal() {
        let mut mmix = MMix::new();
        // FEQL $1, $2, $3 - Test 4.0 != 5.0
        mmix.set_register(2, 4.0f64.to_bits());
        mmix.set_register(3, 5.0f64.to_bits());
        mmix.write_tetra(0, 0x03010203); // FEQL $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Not equal
    }

    #[test]
    fn test_fun() {
        let mut mmix = MMix::new();
        // FUN $1, $2, $3 - Test if unordered
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x02010203); // FUN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1); // Unordered
    }

    #[test]
    fn test_fun_ordered() {
        let mut mmix = MMix::new();
        // FUN $1, $2, $3 - Test if unordered (both normal)
        mmix.set_register(2, 2.0f64.to_bits());
        mmix.set_register(3, 3.0f64.to_bits());
        mmix.write_tetra(0, 0x02010203); // FUN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Ordered
    }

    #[test]
    fn test_fcmpe() {
        let mut mmix = MMix::new();
        // FCMPE $1, $2, $3 - Compare 5.0 and 5.001 with epsilon 0.01
        mmix.set_special(SpecialReg::RE, 0.01f64.to_bits());
        mmix.set_register(2, 5.0f64.to_bits());
        mmix.set_register(3, 5.001f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Equal within epsilon
    }

    #[test]
    fn test_feqle() {
        let mut mmix = MMix::new();
        // FEQLE $1, $2, $3 - Test equivalence with epsilon
        mmix.set_special(SpecialReg::RE, 0.1f64.to_bits());
        mmix.set_register(2, 10.0f64.to_bits());
        mmix.set_register(3, 10.05f64.to_bits());
        mmix.write_tetra(0, 0x13010203); // FEQLE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1); // Equivalent
    }

    #[test]
    fn test_fune() {
        let mut mmix = MMix::new();
        // FUNE $1, $2, $3 - neither operand nor rE is exceptional (no NaN,
        // rE not negative), so FUNE reports 0: it says nothing about
        // proximity, only whether the inputs are exceptional.
        mmix.set_special(SpecialReg::RE, 0.5f64.to_bits());
        mmix.set_register(2, 7.0f64.to_bits());
        mmix.set_register(3, 7.3f64.to_bits());
        mmix.write_tetra(0, 0x12010203); // FUNE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
    }

    #[test]
    fn test_fadd() {
        let mut mmix = MMix::new();
        // FADD $1, $2, $3 - Add 2.5 + 3.7
        mmix.set_register(2, 2.5f64.to_bits());
        mmix.set_register(3, 3.7f64.to_bits());
        mmix.write_tetra(0, 0x04010203); // FADD $1,$2,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 6.2).abs() < 1e-10);
    }

    #[test]
    fn test_fsub() {
        let mut mmix = MMix::new();
        // FSUB $1, $2, $3 - Subtract 10.0 - 3.5
        mmix.set_register(2, 10.0f64.to_bits());
        mmix.set_register(3, 3.5f64.to_bits());
        mmix.write_tetra(0, 0x06010203); // FSUB $1,$2,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 6.5).abs() < 1e-10);
    }

    #[test]
    fn test_fmul() {
        let mut mmix = MMix::new();
        // FMUL $1, $2, $3 - Multiply 4.0 * 2.5
        mmix.set_register(2, 4.0f64.to_bits());
        mmix.set_register(3, 2.5f64.to_bits());
        mmix.write_tetra(0, 0x10010203); // FMUL $1,$2,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 10.0).abs() < 1e-10);
    }

    #[test]
    fn test_fdiv() {
        let mut mmix = MMix::new();
        // FDIV $1, $2, $3 - Divide 15.0 / 3.0
        mmix.set_register(2, 15.0f64.to_bits());
        mmix.set_register(3, 3.0f64.to_bits());
        mmix.write_tetra(0, 0x14010203); // FDIV $1,$2,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 5.0).abs() < 1e-10);
    }

    #[test]
    fn test_frem() {
        let mut mmix = MMix::new();
        // IEEE 754 remainder of 7.5 by 2.0: 7.5/2 = 3.75 → round-half-even = 4
        // → r = 7.5 - 4·2 = -0.5. (Rust's `%` would give 1.5.)
        mmix.set_register(2, 7.5f64.to_bits());
        mmix.set_register(3, 2.0f64.to_bits());
        mmix.write_tetra(0, 0x16010203);
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result + 0.5).abs() < 1e-10, "got {}", result);
    }

    #[test]
    fn test_frem_zero_divisor_nan() {
        let mut mmix = MMix::new();
        mmix.set_register(2, 5.0f64.to_bits());
        mmix.set_register(3, 0.0f64.to_bits());
        mmix.write_tetra(0, 0x16010203);
        assert!(mmix.execute_instruction());
        assert!(f64::from_bits(mmix.get_register(1)).is_nan());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fsqrt() {
        let mut mmix = MMix::new();
        // FSQRT $1, $3 - Square root of 16.0
        mmix.set_register(3, 16.0f64.to_bits());
        mmix.write_tetra(0, 0x15010003); // FSQRT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_fint() {
        let mut mmix = MMix::new();
        // FINT $1, $3 - Round 3.7 to nearest integer
        mmix.set_register(3, 3.7f64.to_bits());
        mmix.write_tetra(0, 0x17010003); // FINT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_fix() {
        let mut mmix = MMix::new();
        // Default rA mode 0 = ROUND_NEAR: 42.9 → 43.
        mmix.set_register(3, 42.9f64.to_bits());
        mmix.write_tetra(0, 0x05010003); // FIX $1,$0,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 43);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_fix_trunc_mode() {
        let mut mmix = MMix::new();
        // rA mode 1 = ROUND_OFF (toward zero): 42.9 → 42.
        mmix.set_special(SpecialReg::RA, 1 << RA_ROUND_SHIFT);
        mmix.set_register(3, 42.9f64.to_bits());
        mmix.write_tetra(0, 0x05010003);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 42);
    }

    #[test]
    fn test_fix_negative() {
        let mut mmix = MMix::new();
        // Mode 0 = NEAR rounds -17.8 → -18.
        mmix.set_register(3, (-17.8f64).to_bits());
        mmix.write_tetra(0, 0x05010003);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -18);
    }

    #[test]
    fn test_fix_nan_sets_w_and_i() {
        let mut mmix = MMix::new();
        mmix.set_register(3, f64::NAN.to_bits());
        mmix.write_tetra(0, 0x05010003);
        assert!(mmix.execute_instruction());
        let ra = mmix.get_special(SpecialReg::RA);
        assert!((ra & RA_W) != 0);
        assert!((ra & RA_I) != 0);
    }

    #[test]
    fn test_fixu() {
        let mut mmix = MMix::new();
        // Mode 0 = NEAR with round-half-to-even: 99.5 → 100 (100 is even).
        mmix.set_register(3, 99.5f64.to_bits());
        mmix.write_tetra(0, 0x07010003);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 100);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_flot() {
        let mut mmix = MMix::new();
        // FLOT $1, $3 - Convert signed integer 42 to float
        mmix.set_register(3, 42);
        mmix.write_tetra(0, 0x08010003); // FLOT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 42.0).abs() < 1e-10);
    }

    #[test]
    fn test_flot_negative() {
        let mut mmix = MMix::new();
        // FLOT $1, $3 - Convert signed integer -100 to float
        mmix.set_register(3, (-100i64) as u64);
        mmix.write_tetra(0, 0x08010003); // FLOT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - (-100.0)).abs() < 1e-10);
    }

    #[test]
    fn test_floti() {
        let mut mmix = MMix::new();
        // FLOTI $1, $0, 100 - Convert immediate signed 100 to float (Y=$0 is rounding mode, Z=100 is value)
        mmix.write_tetra(0, 0x09010064); // FLOTI $1,$0,100 (X=01, Y=00, Z=64)
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 100.0).abs() < 1e-10);
    }

    #[test]
    fn test_floti_negative() {
        let mut mmix = MMix::new();
        // FLOTI $1, $0, -1 - Convert immediate signed -1 to float (Y=$0, Z=0xFF=-1 as signed byte)
        mmix.write_tetra(0, 0x090100FF); // FLOTI $1,$0,255 (X=01, Y=00, Z=FF which is -1 signed)
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - (-1.0)).abs() < 1e-10);
    }

    #[test]
    fn test_flotu() {
        let mut mmix = MMix::new();
        // FLOTU $1, $3 - Convert unsigned integer to float
        mmix.set_register(3, 1000);
        mmix.write_tetra(0, 0x0A010003); // FLOTU $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 1000.0).abs() < 1e-10);
    }

    #[test]
    fn test_flotui() {
        let mut mmix = MMix::new();
        // FLOTUI $1, $0, 244 - Convert immediate unsigned 244 to float (Y=$0, Z=244)
        mmix.write_tetra(0, 0x0B0100F4); // FLOTUI $1,$0,244 (X=01, Y=00, Z=F4=244)
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 244.0).abs() < 1e-10);
    }

    #[test]
    fn test_sflot() {
        let mut mmix = MMix::new();
        // SFLOT $1, $3 - Convert signed to short float (f32 precision)
        mmix.set_register(3, 123);
        mmix.write_tetra(0, 0x0C010003); // SFLOT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 123.0).abs() < 1e-5);
    }

    #[test]
    fn test_sfloti() {
        let mut mmix = MMix::new();
        // SFLOTI $1, 64 - Convert immediate signed to short float
        mmix.write_tetra(0, 0x0D010040); // SFLOTI $1,64 (YZ=0x0040)
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 64.0).abs() < 1e-5);
    }

    #[test]
    fn test_sflotu() {
        let mut mmix = MMix::new();
        // SFLOTU $1, $3 - Convert unsigned to short float
        mmix.set_register(3, 777);
        mmix.write_tetra(0, 0x0E010003); // SFLOTU $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 777.0).abs() < 1e-5);
    }

    #[test]
    fn test_sflotui() {
        let mut mmix = MMix::new();
        // SFLOTUI $1, 255 - Convert immediate unsigned to short float
        mmix.write_tetra(0, 0x0F0100FF); // SFLOTUI $1,255 (YZ=0x00FF)
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 255.0).abs() < 1e-5);
    }

    #[test]
    fn test_fint_round_near() {
        let mut mmix = MMix::new();
        // FINT $1, $0, $3 - Integerize with ROUND_NEAR mode
        mmix.set_special(SpecialReg::RA, 0 << RA_ROUND_SHIFT); // Round mode 0 = ROUND_NEAR
        mmix.set_register(3, 3.7f64.to_bits());
        mmix.write_tetra(0, 0x17010003); // FINT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_fint_round_off() {
        let mut mmix = MMix::new();
        // Mode 1 = ROUND_OFF (toward zero / truncate).
        mmix.set_special(SpecialReg::RA, 1 << RA_ROUND_SHIFT);
        mmix.set_register(3, 3.7f64.to_bits());
        mmix.write_tetra(0, 0x17010003); // FINT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_fint_round_up() {
        let mut mmix = MMix::new();
        // Mode 2 = ROUND_UP (toward +∞).
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT);
        mmix.set_register(3, 3.2f64.to_bits());
        mmix.write_tetra(0, 0x17010003); // FINT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_fint_round_down() {
        let mut mmix = MMix::new();
        // Mode 3 = ROUND_DOWN (toward -∞).
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT);
        mmix.set_register(3, 3.9f64.to_bits());
        mmix.write_tetra(0, 0x17010003); // FINT $1,$0,$3
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_fint_round_down_negative() {
        let mut mmix = MMix::new();
        // Mode 3 floors -3.2 → -4.0 (toward -∞).
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT);
        mmix.set_register(3, (-3.2f64).to_bits());
        mmix.write_tetra(0, 0x17010003);
        assert!(mmix.execute_instruction());
        let result = f64::from_bits(mmix.get_register(1));
        assert!((result + 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_fint_inexact_flag() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RA, 0 << RA_ROUND_SHIFT);
        mmix.set_register(3, 3.5f64.to_bits());
        mmix.write_tetra(0, 0x17010003);
        assert!(mmix.execute_instruction());
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    // ========== Zero or Set Tests ==========

    #[test]
    fn test_zsn_condition_true() {
        let mut mmix = MMix::new();
        // ZSN $1, $2, $3 - If $2 < 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, (-10i64) as u64);
        mmix.set_register(3, 50);
        mmix.write_tetra(0, 0x70010203); // ZSN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 50); // Condition true: $3
    }

    #[test]
    fn test_zsn_condition_false() {
        let mut mmix = MMix::new();
        // ZSN $1, $2, $3 - If $2 >= 0, set $1 = 0
        mmix.set_register(2, 100);
        mmix.set_register(3, 50);
        mmix.write_tetra(0, 0x70010203); // ZSN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zsni() {
        let mut mmix = MMix::new();
        // ZSNI $1, $2, 50 - If $2 < 0, set $1 = 50, else $1 = 0
        mmix.set_register(2, (-1i64) as u64);
        mmix.write_tetra(0, 0x71010232); // ZSNI $1,$2,50
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 50); // Condition true: 50
    }

    #[test]
    fn test_zsz_condition_true() {
        let mut mmix = MMix::new();
        // ZSZ $1, $2, $3 - If $2 == 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, 0);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x72010203); // ZSZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 20); // Condition true: $3
    }

    #[test]
    fn test_zsz_condition_false() {
        let mut mmix = MMix::new();
        // ZSZ $1, $2, $3 - Set $1 = 0 if $1 is not zero
        mmix.set_register(1, 1);
        mmix.set_register(2, 10);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x72010203); // ZSZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zszi() {
        let mut mmix = MMix::new();
        // ZSZI $1, $2, 15 - If $2 == 0, set $1 = 15, else $1 = 0
        mmix.set_register(2, 0);
        mmix.write_tetra(0, 0x7301020F); // ZSZI $1,$2,15
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 15); // Condition true: 15
    }

    #[test]
    fn test_zsp_condition_true() {
        let mut mmix = MMix::new();
        // ZSP $1, $2, $3 - If $2 > 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, 5);
        mmix.set_register(3, 7);
        mmix.write_tetra(0, 0x74010203); // ZSP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 7); // Condition true: $3
    }

    #[test]
    fn test_zsp_condition_false_zero() {
        let mut mmix = MMix::new();
        // ZSP $1, $2, $3 - If $2 <= 0, set $1 = 0
        mmix.set_register(2, 0);
        mmix.set_register(3, 7);
        mmix.write_tetra(0, 0x74010203); // ZSP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zspi() {
        let mut mmix = MMix::new();
        // ZSPI $1, $2, 25 - If $2 > 0, set $1 = 25, else $1 = 0
        mmix.set_register(2, 50);
        mmix.write_tetra(0, 0x75010219); // ZSPI $1,$2,25
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 25); // Condition true: 25
    }

    #[test]
    fn test_zsod_condition_true() {
        let mut mmix = MMix::new();
        // ZSOD $1, $2, $3 - If $2 is odd, set $1 = $3, else $1 = 0
        mmix.set_register(2, 7);
        mmix.set_register(3, 15);
        mmix.write_tetra(0, 0x76010203); // ZSOD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 15); // Condition true: $3
    }

    #[test]
    fn test_zsod_condition_false() {
        let mut mmix = MMix::new();
        // ZSOD $1, $2, $3 - Set $1 = 0 if $1 is even
        mmix.set_register(1, 8);
        mmix.set_register(2, 10);
        mmix.set_register(3, 15);
        mmix.write_tetra(0, 0x76010203); // ZSOD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zsodi() {
        let mut mmix = MMix::new();
        // ZSODI $1, $2, 11 - If $2 is odd, set $1 = 11, else $1 = 0
        mmix.set_register(2, 99);
        mmix.write_tetra(0, 0x7701020B); // ZSODI $1,$2,11
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 11); // Condition true: 11
    }

    #[test]
    fn test_zsnn_condition_true_positive() {
        let mut mmix = MMix::new();
        // ZSNN $1, $2, $3 - If $2 >= 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, 30);
        mmix.set_register(3, 40);
        mmix.write_tetra(0, 0x78010203); // ZSNN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 40); // Condition true: $3
    }

    #[test]
    fn test_zsnn_condition_true_zero() {
        let mut mmix = MMix::new();
        // ZSNN $1, $2, $3 - If $2 >= 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, 0);
        mmix.set_register(3, 40);
        mmix.write_tetra(0, 0x78010203); // ZSNN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 40); // Condition true: $3
    }

    #[test]
    fn test_zsnn_condition_false() {
        let mut mmix = MMix::new();
        // ZSNN $1, $2, $3 - If $2 < 0, set $1 = 0
        mmix.set_register(2, (-5i64) as u64);
        mmix.set_register(3, 40);
        mmix.write_tetra(0, 0x78010203); // ZSNN $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zsnni() {
        let mut mmix = MMix::new();
        // ZSNNI $1, $2, 8 - If $2 >= 0, set $1 = 8, else $1 = 0
        mmix.set_register(2, 92);
        mmix.write_tetra(0, 0x79010208); // ZSNNI $1,$2,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 8); // Condition true: 8
    }

    #[test]
    fn test_zsnz_condition_true() {
        let mut mmix = MMix::new();
        // ZSNZ $1, $2, $3 - If $2 != 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, 100);
        mmix.set_register(3, 200);
        mmix.write_tetra(0, 0x7A010203); // ZSNZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 200); // Condition true: $3
    }

    #[test]
    fn test_zsnz_condition_false() {
        let mut mmix = MMix::new();
        // ZSNZ $1, $2, $3 - If $2 == 0, set $1 = 0
        mmix.set_register(2, 0);
        mmix.set_register(3, 200);
        mmix.write_tetra(0, 0x7A010203); // ZSNZ $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zsnzi() {
        let mut mmix = MMix::new();
        // ZSNZI $1, $2, 33 - If $2 != 0, set $1 = 33, else $1 = 0
        mmix.set_register(2, 67);
        mmix.write_tetra(0, 0x7B010221); // ZSNZI $1,$2,33
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 33); // Condition true: 33
    }

    #[test]
    fn test_zsnp_condition_true_negative() {
        let mut mmix = MMix::new();
        // ZSNP $1, $2, $3 - If $2 <= 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, (-100i64) as u64);
        mmix.set_register(3, 25);
        mmix.write_tetra(0, 0x7C010203); // ZSNP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 25); // Condition true: $3
    }

    #[test]
    fn test_zsnp_condition_true_zero() {
        let mut mmix = MMix::new();
        // ZSNP $1, $2, $3 - If $2 == 0, set $1 = $3, else $1 = 0
        mmix.set_register(2, 0);
        mmix.set_register(3, 25);
        mmix.write_tetra(0, 0x7C010203); // ZSNP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 25); // Condition true: $3
    }

    #[test]
    fn test_zsnp_condition_false() {
        let mut mmix = MMix::new();
        // ZSNP $1, $2, $3 - Set $1 = 0 if $1 is positive
        mmix.set_register(1, 1);
        mmix.set_register(2, 50);
        mmix.set_register(3, 25);
        mmix.write_tetra(0, 0x7C010203); // ZSNP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zsnpi() {
        let mut mmix = MMix::new();
        // ZSNPI $1, $2, 44 - If $2 <= 0, set $1 = 44, else $1 = 0
        mmix.set_register(2, 0);
        mmix.write_tetra(0, 0x7D01022C); // ZSNPI $1,$2,44
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 44); // Condition true: 44
    }

    #[test]
    fn test_zsev_condition_true() {
        let mut mmix = MMix::new();
        // ZSEV $1, $2, $3 - If $2 is even, set $1 = $3, else $1 = 0
        mmix.set_register(2, 80);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x7E010203); // ZSEV $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 20); // Condition true: $3
    }

    #[test]
    fn test_zsev_condition_false() {
        let mut mmix = MMix::new();
        // ZSEV $1, $2, $3 - If $2 is odd, set $1 = 0
        mmix.set_register(2, 7);
        mmix.set_register(3, 20);
        mmix.write_tetra(0, 0x7E010203); // ZSEV $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Condition false: 0
    }

    #[test]
    fn test_zsevi() {
        let mut mmix = MMix::new();
        // ZSEVI $1, $2, 12 - If $2 is even, set $1 = 12, else $1 = 0
        mmix.set_register(2, 88);
        mmix.write_tetra(0, 0x7F01020C); // ZSEVI $1,$2,12
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 12); // Condition true: 12
    }

    // ========== Special Load/Store Tests ==========

    #[test]
    fn test_ldht() {
        let mut mmix = MMix::new();
        // LDHT $1, $2, $3 - Load high tetra
        mmix.set_register(2, 100);
        mmix.set_register(3, 4);
        mmix.write_tetra(104, 0x12345678);
        mmix.write_tetra(0, 0x92010203); // LDHT $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0x1234567800000000);
    }

    #[test]
    fn test_ldhti() {
        let mut mmix = MMix::new();
        // LDHTI $1, $2, 8 - Load high tetra immediate
        mmix.set_register(2, 100);
        mmix.write_tetra(108, 0xABCDEF01);
        mmix.write_tetra(0, 0x93010208); // LDHTI $1,$2,8
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0xABCDEF0100000000);
    }

    #[test]
    fn test_cswap_success() {
        let mut mmix = MMix::new();
        // CSWAP $1, $2, $3 - Compare and swap (successful)
        let addr = 1000u64;
        let old_value = 0x123456789ABCDEF0u64;
        let new_value = 0xFEDCBA9876543210u64;

        mmix.write_octa(addr, old_value);
        mmix.set_special(SpecialReg::RP, old_value); // Set compare value
        mmix.set_register(1, new_value); // New value to write
        mmix.set_register(2, addr);
        mmix.set_register(3, 0);

        mmix.write_tetra(0, 0x94010203); // CSWAP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1); // Success
        assert_eq!(mmix.read_octa(addr), new_value); // Memory updated
    }

    #[test]
    fn test_cswap_failure() {
        let mut mmix = MMix::new();
        // CSWAP $1, $2, $3 - Compare and swap (failed)
        let addr = 1000u64;
        let mem_value = 0x123456789ABCDEF0u64;
        let compare_value = 0x1111111111111111u64;
        let new_value = 0xFEDCBA9876543210u64;

        mmix.write_octa(addr, mem_value);
        mmix.set_special(SpecialReg::RP, compare_value); // Different compare value
        mmix.set_register(1, new_value);
        mmix.set_register(2, addr);
        mmix.set_register(3, 0);

        mmix.write_tetra(0, 0x94010203); // CSWAP $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Failure
        assert_eq!(mmix.read_octa(addr), mem_value); // Memory unchanged
        assert_eq!(mmix.get_special(SpecialReg::RP), mem_value); // rP <- M8[$Y+$Z]
    }

    #[test]
    fn test_cswapi() {
        let mut mmix = MMix::new();
        // CSWAPI $1, $2, 16 - Compare and swap immediate
        let addr = 2000u64;
        let old_value = 0xAAAAAAAAAAAAAAAAu64;
        let new_value = 0xBBBBBBBBBBBBBBBBu64;

        mmix.write_octa(addr + 16, old_value);
        mmix.set_special(SpecialReg::RP, old_value);
        mmix.set_register(1, new_value);
        mmix.set_register(2, addr);

        mmix.write_tetra(0, 0x95010210); // CSWAPI $1,$2,16
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1); // Success
        assert_eq!(mmix.read_octa(addr + 16), new_value);
    }

    #[test]
    fn test_cswapi_failure() {
        let mut mmix = MMix::new();
        // CSWAPI $1, $2, 16 - Compare and swap immediate (failed)
        let addr = 2000u64;
        let mem_value = 0x123456789ABCDEF0u64;
        let compare_value = 0x1111111111111111u64;
        let new_value = 0xFEDCBA9876543210u64;

        mmix.write_octa(addr + 16, mem_value);
        mmix.set_special(SpecialReg::RP, compare_value); // Different compare value
        mmix.set_register(1, new_value);
        mmix.set_register(2, addr);

        mmix.write_tetra(0, 0x95010210); // CSWAPI $1,$2,16
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Failure
        assert_eq!(mmix.read_octa(addr + 16), mem_value); // Memory unchanged
        assert_eq!(mmix.get_special(SpecialReg::RP), mem_value); // rP <- M8[$Y+Z]
    }

    #[test]
    fn octa_load_reads_the_aligned_base_from_any_address_in_the_block() {
        // LDO $1,$2,$3 with $3 sweeping the octabyte's own aligned block:
        // every one of the 8 addresses must resolve to the same value:
        // M8[A] = M8[8*floor(A/8)].
        let base = 800u64;
        let value = 0x1122334455667788u64;
        for offset in 0u64..8 {
            let mut mmix = MMix::new();
            mmix.write_octa(base, value);
            mmix.set_register(2, base);
            mmix.set_register(3, offset);
            mmix.write_tetra(0, 0x8C010203); // LDO $1,$2,$3
            assert!(mmix.execute_instruction());
            assert_eq!(mmix.get_register(1), value, "offset {offset}");
        }
    }

    #[test]
    fn octa_store_at_misaligned_address_lands_at_aligned_base() {
        // STO $1,$2,$3 at base+5: the write must land at the aligned base,
        // not straddle base and base+8. Reverting write_octa's mask alone
        // fails this, since the value would then land 5 bytes high.
        let mut mmix = MMix::new();
        let base = 800u64;
        let value = 0x99AABBCCDDEEFF00u64;
        mmix.set_register(1, value);
        mmix.set_register(2, base);
        mmix.set_register(3, 5);
        mmix.write_tetra(0, 0xAC010203); // STO $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(base), value);
    }

    #[test]
    fn tetra_load_reads_the_aligned_base_from_any_address_in_the_block() {
        // LDTU $1,$2,$3 with $3 sweeping the tetra's own aligned block.
        let base = 400u64;
        let value = 0x11223344u32;
        for offset in 0u64..4 {
            let mut mmix = MMix::new();
            mmix.write_tetra(base, value);
            mmix.set_register(2, base);
            mmix.set_register(3, offset);
            mmix.write_tetra(0, 0x8A010203); // LDTU $1,$2,$3
            assert!(mmix.execute_instruction());
            assert_eq!(mmix.get_register(1), value as u64, "offset {offset}");
        }
    }

    #[test]
    fn tetra_store_at_misaligned_address_lands_at_aligned_base() {
        // STT $1,$2,$3 at base+3: reverting write_tetra's mask alone fails
        // this.
        let mut mmix = MMix::new();
        let base = 400u64;
        let value = 0xAABBCCDDu32;
        mmix.set_register(1, value as u64);
        mmix.set_register(2, base);
        mmix.set_register(3, 3);
        mmix.write_tetra(0, 0xA8010203); // STT $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_tetra(base), value);
    }

    #[test]
    fn wyde_load_reads_the_aligned_base_from_any_address_in_the_block() {
        // LDWU $1,$2,$3 with $3 sweeping the wyde's own aligned block.
        let base = 200u64;
        let value = 0xBEEFu16;
        for offset in 0u64..2 {
            let mut mmix = MMix::new();
            mmix.write_wyde(base, value);
            mmix.set_register(2, base);
            mmix.set_register(3, offset);
            mmix.write_tetra(0, 0x86010203); // LDWU $1,$2,$3
            assert!(mmix.execute_instruction());
            assert_eq!(mmix.get_register(1), value as u64, "offset {offset}");
        }
    }

    #[test]
    fn wyde_store_at_misaligned_address_lands_at_aligned_base() {
        // STW $1,$2,$3 at base+1: reverting write_wyde's mask alone fails
        // this.
        let mut mmix = MMix::new();
        let base = 200u64;
        let value = 0xCAFEu16;
        mmix.set_register(1, value as u64);
        mmix.set_register(2, base);
        mmix.set_register(3, 1);
        mmix.write_tetra(0, 0xA4010203); // STW $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_wyde(base), value);
    }

    #[test]
    fn byte_access_at_an_odd_address_still_reads_that_byte() {
        // A byte is its own alignment: read_byte/write_byte take no mask,
        // unlike the wider accessors above. There is no fix to revert here —
        // this guards against someone later "helpfully" masking read_byte to
        // match its wider siblings.
        let mut mmix = MMix::new();
        mmix.write_byte(801, 0x42);
        assert_eq!(mmix.read_byte(801), 0x42);
        assert_eq!(mmix.read_byte(800), 0);
    }

    #[test]
    fn test_ldunc() {
        let mut mmix = MMix::new();
        // LDUNC $1, $2, $3 - Load uncached
        mmix.set_register(2, 500);
        mmix.set_register(3, 24);
        mmix.write_octa(524, 0x0123456789ABCDEFu64);
        mmix.write_tetra(0, 0x96010203); // LDUNC $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0x0123456789ABCDEFu64);
    }

    #[test]
    fn test_ldunci() {
        let mut mmix = MMix::new();
        // LDUNCI $1, $2, 32 - Load uncached immediate
        mmix.set_register(2, 600);
        mmix.write_octa(632, 0xFEDCBA9876543210u64);
        mmix.write_tetra(0, 0x97010220); // LDUNCI $1,$2,32
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0xFEDCBA9876543210u64);
    }

    #[test]
    fn test_ldvts() {
        let mut mmix = MMix::new();
        // LDVTS $1, $2, $3 - Load virtual translation status
        mmix.set_register(2, 0x1000);
        mmix.set_register(3, 0);
        mmix.write_tetra(0, 0x98010203); // LDVTS $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Returns 0 in simulation
    }

    #[test]
    fn test_ldvtsi() {
        let mut mmix = MMix::new();
        // LDVTSI $1, $2, 0 - Load virtual translation status immediate
        mmix.set_register(2, 0x2000);
        mmix.write_tetra(0, 0x99010200); // LDVTSI $1,$2,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0); // Returns 0 in simulation
    }

    #[test]
    fn test_preld() {
        let mut mmix = MMix::new();
        // PRELD $1, $2, $3 - Preload data (no-op)
        mmix.write_tetra(0, 0x9A010203); // PRELD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_preldi() {
        let mut mmix = MMix::new();
        // PRELDI $1, $2, 64 - Preload data immediate (no-op)
        mmix.write_tetra(0, 0x9B010240); // PRELDI $1,$2,64
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_prego() {
        let mut mmix = MMix::new();
        // PREGO $1, $2, $3 - Preload to go (no-op)
        mmix.write_tetra(0, 0x9C010203); // PREGO $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_pregoi() {
        let mut mmix = MMix::new();
        // PREGOI $1, $2, 128 - Preload to go immediate (no-op)
        mmix.write_tetra(0, 0x9D010280); // PREGOI $1,$2,128
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_go() {
        let mut mmix = MMix::new();
        // GO $1, $2, $3 - Go to location
        mmix.set_register(2, 1000);
        mmix.set_register(3, 24);
        mmix.write_tetra(0, 0x9E010203); // GO $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 4); // Return address
        assert_eq!(mmix.get_pc(), 1024); // Jump to 1000 + 24
    }

    #[test]
    fn test_goi() {
        let mut mmix = MMix::new();
        // GOI $1, $2, 200 - Go to location immediate
        mmix.set_register(2, 5000);
        mmix.write_tetra(0, 0x9F0102C8); // GOI $1,$2,200
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 4); // Return address
        assert_eq!(mmix.get_pc(), 5200); // Jump to 5000 + 200
    }

    // ========== Stack/Sync/Store Tests ==========

    #[test]
    fn test_stsf() {
        let mut mmix = MMix::new();
        // STSF $1, $2, $3 - Store short float
        let f64_value = std::f64::consts::PI;
        mmix.set_register(1, f64_value.to_bits());
        mmix.set_register(2, 1000);
        mmix.set_register(3, 8);
        mmix.write_tetra(0, 0xB0010203); // STSF $1,$2,$3
        assert!(mmix.execute_instruction());

        let stored_tetra = mmix.read_tetra(1008);
        let f32_value = f32::from_bits(stored_tetra);
        assert!((f32_value - std::f32::consts::PI).abs() < 1e-5);
    }

    #[test]
    fn test_stsfi() {
        let mut mmix = MMix::new();
        // STSFI $1, $2, 16 - Store short float immediate
        let f64_value = std::f64::consts::E;
        mmix.set_register(1, f64_value.to_bits());
        mmix.set_register(2, 2000);
        mmix.write_tetra(0, 0xB1010210); // STSFI $1,$2,16
        assert!(mmix.execute_instruction());

        let stored_tetra = mmix.read_tetra(2016);
        let f32_value = f32::from_bits(stored_tetra);
        assert!((f32_value - std::f32::consts::E).abs() < 1e-5);
    }

    #[test]
    fn test_stht() {
        let mut mmix = MMix::new();
        // STHT $1, $2, $3 - Store high tetra
        mmix.set_register(1, 0x1234567890ABCDEFu64);
        mmix.set_register(2, 500);
        mmix.set_register(3, 12);
        mmix.write_tetra(0, 0xB2010203); // STHT $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_tetra(512), 0x12345678);
    }

    #[test]
    fn test_sthti() {
        let mut mmix = MMix::new();
        // STHTI $1, $2, 24 - Store high tetra immediate
        mmix.set_register(1, 0xFEDCBA9876543210u64);
        mmix.set_register(2, 600);
        mmix.write_tetra(0, 0xB7010218); // STHTI $1,$2,24
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_tetra(624), 0xFEDCBA98);
    }

    #[test]
    fn test_stco() {
        let mut mmix = MMix::new();
        // STCO $X, $Y, $Z - Store constant octabyte (X=42)
        mmix.set_register(2, 1500);
        mmix.set_register(3, 8);
        mmix.write_tetra(0, 0xB42A0203); // STCO $42,$2,$3 (X=0x2A=42)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(1508), 42);
    }

    #[test]
    fn test_stcoi() {
        let mut mmix = MMix::new();
        // STCOI $X, $Y, Z - Store constant octabyte immediate (X=100)
        mmix.set_register(2, 2500);
        mmix.write_tetra(0, 0xB5640220); // STCOI $100,$2,32 (X=0x64=100)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(2532), 100);
    }

    #[test]
    fn test_stunc() {
        let mut mmix = MMix::new();
        // STUNC $1, $2, $3 - Store uncached
        mmix.set_register(1, 0xABCDEF0123456789u64);
        mmix.set_register(2, 3000);
        mmix.set_register(3, 16);
        mmix.write_tetra(0, 0xB6010203); // STUNC $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(3016), 0xABCDEF0123456789u64);
    }

    #[test]
    fn test_stunci() {
        let mut mmix = MMix::new();
        // STUNCI $1, $2, 40 - Store uncached immediate
        mmix.set_register(1, 0x123456789ABCDEFu64);
        mmix.set_register(2, 4000);
        mmix.write_tetra(0, 0xB7010228); // STUNCI $1,$2,40
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.read_octa(4040), 0x123456789ABCDEFu64);
    }

    #[test]
    fn test_syncd() {
        let mut mmix = MMix::new();
        // SYNCD $1, $2, $3 - Synchronize data (no-op)
        mmix.write_tetra(0, 0xB8010203); // SYNCD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_syncdi() {
        let mut mmix = MMix::new();
        // SYNCDI $1, $2, 64 - Synchronize data immediate (no-op)
        mmix.write_tetra(0, 0xB9010203); // SYNCDI $1,$2,64
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_prest() {
        let mut mmix = MMix::new();
        // PREST $1, $2, $3 - Prestore (no-op)
        mmix.write_tetra(0, 0xBA010203); // PREST $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    #[test]
    fn test_presti() {
        let mut mmix = MMix::new();
        // PRESTI $1, $2, 128 - Prestore immediate (no-op)
        mmix.write_tetra(0, 0xBB010280); // PRESTI $1,$2,128
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4); // PC advanced
    }

    // ========== TRAP Handler Tests ==========

    #[test]
    fn test_trap_halt() {
        let mut mmix = MMix::new();
        // TRAP 0, Halt, 0
        mmix.write_tetra(0, 0x00000000); // TRAP 0,0,0
        let should_continue = mmix.execute_instruction();
        assert!(!should_continue); // Should halt
        assert_eq!(mmix.get_pc(), 4); // PC still advances
    }

    #[test]
    fn test_trap_fputs_stdout() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        let test_string = b"Hello, MMIX!\0";
        let str_addr = 1000u64;

        for (i, &byte) in test_string.iter().enumerate() {
            mmix.write_byte(str_addr + i as u64, byte);
        }

        mmix.set_register(255, str_addr); // Fputs reads string address from $255
        mmix.write_tetra(0, 0x00000801); // TRAP 0, Fputs (8), 1 (stdout)
        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_pc(), 4);
        assert_eq!(mmix.get_register(255), 12); // bytes written
        assert_eq!(handle.stdout(), b"Hello, MMIX!");
        assert!(handle.stderr().is_empty());
    }

    #[test]
    fn test_trap_fputs_stderr() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        let test_string = b"Error message\0";
        let str_addr = 2000u64;

        for (i, &byte) in test_string.iter().enumerate() {
            mmix.write_byte(str_addr + i as u64, byte);
        }

        mmix.set_register(255, str_addr);
        mmix.write_tetra(0, 0x00000802); // TRAP 0, Fputs (8), 2 (stderr)
        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_pc(), 4);
        assert_eq!(mmix.get_register(255), 13);
        assert_eq!(handle.stderr(), b"Error message");
        assert!(handle.stdout().is_empty());
    }

    #[test]
    fn test_trap_fputc_stdout() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(255, b'X' as u64);
        mmix.write_tetra(0, 0x00000901); // TRAP 0, Fputc (9), 1 (stdout)
        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_register(255), 0); // Success (return code 0 in $255)
        assert_eq!(mmix.get_pc(), 4);
        assert_eq!(handle.stdout(), b"X");
    }

    #[test]
    fn test_trap_fputws() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        // TRAP 0, Fputws, 1 (write wide string to stdout)
        let test_string = b"Wide string\0";
        let str_addr = 3000u64;

        for (i, &byte) in test_string.iter().enumerate() {
            mmix.write_byte(str_addr + i as u64, byte);
        }

        mmix.set_register(255, str_addr); // $255 contains string address
        mmix.write_tetra(0, 0x00000A01); // TRAP 0, 10, 1 (Fputws to stdout)
        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_register(255), 11); // Character count returned in $255
        assert_eq!(handle.stdout(), b"Wide string");
    }

    #[test]
    fn test_host_trap_hook_reports_arg_and_both_255_values() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        let test_string = b"Hi\0";
        let str_addr = 4000u64;

        for (i, &byte) in test_string.iter().enumerate() {
            mmix.write_byte(str_addr + i as u64, byte);
        }

        mmix.set_register(255, str_addr);
        mmix.write_tetra(0, 0x00000801); // TRAP 0, Fputs (8), 1 (stdout)
        assert!(mmix.execute_instruction());

        let traps = handle.traps();
        assert_eq!(traps.len(), 1);
        let (code, arg, arg255, result255) = traps[0];
        assert_eq!(code, TrapCode::Fputs);
        assert_eq!(arg, 1); // fd 1 (stdout)
        assert_eq!(arg255, str_addr); // $255 before: the string address
        assert_eq!(result255, 2); // $255 after: the byte count
        assert!(handle.diagnostics().is_empty()); // a clean write logs no diagnostic
    }

    #[test]
    fn test_halt_routes_diagnostic_and_flush_to_host() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_register(255, 42);
        mmix.write_tetra(0, 0x00000000); // TRAP 0, Halt (0), 0
        let should_continue = mmix.execute_instruction();
        assert!(!should_continue);
        assert_eq!(
            handle.diagnostics(),
            vec!["HALT trap at PC=0x0000000000000000, exit code=42".to_string()]
        );
        assert_eq!(handle.flushes(), 1);
        assert!(handle.stderr().is_empty()); // no stray fd-2 write alongside it
        assert_eq!(handle.traps(), vec![(TrapCode::Halt, 0, 42, 42)]);
    }

    #[test]
    fn test_reset_restores_a_dirtied_machine_and_keeps_the_host() {
        let (host, handle) = CaptureHost::with_clock(11);
        let mut mmix = MMix::with_host(host);

        // Dirty seven of the nine fields. `file_handles` and `next_fd` need a
        // real file, so they are left to `blank`'s exhaustive struct literal.
        const SCRATCH: u64 = 0x5000; // never executed, so nothing overwrites it
        for reg in 0..=255u8 {
            mmix.set_register(reg, 0xDEAD_0000 | u64::from(reg));
        }
        mmix.set_special(SpecialReg::RA, 0x1234);
        mmix.set_special(SpecialReg::RG, 200);
        mmix.write_tetra(SCRATCH, 0xFFFF_FFFF);
        assert_ne!(mmix.read_tetra(SCRATCH), 0, "memory must start dirty");

        // A real PUSHJ, so `call_depth` is genuinely nonzero.
        mmix.set_pc(0x4000);
        mmix.write_tetra(0x4000, 0xF2_02_00_01); // PUSHJ $2, forward 1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.call_depth(), 1, "PUSHJ must push a frame");

        mmix.set_pc(0x4100);
        mmix.set_register(255, 77);
        mmix.write_tetra(0x4100, 0x00000000); // TRAP 0, Halt -> sets exit_code
        assert!(!mmix.execute_instruction());
        assert_eq!(mmix.get_exit_code(), 77);

        mmix.reset();

        let fresh = MMix::new();
        for reg in 0..=255u8 {
            assert_eq!(mmix.get_register(reg), fresh.get_register(reg), "$#{reg}");
        }
        for spec in [
            SpecialReg::RA,
            SpecialReg::RG,
            SpecialReg::RL,
            SpecialReg::RN,
            SpecialReg::RO,
            SpecialReg::RS,
        ] {
            assert_eq!(mmix.get_special(spec), fresh.get_special(spec), "{spec:?}");
        }
        assert_eq!(mmix.get_pc(), fresh.get_pc());
        assert_eq!(mmix.get_exit_code(), fresh.get_exit_code());
        assert_eq!(mmix.call_depth(), fresh.call_depth(), "frames");
        assert_eq!(mmix.read_tetra(SCRATCH), 0, "memory");

        // The host survives, and is still the injected one.
        mmix.set_register(255, u64::from(b'A'));
        mmix.write_tetra(0, 0x00000901); // TRAP 0, Fputc, fd 1
        assert!(mmix.execute_instruction());
        assert_eq!(handle.stdout(), b"A");
    }

    #[test]
    fn test_boxed_host_delegates_every_method() {
        let (host, handle) = CaptureHost::with_clock(7_000_000);
        let boxed: Box<dyn Host> = Box::new(host);
        let mut mmix = MMix::with_host(boxed);

        mmix.set_register(255, u64::from(b'Z'));
        mmix.write_tetra(0, 0x00000901); // TRAP 0, Fputc (9), fd 1 -> write
        assert!(mmix.execute_instruction());

        mmix.set_pc(4);
        mmix.write_tetra(4, 0x00000D00); // TRAP 0, Time (13), unit 0 -> now_micros
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(255), 7);

        mmix.set_pc(8);
        mmix.set_register(255, 9);
        mmix.write_tetra(8, 0x00000000); // TRAP 0, Halt (0) -> flush + diagnostic
        assert!(!mmix.execute_instruction());

        // One assertion per trait method, so a missed delegation names itself.
        assert_eq!(handle.stdout(), b"Z"); // write
        assert_eq!(handle.flushes(), 1); // flush
        assert_eq!(handle.diagnostics().len(), 1); // diagnostic
        assert_eq!(
            handle.traps(),
            vec![
                (TrapCode::Fputc, 1, u64::from(b'Z'), 0),
                // $255 enters Time as 0: Fputc stored 0 there on success.
                (TrapCode::Time, 0, 0, 7),
                (TrapCode::Halt, 0, 9, 9),
            ]
        ); // trap
    }

    #[test]
    fn test_injected_clock_drives_handle_time() {
        let (host, _handle) = CaptureHost::with_clock(5_000_000); // 5s since epoch
        let mut mmix = MMix::with_host(host);
        mmix.write_tetra(0, 0x00000D00); // TRAP 0, Time (13), unit=0 (seconds)
        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_register(255), 5);
    }

    #[test]
    fn test_trap_read_cstring() {
        let mut mmix = MMix::new();
        // Test the helper function read_cstring
        let test_string = b"Test String\0";
        let addr = 1000u64;

        for (i, &byte) in test_string.iter().enumerate() {
            mmix.write_byte(addr + i as u64, byte);
        }

        let result = mmix.read_cstring(addr, 256);
        assert_eq!(result, "Test String");
    }

    #[test]
    fn test_trap_fclose_error() {
        let mut mmix = MMix::new();
        // Try to close non-existent file
        mmix.set_register(255, 99u64); // Non-existent FD in $255
        mmix.write_tetra(0, 0x00000300); // TRAP 0, 3, 0
        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_register(255), (-1i64) as u64); // Error returned in $255
    }

    #[test]
    fn test_trap_time_microseconds() {
        let mut mmix = MMix::new();
        // TRAP 0, Time, 2 (get time in microseconds)
        mmix.write_tetra(0, 0x00000D02); // TRAP 0, 13, 2 (Time in microseconds)

        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_pc(), 4); // PC advanced

        let time_us = mmix.get_register(255);
        // Time should be greater than 0 (some time has passed since Unix epoch)
        assert!(time_us > 0);
        // Time should be reasonable (after Jan 1, 2020)
        // Jan 1, 2020 00:00:00 UTC = 1577836800 seconds = 1577836800000000 microseconds
        assert!(time_us > 1_577_836_800_000_000);
        // Time should be before year 3000 (approximately)
        // Jan 1, 3000 00:00:00 UTC ≈ 32503680000 seconds ≈ 32503680000000000 microseconds
        assert!(time_us < 32_503_680_000_000_000);
    }

    #[test]
    fn test_trap_time_milliseconds() {
        let mut mmix = MMix::new();
        // TRAP 0, Time, 1 (get time in milliseconds)
        mmix.write_tetra(0, 0x00000D01); // TRAP 0, 13, 1 (Time in milliseconds)

        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_pc(), 4);

        let time_ms = mmix.get_register(255);
        assert!(time_ms > 0);
        // After Jan 1, 2020 in milliseconds
        assert!(time_ms > 1_577_836_800_000);
        // Before year 3000 in milliseconds
        assert!(time_ms < 32_503_680_000_000);
    }

    #[test]
    fn test_trap_time_seconds() {
        let mut mmix = MMix::new();
        // TRAP 0, Time, 0 (get time in seconds)
        mmix.write_tetra(0, 0x00000D00); // TRAP 0, 13, 0 (Time in seconds)

        let should_continue = mmix.execute_instruction();
        assert!(should_continue);
        assert_eq!(mmix.get_pc(), 4);

        let time_s = mmix.get_register(255);
        assert!(time_s > 0);
        // After Jan 1, 2020 in seconds
        assert!(time_s > 1_577_836_800);
        // Before year 3000 in seconds
        assert!(time_s < 32_503_680_000);
    }

    #[test]
    fn test_trap_time_monotonic() {
        let mut mmix = MMix::new();
        // Get time twice and ensure second is >= first (monotonic)
        mmix.write_tetra(0, 0x00000D02); // TRAP 0, 13, 2 (microseconds)
        mmix.execute_instruction();
        let time1 = mmix.get_register(255);

        // Reset PC and execute again
        mmix.set_pc(0);
        mmix.execute_instruction();
        let time2 = mmix.get_register(255);

        // Time should be monotonic (second time >= first time)
        assert!(time2 >= time1);
    }

    #[test]
    fn test_trap_fputs_unknown_fd_returns_error() {
        // Fputs to a closed/unknown fd must report -1, not the byte count.
        let mut mmix = MMix::new();
        let test_string = b"data\0";
        let str_addr = 200u64;
        for (i, &byte) in test_string.iter().enumerate() {
            mmix.write_byte(str_addr + i as u64, byte);
        }
        mmix.set_register(255, str_addr);
        // TRAP 0, Fputs (8), 99 (no such fd)
        mmix.write_tetra(0, 0x00000863);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(255), (-1i64) as u64);
    }

    #[test]
    fn test_trap_fputc_unknown_fd_returns_error() {
        let mut mmix = MMix::new();
        mmix.set_register(255, b'A' as u64);
        // TRAP 0, Fputc (9), 99
        mmix.write_tetra(0, 0x00000963);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(255), (-1i64) as u64);
    }

    // ==================== Floating-point: rA flag coverage ====================

    #[test]
    fn test_fadd_overflow_sets_o() {
        let mut mmix = MMix::new();
        mmix.set_register(2, f64::MAX.to_bits());
        mmix.set_register(3, f64::MAX.to_bits());
        mmix.write_tetra(0, 0x04010203); // FADD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert!(f64::from_bits(mmix.get_register(1)).is_infinite());
        assert!((mmix.get_special(SpecialReg::RA) & RA_O) != 0);
    }

    #[test]
    fn test_fsub_inf_minus_inf_sets_i() {
        let mut mmix = MMix::new();
        mmix.set_register(2, f64::INFINITY.to_bits());
        mmix.set_register(3, f64::INFINITY.to_bits());
        mmix.write_tetra(0, 0x06010203); // FSUB $1,$2,$3
        assert!(mmix.execute_instruction());
        assert!(f64::from_bits(mmix.get_register(1)).is_nan());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fmul_zero_times_inf_sets_i() {
        let mut mmix = MMix::new();
        mmix.set_register(2, 0.0f64.to_bits());
        mmix.set_register(3, f64::INFINITY.to_bits());
        mmix.write_tetra(0, 0x10010203); // FMUL $1,$2,$3
        assert!(mmix.execute_instruction());
        assert!(f64::from_bits(mmix.get_register(1)).is_nan());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fdiv_by_zero_sets_z() {
        let mut mmix = MMix::new();
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 0.0f64.to_bits());
        mmix.write_tetra(0, 0x14010203); // FDIV $1,$2,$3
        assert!(mmix.execute_instruction());
        assert!(f64::from_bits(mmix.get_register(1)).is_infinite());
        let ra = mmix.get_special(SpecialReg::RA);
        assert!((ra & RA_Z) != 0, "rA={:#x}", ra);
    }

    #[test]
    fn test_fdiv_zero_by_zero_sets_i() {
        let mut mmix = MMix::new();
        mmix.set_register(2, 0.0f64.to_bits());
        mmix.set_register(3, 0.0f64.to_bits());
        mmix.write_tetra(0, 0x14010203);
        assert!(mmix.execute_instruction());
        assert!(f64::from_bits(mmix.get_register(1)).is_nan());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fdiv_underflow_sets_u() {
        let mut mmix = MMix::new();
        mmix.set_register(2, f64::MIN_POSITIVE.to_bits());
        mmix.set_register(3, 1e16f64.to_bits());
        mmix.write_tetra(0, 0x14010203);
        assert!(mmix.execute_instruction());
        let r = f64::from_bits(mmix.get_register(1));
        assert_eq!(r, 0.0, "expected complete underflow to zero, got {:?}", r);
        assert!((mmix.get_special(SpecialReg::RA) & RA_U) != 0);
    }

    #[test]
    fn test_fsqrt_negative_sets_i() {
        let mut mmix = MMix::new();
        mmix.set_register(3, (-4.0f64).to_bits());
        mmix.write_tetra(0, 0x15010003); // FSQRT $1,$0,$3
        assert!(mmix.execute_instruction());
        assert!(f64::from_bits(mmix.get_register(1)).is_nan());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fsqrt_normal_no_flag() {
        let mut mmix = MMix::new();
        mmix.set_register(3, 9.0f64.to_bits());
        mmix.write_tetra(0, 0x15010003);
        assert!(mmix.execute_instruction());
        assert!((f64::from_bits(mmix.get_register(1)) - 3.0).abs() < 1e-10);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_I, 0);
    }

    #[test]
    fn test_fcmp_nan_sets_i() {
        let mut mmix = MMix::new();
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x01010203); // FCMP
        assert!(mmix.execute_instruction());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_feql_nan_no_flag() {
        let mut mmix = MMix::new();
        // FEQL is "quiet" for NaN: returns 0, no I flag.
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x03010203);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_I, 0);
    }

    #[test]
    fn test_fune_includes_nan() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.001f64.to_bits());
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 5.0f64.to_bits());
        mmix.write_tetra(0, 0x12010203); // FUNE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1);
    }

    #[test]
    fn test_fcmpe_outside_epsilon() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.001f64.to_bits());
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 2.0f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1);
    }

    #[test]
    fn test_fcmpe_binade_scaled_radius() {
        // A flat |y-z|<=epsilon test gives -1 (16 > 0.25). 1024's raw
        // exponent field is 1033, so Nε's radius is 0.25 * 2^11 = 512,
        // which covers 1040 (diff 16) and FCMPE reports 0.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.25f64.to_bits());
        mmix.set_register(2, 1024.0f64.to_bits());
        mmix.set_register(3, 1040.0f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
    }

    #[test]
    fn test_fcmpe_radius_uses_e_minus_1022_not_1023() {
        // 1.0's raw exponent field is 1023, so the radius is
        // 0.5 * 2^(1023-1022) = 1.0, covering the 0.75 gap to 1.75. An
        // off-by-one-binade radius (2^(e-1023) = 0.5) would not.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.5f64.to_bits());
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 1.75f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
    }

    #[test]
    fn test_fcmpe_denormal_neighborhood_uses_fixed_radius() {
        // $3 is subnormal (raw exponent field 0): Nε's denormal case uses
        // the fixed radius 2^-1021 * ε, not a per-value binade scale, and
        // that radius is far smaller than the gap to $2. A flat
        // |y-z|<=epsilon check would call this pair close (1e-300 <=
        // 1e-10) and report 0; the correct radius does not, and $2 > $3
        // gives +1.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 1e-10f64.to_bits());
        mmix.set_register(2, 1e-300f64.to_bits());
        mmix.set_register(3, f64::from_bits(1).to_bits()); // smallest subnormal
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, 1);
    }

    #[test]
    fn test_fcmpe_infinite_neighborhood_epsilon_at_least_two() {
        // Nε(+∞) is everything when ε≥2, so 5.0 ∈ Nε(+∞) and FCMPE
        // reports 0. A flat |y-z|<=epsilon check sees an infinite
        // difference, never within any finite epsilon, and falls back to
        // the sign compare (5.0 < ∞ ⇒ -1).
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 3.0f64.to_bits());
        mmix.set_register(2, 5.0f64.to_bits());
        mmix.set_register(3, f64::INFINITY.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
    }

    #[test]
    fn test_fcmpe_nan_operand_forces_zero_and_raises_invalid() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.1f64.to_bits());
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 5.0f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fcmpe_negative_epsilon_forces_zero_and_raises_invalid() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, (-1.0f64).to_bits());
        mmix.set_register(2, 5.0f64.to_bits());
        mmix.set_register(3, 6.0f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fune_negative_epsilon_is_exceptional() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, (-1.0f64).to_bits());
        mmix.set_register(2, 5.0f64.to_bits());
        mmix.set_register(3, 5.0f64.to_bits());
        mmix.write_tetra(0, 0x12010203); // FUNE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_I, 0); // FUNE raises nothing
    }

    #[test]
    fn test_fix_y_override_forces_mode_regardless_of_ra() {
        // rA's persistent mode is ROUND_UP (2); Y=1 (ROUND_OFF) must
        // override it: trunc(2.5)=2, not rA's ceil(2.5)=3.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT);
        mmix.set_register(2, 2.5f64.to_bits());
        mmix.write_tetra(0, 0x05010102); // FIX $1,1,$2 (Y=ROUND_OFF)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, 2);
    }

    #[test]
    fn test_fix_two_operand_form_still_honors_ra_mode() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT); // ROUND_UP
        mmix.set_register(2, 2.5f64.to_bits());
        mmix.write_tetra(0, 0x05010002); // FIX $1,0,$2 (Y=0, no override)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, 3); // ceil(2.5) per rA's mode
    }

    #[test]
    fn test_y_greater_than_four_halts_with_diagnostic() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.write_tetra(0, 0x0901050A); // FLOTI $1,5,10 (Y=5, illegal)
        let should_continue = mmix.execute_instruction();
        assert!(!should_continue);
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("FLOTI"));
        assert!(handle.diagnostics()[0].contains("Y=5"));
    }

    #[test]
    fn test_fsqrt_y_greater_than_four_halts_with_diagnostic() {
        // The Y>4 halt is wired at every rounding-mode read site; FLOTI
        // above pins the FLOT/i2f_conv_ri! site, this pins FSQRT's separate
        // finalize_fp_unop site.
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.write_tetra(0, 0x15010502); // FSQRT $1,5,$2 (Y=5, illegal)
        let should_continue = mmix.execute_instruction();
        assert!(!should_continue);
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("FSQRT"));
        assert!(handle.diagnostics()[0].contains("Y=5"));
    }

    #[test]
    fn test_fix_y_two_selects_round_up_not_round_off() {
        // Y=2 (ROUND_UP) must map to rA mode 2, not `Y-1`'s mode 1
        // (ROUND_OFF). rA holds ROUND_OFF already, so the two mappings
        // coincide unless Y's own value (2) is honored: ceil(2.5)=3 under
        // the correct mapping's ROUND_UP, trunc(2.5)=2 under the
        // forbidden Y-1 mapping (indistinguishable from rA's own
        // ROUND_OFF, i.e. Y ignored).
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RA, 1 << RA_ROUND_SHIFT); // ROUND_OFF
        mmix.set_register(2, 2.5f64.to_bits());
        mmix.write_tetra(0, 0x05010202); // FIX $1,2,$2 (Y=ROUND_UP)
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, 3);
    }

    #[test]
    fn test_fcmpe_denormal_radius_pins_exact_constant() {
        // Both operands are denormal (raw exponent field 0), placing the
        // gap strictly between the off-by-one radius 2^-1022*ε and the
        // correct radius 2^-1021*ε — only the correct constant reports 0.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.1f64.to_bits());
        mmix.set_register(2, 1.5e-308f64.to_bits());
        mmix.set_register(3, 1.83e-308f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
    }

    #[test]
    fn test_fcmpe_denormal_radius_pins_exact_constant_upper_side() {
        // The sibling test above pins the -1021 -> -1022 boundary; this
        // pins the other side. The gap sits strictly between the correct
        // radius 2^-1021*ε and the off-by-one radius 2^-1020*ε, so only
        // the correct constant reports non-zero (not close).
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.1f64.to_bits());
        mmix.set_register(2, 1.5e-308f64.to_bits());
        mmix.set_register(3, 2.16752215755216e-308f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1);
    }

    #[test]
    fn test_fcmpe_infinite_neighborhood_epsilon_below_one() {
        // Nε(+∞) = {+∞} only when ε < 1: a finite value is never close to
        // +∞ and the ordinary sign compare applies.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.5f64.to_bits());
        mmix.set_register(2, 5.0f64.to_bits());
        mmix.set_register(3, f64::INFINITY.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1);
    }

    #[test]
    fn test_fcmpe_infinite_neighborhood_epsilon_below_one_opposite_infinities() {
        // Nε(+∞) = {+∞} when ε < 1: the entry condition is `u == v`, exact
        // equality, not `u.is_infinite()` — opposite infinities are each
        // infinite but never equal, so they must compare -1, not 0. A
        // mutant widening the entry test to `u.is_infinite()` would wrongly
        // place -∞ in Nε(+∞) here and report 0.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.5f64.to_bits());
        mmix.set_register(2, f64::NEG_INFINITY.to_bits());
        mmix.set_register(3, f64::INFINITY.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1);
    }

    #[test]
    fn test_fcmpe_infinite_neighborhood_epsilon_one_to_two() {
        // Nε(+∞) = everything except -∞ when 1 ≤ ε < 2: a finite value is
        // close to +∞, but -∞ itself is not — the "except" half, which a
        // mutation collapsing this branch to unconditional "everything"
        // (ε ≥ 2's behavior) would not catch on the finite vector alone.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 1.5f64.to_bits());
        mmix.set_register(2, 5.0f64.to_bits());
        mmix.set_register(3, f64::INFINITY.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);

        let mut opposite = MMix::new();
        opposite.set_special(SpecialReg::RE, 1.5f64.to_bits());
        opposite.set_register(2, f64::NEG_INFINITY.to_bits());
        opposite.set_register(3, f64::INFINITY.to_bits());
        opposite.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(opposite.execute_instruction());
        assert_eq!(opposite.get_register(1) as i64, -1);
    }

    #[test]
    fn test_feqle_stronger_than_fcmpe_asymmetric_binade() {
        // 4.0 sits at the start of a binade twice as wide as 3.99's; the
        // gap fits inside 4.0's radius but not inside 3.99's, so
        // 3.99 ∈ Nε(4.0) while 4.0 ∉ Nε(3.99) — FCMPE's OR is satisfied
        // (∼ holds) but FEQLE's AND (≈) is not. An &&-to-|| mutation in
        // FEQLE's arm would survive without this test.
        let mut fcmpe = MMix::new();
        fcmpe.set_special(SpecialReg::RE, 0.002f64.to_bits());
        fcmpe.set_register(2, 3.99f64.to_bits());
        fcmpe.set_register(3, 4.0f64.to_bits());
        fcmpe.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(fcmpe.execute_instruction());
        assert_eq!(fcmpe.get_register(1), 0);

        let mut feqle = MMix::new();
        feqle.set_special(SpecialReg::RE, 0.002f64.to_bits());
        feqle.set_register(2, 3.99f64.to_bits());
        feqle.set_register(3, 4.0f64.to_bits());
        feqle.write_tetra(0, 0x13010203); // FEQLE $1,$2,$3
        assert!(feqle.execute_instruction());
        assert_eq!(feqle.get_register(1), 0);
    }

    #[test]
    fn test_feqle_nan_operand_forces_zero_and_raises_invalid() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.1f64.to_bits());
        mmix.set_register(2, f64::NAN.to_bits());
        mmix.set_register(3, 5.0f64.to_bits());
        mmix.write_tetra(0, 0x13010203); // FEQLE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fcmpe_reflexive_at_top_binade_zero_epsilon() {
        // f64::MAX's raw exponent field is 2046, the top binade, where
        // `2^(e-1022)` is `2^1024` — unrepresentable, and `0.0 * inf` is
        // NaN. Reflexivity must still hold: a value is always in its own
        // Nε-neighborhood, so FCMPE(v, v) is 0 even with ε = 0.0.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.0f64.to_bits());
        mmix.set_register(2, f64::MAX.to_bits());
        mmix.set_register(3, f64::MAX.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, 0);
    }

    #[test]
    fn test_feqle_reflexive_at_top_binade_zero_epsilon() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.0f64.to_bits());
        mmix.set_register(2, f64::MAX.to_bits());
        mmix.set_register(3, f64::MAX.to_bits());
        mmix.write_tetra(0, 0x13010203); // FEQLE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1);
    }

    #[test]
    fn test_fcmpe_zero_neighborhood_reflexive() {
        // Nε(0) = {0}: zero is always in its own neighborhood, so
        // FCMPE(0.0, 0.0) is 0 for any ε >= 0.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.0f64.to_bits());
        mmix.set_register(2, 0.0f64.to_bits());
        mmix.set_register(3, 0.0f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0);
    }

    #[test]
    fn test_fcmpe_zero_neighborhood_excludes_nonzero() {
        // Nε(0) = {0}, the single point, not "anything within ε of 0" —
        // a nonzero value is never in it, however small, and no ε widens
        // that set.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 0.1f64.to_bits());
        mmix.set_register(2, 0.0f64.to_bits());
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1);
    }

    #[test]
    fn test_fcmpe_top_binade_radius_stays_finite_not_infinite() {
        // Both operands are huge and finite (top binade), but far enough
        // apart that the correct, finite radius (ε * 2^1024, computed
        // without materializing the unrepresentable literal `2^1024`)
        // does not cover the gap — an `inf`-radius implementation would
        // wrongly call this pair close (0) for any ε > 0.
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RE, 1e-300f64.to_bits());
        mmix.set_register(2, (f64::MAX / 2.0).to_bits());
        mmix.set_register(3, f64::MAX.to_bits());
        mmix.write_tetra(0, 0x11010203); // FCMPE $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1);
    }

    #[test]
    fn test_stsf_rounding_default_near() {
        let mut mmix = MMix::new();
        let v: f64 = 1.0f64 + f32::EPSILON as f64 / 2.0; // exactly half-ULP above 1.0 in f32
        mmix.set_register(1, v.to_bits()); // value to store
        mmix.set_register(2, 0x100); // base address
        mmix.set_register(3, 0); // offset
        // STSF $1,$2,$3
        mmix.write_tetra(0, 0xB0010203);
        assert!(mmix.execute_instruction());
        let stored_bits = mmix.read_tetra(0x100);
        let round_trip = f32::from_bits(stored_bits) as f64;
        // Default round-to-nearest-even rounds to 1.0 exactly (1.0 is even).
        assert_eq!(round_trip, 1.0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_stsf_rounding_up_mode() {
        let mut mmix = MMix::new();
        // Pick a value strictly between two adjacent f32 values.
        let v: f64 = 1.0f64 + (f32::EPSILON as f64) * 0.25;
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT); // ROUND_UP
        mmix.set_register(1, v.to_bits());
        mmix.set_register(2, 0x100);
        mmix.set_register(3, 0);
        mmix.write_tetra(0, 0xB0010203);
        assert!(mmix.execute_instruction());
        let stored = f32::from_bits(mmix.read_tetra(0x100));
        // Result must be >= input.
        assert!((stored as f64) >= v, "{} >= {}", stored, v);
        // And strictly above 1.0 since exact value > 1.0.
        assert!(stored > 1.0);
    }

    #[test]
    fn test_stsf_rounding_down_mode() {
        let mut mmix = MMix::new();
        let v: f64 = 1.0f64 + (f32::EPSILON as f64) * 0.25;
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT); // ROUND_DOWN
        mmix.set_register(1, v.to_bits());
        mmix.set_register(2, 0x100);
        mmix.set_register(3, 0);
        mmix.write_tetra(0, 0xB0010203);
        assert!(mmix.execute_instruction());
        let stored = f32::from_bits(mmix.read_tetra(0x100));
        // Result must be <= input.
        assert!((stored as f64) <= v);
        // And exactly 1.0 (largest f32 ≤ v).
        assert_eq!(stored, 1.0);
    }

    #[test]
    fn test_stsf_overflow_to_inf_sets_o() {
        let mut mmix = MMix::new();
        // 1e40 overflows f32.
        mmix.set_register(1, 1e40f64.to_bits());
        mmix.set_register(2, 0x100);
        mmix.set_register(3, 0);
        mmix.write_tetra(0, 0xB0010203);
        assert!(mmix.execute_instruction());
        let stored = f32::from_bits(mmix.read_tetra(0x100));
        assert!(stored.is_infinite() && stored.is_sign_positive());
        assert!((mmix.get_special(SpecialReg::RA) & RA_O) != 0);
    }

    #[test]
    fn test_ieee_remainder_helper() {
        // Direct check of the helper for clarity.
        assert_eq!(MMix::ieee_remainder(7.5, 2.0), -0.5);
        assert_eq!(MMix::ieee_remainder(10.0, 3.0), 1.0);
        assert!(MMix::ieee_remainder(1.0, 0.0).is_nan());
        assert!(MMix::ieee_remainder(f64::INFINITY, 1.0).is_nan());
        assert_eq!(MMix::ieee_remainder(3.0, f64::INFINITY), 3.0);
    }

    // ==================== Assembler integration: FCMPE/FUNE/FEQLE ====================

    #[test]
    fn test_assembler_emits_fcmpe() {
        use crate::encode::encode_instruction_bytes;
        use crate::mmixal::MMixInstruction;
        let bytes = encode_instruction_bytes(&MMixInstruction::FCMPE(1, 2, 3));
        assert_eq!(bytes, vec![0x11, 1, 2, 3]);
    }

    #[test]
    fn test_assembler_emits_fune() {
        use crate::encode::encode_instruction_bytes;
        use crate::mmixal::MMixInstruction;
        let bytes = encode_instruction_bytes(&MMixInstruction::FUNE(1, 2, 3));
        assert_eq!(bytes, vec![0x12, 1, 2, 3]);
    }

    #[test]
    fn test_assembler_emits_feqle() {
        use crate::encode::encode_instruction_bytes;
        use crate::mmixal::MMixInstruction;
        let bytes = encode_instruction_bytes(&MMixInstruction::FEQLE(1, 2, 3));
        assert_eq!(bytes, vec![0x13, 1, 2, 3]);
    }

    // ==================== sNaN handling ====================

    /// IEEE 754 binary64 sNaN: exponent all 1s, mantissa nonzero, bit 51 clear.
    const SNAN_BITS: u64 = 0x7FF0_0000_0000_0001;
    const QNAN_BITS: u64 = 0x7FF8_0000_0000_0001;

    #[test]
    fn test_is_signaling_nan_classifies_correctly() {
        assert!(MMix::is_signaling_nan(f64::from_bits(SNAN_BITS)));
        assert!(!MMix::is_signaling_nan(f64::from_bits(QNAN_BITS)));
        assert!(!MMix::is_signaling_nan(f64::NAN));
        assert!(!MMix::is_signaling_nan(1.0));
        assert!(!MMix::is_signaling_nan(f64::INFINITY));
    }

    #[test]
    fn test_quiet_nan_sets_high_mantissa_bit() {
        let q = MMix::quiet_nan(f64::from_bits(SNAN_BITS));
        assert!(q.is_nan());
        assert_eq!(q.to_bits() & (1 << 51), 1 << 51);
        // Non-NaN passes through unchanged.
        assert_eq!(MMix::quiet_nan(1.5).to_bits(), 1.5f64.to_bits());
    }

    #[test]
    fn test_fadd_snan_raises_i_and_quiets() {
        let mut mmix = MMix::new();
        mmix.set_register(2, SNAN_BITS);
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x04010203); // FADD $1,$2,$3
        assert!(mmix.execute_instruction());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
        let result = mmix.get_register(1);
        // Result must be a NaN, and must be quiet.
        assert!(f64::from_bits(result).is_nan());
        assert_eq!(result & (1 << 51), 1 << 51);
    }

    #[test]
    fn test_fadd_qnan_does_not_raise_i() {
        let mut mmix = MMix::new();
        mmix.set_register(2, QNAN_BITS);
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x04010203);
        assert!(mmix.execute_instruction());
        // qNaN propagation is silent — I must not be raised.
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_I, 0);
        assert!(f64::from_bits(mmix.get_register(1)).is_nan());
    }

    #[test]
    fn test_fmul_snan_raises_i() {
        let mut mmix = MMix::new();
        mmix.set_register(2, 2.0f64.to_bits());
        mmix.set_register(3, SNAN_BITS);
        mmix.write_tetra(0, 0x10010203); // FMUL
        assert!(mmix.execute_instruction());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    #[test]
    fn test_fsqrt_snan_raises_i() {
        let mut mmix = MMix::new();
        mmix.set_register(3, SNAN_BITS);
        mmix.write_tetra(0, 0x15010003); // FSQRT
        assert!(mmix.execute_instruction());
        assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
    }

    // ==================== Directed rounding for FP arithmetic ====================

    /// Build an operand pair whose true sum lies strictly between two adjacent
    /// f64 values: 1.0 + 2^-53. Round-to-nearest-even gives 1.0 (mantissa LSB
    /// of 1.0 is even); ROUND_UP must produce 1.0 + 2^-52.
    fn one_plus_half_ulp() -> (f64, f64) {
        let a = 1.0f64;
        let half_ulp = f64::from_bits(0x3CA0_0000_0000_0000); // 2^-53
        (a, half_ulp)
    }

    #[test]
    fn test_fadd_round_near_default() {
        let mut mmix = MMix::new();
        let (a, b) = one_plus_half_ulp();
        mmix.set_register(2, a.to_bits());
        mmix.set_register(3, b.to_bits());
        mmix.write_tetra(0, 0x04010203);
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 1.0);
        // Inexact must be raised because the sum was rounded.
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_fadd_round_up_bumps_to_next_f64() {
        let mut mmix = MMix::new();
        let (a, b) = one_plus_half_ulp();
        mmix.set_register(2, a.to_bits());
        mmix.set_register(3, b.to_bits());
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT); // ROUND_UP
        mmix.write_tetra(0, 0x04010203);
        assert!(mmix.execute_instruction());
        let r = f64::from_bits(mmix.get_register(1));
        assert!(r > 1.0, "expected r > 1.0, got {}", r);
        assert_eq!(r, 1.0f64.next_up());
    }

    #[test]
    fn test_fadd_round_down_keeps_below() {
        let mut mmix = MMix::new();
        let (a, b) = one_plus_half_ulp();
        mmix.set_register(2, a.to_bits());
        mmix.set_register(3, b.to_bits());
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT); // ROUND_DOWN
        mmix.write_tetra(0, 0x04010203);
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 1.0);
    }

    #[test]
    fn test_fadd_round_off_toward_zero_negative() {
        let mut mmix = MMix::new();
        // -(1 + 2^-53) under round-up should keep -1.0 (less negative).
        // Under ROUND_OFF (toward 0), also -1.0.
        let (a, b) = one_plus_half_ulp();
        mmix.set_register(2, (-a).to_bits());
        mmix.set_register(3, (-b).to_bits());
        mmix.set_special(SpecialReg::RA, 1 << RA_ROUND_SHIFT); // ROUND_OFF
        mmix.write_tetra(0, 0x04010203);
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), -1.0);
    }

    #[test]
    fn test_fmul_directed_rounding() {
        let mut mmix = MMix::new();
        // 1/3 in f64 is inexact; (1/3) * 3 ≠ 1 exactly, gives a nearby f64.
        // The exact product 0.333…·3 = 0.999… so result is just below 1.
        let third = 1.0f64 / 3.0;
        mmix.set_register(2, third.to_bits());
        mmix.set_register(3, 3.0f64.to_bits());
        // Default: round-to-nearest gives 1.0.
        mmix.write_tetra(0, 0x10010203); // FMUL
        assert!(mmix.execute_instruction());
        let near_result = f64::from_bits(mmix.get_register(1));

        // Reset and try ROUND_DOWN (toward -∞): result must be ≤ near_result
        // and strictly less than 1.
        let mut mmix = MMix::new();
        mmix.set_register(2, third.to_bits());
        mmix.set_register(3, 3.0f64.to_bits());
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT);
        mmix.write_tetra(0, 0x10010203);
        assert!(mmix.execute_instruction());
        let down_result = f64::from_bits(mmix.get_register(1));
        assert!(down_result < 1.0, "ROUND_DOWN gave {}", down_result);
        assert!(down_result <= near_result);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_fdiv_directed_rounding() {
        let mut mmix = MMix::new();
        // 1.0 / 3.0 is inexact. Default → nearest. ROUND_UP must give a value
        // strictly greater than the nearest result.
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 3.0f64.to_bits());
        mmix.write_tetra(0, 0x14010203); // FDIV
        assert!(mmix.execute_instruction());
        let near = f64::from_bits(mmix.get_register(1));

        let mut mmix = MMix::new();
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 3.0f64.to_bits());
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT); // ROUND_UP
        mmix.write_tetra(0, 0x14010203);
        assert!(mmix.execute_instruction());
        let up = f64::from_bits(mmix.get_register(1));
        assert!(up > near, "ROUND_UP={} should exceed nearest={}", up, near);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_fdiv_directed_rounding_negative_divisor() {
        let mut mmix = MMix::new();
        // 1.0 / -3.0 — verify sign-of-divisor handling in residual.
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, (-3.0f64).to_bits());
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT); // ROUND_DOWN
        mmix.write_tetra(0, 0x14010203);
        assert!(mmix.execute_instruction());
        let r = f64::from_bits(mmix.get_register(1));
        // True 1/-3 ≈ -0.333…; ROUND_DOWN must give a value ≤ true (more negative).
        assert!(r < -0.333, "ROUND_DOWN of 1/-3 was {}", r);
    }

    #[test]
    fn test_fsqrt_directed_rounding() {
        let mut mmix = MMix::new();
        // sqrt(2) is irrational. ROUND_UP and ROUND_DOWN must straddle the
        // nearest result.
        mmix.set_register(3, 2.0f64.to_bits());
        mmix.write_tetra(0, 0x15010003); // FSQRT
        assert!(mmix.execute_instruction());
        let near = f64::from_bits(mmix.get_register(1));

        let mut mmix = MMix::new();
        mmix.set_register(3, 2.0f64.to_bits());
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT); // UP
        mmix.write_tetra(0, 0x15010003);
        assert!(mmix.execute_instruction());
        let up = f64::from_bits(mmix.get_register(1));

        let mut mmix = MMix::new();
        mmix.set_register(3, 2.0f64.to_bits());
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT); // DOWN
        mmix.write_tetra(0, 0x15010003);
        assert!(mmix.execute_instruction());
        let down = f64::from_bits(mmix.get_register(1));

        assert!(down <= near && near <= up);
        assert!(down < up);
    }

    // ==================== Inexact (X) flag for arithmetic ====================

    #[test]
    fn test_fadd_exact_no_x_flag() {
        let mut mmix = MMix::new();
        // 1.0 + 2.0 is exact; X must not be raised.
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 2.0f64.to_bits());
        mmix.write_tetra(0, 0x04010203);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_X, 0);
    }

    #[test]
    fn test_fmul_exact_no_x_flag() {
        let mut mmix = MMix::new();
        // 1.5 × 4.0 = 6.0 exactly.
        mmix.set_register(2, 1.5f64.to_bits());
        mmix.set_register(3, 4.0f64.to_bits());
        mmix.write_tetra(0, 0x10010203);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_X, 0);
    }

    #[test]
    fn test_fdiv_exact_no_x_flag() {
        let mut mmix = MMix::new();
        // 12.0 / 4.0 = 3.0 exactly.
        mmix.set_register(2, 12.0f64.to_bits());
        mmix.set_register(3, 4.0f64.to_bits());
        mmix.write_tetra(0, 0x14010203);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_X, 0);
    }

    // ============== Subnormal operands and results ==============

    #[test]
    fn test_subnormal_operand_raises_no_divide_check() {
        let mut mmix = MMix::new();
        // MMIX has no denormalized-operand event; D is the integer divide check.
        mmix.set_register(2, f64::MIN_POSITIVE.to_bits() >> 4); // subnormal
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x04010203); // FADD
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_D, 0);
    }

    #[test]
    fn test_subnormal_result_raises_underflow() {
        let mut mmix = MMix::new();
        // MIN_POSITIVE / 2.0 underflows to a subnormal; U reports it.
        mmix.set_register(2, f64::MIN_POSITIVE.to_bits());
        mmix.set_register(3, 2.0f64.to_bits());
        mmix.write_tetra(0, 0x14010203); // FDIV
        assert!(mmix.execute_instruction());
        let ra = mmix.get_special(SpecialReg::RA);
        let r = f64::from_bits(mmix.get_register(1));
        assert!(r.is_subnormal(), "expected subnormal result, got {}", r);
        assert!((ra & RA_U) != 0, "U should be set on underflow");
    }

    #[test]
    fn test_subnormal_plus_zero_raises_no_underflow() {
        let mut mmix = MMix::new();
        // A subnormal result that merely reproduces a subnormal operand lost
        // nothing; the nonzero-operand guard keeps U off it.
        mmix.set_register(2, 1u64); // smallest positive subnormal
        mmix.set_register(3, 0.0f64.to_bits());
        mmix.write_tetra(0, 0x04010203); // FADD
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 1u64);
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_U, 0);
    }

    #[test]
    fn test_exact_cancellation_fadd_raises_no_underflow() {
        let mut mmix = MMix::new();
        // 1.0 + -1.0 is exactly zero: nothing was too small to represent.
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, (-1.0f64).to_bits());
        mmix.write_tetra(0, 0x04010203); // FADD
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 0.0);
        assert_eq!(
            mmix.get_special(SpecialReg::RA) & RA_U,
            0,
            "exact cancellation is not an underflow"
        );
    }

    #[test]
    fn test_exact_cancellation_fsub_raises_no_underflow() {
        let mut mmix = MMix::new();
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, 1.0f64.to_bits());
        mmix.write_tetra(0, 0x06010203); // FSUB
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 0.0);
        assert_eq!(
            mmix.get_special(SpecialReg::RA) & RA_U,
            0,
            "exact cancellation is not an underflow"
        );
    }

    #[test]
    fn test_frem_exact_zero_raises_no_underflow() {
        let mut mmix = MMix::new();
        // The IEEE remainder is exact by definition, so FREM cannot underflow.
        mmix.set_register(2, (-3.0f64).to_bits());
        mmix.set_register(3, 1.5f64.to_bits());
        mmix.write_tetra(0, 0x16010203); // FREM
        assert!(mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RA) & RA_U,
            0,
            "an exact remainder is not an underflow"
        );
    }

    #[test]
    fn test_fdiv_to_zero_raises_underflow() {
        let mut mmix = MMix::new();
        // The true quotient is nonzero but far below the subnormal range.
        mmix.set_register(2, f64::MIN_POSITIVE.to_bits());
        mmix.set_register(3, 1e16f64.to_bits());
        mmix.write_tetra(0, 0x14010203); // FDIV
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 0.0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_U) != 0);
    }

    #[test]
    fn test_fmul_to_zero_raises_underflow() {
        let mut mmix = MMix::new();
        // MIN_POSITIVE^2 is 2^-2044: nonzero, and below the subnormal range.
        // The FMA residual rounds to zero here, so it cannot witness the
        // underflow — only the operands can.
        mmix.set_register(2, f64::MIN_POSITIVE.to_bits());
        mmix.set_register(3, f64::MIN_POSITIVE.to_bits());
        mmix.write_tetra(0, 0x10010203); // FMUL
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 0.0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_U) != 0);
    }

    #[test]
    fn test_fdiv_by_infinity_is_exact_zero() {
        let mut mmix = MMix::new();
        // finite / inf is exactly +0.0: neither inexact nor an underflow. The
        // residual is NaN here, so an unguarded `err != 0.0` would raise X.
        mmix.set_register(2, 1.0f64.to_bits());
        mmix.set_register(3, f64::INFINITY.to_bits());
        mmix.write_tetra(0, 0x14010203); // FDIV
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0.0f64.to_bits());
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
    }

    // ==================== FREM / FIXU / FCMP / conversions ====================

    #[test]
    fn test_frem_zero_takes_dividend_sign() {
        let mut mmix = MMix::new();
        // IEEE 754 gives a zero remainder the sign of the dividend; the
        // divisor's sign does not enter. Compare bit patterns — -0.0 == 0.0.
        mmix.set_register(2, (-3.0f64).to_bits());
        mmix.set_register(3, 1.5f64.to_bits());
        mmix.write_tetra(0, 0x16010203); // FREM $1,$2,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), (-0.0f64).to_bits());

        let mut mmix = MMix::new();
        mmix.set_register(2, 3.0f64.to_bits());
        mmix.set_register(3, (-1.5f64).to_bits());
        mmix.write_tetra(0, 0x16010203);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1), 0.0f64.to_bits());
    }

    #[test]
    fn test_fixu_wraps_mod_two_to_the_64() {
        // u($X) <- int(f($Z)) mod 2^64. A value whose ulp reaches 2^64
        // therefore yields zero rather than saturating.
        let cases: [(f64, u64); 10] = [
            (-1.0, 0xFFFF_FFFF_FFFF_FFFF),
            (-0.5, 0), // rounds to -0.0 under NEAR
            (3.7, 4),
            (9223372036854775808.0, 0x8000_0000_0000_0000), // 2^63
            (-9223372036854775808.0, 0x8000_0000_0000_0000), // -2^63
            (18446744073709551616.0, 0),                    // 2^64
            (1e300, 0),
            (18446744073709549568.0, 0xFFFF_FFFF_FFFF_F800),
            // The exponent at which every low bit has shifted out. An odd
            // significand distinguishes the two sides: at 2^115 the value is
            // 2^115 + 2^63, whose low octabyte is 2^63; one exponent higher
            // every surviving bit sits above the octabyte.
            (
                f64::from_bits(((115 + 1023) << 52) | 1),
                0x8000_0000_0000_0000,
            ),
            (f64::from_bits(((116 + 1023) << 52) | 1), 0),
        ];
        for (operand, expected) in cases {
            let mut mmix = MMix::new();
            mmix.set_register(3, operand.to_bits());
            mmix.write_tetra(0, 0x07010003); // FIXU $1,$0,$3
            assert!(mmix.execute_instruction());
            assert_eq!(
                mmix.get_register(1),
                expected,
                "FIXU {operand} should be {expected:#X}"
            );
        }
    }

    #[test]
    fn test_fix_negative_is_still_signed() {
        let mut mmix = MMix::new();
        // FIX keeps its signed conversion; only FIXU wraps.
        mmix.set_register(3, (-1.0f64).to_bits());
        mmix.write_tetra(0, 0x05010003); // FIX $1,$0,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(1) as i64, -1);
    }

    #[test]
    fn test_fcmp_nan_answers_zero_in_either_position() {
        for (y, z) in [(f64::NAN, 1.0f64), (1.0f64, f64::NAN), (f64::NAN, f64::NAN)] {
            let mut mmix = MMix::new();
            mmix.set_register(2, y.to_bits());
            mmix.set_register(3, z.to_bits());
            mmix.write_tetra(0, 0x01010203); // FCMP $1,$2,$3
            assert!(mmix.execute_instruction());
            assert_eq!(mmix.get_register(1), 0, "FCMP {y},{z}");
            assert!((mmix.get_special(SpecialReg::RA) & RA_I) != 0);
        }
    }

    #[test]
    fn test_fcmp_ordered_still_three_way() {
        for (y, z, expected) in [(1.0f64, 2.0f64, -1i64), (2.0, 2.0, 0), (3.0, 2.0, 1)] {
            let mut mmix = MMix::new();
            mmix.set_register(2, y.to_bits());
            mmix.set_register(3, z.to_bits());
            mmix.write_tetra(0, 0x01010203); // FCMP $1,$2,$3
            assert!(mmix.execute_instruction());
            assert_eq!(mmix.get_register(1) as i64, expected, "FCMP {y},{z}");
            assert_eq!(mmix.get_special(SpecialReg::RA) & RA_I, 0);
        }
    }

    #[test]
    fn test_flot_inexact_conversion_raises_x() {
        let mut mmix = MMix::new();
        // 2^53+1 has no f64 image; it rounds to 2^53 and X reports the loss.
        mmix.set_register(3, (1u64 << 53) + 1);
        mmix.write_tetra(0, 0x08010003); // FLOT $1,$0,$3
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 9007199254740992.0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_flot_exact_conversion_raises_nothing() {
        let mut mmix = MMix::new();
        mmix.set_register(3, 42);
        mmix.write_tetra(0, 0x08010003); // FLOT $1,$0,$3
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 42.0);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
    }

    #[test]
    fn test_flot_honors_directed_rounding_mode() {
        let mut up = MMix::new();
        up.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT); // ROUND_UP
        up.set_register(3, (1u64 << 53) + 1);
        up.write_tetra(0, 0x08010003); // FLOT $1,$0,$3
        assert!(up.execute_instruction());
        let up_result = f64::from_bits(up.get_register(1));

        let mut down = MMix::new();
        down.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT); // ROUND_DOWN
        down.set_register(3, (1u64 << 53) + 1);
        down.write_tetra(0, 0x08010003);
        assert!(down.execute_instruction());
        let down_result = f64::from_bits(down.get_register(1));

        assert_eq!(down_result, 9007199254740992.0);
        assert_eq!(up_result, 9007199254740994.0);
        assert!(up_result > down_result);

        // The negative arm negates both the magnitude and the residual, so a
        // directed mode must still round toward its own infinity.
        let mut neg_up = MMix::new();
        neg_up.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT); // ROUND_UP
        neg_up.set_register(3, (-((1i64 << 53) + 1)) as u64);
        neg_up.write_tetra(0, 0x08010003);
        assert!(neg_up.execute_instruction());
        assert_eq!(f64::from_bits(neg_up.get_register(1)), -9007199254740992.0);

        let mut neg_down = MMix::new();
        neg_down.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT); // ROUND_DOWN
        neg_down.set_register(3, (-((1i64 << 53) + 1)) as u64);
        neg_down.write_tetra(0, 0x08010003);
        assert!(neg_down.execute_instruction());
        assert_eq!(
            f64::from_bits(neg_down.get_register(1)),
            -9007199254740994.0
        );
    }

    #[test]
    fn test_flotu_max_raises_x() {
        let mut mmix = MMix::new();
        // u64::MAX rounds up to 2^64, losing eleven bits. Recovering the
        // residual by casting back saturates to u64::MAX and reports zero, so
        // this vector is the one that catches that mistake.
        mmix.set_register(3, u64::MAX);
        mmix.write_tetra(0, 0x0A010003); // FLOTU $1,$0,$3
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 18446744073709551616.0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    #[test]
    fn test_sflotu_inexact_wide_step_raises_x() {
        let mut mmix = MMix::new();
        // 2^53+1 rounds to 2^53 on the way to f64; 2^53 then narrows to f32
        // exactly, so only the integer-to-f64 step can raise X here.
        mmix.set_register(3, (1u64 << 53) + 1);
        mmix.write_tetra(0, 0x0E010003); // SFLOTU $1,$0,$3
        assert!(mmix.execute_instruction());
        assert_eq!(f64::from_bits(mmix.get_register(1)), 9007199254740992.0);
        assert!((mmix.get_special(SpecialReg::RA) & RA_X) != 0);
    }

    // ==================== Overflow with directed rounding ====================

    #[test]
    fn test_overflow_round_off_clamps_to_max() {
        let mut mmix = MMix::new();
        mmix.set_register(2, f64::MAX.to_bits());
        mmix.set_register(3, f64::MAX.to_bits());
        mmix.set_special(SpecialReg::RA, 1 << RA_ROUND_SHIFT); // ROUND_OFF (toward 0)
        mmix.write_tetra(0, 0x04010203); // FADD
        assert!(mmix.execute_instruction());
        let r = f64::from_bits(mmix.get_register(1));
        assert_eq!(r, f64::MAX);
        assert!((mmix.get_special(SpecialReg::RA) & RA_O) != 0);
    }

    #[test]
    fn test_overflow_round_down_negative_keeps_neg_inf() {
        let mut mmix = MMix::new();
        mmix.set_register(2, f64::MIN.to_bits()); // most-negative finite
        mmix.set_register(3, f64::MIN.to_bits());
        mmix.set_special(SpecialReg::RA, 3 << RA_ROUND_SHIFT); // ROUND_DOWN (toward -∞)
        mmix.write_tetra(0, 0x04010203);
        assert!(mmix.execute_instruction());
        let r = f64::from_bits(mmix.get_register(1));
        assert!(r.is_infinite() && r.is_sign_negative());
    }

    /// `JMP 0,0,0` at address `addr`: offset 0 branches back to itself,
    /// forever. Shared by every never-halts test below.
    fn write_infinite_loop(mmix: &mut MMix, addr: u64) {
        mmix.write_tetra(addr, 0xF0000000);
    }

    #[test]
    fn run_bounded_halts_normally_and_reports_the_count() {
        let mut mmix = MMix::new();
        mmix.write_tetra(0, 0xE7010000); // INCL $1, YZ=0
        mmix.write_tetra(4, 0xE7010203); // INCL $1, YZ=0x0203
        mmix.write_tetra(8, 0xE7010203); // INCL $1, YZ=0x0203
        mmix.write_tetra(12, 0xFF000000); // TRIP (halt)

        let (count, stop) = mmix.run_bounded(100);
        assert_eq!(count, 3);
        assert_eq!(stop, Stop::Halted);
    }

    #[test]
    fn run_bounded_stops_at_the_budget_on_a_program_that_never_halts() {
        let mut mmix = MMix::new();
        write_infinite_loop(&mut mmix, 0);

        let (count, stop) = mmix.run_bounded(1_000);
        assert_eq!(count, 1_000);
        assert_eq!(stop, Stop::BudgetExhausted);
    }

    #[test]
    fn occupied_yields_nonzero_bytes_ascending_after_a_zero_write() {
        // Six surviving addresses written out of ascending order: with only two
        // survivors, HashMap iteration lands in ascending order by chance often
        // enough that deleting the sort in `occupied` doesn't reliably fail this
        // test. Six addresses drops that accidental-pass rate to roughly 1/720.
        let mut mmix = MMix::new();
        mmix.write_byte(500, 5);
        mmix.write_byte(100, 1);
        mmix.write_byte(700, 7);
        mmix.write_byte(300, 3);
        mmix.write_byte(900, 9);
        mmix.write_byte(400, 4);
        mmix.write_byte(200, 6);
        mmix.write_byte(200, 0); // zero-write: removed, must not appear

        let items: Vec<(u64, u8)> = mmix.occupied().collect();
        assert_eq!(
            items,
            vec![(100, 1), (300, 3), (400, 4), (500, 5), (700, 7), (900, 9)]
        );
    }

    #[test]
    fn loaded_extent_includes_the_hello_world_nul_terminator_that_occupied_omits() {
        // Reproduces examples/hello_world.mms's Text BYTE directive: its
        // trailing NUL is a real loaded byte that write_byte's zero-removal
        // hides from `occupied`, checked by address rather than by a total
        // count (write_image also writes every instruction, so the totals
        // include far more than this one directive).
        use crate::debugger::write_image;
        use crate::mmixal::MMixAssembler;

        const HELLO_WORLD: &str = "\
\tLOC\tData_Segment
\tGREG\t@
Text\tBYTE\t\"Hello world!\",'\\n',0

\tLOC\t#100

Main\tLDA\t$255,Text
\tTRAP\t0,Fputs,StdOut
\tTRAP\t0,Halt,0
";
        let mut asm = MMixAssembler::new(HELLO_WORLD, "hello_world.mms");
        asm.parse().expect("hello_world.mms must assemble");
        let text_addr = *asm.labels.get("Text").expect("Text label");
        // "Hello world!",'\n',0 is 14 bytes; the NUL terminator is the last.
        let nul_addr = text_addr + 13;

        let mut mmix = MMix::new();
        write_image(&mut mmix, &asm);

        let loaded: Vec<(u64, u8)> = mmix.loaded_extent().collect();
        assert!(loaded.contains(&(nul_addr, 0)));

        let occupied: Vec<(u64, u8)> = mmix.occupied().collect();
        assert!(!occupied.iter().any(|&(addr, _)| addr == nul_addr));
    }

    #[test]
    fn loaded_extent_is_unchanged_by_runtime_writes_during_execution() {
        // Mirrors debugger.rs's CALL_PROGRAM fixture: PUSHJ spills the
        // caller's frame to the register stack (addresses at
        // 0x6000000000000000+), a real runtime write that goes through
        // `write_byte`, not `write_loaded_byte`. `loaded_extent` tracks only
        // what `write_image` loaded, so a run must leave it unchanged.
        use crate::debugger::{entry_point, write_image};
        use crate::mmixal::MMixAssembler;

        const CALL_PROGRAM: &str = "\
\tLOC\t#100
Main\tPUSHJ\t$0,Sub
\tSETI\t$1,7
\tTRAP\t0,Halt,0
Sub\tSETI\t$0,3
\tPOP\t0,0
";
        let mut asm = MMixAssembler::new(CALL_PROGRAM, "call.mms");
        asm.parse().expect("call.mms must assemble");

        let mut mmix = MMix::new();
        write_image(&mut mmix, &asm);
        let before: Vec<(u64, u8)> = mmix.loaded_extent().collect();
        assert!(!before.is_empty(), "write_image must have loaded something");

        mmix.set_pc(entry_point(&asm));
        mmix.run(); // PUSHJ spills a frame; POP restores it; TRAP halts.

        let after: Vec<(u64, u8)> = mmix.loaded_extent().collect();
        assert_eq!(
            before, after,
            "a runtime write (PUSHJ's register-stack spill) must not appear \
             in loaded_extent"
        );
    }

    #[test]
    fn journal_records_writes_only_while_enabled_including_a_zero_write() {
        let mut mmix = MMix::new();
        mmix.write_byte(10, 1); // before enabling: not recorded

        mmix.set_journal(true);
        mmix.write_byte(20, 2);
        // A zero-write to a fresh address (never written before) is still a
        // recorded state change, distinct from the nonzero write above.
        mmix.write_byte(25, 0);
        mmix.write_byte(30, 3);
        mmix.set_journal(false);
        mmix.write_byte(40, 4); // journal off again: not recorded

        assert_eq!(mmix.take_journal(), vec![20, 25, 30]);
        // Drained: the next call is empty without another write.
        assert!(mmix.take_journal().is_empty());
    }

    #[test]
    fn journal_enabled_flag_survives_reset_but_the_buffer_does_not() {
        let mut mmix = MMix::new();
        mmix.set_journal(true);
        mmix.write_byte(50, 7);
        assert_eq!(mmix.take_journal(), vec![50]);

        mmix.reset();
        assert!(mmix.take_journal().is_empty());

        // The flag itself survived the reset.
        mmix.write_byte(60, 8);
        assert_eq!(mmix.take_journal(), vec![60]);
    }

    #[test]
    fn run_bounded_halted_diagnostic_matches_runs_pre_existing_text() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.write_tetra(0, 0xFF000000); // TRIP (halt)

        let (count, stop) = mmix.run_bounded(100);
        assert_eq!(stop, Stop::Halted);
        // TRIP itself emits its own diagnostic first; run_bounded's is last.
        assert_eq!(
            handle.diagnostics().last(),
            Some(&format!(
                "Execution stopped at PC={:#018x} after {} instructions",
                mmix.get_pc(),
                count
            ))
        );
    }

    #[test]
    fn run_bounded_exhausted_diagnostic_is_visibly_different() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        write_infinite_loop(&mut mmix, 0);

        let (count, stop) = mmix.run_bounded(1_000);
        assert_eq!(stop, Stop::BudgetExhausted);
        assert_eq!(
            handle.diagnostics().last(),
            Some(&format!(
                "Execution paused at PC={:#018x} after {} instructions (budget exhausted)",
                mmix.get_pc(),
                count
            ))
        );
    }

    /// The dump labels each slot with the name of the register that slot
    /// holds, so a value never appears under a neighbour's name.
    #[test]
    fn display_labels_each_special_register_with_its_own_name() {
        let mut mmix = MMix::new();
        let expected = [
            (SpecialReg::RN, "rN", 0x1111_u64),
            (SpecialReg::RO, "rO", 0x2222),
            (SpecialReg::RG, "rG", 0x3333),
            (SpecialReg::RL, "rL", 0x4444),
        ];
        for (reg, _, value) in expected {
            mmix.set_special(reg, value);
        }

        let dump = mmix.to_string();
        for (_, name, value) in expected {
            let line = format!("{:<4} = {:#018x}", name, value);
            assert!(
                dump.contains(&line),
                "expected `{line}` in the dump, got:\n{dump}"
            );
        }
    }
    // ============== rA layout and the integer events ==============

    #[test]
    fn test_ra_bits_match_knuth_predefs() {
        // The predefined symbols: D_BIT=#80 V_BIT=#40 W_BIT=#20 I_BIT=#10
        //                         O_BIT=#08 U_BIT=#04 Z_BIT=#02 X_BIT=#01
        assert_eq!(RA_D, 0x80);
        assert_eq!(RA_V, 0x40);
        assert_eq!(RA_W, 0x20);
        assert_eq!(RA_I, 0x10);
        assert_eq!(RA_O, 0x08);
        assert_eq!(RA_U, 0x04);
        assert_eq!(RA_Z, 0x02);
        assert_eq!(RA_X, 0x01);
        assert_eq!(RA_ROUND_SHIFT, 16);
        assert_eq!(RA_MAX, 0x3FFFF);
    }

    /// Run the signed division `word` encodes over $1 and the divisor,
    /// returning quotient, remainder and rA. The register form reads the
    /// divisor from $2, the immediate form from the instruction's Z field.
    fn run_signed_div(word: u32, dividend: i64, divisor: i64) -> (i64, i64, u64) {
        let mut mmix = MMix::new();
        mmix.set_register(1, dividend as u64);
        mmix.set_register(2, divisor as u64);
        mmix.write_tetra(0, word);
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_pc(), 4, "division must advance the PC");
        (
            mmix.get_register(3) as i64,
            mmix.get_special(SpecialReg::RR) as i64,
            mmix.get_special(SpecialReg::RA),
        )
    }

    /// Run `DIV $3,$1,$2` on the given operands.
    fn run_div(dividend: i64, divisor: i64) -> (i64, i64, u64) {
        run_signed_div(0x1C030102, dividend, divisor)
    }

    /// Run `DIVI $3,$1,Z`; Z is a byte, so the divisor is in `0..=255`.
    fn run_divi(dividend: i64, divisor: u8) -> (i64, i64, u64) {
        run_signed_div(0x1D030100 | divisor as u32, dividend, 0)
    }

    #[test]
    fn test_div_floors_toward_negative_infinity() {
        // Truncation would give (-3, -1), (-3, 1) and (3, 1).
        assert_eq!(run_div(-7, 2), (-4, 1, 0));
        assert_eq!(run_div(7, -2), (-4, -1, 0));
        assert_eq!(run_div(-7, -2), (3, -1, 0));
        // Exact division is unaffected by the floor adjustment.
        assert_eq!(run_div(-8, 2), (-4, 0, 0));
        assert_eq!(run_div(7, 2), (3, 1, 0));
    }

    #[test]
    fn test_div_min_by_minus_one_wraps_and_raises_v() {
        let (quotient, remainder, ra) = run_div(i64::MIN, -1);
        assert_eq!(quotient as u64, 0x8000000000000000);
        assert_eq!(remainder, 0);
        assert_eq!(ra & RA_V, RA_V);
    }

    #[test]
    fn test_divi_floors_toward_negative_infinity() {
        // Only positive divisors are encodable; truncation would give (-3, -1),
        // (-2, -1) and (3, 1).
        assert_eq!(run_divi(-7, 2), (-4, 1, 0));
        assert_eq!(run_divi(-7, 3), (-3, 2, 0));
        // Exact division is unaffected by the floor adjustment.
        assert_eq!(run_divi(-8, 2), (-4, 0, 0));
        assert_eq!(run_divi(7, 2), (3, 1, 0));
    }

    #[test]
    fn test_divi_by_zero_raises_divide_check() {
        let (quotient, remainder, ra) = run_divi(42, 0);
        assert_eq!(quotient, 0);
        assert_eq!(remainder, 42);
        assert_eq!(ra & RA_D, RA_D, "D is the integer divide check");
        assert_eq!(ra & RA_V, 0, "divide by zero is not an overflow");
    }

    #[test]
    fn test_signed_divide_by_zero_raises_divide_check() {
        let mut mmix = MMix::new();
        mmix.set_register(1, 42);
        mmix.set_register(2, 0);
        mmix.write_tetra(0, 0x1C030102); // DIV $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
        assert_eq!(mmix.get_special(SpecialReg::RR), 42);
        let ra = mmix.get_special(SpecialReg::RA);
        assert_eq!(ra & RA_D, RA_D, "D is the integer divide check");
        assert_eq!(ra & RA_V, 0, "divide by zero is not an overflow");
    }

    #[test]
    fn test_divu_uses_rd_when_divisor_is_not_greater() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RD, 5);
        mmix.set_register(1, 0x1234);
        mmix.set_register(2, 3);
        mmix.write_tetra(0, 0x1E030102); // DIVU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 5);
        assert_eq!(mmix.get_special(SpecialReg::RR), 0x1234);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
    }

    #[test]
    fn test_divu_by_zero_is_the_rd_rule_and_raises_nothing() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RD, 7);
        mmix.set_register(1, 0xABCD);
        mmix.set_register(2, 0);
        mmix.write_tetra(0, 0x1E030102); // DIVU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 7);
        assert_eq!(mmix.get_special(SpecialReg::RR), 0xABCD);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0, "DIVU has no D");
    }

    #[test]
    fn test_divu_divides_the_full_128_bit_dividend() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RD, 1);
        mmix.set_register(1, 0);
        mmix.set_register(2, 2);
        mmix.write_tetra(0, 0x1E030102); // DIVU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x8000000000000000); // 2^64 / 2
        assert_eq!(mmix.get_special(SpecialReg::RR), 0);
    }

    #[test]
    fn test_divui_uses_rd_when_divisor_is_not_greater() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RD, 5);
        mmix.set_register(1, 0x1234);
        mmix.write_tetra(0, 0x1F030103); // DIVUI $3,$1,3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 5);
        assert_eq!(mmix.get_special(SpecialReg::RR), 0x1234);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
    }

    #[test]
    fn test_divui_by_zero_is_the_rd_rule_and_raises_nothing() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RD, 7);
        mmix.set_register(1, 0xABCD);
        mmix.write_tetra(0, 0x1F030100); // DIVUI $3,$1,0
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 7);
        assert_eq!(mmix.get_special(SpecialReg::RR), 0xABCD);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0, "DIVUI has no D");
    }

    #[test]
    fn test_divui_divides_the_full_128_bit_dividend() {
        let mut mmix = MMix::new();
        mmix.set_special(SpecialReg::RD, 1);
        mmix.set_register(1, 0);
        mmix.write_tetra(0, 0x1F030102); // DIVUI $3,$1,2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x8000000000000000); // 2^64 / 2
        assert_eq!(mmix.get_special(SpecialReg::RR), 0);
    }

    #[test]
    fn test_mul_leaves_rh_to_mulu() {
        let mut mmix = MMix::new();
        mmix.set_register(1, 1 << 32);
        mmix.set_register(2, 1 << 32);
        mmix.write_tetra(0, 0x1A030102); // MULU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0);
        assert_eq!(mmix.get_special(SpecialReg::RH), 1);

        mmix.set_register(5, 6);
        mmix.set_register(6, 7);
        mmix.write_tetra(4, 0x18040506); // MUL $4,$5,$6
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(4), 42);
        assert_eq!(mmix.get_special(SpecialReg::RH), 1, "rH is MULU's output");
    }

    #[test]
    fn test_mul_overflow_raises_v() {
        let mut mmix = MMix::new();
        mmix.set_register(1, i64::MAX as u64);
        mmix.set_register(2, 2);
        mmix.write_tetra(0, 0x18030102); // MUL $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RA) & RA_V, RA_V);
        assert_eq!(mmix.get_special(SpecialReg::RH), 0);
    }

    #[test]
    fn test_add_overflow_raises_v_not_u() {
        let mut mmix = MMix::new();
        mmix.set_register(1, i64::MAX as u64);
        mmix.set_register(2, 1);
        mmix.write_tetra(0, 0x20030102); // ADD $3,$1,$2
        assert!(mmix.execute_instruction());
        let ra = mmix.get_special(SpecialReg::RA);
        assert_eq!(ra & RA_V, RA_V, "integer overflow is V");
        assert_eq!(ra & RA_U, 0, "U is floating underflow");
    }

    /// Run the signed left shift `word` encodes over $1, returning the result
    /// and rA. The register form reads the count from $2, the immediate form
    /// from the instruction's Z field.
    fn run_shift_left(word: u32, value: u64, shift: u64) -> (u64, u64) {
        let mut mmix = MMix::new();
        mmix.set_register(1, value);
        mmix.set_register(2, shift);
        mmix.write_tetra(0, word);
        assert!(mmix.execute_instruction());
        (mmix.get_register(3), mmix.get_special(SpecialReg::RA))
    }

    /// Run `SL $3,$1,$2`.
    fn run_sl(value: u64, shift: u64) -> (u64, u64) {
        run_shift_left(0x38030102, value, shift)
    }

    /// Run `SLI $3,$1,Z`.
    fn run_sli(value: u64, shift: u8) -> (u64, u64) {
        run_shift_left(0x39030100 | shift as u32, value, 0)
    }

    #[test]
    fn test_sl_overflows_when_the_product_leaves_the_signed_range() {
        // A set bit leaves the top: 2^62 · 4 = 2^64.
        let (result, ra) = run_sl(1 << 62, 2);
        assert_eq!(result, 0);
        assert_eq!(ra & RA_V, RA_V);

        // Nothing is shifted out, yet 2^62 · 2 = 2^63 exceeds the signed range.
        let (result, ra) = run_sl(0x4000000000000000, 1);
        assert_eq!(result, 0x8000000000000000);
        assert_eq!(ra & RA_V, RA_V, "the sign flip is an overflow");

        // 2^60 · 4 = 2^62 fits, so nothing is raised.
        let (result, ra) = run_sl(1 << 60, 2);
        assert_eq!(result, 1 << 62);
        assert_eq!(ra, 0, "a representable product raises nothing");

        // -1 · 2^63 = -2^63 is the most negative octabyte, and fits.
        let (result, ra) = run_sl(u64::MAX, 63);
        assert_eq!(result, 0x8000000000000000);
        assert_eq!(ra, 0);
    }

    #[test]
    fn test_sli_overflows_when_the_product_leaves_the_signed_range() {
        // A set bit leaves the top: 2^62 · 4 = 2^64.
        let (result, ra) = run_sli(1 << 62, 2);
        assert_eq!(result, 0);
        assert_eq!(ra & RA_V, RA_V);

        // Nothing is shifted out, yet 2^62 · 2 = 2^63 exceeds the signed range.
        let (result, ra) = run_sli(0x4000000000000000, 1);
        assert_eq!(result, 0x8000000000000000);
        assert_eq!(ra & RA_V, RA_V, "the sign flip is an overflow");

        // 2^60 · 4 = 2^62 fits, so nothing is raised.
        let (result, ra) = run_sli(1 << 60, 2);
        assert_eq!(result, 1 << 62);
        assert_eq!(ra, 0, "a representable product raises nothing");

        // A shift of zero is the identity, whatever the sign bits hold.
        let (result, ra) = run_sli(0x8000000000000000, 0);
        assert_eq!(result, 0x8000000000000000);
        assert_eq!(ra, 0);
    }

    #[test]
    fn test_slu_never_overflows() {
        let mut mmix = MMix::new();
        mmix.set_register(1, 0x4000000000000000);
        mmix.set_register(2, 1);
        mmix.write_tetra(0, 0x3A030102); // SLU $3,$1,$2
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x8000000000000000);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
    }

    #[test]
    fn test_neg_overflow_raises_v() {
        // NEG $3,Y,$1 computes Y - s($1); every such overflow reports V.
        for y in [0u32, 5, 255] {
            let mut mmix = MMix::new();
            mmix.set_register(1, i64::MIN as u64);
            mmix.write_tetra(0, 0x34030001 | (y << 8)); // NEG $3,y,$1
            assert!(mmix.execute_instruction());
            assert_eq!(
                mmix.get_special(SpecialReg::RA) & RA_V,
                RA_V,
                "NEG $3,{y},$1 overflows"
            );
            assert_eq!(
                mmix.get_register(3),
                (y as i64).wrapping_sub(i64::MIN) as u64
            );
        }
    }

    #[test]
    fn test_negu_has_no_overflow() {
        let mut mmix = MMix::new();
        mmix.set_register(1, i64::MIN as u64);
        mmix.write_tetra(0, 0x36030001); // NEGU $3,0,$1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(3), 0x8000000000000000);
        assert_eq!(mmix.get_special(SpecialReg::RA), 0);
    }

    /// Store `value` from $1 to address 0 with the given store opcode word,
    /// returning rA.
    fn run_store(word: u32, value: u64) -> u64 {
        let mut mmix = MMix::new();
        mmix.set_register(1, value);
        mmix.write_tetra(0, word);
        assert!(mmix.execute_instruction());
        mmix.get_special(SpecialReg::RA)
    }

    #[test]
    fn test_signed_stores_raise_v_when_the_value_does_not_fit() {
        // Register form: ST* $1,$2,$3 with $2 = $3 = 0. Immediate form: Z = 0.
        for (word, wide, narrow) in [
            (0xA0010203u32, 200u64, 127u64),   // STB
            (0xA1010200, 200, 127),            // STBI
            (0xA4010203, 40000, 32767),        // STW
            (0xA5010200, 40000, 32767),        // STWI
            (0xA8010203, 1 << 32, 0x7FFFFFFF), // STT
            (0xA9010200, 1 << 32, 0x7FFFFFFF), // STTI
        ] {
            assert_eq!(run_store(word, wide) & RA_V, RA_V, "{word:#010X} overflows");
            assert_eq!(run_store(word, narrow), 0, "{word:#010X} in range");
        }
    }

    #[test]
    fn test_put_ra_writes_the_rounding_mode_at_bits_17_16() {
        let mut mmix = MMix::new();
        mmix.set_register(1, 1 << RA_ROUND_SHIFT); // ROUND_OFF
        mmix.write_tetra(0, 0xF6150001); // PUT rA,$1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RA), 1 << RA_ROUND_SHIFT);

        // The mode is read from those bits: ROUND_OFF truncates 42.9 to 42.
        mmix.set_register(3, 42.9f64.to_bits());
        mmix.write_tetra(4, 0x05020003); // FIX $2,$0,$3
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_register(2), 42);

        // Raising an event leaves the mode field alone.
        let ra = mmix.get_special(SpecialReg::RA);
        assert_eq!(ra & RA_X, RA_X, "the conversion was inexact");
        assert_eq!(ra >> RA_ROUND_SHIFT, 1, "the mode survives an event");
    }

    #[test]
    fn test_put_ra_rejects_a_value_wider_than_18_bits() {
        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        mmix.set_special(SpecialReg::RA, 2 << RA_ROUND_SHIFT);
        mmix.set_register(1, RA_MAX + 1);
        mmix.write_tetra(0, 0xF6150001); // PUT rA,$1
        assert!(!mmix.execute_instruction());
        assert_eq!(
            mmix.get_special(SpecialReg::RA),
            2 << RA_ROUND_SHIFT,
            "a rejected write leaves rA unchanged"
        );
        assert_eq!(mmix.get_pc(), 0, "the PC stays on the rejected instruction");
        assert_eq!(handle.diagnostics().len(), 1);
        assert!(handle.diagnostics()[0].contains("rA"));
    }

    #[test]
    fn test_put_ra_accepts_the_widest_legal_value() {
        let mut mmix = MMix::new();
        mmix.set_register(1, RA_MAX);
        mmix.write_tetra(0, 0xF6150001); // PUT rA,$1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RA), RA_MAX);
    }

    #[test]
    fn test_put_other_specials_is_not_capped() {
        let mut mmix = MMix::new();
        mmix.set_register(1, u64::MAX);
        mmix.write_tetra(0, 0xF6010001); // PUT rD,$1
        assert!(mmix.execute_instruction());
        assert_eq!(mmix.get_special(SpecialReg::RD), u64::MAX);
    }

    /// End-to-end proof of the `debug` contract: a subroutine that sets
    /// locals, prints, makes a nested call with `rJ` saved and restored,
    /// prints again, then returns, leaves its caller's locals, `rL`, `rJ`
    /// and the returned value exactly as an equivalent program without the
    /// two `debug` lines would.
    #[test]
    fn test_debug_preserves_every_register_around_a_nested_call() {
        use crate::debugger::{entry_point, write_image};
        use crate::mmixal::MMixAssembler;

        const SOURCE: &str = "\
\tLOC\t#100
Main\tSET\t$1,11
\tPUSHJ\t$2,Sub
\tTRAP\t0,Halt,0
Sub\tSET\t$0,5
\tSET\t$1,7
\tdebug\t\"first\"
\tGET\t$2,rJ
\tPUSHJ\t$3,Nested
\tPUT\trJ,$2
\tdebug\t\"second\"
\tPOP\t1,0
Nested\tSET\t$0,42
\tPOP\t0,0
";
        let mut asm = MMixAssembler::new(SOURCE, "<test>");
        asm.parse().expect("program must assemble");
        let main_addr = *asm.labels.get("Main").expect("Main label");

        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        write_image(&mut mmix, &asm);
        mmix.set_pc(entry_point(&asm));

        let (_, stop) = mmix.run_bounded(10_000);
        assert_eq!(stop, Stop::Halted);

        let stdout = String::from_utf8(handle.stdout()).expect("valid utf8");
        assert!(stdout.contains("first\n"), "got {stdout:?}");
        assert!(stdout.contains("second\n"), "got {stdout:?}");
        assert!(
            stdout.find("first").unwrap() < stdout.find("second").unwrap(),
            "the two debug lines must print in order, got {stdout:?}"
        );

        // Main's own local, staged below PUSHJ's hole, survives Sub's whole
        // call -- including both debug lines and the nested call inside it.
        assert_eq!(mmix.get_register(1), 11, "caller's local $1 must survive");
        // Sub's $0, set before either debug line, is what POP 1,0 returns
        // to the hole -- proof debug left it untouched across both calls.
        assert_eq!(mmix.get_register(2), 5, "returned value");
        assert_eq!(mmix.get_special(SpecialReg::RL), 3);
        // rJ lands back on Main's own PUSHJ (the second instruction) + 4:
        // Sub's own POP read it straight, with nothing to restore, since
        // nothing after Sub's own GET/PUT round trip ever touched it.
        assert_eq!(mmix.get_special(SpecialReg::RJ), main_addr + 8);
        // TRAP's own handler advances pc past itself before halting.
        assert_eq!(mmix.get_pc(), main_addr + 12, "halt address");
        assert_eq!(mmix.call_depth(), 0);
    }

    /// At `rG = 255`, `$254` is local, so `debug`'s stub (`SAVE $254,0`)
    /// breaks the `X >= rG` rule and halts before its `Fputs` ever runs.
    /// Pinned until C8 replaces the stub with a single `TRAP`.
    #[test]
    fn test_debug_after_put_rg_255_halts_at_the_stubs_save() {
        use crate::debugger::{entry_point, write_image};
        use crate::mmixal::MMixAssembler;

        const SOURCE: &str = "\
\tLOC\t#100
\tSET\t$1,255
\tPUT\trG,$1
\tdebug\t\"unreachable\"
";
        let mut asm = MMixAssembler::new(SOURCE, "<test>");
        asm.parse().expect("program must assemble");

        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        write_image(&mut mmix, &asm);
        mmix.set_pc(entry_point(&asm));

        let (_, stop) = mmix.run_bounded(100);
        assert_eq!(stop, Stop::Halted);
        assert!(
            handle.stdout().is_empty(),
            "the stub halts before Fputs runs"
        );
        // run_bounded logs its own halt notice alongside SAVE's rejection.
        assert!(handle.diagnostics().iter().any(|d| d.contains("SAVE")));
    }

    /// Assembles `source`, runs it under a fresh `CaptureHost` for up to
    /// `budget` instructions, and returns the machine, the run's outcome,
    /// and captured stdout. Shared by the `debug`-expansion regression
    /// tests below.
    fn assemble_and_run_bounded(source: &str, budget: usize) -> (MMix, Stop, String) {
        use crate::debugger::{entry_point, write_image};
        use crate::mmixal::MMixAssembler;

        let mut asm = MMixAssembler::new(source, "<test>");
        asm.parse().expect("program must assemble");

        let (host, handle) = CaptureHost::new();
        let mut mmix = MMix::with_host(host);
        write_image(&mut mmix, &asm);
        mmix.set_pc(entry_point(&asm));
        let (_, stop) = mmix.run_bounded(budget);

        let stdout = String::from_utf8(handle.stdout()).expect("valid utf8");
        (mmix, stop, stdout)
    }

    /// A `debug` line followed by a trailing blank line at end of file, with
    /// nothing after it to halt on: the guard ahead of the generated block
    /// (`preprocess_debug`) halts the program instead of looping through the
    /// stub forever, and the text prints exactly once.
    #[test]
    fn test_debug_directive_followed_by_a_blank_line_at_eof() {
        let source = "\tLOC\t#100\nMain\tdebug \"hi\"\n\n";
        let (_, stop, stdout) = assemble_and_run_bounded(source, 1_000);
        assert_eq!(stop, Stop::Halted, "must not loop, got {stdout:?}");
        assert_eq!(stdout, "hi\n");
    }

    /// A `debug` line followed by a trailing comment line at end of file.
    #[test]
    fn test_debug_directive_followed_by_a_comment_line_at_eof() {
        let source = "\tLOC\t#100\nMain\tdebug \"hi\"\n; nothing else follows\n";
        let (_, stop, stdout) = assemble_and_run_bounded(source, 1_000);
        assert_eq!(stop, Stop::Halted, "must not loop, got {stdout:?}");
        assert_eq!(stdout, "hi\n");
    }

    /// A `debug` line as the source's last statement, with nothing after
    /// it at all -- not even a blank or comment line.
    #[test]
    fn test_debug_directive_as_the_last_statement() {
        let source = "\tLOC\t#100\nMain\tdebug \"hi\"\n";
        let (_, stop, stdout) = assemble_and_run_bounded(source, 1_000);
        assert_eq!(stop, Stop::Halted, "must not loop, got {stdout:?}");
        assert_eq!(stdout, "hi\n");
    }

    /// An `IS` line right after `debug`: unrelated to the call's own return
    /// address, it binds its own constant and every later instruction
    /// still runs in order.
    #[test]
    fn test_debug_directive_followed_by_an_is_line() {
        let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
Ret2\tIS\t#10C
\tSET\t$1,7
\tSET\t$2,Ret2
\tTRAP\t0,Halt,0
";
        let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
        assert_eq!(stop, Stop::Halted);
        assert_eq!(stdout, "hi\n");
        assert_eq!(mmix.get_register(1), 7);
        assert_eq!(mmix.get_register(2), 0x10C, "Ret2 must still bind #10C");
    }

    /// A `GREG` line right after `debug`: it allocates its own register
    /// exactly as it would without `debug` in front of it.
    #[test]
    fn test_debug_directive_followed_by_a_greg_line() {
        let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
Foo\tGREG\t@
\tSET\tFoo,42
\tSET\t$1,Foo
\tTRAP\t0,Halt,0
";
        let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
        assert_eq!(stop, Stop::Halted);
        assert_eq!(stdout, "hi\n");
        assert_eq!(mmix.get_register(1), 42, "Foo must still hold 42");
    }

    /// A label-only line (no instruction) right after `debug`.
    #[test]
    fn test_debug_directive_followed_by_a_label_only_line() {
        let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
Done
\tSET\t$1,7
\tTRAP\t0,Halt,0
";
        let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
        assert_eq!(stop, Stop::Halted);
        assert_eq!(stdout, "hi\n");
        assert_eq!(mmix.get_register(1), 7);
    }

    /// A `:`-prefixed (global-namespace) label-only line right after `debug`.
    #[test]
    fn test_debug_directive_followed_by_a_colon_prefixed_label() {
        let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
:Done
\tSET\t$1,7
\tTRAP\t0,Halt,0
";
        let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
        assert_eq!(stop, Stop::Halted);
        assert_eq!(stdout, "hi\n");
        assert_eq!(mmix.get_register(1), 7);
    }
}