systemless 0.100.0

High-Level Emulation for classic Macintosh applications
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
//! Resource Manager and File Manager trap handlers.

use crate::cpu::{CpuOps, Register};
use crate::loader::CodeSegmentHeader;
use crate::gestalt_manager::{
    evaluate_gestalt_query, evaluate_new_gestalt, evaluate_replace_gestalt,
    is_builtin_gestalt_selector, GestaltEvaluationContext, NewGestaltAction,
    ReplaceGestaltAction, GESTALT_DUP_SELECTOR_ERR_U32 as GESTALT_DUP_SELECTOR_ERR,
    GESTALT_UNDEF_SELECTOR_ERR_U32 as GESTALT_UNDEF_SELECTOR_ERR,
};
use crate::managers::resource::ResourceFork;
use crate::memory::globals::addr;
use crate::memory::{MacMemoryBus, MemoryBus};
use crate::process_context::ProcessVfsDirectory;
use crate::process_manager::{ProcessSerialNumber, SingleProcessEnumeration};
use crate::trap::types::{decode_mac_roman, encode_mac_roman_lossy, read_fsspec_name};
use crate::{Error, Result};

use std::collections::BTreeMap;
use std::sync::OnceLock;

use super::dispatch::{
    raw_trap_route, selector_operation_route, OsRoutineVariant, SelectorOperationRoute,
};

static TRACE_MENU_PICT: OnceLock<bool> = OnceLock::new();
static TRACE_FSSPEC: OnceLock<bool> = OnceLock::new();
static TRACE_SOUND_RESOURCE: OnceLock<bool> = OnceLock::new();
static TRACE_GETRESOURCE: OnceLock<bool> = OnceLock::new();
static TRACE_LOADSEG: OnceLock<bool> = OnceLock::new();

const RESOURCE_DISPATCH_OPERATION_ROUTES: &[SelectorOperationRoute] =
    &include!("generated_resource_dispatch_operations.rs");
const HIGH_LEVEL_FS_DISPATCH_OPERATION_ROUTES: &[SelectorOperationRoute] =
    &include!("generated_high_level_fs_dispatch_operations.rs");
const HFS_DISPATCH_OPERATION_ROUTES: &[SelectorOperationRoute] =
    &include!("generated_hfs_dispatch_operations.rs");
const OS_DISPATCH_OPERATION_ROUTES: &[SelectorOperationRoute] =
    &include!("generated_os_dispatch_operations.rs");

fn resource_dispatch_operation_route(
    trap_word: u16,
    selector: u32,
) -> Option<&'static SelectorOperationRoute> {
    if trap_word != 0xA822 {
        return None;
    }
    selector_operation_route(RESOURCE_DISPATCH_OPERATION_ROUTES, selector)
}

fn high_level_fs_dispatch_operation_route(
    trap_word: u16,
    selector: u32,
) -> Option<&'static SelectorOperationRoute> {
    if trap_word != 0xAA52 {
        return None;
    }
    selector_operation_route(HIGH_LEVEL_FS_DISPATCH_OPERATION_ROUTES, selector)
}

fn hfs_dispatch_operation_route(
    trap_word: u16,
    selector: u32,
) -> Option<&'static SelectorOperationRoute> {
    if trap_word != 0xA260 {
        return None;
    }
    selector_operation_route(HFS_DISPATCH_OPERATION_ROUTES, selector)
}

fn os_dispatch_operation_route(
    trap_word: u16,
    selector: u16,
) -> Option<&'static SelectorOperationRoute> {
    if trap_word != 0xA88F {
        return None;
    }
    selector_operation_route(OS_DISPATCH_OPERATION_ROUTES, u32::from(selector))
}

const BOOT_VOLUME_ALLOCATION_BLOCKS: u16 = 16_384;
const BOOT_VOLUME_ALLOCATION_BLOCK_SIZE: u32 = 4 * 1024;
const BOOT_VOLUME_FREE_BLOCKS: u16 = 16_384;
const NO_ERR: u32 = 0;
const MEM_FULL_ERR: u32 = (-108i32) as u32;
const NIL_HANDLE_ERR: u32 = (-109i32) as u32;
const MEM_WZ_ERR: u32 = (-111i32) as u32;
const RES_NOT_FOUND_ERR: i16 = -192;
const NO_OUTSTANDING_HLE_ERR: i16 = -608;
const CONNECTION_INVALID_ERR: i16 = -609;
const NO_PORT_ERR: i16 = -903;

#[derive(Clone, Debug)]
struct CatSearchEntry {
    name: String,
    vref_num: i16,
    parent_dir_id: u32,
    is_directory: bool,
    locked: bool,
    finder_info: [u8; 16],
    extended_finder_info: [u8; 16],
    data_length: u32,
    resource_length: u32,
    child_count: u16,
    created_date: u32,
    modified_date: u32,
    backup_date: u32,
}

fn trace_menu_pict_enabled() -> bool {
    *TRACE_MENU_PICT.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_MENU_PICT").is_some())
}

fn trace_fsspec_enabled() -> bool {
    *TRACE_FSSPEC.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_FSSPEC").is_some())
}

fn trace_sound_resource_enabled() -> bool {
    *TRACE_SOUND_RESOURCE.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_SOUND").is_some())
}

fn trace_getresource_enabled() -> bool {
    *TRACE_GETRESOURCE.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_GETRESOURCE").is_some())
}

fn trace_loadseg_enabled() -> bool {
    *TRACE_LOADSEG.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_LOADSEG").is_some())
}

fn signed_byte_from_stack_word(word: u16) -> i16 {
    let byte = if word & 0x00FF == 0 {
        (word >> 8) as u8
    } else {
        (word & 0x00FF) as u8
    };
    i16::from(byte as i8)
}

fn file_permission_from_stack_word(word: u16) -> i16 {
    fn is_file_permission(byte: u8) -> bool {
        matches!(byte, 0..=4)
    }

    let high = (word >> 8) as u8;
    let low = (word & 0x00FF) as u8;
    match (is_file_permission(high), is_file_permission(low)) {
        (true, false) => high as i16,
        (false, true) => low as i16,
        _ => signed_byte_from_stack_word(word),
    }
}

fn temporary_memory_free_estimate(bus: &MacMemoryBus) -> u32 {
    (bus.ram_size() / 2).clamp(8 * 1024 * 1024, 64 * 1024 * 1024)
}

fn write_temp_memory_result_code(bus: &mut MacMemoryBus, result_code_ptr: u32, result: u32) {
    if result_code_ptr != 0 {
        bus.write_word(result_code_ptr, result as u16);
    }
}

fn write_osdispatch_oseerr_result<C: CpuOps>(
    cpu: &mut C,
    bus: &mut MacMemoryBus,
    result_slot: u32,
    err: i16,
) {
    bus.write_word(result_slot, err as u16);
    cpu.write_reg(Register::D0, err as i32 as u32);
    cpu.write_reg(Register::A7, result_slot);
}

fn write_osdispatch_selector_result<C: CpuOps>(
    cpu: &mut C,
    bus: &mut MacMemoryBus,
    selector_slot: u32,
    err: i16,
) {
    bus.write_word(selector_slot, err as u16);
    cpu.write_reg(Register::D0, err as i32 as u32);
    cpu.write_reg(Register::A7, selector_slot);
}

fn scribble_temporary_allocation(bus: &mut MacMemoryBus, address: u32, size: u32) {
    for offset in 0..size {
        bus.write_byte(address.wrapping_add(offset), 0xA5);
    }
}

fn temporary_memory_handle_status(bus: &MacMemoryBus, handle: u32) -> u32 {
    if handle == 0 {
        return NIL_HANDLE_ERR;
    }
    if bus.get_alloc_size(handle).is_none() {
        return MEM_WZ_ERR;
    }
    let ptr = bus.read_long(handle);
    if ptr == 0 {
        return NIL_HANDLE_ERR;
    }
    if bus.get_alloc_size(ptr).is_none() {
        return MEM_WZ_ERR;
    }
    NO_ERR
}

fn format_ostype(res_type: [u8; 4]) -> String {
    res_type
        .into_iter()
        .map(|byte| {
            if byte.is_ascii_graphic() || byte == b' ' {
                byte as char
            } else {
                '.'
            }
        })
        .collect()
}

impl super::TrapDispatcher {
    fn restore_native_toolbox_nonvolatile<C: CpuOps>(
        cpu: &mut C,
        call: &super::dispatch::NativeTrapCallState,
    ) {
        for (reg, value) in [
            Register::D3,
            Register::D4,
            Register::D5,
            Register::D6,
            Register::D7,
        ]
        .into_iter()
        .zip(call.preserved_d_regs)
        {
            cpu.write_reg(reg, value);
        }
        for (reg, value) in [
            Register::A2,
            Register::A3,
            Register::A4,
            Register::A5,
            Register::A6,
        ]
        .into_iter()
        .zip(call.preserved_a_regs)
        {
            cpu.write_reg(reg, value);
        }
    }

    pub(crate) const RES_NOT_FOUND: i16 = -192;
    pub(crate) const RES_ATTR_ERR: i16 = -198;
    pub(crate) const RES_CHANGED_ATTR: u16 = 0x0002;
    pub(crate) const RES_SYS_REF_ATTR: u16 = 0x0080;
    pub(crate) const RES_MAP_CHANGED_ATTR: u16 = 0x0020;
    pub(crate) const RES_MAP_READ_ONLY_ATTR: u16 = 0x0080;

    fn is_available_synthetic_driver_name(filename: &str) -> bool {
        // Driver presence is a capability probe. Keep this list limited to
        // services backed by the HLE: AppleTalk's .MPP/.ATP/.XPP drivers must
        // remain absent until their control, status, and protocol paths exist.
        [".AIn", ".AOut", ".BIn", ".BOut"]
            .iter()
            .any(|driver| filename.eq_ignore_ascii_case(driver))
    }

    fn is_unavailable_appletalk_driver_name(filename: &str) -> bool {
        [".MPP", ".ATP", ".XPP"]
            .iter()
            .any(|driver| filename.eq_ignore_ascii_case(driver))
    }

    fn address_is_loaded_code(&self, address: u32) -> bool {
        let mut bases: Vec<u32> = self.segment_map.values().copied().collect();
        bases.sort_unstable();

        let Some((index, &base)) = bases
            .iter()
            .enumerate()
            .rev()
            .find(|(_, base)| address >= **base)
        else {
            return false;
        };

        bases
            .get(index + 1)
            .map(|&next| address < next)
            .unwrap_or(false)
            && address >= base
    }

    /// Minimal serialized resource fork containing an empty resource map.
    fn empty_resource_fork_bytes() -> Vec<u8> {
        let mut bytes = vec![0u8; 46];
        let mut header = [0u8; 16];
        header[0..4].copy_from_slice(&16u32.to_be_bytes());
        header[4..8].copy_from_slice(&16u32.to_be_bytes());
        header[8..12].copy_from_slice(&0u32.to_be_bytes());
        header[12..16].copy_from_slice(&30u32.to_be_bytes());
        bytes[0..16].copy_from_slice(&header);
        bytes[16..32].copy_from_slice(&header);
        bytes[40..42].copy_from_slice(&28u16.to_be_bytes());
        bytes[42..44].copy_from_slice(&30u16.to_be_bytes());
        bytes[44..46].copy_from_slice(&0xFFFFu16.to_be_bytes());
        bytes
    }

    fn resolve_file_mark_position(
        pos_mode: u16,
        pos_offset: i32,
        cur_pos: usize,
        file_len: usize,
    ) -> std::result::Result<usize, i16> {
        let base = match pos_mode & 0x03 {
            0 => return Ok(cur_pos),
            1 => 0i64,
            2 => file_len as i64,
            3 => cur_pos as i64,
            _ => cur_pos as i64,
        };
        let position = base + pos_offset as i64;
        if position < 0 {
            Err(-40)
        } else {
            Ok(position as usize)
        }
    }

    fn loadseg_entry_is_loaded(bus: &MacMemoryBus, entry_addr: u32) -> bool {
        bus.read_word(entry_addr) == 0x4EF9 || bus.read_word(entry_addr + 2) == 0x4EF9
    }

    fn loadseg_entry_dispatch_pc(bus: &MacMemoryBus, entry_addr: u32) -> u32 {
        if bus.read_word(entry_addr) == 0x4EF9 {
            entry_addr
        } else {
            entry_addr + 2
        }
    }

    fn patch_loadseg_entry(
        bus: &mut MacMemoryBus,
        seg_num: i16,
        seg_addr: u32,
        header_size: u32,
        entry_addr: u32,
    ) -> u32 {
        let routine_offset = if bus.read_word(entry_addr) == 0xA9F0 {
            // Think C format: [A9F0, 0000, offset, seg#]
            bus.read_word(entry_addr + 4) as u32
        } else {
            // Standard format: [offset, 3F3C, seg#, A9F0]
            bus.read_word(entry_addr) as u32
        };
        let code_addr = seg_addr + header_size + routine_offset;
        if bus.read_word(entry_addr) == 0xA9F0 {
            // Think C format entries are called at entry+0, so the loaded
            // entry must also begin with the JMP instruction.
            bus.write_word(entry_addr, 0x4EF9); // JMP.L
            bus.write_long(entry_addr + 2, code_addr);
            bus.write_word(entry_addr + 6, 0);
        } else {
            bus.write_word(entry_addr, seg_num as u16);
            bus.write_word(entry_addr + 2, 0x4EF9); // JMP.L
            bus.write_long(entry_addr + 4, code_addr);
        }
        code_addr
    }

    fn refresh_segment_from_resource(
        &self,
        bus: &mut MacMemoryBus,
        seg_num: i16,
        seg_addr: u32,
        trace_loadseg: bool,
    ) {
        let Some(resources) = self.resources.as_ref() else {
            return;
        };

        let code_key = (*b"CODE", seg_num);
        let ptr = resources
            .files
            .get(&0)
            .and_then(|file| file.loaded.get(&code_key))
            .copied()
            .or_else(|| {
                self.resource_search_order().into_iter().find_map(|refnum| {
                    resources
                        .files
                        .get(&refnum)
                        .and_then(|file| file.loaded.get(&code_key))
                        .copied()
                })
            });
        let Some(ptr) = ptr else {
            return;
        };

        let Some(resource_size) = bus.get_alloc_size(ptr) else {
            return;
        };
        if resource_size == 0 {
            return;
        }

        let current_header =
            CodeSegmentHeader::from_words(bus.read_word(seg_addr), bus.read_word(seg_addr + 2));
        let refreshed_header =
            CodeSegmentHeader::from_words(bus.read_word(ptr), bus.read_word(ptr + 2));
        let mut preserve_header_bytes = 0u32;
        if let (Some(current_count), Some(refreshed_count)) = (
            current_header.jump_table_entry_count(),
            refreshed_header.jump_table_entry_count(),
        ) {
            let tolerated_count = current_count.saturating_mul(4).max(current_count + 256);
            if current_count > 0 && refreshed_count > tolerated_count {
                if trace_loadseg {
                    eprintln!(
                        "[TRAP] LoadSeg: preserving CODE {} resident header; resource header {:?} expands resident {:?} entry count {} -> {}",
                        seg_num, refreshed_header, current_header, current_count, refreshed_count
                    );
                }
                preserve_header_bytes = current_header.code_header_size();
            }
        }

        let loaded_size = if seg_addr >= 4 {
            bus.read_long(seg_addr - 4)
        } else {
            0
        };
        let copy_len = resource_size.min(loaded_size);
        if copy_len == 0 {
            return;
        }

        let copied_bytes = if preserve_header_bytes > 0 {
            let preserved = preserve_header_bytes.min(copy_len);
            let body_len = copy_len.saturating_sub(preserved);
            if body_len == 0 {
                Vec::new()
            } else {
                let bytes = bus.read_bytes(ptr + preserved, body_len as usize);
                bus.write_bytes(seg_addr + preserved, &bytes);
                bytes
            }
        } else {
            let bytes = bus.read_bytes(ptr, copy_len as usize);
            bus.write_bytes(seg_addr, &bytes);
            bytes
        };

        if trace_loadseg {
            let preview: Vec<String> = copied_bytes
                .iter()
                .take(16)
                .map(|byte| format!("{byte:02X}"))
                .collect();
            eprintln!(
                "[TRAP] LoadSeg: refreshed CODE {} from resource ptr=${:08X} len={} copied={} preserved_header={} preview={}",
                seg_num,
                ptr,
                resource_size,
                copy_len,
                preserve_header_bytes,
                preview.join(" ")
            );
            if resource_size != loaded_size {
                eprintln!(
                    "[TRAP] LoadSeg: CODE {} resource size {} differs from segment buffer {}",
                    seg_num, resource_size, loaded_size
                );
            }
        }
    }

    fn allocate_loadseg_getresource_trampoline(&mut self, bus: &mut MacMemoryBus) -> u32 {
        if let Some(addr) = self.loadseg_getresource_trampoline_addr {
            return addr;
        }
        let addr = bus.alloc(8);
        bus.write_word(addr, 0x303C); // MOVE.W #imm, D0
        bus.write_word(addr + 2, super::dispatch::LOADSEG_GETRESOURCE_SENTINEL);
        bus.write_word(addr + 4, 0xA816); // _Pack8
        self.loadseg_getresource_trampoline_addr = Some(addr);
        addr
    }

    fn save_d_regs<C: CpuOps>(cpu: &C) -> [u32; 8] {
        [
            cpu.read_reg(Register::D0),
            cpu.read_reg(Register::D1),
            cpu.read_reg(Register::D2),
            cpu.read_reg(Register::D3),
            cpu.read_reg(Register::D4),
            cpu.read_reg(Register::D5),
            cpu.read_reg(Register::D6),
            cpu.read_reg(Register::D7),
        ]
    }

    fn save_a_regs<C: CpuOps>(cpu: &C) -> [u32; 8] {
        [
            cpu.read_reg(Register::A0),
            cpu.read_reg(Register::A1),
            cpu.read_reg(Register::A2),
            cpu.read_reg(Register::A3),
            cpu.read_reg(Register::A4),
            cpu.read_reg(Register::A5),
            cpu.read_reg(Register::A6),
            cpu.read_reg(Register::A7),
        ]
    }

    fn restore_regs<C: CpuOps>(cpu: &mut C, d_regs: [u32; 8], a_regs: [u32; 8]) {
        for (index, value) in d_regs.into_iter().enumerate() {
            cpu.write_reg(
                match index {
                    0 => Register::D0,
                    1 => Register::D1,
                    2 => Register::D2,
                    3 => Register::D3,
                    4 => Register::D4,
                    5 => Register::D5,
                    6 => Register::D6,
                    _ => Register::D7,
                },
                value,
            );
        }
        for (index, value) in a_regs.into_iter().enumerate() {
            cpu.write_reg(
                match index {
                    0 => Register::A0,
                    1 => Register::A1,
                    2 => Register::A2,
                    3 => Register::A3,
                    4 => Register::A4,
                    5 => Register::A5,
                    6 => Register::A6,
                    _ => Register::A7,
                },
                value,
            );
        }
    }

    fn maybe_inject_native_getresource_for_loadseg<C: CpuOps>(
        &mut self,
        bus: &mut MacMemoryBus,
        cpu: &mut C,
        seg_num: i16,
        entry_addr: u32,
        trace_loadseg: bool,
    ) -> bool {
        if self.loadseg_getresource_state.is_some() {
            return false;
        }

        let Some(handler_addr) = self.native_trap_handler(bus, 0xA9A0) else {
            return false;
        };

        let trampoline = self.allocate_loadseg_getresource_trampoline(bus);
        let saved_sp = cpu.read_reg(Register::A7);
        let call_sp = saved_sp.wrapping_sub(14);

        // Native trap handlers are entered as if the trap dispatcher did a
        // JSR to them: return PC first, then the original Pascal arguments.
        bus.write_long(call_sp, trampoline);
        bus.write_word(call_sp + 4, seg_num as u16);
        bus.write_long(call_sp + 6, u32::from_be_bytes(*b"CODE"));
        bus.write_long(call_sp + 10, 0);

        self.loadseg_getresource_state = Some(super::dispatch::LoadSegGetResourceState {
            seg_num,
            entry_addr,
            result_sp: call_sp + 10,
            d_regs: Self::save_d_regs(cpu),
            a_regs: Self::save_a_regs(cpu),
        });

        cpu.write_reg(Register::A7, call_sp);
        cpu.write_reg(Register::PC, handler_addr);

        if trace_loadseg {
            eprintln!(
                "[TRAP] LoadSeg: invoking native GetResource('CODE', {}) handler=${:08X} trampoline=${:08X}",
                seg_num, handler_addr, trampoline
            );
        }

        true
    }

    pub(crate) fn resume_loadseg_after_getresource<C: CpuOps>(
        &mut self,
        bus: &mut MacMemoryBus,
        cpu: &mut C,
    ) -> Result<()> {
        let state = self
            .loadseg_getresource_state
            .take()
            .expect("LoadSeg GetResource trampoline fired without saved state");
        let trace_loadseg = trace_loadseg_enabled();
        let handle = bus.read_long(state.result_sp);

        if trace_loadseg {
            let ptr = if handle == 0 {
                0
            } else {
                bus.read_long(handle)
            };
            eprintln!(
                "[TRAP] LoadSeg: native GetResource returned handle=${:08X} ptr=${:08X} for CODE {}",
                handle, ptr, state.seg_num
            );
        }

        Self::restore_regs(cpu, state.d_regs, state.a_regs);
        self.finish_loadseg(bus, cpu, state.seg_num, Some(state.entry_addr), true)
    }

    fn finish_loadseg<C: CpuOps>(
        &mut self,
        bus: &mut MacMemoryBus,
        cpu: &mut C,
        seg_num: i16,
        entry_addr: Option<u32>,
        refresh_from_resource: bool,
    ) -> Result<()> {
        let trace_loadseg = trace_loadseg_enabled();
        let existing_seg_addr = self.segment_map.get(&seg_num).copied();
        let seg_addr = existing_seg_addr.or_else(|| {
            let (_, ptr) = self.find_or_load_resource_any(bus, *b"CODE", seg_num)?;
            self.segment_map.insert(seg_num, ptr);
            super::dispatch::record_segment_base(seg_num, ptr);
            if trace_loadseg {
                eprintln!(
                    "[TRAP] LoadSeg: materialized CODE {} from resource chain at ${:08X}",
                    seg_num, ptr
                );
            }
            Some(ptr)
        });

        if let Some(seg_addr) = seg_addr {
            if refresh_from_resource && existing_seg_addr.is_some() {
                self.refresh_segment_from_resource(bus, seg_num, seg_addr, trace_loadseg);
            }

            let segment_header =
                CodeSegmentHeader::from_words(bus.read_word(seg_addr), bus.read_word(seg_addr + 2));
            let header_size = segment_header.code_header_size();

            // Read segment header. Standard near segments store byte offset
            // + entry count. Symantec/THINK far segments store first
            // jump-table entry index + entry count.
            if let (Some(tab_off), Some(n_entries)) = (
                segment_header.jump_table_start_offset(),
                segment_header.jump_table_entry_count(),
            ) {
                let a5 = cpu.read_reg(Register::A5);
                let cur_jt_offset = bus.read_word(addr::CUR_JT_OFFSET) as u32;
                let ptr_base = a5 + tab_off + cur_jt_offset;

                if trace_loadseg {
                    let header_desc = match segment_header {
                        CodeSegmentHeader::Near {
                            table_offset,
                            entry_count,
                        } => format!("near taboff={} n={}", table_offset, entry_count),
                        CodeSegmentHeader::ThinkFar {
                            has_relocations,
                            first_entry_index,
                            entry_count,
                        } => format!(
                            "think-far first_jt={} n={} relocs={}",
                            first_entry_index, entry_count, has_relocations
                        ),
                        CodeSegmentHeader::MpwFar => "mpw-far".to_string(),
                    };
                    eprintln!(
                        "[TRAP] LoadSeg seg={}: {} ptr=${:08X}",
                        seg_num, header_desc, ptr_base
                    );
                }

                let mut patched = 0u32;
                for i in 0..n_entries {
                    let p = ptr_base + i * 8;
                    // Skip already-loaded entries. MPW-style entries place
                    // JMP.L at +2; Think-style entries place it at +0.
                    if Self::loadseg_entry_is_loaded(bus, p) {
                        continue;
                    }
                    Self::patch_loadseg_entry(bus, seg_num, seg_addr, header_size, p);
                    patched += 1;
                }
                if trace_loadseg {
                    eprintln!(
                        "[TRAP] LoadSeg: patched {}/{} entries for seg {}",
                        patched, n_entries, seg_num
                    );
                }
            }

            // Ensure the calling entry itself was patched. In Think C format,
            // the calling entry may lie outside the segment header's taboff
            // range (entries for a given segment can be scattered across the JT).
            if let Some(entry_addr) = entry_addr {
                if !Self::loadseg_entry_is_loaded(bus, entry_addr) {
                    let code_addr =
                        Self::patch_loadseg_entry(bus, seg_num, seg_addr, header_size, entry_addr);
                    if trace_loadseg {
                        eprintln!(
                            "[TRAP] LoadSeg: patched calling entry at ${:08X} -> ${:08X}",
                            entry_addr, code_addr
                        );
                    }
                }
            }

            // Apply environment-driven byte patches now that this segment's
            // code is in RAM. Format:
            //   SYSTEMLESS_PATCH_BYTES="0xADDR=HEXBYTES,0xADDR2=BYTES2"
            // This is a diagnostics/test harness hook: callers provide both
            // the absolute address and replacement bytes explicitly.
            if let Ok(spec) = std::env::var("SYSTEMLESS_PATCH_BYTES") {
                for chunk in spec.split(',') {
                    let chunk = chunk.trim();
                    if chunk.is_empty() {
                        continue;
                    }
                    let Some((addr_str, bytes_str)) = chunk.split_once('=') else {
                        continue;
                    };
                    let addr_str = addr_str
                        .trim()
                        .trim_start_matches("0x")
                        .trim_start_matches("0X");
                    let Ok(addr) = u32::from_str_radix(addr_str, 16) else {
                        continue;
                    };
                    let bytes_str = bytes_str.trim();
                    if bytes_str.len() % 2 != 0 {
                        continue;
                    }
                    let mut written = 0u32;
                    for i in 0..(bytes_str.len() / 2) {
                        let hex = &bytes_str[i * 2..i * 2 + 2];
                        let Ok(byte) = u8::from_str_radix(hex, 16) else {
                            continue;
                        };
                        bus.write_byte(addr + written, byte);
                        written += 1;
                    }
                    eprintln!(
                        "[PATCH] Wrote {} bytes at ${:08X} (post-LoadSeg seg={})",
                        written, addr, seg_num
                    );
                }
            }

            // Re-execute the calling JT entry at the JMP instruction. MPW
            // entries dispatch at entry+2; Think C entries dispatch at entry+0.
            if let Some(entry_addr) = entry_addr {
                let jmp_addr = Self::loadseg_entry_dispatch_pc(bus, entry_addr);
                if trace_loadseg {
                    eprintln!("[TRAP] LoadSeg: re-executing JT entry at ${:08X}", jmp_addr);
                }
                cpu.write_reg(Register::PC, jmp_addr);
            }
            Ok(())
        } else {
            eprintln!("ERROR: LoadSeg unknown segment {}", seg_num);
            Err(Error::Halted)
        }
    }

    fn should_trace_extended_resource_activity(&self) -> bool {
        trace_sound_resource_enabled()
            && self
                .resources
                .as_ref()
                .is_some_and(|resources| resources.files.len() > 1)
    }

    fn add_resource_materialization_tick_cost(&mut self, bus: &MacMemoryBus, ptr: u32) {
        let Some(byte_len) = bus.get_alloc_size(ptr) else {
            return;
        };
        self.add_hle_tick_cost(Self::resource_load_tick_cost(byte_len));
    }

    fn resource_trace_chain(&self) -> String {
        self.resource_search_order()
            .into_iter()
            .map(|refnum| {
                if let Some(name) = self.resource_file_name(refnum) {
                    format!("{}:{}", refnum, name)
                } else {
                    refnum.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join(" -> ")
    }

    // ResLoad is guest-owned state: assembly callers may write the byte
    // directly rather than call SetResLoad. Inside Macintosh I (1985), I-118;
    // More Macintosh Toolbox (1993), pp. 1-75 and 1-79.
    pub(crate) fn resource_loading_enabled(bus: &MacMemoryBus) -> bool {
        bus.read_byte(crate::memory::globals::addr::RES_LOAD) != 0
    }

    pub(crate) fn get_or_create_resource_handle_in_file(
        &mut self,
        bus: &mut MacMemoryBus,
        res_type: [u8; 4],
        res_id: i16,
        ptr: u32,
        refnum: u16,
    ) -> u32 {
        let key = (refnum, res_type, res_id);
        let recorded_resident = self.resident_resources.contains(&key);
        if let Some(handle) = self.resource_handles_by_key.get(&key).copied() {
            if let Some((mut existing_ptr, existing_type, existing_id)) =
                self.loaded_handles.get(&handle).copied()
            {
                if existing_type == res_type
                    && existing_id == res_id
                    && self.resource_handle_files.get(&handle).copied() == Some(refnum)
                {
                    // IM:More Macintosh Toolbox 1993, 1-79: SetResLoad(TRUE)
                    // restores automatic loading for resource-returning routines.
                    // If this resource was first seen while SetResLoad(FALSE) was
                    // active, the handle exists but its master pointer is NIL; a
                    // later lookup with loading enabled should fill it and restore
                    // the reverse ptr->handle ownership so RecoverHandle keeps
                    // working after the refill.
                    if existing_ptr == 0 && ptr != 0 {
                        existing_ptr = ptr;
                        self.with_resource_manager_mut(|resource_manager| {
                            resource_manager
                                .loaded_handles
                                .insert(handle, (ptr, existing_type, existing_id));
                        });
                    }
                    if bus.read_long(handle) == 0
                        && (Self::resource_loading_enabled(bus) || recorded_resident)
                    {
                        bus.write_long(handle, existing_ptr);
                        self.add_resource_materialization_tick_cost(bus, existing_ptr);
                    }
                    if bus.read_long(handle) != 0 && existing_ptr != 0 {
                        self.with_resource_manager_mut(|resource_manager| {
                            resource_manager.resident_resources.insert(key);
                        });
                        self.track_handle_ptr(existing_ptr, handle);
                    }
                    self.update_handle_state_bits(handle, |state| {
                        Some(state.unwrap_or(0x40) | 0x20)
                    });
                    return handle;
                }
            }
            self.with_resource_manager_mut(|resource_manager| {
                resource_manager.resource_handles_by_key.remove(&key);
            });
        }

        let handle = bus.alloc(4);
        // IM:More Macintosh Toolbox 1993, 1-79: SetResLoad(FALSE) returns
        // an empty handle (master pointer NIL) for resource data that is not
        // already in memory. Keep the true data pointer in loaded_handles so
        // LoadResource can populate the master pointer later.
        let materialize = Self::resource_loading_enabled(bus) || recorded_resident;
        bus.write_long(handle, if materialize { ptr } else { 0 });
        self.with_resource_manager_mut(|resource_manager| {
            resource_manager
                .loaded_handles
                .insert(handle, (ptr, res_type, res_id));
            resource_manager.resource_handle_files.insert(handle, refnum);
        });
        self.remember_resource_handle_index(handle, key.0, key.1, key.2);
        self.update_handle_state_bits(handle, |state| Some(state.unwrap_or(0x40) | 0x20));
        if materialize && ptr != 0 {
            self.with_resource_manager_mut(|resource_manager| {
                resource_manager.resident_resources.insert(key);
            });
            self.track_handle_ptr(ptr, handle);
            self.add_resource_materialization_tick_cost(bus, ptr);
        }
        handle
    }

    pub(crate) fn get_or_create_resource_handle(
        &mut self,
        bus: &mut MacMemoryBus,
        res_type: [u8; 4],
        res_id: i16,
        ptr: u32,
    ) -> u32 {
        let refnum = self
            .resource_refnum_for_ptr(res_type, res_id, ptr)
            .unwrap_or_else(|| self.current_resource_refnum());
        self.get_or_create_resource_handle_in_file(bus, res_type, res_id, ptr, refnum)
    }

    fn resource_file_contains(&self, refnum: u16, res_type: [u8; 4], res_id: i16) -> bool {
        if self.resources.as_ref().is_some_and(|resources| {
            resources
                .files
                .get(&refnum)
                .is_some_and(|file| file.loaded.contains_key(&(res_type, res_id)))
        }) {
            return true;
        }

        if self
            .resource_backing_data
            .contains_key(&(refnum, res_type, res_id))
        {
            return true;
        }

        false
    }

    pub(crate) fn resource_file_contains_type(&self, refnum: u16, res_type: [u8; 4]) -> bool {
        self.resources.as_ref().is_some_and(|resources| {
            resources
                .files
                .get(&refnum)
                .is_some_and(|file| file.loaded.keys().any(|(kind, _)| *kind == res_type))
        }) || self
            .resource_backing_data
            .keys()
            .any(|(file, kind, _)| *file == refnum && *kind == res_type)
    }

    fn resource_ptr_referenced_elsewhere(&self, refnum: u16, ptr: u32) -> bool {
        self.resources.as_ref().is_some_and(|resources| {
            resources.files.iter().any(|(other_refnum, file)| {
                *other_refnum != refnum && file.loaded.values().any(|&p| p == ptr)
            })
        })
    }

    pub(crate) fn reload_resource_data_from_file(
        &mut self,
        bus: &mut MacMemoryBus,
        refnum: u16,
        res_type: [u8; 4],
        res_id: i16,
    ) -> Option<u32> {
        let (data, attrs, name) = if let Some(data) = self
            .resource_backing_data
            .get(&(refnum, res_type, res_id))
            .cloned()
        {
            let attrs = self
                .resources
                .as_ref()
                .and_then(|resources| resources.files.get(&refnum))
                .and_then(|file| file.attrs.get(&(res_type, res_id)).copied())
                .unwrap_or(0);
            let name = self
                .resources
                .as_ref()
                .and_then(|resources| resources.files.get(&refnum))
                .and_then(|file| file.names_by_id.get(&(res_type, res_id)).cloned());
            (data, attrs, name)
        } else {
            let file_name = self.resource_file_name(refnum)?.to_string();
            let rsrc_bytes = self.vfs_rsrc.get(&file_name)?;
            let fork = ResourceFork::parse(rsrc_bytes)?;
            let resource = fork.resources().get(&(res_type, res_id))?;
            let data = resource.data.clone();
            let attrs = resource.attrs;
            let name = resource.name.clone();
            self.remember_resource_backing_data(refnum, res_type, res_id, data.clone());
            (data, attrs, name)
        };
        let ptr = bus.alloc(data.len() as u32);
        if ptr == 0 {
            return None;
        }
        // An application's resident CODE segment may have been relocated by
        // the Segment Loader before its Resource Manager handle is first
        // requested. Materialize the same relocated bytes in this separate
        // allocation, preserving the resource handle's ordinary heap block.
        // Inside Macintosh Volume II (1985), pp. II-59–II-61.
        if refnum == 0 && res_type == *b"CODE" {
            if let Some(&segment_ptr) = self.segment_map.get(&res_id) {
                let relocated = bus.read_bytes(segment_ptr, data.len());
                bus.write_bytes(ptr, &relocated);
            } else {
                bus.write_bytes(ptr, &data);
            }
        } else {
            bus.write_bytes(ptr, &data);
        }
        Self::zero_loaded_resource_padding(bus, ptr, data.len() as u32);

        self.with_resource_manager_mut(|resource_manager| {
            if let Some(file) = resource_manager
                .resources
                .as_mut()
                .and_then(|resources| resources.files.get_mut(&refnum))
            {
                file.loaded.insert((res_type, res_id), ptr);
                file.attrs.insert((res_type, res_id), attrs);
                if let Some(name) = name {
                    file.named.insert((res_type, name.clone()), (res_id, ptr));
                    file.names_by_id.insert((res_type, res_id), name);
                }
            }
        });

        if refnum == 0 && res_type == *b"CODE" {
            self.mirror_application_code_resource_relocations(bus, res_id, ptr);
        }

        Some(ptr)
    }

    fn find_or_load_resource_current(
        &mut self,
        bus: &mut MacMemoryBus,
        res_type: [u8; 4],
        res_id: i16,
    ) -> Option<(u16, u32)> {
        let res_type = super::TrapDispatcher::normalize_ostype(res_type);
        let refnum = self.current_resource_refnum();
        let live_ptr = self
            .resources
            .as_ref()
            .and_then(|resources| resources.files.get(&refnum))
            .and_then(|file| file.loaded.get(&(res_type, res_id)).copied())
            .filter(|ptr| *ptr != 0);
        if let Some(ptr) = live_ptr {
            return Some((refnum, ptr));
        }

        let known_entry = self
            .resources
            .as_ref()
            .and_then(|resources| resources.files.get(&refnum))
            .is_some_and(|file| file.loaded.contains_key(&(res_type, res_id)));
        if known_entry || self.resource_file_contains(refnum, res_type, res_id) {
            return self
                .reload_resource_data_from_file(bus, refnum, res_type, res_id)
                .map(|ptr| (refnum, ptr));
        }

        None
    }

    fn reload_named_resource_if_needed(
        &mut self,
        bus: &mut MacMemoryBus,
        refnum: u16,
        res_type: [u8; 4],
        res_id: i16,
        ptr: u32,
    ) -> Option<u32> {
        // More Macintosh Toolbox 1993, 1-79: with SetResLoad(FALSE),
        // resource-returning routines may return an empty handle; preserve
        // that contract while restoring released resources when automatic
        // loading is enabled.
        if ptr != 0 || !Self::resource_loading_enabled(bus) {
            return Some(ptr);
        }

        self.reload_resource_data_from_file(bus, refnum, res_type, res_id)
    }

    pub(crate) fn find_named_resource_current_loaded(
        &mut self,
        bus: &mut MacMemoryBus,
        res_type: [u8; 4],
        name: &str,
    ) -> Option<(u16, i16, u32)> {
        let (refnum, res_id, ptr) = self.find_named_resource_current(res_type, name)?;
        let ptr = self.reload_named_resource_if_needed(bus, refnum, res_type, res_id, ptr)?;
        if refnum == 0 && res_type == *b"CODE" {
            self.mirror_application_code_resource_relocations(bus, res_id, ptr);
        }
        Some((refnum, res_id, ptr))
    }

    pub(crate) fn find_named_resource_any_loaded(
        &mut self,
        bus: &mut MacMemoryBus,
        res_type: [u8; 4],
        name: &str,
    ) -> Option<(u16, i16, u32)> {
        let (refnum, res_id, ptr) = self.find_named_resource_any(res_type, name)?;
        let ptr = self.reload_named_resource_if_needed(bus, refnum, res_type, res_id, ptr)?;
        if refnum == 0 && res_type == *b"CODE" {
            self.mirror_application_code_resource_relocations(bus, res_id, ptr);
        }
        Some((refnum, res_id, ptr))
    }

    pub(crate) fn find_or_load_resource_any(
        &mut self,
        bus: &mut MacMemoryBus,
        res_type: [u8; 4],
        res_id: i16,
    ) -> Option<(u16, u32)> {
        let res_type = super::TrapDispatcher::normalize_ostype(res_type);
        for refnum in self.resource_search_order() {
            let live_ptr = self
                .resources
                .as_ref()
                .and_then(|resources| resources.files.get(&refnum))
                .and_then(|file| file.loaded.get(&(res_type, res_id)).copied())
                .filter(|ptr| *ptr != 0);
            if let Some(ptr) = live_ptr {
                return Some((refnum, ptr));
            }

            let known_entry = self
                .resources
                .as_ref()
                .and_then(|resources| resources.files.get(&refnum))
                .is_some_and(|file| file.loaded.contains_key(&(res_type, res_id)));
            if known_entry || self.resource_file_contains(refnum, res_type, res_id) {
                if let Some(ptr) =
                    self.reload_resource_data_from_file(bus, refnum, res_type, res_id)
                {
                    return Some((refnum, ptr));
                }
            }
        }

        None
    }

    fn restore_loaded_resource_handle(&mut self, handle: u32, ptr: u32) {
        self.track_handle_ptr(ptr, handle);
        self.update_handle_state_bits(handle, |state| Some(state.unwrap_or(0x40) | 0x20));
        self.with_resource_manager_mut(|resource_manager| {
            if let (Some((_, res_type, res_id)), Some(refnum)) = (
                resource_manager.loaded_handles.get(&handle).copied(),
                resource_manager.resource_handle_files.get(&handle).copied(),
            ) {
                resource_manager
                    .resident_resources
                    .insert((refnum, res_type, res_id));
            }
            resource_manager.detached_handles.remove(&handle);
            if let Some(refnum) = resource_manager.detached_handle_files.remove(&handle) {
                // A reload should repair any stale detached-file bookkeeping so
                // later Resource Manager queries still see a live resource.
                resource_manager.resource_handle_files.insert(handle, refnum);
            }
        });
    }

    pub(crate) fn forget_resource_residency_for_handle(&mut self, handle: u32) {
        self.with_resource_manager_mut(|resource_manager| {
            if let (Some((_, res_type, res_id)), Some(refnum)) = (
                resource_manager.loaded_handles.get(&handle).copied(),
                resource_manager.resource_handle_files.get(&handle).copied(),
            ) {
                resource_manager
                    .resident_resources
                    .remove(&(refnum, res_type, res_id));
            }
        });
    }

    /// Retain a resource handle's identity while marking its data nonresident.
    ///
    /// `EmptyHandle` releases the relocatable block and sets the master
    /// pointer to `NIL`; a later Resource Manager lookup may reload the data
    /// into the same handle. Inside Macintosh: Memory (1992), pp. 2-51--2-52,
    /// and More Macintosh Toolbox (1993), pp. 1-79--1-80.
    pub(crate) fn empty_resource_handle_residency(&mut self, handle: u32) {
        self.with_resource_manager_mut(|resource_manager| {
            let Some((_, res_type, res_id)) =
                resource_manager.loaded_handles.get(&handle).copied()
            else {
                return;
            };
            let Some(refnum) = resource_manager.resource_handle_files.get(&handle).copied() else {
                return;
            };
            resource_manager
                .resident_resources
                .remove(&(refnum, res_type, res_id));
            if let Some(entry) = resource_manager.loaded_handles.get_mut(&handle) {
                entry.0 = 0;
            }
            if let Some(file) = resource_manager
                .resources
                .as_mut()
                .and_then(|resources| resources.files.get_mut(&refnum))
            {
                file.loaded.insert((res_type, res_id), 0);
                for ((named_type, _), (named_id, ptr)) in &mut file.named {
                    if *named_type == res_type && *named_id == res_id {
                        *ptr = 0;
                    }
                }
            }
        });
    }

    pub(crate) fn live_resource_identity_for_handle(
        &self,
        handle: u32,
    ) -> Option<([u8; 4], i16, Option<u16>)> {
        let (_, res_type, res_id) = self.loaded_handles.get(&handle).copied()?;
        let refnum = self.resource_handle_files.get(&handle).copied();
        Some((res_type, res_id, refnum))
    }

    fn current_system_reference_for_handle(&self, handle: u32) -> Option<(u16, i16)> {
        let (ptr, res_type, _res_id) = self.loaded_handles.get(&handle).copied()?;
        let home_refnum = self.resource_handle_files.get(&handle).copied()?;
        if home_refnum != 0 {
            return None;
        }

        let current_refnum = self.current_resource_refnum();
        if current_refnum == 0 {
            return None;
        }

        let resources = self.resources.as_ref()?;
        let file = resources.files.get(&current_refnum)?;
        file.loaded
            .iter()
            .find_map(|((loaded_type, loaded_id), loaded_ptr)| {
                if *loaded_type == res_type
                    && *loaded_ptr == ptr
                    && file
                        .attrs
                        .get(&(*loaded_type, *loaded_id))
                        .is_some_and(|attrs| (*attrs & Self::RES_SYS_REF_ATTR as u8) != 0)
                {
                    Some((current_refnum, *loaded_id))
                } else {
                    None
                }
            })
    }

    pub(crate) fn resource_record_for_handle(&self, handle: u32) -> Option<(u16, [u8; 4], i16)> {
        let (_, res_type, res_id) = self.loaded_handles.get(&handle).copied()?;
        let home_refnum = self.resource_handle_files.get(&handle).copied()?;
        if let Some((current_refnum, current_id)) = self.current_system_reference_for_handle(handle)
        {
            return Some((current_refnum, res_type, current_id));
        }
        Some((home_refnum, res_type, res_id))
    }

    pub(crate) fn resource_attributes_for_handle(&self, handle: u32) -> Option<u16> {
        let (refnum, res_type, res_id) = self.resource_record_for_handle(handle)?;
        let attrs = self.resources.as_ref().and_then(|resources| {
            resources
                .files
                .get(&refnum)
                .and_then(|file| file.attrs.get(&(res_type, res_id)).copied())
        });
        Some(attrs.unwrap_or(0) as u16)
    }

    pub(crate) fn remove_resource_reference(
        &mut self,
        bus: &mut MacMemoryBus,
        handle: u32,
    ) -> bool {
        const RMV_RES_FAILED: i16 = -196;

        if let Some((refnum, res_type, res_id)) = self.resource_record_for_handle(handle) {
            let current_refnum = self.current_resource_refnum();
            let attrs = self.resource_attributes_for_handle(handle).unwrap_or(0);
            let home_refnum = self.resource_handle_files.get(&handle).copied();
            let shadowed_system_ref = home_refnum == Some(0)
                && self.current_system_reference_for_handle(handle).is_some();

            // Must be in the current file and not protected.
            if (!shadowed_system_ref && refnum != current_refnum) || (attrs & 0x0008) != 0 {
                bus.write_word(0x0A60, RMV_RES_FAILED as u16);
                false
            } else if shadowed_system_ref {
                self.with_resource_manager_mut(|resource_manager| {
                    if let Some(resources) = resource_manager.resources.as_mut() {
                        if let Some(file) = resources.files.get_mut(&refnum) {
                            file.loaded.remove(&(res_type, res_id));
                            file.attrs.remove(&(res_type, res_id));
                            file.names_by_id.remove(&(res_type, res_id));
                            file.named
                                .retain(|(t, _), (id, _)| !(*t == res_type && *id == res_id));
                        }
                    }
                    if let Some(order) = resource_manager.resource_file_order.get_mut(&refnum) {
                        order.retain(|key| *key != (res_type, res_id));
                    }
                });
                self.forget_resource_backing_data(refnum, res_type, res_id);
                bus.write_word(0x0A60, 0);
                true
            } else {
                self.with_resource_manager_mut(|resource_manager| {
                    if let Some(resources) = resource_manager.resources.as_mut() {
                        if let Some(file) = resources.files.get_mut(&current_refnum) {
                            file.loaded.remove(&(res_type, res_id));
                            file.attrs.remove(&(res_type, res_id));
                            file.names_by_id.remove(&(res_type, res_id));
                            file.named
                                .retain(|(t, _), (id, _)| !(*t == res_type && *id == res_id));
                        }
                    }
                    if let Some(order) = resource_manager
                        .resource_file_order
                        .get_mut(&current_refnum)
                    {
                        order.retain(|key| *key != (res_type, res_id));
                    }
                });
                self.forget_resource_backing_data(current_refnum, res_type, res_id);
                self.forget_resource_handle_index_for_handle(handle);
                self.with_resource_manager_mut(|resource_manager| {
                    resource_manager.loaded_handles.remove(&handle);
                    resource_manager.resource_handle_files.remove(&handle);
                });
                self.update_handle_state_bits(handle, |state| Some(state.unwrap_or(0x40) & !0x20));
                bus.write_word(0x0A60, 0);
                true
            }
        } else {
            bus.write_word(0x0A60, RMV_RES_FAILED as u16);
            false
        }
    }

    pub(crate) fn add_resource_reference(
        &mut self,
        bus: &mut MacMemoryBus,
        handle: u32,
        new_id: i16,
        name_ptr: u32,
    ) -> bool {
        const ADD_REF_FAILED: i16 = -195;

        let Some((res_type, _res_id, source_refnum)) =
            self.live_resource_identity_for_handle(handle)
        else {
            bus.write_word(0x0A60, ADD_REF_FAILED as u16);
            return false;
        };
        if source_refnum != Some(0) {
            bus.write_word(0x0A60, ADD_REF_FAILED as u16);
            return false;
        }

        let current_refnum = self.current_resource_refnum();
        if current_refnum == 0 {
            bus.write_word(0x0A60, ADD_REF_FAILED as u16);
            return false;
        }

        let Some(ptr) = self.loaded_handles.get(&handle).map(|(ptr, _, _)| *ptr) else {
            bus.write_word(0x0A60, ADD_REF_FAILED as u16);
            return false;
        };

        let Some(source_attrs) = self.resource_attributes_for_handle(handle) else {
            bus.write_word(0x0A60, ADD_REF_FAILED as u16);
            return false;
        };

        let name = (name_ptr != 0)
            .then(|| bus.read_pstring(name_ptr))
            .and_then(|name| String::from_utf8(name).ok())
            .filter(|name| !name.is_empty());
        let inserted = self.with_resource_manager_mut(|resource_manager| {
            let Some(resources) = resource_manager.resources.as_mut() else {
                return false;
            };
            let Some(file) = resources.files.get_mut(&current_refnum) else {
                return false;
            };

            if file.loaded.contains_key(&(res_type, new_id))
                || file
                    .loaded
                    .values()
                    .any(|&existing_ptr| existing_ptr == ptr)
            {
                return false;
            }

            let attrs =
                (source_attrs as u8) | Self::RES_CHANGED_ATTR as u8 | Self::RES_SYS_REF_ATTR as u8;
            file.loaded.insert((res_type, new_id), ptr);
            file.attrs.insert((res_type, new_id), attrs);
            file.map_attrs |= Self::RES_MAP_CHANGED_ATTR;
            if let Some(name) = name {
                file.named.insert((res_type, name.clone()), (new_id, ptr));
                file.names_by_id.insert((res_type, new_id), name);
            }
            resource_manager
                .resource_file_order
                .entry(current_refnum)
                .or_default()
                .push((res_type, new_id));
            true
        });
        if !inserted {
            bus.write_word(0x0A60, ADD_REF_FAILED as u16);
            return false;
        }

        if let Some(size) = bus.get_alloc_size(ptr) {
            self.remember_resource_backing_data(
                current_refnum,
                res_type,
                new_id,
                bus.read_bytes(ptr, size as usize),
            );
        }

        bus.write_word(0x0A60, 0);
        true
    }

    /// Simulate writing a resource-backed handle out to disk by
    /// clearing its resChanged bit in the resource map. Returns true
    /// when the handle was a writable changed resource and the flag was
    /// cleared, false otherwise.
    pub(crate) fn write_resource_backing_if_changed(
        &mut self,
        bus: &MacMemoryBus,
        handle: u32,
    ) -> bool {
        let Some((refnum, res_type, res_id)) = self.resource_record_for_handle(handle) else {
            return false;
        };
        let attrs = self.resource_attributes_for_handle(handle).unwrap_or(0);
        if (attrs & 0x0008) != 0 || (attrs & Self::RES_CHANGED_ATTR) == 0 {
            return false;
        }

        let handle_ptr = bus.read_long(handle);
        let backing_ptr = if handle_ptr != 0 {
            handle_ptr
        } else {
            self.loaded_handles
                .get(&handle)
                .map(|(ptr, _, _)| *ptr)
                .unwrap_or(0)
        };
        if backing_ptr != 0 {
            if let Some(size) = bus.get_alloc_size(backing_ptr) {
                let data = bus.read_bytes(backing_ptr, size as usize);
                self.remember_resource_backing_data(refnum, res_type, res_id, data);
            }
        }

        self.with_resource_manager_mut(|resource_manager| {
            if let Some(resources) = resource_manager.resources.as_mut() {
                if let Some(file) = resources.files.get_mut(&refnum) {
                    if let Some(a) = file.attrs.get_mut(&(res_type, res_id)) {
                        *a &= !(Self::RES_CHANGED_ATTR as u8);
                    }
                    if !file
                        .attrs
                        .values()
                        .any(|attr| (*attr & Self::RES_CHANGED_ATTR as u8) != 0)
                    {
                        file.map_attrs &= !Self::RES_MAP_CHANGED_ATTR;
                    }
                }
            }
        });
        true
    }

    fn resource_metadata_for_handle(&self, handle: u32) -> Option<([u8; 4], i16, Option<String>)> {
        let (refnum, res_type, res_id) = self.resource_record_for_handle(handle)?;

        let name = self.resources.as_ref().and_then(|resources| {
            resources
                .files
                .get(&refnum)
                .and_then(|file| file.names_by_id.get(&(res_type, res_id)).cloned())
        });

        Some((res_type, res_id, name))
    }

    pub(crate) fn rsrc_map_entry_for_handle(&self, handle: u32) -> Option<u32> {
        let (_, res_type, res_id) = self.loaded_handles.get(&handle).copied()?;
        let refnum = self.resource_handle_files.get(&handle).copied()?;
        let file_name = if refnum == 0 {
            self.launched_app_path()
        } else {
            self.resource_file_name(refnum)
        };
        if let Some(file_name) = file_name {
            if let Some(rsrc_bytes) = self.vfs_rsrc.get(file_name) {
                if let Some(fork) = ResourceFork::parse(rsrc_bytes) {
                    if let Some(resource) = fork.resources().get(&(res_type, res_id)) {
                        return Some(resource.reference_offset as u32);
                    }
                }
            }
        }

        let resources = self.resources.as_ref()?;
        let file = resources.files.get(&refnum)?;
        let mut ordered_keys: Vec<([u8; 4], i16)> = file.loaded.keys().copied().collect();
        ordered_keys.sort_unstable_by(|(type_a, id_a), (type_b, id_b)| {
            type_a.cmp(type_b).then(id_a.cmp(id_b))
        });
        let index = ordered_keys
            .iter()
            .position(|key| *key == (res_type, res_id))? as u32;
        Some(38 + index * 12)
    }

    fn resource_file_needs_writeback(
        file: &super::dispatch::ResourceFileMap,
        changed_attr: u8,
        changed_map_attr: u16,
    ) -> bool {
        (file.map_attrs & changed_map_attr) != 0
            || file
                .attrs
                .values()
                .any(|attrs| (*attrs & changed_attr) != 0)
    }

    fn resource_data_for_writeback(
        &self,
        bus: &MacMemoryBus,
        refnum: u16,
        res_type: [u8; 4],
        res_id: i16,
        ptr: u32,
    ) -> Option<Vec<u8>> {
        let live_ptr = self
            .handle_for_ptr(ptr)
            .map(|handle| bus.read_long(handle))
            .filter(|handle_ptr| *handle_ptr != 0)
            .unwrap_or(ptr);
        if live_ptr != 0 {
            if let Some(size) = bus.get_alloc_size(live_ptr) {
                return Some(bus.read_bytes(live_ptr, size as usize));
            }
        }

        if let Some(data) = self
            .resource_backing_data
            .get(&(refnum, res_type, res_id))
            .cloned()
        {
            return Some(data);
        }

        let file_name = self.resource_file_name(refnum)?;
        let rsrc_bytes = self.vfs_rsrc.get(file_name)?;
        let fork = ResourceFork::parse(rsrc_bytes)?;
        fork.resources()
            .get(&(res_type, res_id))
            .map(|resource| resource.data.clone())
    }

    fn serialize_resource_file_map_for_writeback(
        &self,
        bus: &MacMemoryBus,
        refnum: u16,
        file: &super::dispatch::ResourceFileMap,
    ) -> Option<Vec<u8>> {
        const DATA_OFFSET: u32 = 16;

        struct WriteEntry {
            id: i16,
            data: Vec<u8>,
            attrs: u8,
            name: Option<Vec<u8>>,
            name_offset: Option<u16>,
            data_offset: u32,
        }

        let changed_attr = Self::RES_CHANGED_ATTR as u8;
        let mut type_groups: BTreeMap<[u8; 4], Vec<WriteEntry>> = BTreeMap::new();
        for (&(res_type, res_id), &ptr) in &file.loaded {
            let data = self.resource_data_for_writeback(bus, refnum, res_type, res_id, ptr)?;
            let attrs = file.attrs.get(&(res_type, res_id)).copied().unwrap_or(0) & !changed_attr;
            let name = file.names_by_id.get(&(res_type, res_id)).and_then(|name| {
                let encoded = encode_mac_roman_lossy(name);
                if encoded.is_empty() {
                    None
                } else {
                    Some(encoded.into_iter().take(255).collect())
                }
            });
            type_groups.entry(res_type).or_default().push(WriteEntry {
                id: res_id,
                data,
                attrs,
                name,
                name_offset: None,
                data_offset: 0,
            });
        }

        if type_groups.is_empty() {
            let mut bytes = Self::empty_resource_fork_bytes();
            let map_start = 16usize;
            let map_attrs = file.map_attrs & !Self::RES_MAP_CHANGED_ATTR;
            bytes[map_start + 22..map_start + 24].copy_from_slice(&map_attrs.to_be_bytes());
            return Some(bytes);
        }

        let mut data_section = Vec::new();
        for entries in type_groups.values_mut() {
            entries.sort_by_key(|entry| entry.id);
            for entry in entries {
                if data_section.len() > 0x00FF_FFFF {
                    return None;
                }
                entry.data_offset = data_section.len() as u32;
                data_section.extend_from_slice(&(entry.data.len() as u32).to_be_bytes());
                data_section.extend_from_slice(&entry.data);
            }
        }

        let type_count = type_groups.len();
        if type_count == 0 || type_count > u16::MAX as usize + 1 {
            return None;
        }
        let resource_count: usize = type_groups.values().map(Vec::len).sum();
        let ref_lists_offset = 2usize.checked_add(type_count.checked_mul(8)?)?;
        let name_list_offset = 30usize
            .checked_add(ref_lists_offset)?
            .checked_add(resource_count.checked_mul(12)?)?;
        if name_list_offset > u16::MAX as usize {
            return None;
        }

        let mut name_section = Vec::new();
        for entries in type_groups.values_mut() {
            for entry in entries {
                if let Some(name) = entry.name.as_ref() {
                    if name_section.len() > u16::MAX as usize {
                        return None;
                    }
                    entry.name_offset = Some(name_section.len() as u16);
                    name_section.push(name.len() as u8);
                    name_section.extend_from_slice(name);
                }
            }
        }

        let map_length = name_list_offset.checked_add(name_section.len())?;
        let map_offset = DATA_OFFSET.checked_add(data_section.len() as u32)?;
        let total_len = (map_offset as usize).checked_add(map_length)?;
        let mut bytes = vec![0u8; total_len];
        let mut header = [0u8; 16];
        header[0..4].copy_from_slice(&DATA_OFFSET.to_be_bytes());
        header[4..8].copy_from_slice(&map_offset.to_be_bytes());
        header[8..12].copy_from_slice(&(data_section.len() as u32).to_be_bytes());
        header[12..16].copy_from_slice(&(map_length as u32).to_be_bytes());
        bytes[0..16].copy_from_slice(&header);
        bytes[DATA_OFFSET as usize..DATA_OFFSET as usize + data_section.len()]
            .copy_from_slice(&data_section);

        let map_start = map_offset as usize;
        let type_list_offset = 30u16;
        bytes[map_start..map_start + 16].copy_from_slice(&header);
        bytes[map_start + 16..map_start + 20].copy_from_slice(&0u32.to_be_bytes());
        bytes[map_start + 20..map_start + 22].copy_from_slice(&0u16.to_be_bytes());
        let map_attrs = file.map_attrs & !Self::RES_MAP_CHANGED_ATTR;
        bytes[map_start + 22..map_start + 24].copy_from_slice(&map_attrs.to_be_bytes());
        bytes[map_start + 24..map_start + 26].copy_from_slice(&type_list_offset.to_be_bytes());
        bytes[map_start + 26..map_start + 28]
            .copy_from_slice(&(name_list_offset as u16).to_be_bytes());
        bytes[map_start + 28..map_start + 30]
            .copy_from_slice(&((type_count as u16) - 1).to_be_bytes());

        let type_list_start = map_start + type_list_offset as usize;
        bytes[type_list_start..type_list_start + 2]
            .copy_from_slice(&((type_count as u16) - 1).to_be_bytes());

        let mut next_ref_list_offset = ref_lists_offset;
        for (index, (res_type, entries)) in type_groups.iter().enumerate() {
            if entries.len() > u16::MAX as usize + 1 || next_ref_list_offset > u16::MAX as usize {
                return None;
            }

            let type_entry = type_list_start + 2 + index * 8;
            bytes[type_entry..type_entry + 4].copy_from_slice(res_type);
            bytes[type_entry + 4..type_entry + 6]
                .copy_from_slice(&((entries.len() as u16) - 1).to_be_bytes());
            bytes[type_entry + 6..type_entry + 8]
                .copy_from_slice(&(next_ref_list_offset as u16).to_be_bytes());

            let ref_list_start = type_list_start + next_ref_list_offset;
            for (entry_index, entry) in entries.iter().enumerate() {
                let ref_entry = ref_list_start + entry_index * 12;
                bytes[ref_entry..ref_entry + 2].copy_from_slice(&(entry.id as u16).to_be_bytes());
                let name_offset = entry.name_offset.unwrap_or(0xFFFF);
                bytes[ref_entry + 2..ref_entry + 4].copy_from_slice(&name_offset.to_be_bytes());
                bytes[ref_entry + 4] = entry.attrs;
                let data_offset = entry.data_offset.to_be_bytes();
                bytes[ref_entry + 5..ref_entry + 8].copy_from_slice(&data_offset[1..4]);
                bytes[ref_entry + 8..ref_entry + 12].copy_from_slice(&0u32.to_be_bytes());
            }

            next_ref_list_offset += entries.len() * 12;
        }

        let name_list_start = map_start + name_list_offset;
        bytes[name_list_start..name_list_start + name_section.len()].copy_from_slice(&name_section);
        Some(bytes)
    }

    pub(crate) fn flush_resource_file_refnum(&mut self, bus: &MacMemoryBus, refnum: u16) -> bool {
        if refnum == 0 {
            return false;
        }
        let Some((file_name, bytes)) = (|| {
            let resources = self.resources.as_ref()?;
            let file = resources.files.get(&refnum)?;
            if (file.map_attrs & Self::RES_MAP_READ_ONLY_ATTR) != 0 {
                return None;
            }
            if !Self::resource_file_needs_writeback(
                file,
                Self::RES_CHANGED_ATTR as u8,
                Self::RES_MAP_CHANGED_ATTR,
            ) {
                return None;
            }
            let file_name = resources.names.get(&refnum)?.clone();
            let bytes = self.serialize_resource_file_map_for_writeback(bus, refnum, file)?;
            Some((file_name, bytes))
        })() else {
            return false;
        };

        if let Some(fork) = ResourceFork::parse(&bytes) {
            self.clear_resource_file_backing_data(refnum);
            self.remember_resource_fork_backing_data(refnum, &fork);
        }

        let len = bytes.len();
        self.vfs_rsrc.insert(file_name.clone(), bytes);
        self.touch_vfs_entry(&file_name);
        if super::dispatch::trace_resfile_enabled() {
            eprintln!(
                "[RSRC] flushed resource refnum={} name={:?} bytes={}",
                refnum, file_name, len
            );
        }
        true
    }

    pub(crate) fn dispatch_resource<C: CpuOps>(
        &mut self,
        is_tool: bool,
        trap_num: u16,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
    ) -> Option<Result<()>> {
        self.read_tick_count(bus);
        Some(match (is_tool, trap_num) {
            // ServerDispatch ($A094)
            // Dispatches synchronous Macintosh File Sharing server-control calls.
            // FUNCTION SyncServerDispatch(pb: SCParamBlockPtr): OSErr;
            // AppleShare 3.0 File Server Controls, Appendix B, pp. 73; SCShutDown, pp. 58-59.
            // Systemless does not run a file server, so valid control calls observe
            // the documented absent-server result instead of a synthetic service.
            (false, 0x94) => {
                const IO_RESULT_OFFSET: u32 = 16;
                const SC_CODE_OFFSET: u32 = 26;
                const PARAM_ERR: i16 = -50;

                let pb = cpu.read_reg(Register::A0);
                let result = if pb == 0 {
                    PARAM_ERR
                } else {
                    let sc_code = bus.read_word(pb + SC_CODE_OFFSET);
                    eprintln!(
                        "[SERVER] SyncServerDispatch pb=${pb:08X} scCode={sc_code} -> paramErr (server not running)"
                    );
                    bus.write_word(pb + IO_RESULT_OFFSET, PARAM_ERR as u16);
                    PARAM_ERR
                };
                cpu.write_reg(Register::D0, result as i32 as u32);
                Ok(())
            }

            // GetResource ($A9A0)
            // Returns a handle to the resource with the given type and ID.
            // FUNCTION GetResource(theType: ResType; theID: INTEGER): Handle;
            // Inside Macintosh Volume I, I-119
            // GetResource ($A9A0): Loads from ResourceFork, allocates in guest memory
            (true, 0x1A0) => {
                let sp = cpu.read_reg(Register::A7);
                let res_id = bus.read_word(sp) as i16;
                let raw_res_type = bus.read_long(sp + 2).to_be_bytes();
                let res_type = super::TrapDispatcher::normalize_ostype(raw_res_type);
                let trace_sound_resource = trace_sound_resource_enabled() && res_type == *b"snd ";
                let trace_extended = self.should_trace_extended_resource_activity();

                if trace_extended {
                    eprintln!(
                        "[RSRC] GetResource raw='{}' norm='{}' id={} current={} chain=[{}]",
                        format_ostype(raw_res_type),
                        format_ostype(res_type),
                        res_id,
                        self.current_resource_refnum(),
                        self.resource_trace_chain()
                    );
                }

                // Wide-net GetResource trace (gate: SYSTEMLESS_TRACE_GETRESOURCE=1).
                // Logs tick + type + id for every GetResource call.
                if trace_getresource_enabled() {
                    eprintln!(
                        "[GETRESOURCE] tick={} type='{}' id={}",
                        self.current_tick(),
                        format_ostype(res_type),
                        res_id,
                    );
                }

                if trace_menu_pict_enabled() && res_type == *b"PICT" {
                    eprintln!("[RSRC] GetResource('PICT', {})", res_id);
                }
                if trace_sound_resource {
                    eprintln!("[RSRC] GetResource('snd ', {})", res_id);
                }

                if let Some((refnum, ptr)) = self.find_or_load_resource_any(bus, res_type, res_id) {
                    if trace_menu_pict_enabled() && res_type == *b"PICT" {
                        eprintln!(
                            "[RSRC] GetResource('PICT', {}) -> ${:08X} (refnum {})",
                            res_id, ptr, refnum
                        );
                    }
                    if trace_sound_resource {
                        eprintln!(
                            "[RSRC] GetResource('snd ', {}) -> ${:08X} (refnum {})",
                            res_id, ptr, refnum
                        );
                    }
                    if trace_getresource_enabled() {
                        let preview: Vec<String> = bus
                            .read_bytes(ptr, 16)
                            .iter()
                            .map(|b| format!("{:02X}", b))
                            .collect();
                        eprintln!(
                            "[GETRESOURCE]   -> ptr=${:08X} preview={}",
                            ptr,
                            preview.join(" ")
                        );
                    }
                    let handle = self
                        .get_or_create_resource_handle_in_file(bus, res_type, res_id, ptr, refnum);

                    cpu.write_reg(Register::A0, handle);
                    cpu.write_reg(Register::D0, 0);
                    bus.write_word(0x0A60, 0); // ResErr = noErr
                    bus.write_long(sp + 6, handle);
                    cpu.write_reg(Register::A7, sp + 6);
                    return Some(Ok(()));
                }

                if trace_menu_pict_enabled() && res_type == *b"PICT" {
                    eprintln!("[RSRC] GetResource('PICT', {}) -> not found", res_id);
                }
                if trace_sound_resource {
                    eprintln!("[RSRC] GetResource('snd ', {}) -> not found", res_id);
                }

                if res_type == *b"ICON" {
                    if let Some(ptr) = self.synthesize_system_icon(bus, res_id) {
                        let handle = self.get_or_create_resource_handle(bus, res_type, res_id, ptr);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0);
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"STR " {
                    if let Some(ptr) = self.synthesize_system_str(bus, res_id) {
                        let handle = self.get_or_create_resource_handle(bus, res_type, res_id, ptr);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"INTL" {
                    if let Some(ptr) = self.synthesize_system_intl(bus, res_id) {
                        let handle = self
                            .get_or_create_resource_handle_in_file(bus, res_type, res_id, ptr, 0);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"PAT#" {
                    if let Some(ptr) = self.synthesize_system_pattern_list(bus, res_id) {
                        let handle = self
                            .get_or_create_resource_handle_in_file(bus, res_type, res_id, ptr, 0);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"clut" {
                    if let Some(ptr) = self.synthesize_system_clut(bus, res_id) {
                        if trace_getresource_enabled() {
                            let preview: Vec<String> = bus
                                .read_bytes(ptr, 16)
                                .iter()
                                .map(|b| format!("{:02X}", b))
                                .collect();
                            eprintln!(
                                "[GETRESOURCE]   -> synthetic ptr=${:08X} preview={}",
                                ptr,
                                preview.join(" ")
                            );
                        }
                        let handle = self.get_or_create_resource_handle(bus, res_type, res_id, ptr);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"wctb" {
                    if let Some(ptr) = self.synthesize_system_wctb(bus, res_id) {
                        let handle = self.get_or_create_resource_handle(bus, res_type, res_id, ptr);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"WDEF" {
                    if let Some(ptr) = self.synthesize_system_wdef(bus, res_id) {
                        let handle = self
                            .get_or_create_resource_handle_in_file(bus, res_type, res_id, ptr, 0);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"MDEF" {
                    if let Some(ptr) = self.synthesize_system_mdef(bus, res_id) {
                        let handle = self
                            .get_or_create_resource_handle_in_file(bus, res_type, res_id, ptr, 0);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"KCHR" {
                    if let Some(ptr) = self.synthesize_system_kchr(bus, res_id) {
                        if trace_getresource_enabled() {
                            let preview: Vec<String> = bus
                                .read_bytes(ptr, 16)
                                .iter()
                                .map(|b| format!("{:02X}", b))
                                .collect();
                            eprintln!(
                                "[GETRESOURCE]   -> synthetic ptr=${:08X} preview={}",
                                ptr,
                                preview.join(" ")
                            );
                        }
                        let handle = self.get_or_create_resource_handle(bus, res_type, res_id, ptr);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                if res_type == *b"KMAP" {
                    if let Some(ptr) = self.synthesize_system_kmap(bus, res_id) {
                        let handle = self.get_or_create_resource_handle(bus, res_type, res_id, ptr);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, 0);
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_long(sp + 6, handle);
                        cpu.write_reg(Register::A7, sp + 6);
                        return Some(Ok(()));
                    }
                }

                cpu.write_reg(Register::A0, 0);
                cpu.write_reg(Register::D0, 0);
                bus.write_word(0x0A60, 0);
                bus.write_long(sp + 6, 0);
                cpu.write_reg(Register::A7, sp + 6);
                Ok(())
            }

            // Get1Resource ($A81F)
            // FUNCTION Get1Resource(theType: ResType; theID: INTEGER): Handle;
            // Searches only the current resource file (unlike GetResource which searches all).
            // Inside Macintosh Volume I, I-119
            // Get1Resource ($A81F): Searches current resource file only; writes ResErr per IM:I I-119
            (true, 0x01F) => {
                let sp = cpu.read_reg(Register::A7);
                let id = bus.read_word(sp) as i16;
                let raw_res_type = bus.read_long(sp + 2).to_be_bytes();
                let res_type = super::TrapDispatcher::normalize_ostype(raw_res_type);
                let trace_sound_resource = trace_sound_resource_enabled() && res_type == *b"snd ";
                let trace_extended = self.should_trace_extended_resource_activity();

                if trace_extended {
                    eprintln!(
                        "[RSRC] Get1Resource raw='{}' norm='{}' id={} current={} chain=[{}]",
                        format_ostype(raw_res_type),
                        format_ostype(res_type),
                        id,
                        self.current_resource_refnum(),
                        self.resource_trace_chain()
                    );
                }

                if trace_menu_pict_enabled() && res_type == *b"PICT" {
                    eprintln!("[RSRC] Get1Resource('PICT', {})", id);
                }
                if trace_sound_resource {
                    eprintln!("[RSRC] Get1Resource('snd ', {})", id);
                }

                let handle = if let Some((refnum, ptr)) =
                    self.find_or_load_resource_current(bus, res_type, id)
                {
                    if trace_menu_pict_enabled() && res_type == *b"PICT" {
                        eprintln!(
                            "[RSRC] Get1Resource('PICT', {}) -> ${:08X} (refnum {})",
                            id, ptr, refnum
                        );
                    }
                    if trace_sound_resource {
                        eprintln!(
                            "[RSRC] Get1Resource('snd ', {}) -> ${:08X} (refnum {})",
                            id, ptr, refnum
                        );
                    }
                    self.get_or_create_resource_handle_in_file(bus, res_type, id, ptr, refnum)
                } else if res_type == *b"STR " {
                    match self.synthesize_system_str(bus, id) {
                        Some(ptr) => self.get_or_create_resource_handle(bus, res_type, id, ptr),
                        None => 0,
                    }
                } else {
                    if trace_menu_pict_enabled() && res_type == *b"PICT" {
                        eprintln!("[RSRC] Get1Resource('PICT', {}) -> not found", id);
                    }
                    if trace_sound_resource {
                        eprintln!("[RSRC] Get1Resource('snd ', {}) -> not found", id);
                    }
                    0
                };

                // Per BasiliskII/System 7.5.3: misses return NIL and leave
                // ResError at noErr. Callers must check the returned handle,
                // not infer miss from ResError.
                if handle != 0 {
                    cpu.write_reg(Register::A0, handle);
                    cpu.write_reg(Register::D0, 0);
                    bus.write_word(0x0A60, 0); // ResErr = noErr
                    bus.write_long(sp + 6, handle);
                    cpu.write_reg(Register::A7, sp + 6);
                } else {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, 0);
                    bus.write_word(0x0A60, 0);
                    bus.write_long(sp + 6, 0);
                    cpu.write_reg(Register::A7, sp + 6);
                }
                Ok(())
            }

            // DetachResource ($A992)
            // Sets the resource's master pointer so the resource data won't be released.
            // PROCEDURE DetachResource(theResource: Handle);
            // Inside Macintosh Volume I, I-122
            // DetachResource ($A992): Clones shared resource data into a detached private handle and stops treating that handle as resource-backed
            (true, 0x192) => {
                let sp = cpu.read_reg(Register::A7);
                let handle = bus.read_long(sp);
                if let Some((ptr, res_type, res_id)) = self.loaded_handles.get(&handle).copied() {
                    let attrs = self.resource_attributes_for_handle(handle).unwrap_or(0);
                    if (attrs & Self::RES_CHANGED_ATTR) != 0 {
                        bus.write_word(0x0A60, 0);
                    } else {
                        // DetachResource keeps the current handle/data valid but removes
                        // the link from the resource map. In this HLE, GetResource hands
                        // out per-call master pointers to shared guest data, so detaching
                        // must clone the block to keep subsequent SetHandleSize and
                        // DisposeHandle calls from mutating or freeing the shared resource.
                        // Macintosh Revealed 1987, p. 306
                        if handle != 0 && ptr != 0 {
                            if let Some(size) = bus.get_alloc_size(ptr) {
                                let detached_ptr = bus.alloc(size);
                                for offset in 0..size {
                                    bus.write_byte(
                                        detached_ptr + offset,
                                        bus.read_byte(ptr + offset),
                                    );
                                }
                                bus.write_long(handle, detached_ptr);
                            }
                        }
                        // Detaching severs this handle from the resource map without
                        // deleting the resource reference. Mark its shared data as
                        // unloaded so a later lookup reloads pristine fork bytes.
                        self.unload_resource_live_map_entry_for_handle(handle);
                        self.forget_resource_residency_for_handle(handle);
                        self.forget_resource_handle_index_for_handle(handle);
                        self.with_resource_manager_mut(|resource_manager| {
                            resource_manager.loaded_handles.remove(&handle);
                            if let Some(refnum) =
                                resource_manager.resource_handle_files.remove(&handle)
                            {
                                resource_manager.detached_handle_files.insert(handle, refnum);
                            }
                            resource_manager
                                .detached_handles
                                .insert(handle, (res_type, res_id));
                        });
                        self.update_handle_state_bits(handle, |state| {
                            Some(state.unwrap_or(0x40) & !0x20)
                        });
                        bus.write_word(0x0A60, 0);
                    }
                } else {
                    // Per BasiliskII/System 7.5.3: NIL and other
                    // non-resource handles return resNotFound.
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // LoadResource ($A9A2)
            // Reads a resource into memory. No-op if already loaded.
            // PROCEDURE LoadResource(theResource: Handle);
            // Inside Macintosh: More Macintosh Toolbox 1993, 1-80
            //
            // ReleaseResource ($A9A3)
            // Releases the memory occupied by a resource.
            // PROCEDURE ReleaseResource(theResource: Handle);
            // Inside Macintosh Volume I, I-121
            // LoadResource ($A9A2): Populates empty SetResLoad(FALSE) handles and reloads resource-backed handles whose master pointer was later emptied/purged; BasiliskII leaves plain handles untouched and reports `noErr` there.
            (true, 0x1A2) => {
                let sp = cpu.read_reg(Register::A7);
                let handle = bus.read_long(sp);
                if handle == 0 {
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                } else if let Some((ptr, res_type, res_id)) =
                    self.loaded_handles.get(&handle).copied()
                {
                    if super::dispatch::trace_resfile_enabled() {
                        let type_str = String::from_utf8_lossy(&res_type);
                        eprintln!(
                            "[TRAP] LoadResource handle=${:08X} '{}' {} ptr=${:08X}",
                            handle, type_str, res_id, ptr
                        );
                    }
                    let reloaded_ptr = if ptr != 0 {
                        Some(ptr)
                    } else {
                        self.resource_handle_files
                            .get(&handle)
                            .copied()
                            .and_then(|refnum| {
                                self.reload_resource_data_from_file(bus, refnum, res_type, res_id)
                            })
                    };
                    if let Some(ptr) = reloaded_ptr {
                        // Successful reload must canonicalize the master
                        // pointer again even if the caller had emptied or
                        // scribbled over it first.
                        let was_empty = bus.read_long(handle) == 0;
                        bus.write_long(handle, ptr);
                        self.with_resource_manager_mut(|resource_manager| {
                            if let Some(entry) = resource_manager.loaded_handles.get_mut(&handle) {
                                entry.0 = ptr;
                            }
                        });
                        self.restore_loaded_resource_handle(handle, ptr);
                        if was_empty {
                            self.add_resource_materialization_tick_cost(bus, ptr);
                        }
                        bus.write_word(0x0A60, 0);
                    } else {
                        bus.write_word(0x0A60, MEM_FULL_ERR as u16);
                    }
                } else {
                    bus.write_word(0x0A60, 0);
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // ReleaseResource ($A9A3)
            // Releases the memory occupied by a resource and invalidates the
            // caller's handle-to-resource association. The canonical resource
            // bytes remain in Systemless's resource map, so a later GetResource
            // allocates a fresh handle for the same resource data.
            // PROCEDURE ReleaseResource(theResource: Handle);
            // Inside Macintosh Volume I, I-120 to I-121
            // ReleaseResource ($A9A3): Clears a resource handle's master pointer and invalidates its Resource Manager handle identity; returns `resNotFound` for non-resource handles
            (true, 0x1A3) => {
                let sp = cpu.read_reg(Register::A7);
                let handle = bus.read_long(sp);
                if let Some((ptr, res_type, res_id)) = self.loaded_handles.get(&handle).copied() {
                    if super::dispatch::trace_resfile_enabled() {
                        let type_str = String::from_utf8_lossy(&res_type);
                        eprintln!(
                            "[TRAP] ReleaseResource handle=${:08X} '{}' {} ptr=${:08X}",
                            handle, type_str, res_id, ptr
                        );
                    }
                    let attrs = self.resource_attributes_for_handle(handle).unwrap_or(0);
                    if (attrs & Self::RES_CHANGED_ATTR) == 0 {
                        self.forget_resource_residency_for_handle(handle);
                        let resource_record = self.resource_record_for_handle(handle);
                        let can_reload = resource_record
                            .map(|(refnum, record_type, record_id)| {
                                self.resource_file_contains(refnum, record_type, record_id)
                            })
                            .unwrap_or(false);
                        if can_reload {
                            if let Some((refnum, record_type, record_id)) = resource_record {
                                if !self.resource_backing_data.contains_key(&(
                                    refnum,
                                    record_type,
                                    record_id,
                                )) {
                                    if let Some(size) = bus.get_alloc_size(ptr) {
                                        self.remember_resource_backing_data(
                                            refnum,
                                            record_type,
                                            record_id,
                                            bus.read_bytes(ptr, size as usize),
                                        );
                                    }
                                }
                            }
                        }
                        bus.write_long(handle, 0);
                        self.untrack_handle_ptr(ptr);
                        self.forget_resource_handle_index_for_handle(handle);
                        self.with_resource_manager_mut(|resource_manager| {
                            resource_manager.loaded_handles.remove(&handle);
                            resource_manager.resource_handle_files.remove(&handle);
                        });
                        self.remove_handle_state_bits(handle);
                        if can_reload {
                            if let Some((refnum, record_type, record_id)) = resource_record {
                                self.with_resource_manager_mut(|resource_manager| {
                                    if let Some(file) = resource_manager
                                        .resources
                                        .as_mut()
                                        .and_then(|resources| resources.files.get_mut(&refnum))
                                    {
                                        if file
                                            .loaded
                                            .get(&(record_type, record_id))
                                            .is_some_and(|&loaded_ptr| loaded_ptr == ptr)
                                        {
                                            file.loaded.insert((record_type, record_id), 0);
                                        }
                                        if let Some(name) = file
                                            .names_by_id
                                            .get(&(record_type, record_id))
                                            .cloned()
                                        {
                                            if file
                                                .named
                                                .get(&(record_type, name.clone()))
                                                .is_some_and(|(_, named_ptr)| *named_ptr == ptr)
                                            {
                                                file.named
                                                    .insert((record_type, name), (record_id, 0));
                                            }
                                        }
                                    }
                                });
                                if !self.resource_ptr_referenced_elsewhere(refnum, ptr) {
                                    bus.free(ptr);
                                }
                            }
                        }
                    }
                    bus.write_word(0x0A60, 0);
                } else {
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // SizeResource ($A9A5)
            // Returns the size (in bytes) of a resource in the resource file.
            // FUNCTION SizeResource(theResource: Handle): LONGINT;
            // Inside Macintosh Volume I, I-121
            //
            // Both paths must update ResErr: success → noErr, failure →
            // resNotFound. Before this fix the success path left ResErr
            // untouched, so a caller that ran a successful SizeResource
            // after an earlier failed Resource Manager call would see a
            // stale -192.
            //
            // SizeResource ($A9A5): Returns data size; clears ResErr on success per IM:I I-121
            (true, 0x1A5) => self.handle_resource_size_query(bus, cpu),

            // RGetResource ($A80C)
            // GetResource that includes ROM-resident resources in the
            // search.
            // FUNCTION RGetResource(theType: ResType; theID: INTEGER): Handle;
            // Inside Macintosh: More Macintosh Toolbox 1993, 1-78
            // (also Inside Macintosh Volume V, V-159)
            //
            // IM:MTb 1-78: "RGetResource first uses GetResource to
            // search [the chain]. [...] If GetResource doesn't find
            // the specified resource [...] RGetResource sets the
            // global variable RomMapInsert to TRUE, then calls
            // GetResource again. In response, GetResource [...]
            // looks in the resource map of the ROM-resident resources
            // before searching the resource map of the System file."
            //
            // Systemless's HLE has no ROM resource fork, so the second
            // pass would walk an empty ROM map and produce the same
            // NIL. Delegate the entire call to GetResource ($A9A0).
            // The RomMapInsert global is documented as auto-cleared
            // per call; since no other Systemless trap consumes it,
            // modelling it would be cosmetic — skip.
            //
            // Stack frame is identical to GetResource:
            //   pre:  SP -> [theID(2)][theType(4)][result-slot(4)]
            //   post: SP -> [result(4)]; pop 6, leave 4.
            //
            // Regression coverage:
            //   rgetresource_returns_handle_for_open_chain_match
            //   rgetresource_miss_returns_nil_with_resnotfound
            //   rgetresource_walks_chain_not_just_current_file
            // RGetResource ($A80C): Reuses GetResource for the resource-chain
            // search. Systemless HLE has no ROM resource fork to retry, so a
            // NIL result is the final miss and keeps RGetResource's documented
            // resNotFound result separate from plain GetResource's Basilisk
            // NIL/noErr miss behavior.
            (true, 0x00C) => {
                let sp = cpu.read_reg(Register::A7);
                match self.dispatch_resource(true, 0x1A0, cpu, bus) {
                    Some(Ok(())) => {}
                    Some(Err(err)) => return Some(Err(err)),
                    None => return None,
                }
                if bus.read_long(sp + 6) == 0 {
                    cpu.write_reg(Register::D0, Self::RES_NOT_FOUND as i32 as u32);
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                Ok(())
            }

            // GetResFileAttrs ($A9F6)
            // Returns the resource-map-level attribute INTEGER for an
            // open resource file.
            // FUNCTION GetResFileAttrs(refNum: INTEGER): INTEGER;
            // Inside Macintosh Volume I, I-126
            //
            // IM:I-126: "If there's no resource file with the given
            // reference number, GetResFileAttrs will do nothing and
            // the ResError function will return the result code
            // resFNotFound." — the result slot is left untouched on
            // the error path (caller's pre-call value preserved).
            //
            // Stack frame:
            //   pre:  SP -> [refNum(2)][result-slot(2)]
            //   post: SP -> [result(2)]; pop 2 leaves 2.
            //
            // GetResFileAttrs ($A9F6): Returns the documented resource-map
            // attribute bits (mapReadOnly/mapCompact/mapChanged) per IM:I-126;
            // resFNotFound on missing refnum, result slot untouched on error path.
            (true, 0x1F6) => {
                let sp = cpu.read_reg(Register::A7);
                let refnum = bus.read_word(sp);

                let attrs_opt = self
                    .resources
                    .as_ref()
                    .and_then(|resources| resources.files.get(&refnum))
                    .map(|file| file.map_attrs);

                match attrs_opt {
                    Some(attrs) => {
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        bus.write_word(sp + 2, attrs & 0x00E0);
                    }
                    None => {
                        bus.write_word(0x0A60, (-193i16) as u16); // resFNotFound
                    }
                }
                cpu.write_reg(Register::A7, sp + 2);
                Ok(())
            }

            // SetResFileAttrs ($A9F7)
            // Sets the resource-map-level attribute INTEGER for an
            // open resource file.
            // PROCEDURE SetResFileAttrs(refNum: INTEGER; attrs: INTEGER);
            // Inside Macintosh Volume I, I-126
            //
            // IM:I-126: "If there's no resource file with the given
            // reference number, SetResFileAttrs will do nothing but
            // the ResError function will return the result code
            // noErr." — the only Resource Manager error path that
            // resolves to noErr instead of a -19x code, and the IM
            // wording is verbatim. Real-Mac BasiliskII confirms.
            //
            // Stack frame (Pascal — refNum pushed first, deepest):
            //   pre:  SP -> [attrs(2)][refNum(2)]
            //   post: SP -> (args popped, A7 = pre + 4)
            //
            // SetResFileAttrs ($A9F7): Stores only the documented
            // resource-map attribute bits (mapReadOnly/mapCompact/mapChanged)
            // per IM:I-126; missing refnum is a documented no-op that
            // returns noErr (not resFNotFound — IM verbatim).
            (true, 0x1F7) => {
                let sp = cpu.read_reg(Register::A7);
                let attrs = bus.read_word(sp);
                let refnum = bus.read_word(sp + 2);

                self.with_resource_manager_mut(|resource_manager| {
                    if let Some(file) = resource_manager
                        .resources
                        .as_mut()
                        .and_then(|resources| resources.files.get_mut(&refnum))
                    {
                        file.map_attrs = attrs & 0x00E0;
                    }
                });
                // Both branches set ResErr to noErr per IM:I-126.
                bus.write_word(0x0A60, 0);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // MaxSizeRsrc ($A821)
            // Returns the resource size from the resource map without
            // reading from disk.
            // FUNCTION MaxSizeRsrc(theResource: Handle): LONGINT;
            // Inside Macintosh Volume IV, IV-16
            //
            // IM:IV-16: "MaxSizeRsrc is similar to SizeResource except
            // that it does not cause the disk to be read; instead it
            // determines the size (in bytes) of the resource from the
            // offsets found in the resource map." In Systemless's HLE
            // every resource we know about is already resolved to a
            // guest-bus pointer (no offline-fork distinction), so the
            // disk-vs-map nuance collapses and the two traps share an
            // implementation. A future on-disk simulation would need to
            // reintroduce the disk-vs-map distinction.
            //
            // Regression coverage:
            //   maxsizersrc_returns_resource_size_for_loaded_resource_handle
            //   maxsizersrc_returns_minus_one_and_sets_resnotfound_for_non_resource_handle
            //   maxsizersrc_consumes_handle_argument_and_writes_function_result_slot
            // MaxSizeRsrc ($A821): Returns resource size from map without disk read per IM:IV-16. In our memory-resident HLE this collapses to the same data path as SizeResource ($A9A5).
            (true, 0x021) => self.handle_resource_size_query(bus, cpu),

            // ResourceDispatch ($A822) — partial-resource family
            // PROCEDURE ReadPartialResource (theResource: Handle;
            //     offset: LongInt; buffer: UNIV Ptr; count: LongInt);
            // PROCEDURE WritePartialResource(theResource: Handle;
            //     offset: LongInt; buffer: UNIV Ptr; count: LongInt);
            // PROCEDURE SetResourceSize    (theResource: Handle;
            //     newSize: LongInt);
            // Inside Macintosh: More Macintosh Toolbox 1993, 1-69 .. 1-71
            // Inside Macintosh Volume VI 1991, p. C-27 (selector table)
            //
            // IM:VI lists the D0 values as $0001/$0002/$0003. MMTB
            // prints $7001/$7002/$7003, which Universal Interfaces 3.4
            // confirms are complete MOVEQ opcodes preceding $A822, not
            // alternate D0 values. Runtime identity therefore uses 1--3.
            // The semantic handler retains its existing low-byte behavior
            // for compatibility, without attributing noncanonical values to
            // a generated operation.
            //
            // The Mac maintains a disk/memory dichotomy that makes
            // the partial-resource workflow non-trivial there: a
            // typical caller does SetResLoad(FALSE) so GetResource
            // returns an empty handle, then uses the partial routines
            // to stream data in/out of disk. Systemless's HLE has no
            // separate disk fork — every loaded resource is a real
            // guest-bus allocation — so all three traps act on the
            // in-memory copy directly. ReadPartialResource is
            // therefore byte-for-byte equivalent to a BlockMove from
            // (*handle + offset). WritePartialResource is a BlockMove
            // in the opposite direction; if the write would extend
            // past the current resource, MMTB 1-70 says the Resource
            // Manager grows the resource and returns the diagnostic
            // result code writingPastEnd (-189). SetResourceSize
            // resizes the in-memory allocation and returns noErr —
            // MMTB's documented `resourceInMemory` (-188) success
            // code is a real-Mac quirk that signals "disk size
            // updated, memory unchanged"; reporting it here would
            // break callers that treat any non-zero ResErr as a
            // failure when the operation actually succeeded.
            //
            // ResourceDispatch ($A822)
            // Reads, writes, or resizes part of a memory-resident resource.
            // D0: selector; stack: routine parameters; ResErr: result code.
            // More Macintosh Toolbox (1993), pp. 1-111 to 1-115.
            (true, 0x022) => {
                let sp = cpu.read_reg(Register::A7);
                let selector = cpu.read_reg(Register::D0);
                let operation = resource_dispatch_operation_route(self.current_trap_word, selector);
                self.current_selector_operation = operation.map(|route| route.operation_id);
                let routine = (selector & 0xFF) as u8;
                match routine {
                    // ResourceDispatch selector 0 ($A822)
                    // Returns the resource-map handle for a file reference number.
                    // This private selector is used by native System 7 code;
                    // map handles and the refnum in each map are described in Inside
                    // Macintosh Volume I (1985), pp. I-126 to I-127, and More
                    // Macintosh Toolbox (1993), p. 1-147.
                    0x00 if selector == 0 => {
                        let refnum = bus.read_word(sp);
                        let app_refnum = bus.read_word(crate::memory::globals::addr::CUR_APREF_NUM);
                        let mut handle = bus.read_long(0x0A50); // TopMapHndl
                        let mut found = 0;
                        for _ in 0..64 {
                            if handle == 0 { break; }
                            let map = bus.read_long(handle);
                            if map == 0 { break; }
                            if bus.read_word(map + 20) == refnum
                                || (refnum == app_refnum && bus.read_word(map + 20) == 0)
                            {
                                found = handle;
                                break;
                            }
                            handle = bus.read_long(map + 16);
                        }
                        bus.write_long(sp + 2, found);
                        bus.write_word(0x0A60, if found == 0 { Self::RES_NOT_FOUND as u16 } else { 0 });
                        cpu.write_reg(Register::A7, sp + 2);
                    }
                    // ReadPartialResource (selector 1) — 16 bytes args
                    // SP+12 theResource | SP+8 offset | SP+4 buffer | SP+0 count
                    0x01 => {
                        let count = bus.read_long(sp) as i32;
                        let buffer = bus.read_long(sp + 4);
                        let offset = bus.read_long(sp + 8) as i32;
                        let handle = bus.read_long(sp + 12);

                        let res_err =
                            self.read_partial_resource(bus, handle, offset, buffer, count);
                        bus.write_word(0x0A60, res_err as u16);
                        cpu.write_reg(Register::A7, sp + 16);
                    }
                    // WritePartialResource (selector 2) — 16 bytes args
                    // SP+12 theResource | SP+8 offset | SP+4 buffer | SP+0 count
                    0x02 => {
                        let count = bus.read_long(sp) as i32;
                        let buffer = bus.read_long(sp + 4);
                        let offset = bus.read_long(sp + 8) as i32;
                        let handle = bus.read_long(sp + 12);

                        let res_err =
                            self.write_partial_resource(bus, handle, offset, buffer, count);
                        bus.write_word(0x0A60, res_err as u16);
                        cpu.write_reg(Register::A7, sp + 16);
                    }
                    // SetResourceSize (selector 3) — 8 bytes args
                    // SP+4 theResource | SP+0 newSize
                    0x03 => {
                        let new_size = bus.read_long(sp) as i32;
                        let handle = bus.read_long(sp + 4);

                        let res_err = self.set_resource_size(bus, handle, new_size);
                        bus.write_word(0x0A60, res_err as u16);
                        cpu.write_reg(Register::A7, sp + 8);
                    }
                    _ => {
                        eprintln!(
                            "[TRAP] ResourceDispatch unknown selector ${:04X} (low byte ${:02X})",
                            cpu.read_reg(Register::D0) & 0xFFFF,
                            routine
                        );
                        // Per the unknown-selector convention used by
                        // DialogDispatch, we leave SP unchanged and set
                        // resNotFound so the caller surfaces the miss.
                        bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                    }
                }
                Ok(())
            }

            // ResError ($A9AF)
            // Returns the result code from the most recent Resource Manager call.
            // FUNCTION ResError: INTEGER;
            // Inside Macintosh Volume I, I-118
            // ResError ($A9AF): Returns last resource error from D0
            (true, 0x1AF) => {
                let sp = cpu.read_reg(Register::A7);
                let res_err = bus.read_word(0x0A60) as i16;
                let pc = cpu.read_reg(Register::PC);
                eprintln!("[TRAP] ResError -> {} (PC=${:08X})", res_err, pc);
                bus.write_word(sp, res_err as u16);
                Ok(())
            }

            // Get1NamedResource ($A820)
            // Returns a handle to the named resource of the given type in the current resource file.
            // FUNCTION Get1NamedResource(theType: ResType; name: Str255): Handle;
            // Inside Macintosh Volume VI, VI-13
            //
            // More Macintosh Toolbox 1993, 1-77--1-78 documents NIL with
            // noErr for an absent type. A Mac OS 8.1 fixture instead returns
            // resNotFound for both an absent type and a missing resource of
            // a present type.
            (true, 0x020) => {
                let sp = cpu.read_reg(Register::A7);
                let name_ptr = bus.read_long(sp);
                let raw_res_type = bus.read_long(sp + 4).to_be_bytes();
                let res_type = super::TrapDispatcher::normalize_ostype(raw_res_type);
                let type_str = std::str::from_utf8(&res_type).unwrap_or("????");
                // Read Pascal string name
                let name_len = bus.read_byte(name_ptr) as usize;
                let mut name_bytes = vec![0u8; name_len];
                for (i, byte) in name_bytes.iter_mut().enumerate() {
                    *byte = bus.read_byte(name_ptr + 1 + i as u32);
                }
                let name = String::from_utf8_lossy(&name_bytes).to_string();
                eprintln!("[TRAP] Get1NamedResource('{}', \"{}\")", type_str, name);

                // Look up by (type, name) in the named resources index
                let handle = self
                    .find_named_resource_current_loaded(bus, res_type, &name)
                    .map(|(refnum, id, ptr)| {
                        self.get_or_create_resource_handle_in_file(bus, res_type, id, ptr, refnum)
                    });

                if let Some(h) = handle {
                    eprintln!("[TRAP] Get1NamedResource -> handle ${:08X}", h);
                    cpu.write_reg(Register::A0, h);
                    bus.write_long(sp + 8, h);
                    cpu.write_reg(Register::A7, sp + 8);
                    cpu.write_reg(Register::D0, 0);
                    bus.write_word(0x0A60, 0); // ResErr = noErr
                } else {
                    eprintln!("[TRAP] Get1NamedResource -> NULL (not found)");
                    cpu.write_reg(Register::A0, 0);
                    bus.write_long(sp + 8, 0);
                    cpu.write_reg(Register::A7, sp + 8);
                    cpu.write_reg(Register::D0, 0);
                    bus.write_word(0x0A60, RES_NOT_FOUND_ERR as u16);
                }
                Ok(())
            }

            // CurResFile ($A994)
            // Returns the file reference number of the current resource file.
            // FUNCTION CurResFile: INTEGER;
            // Inside Macintosh Volume I, I-116
            // CurResFile ($A994): Returns the current resource-file refnum from the live Resource Manager search state
            (true, 0x194) => {
                let sp = cpu.read_reg(Register::A7);
                let internal_refnum = self.current_resource_refnum();
                // The initial application resource map uses internal key 0,
                // while CurApRefNum stores its guest-visible FCB refnum.
                // CurResFile reports the latter. Inside Macintosh Volume I,
                // p. I-116.
                let refnum = if internal_refnum == 0 {
                    bus.read_word(addr::CUR_APREF_NUM)
                } else {
                    internal_refnum
                };
                if super::dispatch::trace_resfile_enabled() {
                    eprintln!(
                        "[TRAP] CurResFile -> {} (PC=${:08X})",
                        refnum,
                        cpu.read_reg(Register::PC)
                    );
                }
                bus.write_word(sp, refnum);
                Ok(())
            }

            // HomeResFile ($A9A4)
            // Returns the file reference number of the resource file containing the resource.
            // FUNCTION HomeResFile(theResource: Handle): INTEGER;
            // Inside Macintosh Volume I, I-117
            //
            // Regression coverage:
            //   src/trap/resource.rs::tests::home_res_file_returns_loaded_resource_refnum
            //   src/trap/resource.rs::tests::home_res_file_returns_minus_one_for_detached_handle
            //   src/trap/resource.rs::tests::home_res_file_returns_minus_one_for_unknown_handle
            // HomeResFile ($A9A4): Returns the owning resource-file refnum for live resource handles; detached or unknown handles return `-1` and `resNotFound`
            (true, 0x1A4) => {
                let sp = cpu.read_reg(Register::A7);
                let handle = bus.read_long(sp);
                let new_sp = sp + 4;
                cpu.write_reg(Register::A7, new_sp);
                if self.loaded_handles.contains_key(&handle) {
                    let internal_refnum = self
                        .resource_handle_files
                        .get(&handle)
                        .copied()
                        .unwrap_or(0);
                    // The initial application resource map is stored under
                    // internal key 0, while the guest-visible resource fork
                    // has the FCB refnum recorded in CurApRefNum (normally 2).
                    // HomeResFile must return the actual file refnum, not the
                    // Resource Manager's internal key. Inside Macintosh
                    // Volume I, p. I-117.
                    let refnum = if internal_refnum == 0 {
                        bus.read_word(addr::CUR_APREF_NUM)
                    } else {
                        internal_refnum
                    };
                    bus.write_word(new_sp, refnum);
                    bus.write_word(0x0A60, 0);
                } else {
                    bus.write_word(new_sp, (-1i16) as u16);
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                Ok(())
            }

            // LoadSeg ($A9F0)
            // Loads a CODE segment and patches its jump table entries.
            // Inside Macintosh Volume II, II-60; Executor segment.cpp C_LoadSeg
            //
            // Two JT entry formats are supported:
            //
            // 1. Standard MPW format (Inside Macintosh Volume II, II-60):
            //    Unloaded: [offset(2), 3F3C(2), seg#(2), A9F0(2)]
            //    Loaded:   [seg#(2),   4EF9(2), address(4)       ]
            //    Calls enter at entry+2. LoadSeg seg# pushed on stack by MOVE.W.
            //
            // 2. Think C / CodeWarrior format (Processes 1994, 7-7 note):
            //    Unloaded: [A9F0(2), 0000(2), offset(2), seg#(2)]
            //    Loaded:   [seg#(2), 4EF9(2), address(4)        ]
            //    Calls enter at entry+0. No MOVE.W; seg# read from JT entry.
            //    The word popped from stack is the high word of the JSR return
            //    address, not the actual segment number.
            //
            // Regression coverage:
            //   resource::tests::loadseg_mpw_call_consumes_segment_number_word_argument
            //   resource::tests::loadseg_patches_calling_jump_table_entry_to_jmp_loaded_code
            // LoadSeg ($A9F0): Loads CODE resource, caches in segment_map
            (true, 0x1F0) => {
                let sp = cpu.read_reg(Register::A7);
                let pc = cpu.read_reg(Register::PC); // past A9F0
                let a9f0_addr = pc.wrapping_sub(2);

                let is_loadseg_trampoline = bus
                    .system_trap_gateway(0xA9F0)
                    .is_some_and(|addr| addr == a9f0_addr);

                let auto_pop_old_trap = (self.current_trap_word & 0x0400) != 0;
                let original_trap_return = self.current_trap_caller;
                let native_call = (is_loadseg_trampoline && auto_pop_old_trap)
                    .then(|| self.take_latest_native_trap_call(0xA9F0))
                    .flatten();

                // Detect format: in standard format, [A9F0-4] = 3F3C (MOVE.W).
                // In Think C format, A9F0 is at entry+0 and [A9F0+2] = 0x0000.
                //
                // Native LoadSeg handlers save the previous trap address via
                // GetTrapAddress and later jump to its auto-pop form (e.g.
                // $ADF0). The dispatcher records the original A-line return
                // PC and argument SP before entering any installed handler,
                // so recovery does not depend on that handler's stack frame.
                let old_trap_standard = auto_pop_old_trap
                    && original_trap_return.is_some_and(|return_pc| {
                        bus.read_word(return_pc.wrapping_sub(6)) == 0x3F3C
                            && (bus.read_word(return_pc.wrapping_sub(2)) & !0x0400u16) == 0xA9F0
                    });
                let old_trap_think = auto_pop_old_trap
                    && !old_trap_standard
                    && original_trap_return.is_some_and(|return_pc| {
                        let trap_addr = return_pc.wrapping_sub(2);
                        (bus.read_word(trap_addr) & !0x0400u16) == 0xA9F0
                            && bus.read_word(trap_addr + 2) == 0x0000
                    });
                let native_old_trap_standard = native_call.as_ref().is_some_and(|call| {
                    bus.read_word(call.return_pc.wrapping_sub(6)) == 0x3F3C
                        && (bus.read_word(call.return_pc.wrapping_sub(2)) & !0x0400u16) == 0xA9F0
                });
                let native_old_trap_think = native_call.as_ref().is_some_and(|call| {
                    let trap_addr = call.return_pc.wrapping_sub(2);
                    (bus.read_word(trap_addr) & !0x0400u16) == 0xA9F0
                        && bus.read_word(trap_addr + 2) == 0x0000
                });

                let word_before_seg = bus.read_word(a9f0_addr.wrapping_sub(4));
                let is_standard = old_trap_standard || word_before_seg == 0x3F3C;

                let direct_saved_gateway = is_loadseg_trampoline
                    && auto_pop_old_trap
                    && native_call.is_none()
                    && !old_trap_standard
                    && !old_trap_think;
                let saved_gateway_reentry = direct_saved_gateway
                    .then(|| bus.read_long(sp.wrapping_sub(4)).wrapping_sub(6));

                let (seg_num, entry_addr, fmt, refresh_from_resource) = if native_old_trap_standard
                {
                    let call = native_call.as_ref().unwrap();
                    let sn = bus.read_word(call.argument_sp) as i16;
                    cpu.write_reg(Register::A7, call.argument_sp.wrapping_add(2));
                    Self::restore_native_toolbox_nonvolatile(cpu, call);
                    (
                        sn,
                        Some(call.return_pc.wrapping_sub(8)),
                        "mpw-native-oldtrap",
                        true,
                    )
                } else if native_old_trap_think {
                    let call = native_call.as_ref().unwrap();
                    let entry = call.return_pc.wrapping_sub(2);
                    let sn = bus.read_word(entry + 6) as i16;
                    cpu.write_reg(Register::A7, call.argument_sp);
                    Self::restore_native_toolbox_nonvolatile(cpu, call);
                    (sn, Some(entry), "thinkc-native-oldtrap", true)
                } else if old_trap_standard {
                    let return_pc = original_trap_return.unwrap();
                    let sn = bus.read_word(sp) as i16;
                    cpu.write_reg(Register::A7, sp + 2);
                    (sn, Some(return_pc.wrapping_sub(8)), "mpw-oldtrap", true)
                } else if old_trap_think {
                    let return_pc = original_trap_return.unwrap();
                    let entry = return_pc.wrapping_sub(2);
                    let sn = bus.read_word(entry + 6) as i16;
                    (sn, Some(entry), "thinkc-oldtrap", true)
                } else if direct_saved_gateway {
                    // A caller can push a synthetic return PC and segment
                    // argument, then JMP through a saved auto-pop gateway.
                    // The six preceding bytes are the dispatch sequence to
                    // re-execute after loading. Inside Macintosh Volume II,
                    // II-60, describes the same six-byte LoadSeg re-entry.
                    let sn = bus.read_word(sp) as i16;
                    cpu.write_reg(Register::A7, sp + 2);
                    (sn, None, "saved-gateway", false)
                } else if is_standard {
                    // Standard: seg# was pushed by MOVE.W, pop it
                    let sn = bus.read_word(sp) as i16;
                    cpu.write_reg(Register::A7, sp + 2);
                    // Entry starts 6 bytes before A9F0
                    (sn, Some(a9f0_addr.wrapping_sub(6)), "mpw", false)
                } else {
                    // Think C: A9F0 at entry+0, seg# at entry+6, offset at entry+4
                    // Stack has JSR return address (don't pop segment number)
                    let entry = a9f0_addr; // A9F0 IS entry+0
                    let sn = bus.read_word(entry + 6) as i16;
                    (sn, Some(entry), "thinkc", false)
                };

                let trace_loadseg = trace_loadseg_enabled();
                if trace_loadseg {
                    if let Some(entry_addr) = entry_addr {
                        eprintln!(
                            "[TRAP] LoadSeg(seg={}, fmt={}) entry=${:08X}",
                            seg_num, fmt, entry_addr
                        );
                    } else {
                        eprintln!("[TRAP] LoadSeg(seg={}, fmt={}) entry=none", seg_num, fmt);
                    }
                }

                if refresh_from_resource {
                    self.preserve_auto_pop_pc_once = auto_pop_old_trap;
                    self.finish_loadseg(bus, cpu, seg_num, entry_addr, true)
                } else if let Some(entry_addr) = entry_addr {
                    if self.maybe_inject_native_getresource_for_loadseg(
                        bus,
                        cpu,
                        seg_num,
                        entry_addr,
                        trace_loadseg,
                    ) {
                        Ok(())
                    } else {
                        self.finish_loadseg(bus, cpu, seg_num, Some(entry_addr), false)
                    }
                } else {
                    let result = self.finish_loadseg(bus, cpu, seg_num, None, false);
                    if result.is_ok() {
                        if let Some(reentry) = saved_gateway_reentry {
                            self.preserve_auto_pop_pc_once = true;
                            cpu.write_reg(Register::PC, reentry);
                        }
                    }
                    result
                }
            }

            // GetResInfo ($A9A8)
            // Returns the resource ID, type, and name for a resource-backed handle.
            // PROCEDURE GetResInfo (theResource: Handle; VAR theID: Integer;
            //     VAR theType: ResType; VAR name: Str255);
            // More Macintosh Toolbox 1993, 1-81 to 1-82
            // GetResInfo ($A9A8): Pops 16 bytes; returns resource ID, type, and Pascal name for resource-backed handles
            (true, 0x1A8) => {
                let sp = cpu.read_reg(Register::A7);
                let name_ptr = bus.read_long(sp);
                let type_ptr = bus.read_long(sp + 4);
                let id_ptr = bus.read_long(sp + 8);
                let handle = bus.read_long(sp + 12);

                if let Some((res_type, res_id, name)) = self.resource_metadata_for_handle(handle) {
                    if id_ptr != 0 {
                        bus.write_word(id_ptr, res_id as u16);
                    }
                    if type_ptr != 0 {
                        bus.write_long(type_ptr, u32::from_be_bytes(res_type));
                    }
                    if name_ptr != 0 {
                        bus.write_pstring(name_ptr, name.as_deref().unwrap_or("").as_bytes());
                    }
                    bus.write_word(0x0A60, 0);
                } else {
                    bus.write_word(0x0A60, (-192i16) as u16);
                }

                cpu.write_reg(Register::A7, sp + 16);
                Ok(())
            }

            // GetResAttrs ($A9A6)
            // Returns the resource attributes for a live resource handle.
            // FUNCTION GetResAttrs(theResource: Handle): INTEGER;
            // Inside Macintosh Volume I, I-121
            //
            // Regression coverage:
            //   tests::get_res_attrs_returns_attribute_bits_for_live_resource_handle
            //   tests::get_res_attrs_returns_res_changed_for_unknown_handle
            // GetResAttrs ($A9A6): Returns resource-map attribute bits for live resource handles; non-resource handles report `resChanged` and set `resNotFound`
            (true, 0x1A6) => {
                let sp = cpu.read_reg(Register::A7);
                let handle = bus.read_long(sp);
                if let Some(attrs) = self.resource_attributes_for_handle(handle) {
                    bus.write_word(sp + 4, attrs);
                    bus.write_word(0x0A60, 0);
                } else {
                    bus.write_word(sp + 4, Self::RES_CHANGED_ATTR);
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // InitPack ($A9E5)
            // PROCEDURE InitPack(packID: INTEGER);
            // Inside Macintosh Volume I, I-483
            // Prior implementation lumped this with TECut as a shared Ok(()) and
            // silently left the 2-byte packID on the stack — latent bug.
            // InitPack ($A9E5): Pops 2-byte packID and returns per IM:I I-483.
            // Per-package loading (Floating Point, Math, etc.) is not modelled;
            // Systemless keeps the call as a no-op but records the last pack ID so
            // future pack-specific heuristics have a cheap hook.
            // Note: CountTypes / Count1Types live at `$A99E` (Toolbox, `0x19E`),
            // not `$A9E5`.
            (true, 0x1E5) => {
                let sp = cpu.read_reg(Register::A7);
                self.last_init_pack_id = Some(bus.read_word(sp) as i16);
                cpu.write_reg(Register::A7, sp + 2);
                Ok(())
            }

            // TECut ($A9D6) is handled in dispatch_dialog because it needs
            // the TERec accessors. Leaving the arm out here lets the
            // dispatch chain fall through to dispatch_dialog.
            // NOTE: DisposePalette ($AA93, 0x293) is handled by the Palette
            // Manager in quickdraw.rs.
            // NOTE: PutScrap ($A9FE, 0x1FE) moved to toolbox.rs Scrap Manager.

            // ========== Script Manager phantom-trap arms ==========
            //
            // $AA87 GetScript / $AA88 SetScript / $AA89 GetEnvirons
            // are PHANTOM TRAP WORDS: per IM:VI Table C-1 master
            // trap dispatch table + IM:V V-291 master trap
            // dispatch table, the trap-word range $AA87..$AA89 is
            // NOT allocated to any documented Apple trap (the
            // documented range goes ... $AA52 _HighLevelFSDispatch
            // ... $AA90 _InitPalettes ... with a gap covering
            // $AA53..$AA8F that includes our three phantom arms
            // — verified via `grep -nE "AA8[7-9]\b"
            // systemless-inside-macintosh-md/` returning zero matches
            // in the master dispatch tables).
            //
            // The canonical Script Manager dispatch is via
            // $A8B5 _ScriptUtil (a selector-based dispatcher
            // already implemented at quickdraw.rs:5903 with
            // selectors 0..22 covering FontScript, IntlScript,
            // KeyScript, Font2Script, GetEnvirons, SetEnvirons,
            // GetScript, SetScript, CharByte, CharType,
            // Char2Pixel etc.) — apps using MPW Pascal call
            // `GetScript(script, selector)` which the compiler
            // expands to `_ScriptUtil` ($A8B5) with D0 set to
            // the GetScript selector (4 per IM:VI 14-23 + Text
            // 1993 6-11). There is no separate $AA87 trap-word
            // dispatch on real Mac.
            //
            // ## Why these phantom arms exist in Systemless
            //
            // Some 68k binaries (especially older System-6 or
            // System-7 .0 era apps that linked against
            // pre-Universal-Headers MPW glue) emit $AA87 / $AA88
            // / $AA89 directly as a courtesy to the kernel's
            // dispatch table (Apple kept many such word-aliases
            // allocated for binary compatibility). On real Mac
            // these would either land on the unimplemented-trap
            // handler ($A89F) or on a glue-layer hook. Systemless's
            // arms collapse them to noErr / 0 / no-op so apps
            // don't crash.
            //
            // ## Stack frames (best-effort, no IM cite)
            //
            // - $AA87 GetScript: 6 args (script INTEGER + selector
            //   INTEGER) + 2 result. Pop 6. Returns 0 INTEGER as
            //   "script not installed" sentinel per IM:VI 14-29
            //   GetScript-via-ScriptUtil "Returns 0 if the script
            //   isn't installed".
            // - $AA88 SetScript: 6 args (script INTEGER + selector
            //   INTEGER + value INTEGER), no result. Pop 6.
            // - $AA89 GetEnvirons: 4 args (selector INTEGER) + 2
            //   result. Pop 6 = 4 args + 2 result-slot? Actually
            //   the existing impl pops 2 args + 2 result writeback
            //   = 4-byte total stack window. Wait, current pop is
            //   sp+2 which is 2 bytes — `bus.write_word(sp+2, 0);
            //   cpu.write_reg(Register::A7, sp+2)`. That's pop=2
            //   on a frame that the trap-doc claims is "Pops 6
            //   bytes". Trap-doc lies; existing impl correctly
            //   pops 2 + writes 2 result. The 6 in the trap-doc
            //   is the FRAME WINDOW (2 args + 2 result + 2 slack
            //   pre-pollution?) not the pop count.
            //
            // ## Manager classification corrected
            //
            // Was "Resource Manager — Toolbox Traps" (an artifact
            // of where the arm landed in dispatch_resource).
            // Per the manager-classification audit pattern: the
            // canonical manager is whatever IM
            // chapter heading the trap is documented under, NOT
            // what dispatch arm it lands in. Per IM:VI 14-1
            // "Script Manager" chapter heading + Text 1993 6-1
            // "Script Manager" chapter, the canonical manager
            // for these phantom GetScript/SetScript/GetEnvirons
            // aliases is Script Manager (even though they're
            // phantom — the IM-documented routine names live in
            // the Script Manager chapter).

            // GetScript ($AA87)
            // PHANTOM trap-word — see Script Manager phantom-trap
            // family rationale block above. Arm matches the
            // ScriptUtil ($A8B5) selector-4 GetScript behaviour
            // exactly: returns 0 INTEGER as "script not installed"
            // sentinel per IM:VI 14-29 (the ScriptUtil-GetScript
            // selector documents this fallback).
            // GetScript ($AA87): Phantom trap word — verified absent from IM:VI Table C-1 + IM:V V-291 master dispatch tables. Stack: SP+0 selector(2), SP+2 script(2), SP+4 result(2). Pops 4 + writes 0 INTEGER to result slot (pre-pop SP+4) per IM:VI 14-29 ScriptUtil-GetScript "Returns 0 if the script isn't installed" fallback. Canonical dispatch is via $A8B5 _ScriptUtil (selector 4) — apps that emit $AA87 directly are using non-public Apple-allocated word-aliases.
            (true, 0x287) => {
                // GetScript: FUNCTION (script, selector): Int
                // SP+0 selector(2), SP+2 script(2), SP+4 result(2).
                let sp = cpu.read_reg(Register::A7);
                bus.write_word(sp + 4, 0);
                cpu.write_reg(Register::A7, sp + 4);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // SetScript ($AA88)
            // PHANTOM trap-word — see Script Manager phantom-trap
            // family rationale block above. Arm matches the
            // ScriptUtil ($A8B5) selector-6 SetScript behaviour
            // (PROCEDURE no-op since Systemless doesn't maintain
            // per-script Manager state).
            // SetScript ($AA88): Phantom trap word — verified absent from IM:VI Table C-1 + IM:V V-291 master dispatch tables. Stack: SP+0 value(2), SP+2 selector(2), SP+4 script(2). Pops 6 PROCEDURE no-result per IM:VI 14-29 ScriptUtil-SetScript sig — Systemless doesn't maintain per-script-system local-variable state so the set is a no-op. Canonical dispatch is via $A8B5 _ScriptUtil (selector 6).
            (true, 0x288) => {
                // SetScript: PROCEDURE (script, selector, value). Pops 6.
                let sp = cpu.read_reg(Register::A7);
                cpu.write_reg(Register::A7, sp + 6);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // GetEnvirons ($AA89)
            // PHANTOM trap-word — see Script Manager phantom-trap
            // family rationale block above. Arm matches the
            // ScriptUtil ($A8B5) selector-4 GetEnvirons behaviour:
            // returns 0 INTEGER as "verb not recognised" sentinel
            // per IM:VI 14-30 ScriptUtil-GetEnvirons fallback.
            // Apps that probe `GetEnvirons(smVersion)` to detect
            // Script Manager version see 0 — they should fall
            // back to Gestalt('scri') which Systemless handles in
            // its main dispatcher.
            // GetEnvirons ($AA89): Phantom trap word — verified absent from IM:VI Table C-1 + IM:V V-291 master dispatch tables. Stack: SP+0 selector(2), SP+2 result(2). Pops 2 + writes 0 INTEGER to result slot per IM:VI 14-30 ScriptUtil-GetEnvirons "Returns 0 if the script isn't installed or the verb isn't recognized". Apps that probe smVersion via GetEnvirons see 0 → they fall back to Gestalt('scri'). Canonical dispatch is via $A8B5 _ScriptUtil (selector 4 — same selector index but "GetEnvirons" not "GetScript").
            (true, 0x289) => {
                // GetEnvirons: FUNCTION (selector): Int
                // SP+0 selector(2), SP+2 result(2).
                let sp = cpu.read_reg(Register::A7);
                bus.write_word(sp + 2, 0);
                cpu.write_reg(Register::A7, sp + 2);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }
            // ChangedResource ($A9AA)
            // Marks a resource as changed so its data and map entry will be
            // written to disk when the resource file is updated.
            // PROCEDURE ChangedResource(theResource: Handle);
            // Inside Macintosh Volume IV, p. IV-16
            //
            // Regression coverage:
            //   tests::changedresource_sets_reschanged_attribute_for_unprotected_resource
            //   tests::changedresource_protected_resource_is_noop_with_resattrerr
            // ChangedResource ($A9AA): Sets resChanged attribute on resource; resProtected returns resAttrErr per IM:IV IV-16 / MTB 1-88
            (true, 0x1AA) => {
                let sp = cpu.read_reg(Register::A7);
                let handle = bus.read_long(sp);
                if let Some((refnum, res_type, res_id)) = self.resource_record_for_handle(handle) {
                    let attrs = self.resource_attributes_for_handle(handle).unwrap_or(0);
                    // resProtected (bit 3) blocks the operation with resAttrErr
                    if (attrs & 0x0008) != 0 {
                        bus.write_word(0x0A60, Self::RES_ATTR_ERR as u16);
                    } else {
                        // Set the resChanged attribute (bit 1) on the resource
                        self.with_resource_manager_mut(|resource_manager| {
                            if let Some(resources) = resource_manager.resources.as_mut() {
                                if let Some(file) = resources.files.get_mut(&refnum) {
                                    let entry = file.attrs.entry((res_type, res_id)).or_insert(0);
                                    *entry |= Self::RES_CHANGED_ATTR as u8;
                                    file.map_attrs |= Self::RES_MAP_CHANGED_ATTR;
                                }
                            }
                        });
                        bus.write_word(0x0A60, 0); // noErr
                    }
                } else {
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // SetResInfo ($A9A9)
            // Changes the resource ID and name of a resource in the resource
            // map in memory. The change is not written to disk until the file
            // is updated (after ChangedResource is called).
            // PROCEDURE SetResInfo(theResource: Handle; theID: INTEGER; name: Str255);
            // Inside Macintosh Volume IV, p. IV-16
            //
            // Regression coverage:
            //   setresinfo_protected_resource_is_noop_with_resattrerr
            // SetResInfo ($A9A9): Updates resource ID and name in memory map; resProtected returns resAttrErr per IM:IV IV-16 / MTB 1-82
            (true, 0x1A9) => {
                let sp = cpu.read_reg(Register::A7);
                // Pascal LTR push order: theResource first (deepest), theID,
                // then name (shallowest, at SP+0).
                let name_ptr = bus.read_long(sp);
                let new_id = bus.read_word(sp + 4) as i16;
                let handle = bus.read_long(sp + 6);

                if let Some((refnum, res_type, old_id)) = self.resource_record_for_handle(handle) {
                    let attrs = self.resource_attributes_for_handle(handle).unwrap_or(0);
                    // resProtected (bit 3) blocks the operation with resAttrErr
                    if (attrs & 0x0008) != 0 {
                        bus.write_word(0x0A60, Self::RES_ATTR_ERR as u16);
                    } else {
                        let home_refnum = self.resource_handle_files.get(&handle).copied();
                        let new_name = (name_ptr != 0)
                            .then(|| bus.read_pstring(name_ptr))
                            .and_then(|bytes| String::from_utf8(bytes).ok())
                            .filter(|name| !name.is_empty());
                        let moved_data = self.with_resource_manager_mut(|resource_manager| {
                            // Update the resource ID in loaded_handles for the live
                            // home record only. System-reference shadow entries live
                            // in the current file's map and must not re-home the
                            // source handle.
                            if home_refnum == Some(refnum) {
                                if let Some(entry) = resource_manager.loaded_handles.get_mut(&handle)
                                {
                                    entry.2 = new_id;
                                }
                                if old_id != new_id {
                                    resource_manager
                                        .resource_handles_by_key
                                        .remove(&(refnum, res_type, old_id));
                                    resource_manager
                                        .resource_handles_by_key
                                        .insert((refnum, res_type, new_id), handle);
                                }
                            }
                            let moved_data = if old_id != new_id {
                                let data = resource_manager
                                    .resource_backing_data
                                    .remove(&(refnum, res_type, old_id));
                                if let Some(order) =
                                    resource_manager.resource_file_order.get_mut(&refnum)
                                {
                                    if let Some(key) =
                                        order.iter_mut().find(|key| **key == (res_type, old_id))
                                    {
                                        *key = (res_type, new_id);
                                    }
                                }
                                data
                            } else {
                                None
                            };

                            if let Some(resources) = resource_manager.resources.as_mut() {
                                if let Some(file) = resources.files.get_mut(&refnum) {
                                // Move the loaded entry from old_id to new_id
                                if let Some(ptr) = file.loaded.remove(&(res_type, old_id)) {
                                    file.loaded.insert((res_type, new_id), ptr);
                                }
                                // Move the attrs entry
                                if let Some(a) = file.attrs.remove(&(res_type, old_id)) {
                                    file.attrs.insert((res_type, new_id), a);
                                }
                                let old_name = file.names_by_id.remove(&(res_type, old_id));
                                // Update name if name_ptr != 0 (assembly-language note)
                                if let Some(name_str) = new_name {
                                    // Remove old named entry for this resource
                                    file.named.retain(|(t, _), (id, _)| {
                                        !(*t == res_type && *id == old_id)
                                    });
                                    let ptr_val = file
                                        .loaded
                                        .get(&(res_type, new_id))
                                        .copied()
                                        .unwrap_or(0);
                                    file.named.insert(
                                        (res_type, name_str.clone()),
                                        (new_id, ptr_val),
                                    );
                                    file.names_by_id.insert((res_type, new_id), name_str);
                                } else {
                                    if let Some(name_str) = old_name {
                                        file.names_by_id.insert((res_type, new_id), name_str);
                                    }
                                    // name_ptr == 0: update existing named entries to new ID
                                    for ((t, _), (id, _)) in file.named.iter_mut() {
                                        if *t == res_type && *id == old_id {
                                            *id = new_id;
                                        }
                                    }
                                }
                            }
                            }
                            moved_data
                        });
                        if let Some(data) = moved_data {
                            self.remember_resource_backing_data(refnum, res_type, new_id, data);
                        }
                        bus.write_word(0x0A60, 0); // noErr
                    }
                } else {
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                cpu.write_reg(Register::A7, sp + 10);
                Ok(())
            }

            // AddResource ($A9AB)
            // Adds a resource reference to the current resource file for data
            // already in memory. Sets the resChanged attribute so the data
            // will be written when the file is updated.
            // PROCEDURE AddResource(theData: Handle; theType: ResType;
            //   theID: INTEGER; name: Str255);
            // Inside Macintosh: More Macintosh Toolbox 1993, 1-90.
            //
            // Reference coverage:
            //   a9ab_addresource_reserror
            // AddResource ($A9AB): Adds data handle to current resource file with resChanged; validates NIL/existing handles per MMTB 1-90.
            (true, 0x1AB) => {
                let sp = cpu.read_reg(Register::A7);
                // Pascal pushes the last formal nearest SP:
                //   SP+0 name: Str255 pointer
                //   SP+4 theID: Integer
                //   SP+6 theType: ResType
                //   SP+10 theData: Handle
                let name_ptr = bus.read_long(sp);
                let res_id = bus.read_word(sp + 4) as i16;
                let res_type_raw = bus.read_long(sp + 6);
                let res_type = res_type_raw.to_be_bytes();
                let handle = bus.read_long(sp + 10);

                const ADD_RES_FAILED: i16 = -194;

                // Fail if handle is NIL or already a resource handle
                if handle == 0 || self.loaded_handles.contains_key(&handle) {
                    bus.write_word(0x0A60, ADD_RES_FAILED as u16);
                } else {
                    let ptr = bus.read_long(handle);
                    let refnum = self.current_resource_refnum();
                    let name = (name_ptr != 0)
                        .then(|| bus.read_pstring(name_ptr))
                        .and_then(|bytes| String::from_utf8(bytes).ok())
                        .filter(|name| !name.is_empty());
                    self.with_resource_manager_mut(|resource_manager| {
                        // Register in loaded_handles and resource_handle_files
                        resource_manager
                            .loaded_handles
                            .insert(handle, (ptr, res_type, res_id));
                        resource_manager.resource_handle_files.insert(handle, refnum);
                        resource_manager
                            .resource_handles_by_key
                            .insert((refnum, res_type, res_id), handle);

                        let mut added_to_file = false;
                        if let Some(resources) = resource_manager.resources.as_mut() {
                            if let Some(file) = resources.files.get_mut(&refnum) {
                                // Add to loaded map
                                file.loaded.insert((res_type, res_id), ptr);
                                added_to_file = true;
                                // Set resChanged attribute
                                let entry = file.attrs.entry((res_type, res_id)).or_insert(0);
                                *entry |= Self::RES_CHANGED_ATTR as u8;
                                file.map_attrs |= Self::RES_MAP_CHANGED_ATTR;

                                if let Some(name_str) = name {
                                    file.named
                                        .insert((res_type, name_str.clone()), (res_id, ptr));
                                    file.names_by_id.insert((res_type, res_id), name_str);
                                }
                            }
                        }
                        if added_to_file {
                            resource_manager
                                .resource_file_order
                                .entry(refnum)
                                .or_default()
                                .push((res_type, res_id));
                        }
                    });
                    self.remember_resource_handle_index(handle, refnum, res_type, res_id);
                    self.update_handle_state_bits(handle, |state| {
                        Some(state.unwrap_or(0x40) | 0x20)
                    });
                    if ptr != 0 {
                        if let Some(size) = bus.get_alloc_size(ptr) {
                            self.remember_resource_backing_data(
                                refnum,
                                res_type,
                                res_id,
                                bus.read_bytes(ptr, size as usize),
                            );
                        }
                    }
                    bus.write_word(0x0A60, 0); // noErr
                }
                cpu.write_reg(Register::A7, sp + 14);
                Ok(())
            }

            // AddReference ($A9AC)
            // PROCEDURE AddReference(theResource: Handle; theID: INTEGER;
            //                         name: Str255);
            // Public MPW trap declaration: `_AddReference = $A9AC`
            // (Resource Manager trap table / Traps.h).
            // Inside Macintosh: Promotional Edition (1985), Resource
            // Manager Programmer's Guide, "Modifying System References".
            //
            // Given a handle to a system resource, AddReference adds a
            // system reference to the current resource file, gives it the
            // supplied ID and name, and sets resChanged so the map will be
            // written out on update. That current-file system reference is
            // observable through GetResInfo / GetResAttrs on the source
            // handle while HomeResFile remains the system file. The
            // documented failure cases are:
            // - the current resource file is the system file,
            // - the handle is not a handle to a system resource,
            // - the current file already contains a system reference to the
            //   same resource.
            // ResError returns addRefFailed (-195) for these branches.
            //
            // Stack layout (Pascal left-to-right push order):
            //   SP+0  name pointer (Str255)
            //   SP+4  theID (INTEGER)
            //   SP+6  theResource (Handle)
            // Pops 10 bytes. No function result.
            (true, 0x1AC) => {
                let sp = cpu.read_reg(Register::A7);
                let name_ptr = bus.read_long(sp);
                let new_id = bus.read_word(sp + 4) as i16;
                let handle = bus.read_long(sp + 6);
                let _ = self.add_resource_reference(bus, handle, new_id, name_ptr);
                cpu.write_reg(Register::A7, sp + 10);
                Ok(())
            }

            // WriteResource ($A9B0)
            // Writes the resource data for the given resource to the resource
            // file on disk. Does nothing (returning noErr) when resProtected
            // is set or resChanged is not set. In Systemless's HLE, there is no
            // physical resource file to write to, so this is a contract-
            // conformant no-op that clears resChanged after "writing".
            // PROCEDURE WriteResource(theResource: Handle);
            // Inside Macintosh Volume I, I-124
            //
            // WriteResource ($A9B0): Respects resProtected/resChanged flags; clears resChanged after write per IM:I I-124
            (true, 0x1B0) => {
                let sp = cpu.read_reg(Register::A7);
                let handle = bus.read_long(sp);
                if self.live_resource_identity_for_handle(handle).is_some() {
                    let attrs = self.resource_attributes_for_handle(handle).unwrap_or(0);
                    // resProtected (bit 3): do nothing, return noErr
                    // resChanged not set (bit 1): do nothing, return noErr
                    if (attrs & 0x0008) != 0 || (attrs & Self::RES_CHANGED_ATTR) == 0 {
                        bus.write_word(0x0A60, 0);
                    } else {
                        if let Some((refnum, _, _)) = self.resource_record_for_handle(handle) {
                            let _ = self.flush_resource_file_refnum(bus, refnum);
                        }
                        let _ = self.write_resource_backing_if_changed(bus, handle);
                        bus.write_word(0x0A60, 0);
                    }
                } else {
                    bus.write_word(0x0A60, Self::RES_NOT_FOUND as u16);
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // CreateResFile ($A9B1)
            // PROCEDURE CreateResFile(fileName: Str255);
            // More Macintosh Toolbox (1993), pp. 1-57 and 1-66;
            // Inside Macintosh Volume I (1985), p. I-115.
            //
            // Semantics:
            // - Creates a zero-length data fork plus empty resource fork when
            //   no matching file exists in the OpenRF search namespace.
            // - If a data-fork file exists but has no resource fork, creates
            //   the empty resource fork.
            // - If a file already has a non-empty resource fork map, does
            //   nothing and reports dupFNErr via ResErr.
            // - If the data fork exists and the resource fork is present but
            //   zero-length, creates the empty resource map in place.
            // - Pop 4 bytes (fileName pointer), no function result.
            //
            // Systemless HLE models this with `vfs` (data fork) and `vfs_rsrc`
            // (resource fork). Search-path edge cases (root/System folder)
            // are collapsed to the normalized VFS namespace.
            (true, 0x1B1) => {
                let sp = cpu.read_reg(Register::A7);
                let name_ptr = bus.read_long(sp);
                let name = if name_ptr != 0 {
                    decode_mac_roman(&bus.read_pstring(name_ptr))
                } else {
                    String::new()
                };

                let res_err: i16 = if name.is_empty() {
                    -37 // bdNamErr
                } else {
                    let vfs_key = self
                        .find_vfs_rsrc_file(&name)
                        .or_else(|| self.find_vfs_file(&name))
                        .unwrap_or_else(|| super::TrapDispatcher::normalize_vfs_path(&name));
                    let existing_rsrc_has_map = self
                        .vfs_rsrc
                        .get(&vfs_key)
                        .map(|fork| !fork.is_empty())
                        .unwrap_or(false);
                    if self.vfs_path_is_read_only(&vfs_key) {
                        -44 // wPrErr
                    } else if existing_rsrc_has_map {
                        // MTb 1993 p. 1-57: existing resource fork with a
                        // resource map -> no-op + dupFNErr.
                        -48 // dupFNErr
                    } else {
                        // If a data fork already exists, add or initialise its
                        // zero-length resource fork map. Otherwise create both
                        // forks.
                        self.vfs.ensure_empty(vfs_key.clone());
                        self.vfs_rsrc
                            .insert(vfs_key.clone(), Self::empty_resource_fork_bytes());
                        self.touch_vfs_entry(&vfs_key);
                        if let Some(ref dir) = self.output_dir {
                            let host_path = dir.join(&vfs_key);
                            if let Some(parent) = host_path.parent() {
                                let _ = std::fs::create_dir_all(parent);
                            }
                            let _ = std::fs::write(host_path, []);
                        }
                        0 // noErr
                    }
                };

                bus.write_word(0x0A60, res_err as u16);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // SystemEvent ($A9B2)
            // Lets the Desk Manager handle an event or returns FALSE for application handling.
            // FUNCTION SystemEvent (theEvent: EventRecord): BOOLEAN;
            // Inside Macintosh Volume I (1985), pp. I-90--I-91 and I-442.
            (true, 0x1B2) => {
                let sp = cpu.read_reg(Register::A7);
                let event_ptr = bus.read_long(sp);
                let params = crate::desk_manager::evaluate_system_event_parameters(event_ptr);
                let result = if params.handled() { 1u16 } else { 0u16 };
                bus.write_word(sp + 4, result); // FALSE
                cpu.write_reg(Register::D0, 0);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // Gestalt family: _Gestalt ($A1AD), _NewGestalt ($A3AD),
            // _ReplaceGestalt ($A5AD). All three OS traps share the
            // low byte $AD and so reach the same dispatch arm — the
            // dispatcher only forwards bits 0..7 for OS traps. The central
            // raw route retains their operation identity before that mask.
            //
            // Trap word table per Inside Macintosh Volume VI, p. 6-308.
            // FUNCTION/Pascal signatures and register conventions per
            // Inside Macintosh: Operating System Utilities 1994,
            // 1-31..1-35.
            //
            // Gestalt ($A1AD)
            // Returns the response registered for an environment selector.
            // FUNCTION Gestalt (selector: OSType; VAR response: LongInt): OSErr;
            // Inside Macintosh: Operating System Utilities (1994), pp. 1-25--1-31.
            (false, 0xAD) => {
                let selector = cpu.read_reg(Register::D0);
                let sel = selector.to_be_bytes();
                let eval_context =
                    GestaltEvaluationContext::for_m68k(bus.ram_size(), self.mmu_mode != 0);
                match raw_trap_route(self.current_trap_word).os_routine_variant {
                    // _NewGestalt ($A3AD)
                    //
                    //   FUNCTION NewGestalt (selector: OSType;
                    //                        gestaltFunction:
                    //                            SelectorFunctionUUP): OSErr;
                    //
                    // Inside Macintosh: Operating System Utilities 1994,
                    // pp. 1-31..1-34 (description) and p. 1-50 (trap-word
                    // table).
                    //
                    // OS-bit FUNCTION (bit 11 clear) with register-only ABI
                    // per IM:OSUtils 1994 p. 1-32:
                    //
                    //     Registers on entry:
                    //       A0  Address of new selector function
                    //       D0  Selector code (4-char OSType)
                    //
                    //     Registers on exit:
                    //       D0  Result code
                    //
                    // Result codes:
                    //   noErr                  (0)
                    //   memFullErr           (-108)  Ran out of memory
                    //   gestaltDupSelectorErr (-5552) Selector already exists
                    //   gestaltLocationErr   (-5553) Function not in system heap
                    OsRoutineVariant::GestaltRegister => {
                        let already_known = is_builtin_gestalt_selector(selector, &eval_context)
                            || self.gestalt_registry.contains_key(&selector);
                        let action = evaluate_new_gestalt(
                            selector,
                            cpu.read_reg(Register::A0),
                            already_known,
                        );
                        match action {
                            NewGestaltAction::DuplicateSelector => {
                                cpu.write_reg(Register::D0, GESTALT_DUP_SELECTOR_ERR);
                            }
                            NewGestaltAction::Register { selector, value } => {
                                self.gestalt_registry.insert(selector, value);
                                cpu.write_reg(Register::D0, 0);
                            }
                        }
                        return Some(Ok(()));
                    }
                    // _ReplaceGestalt ($A5AD)
                    //
                    //   FUNCTION ReplaceGestalt (selector: OSType;
                    //                            gestaltFunction:
                    //                                SelectorFunctionUUP;
                    //                            VAR oldGestaltFunction:
                    //                                SelectorFunctionUUP)
                    //                            : OSErr;
                    //
                    // Inside Macintosh: Operating System Utilities 1994,
                    // pp. 1-31..1-35.
                    //
                    // OS-bit FUNCTION (bit 11 clear) with register-only ABI
                    // per IM:OSUtils 1994 p. 1-35:
                    //
                    //     Registers on entry:
                    //       A0  Address of new selector function
                    //       D0  Selector code (4-char OSType)
                    //
                    //     Registers on exit:
                    //       A0  Address of old selector function
                    //           (undefined on error)
                    //       D0  Result code
                    //
                    // Result codes:
                    //   noErr                   (0)
                    //   gestaltUndefSelectorErr (-5551) Undefined selector
                    //   gestaltLocationErr      (-5553) Function not in
                    //                                   system heap
                    OsRoutineVariant::GestaltReplace => {
                        let new_fn = cpu.read_reg(Register::A0);
                        let action = evaluate_replace_gestalt(
                            selector,
                            new_fn,
                            self.gestalt_registry.get(&selector).copied(),
                            is_builtin_gestalt_selector(selector, &eval_context),
                        );
                        match action {
                            ReplaceGestaltAction::ReplaceCustom {
                                old_handler,
                                new_handler,
                            } => {
                                self.gestalt_registry.insert(selector, new_handler);
                                cpu.write_reg(Register::A0, old_handler);
                                cpu.write_reg(Register::D0, 0);
                            }
                            ReplaceGestaltAction::ReplaceBuiltin { new_handler } => {
                                self.gestalt_registry.insert(selector, new_handler);
                                cpu.write_reg(Register::A0, 0);
                                cpu.write_reg(Register::D0, 0);
                            }
                            ReplaceGestaltAction::UndefinedSelector => {
                                cpu.write_reg(Register::D0, GESTALT_UNDEF_SELECTOR_ERR);
                            }
                        }
                        return Some(Ok(()));
                    }
                    // `_Gestalt` ($A1AD) and unresolved modifier forms fall
                    // through to the query handler below.
                    _ => {}
                }

                let evaluation = evaluate_gestalt_query(selector, &eval_context, None);
                if evaluation.error_code == 0 {
                    cpu.write_reg(Register::A0, evaluation.response);
                    cpu.write_reg(Register::D0, 0);
                } else {
                    if sel == *b"SAVR" || sel == *b"a/ux" {
                        cpu.write_reg(Register::A0, 0);
                    } else {
                        let s = std::str::from_utf8(&sel).unwrap_or("????");
                        eprintln!("[GESTALT] Unknown selector '{}' (${:08X})", s, selector);
                    }
                    cpu.write_reg(Register::D0, GESTALT_UNDEF_SELECTOR_ERR);
                }
                Ok(())
            }

            // ========== File Manager ==========

            // PBOpen / HOpen ($A000 / $A200)
            // Opens a file data fork with the access mode in ioPermssn.
            // FUNCTION PBOpen (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh: Files (1992), pp. 2-7 to 2-8, 2-185 to 2-186.
            (false, 0x00) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let filename = Self::read_pb_filename(bus, name_ptr);
                let permission = bus.read_byte(pb + 27);
                eprintln!("[TRAP] PBOpen(\"{}\", perm={})", filename, permission);

                // Clear ioRefNum upfront so the failure path produces a
                // deterministic *refNum = 0 (IM:II-92 leaves this undefined
                // on failure, but games that read *refNum after an error
                // expect 0).
                bus.write_word(pb + 24, 0);

                // HOpen supplies ioDirID and uses HFS names, where slash is
                // a legal filename character; only colon separates path
                // components. Files 1992, pp. 2-27 to 2-29, 2-185 to 2-186.
                let vfs_file = if self.current_trap_word & 0x0200 != 0 {
                    let vref = bus.read_word(pb + 22) as i16;
                    let dir_id = bus.read_long(pb + 48);
                    self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                } else {
                    self.find_vfs_file(&filename)
                };
                if let Some(vfs_name) = vfs_file {
                    let read_only = self.vfs_path_is_read_only(&vfs_name);
                    let requests_write = matches!(permission, 2 | 3 | 4);
                    if requests_write && read_only {
                        // Extracted disk-image volumes are mounted read-only;
                        // fsCurPerm follows the volume permission and explicit
                        // write modes fail with wPrErr.
                        bus.write_word(pb + 16, (-44i16) as u16);
                        cpu.write_reg(Register::D0, (-44i32) as u32);
                        return Some(Ok(()));
                    }
                    let writable = matches!(permission, 0 | 2 | 3 | 4) && !read_only;
                    let refnum = match self.allocate_data_file_fcb(bus, &vfs_name, writable) {
                        Ok(refnum) => refnum,
                        Err(err) => {
                            bus.write_word(pb + 16, err as u16);
                            cpu.write_reg(Register::D0, err as i32 as u32);
                            return Some(Ok(()));
                        }
                    };
                    self.open_files.insert(refnum, vfs_name.clone());
                    // Files 1992, 2-8: fsCurPerm (0) grants read/write when
                    // write access is available; fsWrPerm (2), fsRdWrPerm
                    // (3), and fsRdWrShPerm (4) explicitly request it.
                    // PBGetFCBInfo exposes the granted mode through bit 8 of
                    // ioFCBFlags (Files 1992, 2-108).
                    if writable {
                        self.write_refnums.insert(refnum);
                    }
                    self.file_positions.insert(refnum, 0);
                    bus.write_word(pb + 24, refnum);
                    bus.write_word(pb + 16, 0); // noErr
                    cpu.write_reg(Register::D0, 0);
                    eprintln!("[TRAP] PBOpen -> refnum={} vfs=\"{}\"", refnum, vfs_name);
                } else if Self::is_available_synthetic_driver_name(&filename) {
                    let refnum = self.allocate_process_file_refnum();
                    self.synthetic_drivers.insert(refnum, filename.clone());
                    bus.write_word(pb + 24, refnum);
                    bus.write_word(pb + 16, 0);
                    cpu.write_reg(Register::D0, 0);
                    eprintln!(
                        "[TRAP] PBOpen -> synthetic driver refnum={} name=\"{}\"",
                        refnum, filename
                    );
                } else if Self::is_unavailable_appletalk_driver_name(&filename) {
                    // A missing Device Manager driver reports dInstErr, not
                    // the File Manager's fnfErr (Inside Macintosh Volume II,
                    // II-183).
                    eprintln!("[TRAP] PBOpen: driver is not installed");
                    bus.write_word(pb + 16, (-26i16) as u16); // dInstErr
                    cpu.write_reg(Register::D0, (-26i32) as u32);
                } else {
                    eprintln!("[TRAP] PBOpen: file not found in VFS");
                    bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                    cpu.write_reg(Register::D0, (-43i32) as u32);
                }
                Ok(())
            }

            // PBRead/PBReadAsync ($A002/$A402)
            // Reads bytes from an open file, including PBRead newline mode.
            // FUNCTION PBRead (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // Files 1992, 2-84, 2-121 to 2-122, 2-238
            (false, 0x02) => {
                let pb = cpu.read_reg(Register::A0);
                let async_call = matches!(
                    raw_trap_route(self.current_trap_word).os_routine_variant,
                    OsRoutineVariant::ParameterBlockAsynchronous
                );
                let completion_addr = bus.read_long(pb + 12);
                let ref_num = bus.read_word(pb + 24);
                let buffer = bus.read_long(pb + 32);
                let request_count = bus.read_long(pb + 36) as usize;
                let pos_mode = bus.read_word(pb + 44);
                let pos_offset = bus.read_long(pb + 46) as i32;
                eprintln!(
                    "[TRAP] PBRead ref={} buf=${:08X} count={} posMode={} posOff={}",
                    ref_num, buffer, request_count, pos_mode, pos_offset
                );

                if let Some(filename) = self.open_files.get(&ref_num).cloned() {
                    if let Some(file_buf) = self.vfs.get(&filename) {
                        let file_len = file_buf.len();
                        let cur_pos =
                            usize::try_from(*self.file_positions.get(&ref_num).unwrap_or(&0))
                                .unwrap_or(usize::MAX);
                        match Self::resolve_file_mark_position(
                            pos_mode, pos_offset, cur_pos, file_len,
                        ) {
                            Err(_) => {
                                bus.write_word(pb + 16, (-40i16) as u16); // posErr
                                bus.write_long(pb + 40, 0);
                                bus.write_long(pb + 46, cur_pos as u32);
                                cpu.write_reg(Register::D0, (-40i32) as u32);
                            }
                            Ok(start) => {
                                let start = start.min(file_len);
                                let avail = file_len - start;
                                let max_read = request_count.min(avail);
                                let newline_mode = (pos_mode & 0x0080) != 0;
                                let newline_char = (pos_mode >> 8) as u8;
                                let newline_offset = if newline_mode {
                                    file_buf[start..start + max_read]
                                        .iter()
                                        .position(|&byte| byte == newline_char)
                                } else {
                                    None
                                };
                                let bytes_read =
                                    newline_offset.map(|offset| offset + 1).unwrap_or(max_read);
                                let stopped_at_newline = newline_offset.is_some();

                                bus.write_bytes(buffer, &file_buf[start..start + bytes_read]);

                                self.file_positions.insert(ref_num, start + bytes_read);
                                bus.write_long(pb + 40, bytes_read as u32);
                                bus.write_long(pb + 46, (start + bytes_read) as u32);
                                self.recent_file_read = Some(super::dispatch::RecentFileRead {
                                    ref_num,
                                    filename: filename.clone(),
                                    buffer,
                                    start,
                                    bytes_read,
                                });

                                if !stopped_at_newline && bytes_read < request_count {
                                    eprintln!(
                                        "[TRAP] PBRead -> eofErr (read {} of {} from pos {})",
                                        bytes_read, request_count, start
                                    );
                                    bus.write_word(pb + 16, (-39i16) as u16); // eofErr
                                    cpu.write_reg(Register::D0, (-39i32) as u32);
                                } else {
                                    bus.write_word(pb + 16, 0);
                                    cpu.write_reg(Register::D0, 0);
                                }
                            }
                        }
                    } else {
                        eprintln!("[TRAP] PBRead -> fnfErr (file not in VFS)");
                        self.recent_file_read = None;
                        bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                        bus.write_long(pb + 40, 0);
                        cpu.write_reg(Register::D0, (-43i32) as u32);
                    }
                } else if self.synthetic_drivers.contains_key(&ref_num) {
                    self.recent_file_read = None;
                    bus.write_word(pb + 16, 0);
                    bus.write_long(pb + 40, 0);
                    cpu.write_reg(Register::D0, 0);
                } else {
                    eprintln!("[TRAP] PBRead -> rfNumErr (refnum {} not open)", ref_num);
                    self.recent_file_read = None;
                    bus.write_word(pb + 16, (-51i16) as u16); // rfNumErr
                    bus.write_long(pb + 40, 0);
                    cpu.write_reg(Register::D0, (-51i32) as u32);
                }

                if async_call {
                    let result = cpu.read_reg(Register::D0) as i16;
                    self.pending_file_completions.push_back(
                        crate::process_context::PendingFileCompletion {
                            parameter_block: pb,
                            completion_addr,
                            result,
                        },
                    );
                    // A successfully queued asynchronous request returns noErr.
                    // ioResult remains positive until the request completes.
                    bus.write_word(pb + 16, 1);
                    cpu.write_reg(Register::D0, 0);
                } else {
                    // The File Manager clears ioCompletion for synchronous calls.
                    bus.write_long(pb + 12, 0);
                }
                Ok(())
            }

            // FSWrite ($A003)
            // FSWrite ($A003): Writes to output_dir or VFS
            (false, 0x03) => {
                let pb = cpu.read_reg(Register::A0);
                let ref_num = bus.read_word(pb + 24);
                let buffer = bus.read_long(pb + 32);
                let request_count = bus.read_long(pb + 36) as usize;
                let pos_mode = bus.read_word(pb + 44);
                let pos_offset = bus.read_long(pb + 46) as i32;
                eprintln!(
                    "[TRAP] FSWrite ref={} buf=${:08X} count={} posMode={} posOff={}",
                    ref_num as i16, buffer, request_count, pos_mode, pos_offset
                );

                let signed_ref_num = ref_num as i16;
                if signed_ref_num < 0 {
                    let result =
                        self.write_device_driver(bus, signed_ref_num, buffer, request_count);
                    let (err, actual_count) = match result {
                        Ok(actual_count) => (0i16, actual_count),
                        Err(err) => (err, 0),
                    };
                    bus.write_long(pb + 40, actual_count as u32);
                    bus.write_word(pb + 16, err as u16);
                    cpu.write_reg(Register::D0, err as i32 as u32);
                    return Some(Ok(()));
                }

                let Some(filename) = self.open_files.get(&ref_num).cloned() else {
                    if self.synthetic_drivers.contains_key(&ref_num) {
                        bus.write_long(pb + 40, request_count as u32);
                        bus.write_word(pb + 16, 0);
                        cpu.write_reg(Register::D0, 0);
                        return Some(Ok(()));
                    }
                    eprintln!("[TRAP] FSWrite -> rfNumErr (refnum {} not open)", ref_num);
                    bus.write_long(pb + 40, 0);
                    bus.write_word(pb + 16, (-51i16) as u16); // rfNumErr
                    cpu.write_reg(Register::D0, (-51i32) as u32);
                    return Some(Ok(()));
                };

                if self.vfs_path_is_read_only(&filename) {
                    bus.write_long(pb + 40, 0);
                    bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                    cpu.write_reg(Register::D0, (-44i32) as u32);
                    return Some(Ok(()));
                }

                if !self.write_refnums.contains(&ref_num) {
                    bus.write_long(pb + 40, 0);
                    bus.write_word(pb + 16, (-61i16) as u16); // wrPermErr
                    cpu.write_reg(Register::D0, (-61i32) as u32);
                    return Some(Ok(()));
                }

                let file_len = self.vfs.get(&filename).map_or(0, Vec::len);
                let cur_pos = usize::try_from(*self.file_positions.get(&ref_num).unwrap_or(&0))
                    .unwrap_or(usize::MAX);
                let Ok(start) =
                    Self::resolve_file_mark_position(pos_mode, pos_offset, cur_pos, file_len)
                else {
                    bus.write_long(pb + 40, 0);
                    bus.write_long(pb + 46, cur_pos as u32);
                    bus.write_word(pb + 16, (-40i16) as u16); // posErr
                    cpu.write_reg(Register::D0, (-40i32) as u32);
                    return Some(Ok(()));
                };
                let (new_pos, host_sync_bytes) = self.vfs.with_entry_or_default_mut(
                    filename.clone(),
                    |file_buf| {
                        if start > file_buf.len() {
                            file_buf.resize(start, 0);
                        }
                        let end = start.saturating_add(request_count);
                        if end > file_buf.len() {
                            file_buf.resize(end, 0);
                        }
                        bus.read_bytes_into(buffer, &mut file_buf[start..start + request_count]);

                        let sync = if self.output_dir.is_some() {
                            Some(file_buf.clone())
                        } else {
                            None
                        };
                        (end, sync)
                    },
                );

                self.file_positions.insert(ref_num, new_pos);
                bus.write_long(pb + 40, request_count as u32);
                bus.write_long(pb + 46, new_pos as u32);

                if let (Some(dir), Some(bytes)) = (&self.output_dir, host_sync_bytes) {
                    let host_path = dir.join(&filename);
                    if let Some(parent) = host_path.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    if let Err(e) = std::fs::write(&host_path, bytes) {
                        eprintln!(
                            "[FSWrite] failed to sync {} to host ({}): {}",
                            filename,
                            host_path.display(),
                            e
                        );
                    }
                }
                self.touch_vfs_entry(&filename);

                // Resource forks live in self.vfs_rsrc; PBOpenRF mirrors the
                // bytes into self.vfs under "__rsrc__<name>" so FSRead/FSWrite
                // share the data-fork code path. Mirror writes back so a later
                // OpenRFPerm/PBOpenRF reads the latest data (Mars Rising's
                // installer copies its rsrc fork to a temp file then re-opens it).
                if let Some(real_name) = filename.strip_prefix("__rsrc__") {
                    if let Some(buf) = self.vfs.get(&filename).cloned() {
                        self.vfs_rsrc.insert(real_name.to_string(), buf);
                    }
                }

                bus.write_word(pb + 16, 0);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // FSClose ($A001)
            // FUNCTION FSClose(refNum: INTEGER): OSErr;
            // Inside Macintosh Volume II, II-92. Result codes:
            //   noErr (0) — file closed
            //   rfNumErr (-51) — reference number specifies a nonexistent
            //                     access path (sibling of FSRead / FSWrite
            //                     / PBGetEOF, which all validate refnum)
            // Resource Manager open calls return file reference numbers for
            // resource forks (More Macintosh Toolbox 1993, 1-58 to 1-66).
            // If that refnum is also present in the resource chain, close the
            // in-memory resource map and its loaded handles too.
            (false, 0x01) => {
                let pb = cpu.read_reg(Register::A0);
                let ref_num = bus.read_word(pb + 24);
                let closed_file = if self.open_files.remove(&ref_num).is_some() {
                    self.file_positions.remove(&ref_num);
                    self.write_refnums.remove(&ref_num);
                    Self::clear_file_fcb(bus, ref_num);
                    true
                } else {
                    false
                };
                let closed_resource_file = self.close_resource_file_refnum(bus, ref_num);
                let err: i16 = if closed_file || closed_resource_file {
                    0
                } else if self.synthetic_drivers.remove(&ref_num).is_some() {
                    0
                } else {
                    -51
                };
                bus.write_word(pb + 16, err as u16);
                cpu.write_reg(Register::D0, err as i32 as u32);
                Ok(())
            }

            // PBGetVol / PBHGetVol ($A014 / $A214)
            // Returns the default volume reference number (a WDRefNum for the app folder).
            // FUNCTION PBGetVol  (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // FUNCTION PBHGetVol (paramBlock: WDPBPtr;    async: BOOLEAN): OSErr;
            // PBHGetVol additionally returns ioWDDirID (directory ID) at offset 48.
            // Inside Macintosh Volume IV, IV-96 / Files 1992, 2-160
            // PBHGetVol subsection begins IM:Files 1992 line 8305; trap macro
            // `_HGetVol` per IM:Files line 8331 + table line 14488. The OS-trap
            // dispatcher masks `trap & 0x00FF`, so $A214 PBHGetVol and $A014
            // PBGetVol land on the same low byte and share this arm.
            //
            // trap-doc: $A014 | PBGetVol | Partial | File Manager & Gestalt — OS Traps | Fills ioVRefNum and ioNamePtr from the current volume (IM:Files 1992, 2-162)
            // PBHGetVol ($A214): HFS variant aliased onto $A014
            (false, 0x14) => {
                let pb = cpu.read_reg(Register::A0);
                let volume_ref_num = self.resolve_volume_ref_num(*self.app_wd_refnum);
                let volume_name = self
                    .vfs_volume_for_ref_num(volume_ref_num)
                    .map(|volume| volume.name.as_str())
                    .unwrap_or(super::TrapDispatcher::boot_volume_name());
                bus.write_word(pb + 22, *self.app_wd_refnum as u16);
                let name_ptr = bus.read_long(pb + 18);
                if name_ptr != 0 {
                    Self::write_pstring(bus, name_ptr, volume_name);
                }
                // HGetVol fields: ioWDProcID and ioWDVRefNum and ioWDDirID
                // Always populate these so both PBGetVol and HGetVol callers work.
                bus.write_long(pb + 28, 0); // ioWDProcID
                bus.write_word(pb + 32, volume_ref_num as u16); // ioWDVRefNum
                let dir_id = self
                    .working_directory_info(*self.app_wd_refnum)
                    .map(|wd| wd.dir_id)
                    .unwrap_or(*self.default_dir_id);
                bus.write_long(pb + 48, dir_id); // ioWDDirID
                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBGetVInfo / PBHGetVInfo ($A007 / $A207)
            // FUNCTION PBGetVInfo (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // FUNCTION PBHGetVInfo (paramBlock: HParmBlkPtr; async: Boolean): OSErr;
            // Inside Macintosh Volume II, II-104; HFS variant Files 1992,
            // 2-144 (subsection begins line 8018; trap macro `_HGetVolInfo`
            // per line 8077).
            // The OS-trap dispatcher masks `trap & 0x00FF`, so $A207
            // PBHGetVInfo and $A007 PBGetVInfo land on the same low
            // byte and share this arm.
            //
            // PBGetVInfo ($A007): Returns mounted volume info and free-space figures
            // PBHGetVInfo ($A207): HFS variant aliased onto $A007
            (false, 0x07) => {
                let pb = cpu.read_reg(Register::A0);
                let is_hfs_variant = matches!(
                    raw_trap_route(self.current_trap_word).os_routine_variant,
                    OsRoutineVariant::FileHfsSynchronous | OsRoutineVariant::FileHfsAsynchronous
                );
                let volume_index = bus.read_word(pb + 28) as i16;
                let requested_vref = bus.read_word(pb + 22) as i16;
                let requested_name = Self::read_pb_filename(bus, bus.read_long(pb + 18));
                let relative_pathname = requested_name.starts_with(':');
                let absolute_pathname = !relative_pathname && requested_name.contains(':');
                if super::dispatch::trace_resfile_enabled() {
                    eprintln!(
                        "[TRAP] PBHGetVInfo index={} vref={} name={:?}",
                        volume_index, requested_vref, requested_name
                    );
                }
                let boot_volume = || {
                    Some((
                        super::TrapDispatcher::boot_volume_name().to_string(),
                        super::TrapDispatcher::boot_volume_ref_num(),
                        0u16,
                    ))
                };
                let volume_by_name = |name: &str| {
                    // A full pathname names its volume before the first colon.
                    // Files 1992, 2-6 and 2-145.
                    let name = name.split(':').next().unwrap_or(name);
                    if name.eq_ignore_ascii_case(super::TrapDispatcher::boot_volume_name()) {
                        boot_volume()
                    } else {
                        self.vfs_volume_by_name(name)
                            .map(|volume| (volume.name.clone(), volume.ref_num, volume.attributes))
                    }
                };
                let volume_by_ref = |requested_vref: i16| {
                    let volume_ref_num = if requested_vref
                        == super::TrapDispatcher::boot_volume_ref_num()
                        || self
                            .vfs_volumes
                            .iter()
                            .any(|volume| volume.ref_num == requested_vref)
                    {
                        Some(requested_vref)
                    } else {
                        self.working_directories
                            .get(&requested_vref)
                            .map(|working_directory| working_directory.volume_ref_num)
                    }?;
                    if volume_ref_num == super::TrapDispatcher::boot_volume_ref_num() {
                        boot_volume()
                    } else {
                        self.vfs_volume_for_ref_num(volume_ref_num)
                            .map(|volume| (volume.name.clone(), volume.ref_num, volume.attributes))
                    }
                };
                let volume_info = if volume_index == 0 {
                    // Files 1992, 2-145: ioVolIndex == 0 selects a volume by
                    // ioNamePtr or ioVRefNum instead of enumerating the VCB
                    // queue. Do not silently turn an unknown vRefNum into the
                    // boot volume; callers use nsvErr to detect a bad volume.
                    if requested_vref != 0 {
                        volume_by_ref(requested_vref)
                    } else if relative_pathname {
                        volume_by_ref(*self.app_wd_refnum)
                    } else if !requested_name.is_empty() {
                        volume_by_name(&requested_name)
                    } else {
                        volume_by_ref(*self.app_wd_refnum)
                    }
                } else if volume_index > 0 {
                    let mut mounted = self
                        .vfs_volumes
                        .iter()
                        .map(|volume| (volume.name.clone(), volume.ref_num, volume.attributes))
                        .collect::<Vec<_>>();
                    mounted.sort_by_key(|(_, ref_num, _)| std::cmp::Reverse(*ref_num));
                    let mut volumes = vec![(
                        super::TrapDispatcher::boot_volume_name().to_string(),
                        super::TrapDispatcher::boot_volume_ref_num(),
                        0u16,
                    )];
                    volumes.extend(mounted);
                    volumes.get((volume_index - 1) as usize).cloned()
                } else {
                    // Files 1992, 2-145: a negative ioVolIndex selects the
                    // volume by ioNamePtr and ioVRefNum in the standard way.
                    // A full pathname's volume name takes precedence; otherwise
                    // a nonzero volume or working-directory reference is used.
                    if absolute_pathname {
                        volume_by_name(&requested_name)
                    } else if requested_vref != 0 {
                        volume_by_ref(requested_vref)
                    } else if relative_pathname {
                        volume_by_ref(*self.app_wd_refnum)
                    } else if !requested_name.is_empty() {
                        volume_by_name(&requested_name)
                    } else {
                        volume_by_ref(*self.app_wd_refnum)
                    }
                };
                let Some((volume_name, volume_ref_num, volume_attributes)) = volume_info else {
                    // Files 1992, 2-145: positive ioVolIndex values walk the
                    // mounted-volume queue, and enumeration ends with nsvErr.
                    const NSV_ERR: i16 = -35;
                    bus.write_word(pb + 16, NSV_ERR as u16);
                    cpu.write_reg(Register::D0, NSV_ERR as i32 as u32);
                    return Some(Ok(()));
                };

                let mounted_info = self.vfs_volume_for_ref_num(volume_ref_num);
                let volume_file_count = mounted_info.map_or(100, |volume| volume.file_count);
                let allocation_block_count = mounted_info
                    .map_or(BOOT_VOLUME_ALLOCATION_BLOCKS, |volume| {
                        volume.allocation_block_count
                    });
                let allocation_block_size = mounted_info
                    .map_or(BOOT_VOLUME_ALLOCATION_BLOCK_SIZE, |volume| {
                        volume.allocation_block_size
                    });
                let clump_size = mounted_info.map_or(BOOT_VOLUME_ALLOCATION_BLOCK_SIZE, |volume| {
                    volume.clump_size
                });
                let free_blocks =
                    mounted_info.map_or(BOOT_VOLUME_FREE_BLOCKS, |volume| volume.free_blocks);
                let created_date = mounted_info.map(|volume| volume.created_date).unwrap_or(0);
                let modified_date = mounted_info.map(|volume| volume.modified_date).unwrap_or(0);
                let bitmap_start = mounted_info.map(|volume| volume.bitmap_start).unwrap_or(0);
                let allocation_pointer = mounted_info
                    .map(|volume| volume.allocation_pointer)
                    .unwrap_or(0);
                let allocation_start = mounted_info
                    .map(|volume| volume.allocation_start)
                    .unwrap_or(0);
                let next_catalog_id = mounted_info
                    .map(|volume| volume.next_catalog_id)
                    .unwrap_or(0);
                let name_ptr = bus.read_long(pb + 18);
                if name_ptr != 0 {
                    Self::write_pstring(bus, name_ptr, &volume_name);
                }
                bus.write_word(pb + 22, volume_ref_num as u16);
                bus.write_long(pb + 30, created_date); // ioVCrDate
                bus.write_long(pb + 34, modified_date); // ioVLsMod
                bus.write_word(pb + 38, volume_attributes); // ioVAtrb
                bus.write_word(pb + 40, volume_file_count); // ioVNmFls (files on volume)
                bus.write_word(pb + 42, bitmap_start); // ioVBitMap
                bus.write_word(pb + 44, allocation_pointer); // ioAllocPtr

                // Files 1992, 2-46 and 2-144: callers multiply the unsigned
                // ioVFrBlk block count by ioVAlBlkSiz to determine free bytes.
                // Report a modest 64 MB boot volume so installers and demos
                // that require scratch space do not reject the system disk.
                bus.write_word(pb + 46, allocation_block_count); // ioVNmAlBlks
                bus.write_long(pb + 48, allocation_block_size); // ioVAlBlkSiz
                bus.write_long(pb + 52, clump_size); // ioVClpSiz
                bus.write_word(pb + 56, allocation_start); // ioAlBlSt
                bus.write_long(pb + 58, next_catalog_id); // ioVNxtCNID
                bus.write_word(pb + 62, free_blocks); // ioVFrBlk
                                                      // VolumeParam ends after ioVFrBlk at byte 64. Only the HFS
                                                      // HVolumeParam supplied to PBHGetVInfo has the fields that
                                                      // follow it. Files 1992, pp. 2-91--2-92 and 2-96--2-97.
                if is_hfs_variant {
                    bus.write_word(pb + 64, 0x4244); // ioVSigWord (HFS)

                    // Files 1992, 2-145: an online volume has a positive
                    // drive number; zero marks an offline or ejected volume.
                    // Use a stable virtual drive number for mounted volumes.
                    bus.write_word(pb + 66, volume_ref_num.unsigned_abs().max(1)); // ioVDrvInfo
                    bus.write_word(pb + 68, 0); // ioVDRefNum
                    bus.write_word(pb + 70, 0); // ioVFSID (File Manager)
                }
                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBGetEOF ($A011)
            // PBGetEOF ($A011): Returns file length from VFS
            (false, 0x11) => {
                let pb = cpu.read_reg(Register::A0);
                let ref_num = bus.read_word(pb + 24);
                if let Some(filename) = self.open_files.get(&ref_num) {
                    if let Some(file_buf) = self.vfs.get(filename) {
                        bus.write_long(pb + 28, file_buf.len() as u32); // ioMisc = logical EOF
                        bus.write_word(pb + 16, 0);
                        cpu.write_reg(Register::D0, 0);
                    } else {
                        bus.write_word(pb + 16, (-43i16) as u16);
                        cpu.write_reg(Register::D0, (-43i32) as u32);
                    }
                } else {
                    bus.write_word(pb + 16, (-51i16) as u16);
                    cpu.write_reg(Register::D0, (-51i32) as u32);
                }
                Ok(())
            }

            // PBSetFPos ($A044)
            // Sets the file mark (position) for an open file.
            // FUNCTION PBSetFPos(paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Files 1992, 2-214
            // PBSetFPos ($A044): Sets file mark position; supports fsAtMark, fsFromStart, fsFromLEOF, fsFromMark
            (false, 0x44) => {
                let pb = cpu.read_reg(Register::A0);
                let ref_num = bus.read_word(pb + 24);
                let pos_mode = bus.read_word(pb + 44) & 0x03;
                let pos_offset = bus.read_long(pb + 46) as i32;

                if let Some(filename) = self.open_files.get(&ref_num).cloned() {
                    let file_len = self.vfs.get(&filename).map(|f| f.len()).unwrap_or(0);
                    let cur_pos = usize::try_from(*self.file_positions.get(&ref_num).unwrap_or(&0))
                        .unwrap_or(usize::MAX);
                    let Ok(requested_pos) =
                        Self::resolve_file_mark_position(pos_mode, pos_offset, cur_pos, file_len)
                    else {
                        bus.write_long(pb + 46, cur_pos as u32);
                        bus.write_word(pb + 16, (-40i16) as u16); // posErr
                        cpu.write_reg(Register::D0, (-40i32) as u32);
                        return Some(Ok(()));
                    };
                    let (new_pos, err) = if requested_pos > file_len {
                        (file_len, -39i16)
                    } else {
                        (requested_pos, 0i16)
                    };
                    self.file_positions.insert(ref_num, new_pos);
                    bus.write_long(pb + 46, new_pos as u32);
                    bus.write_word(pb + 16, err as u16);
                    cpu.write_reg(Register::D0, err as i32 as u32);
                } else {
                    bus.write_word(pb + 16, (-51i16) as u16); // rfNumErr
                    cpu.write_reg(Register::D0, (-51i32) as u32);
                }
                Ok(())
            }

            // PBFlushFile ($A045)
            // Per IM:II II-114: "Writes the contents of the access
            // path buffer indicated by the file reference number
            // ioRefNum to the volume, and updates the file's entry
            // in the file directory."
            // FUNCTION PBFlushFile (paramBlock: ParmBlkPtr;
            //                      async: BOOLEAN): OSErr;
            // Inside Macintosh Volume II, II-114
            //
            // Register convention (OS trap): A0 = paramBlock ptr;
            // result in D0 + ioResult slot at pb+16.
            //
            // Result codes per IM:II II-114:
            //   noErr (0) — buffer flushed
            //   rfNumErr (-51) — reference number specifies a nonexistent
            //                    access path
            //
            // ## Status: Stub → Partial promotion
            //
            // Systemless's VFS has no per-file write-back buffer
            // (all FSWrite goes directly to the in-memory VFS
            // map; no deferred writes that need flushing). So the
            // "flush buffer to volume" semantic is trivially
            // satisfied. BUT the impl DOES validate the refnum
            // against self.open_files and returns the IM-correct
            // rfNumErr (-51) for a bad refnum — that's substantive
            // refnum-tracking behaviour, not a no-op stub. The
            // prior trap-doc Status was "Stub" with terse Notes
            // "Returns noErr" which lied about the refnum
            // validation. Promoted Stub -> Partial during the
            // stub-with-substantive-body audit; same status issue as
            // PlotIcon $A94B / SetItemCmd $A84F / DisposPalette $AA93 /
            // UpdtControl $A953 / Draw1Control $A96D.
            // PBFlushFile ($A045): Validates ioRefNum (pb+24) against self.open_files + returns rfNumErr (-51) for bad refnum OR noErr (0) for valid; writes result to ioResult (pb+16) AND D0 per IM:II II-114 result-code table. VFS has no per-file write-back buffer so the noErr path is a successful no-op (FSWrite goes directly to the in-memory VFS map).
            (false, 0x45) => {
                let pb = cpu.read_reg(Register::A0);
                let ref_num = bus.read_word(pb + 24);
                let err: i16 = if self.open_files.contains_key(&ref_num) {
                    0
                } else {
                    -51
                };
                bus.write_word(pb + 16, err as u16);
                cpu.write_reg(Register::D0, err as i32 as u32);
                Ok(())
            }

            // PBGetFPos ($A018)
            // FUNCTION PBGetFPos (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh Volume II, II-117. Result codes:
            //   noErr (0); rfNumErr (-51) for a bad reference number.
            // PBGetFPos ($A018): Returns current file position
            (false, 0x18) => {
                let pb = cpu.read_reg(Register::A0);
                let ref_num = bus.read_word(pb + 24);
                if let Some(pos) = self.file_positions.get(&ref_num).copied() {
                    bus.write_long(pb + 46, pos); // ioPosOffset
                    bus.write_word(pb + 44, 0); // ioPosMode
                    bus.write_word(pb + 16, 0);
                    cpu.write_reg(Register::D0, 0);
                } else {
                    bus.write_long(pb + 46, 0);
                    bus.write_word(pb + 44, 0);
                    bus.write_word(pb + 16, (-51i16) as u16);
                    cpu.write_reg(Register::D0, (-51i32) as u32);
                }
                Ok(())
            }

            // PBFlushVol ($A013)
            // Writes the contents of the volume buffer to the volume.
            // FUNCTION PBFlushVol (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // IM:Files 1992, 2-142. Result codes include noErr (0) and
            // nsvErr (-35) when no such volume exists.
            // trap-doc: $A013 | PBFlushVol | Partial | File Manager & Gestalt — OS Traps | No-op flush for known HLE volume specs; nsvErr for unrecognised vRefNum (IM:Files 1992, 2-142)
            (false, 0x13) => {
                let pb = cpu.read_reg(Register::A0);
                let name = Self::read_pb_filename(bus, bus.read_long(pb + 18));
                let vref = bus.read_word(pb + 22) as i16;
                let known_by_vref = vref == 0
                    || vref == Self::boot_volume_ref_num()
                    || self.vfs_volumes.iter().any(|volume| volume.ref_num == vref)
                    || self.working_directories.contains_key(&vref);
                let known_by_name = !name.is_empty()
                    && (name.eq_ignore_ascii_case(super::TrapDispatcher::boot_volume_name())
                        || self.vfs_volume_by_name(&name).is_some());
                let err: i16 = if known_by_vref || known_by_name {
                    0
                } else {
                    -35
                };
                bus.write_word(pb + 16, err as u16);
                cpu.write_reg(Register::D0, err as i32 as u32);
                Ok(())
            }

            // PBUnmountVol ($A00E) / PBUnmountVolImmed ($A20E)
            // Unmounts a volume.
            //   FUNCTION PBUnmountVol      (paramBlock: ParmBlkPtr): OSErr;
            //   FUNCTION PBUnmountVolImmed (paramBlock: ParmBlkPtr): OSErr;
            // Inside Macintosh: Files (1992), p. 2-148 (PBUnmountVol).
            //
            // The $A20E variant is declared in MPW Universal Headers
            // Files.h as `PBUnmountVolImmed(ParmBlkPtr)` and is not
            // separately documented in IM:Files 1992. Its MPW Traps.h
            // macro name is `_HUnmountVol` (also known historically as
            // `PBHUnmountVol`). Both trap
            // words take ParmBlkPtr — not HParmBlkPtr — and reach this
            // arm via the OS-trap dispatcher's `trap & 0x00FF` mask.
            // The "Immed" variant differs from PBUnmountVol in that it
            // does not call PBFlushVol before unmounting.
            //
            // Register convention (OS-bit FUNCTION; IM:Files 1992
            // p. 2-148 + IM:II 1985 p. II-114):
            //   A0 entry: ParmBlkPtr (paramBlock)
            //   D0 exit:  OSErr result code (also mirrored into
            //             pb.ioResult at pb+16 per the basic File
            //             Manager parameter block dispatcher
            //             convention, IM:II 1985 p. II-114)
            //
            // Parameter block fields used (IM:II 1985 p. II-178 IOParam
            // layout):
            //   →  ioCompletion (ProcPtr)  — NIL for synchronous form
            //   ←  ioResult     (OSErr)    — result code (mirrors D0)
            //   →  ioNamePtr    (StringPtr) — volume name (NIL means
            //                                  use ioVRefNum)
            //   →  ioVRefNum    (Integer)  — volume reference number
            //
            // Documented result codes (IM:Files 1992 p. 2-148):
            //   noErr     0   No error
            //   nsvErr  -35   No such volume
            //   ioErr   -36   I/O error
            //   bdNamErr -37  Bad filename
            //   fBsyErr -47   File(s) still open on the volume
            //   paramErr -50  Bad parameter
            //
            // MPW Universal Headers (Files.h):
            //   #pragma parameter __D0 PBUnmountVol(__A0)
            //   EXTERN_API(OSErr) PBUnmountVol(ParmBlkPtr paramBlock)
            //                                       ONEWORDINLINE(0xA00E);
            //   #pragma parameter __D0 PBUnmountVolImmed(__A0)
            //   EXTERN_API(OSErr) PBUnmountVolImmed(ParmBlkPtr paramBlock)
            //                                       ONEWORDINLINE(0xA20E);
            //
            // Systemless HLE compromise: the single-volume VFS has no
            // volume table to unmount from; the boot volume is
            // permanently mounted and any other vRefNum is silently
            // a no-op. The trap collapses to writing noErr (0) into
            // both D0 and pb.ioResult unconditionally. BasiliskII
            // dispatches the real ROM PB trap and is expected to
            // return nsvErr (-35) or paramErr (-50) for an ioVRefNum
            // that does not appear in the VCB queue. The absolute
            // OSErr value therefore differs between the two; the
            // behavioral invariants are (a) the dispatcher convention
            // writing the same OSErr into both D0 and ioResult, and
            // (b) the register-only OS-bit FUNCTION calling convention
            // preserving A7.
            //
            // Regression coverage:
            //   pbunmountvol_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            (false, 0x0E) => {
                let pb = cpu.read_reg(Register::A0);
                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // -----------------------------------------------------------------
            // Volume / I/O-queue family — collapse to noErr no-ops in Systemless's
            // single-volume, synchronous-I/O HLE.
            //
            // These traps mediate state that the HLE does not model:
            //   • PBKillIO    ($A006) — abort I/O on a driver refnum. There is
            //     no async I/O queue to walk.
            //   • PBMountVol  ($A00F) — mount a volume by drive number. A
            //     single VFS volume is permanently mounted; the trap rewrites
            //     `ioVRefNum` with the boot vRefNum and returns noErr.
            //   • PBAllocate  ($A010) / PBAllocContig ($A210) — preallocate
            //     blocks on a file fork. The unbounded heap-backed VFS has no
            //     fragmentation, so every request fully succeeds.
            //   • FInitQueue  ($A016) — clear the file I/O queue. There is no
            //     queue; PROCEDURE returns via D0 = noErr.
            //   • PBEject     ($A017) — eject removable media. None exists.
            //   • PBOffLine   ($A035) — take a volume offline. The boot
            //     volume cannot be brought offline.
            //   • PBSetFVers  ($A043) — set MFS-era file version number. HFS
            //     files are always version 0; the trap is a documented HFS
            //     no-op (IM:II II-117 warns nonzero versions break the
            //     Resource Manager / Segment Loader).
            //   • AddDrive    ($A04E) — append a DrvQEl to the drive queue.
            //     There is no drive queue.

            // PBKillIO ($A006)
            // Terminates the active I/O request and removes all pending I/O
            // requests for the driver whose reference number is in the
            // ioRefNum field of the parameter block.
            // FUNCTION PBKillIO (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh Volume II (1985), p. II-187 + Inside
            // Macintosh: Devices (1994), pp. 1-45 to 1-46.
            //
            // Register convention (OS-bit FUNCTION; IM:II 1985 p. II-187
            // trap macro `_KillIO`):
            //   A0 entry: ParmBlkPtr (paramBlock)
            //   D0 exit:  OSErr result code (also mirrored into pb.ioResult
            //             at pb+16 per Device Manager dispatcher convention,
            //             IM:II 1985 p. II-114; applies to the entire $A0xx
            //             PB family)
            //
            // Parameter block fields used (IM:II 1985 p. II-178 IOParam
            // layout):
            //   →  ioCompletion (ProcPtr)    — completion routine (NIL for
            //                                  the synchronous form)
            //   ←  ioResult     (OSErr)      — result code (mirrors D0)
            //   →  ioRefNum     (Integer)    — driver reference number
            //
            // Documented behavior (IM:II 1985 p. II-187): the abort applies
            // to the driver named by ioRefNum; the active call's completion
            // routine, and the completion routines of any pending calls,
            // execute with the result code abortErr (-27). The function
            // result itself is whatever the driver's KillIO routine returns.
            //
            // MPW Universal Headers (Devices.h):
            //   #pragma parameter __D0 PBKillIOSync(__A0)
            //   EXTERN_API(OSErr) PBKillIOSync(ParmBlkPtr paramBlock)
            //                                          ONEWORDINLINE(0xA006);
            //   #define PBKillIO(pb, async) ((async) ? PBKillIOAsync(pb)
            //                                        : PBKillIOSync(pb))
            //
            // Systemless HLE compromise: the synchronous-I/O HLE has no async
            // I/O queue to walk and no driver-side KillIO routines to
            // invoke, so the trap collapses to a no-op that writes noErr
            // (0) into both D0 and pb.ioResult. BasiliskII dispatches the
            // real ROM PB trap and is expected to return whatever the
            // unit-table lookup produces for a refNum that does not map
            // to an installed driver (typically badUnitErr -21 or
            // unitEmptyErr -22) or whatever the driver's KillIO routine
            // returns for a real one. The absolute return value
            // therefore differs between the two; the behavioral
            // invariants are (a) the dispatcher convention writing the
            // same OSErr into both D0 and ioResult, and (b) the
            // register-only OS-bit FUNCTION calling convention
            // preserving A7.
            //
            // Regression coverage:
            //   pbkillio_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            (false, 0x06) => {
                let pb = cpu.read_reg(Register::A0);
                bus.write_word(pb + 16, 0); // noErr → pb.ioResult
                cpu.write_reg(Register::D0, 0); // noErr → D0
                Ok(())
            }

            // PBMountVol ($A00F)
            // Mounts the volume in the drive supplied via ioVRefNum (input
            // drive number) and rewrites ioVRefNum with the assigned volume
            // reference number (output).
            // FUNCTION PBMountVol (paramBlock: ParmBlkPtr): OSErr;
            // Inside Macintosh: Files (1992), p. 2-139.
            //
            // Register convention (OS-bit FUNCTION; IM:Files 1992 p. 2-139
            // trap macro `_MountVol`):
            //   A0 entry: ParmBlkPtr (paramBlock)
            //   D0 exit:  OSErr result code (also mirrored into pb.ioResult
            //             at pb+16 per File Manager dispatcher convention,
            //             IM:II 1985 p. II-114; applies to the entire $A0xx
            //             PB family)
            //
            // Parameter block fields used (IM:II 1985 p. II-178 IOParam
            // layout):
            //   →  ioCompletion (ProcPtr)    — NIL (PBMountVol is always
            //                                  synchronous per IM:Files
            //                                  1992 p. 2-139)
            //   ←  ioResult     (OSErr)      — result code (mirrors D0)
            //   ↔  ioVRefNum    (Integer)    — input: drive number;
            //                                  output: assigned vRefNum
            //
            // Documented result codes (IM:Files 1992 p. 2-140):
            //   noErr     (0)   — success
            //   ioErr     (-36) — I/O error
            //   tmfoErr   (-42) — too many files open
            //   paramErr  (-50) — bad drive number
            //
            // MPW Universal Headers (Files.h):
            //   #pragma parameter __D0 PBMountVol(__A0)
            //   EXTERN_API(OSErr) PBMountVol(ParmBlkPtr paramBlock)
            //                                          ONEWORDINLINE(0xA00F);
            //
            // Systemless HLE behavior: the single-volume VFS collapses any
            // mount request to the permanently-mounted boot volume. The
            // trap rewrites ioVRefNum with BOOT_VOLUME_REF_NUM (-1) and
            // writes noErr (0) into both D0 and pb.ioResult. BasiliskII
            // dispatches the real ROM PB trap and is expected to return
            // paramErr (-50) for a bogus drive number that does not map
            // to any installed drive queue entry. The absolute OSErr
            // value (and the rewritten ioVRefNum) therefore differ
            // between the two; the behavioral invariants are (a) the
            // dispatcher convention writing the same OSErr into both D0
            // and ioResult, and (b) the register-only OS-bit FUNCTION
            // calling convention preserving A7.
            //
            // Regression coverage:
            //   pbmountvol_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            (false, 0x0F) => {
                let pb = cpu.read_reg(Register::A0);
                bus.write_word(pb + 22, super::TrapDispatcher::boot_volume_ref_num_u16());
                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBAllocate ($A010) / PBAllocContig ($A210)
            // Preallocates ioReqCount bytes on the open file referenced by
            // ioRefNum. ioActCount on output is the bytes actually allocated
            // (rounded up to allocation-block size on real Mac; Systemless
            // matches the request exactly).
            // FUNCTION PBAllocate    (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // FUNCTION PBAllocContig (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // Inside Macintosh: Files (1992), pp. 2-130 to 2-131. The HFS
            // variant ($A210) shares this arm via the OS-trap low-byte mask;
            // both behave identically in Systemless's flat unbounded VFS where
            // contiguous-vs-best-fit is moot.
            //
            // Per IM:Files 1992 p. 2-130 the trap word $A010 is an OS-bit
            // FUNCTION (bit 11 of the trap word is clear) with a strict
            // register-only calling convention:
            //
            //   Entry: A0 = ParmBlkPtr (pointer to the I/O parameter
            //                           block; see IM:Files 1992 p. 2-130
            //                           for the field layout — ioCompletion
            //                           at +12, ioResult at +16, ioRefNum
            //                           at +24, ioReqCount at +36, ioActCount
            //                           at +40)
            //   Exit:  D0 = OSErr     (mirrored into pb.ioResult at pb+16
            //                          per the File Manager dispatcher
            //                          convention, IM:II 1985 p. II-114)
            //
            // Documented result codes (IM:Files 1992, pp. 2-130 to 2-131):
            //   noErr     0    No error
            //   ioErr    -36   I/O error
            //   dskFulErr-34   Disk full
            //   fnfErr   -43   File not found
            //   wPrErr   -44   Hardware volume lock
            //   fLckdErr -45   File is locked
            //   vLckdErr -46   Software volume lock
            //   rfNumErr -51   Bad reference number
            //
            // MPW Universal Headers `Files.h` declares the trap as:
            //   #pragma parameter __D0 PBAllocateSync(__A0)
            //   EXTERN_API(OSErr) PBAllocateSync(ParmBlkPtr paramBlock)
            //       ONEWORDINLINE(0xA010);
            //   #define PBAllocate(pb, async) \
            //       ((async) ? PBAllocateAsync(pb) : PBAllocateSync(pb))
            //
            // Systemless HLE compromise: the unbounded-VFS HLE skips refnum
            // validation and treats every PBAllocate as a success that
            // writes ioActCount = ioReqCount (the requested byte count)
            // and noErr (0) to both D0 and pb.ioResult. There is no real
            // file table or allocation-block fragmentation to validate
            // against, so any caller request succeeds. BasiliskII System
            // 7.5.3 ROM dispatches the real PB trap and is expected to
            // return rfNumErr (-51) for ioRefNum 9999 since no such open
            // file exists in the BasiliskII session.
            //
            // Behavioral invariant: regardless of the absolute OSErr value,
            // the File Manager dispatcher convention (IM:II 1985 p. II-114)
            // writes the SAME value to BOTH D0 and pb.ioResult at pb+16;
            // A7 is preserved across the call since the OS-bit FUNCTION ABI
            // takes no Pascal stack frame. The contiguous-allocation variant
            // ($A210) differs from PBAllocate only in that the real Apple ROM
            // returns dskFulErr (-34) on contiguous-fit failure rather than
            // performing a partial allocation, but both traps obey the same
            // dispatcher convention.
            //
            // Regression coverage:
            //   pballocate_nominal_call_returns_noerr_and_sets_ioactcount
            //   pballocate_writes_ioresult_noerr_when_paramblock_present
            //   pballocate_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            //   pballoccontig_nominal_call_returns_noerr_and_sets_ioactcount
            //   pballoccontig_overwrites_ioresult_field_with_function_result
            //   pballoccontig_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            (false, 0x10) => {
                let pb = cpu.read_reg(Register::A0);
                let req_count = bus.read_long(pb + 36); // ioReqCount
                bus.write_long(pb + 40, req_count); // ioActCount
                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // FInitQueue ($A016)
            // Clears all queued File Manager calls except the current one.
            // PROCEDURE FInitQueue;
            // Inside Macintosh Volume II (1985), p. II-103; Inside
            // Macintosh Volume IV (1986), p. IV-128.
            //
            // Per IM:II 1985 p. II-103 FInitQueue is a parameterless
            // PROCEDURE that clears all queued File Manager calls
            // except the one currently in progress. The trap word
            // $A016 is OS-bit (bit 11 of the trap word is clear); the
            // calling convention is register-only with no inputs and
            // no Pascal FUNCTION result slot.
            //
            // MPW Universal Headers `Files.h` declares the trap as:
            //   EXTERN_API(void) FInitQueue(void) ONEWORDINLINE(0xA016);
            //
            // Systemless HLE compromise: the File Manager I/O queue is
            // permanently empty in the single-volume, synchronous-I/O
            // HLE (all File Manager calls complete inline before
            // returning to the caller), so FInitQueue has nothing to
            // clear. The HLE writes D0=0 (noErr, by Memory Manager
            // dispatcher convention for OS-bit PROCEDUREs) and
            // returns without consuming any stack bytes.
            //
            // Behavioral invariant: A7 is preserved across the call (no
            // Pascal stack frame is consumed) and the queue is left in an
            // empty state on exit.
            //
            // Regression coverage:
            //   finitqueue_has_no_parameters_and_preserves_stack_pointer
            (false, 0x16) => {
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBEject ($A017)
            // Flushes the specified volume, places it offline, and ejects it.
            // FUNCTION PBEject (paramBlock: ParmBlkPtr): OSErr;
            // Inside Macintosh: Files (1992), p. 2-141.
            //
            // Register convention (OS-bit FUNCTION; IM:Files 1992 p. 2-141
            // trap macro `_Eject`):
            //   A0 entry: ParmBlkPtr (paramBlock)
            //   D0 exit:  OSErr result code (also mirrored into pb.ioResult
            //             at pb+16 per File Manager basic parameter block
            //             dispatcher convention, IM:II 1985 p. II-114)
            //
            // Parameter block fields used (IM:Files 1992 p. 2-141):
            //   →  ioCompletion (ProcPtr) — pointer to a completion routine
            //   ←  ioResult     (OSErr)   — result code (mirrors D0)
            //   →  ioNamePtr    (StringPtr) — pointer to a pathname
            //   →  ioVRefNum    (Integer) — volume specification
            //
            // Always executes synchronously.
            //
            // Documented result codes (IM:Files 1992 p. 2-141):
            //   noErr     0    No error
            //   nsvErr   -35   No such volume
            //   ioErr    -36   I/O error
            //   bdNamErr -37   Bad volume name
            //   paramErr -50   No default volume
            //   nsDrvErr -56   No such drive
            //   extFSErr -58   External file system
            //
            // MPW Universal Headers Files.h:
            //   #pragma parameter __D0 PBEject(__A0)
            //   EXTERN_API(OSErr) PBEject(ParmBlkPtr paramBlock)
            //     ONEWORDINLINE(0xA017);
            //
            // Systemless HLE compromise: the single-volume HLE has no
            // removable media to eject, so this stub returns noErr (0)
            // unconditionally and writes 0 to pb.ioResult.
            //
            // Behavioral invariant:
            //   • D0 == pb.ioResult (pb+16) after the call (dispatcher
            //     convention IM:II 1985 p. II-114) regardless of the
            //     absolute OSErr value;
            //   • Register-only OS-bit FUNCTION calling convention; no
            //     Pascal stack frame consumed (A7 preserved).
            //
            // Apple-vs-BasiliskII divergence on absolute OSErr: BII
            // System 7.5.3 ROM is expected to return nsvErr (-35) or a
            // related error for a bogus vRefNum (e.g. 9999), while
            // Systemless returns noErr unconditionally. Both obey
            // the dispatcher convention (D0 == ioResult).
            //
            // Regression coverage:
            //   pbeject_returns_noerr_when_hle_has_no_removable_media
            //   pbeject_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            (false, 0x17) => {
                let pb = cpu.read_reg(Register::A0);
                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBOffLine ($A035)
            // Places the specified volume offline by calling PBFlushVol to
            // flush the volume and releasing all the memory used for the
            // volume except for the volume control block.
            // FUNCTION PBOffLine (paramBlock: ParmBlkPtr): OSErr;
            // Inside Macintosh: Files (1992), pp. 2-141 to 2-142.
            //
            // Register convention (OS-bit FUNCTION; IM:Files 1992 p. 2-142
            // trap macro `_OffLine`):
            //   A0 entry: ParmBlkPtr (paramBlock)
            //   D0 exit:  OSErr result code (also mirrored into pb.ioResult
            //             at pb+16 per File Manager dispatcher convention,
            //             IM:II 1985 p. II-114)
            //
            // Parameter block fields used (IM:Files 1992 p. 2-141):
            //   →  ioCompletion (ProcPtr) — pointer to a completion routine
            //   ←  ioResult     (OSErr)   — result code (mirrors D0)
            //   →  ioNamePtr    (StringPtr) — pointer to a pathname
            //   →  ioVRefNum    (Integer) — volume specification
            //
            // Always executes synchronously.
            //
            // Documented result codes (IM:Files 1992 p. 2-142):
            //   noErr     0    No error
            //   nsvErr   -35   No such volume
            //   ioErr    -36   I/O error
            //   bdNamErr -37   Bad volume name
            //   paramErr -50   No default volume
            //   nsDrvErr -56   No such drive
            //   extFSErr -58   External file system
            //
            // MPW Universal Headers (Files.h):
            //   #pragma parameter __D0 PBOffLine(__A0)
            //   EXTERN_API(OSErr) PBOffLine(ParmBlkPtr paramBlock)
            //                                          ONEWORDINLINE(0xA035);
            //
            // Systemless HLE compromise: the single-volume HLE has no offline-
            // able volume (the boot volume is permanently online in our
            // VFS), so the trap collapses to a no-op that writes noErr (0)
            // into both D0 and pb.ioResult. BasiliskII dispatches the real
            // ROM PB trap and may return a non-zero OSErr (typically
            // nsvErr -35) for a bogus vRefNum. The absolute return value
            // therefore differs between the two; the behavioral invariants
            // are (a) the dispatcher convention writing the same OSErr into
            // both D0 and ioResult, and (b) the register-only OS-bit
            // FUNCTION calling convention preserving A7.
            //
            // Regression coverage:
            //   pboffline_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            (false, 0x35) => {
                let pb = cpu.read_reg(Register::A0);
                bus.write_word(pb + 16, 0); // noErr → pb.ioResult
                cpu.write_reg(Register::D0, 0); // noErr → D0
                Ok(())
            }

            // PBSetFVers / _SetFilType ($A043)
            // Changes the version number of a file (high byte of ioMisc).
            // FUNCTION PBSetFVers (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh Volume II, II-117 / Volume IV, IV-153
            //
            // Register convention (IM:II 1985 p. II-114 File Manager basic-PB
            // dispatcher; IM:II 1985 p. II-117 PBSetFVers entry):
            //   A0 (entry) = ParmBlkPtr — pointer to the parameter block.
            //   D0 (exit)  = OSErr — function result, also mirrored to
            //                pb.ioResult at pb+16 by the OS dispatcher.
            //
            // OS-bit FUNCTION ABI: no Pascal stack argument frame; A7 is
            // preserved across the call. The MPW Universal Headers Files.h
            // declaration confirms the register-only convention:
            //   #pragma parameter __D0 PBSetFVersSync(__A0)
            //   EXTERN_API(OSErr) PBSetFVersSync(ParmBlkPtr paramBlock)
            //                                   ONEWORDINLINE(0xA043);
            //
            // IOParam field map (IM:II 1985 p. II-117):
            //   → 12 ioCompletion pointer (NIL for synchronous calls)
            //   ← 16 ioResult     word    (mirrored from D0)
            //   → 18 ioNamePtr    pointer (Pascal-string file name)
            //   → 22 ioVRefNum    word    (volume reference number)
            //   → 26 ioFVersNum   byte    (current MFS version number)
            //   → 28 ioMisc       byte    (new version in high-order byte)
            //
            // Documented result codes (IM:II 1985 p. II-117):
            //   noErr     ( 0) — call succeeded (and on HFS volumes always)
            //   bdNamErr  (-37) — bad file name
            //   dupFNErr  (-48) — duplicate file name and version
            //   extFSErr  (-58) — external file system
            //   fLckdErr  (-45) — file locked
            //   fnfErr    (-43) — file not found
            //   nsvErr    (-35) — no such volume
            //   wPrErr    (-44) — hardware volume lock
            //
            // Per IM:IV 1986 p. IV-153 (HFS update): "PBSetFVers has no
            // effect on hierarchical volumes." Per IM:II 1985 p. II-117
            // verbatim warning: "The Resource Manager, the Segment Loader,
            // and the Standard File Package operate only on files with
            // version number 0; changing the version number of a file to
            // a nonzero number will prevent them from operating on it."
            //
            // Systemless HLE compromise: the host VFS is HFS-only, so every
            // file is implicitly at version 0 and PBSetFVers is a no-op.
            // We write 0 (noErr) to both pb.ioResult @ pb+16 and D0,
            // honoring the basic-PB dispatcher convention.
            //
            // Behavioral invariant:
            //   1. Dispatcher convention: D0 == pb.ioResult after the call
            //      (both registers receive the same OSErr).
            //   2. Register-only ABI: A0 is the sole input, D0 the sole
            //      output; A7 unchanged.
            //
            // BasiliskII parity note: BII System 7.5.3 ROM dispatches the
            // real PB trap against an HFS volume mounted via extfs. Per
            // IM:IV 1986 p. IV-153 PBSetFVers is a documented no-op there,
            // so the absolute OSErr is expected to be noErr (0) as well.
            // Where the absolute OSErr diverges, that value is still
            // mirrored into both D0 and ioResult.
            //
            // Regression coverage:
            //   pbsetfvers_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            //
            // PBSetFVers ($A043): HFS no-op per IM:IV 1986 p. IV-153;
            // mirrors noErr to D0 and pb.ioResult per IM:II 1985 p. II-114
            // dispatcher convention; preserves A7 per the register-only
            // OS-bit FUNCTION ABI.
            (false, 0x43) => {
                let pb = cpu.read_reg(Register::A0);
                bus.write_word(pb + 16, 0); // noErr → pb.ioResult
                cpu.write_reg(Register::D0, 0); // noErr → D0
                Ok(())
            }

            // AddDrive ($A04E)
            // Adds a drive queue element to the drive queue. Register-form:
            // D0.W = drvNum, D1.W = drvrRefNum, A0 = qEl.
            // PROCEDURE AddDrive (drvrRefNum, drvNum: Integer; qEl: DrvQElPtr);
            // Inside Macintosh: Files (1992), p. 2-236; Technical Note #108
            // "AddDrive, DrvrInstall and DrvrRemove" documents the register
            // calling convention and noErr return.
            // AddDrive ($A04E): No drive queue in HLE; PROCEDURE returns via D0 = noErr.
            (false, 0x4E) => {
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBRename / PBHRename ($A00B / $A20B)
            // Renames a file or directory. PBHRename is the HFS variant.
            // FUNCTION PBRename  (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // FUNCTION PBHRename (paramBlock: HParmBlkPtr; async: Boolean): OSErr;
            // Inside Macintosh: Files (1992), p. 2-118
            //
            // Register convention (IM:Files 1992 p. 2-118):
            //   A0 entry: ParmBlkPtr / HParmBlkPtr (pb)
            //   D0 exit:  OSErr (mirrored to pb.ioResult at pb+16 by the
            //             File Manager basic-PB dispatcher convention,
            //             IM:II 1985 p. II-114).
            //   No Pascal stack frame is consumed (OS-bit FUNCTION ABI).
            //
            // Parameter block fields (IM:Files 1992 p. 2-118):
            //   pb+12 ioCompletion (→) IOCompletionUPP, may be NIL on Sync
            //   pb+16 ioResult     (←) OSErr, mirror of D0
            //   pb+18 ioNamePtr    (→) StringPtr, OLD file name
            //   pb+22 ioVRefNum    (→) volume reference number
            //   pb+28 ioMisc       (→) StringPtr, NEW file name
            //   pb+48 ioDirID      (→) HFS variant only; directory ID
            //
            // Documented result codes (IM:Files 1992 pp. 2-118, 10222..10234):
            //   noErr     0    No error
            //   nsvErr   -35   No such volume
            //   ioErr    -36   I/O error
            //   bdNamErr -37   Bad name
            //   fnfErr   -43   File not found (source missing)
            //   wPrErr   -44   Diskette write-protected
            //   fLckdErr -45   File locked
            //   vLckdErr -46   Volume locked
            //   dupFNErr -48   Duplicate file name (destination exists)
            //   paramErr -50   Empty name
            //
            // MPW Universal Headers (Files.h):
            //   #pragma parameter __D0 PBRenameSync(__A0)
            //   EXTERN_API(OSErr) PBRenameSync(ParmBlkPtr paramBlock)
            //       ONEWORDINLINE(0xA00B);
            //   #pragma parameter __D0 PBHRenameSync(__A0)
            //   EXTERN_API(OSErr) PBHRenameSync(HParmBlkPtr paramBlock)
            //       ONEWORDINLINE(0xA20B);
            //   Sibling Async forms at $A40B and $A60B respectively.
            //
            // Behavioral invariant:
            //   - dispatcher convention: D0 == ioResult @ pb+16.
            //   - register-only calling convention: A7 preserved.
            //
            // Systemless HLE: maintains VFS state in self.vfs / self.vfs_rsrc /
            // self.vfs_metadata / self.locked_files / self.open_files /
            // self.output_dir; the same (false, 0x0B) arm services both
            // $A00B and $A20B since the HFS variant differs only in the
            // ioDirID field which Systemless does not branch on.
            //
            // Regression coverage:
            //   pbhrename_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            //   pbhrename_path_new_name_stays_in_source_directory
            (false, 0x0B) => {
                let pb = cpu.read_reg(Register::A0);
                let old_name_ptr = bus.read_long(pb + 18);
                let new_name_ptr = bus.read_long(pb + 28);
                let old_name = Self::read_pb_filename(bus, old_name_ptr);
                let new_name = Self::read_pb_filename(bus, new_name_ptr);
                eprintln!("[TRAP] PBRename(\"{}\" -> \"{}\")", old_name, new_name);

                if old_name.is_empty() || new_name.is_empty() {
                    bus.write_word(pb + 16, (-50i16) as u16); // paramErr
                    cpu.write_reg(Register::D0, (-50i32) as u32);
                    return Some(Ok(()));
                }

                let Some(old_key) = self.find_vfs_file(&old_name) else {
                    bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                    cpu.write_reg(Register::D0, (-43i32) as u32);
                    return Some(Ok(()));
                };

                if self.vfs_path_is_read_only(&old_key) {
                    bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                    cpu.write_reg(Register::D0, (-44i32) as u32);
                    return Some(Ok(()));
                }

                // Compute new key by replacing the basename of old_key.
                // PBHRename cannot move a file to another directory
                // (Inside Macintosh: Files, 1992, p. 2-199), so even if a
                // caller passes a colon pathname in ioMisc, only its final
                // name participates in the rename.
                let normalized_new = super::TrapDispatcher::normalize_hfs_path(&new_name);
                let new_leaf = super::TrapDispatcher::vfs_basename(&normalized_new);
                if new_leaf.is_empty() {
                    bus.write_word(pb + 16, (-50i16) as u16); // paramErr
                    cpu.write_reg(Register::D0, (-50i32) as u32);
                    return Some(Ok(()));
                }
                let new_key = match old_key.rsplit_once('/') {
                    Some((parent, _)) => format!("{parent}/{new_leaf}"),
                    None => new_leaf.to_string(),
                };

                if new_key == old_key {
                    // Rename to the same name is a noErr no-op per Files
                    // 1992, 2-118 (the file is unaffected).
                    bus.write_word(pb + 16, 0);
                    cpu.write_reg(Register::D0, 0);
                    return Some(Ok(()));
                }

                if self.vfs.contains_key(&new_key) || self.vfs_rsrc.contains_key(&new_key) {
                    bus.write_word(pb + 16, (-48i16) as u16); // dupFNErr
                    cpu.write_reg(Register::D0, (-48i32) as u32);
                    return Some(Ok(()));
                }

                if let Some(data) = self.vfs.remove(&old_key) {
                    self.vfs.insert(new_key.clone(), data);
                }
                if let Some(rsrc) = self.vfs_rsrc.remove(&old_key) {
                    self.vfs_rsrc.insert(new_key.clone(), rsrc);
                }
                if let Some(metadata) = self.vfs_metadata.remove(&old_key) {
                    self.vfs_metadata.insert(new_key.clone(), metadata);
                }
                if self.locked_files.remove(&old_key) {
                    self.locked_files.insert(new_key.clone());
                }
                self.remove_vfs_entry_from_process(&old_key);
                self.publish_vfs_entry_to_process(&new_key);
                // Open access paths must follow the rename so a
                // subsequent FSRead/FSWrite still resolves to the file.
                let open_refnums: Vec<u16> = self
                    .open_files
                    .iter()
                    .filter_map(|record| {
                        if record.path == old_key {
                            u16::try_from(record.ref_num).ok()
                        } else {
                            None
                        }
                    })
                    .collect();
                for refnum in open_refnums {
                    self.open_files.insert(refnum, new_key.clone());
                }

                if let Some(ref dir) = self.output_dir {
                    let old_path = dir.join(&old_key);
                    let new_path = dir.join(&new_key);
                    if let Some(parent) = new_path.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    let _ = std::fs::rename(old_path, new_path);
                }

                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBSetFLock / PBHSetFLock ($A041 / $A241)
            // Locks a file by setting bit 0 of ioFlAttrib (visible via
            // subsequent PBGetFInfo / PBHGetFInfo).
            // FUNCTION PBSetFLock (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // FUNCTION PBHSetFLock (paramBlock: HParmBlkPtr; async: Boolean): OSErr;
            // Inside Macintosh: Files 1992, pp. 2-110 to 2-111
            //
            // Register convention (IM:Files 1992 p. 2-110):
            //   A0 entry: ParmBlkPtr (pb)
            //   D0 exit:  OSErr (mirrored to pb.ioResult at pb+16 by the
            //             File Manager basic-PB dispatcher convention,
            //             IM:II 1985 p. II-114).
            //   No Pascal stack frame is consumed.
            //
            // Parameter block fields (IM:Files 1992 p. 2-110):
            //   pb+12 ioCompletion (→) IOCompletionUPP, may be NIL on Sync
            //   pb+16 ioResult     (←) OSErr, mirror of D0
            //   pb+18 ioNamePtr    (→) StringPtr, file name (Pascal string)
            //   pb+22 ioVRefNum    (→) volume reference number (0 = default)
            //
            // Documented result codes (IM:Files 1992 pp. 2-110, 10141..10150):
            //   noErr     0    No error
            //   fnfErr    -43  File not found
            //   ioErr     -36  I/O error
            //   nsvErr    -35  Volume not found
            //   bdNamErr  -37  Bad filename
            //   paramErr  -50  ioVRefNum bad / ioNamePtr is NIL
            //
            // MPW Universal Headers Files.h:
            //   #pragma parameter __D0 PBSetFLockSync(__A0)
            //   EXTERN_API(OSErr) PBSetFLockSync(ParmBlkPtr paramBlock)
            //                                       ONEWORDINLINE(0xA041);
            //   #define PBSetFLock(pb,async) (async ? PBSetFLockAsync(pb) : PBSetFLockSync(pb))
            //
            // Systemless HLE: maintains lock state in self.locked_files and
            // returns -43 fnfErr for files not in the VFS, matching IM
            // verbatim.
            //
            // BasiliskII divergence note: real System 7.5.3 + extfs
            // returns noErr (0) from PBSetFLock / PBHSetFLock on a
            // missing file, not fnfErr (-43). Systemless keeps the
            // IM-documented absolute OSErr; both obey the dispatcher
            // convention writing the same value to BOTH D0 and
            // pb.ioResult @ pb+16.
            //
            // Regression coverage:
            //   pbsetflock_existing_file_returns_noerr_and_sets_ioflattrib_locked_bit
            //   pbsetflock_missing_file_returns_fnferr_in_d0_and_ioresult
            //   pbsetflock_pbrstflock_write_same_oserr_to_d0_and_ioresult_preserving_stack
            //   pbhsetflock_pbhrstflock_write_same_oserr_to_d0_and_ioresult_preserving_stack
            //   pbrstflock_existing_file_returns_noerr_and_clears_ioflattrib_locked_bit
            //   pbrstflock_missing_file_returns_fnferr_in_d0_and_ioresult
            //   pbhsetflock_existing_file_returns_noerr_and_sets_ioflattrib_locked_bit
            //   pbhrstflock_existing_file_returns_noerr_and_clears_ioflattrib_locked_bit
            (false, 0x41) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let filename = Self::read_pb_filename(bus, name_ptr);
                eprintln!("[TRAP] PBSetFLock(\"{}\")", filename);

                if let Some(vfs_name) = self.find_vfs_file(&filename) {
                    if self.vfs_path_is_read_only(&vfs_name) {
                        bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                        cpu.write_reg(Register::D0, (-44i32) as u32);
                    } else {
                        self.locked_files.insert(vfs_name);
                        bus.write_word(pb + 16, 0); // noErr
                        cpu.write_reg(Register::D0, 0);
                    }
                } else {
                    bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                    cpu.write_reg(Register::D0, (-43i32) as u32);
                }
                Ok(())
            }

            // PBRstFLock / PBHRstFLock ($A042 / $A242)
            // Unlocks a file by clearing bit 0 of ioFlAttrib.
            // FUNCTION PBRstFLock (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // FUNCTION PBHRstFLock (paramBlock: HParmBlkPtr; async: Boolean): OSErr;
            // Inside Macintosh: Files 1992, pp. 2-110 to 2-111
            //
            // Register convention, parameter-block field map, result-
            // code table, MPW Universal Headers declaration, Systemless
            // HLE compromise, and BasiliskII divergence note are all
            // identical to the $A041 PBSetFLock arm above (just swap
            // PBSetFLock → PBRstFLock and ONEWORDINLINE(0xA041) →
            // ONEWORDINLINE(0xA042)).
            //
            // Regression coverage: see the $A041 arm above.
            (false, 0x42) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let filename = Self::read_pb_filename(bus, name_ptr);
                eprintln!("[TRAP] PBRstFLock(\"{}\")", filename);

                if let Some(vfs_name) = self.find_vfs_file(&filename) {
                    if self.vfs_path_is_read_only(&vfs_name) {
                        bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                        cpu.write_reg(Register::D0, (-44i32) as u32);
                    } else {
                        self.locked_files.remove(&vfs_name);
                        bus.write_word(pb + 16, 0); // noErr
                        cpu.write_reg(Register::D0, 0);
                    }
                } else {
                    bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                    cpu.write_reg(Register::D0, (-43i32) as u32);
                }
                Ok(())
            }

            // PBCreate / PBHCreate (0xA008 / 0xA208)
            // Creates a new file.
            // FUNCTION PBCreate (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // FUNCTION PBHCreate (paramBlock: HParmBlkPtr; async: BOOLEAN): OSErr;
            // Files 1992, 2-89 / 9279 (PBCreate) and 2-191 / 9700 (PBHCreate).
            // The OS-trap dispatcher masks `trap & 0x00FF`, so $A208
            // PBHCreate lands on the same low byte and shares this arm.
            //
            // Behavioral note: for a $A208 PBHCreate with dirID=999999,
            // BasiliskII writes dirNFErr per IM:Files 9743 while Systemless
            // writes noErr because the impl does not validate dirID.
            //
            // Regression coverage:
            //   pb_create
            // PBCreate ($A008): Creates file in VFS with metadata, writes to output_dir if set
            // PBHCreate ($A208): HFS variant aliased onto $A008
            (false, 0x08) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let filename = Self::read_pb_filename(bus, name_ptr);
                let v_ref = bus.read_word(pb + 22) as i16;
                let is_hfs_variant = matches!(
                    raw_trap_route(self.current_trap_word).os_routine_variant,
                    OsRoutineVariant::FileHfsSynchronous | OsRoutineVariant::FileHfsAsynchronous
                );
                let dir_id = if is_hfs_variant {
                    bus.read_long(pb + 48)
                } else {
                    0
                };
                eprintln!(
                    "[TRAP] {}(\"{}\") vref={} dirID={}",
                    if is_hfs_variant {
                        "PBHCreate"
                    } else {
                        "PBCreate"
                    },
                    filename,
                    v_ref,
                    dir_id
                );

                if filename.is_empty() {
                    bus.write_word(pb + 16, (-50i16) as u16); // paramErr
                    cpu.write_reg(Register::D0, (-50i32) as u32);
                    return Some(Ok(()));
                }
                let vfs_key = self
                    .vfs_key_for_fsspec(v_ref, dir_id, &filename)
                    .unwrap_or_else(|| super::TrapDispatcher::normalize_hfs_path(&filename));

                if self.vfs_path_is_read_only(&vfs_key) {
                    bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                    cpu.write_reg(Register::D0, (-44i32) as u32);
                    return Some(Ok(()));
                }

                // Inside Macintosh: Files (1992), PBCreate pp. 2-89--2-90
                // and PBHCreate pp. 2-191--2-192: an existing name returns
                // dupFNErr without changing either fork.
                let existing = self
                    .vfs
                    .keys()
                    .chain(self.vfs_rsrc.keys())
                    .find(|key| key.eq_ignore_ascii_case(&vfs_key))
                    .cloned();
                if existing.is_some() {
                    bus.write_word(pb + 16, (-48i16) as u16); // dupFNErr
                    cpu.write_reg(Register::D0, (-48i32) as u32);
                    return Some(Ok(()));
                }

                self.vfs.insert(vfs_key.clone(), Vec::new());
                // Real Mac files always have both forks. PBCreate must seed
                // an empty resource fork too, otherwise a subsequent
                // PBOpenRF on the new file (e.g. Mars Rising's installer
                // pattern: PBCreate "Installer Temp (delete)" then
                // PBOpenRF that file's resource fork) returns fnfErr and
                // the installer halts via _ExitToShell.
                // Files 1992, 1-58 (each file has data + resource fork)
                self.vfs_rsrc.insert(vfs_key.clone(), Vec::new());
                self.touch_vfs_entry(&vfs_key);
                if let Some(ref dir) = self.output_dir {
                    let host_path = dir.join(&vfs_key);
                    if let Some(parent) = host_path.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    let _ = std::fs::write(host_path, []);
                }

                bus.write_word(pb + 16, 0);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBDelete / PBHDelete (0xA009 / 0xA209)
            // Deletes a file.
            // FUNCTION PBDelete (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // FUNCTION PBHDelete (paramBlock: HParmBlkPtr; async: BOOLEAN): OSErr;
            // Files 1992, 2-102 / 9286 (PBDelete) and 2-189 / 9797 (PBHDelete).
            // The HFS variant lands on the same low byte after
            // `trap & 0x00FF` masking and shares this arm.
            //
            // Behavioral note: real Mac extfs (BasiliskII) returns noErr for
            // a missing file on the $A209 PBHDelete path.
            //
            // Regression coverage:
            //   pb_delete
            //   pb_delete_not_found
            // PBDelete ($A009): Deletes file from VFS, cleans up metadata and open file refs
            // PBHDelete ($A209): HFS variant aliased onto $A009
            (false, 0x09) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let filename = Self::read_pb_filename(bus, name_ptr);
                eprintln!("[TRAP] PBDelete(\"{}\")", filename);

                if filename.is_empty() {
                    bus.write_word(pb + 16, (-50i16) as u16); // paramErr
                    cpu.write_reg(Register::D0, (-50i32) as u32);
                    return Some(Ok(()));
                }

                if let Some(vfs_name) = self.find_vfs_file(&filename) {
                    if self.vfs_path_is_read_only(&vfs_name) {
                        bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                        cpu.write_reg(Register::D0, (-44i32) as u32);
                        return Some(Ok(()));
                    }
                    self.vfs.remove(&vfs_name);
                    self.vfs_rsrc.remove(&vfs_name);
                    self.remove_vfs_entry_metadata(&vfs_name);

                    let stale_refs: Vec<u16> = self
                        .open_files
                        .iter()
                        .filter_map(|record| {
                            if record.path == vfs_name {
                                u16::try_from(record.ref_num).ok()
                            } else {
                                None
                            }
                        })
                        .collect();
                    for refnum in stale_refs {
                        self.open_files.remove(&refnum);
                        self.file_positions.remove(&refnum);
                        self.write_refnums.remove(&refnum);
                        Self::clear_file_fcb(bus, refnum);
                    }

                    if let Some(ref dir) = self.output_dir {
                        let host_path = dir.join(&vfs_name);
                        let _ = std::fs::remove_file(host_path);
                    }

                    bus.write_word(pb + 16, 0);
                    cpu.write_reg(Register::D0, 0);
                } else {
                    bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                    cpu.write_reg(Register::D0, (-43i32) as u32);
                }
                Ok(())
            }

            // PBGetFInfo / PBHGetFInfo (0xA00C / 0xA20C)
            // Gets Finder and catalog information for a file.
            // FUNCTION PBGetFInfo (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // FUNCTION PBHGetFInfo (paramBlock: HParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh Volume IV, IV-148; Files 1992, 2-170.
            // The HFS variant ($A20C) is aliased onto this arm via the OS-trap
            // `trap & 0x00FF` mask.
            //
            // PBGetFInfo ($A00C): Returns catalog info with file type, creator, finder flags, and ioFlAttrib lock bit from VFS metadata
            // PBHGetFInfo ($A20C): HFS variant aliased onto $A00C
            (false, 0x0C) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let filename = Self::read_pb_filename(bus, name_ptr);
                let vref = bus.read_word(pb + 22) as i16;
                let fdir_index = bus.read_word(pb + 28) as i16;
                let dir_id = bus.read_long(pb + 48);
                eprintln!(
                    "[TRAP] PBGetFInfo(\"{}\", vRefNum={}, dirID={}, fDirIndex={})",
                    filename, vref, dir_id, fdir_index
                );

                let lookup = if fdir_index > 0 {
                    self.lookup_file_entry_for_get_finfo(vref, dir_id, &filename, fdir_index)
                        .map(|entry| entry.path)
                } else {
                    self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                        .or_else(|| self.find_vfs_file(&filename))
                };

                if let Some(vfs_name) = lookup {
                    let open_refnum = self
                        .open_files
                        .iter()
                        .find(|record| record.path.eq_ignore_ascii_case(&vfs_name))
                        .and_then(|record| u16::try_from(record.ref_num).ok())
                        .or_else(|| self.refnum_for_resource_file_name(&vfs_name));
                    if let Some(metadata) = self.vfs_file_metadata(&vfs_name) {
                        self.fill_file_catalog_info(bus, pb, &vfs_name, metadata);
                        // Inside Macintosh Volume IV, pp. IV-148–149: for a
                        // name-based PBGetFInfo call, ioNamePtr is returned as
                        // the leaf name when an access path to the file is
                        // open. Closed files leave the caller's pathname in
                        // place so the documented PBGetFInfo -> PBSetFInfo
                        // sequence continues to identify the same file.
                        // Indexed calls still need the discovered leaf name.
                        if name_ptr != 0 && (fdir_index > 0 || open_refnum.is_some()) {
                            let guest_name = super::TrapDispatcher::hfs_name_from_vfs_component(
                                super::TrapDispatcher::vfs_basename(&vfs_name),
                            );
                            Self::write_pstring(bus, name_ptr, &guest_name);
                        }
                        bus.write_word(pb + 24, open_refnum.unwrap_or(0));
                    }
                    bus.write_word(pb + 16, 0); // noErr
                    cpu.write_reg(Register::D0, 0);
                } else {
                    bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                    cpu.write_reg(Register::D0, (-43i32) as u32);
                }
                Ok(())
            }

            // PBSetFInfo / PBHSetFInfo (0xA00D / 0xA20D)
            // Sets Finder information for a file.
            // FUNCTION PBSetFInfo (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // FUNCTION PBHSetFInfo (paramBlock: HParmBlkPtr; async: BOOLEAN): OSErr;
            // Files 1992, 2-205 / 9298.  The HFS variant ($A20D) is the
            // same low byte after `trap & 0x00FF` masking and shares
            // this arm.
            //
            // Per Files 1992, 2-205: returns fnfErr (-43) if the named
            // file does not exist. The previous HLE implementation
            // silently returned noErr for missing files, masking bugs in
            // games that rely on this error to detect missing saves.
            //
            //   pb_finfo               ← $A00C/$A00D fnfErr path
            //   pbh_get_set_finfo      ← $A20C/$A20D fnfErr path
            // PBSetFInfo ($A00D): Stores file type, creator, and Finder flags in VFS metadata
            // PBHSetFInfo ($A20D): HFS variant aliased onto $A00D
            (false, 0x0D) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let filename = Self::read_pb_filename(bus, name_ptr);
                let vref = bus.read_word(pb + 22) as i16;
                let dir_id = bus.read_long(pb + 48);
                eprintln!("[TRAP] PBSetFInfo(\"{}\")", filename);
                if let Some(vfs_name) = self
                    .find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                    .or_else(|| self.find_vfs_file(&filename))
                {
                    if self.vfs_path_is_read_only(&vfs_name) {
                        bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                        cpu.write_reg(Register::D0, (-44i32) as u32);
                        return Some(Ok(()));
                    }
                    let file_type = bus.read_long(pb + 32);
                    let creator = bus.read_long(pb + 36);
                    let finder_flags = bus.read_word(pb + 40);
                    self.set_vfs_entry_finfo(&vfs_name, file_type, creator, finder_flags);
                    bus.write_word(pb + 16, 0); // noErr
                    cpu.write_reg(Register::D0, 0);
                } else {
                    bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                    cpu.write_reg(Register::D0, (-43i32) as u32);
                }
                Ok(())
            }

            // PBSetVol / PBHSetVol (0xA015 / 0xA215)
            // Sets the default volume and directory from a parameter block.
            // FUNCTION PBSetVol  (paramBlock: ParmBlkPtr; async: Boolean): OSErr;
            // FUNCTION PBHSetVol (paramBlock: WDPBPtr;    async: Boolean): OSErr;
            // Inside Macintosh: Files 1992, 2-151 to 2-154
            (false, 0x15) => {
                let pb = cpu.read_reg(Register::A0);
                let name_ptr = bus.read_long(pb + 18);
                let name = Self::read_pb_filename(bus, name_ptr);
                let requested_vref = bus.read_word(pb + 22) as i16;
                let is_hfs_set_vol = matches!(
                    raw_trap_route(self.current_trap_word).os_routine_variant,
                    OsRoutineVariant::FileHfsSynchronous | OsRoutineVariant::FileHfsAsynchronous
                );
                let requested_dir_id = if is_hfs_set_vol {
                    bus.read_long(pb + 48)
                } else {
                    0
                };

                let named_volume = (!name.is_empty())
                    .then(|| {
                        if name.eq_ignore_ascii_case(super::TrapDispatcher::boot_volume_name()) {
                            Some((super::TrapDispatcher::boot_volume_ref_num(), 2u32))
                        } else {
                            self.vfs_volume_by_name(&name)
                                .map(|volume| (volume.ref_num, volume.root_dir_id))
                        }
                    })
                    .flatten();
                let matching_working_directory = self
                    .working_directories
                    .get(&requested_vref)
                    .copied()
                    .filter(|working_directory| {
                        named_volume.is_none_or(|(volume_ref_num, _)| {
                            volume_ref_num == working_directory.volume_ref_num
                        })
                    });
                if requested_vref == 0 && !name.is_empty() && named_volume.is_none() {
                    let nsverr: i16 = -35;
                    bus.write_word(pb + 16, nsverr as u16);
                    cpu.write_reg(Register::D0, nsverr as u32);
                    return Some(Ok(()));
                }
                let mut target_volume_ref_num = matching_working_directory
                    .map(|working_directory| working_directory.volume_ref_num)
                    .or_else(|| named_volume.map(|(volume_ref_num, _)| volume_ref_num))
                    .unwrap_or_else(|| self.resolve_volume_ref_num(requested_vref));
                let mut target_dir_id = if let Some(working_directory) = matching_working_directory
                {
                    working_directory.dir_id
                } else if let Some((_, root_dir_id)) = named_volume {
                    root_dir_id
                } else if let Some(working_directory) =
                    self.working_directories.get(&requested_vref)
                {
                    target_volume_ref_num = working_directory.volume_ref_num;
                    working_directory.dir_id
                } else if is_hfs_set_vol
                    && requested_dir_id != 0
                    && self.directory_entry_for_id(requested_dir_id).is_some()
                {
                    requested_dir_id
                } else if requested_vref == 0 {
                    *self.default_dir_id
                } else if requested_vref == Self::boot_volume_ref_num() {
                    // ioVRefNum = -1: boot volume, use root directory (dirID 2).
                    2
                } else if let Some(volume) = self.vfs_volume_for_ref_num(requested_vref) {
                    volume.root_dir_id
                } else {
                    // Unrecognised volume reference number: nsvErr (-35).
                    // IM:Files 1992, 2-162: "nsvErr — No such volume."
                    let nsverr: i16 = -35;
                    bus.write_word(pb + 16, nsverr as u16);
                    cpu.write_reg(Register::D0, nsverr as u32);
                    return Some(Ok(()));
                };

                if named_volume.is_none() && !name.is_empty() {
                    if let Some(path) = self.find_vfs_directory_in_directory(target_dir_id, &name) {
                        if let Some(directory) = self
                            .vfs_directories
                            .iter()
                            .find(|directory| directory.path.eq_ignore_ascii_case(&path))
                        {
                            target_dir_id = directory.dir_id;
                        }
                    } else if let Some(path) = self.find_vfs_file_in_directory(target_dir_id, &name)
                    {
                        if let Some(metadata) = self.vfs_file_metadata(&path) {
                            target_dir_id = metadata.parent_dir_id;
                        }
                    }
                }

                self.default_dir_id
                    .with_mut(|default_dir_id| *default_dir_id = target_dir_id);
                let app_wd_refnum = if target_dir_id == 2 {
                    target_volume_ref_num
                } else {
                    self.open_working_directory(target_volume_ref_num, target_dir_id, 0)
                        .unwrap_or(target_volume_ref_num)
                };
                self.app_wd_refnum
                    .with_mut(|current| *current = app_wd_refnum);

                // Keep the Standard File globals aligned with the current
                // default directory and volume. Files 1992, 3-65.
                bus.write_long(addr::CUR_DIR_STORE, target_dir_id);
                bus.write_word(addr::SF_SAVE_DISK, (-target_volume_ref_num) as u16);

                eprintln!(
                    "[TRAP] PBSetVol name='{}' request_vRefNum={} request_dirID={} -> current_vRefNum={} current_dirID={}",
                    name,
                    requested_vref,
                    requested_dir_id,
                    *self.app_wd_refnum,
                    *self.default_dir_id
                );
                bus.write_word(pb + 16, 0);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // _CmpString ($A03C), the register-level EqualString operation.
            // On entry: A0 = ptr to first string's first character
            //           A1 = ptr to second string's first character
            //           D0 high word = length of first string
            //           D0 low word  = length of second string
            // On exit:  D0 = 0 if equal, 1 if not equal (long word).
            //
            // MARKS (bit 9) makes comparison diacritic-sensitive; CASE (bit
            // 10) makes it case-sensitive. The bare form ignores both. Inside
            // Macintosh: Text (1993), pp. 5-51--5-52. This later four-row table
            // supersedes the opposite MARKS annotation in Volume II (1985),
            // p. II-377. D0 is 0 for equal and 1 for unequal.
            (false, crate::text_utils::CMP_STRING_TRAP_NUM) => {
                let a_ptr = cpu.read_reg(Register::A0);
                let b_ptr = cpu.read_reg(Register::A1);
                let d0 = cpu.read_reg(Register::D0);
                let a_len = (d0 >> 16) & 0xFFFF;
                let b_len = d0 & 0xFFFF;
                let (case_sensitive, diacritic_sensitive) = raw_trap_route(self.current_trap_word)
                    .os_routine_variant
                    .text_comparison_sensitivity()
                    .expect("CmpString trap word must have a classified comparison variant");

                let result: u32 = if a_len != b_len {
                    1
                } else {
                    let mut bytes_a = Vec::with_capacity(a_len as usize);
                    let mut bytes_b = Vec::with_capacity(b_len as usize);
                    for i in 0..a_len {
                        bytes_a.push(bus.read_byte(a_ptr + i));
                        bytes_b.push(bus.read_byte(b_ptr + i));
                    }
                    let equal = crate::text_utils::evaluate_equal_string(
                        &bytes_a,
                        &bytes_b,
                        case_sensitive,
                        diacritic_sensitive,
                    );
                    u32::from(!equal)
                };
                cpu.write_reg(Register::D0, result);
                Ok(())
            }

            // PBSetEOF / HSetEOF ($A012)
            // Sets the logical end-of-file of an open file.
            // FUNCTION PBSetEOF (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh Volume II, II-113
            // PBSetEOF ($A012): Sets file length, truncates/extends VFS data
            (false, 0x12) => {
                let pb = cpu.read_reg(Register::A0);
                let ref_num = bus.read_word(pb + 24);
                let new_eof = bus.read_long(pb + 28) as usize; // ioMisc

                let Some(filename) = self.open_files.get(&ref_num).cloned() else {
                    bus.write_word(pb + 16, (-51i16) as u16); // rfNumErr
                    cpu.write_reg(Register::D0, (-51i32) as u32);
                    return Some(Ok(()));
                };

                if self.vfs_path_is_read_only(&filename) {
                    bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                    cpu.write_reg(Register::D0, (-44i32) as u32);
                    return Some(Ok(()));
                }

                if !self.write_refnums.contains(&ref_num) {
                    bus.write_word(pb + 16, (-61i16) as u16); // wrPermErr
                    cpu.write_reg(Register::D0, (-61i32) as u32);
                    return Some(Ok(()));
                }

                let host_sync_bytes = self.vfs.with_entry_or_default_mut(
                    filename.clone(),
                    |file_buf| {
                        file_buf.resize(new_eof, 0);
                        if self.output_dir.is_some() {
                            Some(file_buf.clone())
                        } else {
                            None
                        }
                    },
                );

                self.file_positions.with_position_mut(&ref_num, |pos| {
                    let new_eof = u32::try_from(new_eof).unwrap_or(u32::MAX);
                    if *pos > new_eof {
                        *pos = new_eof;
                    }
                });

                if let (Some(dir), Some(bytes)) = (&self.output_dir, host_sync_bytes) {
                    let host_path = dir.join(&filename);
                    if let Some(parent) = host_path.parent() {
                        let _ = std::fs::create_dir_all(parent);
                    }
                    if let Err(e) = std::fs::write(&host_path, bytes) {
                        eprintln!(
                            "[PBSetEOF] failed to sync {} to host ({}): {}",
                            filename,
                            host_path.display(),
                            e
                        );
                    }
                }
                self.touch_vfs_entry(&filename);

                bus.write_word(pb + 16, 0); // noErr
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // OSDispatch (0xA88F)
            // Dispatches Temporary Memory, High-Level Event, and Process Manager routines selected by a stack word.
            // FUNCTION TempMaxMem(VAR grow: Size): Size;
            // Inside Macintosh: Memory (1992), pp. 2-79 to 2-80 and 2-104.
            (true, 0x08F) => {
                let sp_entry = cpu.read_reg(Register::A7);
                let stack_sel = bus.read_word(sp_entry) as u32 & 0xFFFF;
                let operation =
                    os_dispatch_operation_route(self.current_trap_word, stack_sel as u16);
                self.current_selector_operation = operation.map(|route| route.operation_id);
                let d0_sel = cpu.read_reg(Register::D0) & 0xFFFF;
                let (selector, sp, selector_from_stack) = match stack_sel {
                    0x0015 | 0x0016 | 0x0018 | 0x001D..=0x0020 | 0x0033..=0x003D | 0x0043 | 0x0045 => {
                        // Pop the selector word pushed by MOVE.W #sel,-(SP).
                        cpu.write_reg(Register::A7, sp_entry + 2);
                        (stack_sel, sp_entry + 2, true)
                    }
                    _ => (d0_sel, sp_entry, false),
                };
                match selector {
                    0x0043 => {
                        // Private System 7 process-service selector. Its
                        // observed Pascal frame is (Ptr, LongInt) -> OSErr.
                        // No process service is installed here; return
                        // unimpErr with the OSDispatch selector word consumed.
                        bus.write_word(sp + 8, (-4i16) as u16);
                        cpu.write_reg(Register::A7, sp + 8);
                        cpu.write_reg(Register::D0, (-4i32) as u32);
                        Ok(())
                    }
                    0x0015 => {
                        // TempMaxMem (0xA88F selector $0015)
                        // Returns the largest contiguous temporary-memory block.
                        // FUNCTION TempMaxMem(VAR grow: Size): Size;
                        // Inside Macintosh Volume VI, 28-36..28-39; Memory 1992, 2-79..2-80.
                        let grow_ptr = bus.read_long(sp);
                        if grow_ptr != 0 {
                            bus.write_long(grow_ptr, 0);
                        }
                        let free = temporary_memory_free_estimate(bus);
                        bus.write_long(sp + 4, free);
                        cpu.write_reg(Register::D0, free);
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    0x0016 => {
                        // TempTopMem (0xA88F selector $0016)
                        // Returns a pointer to the top of addressable RAM.
                        // FUNCTION TempTopMem: Ptr;
                        // Inside Macintosh Volume VI, 28-37 and 28-45.
                        let mem_top = bus.read_long(crate::memory::globals::addr::MEM_TOP);
                        let result = if mem_top != 0 {
                            mem_top
                        } else {
                            bus.ram_size()
                        };
                        bus.write_long(sp, result);
                        cpu.write_reg(Register::D0, result);
                        Ok(())
                    }
                    0x0018 => {
                        // TempFreeMem (0xA88F selector $0018)
                        // Returns the total amount of free temporary memory.
                        // FUNCTION TempFreeMem: LongInt;
                        // Inside Macintosh Volume VI, 28-38 and 28-45.
                        let free = temporary_memory_free_estimate(bus);
                        bus.write_long(sp, free);
                        cpu.write_reg(Register::D0, free);
                        Ok(())
                    }
                    0x001D => {
                        // TempNewHandle (0xA88F selector $001D)
                        // Allocates a relocatable block of temporary memory.
                        // FUNCTION TempNewHandle(logicalSize: Size; VAR resultCode: OSErr): Handle;
                        // Inside Macintosh Volume VI, 28-36..28-39; Memory 1992, 2-78.
                        let result_code_ptr = bus.read_long(sp);
                        let logical_size = bus.read_long(sp + 4);
                        let ptr = bus.alloc(logical_size);
                        let (handle, result_code) = if ptr == 0 && logical_size > 0 {
                            (0, MEM_FULL_ERR)
                        } else {
                            scribble_temporary_allocation(bus, ptr, logical_size);
                            let handle = bus.alloc(4);
                            if handle == 0 {
                                if ptr != 0 {
                                    bus.free(ptr);
                                }
                                (0, MEM_FULL_ERR)
                            } else {
                                bus.write_long(handle, ptr);
                                self.track_handle_ptr(ptr, handle);
                                (handle, NO_ERR)
                            }
                        };
                        write_temp_memory_result_code(bus, result_code_ptr, result_code);
                        bus.write_long(sp + 8, handle);
                        cpu.write_reg(Register::A0, handle);
                        cpu.write_reg(Register::D0, handle);
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    0x001E | 0x001F => {
                        // TempHLock / TempHUnlock (0xA88F selectors $001E / $001F)
                        // Locks or unlocks a relocatable temporary-memory block.
                        // PROCEDURE TempHLock(h: Handle; VAR resultCode: OSErr);
                        // PROCEDURE TempHUnlock(h: Handle; VAR resultCode: OSErr);
                        // Inside Macintosh Volume VI, 28-37..28-39 and 28-45.
                        let result_code_ptr = bus.read_long(sp);
                        let handle = bus.read_long(sp + 4);
                        let result_code = temporary_memory_handle_status(bus, handle);
                        if result_code == NO_ERR {
                            self.update_handle_state_bits(handle, |bits| {
                                let bits = if selector == 0x001E {
                                    bits.unwrap_or(0) | 0x80
                                } else {
                                    bits.unwrap_or(0) & !0x80
                                };
                                (bits != 0).then_some(bits)
                            });
                        }
                        write_temp_memory_result_code(bus, result_code_ptr, result_code);
                        cpu.write_reg(Register::D0, result_code);
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    0x0020 => {
                        // TempDisposeHandle (0xA88F selector $0020)
                        // Releases a relocatable temporary-memory block.
                        // PROCEDURE TempDisposeHandle(h: Handle; VAR resultCode: OSErr);
                        // Inside Macintosh Volume VI, 28-37..28-39 and 28-45.
                        let result_code_ptr = bus.read_long(sp);
                        let handle = bus.read_long(sp + 4);
                        let result_code = if handle != 0
                            && bus.get_alloc_size(handle).is_some()
                            && !self.loaded_handles.contains_key(&handle)
                        {
                            let ptr = bus.read_long(handle);
                            self.untrack_handle_ptr(ptr);
                            bus.free(ptr);
                            bus.free(handle);
                            self.remove_handle_state_bits(handle);
                            NO_ERR
                        } else {
                            MEM_WZ_ERR
                        };
                        write_temp_memory_result_code(bus, result_code_ptr, result_code);
                        cpu.write_reg(Register::D0, result_code);
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    0x0033 => {
                        // AcceptHighLevelEvent (0xA88F selector $0033)
                        // Returns additional data for the outstanding high-level event.
                        // FUNCTION AcceptHighLevelEvent(VAR sender: TargetID;
                        //   VAR msgRefcon: LongInt; msgBuff: Ptr; VAR msgLen: LongInt): OSErr;
                        // Inside Macintosh Volume VI, 5-29 and Macintosh Toolbox Essentials 1992, 2-90.
                        if self.apple_event_launch_state.accept_open_application_event() {
                            let msg_len_ptr = bus.read_long(sp);
                            let msg_refcon_ptr = bus.read_long(sp + 8);
                            let sender_ptr = bus.read_long(sp + 12);
                            if msg_len_ptr != 0 {
                                bus.write_long(msg_len_ptr, 0);
                            }
                            if msg_refcon_ptr != 0 {
                                bus.write_long(msg_refcon_ptr, 0);
                            }
                            if sender_ptr != 0 {
                                // The local launch event has no additional data.
                                // A TargetID is 252 bytes with 68K two-byte
                                // packing: sessionID, two PPCPortRecs, and a
                                // LocationNameRec. The Mac OS sender uses
                                // session -1 and the local port name "MacOS".
                                // Inside Macintosh Volume VI, 5-10 and 7-15.
                                bus.write_bytes(sender_ptr, &[0; 252]);
                                bus.write_long(sender_ptr, u32::MAX);
                                bus.write_byte(sender_ptr + 6, 5);
                                bus.write_bytes(sender_ptr + 7, b"MacOS");
                            }
                            write_osdispatch_oseerr_result(cpu, bus, sp + 16, 0);
                        } else {
                            write_osdispatch_oseerr_result(
                                cpu,
                                bus,
                                sp + 16,
                                NO_OUTSTANDING_HLE_ERR,
                            );
                        }
                        Ok(())
                    }
                    0x0034 => {
                        // PostHighLevelEvent (0xA88F selector $0034)
                        // Sends a high-level event to another application.
                        // FUNCTION PostHighLevelEvent(theEvent: EventRecord; receiverID: Ptr;
                        //   msgRefcon: LongInt; msgBuff: Ptr; msgLen: LongInt;
                        //   postingOptions: LongInt): OSErr;
                        // Inside Macintosh Volume VI, 5-30 and Macintosh Toolbox Essentials 1992, 2-101.
                        write_osdispatch_oseerr_result(cpu, bus, sp + 24, CONNECTION_INVALID_ERR);
                        Ok(())
                    }
                    0x0035 => {
                        // GetProcessSerialNumberFromPortName (0xA88F selector $0035)
                        // Maps a local PPC port name to a process serial number.
                        // FUNCTION GetProcessSerialNumberFromPortName(portName: PPCPortRec;
                        //   VAR PSN: ProcessSerialNumber): OSErr;
                        // Inside Macintosh Volume VI, 5-32 and Macintosh Toolbox Essentials 1992, 2-106.
                        write_osdispatch_oseerr_result(cpu, bus, sp + 8, NO_PORT_ERR);
                        Ok(())
                    }
                    0x0036 => {
                        // LaunchDeskAccessory (0xA88F selector $0036)
                        // Launches a desk accessory from a resource file.
                        // FUNCTION LaunchDeskAccessory(pFileSpec: FSSpecPtr;
                        //   pDAName: StringPtr): OSErr;
                        // Inside Macintosh Volume VI, 29-22..29-23; Processes 1994, 2-30.
                        write_osdispatch_oseerr_result(cpu, bus, sp + 8, RES_NOT_FOUND_ERR);
                        Ok(())
                    }
                    0x0037 => {
                        // GetCurrentProcess (0xA88F selector $0037)
                        // Returns serial number of current process.
                        // FUNCTION GetCurrentProcess(VAR PSN: ProcessSerialNumber): OSErr;
                        // Processes 1994, p. 2-21
                        let psn_ptr = bus.read_long(sp);
                        bus.write_long(psn_ptr, ProcessSerialNumber::CURRENT.high); // highLongOfPSN
                        bus.write_long(psn_ptr + 4, ProcessSerialNumber::CURRENT.low); // lowLongOfPSN = kCurrentProcess
                        bus.write_word(sp + 4, 0); // noErr
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    0x0038 => {
                        // GetNextProcess (0xA88F selector $0038)
                        // Enumerates processes; returns procNotFound at end of list.
                        // FUNCTION GetNextProcess(VAR PSN: ProcessSerialNumber): OSErr;
                        // Processes 1994, p. 2-22
                        let psn_ptr = bus.read_long(sp);
                        let psn = ProcessSerialNumber::new(
                            bus.read_long(psn_ptr),
                            bus.read_long(psn_ptr.wrapping_add(4)),
                        );
                        let err: i16 = match psn.next_single_process() {
                            SingleProcessEnumeration::Current(current) => {
                                bus.write_long(psn_ptr, current.high);
                                bus.write_long(psn_ptr.wrapping_add(4), current.low);
                                0
                            }
                            SingleProcessEnumeration::End => {
                                bus.write_long(psn_ptr, ProcessSerialNumber::CURRENT.high);
                                bus.write_long(psn_ptr.wrapping_add(4), 0);
                                -600
                            }
                            SingleProcessEnumeration::Invalid => -50,
                        };
                        bus.write_word(sp + 4, err as u16);
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    0x0039 => {
                        // GetFrontProcess (0xA88F selector $0039)
                        // Returns foreground process serial number.
                        // FUNCTION GetFrontProcess(VAR PSN: ProcessSerialNumber): OSErr;
                        // Processes 1994, pp. 2-25 to 2-26
                        //
                        // MPW glue (disassembled):
                        //   MOVEQ #-1, D0 / MOVE.L D0, -(SP)  ; 4-byte init slot ($FFFFFFFF)
                        //   PEA <psn>                          ; psn_ptr (4 bytes)
                        //   MOVE.W #$0039, -(SP)               ; selector
                        //   DC.W $A88F / MOVE.W (SP)+, D0      ; trap → result in D0
                        // After selector pop: sp+0=init(4B), sp+4=psn_ptr(4B), sp+8=result(2B).
                        // Inside Macintosh: Processes 1994, pp. 2-25 to 2-26.
                        // Write result word at sp+8; A7 = sp+8 so caller's MOVE.W (SP)+, D0
                        // consumes the result and restores the pre-call stack pointer.
                        let psn_ptr = bus.read_long(sp + 4);
                        bus.write_long(psn_ptr, ProcessSerialNumber::CURRENT.high);
                        bus.write_long(psn_ptr.wrapping_add(4), ProcessSerialNumber::CURRENT.low);
                        bus.write_word(sp + 8, 0);
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    0x003A => {
                        // GetProcessInformation (0xA88F selector $003A)
                        // Returns information about the specified process.
                        // FUNCTION GetProcessInformation(PSN: ProcessSerialNumber;
                        //   VAR info: ProcessInfoRec): OSErr;
                        // Processes 1994, pp. 2-23 to 2-24
                        if selector_from_stack && self.address_is_loaded_code(bus.read_long(sp)) {
                            // Some 68k C runtimes factor the inline selector
                            // into a leaf thunk that pushes only
                            // `MOVE.W #selector,-(SP)` above a JSR return
                            // address. In that shape the selector word is the
                            // only safe OSErr result slot; consuming the
                            // ordinary argument frame would skip the return PC.
                            write_osdispatch_selector_result(cpu, bus, sp_entry, NO_ERR as i16);
                            return Some(Ok(()));
                        }

                        let info_ptr = bus.read_long(sp);
                        let psn_ptr = bus.read_long(sp + 4);
                        let valid_psn = ProcessSerialNumber::new(
                            bus.read_long(psn_ptr),
                            bus.read_long(psn_ptr + 4),
                        )
                        .is_current();

                        if !valid_psn {
                            bus.write_word(sp + 8, (-600i16) as u16); // procNotFound
                            cpu.write_reg(Register::A7, sp + 8);
                            return Some(Ok(()));
                        }

                        let app = self.current_process_application_metadata();
                        let app_name = super::TrapDispatcher::hfs_name_from_vfs_component(
                            super::TrapDispatcher::vfs_basename(&app.path),
                        );

                        let name_ptr = bus.read_long(info_ptr + 4);
                        if name_ptr != 0 {
                            Self::write_pstring(bus, name_ptr, &app_name);
                        }

                        let app_spec_ptr = bus.read_long(info_ptr + 56);
                        if app_spec_ptr != 0 {
                            bus.write_word(
                                app_spec_ptr,
                                super::TrapDispatcher::boot_volume_ref_num_u16(),
                            );
                            bus.write_long(app_spec_ptr + 2, app.parent_dir_id);
                            Self::write_pstring(bus, app_spec_ptr + 6, &app_name);
                        }

                        bus.write_long(info_ptr + 8, ProcessSerialNumber::CURRENT.high); // processNumber.highLongOfPSN
                        bus.write_long(info_ptr + 12, ProcessSerialNumber::CURRENT.low); // processNumber.lowLongOfPSN
                        bus.write_long(info_ptr + 16, app.file_type);
                        bus.write_long(info_ptr + 20, app.creator);
                        bus.write_long(info_ptr + 24, 0); // processMode
                        let app_zone = bus.read_long(crate::memory::globals::addr::APP_L_ZONE);
                        let appl_limit = bus.read_long(crate::memory::globals::addr::APPL_LIMIT);
                        let process_location = if app_zone != 0 { app_zone } else { 0x0010_0000 };
                        let process_free_mem = if app_zone != 0 && appl_limit > app_zone {
                            crate::memory::app_heap_free_bytes(bus)
                        } else {
                            bus.ram_size() / 2
                        };
                        bus.write_long(info_ptr + 28, process_location); // processLocation
                        bus.write_long(info_ptr + 32, crate::memory::app_partition_size_bytes(bus)); // processSize
                        bus.write_long(info_ptr + 36, process_free_mem); // processFreeMem
                        bus.write_long(info_ptr + 40, 0); // processLauncher.highLongOfPSN
                        bus.write_long(info_ptr + 44, 0); // processLauncher.lowLongOfPSN
                        bus.write_long(info_ptr + 48, 0); // processLaunchDate
                        bus.write_long(info_ptr + 52, bus.read_long(0x016A)); // processActiveTime

                        bus.write_word(sp + 8, 0); // noErr
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    0x003B => {
                        // SetFrontProcess (OSDispatch $003B)
                        // FUNCTION SetFrontProcess(PSN: ProcessSerialNumber): OSErr;
                        // Processes 1994, 2-26. The HLE runs a single app
                        // and cannot switch foreground processes; report
                        // success unconditionally.
                        bus.write_word(sp + 4, 0);
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    0x003C => {
                        // WakeUpProcess (OSDispatch $003C)
                        // Makes a suspended process eligible to receive CPU time.
                        // FUNCTION WakeUpProcess(PSN: ProcessSerialNumber): OSErr;
                        // Processes 1994, 2-27
                        // PSN is passed as const pointer (4 bytes), result is OSErr (2 bytes)
                        bus.write_word(sp + 4, 0); // noErr
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    0x003D => {
                        // SameProcess (OSDispatch $003D)
                        // FUNCTION SameProcess(PSN1, PSN2: ProcessSerialNumber;
                        //   VAR result: BOOLEAN): OSErr;
                        // Processes 1994, 2-28. Compares two PSN records;
                        // sets result and returns noErr.
                        let result_ptr = bus.read_long(sp);
                        let psn2_ptr = bus.read_long(sp + 4);
                        let psn1_ptr = bus.read_long(sp + 8);
                        let psn1 = ProcessSerialNumber::new(
                            bus.read_long(psn1_ptr),
                            bus.read_long(psn1_ptr + 4),
                        );
                        let psn2 = ProcessSerialNumber::new(
                            bus.read_long(psn2_ptr),
                            bus.read_long(psn2_ptr + 4),
                        );
                        let same = psn1 == psn2;
                        if result_ptr != 0 {
                            bus.write_byte(result_ptr, if same { 1 } else { 0 });
                        }
                        bus.write_word(sp + 12, 0);
                        cpu.write_reg(Register::A7, sp + 12);
                        Ok(())
                    }
                    0x0045 => {
                        // GetSpecificHighLevelEvent (0xA88F selector $0045)
                        // Searches the application's high-level-event queue with a
                        // caller filter and returns FALSE when no event is selected.
                        // FUNCTION GetSpecificHighLevelEvent
                        //   (aFilter: GetSpecificFilterProcPtr; yourDataPtr: UNIV Ptr;
                        //    VAR err: OSErr): Boolean;
                        // Macintosh Toolbox Essentials 1992, pp. 2-92 to 2-93.
                        //
                        // MPW 3.5 EPPC.h emits THREEWORDINLINE($3F3C,$0045,$A88F).
                        // Its 68k caller frame is filter(4), context(4), err*(4),
                        // Boolean result(1). Systemless has no registered PPC/HLE
                        // port, matching BasiliskII's noPortErr branch for a direct
                        // app without the high-level-event SIZE flag.
                        let err_ptr = bus.read_long(sp + 8);
                        if err_ptr != 0 {
                            bus.write_word(err_ptr, NO_PORT_ERR as u16);
                        }
                        bus.write_byte(sp + 12, 0);
                        cpu.write_reg(Register::D0, 0);
                        cpu.write_reg(Register::A7, sp + 12);
                        Ok(())
                    }
                    _ => {
                        eprintln!(
                            "[PROCESS] OSDispatch unhandled selector ${:04X} (stack=${:04X} d0=${:04X})",
                            selector, stack_sel, d0_sel
                        );
                        return None;
                    }
                }
            }

            // HighLevelFSDispatch ($AA52)
            // Dispatches high-level File Manager FSSpec routines selected in D0.
            // FUNCTION FSMakeFSSpec(vRefNum: INTEGER; dirID: LONGINT; fileName: Str255; VAR spec: FSSpec): OSErr;
            // Inside Macintosh: Files (1992), pp. 2-154 to 2-168.
            (true, 0x252) => {
                let raw_selector = cpu.read_reg(Register::D0);
                let operation =
                    high_level_fs_dispatch_operation_route(self.current_trap_word, raw_selector);
                self.current_selector_operation = operation.map(|route| route.operation_id);
                let selector = raw_selector & 0xFFFF;
                eprintln!("[TRAP] HighLevelFSDispatch Selector={}", selector);
                match selector {
                    1 => {
                        // FSMakeFSSpec ($AA52, selector 1)
                        // Fills in an FSSpec record. Returns fnfErr if file doesn't exist.
                        // FUNCTION FSMakeFSSpec(vRefNum: INTEGER; dirID: LONGINT;
                        //   fileName: Str255; VAR spec: FSSpec): OSErr;
                        // Files 1992, 2-166
                        let sp = cpu.read_reg(Register::A7);
                        let spec_ptr = bus.read_long(sp);
                        let name_ptr = bus.read_long(sp + 4);
                        let dir_id = bus.read_long(sp + 8);
                        let requested_v_ref_num = bus.read_word(sp + 12) as i16;
                        let (resolved_v_ref_num, effective_dir_id) =
                            self.resolve_volume_and_directory(requested_v_ref_num, dir_id);

                        let requested_name = if name_ptr != 0 {
                            let bytes = bus.read_pstring(name_ptr);
                            decode_mac_roman(&bytes)
                        } else {
                            String::new()
                        };

                        let (spec_v_ref_num, spec_dir_id, spec_name, target_key) = if requested_name
                            .is_empty()
                        {
                            (
                                resolved_v_ref_num,
                                effective_dir_id,
                                String::new(),
                                self.directory_path_for_id(effective_dir_id)
                                    .map(str::to_string),
                            )
                        } else if let Some((target_vref, parent_dir_id, basename, key)) = self
                            .fsspec_parts_for_hfs_path(requested_v_ref_num, dir_id, &requested_name)
                        {
                            (target_vref, parent_dir_id, basename, Some(key))
                        } else {
                            // dirNFErr when the resolved dirID or pathname parent is not
                            // a known directory. IM:Files 1992 p. 2-34 notes that
                            // FSMakeFSSpec can return File Manager errors other than
                            // noErr/fnfErr and clears the FSSpec in that case.
                            if trace_fsspec_enabled() {
                                eprintln!(
                                    "[FSSPEC] FSMakeFSSpec dirNFErr request_vRefNum={} resolved_vRefNum={} request_dirID={} resolved_dirID={} name='{}'",
                                    requested_v_ref_num,
                                    resolved_v_ref_num,
                                    dir_id,
                                    effective_dir_id,
                                    requested_name
                                );
                            }
                            bus.write_word(spec_ptr, 0);
                            bus.write_long(spec_ptr + 2, 0);
                            bus.write_byte(spec_ptr + 6, 0);
                            bus.write_word(sp + 14, (-120i16) as u16); // dirNFErr
                            cpu.write_reg(Register::A7, sp + 14);
                            return Some(Ok(()));
                        };

                        bus.write_word(spec_ptr, spec_v_ref_num as u16);
                        bus.write_long(spec_ptr + 2, spec_dir_id);
                        let spec_name_bytes = encode_mac_roman_lossy(&spec_name);
                        let n = spec_name_bytes.len().min(63);
                        bus.write_byte(spec_ptr + 6, n as u8);
                        bus.write_bytes(spec_ptr + 7, &spec_name_bytes[..n]);

                        // FSMakeFSSpec returns fnfErr if the target doesn't exist while
                        // still filling a valid FSSpec. Files 1992, 2-34 to 2-35.
                        let exists = if requested_name.is_empty() {
                            self.directory_entry_for_id(spec_dir_id).is_some()
                        } else if let Some(ref key) = target_key {
                            self.vfs.keys().any(|path| path.eq_ignore_ascii_case(key))
                                || self
                                    .vfs_rsrc
                                    .keys()
                                    .any(|path| path.eq_ignore_ascii_case(key))
                                || self
                                    .vfs_directories
                                    .iter()
                                    .any(|directory| directory.path.eq_ignore_ascii_case(key))
                        } else {
                            false
                        };
                        eprintln!(
                            "[FSSPEC] FSMakeFSSpec request_vRefNum={} resolved_vRefNum={} request_dirID={} resolved_dirID={} name='{}' specDirID={} specName='{}' exists={}",
                            requested_v_ref_num,
                            resolved_v_ref_num,
                            dir_id,
                            effective_dir_id,
                            requested_name,
                            spec_dir_id,
                            spec_name,
                            exists
                        );
                        if trace_fsspec_enabled() && requested_name.is_empty() {
                            eprintln!(
                                "[FSSPEC] FSMakeFSSpec created directory spec for dirID={}",
                                spec_dir_id
                            );
                        }
                        if exists {
                            bus.write_word(sp + 14, 0); // noErr
                        } else {
                            bus.write_word(sp + 14, (-43i16) as u16); // fnfErr
                        }
                        cpu.write_reg(Register::A7, sp + 14);
                        Ok(())
                    }
                    2 => {
                        // FSpOpenDF ($AA52, selector 2)
                        // Opens the data fork of a file specified by an FSSpec.
                        // FUNCTION FSpOpenDF(spec: FSSpec; permission: SignedByte;
                        //   VAR refNum: INTEGER): OSErr;
                        // Files 1992, 2-326 (FSpOpenDF subsection lines 2342..2380;
                        //   trap macro / routine selector at lines 2818..2823;
                        //   result codes 2369..2380 with fnfErr -43 at line 2376).
                        //
                        // Behavioral note: real BasiliskII writes to *refNum
                        // on the fnfErr (-43) failure path while Systemless
                        // leaves the VAR-out untouched.
                        let sp = cpu.read_reg(Register::A7);
                        let ref_num_ptr = bus.read_long(sp);
                        // `permission` is a SignedByte. MPW SC emits a
                        // byte push for FSpOpenDF, while A7 still reserves a
                        // stack word; some callers leave nonzero padding in
                        // the other byte.
                        let permission = file_permission_from_stack_word(bus.read_word(sp + 4));
                        let spec_ptr = bus.read_long(sp + 6);

                        let filename = read_fsspec_name(bus, spec_ptr);
                        eprintln!(
                            "[TRAP] FSpOpenDF(\"{}\", perm={}) ref_num_ptr=${:08X}",
                            filename, permission, ref_num_ptr
                        );

                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        if let Some(vfs_name) =
                            self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                        {
                            // Inside Macintosh: Files (1992), pp. 1-10–1-11:
                            // fsCurPerm grants read/write access when no other
                            // access path is open, or read-only access otherwise.
                            let read_only = self.vfs_path_is_read_only(&vfs_name);
                            let current_write = permission == 0
                                && !read_only
                                && !self
                                    .open_files
                                    .iter()
                                    .any(|open| open.path.eq_ignore_ascii_case(&vfs_name));
                            let wants_write = current_write || matches!(permission, 2 | 3 | 4);
                            if wants_write && read_only {
                                bus.write_word(sp + 10, (-44i16) as u16); // wPrErr
                                cpu.write_reg(Register::A7, sp + 10);
                                return Some(Ok(()));
                            }

                            let refnum = match self.allocate_data_file_fcb(
                                bus,
                                &vfs_name,
                                wants_write && !read_only,
                            ) {
                                Ok(refnum) => refnum,
                                Err(error) => {
                                    bus.write_word(sp + 10, error as u16);
                                    cpu.write_reg(Register::A7, sp + 10);
                                    return Some(Ok(()));
                                }
                            };
                            self.open_files.insert(refnum, vfs_name.clone());
                            if wants_write && !read_only {
                                self.write_refnums.insert(refnum);
                            }
                            self.file_positions.insert(refnum, 0);
                            eprintln!("[TRAP] FSpOpenDF -> refnum={} vfs=\"{}\"", refnum, vfs_name);

                            bus.write_word(ref_num_ptr, refnum);
                            bus.write_word(sp + 10, 0); // noErr
                            cpu.write_reg(Register::A7, sp + 10);
                        } else {
                            eprintln!("[TRAP] FSpOpenDF(\"{}\") -> fnfErr", filename);
                            bus.write_word(sp + 10, (-43i16) as u16); // fnfErr
                            cpu.write_reg(Register::A7, sp + 10);
                        }
                        Ok(())
                    }
                    3 => {
                        // FSpOpenRF ($AA52, selector 3)
                        // Opens the resource fork of a file specified by an FSSpec.
                        // FUNCTION FSpOpenRF(spec: FSSpec; permission: SignedByte;
                        //   VAR refNum: INTEGER): OSErr;
                        // Files 1992, 2-327..2-329.
                        let sp = cpu.read_reg(Register::A7);
                        let ref_num_ptr = bus.read_long(sp);
                        let permission = file_permission_from_stack_word(bus.read_word(sp + 4));
                        let spec_ptr = bus.read_long(sp + 6);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        eprintln!(
                            "[TRAP] FSpOpenRF(\"{}\", perm={}) ref_num_ptr=${:08X}",
                            filename, permission, ref_num_ptr
                        );

                        if vref != 0 && self.working_directory_info(vref).is_none() {
                            eprintln!(
                                "[TRAP] FSpOpenRF(\"{}\") -> nsvErr (vRefNum={})",
                                filename, vref
                            );
                            bus.write_word(sp + 10, (-35i16) as u16); // nsvErr
                            cpu.write_reg(Register::A7, sp + 10);
                            return Some(Ok(()));
                        }

                        let Some(vfs_key) =
                            self.find_vfs_rsrc_file_for_hfs_lookup(vref, dir_id, &filename)
                        else {
                            eprintln!("[TRAP] FSpOpenRF(\"{}\") -> fnfErr", filename);
                            bus.write_word(sp + 10, (-43i16) as u16); // fnfErr
                            cpu.write_reg(Register::A7, sp + 10);
                            return Some(Ok(()));
                        };

                        // Inside Macintosh: Files (1992), pp. 1-10–1-11.
                        let rsrc_key = format!("__rsrc__{vfs_key}");
                        let read_only = self.vfs_path_is_read_only(&vfs_key);
                        let current_write = permission == 0
                            && !read_only
                            && !self
                                .open_files
                                .iter()
                                .any(|open| open.path.eq_ignore_ascii_case(&rsrc_key));
                        let wants_write = current_write || matches!(permission, 2 | 3 | 4);

                        if wants_write && read_only {
                            bus.write_word(sp + 10, (-44i16) as u16); // wPrErr
                            cpu.write_reg(Register::A7, sp + 10);
                            return Some(Ok(()));
                        }

                        let rsrc_data = self.vfs_rsrc.get(&vfs_key).cloned().unwrap_or_default();
                        self.vfs.insert_if_absent(rsrc_key.clone(), rsrc_data);
                        let refnum = self.allocate_process_file_refnum();
                        self.open_files.insert(refnum, rsrc_key.clone());
                        if wants_write {
                            self.write_refnums.insert(refnum);
                        }
                        self.file_positions.insert(refnum, 0);
                        eprintln!("[TRAP] FSpOpenRF -> refnum={} vfs=\"{}\"", refnum, rsrc_key);
                        bus.write_word(ref_num_ptr, refnum);
                        bus.write_word(sp + 10, 0); // noErr
                        cpu.write_reg(Register::A7, sp + 10);
                        Ok(())
                    }
                    4 => {
                        // FSpCreate ($AA52, selector 4)
                        // Creates a new file (both forks) by FSSpec.
                        // FUNCTION FSpCreate(spec: FSSpec; creator: OSType;
                        //   fileType: OSType; scriptTag: ScriptCode): OSErr;
                        // Files 1992, 8480..8531 (function 8484; trap macro /
                        // selector 8510..8514; result codes 8517..8531 with
                        // dirNFErr at 8529 and dupFNErr at 8528).
                        //
                        // Returns dupFNErr (-48) if a case-insensitive
                        // match already exists in VFS, noErr otherwise.
                        // IM:Files 8528 (dupFNErr result code).
                        let sp = cpu.read_reg(Register::A7);
                        let spec_ptr = bus.read_long(sp + 10);
                        let file_type = bus.read_long(sp + 2);
                        let creator = bus.read_long(sp + 6);

                        // Phantom parID → BasiliskII returns dupFNErr (-48).
                        // IM:Files 8529 documents dirNFErr (-120) for a missing parent
                        // directory; however BasiliskII (extfs over HFS) empirically
                        // returns -48 (dupFNErr) for phantom parIDs. BasiliskII is
                        // ground truth per the reference gate.
                        // IM:Files 1992, lines 8510..8531
                        let filename = read_fsspec_name(bus, spec_ptr);
                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        if trace_fsspec_enabled() {
                            eprintln!(
                                "[FSSPEC] FSpCreateResFile file='{}' vref={} dir_id={}",
                                filename, vref, dir_id
                            );
                        }
                        let par_id = dir_id;
                        if par_id > 1 && self.directory_path_for_id(par_id).is_none() {
                            if trace_fsspec_enabled() {
                                eprintln!(
                                    "[FSSPEC] FSpCreateResFile rejecting par_id={} for file='{}'",
                                    par_id, filename
                                );
                            }
                            bus.write_word(sp + 14, (-48i16) as u16); // dupFNErr
                            cpu.write_reg(Register::A7, sp + 14);
                            return Some(Ok(()));
                        }

                        let vfs_key = self
                            .vfs_key_for_fsspec(vref, dir_id, &filename)
                            .unwrap_or_else(|| {
                                super::TrapDispatcher::normalize_hfs_path(&filename)
                            });
                        if trace_fsspec_enabled() {
                            eprintln!(
                                "[FSSPEC] FSpCreateResFile file='{}' vref={} dir_id={} vfs_key='{}'",
                                filename, vref, dir_id, vfs_key
                            );
                        }

                        if self.vfs_path_is_read_only(&vfs_key) {
                            bus.write_word(sp + 14, (-44i16) as u16); // wPrErr
                            cpu.write_reg(Register::A7, sp + 14);
                            return Some(Ok(()));
                        }

                        // dupFNErr (-48): file already exists in VFS.
                        // IM:Files 8528; matches BasiliskII empirical behaviour.
                        let already_exists = self.vfs.contains_key(&vfs_key)
                            || self.vfs.keys().any(|k| k.eq_ignore_ascii_case(&vfs_key));

                        if already_exists {
                            bus.write_word(sp + 14, (-48i16) as u16); // dupFNErr
                        } else {
                            self.vfs.insert(vfs_key.clone(), Vec::new());
                            self.vfs_rsrc.ensure_empty(vfs_key.clone());
                            self.set_vfs_entry_finfo(&vfs_key, file_type, creator, 0);
                            self.touch_vfs_entry(&vfs_key);

                            if let Some(ref dir) = self.output_dir {
                                let host_path = dir.join(&vfs_key);
                                let _ = std::fs::File::create(&host_path);
                            }

                            bus.write_word(sp + 14, 0); // noErr
                        }
                        cpu.write_reg(Register::A7, sp + 14);
                        Ok(())
                    }
                    5 => {
                        // FSpDirCreate ($AA52, selector 5)
                        // Creates a directory specified by an FSSpec and
                        // returns its directory ID.
                        // FUNCTION FSpDirCreate(spec: FSSpec; scriptTag: ScriptCode;
                        //   VAR createdDirID: LongInt): OSErr;
                        // Files 1992, 2-158
                        let sp = cpu.read_reg(Register::A7);
                        let created_dir_id_ptr = bus.read_long(sp);
                        let spec_ptr = bus.read_long(sp + 6);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);

                        let result = if filename.is_empty() {
                            -37i16 // bdNamErr
                        } else {
                            let parent_dir_id = self.resolve_directory_id(vref, dir_id);
                            let Some(parent_path) = self
                                .directory_path_for_id(parent_dir_id)
                                .map(str::to_string)
                            else {
                                bus.write_word(sp + 10, (-120i16) as u16); // dirNFErr
                                cpu.write_reg(Register::A7, sp + 10);
                                return Some(Ok(()));
                            };
                            if self.vfs_path_is_read_only(&parent_path) {
                                bus.write_word(sp + 10, (-44i16) as u16); // wPrErr
                                cpu.write_reg(Register::A7, sp + 10);
                                return Some(Ok(()));
                            }
                            let child_name = super::TrapDispatcher::normalize_hfs_path(&filename);
                            if child_name.is_empty() {
                                -37i16 // bdNamErr
                            } else {
                                let child_path = if parent_path.is_empty() {
                                    child_name
                                } else {
                                    format!("{parent_path}/{child_name}")
                                };
                                let duplicate = self.vfs_directories.iter().any(|directory| {
                                    directory.path.eq_ignore_ascii_case(&child_path)
                                }) || self
                                    .vfs
                                    .keys()
                                    .any(|path| path.eq_ignore_ascii_case(&child_path))
                                    || self
                                        .vfs_rsrc
                                        .keys()
                                        .any(|path| path.eq_ignore_ascii_case(&child_path));
                                if duplicate {
                                    -48i16 // dupFNErr
                                } else {
                                    let new_dir_id = self.ensure_vfs_directory(&child_path);
                                    if created_dir_id_ptr != 0 {
                                        bus.write_long(created_dir_id_ptr, new_dir_id);
                                    }
                                    if let Some(ref dir) = self.output_dir {
                                        let _ = std::fs::create_dir_all(dir.join(&child_path));
                                    }
                                    eprintln!(
                                        "[TRAP] FSpDirCreate(\"{}\") parentDirID={} -> dirID={}",
                                        filename, parent_dir_id, new_dir_id
                                    );
                                    0
                                }
                            }
                        };
                        bus.write_word(sp + 10, result as u16);
                        cpu.write_reg(Register::A7, sp + 10);
                        Ok(())
                    }
                    6 => {
                        // FSpDelete ($AA52, selector 6)
                        // Removes a file or directory specified by an FSSpec.
                        // FUNCTION FSpDelete(spec: FSSpec): OSErr;
                        // Files 1992, 2-329; FSpDelete subsection at IM:Files
                        // 8576..8610 (function signature 8580; trap macro/
                        // selector 8590..8594; result codes 8597..8610 with
                        // fnfErr at 8603, fBsyErr at 8607, dirNFErr at 8608).
                        //
                        // Behavioral note: on the delete-while-open path,
                        // BasiliskII on Unix deletes the open file with noErr,
                        // and a second FSpDelete returns fnfErr -43.
                        let sp = cpu.read_reg(Register::A7);
                        let spec_ptr = bus.read_long(sp);

                        let filename = read_fsspec_name(bus, spec_ptr);
                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        let mut read_only = false;
                        let found_in_vfs = if let Some(vfs_name) =
                            self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                        {
                            read_only = self.vfs_path_is_read_only(&vfs_name);
                            if read_only {
                                false
                            } else {
                                self.vfs.remove(&vfs_name);
                                self.vfs_rsrc.remove(&vfs_name);
                                self.remove_vfs_entry_metadata(&vfs_name);
                                true
                            }
                        } else if let Some(vfs_name) = self.find_vfs_file(&filename) {
                            read_only = self.vfs_path_is_read_only(&vfs_name);
                            if read_only {
                                false
                            } else {
                                self.vfs.remove(&vfs_name);
                                self.vfs_rsrc.remove(&vfs_name);
                                self.remove_vfs_entry_metadata(&vfs_name);
                                true
                            }
                        } else {
                            false
                        };

                        let host_vfs_key = self.vfs_key_for_fsspec(vref, dir_id, &filename);
                        let found_on_host = if !read_only {
                            if let Some(ref dir) = self.output_dir {
                                let host_path = host_vfs_key
                                    .map(|key| dir.join(key))
                                    .unwrap_or_else(|| dir.join(&filename));
                                std::fs::remove_file(&host_path).is_ok()
                            } else {
                                false
                            }
                        } else {
                            false
                        };

                        // fnfErr (-43) when file not found anywhere.
                        // IM:Files 8603: result code fnfErr.
                        let err: i16 = if read_only {
                            -44 // wPrErr
                        } else if found_in_vfs || found_on_host {
                            0
                        } else {
                            -43
                        };
                        bus.write_word(sp + 4, err as u16);
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    7 => {
                        // FSpGetFInfo ($AA52, selector 7)
                        // Returns Finder information for a file specified by an FSSpec.
                        // FUNCTION FSpGetFInfo(spec: FSSpec; VAR fndrInfo: FInfo): OSErr;
                        // Files 1992, 2-327; FSpGetFInfo subsection at IM:Files 8616..8650
                        // (function signature 8620; trap macro/selector 8630..8631; result
                        // codes 8643..8650 with fnfErr at 8645).
                        //
                        // The missing-file path returns fnfErr (-43) and the
                        // companion FSMakeFSSpec dispatch populates the spec.
                        //
                        // BasiliskII mutates the caller's `fndrInfo` buffer on the
                        // fnfErr branch instead of leaving the pre-poisoned bytes
                        // untouched. Mirror that observed mutation here so callers do
                        // not read stale poison after a missing-file probe.
                        let sp = cpu.read_reg(Register::A7);
                        let finfo_ptr = bus.read_long(sp);
                        let spec_ptr = bus.read_long(sp + 4);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        eprintln!("[TRAP] FSpGetFInfo file='{}'", filename);

                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        let vfs_name = self
                            .find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                            .or_else(|| {
                                self.find_vfs_rsrc_file_for_hfs_lookup(vref, dir_id, &filename)
                            });
                        let directory_name =
                            self.find_vfs_directory_for_hfs_lookup(vref, dir_id, &filename);

                        if directory_name.is_some() {
                            // Directory specs are valid for FSpGetFInfo.
                            // Finder type/creator for directories follows
                            // the same canonical values used by PBGetCatInfo.
                            Self::write_finfo(
                                bus,
                                finfo_ptr,
                                u32::from_be_bytes(*b"fold"),
                                u32::from_be_bytes(*b"MACS"),
                                0,
                            );
                            bus.write_word(sp + 8, 0); // noErr
                        } else if let Some(vfs_name) = vfs_name {
                            if let Some(metadata) = self.vfs_file_metadata(&vfs_name) {
                                Self::write_finfo(
                                    bus,
                                    finfo_ptr,
                                    metadata.file_type,
                                    metadata.creator,
                                    metadata.finder_flags,
                                );
                            }
                            bus.write_word(sp + 8, 0); // noErr
                        } else {
                            eprintln!("[TRAP] FSpGetFInfo(\"{}\") -> fnfErr", filename);
                            Self::write_finfo(bus, finfo_ptr, 0, 0, 0);
                            bus.write_word(sp + 8, (-43i16) as u16); // fnfErr
                        }
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    8 => {
                        // FSpSetFInfo (selector 8)
                        // FUNCTION FSpSetFInfo(spec: FSSpec; fndrInfo: FInfo): OSErr;
                        // Stack: [result(2)] [fndrInfo_ptr(4)] [spec_ptr(4)] — pop 8, leave 2
                        // More Macintosh Toolbox, 1-89
                        let sp = cpu.read_reg(Register::A7);
                        let finfo_ptr = bus.read_long(sp);
                        let spec_ptr = bus.read_long(sp + 4);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        let result = if let Some(vfs_name) =
                            self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                        {
                            if self.vfs_path_is_read_only(&vfs_name) {
                                -44i16 // wPrErr
                            } else {
                                let file_type = bus.read_long(finfo_ptr);
                                let creator = bus.read_long(finfo_ptr + 4);
                                let finder_flags = bus.read_word(finfo_ptr + 8);
                                self.set_vfs_entry_finfo(
                                    &vfs_name,
                                    file_type,
                                    creator,
                                    finder_flags,
                                );
                                0
                            }
                        } else {
                            0 // Preserve the existing no-op behavior for a missing file.
                        };
                        bus.write_word(sp + 8, result as u16);
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    9 => {
                        // FSpSetFLock ($AA52, selector 9)
                        // Locks a file — new access paths become read-only.
                        // FUNCTION FSpSetFLock(spec: FSSpec): OSErr;
                        // Inside Macintosh: Files 1992, 8681..8713
                        let sp = cpu.read_reg(Register::A7);
                        let spec_ptr = bus.read_long(sp);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        let err: i16 = if let Some(vfs_name) =
                            self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                        {
                            if self.vfs_path_is_read_only(&vfs_name) {
                                -44
                            } else {
                                self.locked_files.insert(vfs_name);
                                0
                            }
                        } else if let Some(vfs_name) = self.find_vfs_file(&filename) {
                            if self.vfs_path_is_read_only(&vfs_name) {
                                -44
                            } else {
                                self.locked_files.insert(vfs_name);
                                0
                            }
                        } else {
                            -43 // fnfErr
                        };
                        eprintln!("[TRAP] FSpSetFLock(\"{}\") -> {}", filename, err);
                        bus.write_word(sp + 4, err as u16);
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    10 => {
                        // FSpRstFLock ($AA52, selector 10)
                        // Unlocks a file.
                        // FUNCTION FSpRstFLock(spec: FSSpec): OSErr;
                        // Inside Macintosh: Files 1992, 8716..8748
                        let sp = cpu.read_reg(Register::A7);
                        let spec_ptr = bus.read_long(sp);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        let err: i16 = if let Some(vfs_name) =
                            self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                        {
                            if self.vfs_path_is_read_only(&vfs_name) {
                                -44
                            } else {
                                self.locked_files.remove(&vfs_name);
                                0
                            }
                        } else if let Some(vfs_name) = self.find_vfs_file(&filename) {
                            if self.vfs_path_is_read_only(&vfs_name) {
                                -44
                            } else {
                                self.locked_files.remove(&vfs_name);
                                0
                            }
                        } else {
                            0
                        };
                        eprintln!("[TRAP] FSpRstFLock(\"{}\")", filename);
                        bus.write_word(sp + 4, err as u16);
                        cpu.write_reg(Register::A7, sp + 4);
                        Ok(())
                    }
                    13 => {
                        // FSpOpenResFile (selector 13 = $000D)
                        // FUNCTION FSpOpenResFile(spec: FSSpec; permission: SignedByte): INTEGER;
                        // Inside Macintosh Volume VI, 9-43; More Macintosh Toolbox, 1-58
                        // Stack (rightmost on top): [permission(2)] [spec_ptr(4)] [result(2)]
                        let sp = cpu.read_reg(Register::A7);
                        let permission = signed_byte_from_stack_word(bus.read_word(sp));
                        let wants_write = permission == 2 || permission == 3;
                        let spec_ptr = bus.read_long(sp + 2);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        if super::dispatch::trace_resfile_enabled() {
                            eprintln!("[TRAP] FSpOpenResFile file='{}'", filename);
                        }

                        let vref = bus.read_word(spec_ptr) as i16;
                        let dir_id = bus.read_long(spec_ptr + 2);
                        let rsrc_key =
                            self.find_vfs_rsrc_file_for_hfs_lookup(vref, dir_id, &filename);
                        let data_key = self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename);
                        if trace_fsspec_enabled() {
                            eprintln!(
                                "[FSSPEC] FSpOpenResFile file='{}' rsrc_match={:?} data_match={:?}",
                                filename, rsrc_key, data_key
                            );
                        }

                        if let Some(vfs_key) = rsrc_key {
                            if wants_write && self.vfs_path_is_read_only(&vfs_key) {
                                bus.write_word(sp + 6, (-44i16) as u16); // wPrErr
                                cpu.write_reg(Register::D0, (-44i32) as u32);
                                cpu.write_reg(Register::A7, sp + 6);
                                return Some(Ok(()));
                            }
                            // Dedupe: re-opening the same fork must reuse
                            // the existing refnum, not re-allocate every
                            // resource, and must not change CurResFile.
                            // (See OpenRFPerm in toolbox.rs.)
                            if let Some(existing) = self.refnum_for_resource_file_name(&vfs_key) {
                                if wants_write {
                                    self.write_refnums.insert(existing);
                                }
                                if super::dispatch::trace_resfile_enabled() {
                                    eprintln!(
                                        "[TRAP] FSpOpenResFile: \"{}\" already open as refnum {}, dedup",
                                        filename, existing
                                    );
                                }
                                bus.write_word(sp + 6, existing);
                                cpu.write_reg(Register::D0, existing as u32);
                                bus.write_word(0x0A60, 0); // ResErr = noErr
                                cpu.write_reg(Register::A7, sp + 6);
                                return Some(Ok(()));
                            }
                            let refnum =
                                self.open_resource_file_from_vfs_key(bus, &vfs_key, wants_write);
                            bus.write_word(sp + 6, refnum);
                            cpu.write_reg(Register::D0, refnum as u32);
                        } else {
                            // FSpOpenResFile failure semantics:
                            // - If the file exists but has no resource fork, return
                            //   resFNotFound (-193): "resource file not found".
                            // - If the file itself is missing, return fnfErr (-43).
                            //
                            // IM:Volume VI (1991), Resource Manager 13-19..13-20:
                            // FSpOpenResFile uses HOpenResFile result codes and
                            // returns -1 on failure; those include fnfErr for
                            // missing files. Keep the existing data-only
                            // resFNotFound behavior for compatibility with the
                            // OpenResFile/HOpenResFile path.
                            bus.write_word(sp + 6, (-1i16) as u16);
                            cpu.write_reg(Register::D0, (-1i32) as u32);
                            let res_err: i16 = if data_key.is_some() { -193 } else { -43 };
                            bus.write_word(0x0A60, res_err as u16);
                        }
                        cpu.write_reg(Register::A7, sp + 6);
                        Ok(())
                    }
                    14 => {
                        // FSpCreateResFile (selector 14 = $000E)
                        // PROCEDURE FSpCreateResFile(spec: FSSpec; creator: OSType;
                        //   fileType: OSType; scriptTag: ScriptCode);
                        // Stack: [scriptTag(2)] [fileType(4)] [creator(4)] [spec_ptr(4)] — pop 14
                        // More Macintosh Toolbox, 1-56
                        let sp = cpu.read_reg(Register::A7);
                        let file_type = bus.read_long(sp + 2);
                        let creator = bus.read_long(sp + 6);
                        let spec_ptr = bus.read_long(sp + 10);
                        let filename = read_fsspec_name(bus, spec_ptr);
                        if !filename.is_empty() {
                            let vref = bus.read_word(spec_ptr) as i16;
                            let dir_id = bus.read_long(spec_ptr + 2);
                            let Some(vfs_key) = self.vfs_key_for_fsspec(vref, dir_id, &filename)
                            else {
                                bus.write_word(0x0A60, (-120i16) as u16); // dirNFErr
                                cpu.write_reg(Register::A7, sp + 14);
                                return Some(Ok(()));
                            };
                            if self.vfs_path_is_read_only(&vfs_key) {
                                bus.write_word(0x0A60, (-44i16) as u16); // wPrErr
                                cpu.write_reg(Register::A7, sp + 14);
                                return Some(Ok(()));
                            }
                            self.vfs.ensure_empty(vfs_key.clone());
                            self.vfs_rsrc.ensure_empty(vfs_key.clone());
                            self.set_vfs_entry_finfo(&vfs_key, file_type, creator, 0);
                            self.touch_vfs_entry(&vfs_key);
                            if let Some(ref dir) = self.output_dir {
                                let host_path = dir.join(&vfs_key);
                                if let Some(parent) = host_path.parent() {
                                    let _ = std::fs::create_dir_all(parent);
                                }
                                let _ = std::fs::write(host_path, []);
                            }
                        }
                        bus.write_word(0x0A60, 0); // ResErr = noErr
                        cpu.write_reg(Register::A7, sp + 14);
                        Ok(())
                    }
                    15 => {
                        // FSpExchangeFiles (selector 15 = $000F)
                        // FUNCTION FSpExchangeFiles(source: FSSpec;
                        //   dest: FSSpec): OSErr;
                        // Stack (rightmost on top): [dest_ptr(4)]
                        //   [source_ptr(4)] [result(2)]
                        //
                        // Files 1992, pp. 2-165--2-166: exchange both data
                        // and resource forks, plus the modification dates,
                        // while file identity and catalogue information
                        // (including file ID, parent, name, creation date,
                        // and Finder information) remain attached to each
                        // catalogue entry. Open FCBs must continue to refer
                        // to the same file identity after the exchange.
                        let sp = cpu.read_reg(Register::A7);
                        let dest_spec_ptr = bus.read_long(sp);
                        let source_spec_ptr = bus.read_long(sp + 4);

                        let source_name = read_fsspec_name(bus, source_spec_ptr);
                        let source_vref = bus.read_word(source_spec_ptr) as i16;
                        let source_dir_id = bus.read_long(source_spec_ptr + 2);
                        let dest_name = read_fsspec_name(bus, dest_spec_ptr);
                        let dest_vref = bus.read_word(dest_spec_ptr) as i16;
                        let dest_dir_id = bus.read_long(dest_spec_ptr + 2);

                        let (source_volume, _) =
                            self.resolve_volume_and_directory(source_vref, source_dir_id);
                        let (dest_volume, _) =
                            self.resolve_volume_and_directory(dest_vref, dest_dir_id);

                        let source_key = self
                            .find_vfs_file_for_hfs_lookup(source_vref, source_dir_id, &source_name)
                            .or_else(|| {
                                self.find_vfs_rsrc_file_for_hfs_lookup(
                                    source_vref,
                                    source_dir_id,
                                    &source_name,
                                )
                            });
                        let dest_key = self
                            .find_vfs_file_for_hfs_lookup(dest_vref, dest_dir_id, &dest_name)
                            .or_else(|| {
                                self.find_vfs_rsrc_file_for_hfs_lookup(
                                    dest_vref,
                                    dest_dir_id,
                                    &dest_name,
                                )
                            });

                        let result: i16 = if source_volume != dest_volume {
                            -1303 // diffVolErr
                        } else if source_key.is_none() || dest_key.is_none() {
                            -43 // fnfErr
                        } else {
                            let source_key = source_key.expect("checked source FSSpec");
                            let dest_key = dest_key.expect("checked destination FSSpec");

                            if source_key.eq_ignore_ascii_case(&dest_key) {
                                -5038 // afpSameObjectErr
                            } else if self.vfs_path_is_read_only(&source_key)
                                || self.vfs_path_is_read_only(&dest_key)
                            {
                                -46 // vLckdErr
                            } else if self.locked_files.contains(&source_key)
                                || self.locked_files.contains(&dest_key)
                            {
                                -45 // fLckdErr
                            } else {
                                let source_data = self.vfs.remove(&source_key);
                                let dest_data = self.vfs.remove(&dest_key);
                                if let Some(data) = dest_data {
                                    self.vfs.insert(source_key.clone(), data);
                                }
                                if let Some(data) = source_data {
                                    self.vfs.insert(dest_key.clone(), data);
                                }

                                let source_rsrc = self.vfs_rsrc.remove(&source_key);
                                let dest_rsrc = self.vfs_rsrc.remove(&dest_key);
                                if let Some(rsrc) = dest_rsrc {
                                    self.vfs_rsrc.insert(source_key.clone(), rsrc);
                                }
                                if let Some(rsrc) = source_rsrc {
                                    self.vfs_rsrc.insert(dest_key.clone(), rsrc);
                                }

                                let source_metadata = self.vfs_file_metadata(&source_key);
                                let dest_metadata = self.vfs_file_metadata(&dest_key);
                                if let (Some(source_metadata), Some(dest_metadata)) =
                                    (source_metadata, dest_metadata)
                                {
                                    self.vfs_metadata.update(&source_key, |metadata| {
                                        metadata.modified_date = dest_metadata.modified_date;
                                    });
                                    self.vfs_metadata.update(&dest_key, |metadata| {
                                        metadata.modified_date = source_metadata.modified_date;
                                    });
                                    self.publish_vfs_entry_to_process(&source_key);
                                    self.publish_vfs_entry_to_process(&dest_key);
                                }

                                if let Some(ref dir) = self.output_dir {
                                    for key in [&source_key, &dest_key] {
                                        if let Some(data) = self.vfs.get(key) {
                                            let host_path = dir.join(key);
                                            if let Some(parent) = host_path.parent() {
                                                let _ = std::fs::create_dir_all(parent);
                                            }
                                            let _ = std::fs::write(host_path, data);
                                        }
                                    }
                                }
                                0 // noErr
                            }
                        };

                        eprintln!(
                            "[TRAP] FSpExchangeFiles(\"{}\", \"{}\") -> {}",
                            source_name, dest_name, result
                        );
                        bus.write_word(sp + 8, result as u16);
                        cpu.write_reg(Register::A7, sp + 8);
                        Ok(())
                    }
                    _ => {
                        eprintln!(
                            "[TRAP] HighLevelFSDispatch: Unimplemented Selector {}",
                            selector
                        );
                        Err(Error::Halted)
                    }
                }
            }

            // HFSDispatch ($A260) / FSDispatch ($A060)
            // Dispatches hierarchical File Manager routines selected by D0.
            // A0: parameter block; D0 and ioResult: OSErr.
            // Inside Macintosh: Files (1992), pp. 2-183 to 2-238.
            (false, 0x60) => {
                let raw_selector = cpu.read_reg(Register::D0);
                let operation = hfs_dispatch_operation_route(self.current_trap_word, raw_selector);
                self.current_selector_operation = operation.map(|route| route.operation_id);
                let selector = raw_selector & 0xFFFF;
                let pb = cpu.read_reg(Register::A0);
                if matches!(selector, 0x38 | 0x39) {
                    // PBHOpenDeny / PBHOpenRFDeny ($A260, selectors $0038/$0039)
                    // Open a fork with access-deny sharing modes.
                    // FUNCTION PBHOpenDeny(paramBlock: HParmBlkPtr; async: Boolean): OSErr;
                    // Inside Macintosh: Files (1992), pp. 2-209 to 2-210.
                    // The local VFS does not implement deny-mode sharing.
                    // paramErr reports an unsupported volume without falsely
                    // promising a valid ioRefNum.
                    bus.write_word(pb + 16, (-50i16) as u16);
                    cpu.write_reg(Register::D0, (-50i32) as u32);
                    return Some(Ok(()));
                }
                if selector == 0x18 {
                    // PBCatSearch ($A260, selector $0018) searches one
                    // volume's complete catalog and returns bounded FSSpec
                    // batches. Files 1992, 2-38 to 2-42 and 2-204 to 2-206.
                    let result = self.perform_cat_search(bus, pb);
                    bus.write_word(pb + 16, result as u16);
                    cpu.write_reg(Register::D0, result as i32 as u32);
                    return Some(Ok(()));
                }
                if selector == 1 {
                    // PBOpenWD ($A260, selector 1)
                    // Creates a working directory for the specified directory.
                    // FUNCTION PBOpenWD(paramBlock: WDPBPtr; async: Boolean): OSErr;
                    // Files 1992, 2-201 to 2-202
                    let name_ptr = bus.read_long(pb + 18);
                    let name = Self::read_pb_filename(bus, name_ptr);
                    let vref = bus.read_word(pb + 22) as i16;
                    let proc_id = bus.read_long(pb + 28);
                    let requested_dir_id = bus.read_long(pb + 48);
                    if vref != 0 && self.working_directory_info(vref).is_none() {
                        bus.write_word(pb + 16, (-35i16) as u16); // nsvErr
                        cpu.write_reg(Register::D0, (-35i32) as u32);
                        return Some(Ok(()));
                    }
                    let base_dir_id = self.resolve_directory_id(vref, requested_dir_id);
                    // A single-colon partial pathname names the selected directory itself.
                    // Inside Macintosh: Files (1992), pp. 2-27 to 2-29.
                    let effective_dir_id = if name.is_empty() || name == ":" {
                        base_dir_id
                    } else if let Some(path) =
                        self.find_vfs_directory_in_directory(base_dir_id, &name)
                    {
                        self.vfs_directories
                            .iter()
                            .find(|directory| directory.path.eq_ignore_ascii_case(&path))
                            .map(|directory| directory.dir_id)
                            .unwrap_or(base_dir_id)
                    } else {
                        eprintln!(
                            "[TRAP] FSDispatch PBOpenWD name='{}' vref={} dirID={} -> fnfErr",
                            name, vref, requested_dir_id
                        );
                        bus.write_word(pb + 16, (-43i16) as u16);
                        cpu.write_reg(Register::D0, (-43i32) as u32);
                        return Some(Ok(()));
                    };

                    if let Some(wd_ref_num) =
                        self.open_working_directory(vref, effective_dir_id, proc_id)
                    {
                        let volume_ref_num = self.resolve_volume_ref_num(vref);
                        eprintln!(
                            "[TRAP] FSDispatch PBOpenWD name='{}' vref={} dirID={} -> wdRefNum={} resolvedDirID={}",
                            name, vref, requested_dir_id, wd_ref_num, effective_dir_id
                        );
                        bus.write_word(pb + 22, wd_ref_num as u16);
                        bus.write_long(pb + 28, proc_id);
                        bus.write_word(pb + 32, volume_ref_num as u16);
                        bus.write_long(pb + 48, effective_dir_id);
                        bus.write_word(pb + 16, 0);
                        cpu.write_reg(Register::D0, 0);
                    } else {
                        bus.write_word(pb + 16, (-43i16) as u16);
                        cpu.write_reg(Register::D0, (-43i32) as u32);
                    }
                    return Some(Ok(()));
                }

                if selector == 2 {
                    // PBCloseWD ($A260, selector 2)
                    // Releases a working directory reference number.
                    // FUNCTION PBCloseWD(paramBlock: WDPBPtr; async: Boolean): OSErr;
                    // Files 1992, 2-202 to 2-203
                    let wd_ref_num = bus.read_word(pb + 22) as i16;
                    eprintln!("[TRAP] FSDispatch PBCloseWD wdRefNum={}", wd_ref_num);
                    let err = if wd_ref_num == super::TrapDispatcher::boot_volume_ref_num()
                        || self.vfs_volume_for_ref_num(wd_ref_num).is_some()
                        || self.close_working_directory(wd_ref_num)
                    {
                        0
                    } else {
                        -51i16
                    };
                    bus.write_word(pb + 16, err as u16);
                    cpu.write_reg(Register::D0, err as i32 as u32);
                    return Some(Ok(()));
                }

                if selector == 7 {
                    // PBGetWDInfo ($A260, selector 7)
                    // Converts a working directory reference number to volume/directory info.
                    // FUNCTION PBGetWDInfo(paramBlock: WDPBPtr; async: Boolean): OSErr;
                    // Files 1992, 2-203 to 2-204
                    //
                    // Behavioral note: for a phantom ioVRefNum=-999 with
                    // ioWDIndex=0, real Mac returns nsvErr (-35) — interpreting
                    // -999 as a vRefNum (outside the wdRefNum range per
                    // IM:Files 6633) — while Systemless returns rfNumErr (-51).
                    let name_ptr = bus.read_long(pb + 18);
                    let input_vref = bus.read_word(pb + 22) as i16;
                    let wd_index = bus.read_word(pb + 26) as i16;
                    let info = if wd_index > 0 {
                        self.working_directory_by_index(wd_index, input_vref)
                    } else if input_vref == 0 {
                        Some(super::dispatch::WorkingDirectory {
                            ref_num: self
                                .open_working_directory(
                                    super::TrapDispatcher::boot_volume_ref_num(),
                                    *self.default_dir_id,
                                    0,
                                )
                                .unwrap_or(super::TrapDispatcher::boot_volume_ref_num()),
                            volume_ref_num: super::TrapDispatcher::boot_volume_ref_num(),
                            dir_id: *self.default_dir_id,
                            proc_id: 0,
                        })
                    } else {
                        self.working_directory_info(input_vref)
                    };

                    if let Some(working_directory) = info {
                        let returned_vref = if wd_index > 0 {
                            working_directory.volume_ref_num
                        } else {
                            working_directory.ref_num
                        };
                        eprintln!(
                            "[TRAP] FSDispatch PBGetWDInfo input_vRefNum={} ioWDIndex={} -> returned_vRefNum={} ioWDVRefNum={} ioWDDirID={} ioWDProcID=${:08X}",
                            input_vref,
                            wd_index,
                            returned_vref,
                            working_directory.volume_ref_num,
                            working_directory.dir_id,
                            working_directory.proc_id
                        );
                        if name_ptr != 0 {
                            let volume_name = self
                                .vfs_volume_for_ref_num(working_directory.volume_ref_num)
                                .map(|volume| volume.name.as_str())
                                .unwrap_or(super::TrapDispatcher::boot_volume_name());
                            Self::write_pstring(bus, name_ptr, volume_name);
                        }
                        bus.write_word(pb + 22, returned_vref as u16);
                        bus.write_long(pb + 28, working_directory.proc_id);
                        bus.write_word(pb + 32, working_directory.volume_ref_num as u16);
                        bus.write_long(pb + 48, working_directory.dir_id);
                        bus.write_word(pb + 16, 0);
                        cpu.write_reg(Register::D0, 0);
                    } else {
                        eprintln!(
                            "[TRAP] FSDispatch PBGetWDInfo input_vRefNum={} ioWDIndex={} -> rfNumErr",
                            input_vref, wd_index
                        );
                        bus.write_word(pb + 16, (-51i16) as u16);
                        cpu.write_reg(Register::D0, (-51i32) as u32);
                    }
                    return Some(Ok(()));
                }

                let name_ptr = bus.read_long(pb + 18);
                let vref = bus.read_word(pb + 22) as i16;
                // Selector $001A names both PBOpenDF and PBHOpenDF. hfsBit
                // (bit 9) selects the larger HParamBlockRec; without it,
                // offset 48 is outside PBOpenDF's documented inputs and must
                // not participate in lookup. Inside Macintosh Volume IV,
                // Figure 6 and assembly-language note (IV-120); Inside
                // Macintosh Volume VI, pp. 25-51 to 25-52.
                let open_df_uses_hfs_pb = selector == 26 && (self.current_trap_word & 0x0200) != 0;
                let dir_id = if selector == 26 && !open_df_uses_hfs_pb {
                    0
                } else {
                    bus.read_long(pb + 48)
                };
                let filename = Self::read_pb_filename(bus, name_ptr);
                let fdir_index = bus.read_word(pb + 28) as i16;
                eprintln!(
                    "[TRAP] FSDispatch selector={} name_ptr=${:08X} filename=\"{}\" vref={} dirID={} fdirIdx={}",
                    selector, name_ptr, filename, vref, dir_id, fdir_index
                );
                let resolved_vref = self.resolve_volume_ref_num(vref);

                if selector == 6 {
                    // PBDirCreate ($A260, selector 6)
                    // Creates a new directory and returns its directory ID in ioDirID.
                    // FUNCTION PBDirCreate(paramBlock: HParmBlkPtr; async: BOOLEAN): OSErr;
                    // Inside Macintosh Volume IV, IV-146
                    if vref != 0 && self.working_directory_info(vref).is_none() {
                        bus.write_word(pb + 16, (-35i16) as u16); // nsvErr
                        cpu.write_reg(Register::D0, (-35i32) as u32);
                        return Some(Ok(()));
                    }
                    let result = if filename.is_empty() {
                        -37i16 // bdNamErr
                    } else {
                        let parent_dir_id = self.resolve_directory_id(vref, dir_id);
                        let Some(parent_path) = self
                            .directory_path_for_id(parent_dir_id)
                            .map(str::to_string)
                        else {
                            bus.write_word(pb + 16, (-120i16) as u16); // dirNFErr
                            cpu.write_reg(Register::D0, (-120i32) as u32);
                            return Some(Ok(()));
                        };
                        if self.vfs_path_is_read_only(&parent_path) {
                            bus.write_word(pb + 16, (-44i16) as u16); // wPrErr
                            cpu.write_reg(Register::D0, (-44i32) as u32);
                            return Some(Ok(()));
                        }
                        let child_name = super::TrapDispatcher::normalize_hfs_path(&filename);
                        if child_name.is_empty() {
                            -37i16 // bdNamErr
                        } else {
                            let child_path = if parent_path.is_empty() {
                                child_name
                            } else {
                                format!("{parent_path}/{child_name}")
                            };
                            let duplicate =
                                self.vfs_directories.iter().any(|directory| {
                                    directory.path.eq_ignore_ascii_case(&child_path)
                                }) || self
                                    .vfs
                                    .keys()
                                    .any(|path| path.eq_ignore_ascii_case(&child_path))
                                    || self
                                        .vfs_rsrc
                                        .keys()
                                        .any(|path| path.eq_ignore_ascii_case(&child_path));
                            if duplicate {
                                -48i16 // dupFNErr
                            } else {
                                let new_dir_id = self.ensure_vfs_directory(&child_path);
                                if let Some(ref dir) = self.output_dir {
                                    let _ = std::fs::create_dir_all(dir.join(&child_path));
                                }
                                bus.write_long(pb + 48, new_dir_id);
                                eprintln!(
                                    "[TRAP] FSDispatch PBDirCreate(\"{}\") parentDirID={} -> dirID={}",
                                    filename, parent_dir_id, new_dir_id
                                );
                                0
                            }
                        }
                    };
                    bus.write_word(pb + 22, resolved_vref as u16);
                    bus.write_word(pb + 16, result as u16);
                    cpu.write_reg(Register::D0, result as i32 as u32);
                    return Some(Ok(()));
                }

                // PBGetFCBInfo (selector 8): returns info about an open file control block.
                // Input: ioRefNum (offset 24) = file reference number; ioFCBIndx (offset 28)
                //   for indexed access if ioRefNum=0.
                // Output: ioNamePtr filled with filename, ioVRefNum, ioFCBParID, etc.
                // Files 1992, 2-241 to 2-243
                //
                // Behavioral note: for a phantom ioRefNum=-999 with
                // ioFCBIndx=0, real Mac returns rfNumErr (-51) — treating
                // -999 as a categorically-invalid refnum per IM:Files
                // 11733..11736 — while Systemless returns fnOpnErr (-38) per
                // the open_files HashMap miss. Same polymorphic-input
                // divergence class as PBGetWDInfo selector $0007
                // (rfNumErr-vs-nsvErr split).
                if selector == 8 {
                    let ref_num = bus.read_word(pb + 24);
                    let fcb_index = bus.read_word(pb + 28) as i16;
                    eprintln!(
                        "[TRAP] FSDispatch PBGetFCBInfo refNum={} fcbIndx={}",
                        ref_num, fcb_index
                    );

                    // Look up the file by reference number. refNum 0 names the
                    // current application's resource fork. PBOpenRF mirrors
                    // resource forks into open_files as "__rsrc__<path>" so
                    // FSRead/FSWrite can share the data-fork code path.
                    let resolved_fcb = if ref_num == 0 {
                        self.launched_app_path()
                            .map(str::to_owned)
                            .map(|vfs_name| (vfs_name, true))
                    } else if let Some(vfs_name) = self.open_files.get(&ref_num).cloned() {
                        let is_resource_fork = vfs_name.starts_with("__rsrc__");
                        Some((vfs_name, is_resource_fork))
                    } else {
                        self.resource_file_name(ref_num)
                            .map(|vfs_name| (vfs_name.to_string(), true))
                    };

                    if let Some((open_vfs_name, is_resource_fork)) = resolved_fcb {
                        let metadata_name = open_vfs_name
                            .strip_prefix("__rsrc__")
                            .unwrap_or(&open_vfs_name)
                            .to_string();
                        let base_name = super::TrapDispatcher::hfs_name_from_vfs_component(
                            super::TrapDispatcher::vfs_basename(&metadata_name),
                        );
                        let metadata = self.vfs_file_metadata(&metadata_name);
                        let file_len = if is_resource_fork {
                            self.vfs
                                .get(&open_vfs_name)
                                .map(|data| data.len())
                                .or_else(|| {
                                    self.vfs_rsrc.get(&metadata_name).map(|data| data.len())
                                })
                                .unwrap_or(0)
                        } else {
                            self.vfs
                                .get(&metadata_name)
                                .map(|data| data.len())
                                .unwrap_or(0)
                        };
                        let current_pos = self
                            .file_positions
                            .get(&ref_num)
                            .copied()
                            .unwrap_or(0)
                            .min(u32::try_from(file_len).unwrap_or(u32::MAX));
                        let mut flags = if is_resource_fork { 0x0200 } else { 0 };
                        if self.write_refnums.contains(&ref_num) {
                            flags |= 0x0100;
                        }
                        let file_id = metadata.map(|m| m.file_id).unwrap_or(0);
                        let parent_dir_id = metadata.map(|m| m.parent_dir_id).unwrap_or(2);
                        if name_ptr != 0 {
                            Self::write_pstring(bus, name_ptr, &base_name);
                        }
                        let file_volume_ref = self
                            .vfs_volume_for_path(&metadata_name)
                            .map(|volume| volume.ref_num)
                            .unwrap_or(super::TrapDispatcher::boot_volume_ref_num());
                        bus.write_word(pb + 22, file_volume_ref as u16); // ioVRefNum
                        bus.write_word(pb + 30, 0); // filler1
                        bus.write_long(pb + 32, file_id); // ioFCBFlNm
                        bus.write_word(pb + 36, flags); // ioFCBFlags
                        bus.write_word(pb + 38, 0); // ioFCBStBlk
                        bus.write_long(pb + 40, file_len as u32); // ioFCBEOF
                        bus.write_long(pb + 44, file_len as u32); // ioFCBPLen
                        bus.write_long(pb + 48, current_pos); // ioFCBCrPs
                        bus.write_word(pb + 52, file_volume_ref as u16); // ioFCBVRefNum
                        bus.write_long(pb + 54, 0); // ioFCBClpSiz
                        bus.write_long(pb + 58, parent_dir_id); // ioFCBParID
                        eprintln!(
                            "[TRAP] FSDispatch PBGetFCBInfo -> name=\"{}\" len={} pos={} flags=${:04X} parentDirID={}",
                            base_name, file_len, current_pos, flags, parent_dir_id
                        );
                        bus.write_word(pb + 16, 0); // noErr
                        cpu.write_reg(Register::D0, 0);
                    } else {
                        eprintln!(
                            "[TRAP] FSDispatch PBGetFCBInfo: refNum={} not found",
                            ref_num
                        );
                        bus.write_word(pb + 16, (-38i16) as u16); // fnOpnErr
                        cpu.write_reg(Register::D0, (-38i32) as u32);
                    }
                    return Some(Ok(()));
                }

                // PBGetCatInfo (selector 9): returns catalog information.
                // Supports indexed enumeration and directory IDs.
                // Files 1992, 2-190 to 2-192
                //
                // Per IM:Files 9944..9952 the documented errors are
                // noErr / nsvErr / ioErr / bdNamErr / fnfErr / paramErr /
                // dirNFErr; the impl below writes -43 fnfErr on lookup miss.
                if selector == 9 {
                    if vref != 0 && self.working_directory_info(vref).is_none() {
                        bus.write_word(pb + 16, (-35i16) as u16); // nsvErr
                        cpu.write_reg(Register::D0, (-35i32) as u32);
                        return Some(Ok(()));
                    }
                    let lookup = self
                        .lookup_catalog_entry_for_hfs_lookup(vref, dir_id, &filename, fdir_index);

                    if let Some(entry) = lookup {
                        if entry.is_directory {
                            if let Some(directory) = self
                                .vfs_directories
                                .iter()
                                .find(|directory| directory.path.eq_ignore_ascii_case(&entry.path))
                            {
                                self.fill_directory_catalog_info(bus, pb, directory);
                                eprintln!(
                                    "[TRAP] FSDispatch PBGetCatInfo dir \"{}\" -> dirID={} parentDirID={}",
                                    entry.name, directory.dir_id, directory.parent_dir_id
                                );
                            }
                        } else if let Some(metadata) = self.vfs_file_metadata(&entry.path) {
                            self.fill_file_catalog_info(bus, pb, &entry.path, metadata);
                            bus.write_long(pb + 100, metadata.parent_dir_id);
                            eprintln!(
                                "[TRAP] FSDispatch PBGetCatInfo file \"{}\" -> fileID={} parentDirID={}",
                                entry.name, metadata.file_id, metadata.parent_dir_id
                            );
                        }
                        if name_ptr != 0 {
                            let name = Self::hfs_name_from_vfs_component(&entry.name);
                            Self::write_pstring(bus, name_ptr, &name);
                        }
                        bus.write_word(pb + 22, resolved_vref as u16);
                        bus.write_word(pb + 16, 0);
                        cpu.write_reg(Register::D0, 0);
                    } else {
                        bus.write_word(pb + 16, (-43i16) as u16); // fnfErr
                        cpu.write_reg(Register::D0, (-43i32) as u32);
                    }
                    return Some(Ok(()));
                }

                // PBSetCatInfo (selector 10)
                // Updates a file's Finder information and catalogue dates, or
                // a directory's Finder information, using the named entry.
                // FUNCTION PBSetCatInfo(paramBlock: CInfoPBPtr; async: BOOLEAN): OSErr;
                // Inside Macintosh: Files (1992), pp. 2-193 to 2-195.
                if selector == 10 {
                    let error = if vref != 0 && self.working_directory_info(vref).is_none() {
                        -35i16 // nsvErr
                    } else if let Some(entry) =
                        self.lookup_catalog_entry_for_hfs_lookup(vref, dir_id, &filename, 0)
                    {
                        if self.vfs_path_is_read_only(&entry.path) {
                            -46 // vLckdErr
                        } else if entry.is_directory {
                            let file_type = bus.read_long(pb + 32);
                            let creator = bus.read_long(pb + 36);
                            let finder_flags = bus.read_word(pb + 40);
                            self.vfs_directories.with_mut(|directories| {
                                if let Some(directory) = directories.iter_mut().find(|directory| {
                                    directory.path.eq_ignore_ascii_case(&entry.path)
                                }) {
                                    directory.file_type = file_type;
                                    directory.creator = creator;
                                    directory.finder_flags = finder_flags;
                                }
                            });
                            0
                        } else if self.locked_files.contains(&entry.path) {
                            -45 // fLckdErr
                        } else {
                            let file_type = bus.read_long(pb + 32);
                            let creator = bus.read_long(pb + 36);
                            let finder_flags = bus.read_word(pb + 40);
                            let created_date = bus.read_long(pb + 72);
                            let modified_date = bus.read_long(pb + 76);
                            self.vfs_metadata.update(&entry.path, |metadata| {
                                metadata.created_date = created_date;
                                metadata.modified_date = modified_date;
                            });
                            self.set_vfs_entry_finfo(&entry.path, file_type, creator, finder_flags);
                            0
                        }
                    } else {
                        -43 // fnfErr
                    };
                    bus.write_word(pb + 16, error as u16);
                    cpu.write_reg(Register::D0, (error as i32) as u32);
                    return Some(Ok(()));
                }

                // Selector 26 = PBOpenDF / PBHOpenDF: open data fork by name.
                // hfsBit distinguishes the basic parameter block from the HFS
                // form that adds ioDirID. Both forms otherwise share the open,
                // permission, and result behavior below.
                //
                // Per IM:Files 9590..9598 the documented errors are
                // noErr / nsvErr / ioErr / bdNamErr / tmfoErr / fnfErr (-43) /
                // opWrErr / permErr / dirNFErr / afpAccessDenied; the impl
                // below writes -43 fnfErr on lookup miss.
                if selector == 26 {
                    let routine_name = if open_df_uses_hfs_pb {
                        "PBHOpenDF"
                    } else {
                        "PBOpenDF"
                    };
                    if vref != 0 && self.working_directory_info(vref).is_none() {
                        bus.write_word(pb + 16, (-35i16) as u16); // nsvErr
                        cpu.write_reg(Register::D0, (-35i32) as u32);
                        return Some(Ok(()));
                    }
                    // Clear ioRefNum upfront. Files 1992 leaves the output
                    // undefined on failure, but MPW's FSOpen glue writes
                    // `*refNum = pb.ioRefNum` regardless of the result
                    // code — clearing makes the failure path deterministic.
                    bus.write_word(pb + 24, 0);
                    if filename.is_empty() {
                        eprintln!("[TRAP] FSDispatch {routine_name}(\"\") -> bdNamErr");
                        bus.write_word(pb + 16, (-37i16) as u16);
                        cpu.write_reg(Register::D0, (-37i32) as u32);
                        return Some(Ok(()));
                    }
                    if let Some(vfs_name) =
                        self.find_vfs_file_for_hfs_lookup(vref, dir_id, &filename)
                    {
                        let permission = bus.read_byte(pb + 27);
                        let refnum = self.allocate_process_file_refnum();
                        self.open_files.insert(refnum, vfs_name.clone());
                        // Files 1992, pp. 2-183 to 2-184: PBHOpenDF uses the same
                        // ioPermssn values as PBOpen. Record the granted
                        // write access so later PBWrite/PBSetEOF calls honor
                        // the open mode.
                        if matches!(permission, 0 | 2 | 3 | 4) {
                            self.write_refnums.insert(refnum);
                        }
                        self.file_positions.insert(refnum, 0);
                        bus.write_word(pb + 24, refnum); // ioRefNum
                        bus.write_word(pb + 16, 0);
                        cpu.write_reg(Register::D0, 0);
                        eprintln!(
                            "[TRAP] FSDispatch {routine_name}(\"{}\") -> refnum={} vfs=\"{}\"",
                            filename, refnum, vfs_name,
                        );
                        return Some(Ok(()));
                    } else {
                        eprintln!(
                            "[TRAP] FSDispatch {routine_name}(\"{}\") -> fnfErr",
                            filename
                        );
                        bus.write_word(pb + 16, (-43i16) as u16);
                        cpu.write_reg(Register::D0, (-43i32) as u32);
                        return Some(Ok(()));
                    }
                }

                // Return noErr via PB ioResult and D0
                bus.write_word(pb + 16, 0);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // InitFS ($A06C)
            // Public A-trap constant from the Mac OS SDK trap table.
            // Systemless does not model any file-system init side effects here;
            // the caller-visible contract we keep is a no-op that returns
            // noErr and preserves the caller's stack.
            //
            // MPW Universal Headers `Traps.h` publishes `_InitFS = 0xA06C`.
            (false, 0x6C) => {
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            _ => return None,
        })
    }

    /// Shared implementation of SizeResource ($A9A5) and MaxSizeRsrc ($A821).
    ///
    /// Pascal signature is identical for both:
    ///   FUNCTION (theResource: Handle): LONGINT;
    /// Stack on entry:
    ///   SP       theResource (Handle,  4 bytes)
    ///   SP + 4   result      (LongInt, 4 bytes — caller-allocated)
    /// Pops 4 bytes of args, leaves the 4-byte result slot.
    ///
    /// IM:I-121 (SizeResource) and IM:IV-16 (MaxSizeRsrc) document a
    /// disk-vs-map distinction (SizeResource may load the resource;
    /// MaxSizeRsrc reads from the map only) which collapses in our
    /// memory-resident HLE. An empty handle returned while `ResLoad` is false
    /// has no guest allocation, so its byte count comes from the retained
    /// resource-fork backing data without materializing the resource.
    fn handle_resource_size_query<C: CpuOps>(
        &mut self,
        bus: &mut MacMemoryBus,
        cpu: &mut C,
    ) -> Result<()> {
        let sp = cpu.read_reg(Register::A7);
        let handle = bus.read_long(sp);

        let identity = self.loaded_handles.get(&handle).copied();
        let ptr = match identity {
            Some((0, res_type, res_id)) if Self::resource_loading_enabled(bus) => self
                .resource_handle_files
                .get(&handle)
                .copied()
                .and_then(|refnum| {
                    self.reload_resource_data_from_file(bus, refnum, res_type, res_id)
                })
                .unwrap_or(0),
            Some((ptr, _, _)) => ptr,
            None => 0,
        };
        if ptr != 0 && identity.is_some_and(|(old_ptr, _, _)| old_ptr == 0) {
            self.with_resource_manager_mut(|resource_manager| {
                if let Some(entry) = resource_manager.loaded_handles.get_mut(&handle) {
                    entry.0 = ptr;
                }
            });
            bus.write_long(handle, ptr);
            self.restore_loaded_resource_handle(handle, ptr);
        }

        let size: i32 = match identity {
            Some((_, _, _)) if ptr != 0 => bus.get_alloc_size(ptr).map(|s| s as i32).unwrap_or(-1),
            Some((0, res_type, res_id)) => self
                .resource_handle_files
                .get(&handle)
                .and_then(|refnum| self.resource_backing_data.get(&(*refnum, res_type, res_id)))
                .map(|data| data.len() as i32)
                .unwrap_or(-1),
            _ => -1,
        };

        if size < 0 {
            bus.write_word(0x0A60, (-192i16) as u16); // ResErr = resNotFound
        } else {
            bus.write_word(0x0A60, 0); // ResErr = noErr
        }

        bus.write_long(sp + 4, size as u32);
        cpu.write_reg(Register::A7, sp + 4);
        Ok(())
    }

    /// Selector 1 of _ResourceDispatch ($A822). Copies `count` bytes
    /// from (*handle + offset) to `buffer`. Returns the ResErr value
    /// to write back to $0A60.
    /// More Macintosh Toolbox 1993, 1-69.
    fn read_partial_resource(
        &self,
        bus: &mut MacMemoryBus,
        handle: u32,
        offset: i32,
        buffer: u32,
        count: i32,
    ) -> i16 {
        if handle == 0 {
            return Self::RES_NOT_FOUND;
        }
        let handle_ptr = bus.read_long(handle);
        let (ptr, already_in_memory) = if handle_ptr == 0 {
            // MMTB 1993 p. 1-41 documents the normal partial-resource
            // workflow: SetResLoad(FALSE) returns an empty handle, then
            // ReadPartialResource streams bytes from the resource on disk.
            // Systemless keeps that disk backing in loaded_handles.
            let Some((backing_ptr, _, _)) = self.loaded_handles.get(&handle).copied() else {
                return Self::RES_NOT_FOUND;
            };
            (backing_ptr, false)
        } else {
            (handle_ptr, true)
        };
        if ptr == 0 {
            return Self::RES_NOT_FOUND;
        }
        let size = bus.get_alloc_size(ptr).unwrap_or(0) as i64;
        // MMTB 1-69: "If you try to read past the end of a resource
        // or the value of the offset parameter is out of bounds,
        // ResError returns the result code inputOutOfBounds (-190)."
        if offset < 0 || count < 0 {
            return -190;
        }
        let end = offset as i64 + count as i64;
        if end > size {
            return -190;
        }
        if count == 0 {
            return 0;
        }
        let bytes = bus.read_bytes(ptr + offset as u32, count as usize);
        bus.write_bytes(buffer, &bytes);
        // The classic Resource Manager reports `resourceInMemory`
        // after a partial read from a resource that is already loaded.
        if already_in_memory {
            -188
        } else {
            0
        }
    }

    /// Selector 2 of _ResourceDispatch ($A822). Copies `count` bytes
    /// from `buffer` into the resource starting at `offset`. If the
    /// write would extend past the current resource size, the
    /// allocation is grown to fit and `writingPastEnd` (-189) is
    /// returned per MMTB 1-70.
    fn write_partial_resource(
        &mut self,
        bus: &mut MacMemoryBus,
        handle: u32,
        offset: i32,
        buffer: u32,
        count: i32,
    ) -> i16 {
        if handle == 0 {
            return Self::RES_NOT_FOUND;
        }
        let handle_ptr = bus.read_long(handle);
        let handle_was_empty = handle_ptr == 0;
        let ptr = if handle_was_empty {
            // Same SetResLoad(FALSE) partial-resource workflow as
            // ReadPartialResource: the empty handle still names a
            // resource-map entry whose backing bytes Systemless tracks.
            let Some((backing_ptr, _, _)) = self.loaded_handles.get(&handle).copied() else {
                return Self::RES_NOT_FOUND;
            };
            backing_ptr
        } else {
            handle_ptr
        };
        if ptr == 0 {
            return Self::RES_NOT_FOUND;
        }
        if offset < 0 || count < 0 {
            return -190;
        }
        if count == 0 {
            // Zero-length writes are no-ops even if the offset is past
            // the current resource tail.
            return 0;
        }
        let cur_size = bus.get_alloc_size(ptr).unwrap_or(0) as i64;
        let end = offset as i64 + count as i64;
        let mut past_end = false;
        let live_ptr = if end > cur_size {
            past_end = true;
            self.resize_resource_allocation(bus, handle, ptr, end as u32)
        } else {
            ptr
        };
        if live_ptr == 0 {
            // Allocation failed when extending — surface a memory
            // error in the File Manager band per MMTB 1-70.
            return -108; // memFullErr
        }
        if count > 0 {
            let bytes = bus.read_bytes(buffer, count as usize);
            bus.write_bytes(live_ptr + offset as u32, &bytes);
        }
        if handle_was_empty {
            bus.write_long(handle, 0);
            self.untrack_handle_ptr(live_ptr);
        }
        if past_end {
            -189
        } else {
            0
        }
    }

    /// Selector 3 of _ResourceDispatch ($A822). Resizes the resource
    /// allocation to `new_size`, preserving as many bytes as fit.
    /// MMTB 1-71.
    fn set_resource_size(&mut self, bus: &mut MacMemoryBus, handle: u32, new_size: i32) -> i16 {
        if handle == 0 {
            return Self::RES_NOT_FOUND;
        }
        if new_size < 0 {
            // Out-of-band size; treat as input error. MMTB doesn't
            // document negative sizes, but the partial-resource
            // family already uses inputOutOfBounds for invalid
            // numeric arguments per IM:VI 1-69.
            return -190;
        }
        let ptr = bus.read_long(handle);
        if ptr == 0 {
            // Empty handle (e.g. SetResLoad(FALSE) + GetResource).
            // Resize the backing allocation that the Resource Manager
            // still tracks in `loaded_handles`. If we only allocate a
            // new block here, the resource map continues to point at the
            // stale pointer and a later GetResource can synthesize a
            // duplicate handle for the same (type, id) pair.
            if new_size == 0 {
                return 0;
            }
            let Some((old_ptr, _, _)) = self.loaded_handles.get(&handle).copied() else {
                return -192;
            };
            let new_ptr = self.resize_resource_allocation(bus, handle, old_ptr, new_size as u32);
            if new_ptr == 0 {
                return -108; // memFullErr
            }
            return 0;
        }
        let new_ptr = self.resize_resource_allocation(bus, handle, ptr, new_size as u32);
        if new_ptr == 0 && new_size != 0 {
            return -108; // memFullErr
        }
        0
    }

    /// Resize the master-pointer allocation backing a resource handle
    /// to at least `new_size` bytes, preserving the prefix data.
    /// Returns the new master-pointer address (which may differ from
    /// `old_ptr` if the data had to be relocated), or 0 on
    /// allocation failure when `new_size > 0`.
    ///
    /// Updates the live ptr through `*handle`, the `ptr_to_handle`
    /// map, the `loaded_handles` ptr field, and any
    /// `LoadedResources::files[refnum].loaded` / `.named` entries
    /// pointing at the old pointer so subsequent GetResource lookups
    /// see the new allocation. A null old pointer is shared by every
    /// unloaded resource, so only the resized handle's record may be updated.
    pub(crate) fn resize_resource_allocation(
        &mut self,
        bus: &mut MacMemoryBus,
        handle: u32,
        old_ptr: u32,
        new_size: u32,
    ) -> u32 {
        let resized = {
            let memory_manager = self.process_memory_manager();
            let mut memory_manager = memory_manager.borrow_mut();
            memory_manager.attach_classic_memory_bus(bus);
            memory_manager.resize_process_resource_handle(bus, handle, old_ptr, new_size)
        };
        let Ok((old_ptr, new_ptr)) = resized else {
            return 0;
        };
        self.with_resource_manager_mut(|resource_manager| {
            let resource_key =
                resource_manager
                    .loaded_handles
                    .get(&handle)
                    .and_then(|&(_, res_type, res_id)| {
                        resource_manager
                            .resource_handle_files
                            .get(&handle)
                            .copied()
                            .map(|refnum| (refnum, res_type, res_id))
                    });
            if let Some(entry) = resource_manager.loaded_handles.get_mut(&handle) {
                entry.0 = new_ptr;
            }
            if let Some(resources) = resource_manager.resources.as_mut() {
                if old_ptr == 0 {
                    if let Some((refnum, res_type, res_id)) = resource_key {
                        if let Some(file) = resources.files.get_mut(&refnum) {
                            if file.loaded.get(&(res_type, res_id)).copied() == Some(0) {
                                file.loaded.insert((res_type, res_id), new_ptr);
                            }
                            for ((named_type, _), (named_id, ptr)) in &mut file.named {
                                if *named_type == res_type && *named_id == res_id && *ptr == 0 {
                                    *ptr = new_ptr;
                                }
                            }
                        }
                    }
                } else {
                    for file in resources.files.values_mut() {
                        for v in file.loaded.values_mut() {
                            if *v == old_ptr {
                                *v = new_ptr;
                            }
                        }
                        for (_id, v) in file.named.values_mut() {
                            if *v == old_ptr {
                                *v = new_ptr;
                            }
                        }
                    }
                }
            }
        });
        new_ptr
    }

    /// Read a Pascal string filename from a parameter block's ioNamePtr.
    pub(crate) fn read_pb_filename(bus: &MacMemoryBus, name_ptr: u32) -> String {
        if name_ptr == 0 {
            return String::new();
        }
        decode_mac_roman(&bus.read_pstring(name_ptr))
    }

    pub(crate) fn write_pstring(bus: &mut MacMemoryBus, ptr: u32, value: &str) {
        if ptr == 0 {
            return;
        }
        let bytes = encode_mac_roman_lossy(value);
        let len = bytes.len().min(63);
        bus.write_byte(ptr, len as u8);
        for (idx, byte) in bytes.into_iter().take(len).enumerate() {
            bus.write_byte(ptr + 1 + idx as u32, byte);
        }
    }

    fn write_finfo(
        bus: &mut MacMemoryBus,
        finfo_ptr: u32,
        file_type: u32,
        creator: u32,
        finder_flags: u16,
    ) {
        bus.write_long(finfo_ptr, file_type);
        bus.write_long(finfo_ptr + 4, creator);
        bus.write_word(finfo_ptr + 8, finder_flags);
        bus.write_long(finfo_ptr + 10, 0); // fdLocation
        bus.write_word(finfo_ptr + 14, 0); // fdFldr
    }

    fn fill_file_catalog_info(
        &mut self,
        bus: &mut MacMemoryBus,
        pb: u32,
        key: &str,
        metadata: super::dispatch::VfsMetadata,
    ) {
        let data_len = self.vfs.get(key).map_or(0, |data| data.len() as u32);
        let rsrc_len = self.vfs_rsrc.get(key).map_or(0, |data| data.len() as u32);
        // ioFlAttrib bit 0 = file locked.  Files 1992, 2-192.  Maintained
        // by HSetFLock/HRstFLock ($A241/$A242).
        let locked_bit: u8 = if self.locked_files.contains(key) {
            0x01
        } else {
            0x00
        };

        bus.write_byte(pb + 30, locked_bit); // ioFlAttrib
        bus.write_byte(pb + 31, 0); // ioACUser / ioFlVersNum
        Self::write_finfo(
            bus,
            pb + 32,
            metadata.file_type,
            metadata.creator,
            metadata.finder_flags,
        );
        bus.write_long(pb + 48, metadata.file_id);
        bus.write_long(pb + 54, data_len);
        bus.write_long(pb + 58, data_len);
        bus.write_long(pb + 64, rsrc_len);
        bus.write_long(pb + 68, rsrc_len);
        bus.write_long(pb + 72, metadata.created_date);
        bus.write_long(pb + 76, metadata.modified_date);
    }

    fn fill_directory_catalog_info(
        &self,
        bus: &mut MacMemoryBus,
        pb: u32,
        directory: &super::dispatch::VfsDirectory,
    ) {
        bus.write_byte(pb + 30, 0x10); // kFolderBit
        bus.write_byte(pb + 31, 0);
        Self::write_finfo(
            bus,
            pb + 32,
            directory.file_type,
            directory.creator,
            directory.finder_flags,
        );
        bus.write_long(pb + 48, directory.dir_id);
        let child_directory_count = self
            .vfs_directories
            .iter()
            .filter(|child| {
                child.dir_id != directory.dir_id && child.parent_dir_id == directory.dir_id
            })
            .count();
        let child_file_count = self
            .vfs_metadata
            .values()
            .filter(|metadata| metadata.parent_dir_id == directory.dir_id)
            .count();
        let entry_count = child_directory_count
            .saturating_add(child_file_count)
            .min(u16::MAX as usize) as u16;
        bus.write_word(pb + 52, entry_count); // ioDrNmFls
        bus.write_long(pb + 72, 0);
        bus.write_long(pb + 76, 0);
        // ioDrParID: parent directory ID.
        // Files 1992, 2-192
        bus.write_long(pb + 100, directory.parent_dir_id);
    }

    fn cat_search_volume_ref_num(&self, bus: &MacMemoryBus, pb: u32) -> Option<i16> {
        let requested_name = Self::read_pb_filename(bus, bus.read_long(pb + 18));
        if !requested_name.is_empty() {
            if requested_name.eq_ignore_ascii_case(Self::boot_volume_name()) {
                return Some(Self::boot_volume_ref_num());
            }
            return self
                .vfs_volume_by_name(&requested_name)
                .map(|volume| volume.ref_num);
        }

        let requested_ref = bus.read_word(pb + 22) as i16;
        if requested_ref == 0 || requested_ref == Self::boot_volume_ref_num() {
            return Some(self.resolve_volume_ref_num(requested_ref));
        }
        if let Some(volume) = self.vfs_volume_for_ref_num(requested_ref) {
            return Some(volume.ref_num);
        }
        self.working_directory_info(requested_ref)
            .map(|working_directory| working_directory.volume_ref_num)
    }

    fn cat_search_entries(&mut self, volume_ref_num: i16) -> Vec<CatSearchEntry> {
        self.ensure_vfs_catalog();
        let mut entries = Vec::new();

        for directory in &*self.vfs_directories {
            let path = &directory.path;
            let entry_volume_ref = self
                .vfs_volume_for_path(path)
                .map(|volume| volume.ref_num)
                .unwrap_or_else(Self::boot_volume_ref_num);
            if entry_volume_ref != volume_ref_num {
                continue;
            }
            let child_count = self
                .vfs_directories
                .iter()
                .filter(|child| {
                    child.dir_id != directory.dir_id && child.parent_dir_id == directory.dir_id
                })
                .count()
                .saturating_add(
                    self.vfs_metadata
                        .values()
                        .filter(|metadata| metadata.parent_dir_id == directory.dir_id)
                        .count(),
                )
                .min(u16::MAX as usize) as u16;
            let name = if directory.parent_dir_id == 1 {
                if volume_ref_num == Self::boot_volume_ref_num() {
                    Self::boot_volume_name().to_string()
                } else {
                    self.vfs_volume_for_ref_num(volume_ref_num)
                        .map(|volume| volume.name.clone())
                        .unwrap_or_else(|| Self::vfs_basename(&directory.path).to_string())
                }
            } else {
                Self::hfs_name_from_vfs_component(Self::vfs_basename(&directory.path))
            };
            let mut finder_info = [0u8; 16];
            finder_info[..4].copy_from_slice(&directory.file_type.to_be_bytes());
            finder_info[4..8].copy_from_slice(&directory.creator.to_be_bytes());
            finder_info[8..10].copy_from_slice(&directory.finder_flags.to_be_bytes());
            entries.push(CatSearchEntry {
                name,
                vref_num: volume_ref_num,
                parent_dir_id: directory.parent_dir_id,
                is_directory: true,
                locked: false,
                finder_info,
                extended_finder_info: [0; 16],
                data_length: 0,
                resource_length: 0,
                child_count,
                created_date: 0,
                modified_date: 0,
                backup_date: 0,
            });
        }

        let mut file_paths: Vec<String> = self.vfs_metadata.keys().cloned().collect();
        file_paths.sort_unstable_by_key(|path| path.to_ascii_lowercase());
        for path in file_paths {
            let entry_volume_ref = self
                .vfs_volume_for_path(&path)
                .map(|volume| volume.ref_num)
                .unwrap_or_else(Self::boot_volume_ref_num);
            if entry_volume_ref != volume_ref_num {
                continue;
            }
            let Some(metadata) = self.vfs_metadata.get(&path).copied() else {
                continue;
            };
            let mut finder_info = [0u8; 16];
            finder_info[..4].copy_from_slice(&metadata.file_type.to_be_bytes());
            finder_info[4..8].copy_from_slice(&metadata.creator.to_be_bytes());
            finder_info[8..10].copy_from_slice(&metadata.finder_flags.to_be_bytes());
            entries.push(CatSearchEntry {
                name: Self::hfs_name_from_vfs_component(Self::vfs_basename(&path)),
                vref_num: volume_ref_num,
                parent_dir_id: metadata.parent_dir_id,
                is_directory: false,
                locked: self.locked_files.contains(&path),
                finder_info,
                extended_finder_info: [0; 16],
                data_length: self.vfs.get(&path).map_or(0, |data| data.len() as u32),
                resource_length: self.vfs_rsrc.get(&path).map_or(0, |data| data.len() as u32),
                child_count: 0,
                created_date: metadata.created_date,
                modified_date: metadata.modified_date,
                backup_date: 0,
            });
        }

        entries.sort_unstable_by_key(|entry| {
            (
                entry.parent_dir_id,
                entry.name.to_ascii_lowercase(),
                entry.is_directory,
            )
        });
        entries
    }

    fn masked_bytes_match(
        bus: &MacMemoryBus,
        actual: &[u8],
        desired_ptr: u32,
        mask_ptr: u32,
    ) -> bool {
        actual.iter().enumerate().all(|(index, actual)| {
            let desired = bus.read_byte(desired_ptr + index as u32);
            let mask = bus.read_byte(mask_ptr + index as u32);
            (actual ^ desired) & mask == 0
        })
    }

    fn cat_search_entry_matches(
        bus: &MacMemoryBus,
        entry: &CatSearchEntry,
        search_bits: u32,
        info1: u32,
        info2: u32,
    ) -> bool {
        const PARTIAL_NAME: u32 = 1;
        const FULL_NAME: u32 = 2;
        const ATTRIBUTES: u32 = 4;
        const FINDER_INFO: u32 = 8;
        const DIRECTORY_CHILD_COUNT: u32 = 16;
        const DATA_LOGICAL_LENGTH: u32 = 32;
        const DATA_PHYSICAL_LENGTH: u32 = 64;
        const RESOURCE_LOGICAL_LENGTH: u32 = 128;
        const RESOURCE_PHYSICAL_LENGTH: u32 = 256;
        const CREATED_DATE: u32 = 512;
        const MODIFIED_DATE: u32 = 1024;
        const BACKUP_DATE: u32 = 2048;
        const EXTENDED_FINDER_INFO: u32 = 4096;
        const PARENT_ID: u32 = 8192;
        const NEGATE: u32 = 16384;

        let mut matches = true;
        if search_bits & (PARTIAL_NAME | FULL_NAME) != 0 {
            let target = Self::read_pb_filename(bus, bus.read_long(info1 + 18));
            if search_bits & FULL_NAME != 0 {
                matches &= entry.name.eq_ignore_ascii_case(&target);
            } else {
                matches &= entry
                    .name
                    .to_ascii_lowercase()
                    .contains(&target.to_ascii_lowercase());
            }
        }
        if search_bits & ATTRIBUTES != 0 {
            let actual = (u8::from(entry.is_directory) << 4) | u8::from(entry.locked);
            let desired = bus.read_byte(info1 + 30);
            let mask = bus.read_byte(info2 + 30) & 0x11;
            matches &= (actual ^ desired) & mask == 0;
        }
        if search_bits & FINDER_INFO != 0 {
            matches &= Self::masked_bytes_match(bus, &entry.finder_info, info1 + 32, info2 + 32);
        }
        if search_bits & EXTENDED_FINDER_INFO != 0 {
            matches &=
                Self::masked_bytes_match(bus, &entry.extended_finder_info, info1 + 84, info2 + 84);
        }

        if entry.is_directory {
            if search_bits
                & (DATA_LOGICAL_LENGTH
                    | DATA_PHYSICAL_LENGTH
                    | RESOURCE_LOGICAL_LENGTH
                    | RESOURCE_PHYSICAL_LENGTH)
                != 0
            {
                matches = false;
            }
            if search_bits & DIRECTORY_CHILD_COUNT != 0 {
                matches &= entry.child_count >= bus.read_word(info1 + 52)
                    && entry.child_count <= bus.read_word(info2 + 52);
            }
        } else {
            if search_bits & DIRECTORY_CHILD_COUNT != 0 {
                matches = false;
            }
            let range_matches = |bit: u32, offset: u32, value: u32| {
                search_bits & bit == 0
                    || (value >= bus.read_long(info1 + offset)
                        && value <= bus.read_long(info2 + offset))
            };
            matches &= range_matches(DATA_LOGICAL_LENGTH, 54, entry.data_length);
            matches &= range_matches(DATA_PHYSICAL_LENGTH, 58, entry.data_length);
            matches &= range_matches(RESOURCE_LOGICAL_LENGTH, 64, entry.resource_length);
            matches &= range_matches(RESOURCE_PHYSICAL_LENGTH, 68, entry.resource_length);
        }

        let range_matches = |bit: u32, offset: u32, value: u32| {
            search_bits & bit == 0
                || (value >= bus.read_long(info1 + offset)
                    && value <= bus.read_long(info2 + offset))
        };
        matches &= range_matches(CREATED_DATE, 72, entry.created_date);
        matches &= range_matches(MODIFIED_DATE, 76, entry.modified_date);
        matches &= range_matches(BACKUP_DATE, 80, entry.backup_date);
        matches &= range_matches(PARENT_ID, 100, entry.parent_dir_id);

        if search_bits & NEGATE != 0 {
            !matches
        } else {
            matches
        }
    }

    fn write_cat_search_fsspec(bus: &mut MacMemoryBus, ptr: u32, entry: &CatSearchEntry) {
        bus.write_word(ptr, entry.vref_num as u16);
        bus.write_long(ptr + 2, entry.parent_dir_id);
        let bytes = encode_mac_roman_lossy(&entry.name);
        let length = bytes.len().min(63);
        bus.write_byte(ptr + 6, length as u8);
        bus.write_bytes(ptr + 7, &bytes[..length]);
        if length < 63 {
            bus.fill_bytes(ptr + 7 + length as u32, 63 - length as u32, 0);
        }
    }

    fn write_cat_search_position(bus: &mut MacMemoryBus, pb: u32, position: usize) {
        bus.write_long(pb + 52, 1);
        bus.write_long(pb + 56, position.min(u32::MAX as usize) as u32);
        bus.fill_bytes(pb + 60, 8, 0);
    }

    fn perform_cat_search(&mut self, bus: &mut MacMemoryBus, pb: u32) -> i16 {
        bus.write_long(pb + 32, 0);
        let Some(volume_ref_num) = self.cat_search_volume_ref_num(bus, pb) else {
            return -35; // nsvErr
        };
        let requested_count = bus.read_long(pb + 28) as usize;
        if requested_count == 0 {
            return 0;
        }
        let matches_ptr = bus.read_long(pb + 24);
        if matches_ptr == 0 {
            return -50; // paramErr
        }
        let search_bits = bus.read_long(pb + 36);
        let info1 = bus.read_long(pb + 40);
        let info2 = bus.read_long(pb + 44);
        if search_bits & !16384 != 0 && (info1 == 0 || info2 == 0) {
            return -50; // paramErr
        }

        let entries = self.cat_search_entries(volume_ref_num);
        let mut position = if bus.read_long(pb + 52) == 0 {
            0
        } else {
            bus.read_long(pb + 56) as usize
        }
        .min(entries.len());
        let mut actual_count = 0usize;
        while position < entries.len() {
            let entry = &entries[position];
            position += 1;
            if Self::cat_search_entry_matches(bus, entry, search_bits, info1, info2) {
                Self::write_cat_search_fsspec(bus, matches_ptr + actual_count as u32 * 70, entry);
                actual_count += 1;
                if actual_count == requested_count {
                    bus.write_long(pb + 32, actual_count as u32);
                    Self::write_cat_search_position(bus, pb, position);
                    return 0;
                }
            }
        }

        bus.write_long(pb + 32, actual_count as u32);
        Self::write_cat_search_position(bus, pb, entries.len());
        -39 // eofErr
    }

    fn lookup_catalog_entry(
        &mut self,
        dir_id: u32,
        filename: &str,
        fdir_index: i16,
    ) -> Option<super::dispatch::VfsCatalogEntry> {
        if fdir_index < 0 {
            let directory = self.directory_entry_for_id(dir_id)?;
            let path = self.directory_path_for_id(dir_id)?.to_string();
            return Some(super::dispatch::VfsCatalogEntry {
                path,
                name: super::TrapDispatcher::hfs_name_from_vfs_component(
                    &super::TrapDispatcher::vfs_directory_name(&directory.path),
                ),
                is_directory: true,
            });
        }

        if fdir_index > 0 {
            let entries = self.list_vfs_catalog_entries(dir_id);
            return entries.get(fdir_index as usize - 1).cloned();
        }

        // PBGetCatInfo with ioFDirIndex = 0 selects ioNamePtr. System 7.5.3
        // treats an empty name or a single-colon partial pathname as the
        // directory selected by ioDirID. Inside Macintosh: Files (1992),
        // pp. 2-27 to 2-29 and 2-190 to 2-192.
        if filename.is_empty() || filename == ":" {
            let directory = self.directory_entry_for_id(dir_id)?;
            let path = self.directory_path_for_id(dir_id)?.to_string();
            return Some(super::dispatch::VfsCatalogEntry {
                path,
                name: super::TrapDispatcher::hfs_name_from_vfs_component(
                    &super::TrapDispatcher::vfs_directory_name(&directory.path),
                ),
                is_directory: true,
            });
        }

        if let Some(path) = self.find_vfs_directory_in_directory(dir_id, filename) {
            let directory = self
                .vfs_directories
                .iter()
                .find(|directory| directory.path.eq_ignore_ascii_case(&path))?;
            return Some(super::dispatch::VfsCatalogEntry {
                path: path.clone(),
                name: super::TrapDispatcher::hfs_name_from_vfs_component(
                    &super::TrapDispatcher::vfs_directory_name(&directory.path),
                ),
                is_directory: true,
            });
        }
        if let Some(path) = self.find_vfs_file_in_directory(dir_id, filename) {
            self.vfs_file_metadata(&path)?;
            return Some(super::dispatch::VfsCatalogEntry {
                path: path.clone(),
                name: super::TrapDispatcher::hfs_name_from_vfs_component(
                    super::TrapDispatcher::vfs_basename(&path),
                ),
                is_directory: false,
            });
        }
        if let Some(path) = self.find_vfs_rsrc_file_in_directory(dir_id, filename) {
            self.vfs_file_metadata(&path)?;
            return Some(super::dispatch::VfsCatalogEntry {
                path: path.clone(),
                name: super::TrapDispatcher::hfs_name_from_vfs_component(
                    super::TrapDispatcher::vfs_basename(&path),
                ),
                is_directory: false,
            });
        }

        None
    }

    fn list_vfs_file_catalog_entries(
        &mut self,
        dir_id: u32,
    ) -> Vec<super::dispatch::VfsCatalogEntry> {
        self.ensure_vfs_catalog();
        let Some(_) = self.directory_path_for_id(dir_id) else {
            return Vec::new();
        };

        let mut file_paths: Vec<String> = self.vfs_metadata.keys().cloned().collect();
        file_paths.sort_by_key(|path| path.to_ascii_lowercase());

        let mut entries = Vec::new();
        for path in file_paths {
            let Some(metadata) = self.vfs_metadata.get(&path).copied() else {
                continue;
            };
            if metadata.parent_dir_id != dir_id {
                continue;
            }
            entries.push(super::dispatch::VfsCatalogEntry {
                name: super::TrapDispatcher::hfs_name_from_vfs_component(
                    super::TrapDispatcher::vfs_basename(&path),
                ),
                path,
                is_directory: false,
            });
        }

        entries.sort_by_key(|entry| entry.name.to_ascii_lowercase());
        entries
    }

    fn lookup_file_entry(
        &mut self,
        dir_id: u32,
        filename: &str,
        fdir_index: i16,
    ) -> Option<super::dispatch::VfsCatalogEntry> {
        if fdir_index > 0 {
            let entries = self.list_vfs_file_catalog_entries(dir_id);
            return entries.get(fdir_index as usize - 1).cloned();
        }

        if !filename.is_empty() {
            if let Some(path) = self.find_vfs_file_in_directory(dir_id, filename) {
                self.vfs_file_metadata(&path)?;
                return Some(super::dispatch::VfsCatalogEntry {
                    path: path.clone(),
                    name: super::TrapDispatcher::hfs_name_from_vfs_component(
                        super::TrapDispatcher::vfs_basename(&path),
                    ),
                    is_directory: false,
                });
            }
        }

        None
    }

    fn lookup_file_entry_for_get_finfo(
        &mut self,
        vref: i16,
        dir_id: u32,
        filename: &str,
        fdir_index: i16,
    ) -> Option<super::dispatch::VfsCatalogEntry> {
        let mut candidate_dir_ids = self.hfs_lookup_directory_ids(vref, dir_id);
        let non_hfs_dir_id = self.resolve_directory_id(vref, 0);
        if !candidate_dir_ids.contains(&non_hfs_dir_id) {
            candidate_dir_ids.push(non_hfs_dir_id);
        }

        for candidate_dir_id in candidate_dir_ids {
            if let Some(entry) = self.lookup_file_entry(candidate_dir_id, filename, fdir_index) {
                return Some(entry);
            }
        }
        None
    }

    fn lookup_catalog_entry_for_hfs_lookup(
        &mut self,
        vref: i16,
        dir_id: u32,
        filename: &str,
        fdir_index: i16,
    ) -> Option<super::dispatch::VfsCatalogEntry> {
        for candidate_dir_id in self.hfs_lookup_directory_ids(vref, dir_id) {
            if let Some(entry) = self.lookup_catalog_entry(candidate_dir_id, filename, fdir_index) {
                return Some(entry);
            }
        }
        None
    }

    fn find_vfs_file_for_hfs_lookup(
        &mut self,
        vref: i16,
        dir_id: u32,
        filename: &str,
    ) -> Option<String> {
        for candidate_dir_id in self.hfs_lookup_directory_ids(vref, dir_id) {
            if let Some(path) = self.find_vfs_file_in_directory(candidate_dir_id, filename) {
                return Some(path);
            }
        }
        None
    }

    pub(crate) fn find_vfs_rsrc_file_for_hfs_lookup(
        &mut self,
        vref: i16,
        dir_id: u32,
        filename: &str,
    ) -> Option<String> {
        for candidate_dir_id in self.hfs_lookup_directory_ids(vref, dir_id) {
            if let Some(path) = self.find_vfs_rsrc_file_in_directory(candidate_dir_id, filename) {
                return Some(path);
            }
        }
        if let Some(path) = self.materialize_named_quilt_resource_file(filename) {
            return Some(path);
        }
        None
    }

    fn find_vfs_directory_for_hfs_lookup(
        &mut self,
        vref: i16,
        dir_id: u32,
        filename: &str,
    ) -> Option<String> {
        for candidate_dir_id in self.hfs_lookup_directory_ids(vref, dir_id) {
            if let Some(path) = self.find_vfs_directory_in_directory(candidate_dir_id, filename) {
                return Some(path);
            }
        }
        None
    }

    fn directory_id_for_vfs_path(&mut self, path: &str) -> Option<u32> {
        self.ensure_vfs_catalog();
        let normalized = super::TrapDispatcher::normalize_vfs_path(path);
        if normalized.is_empty() {
            return Some(2);
        }

        let mut sorted_directories: Vec<&ProcessVfsDirectory> =
            self.vfs_directories.iter().collect();
        sorted_directories.sort_unstable_by(|left, right| left.path.cmp(&right.path));
        sorted_directories
            .into_iter()
            .find(|directory| directory.path.eq_ignore_ascii_case(&normalized))
            .map(|directory| directory.dir_id)
    }

    fn fsspec_parts_for_hfs_path(
        &mut self,
        vref: i16,
        dir_id: u32,
        filename: &str,
    ) -> Option<(i16, u32, String, String)> {
        let target_key = self.vfs_key_for_fsspec(vref, dir_id, filename)?;
        let parent_path = super::TrapDispatcher::vfs_parent_path(&target_key);
        let parent_dir_id = self.directory_id_for_vfs_path(parent_path)?;
        Some((
            self.resolve_volume_ref_num(vref),
            parent_dir_id,
            super::TrapDispatcher::hfs_name_from_vfs_component(
                super::TrapDispatcher::vfs_basename(&target_key),
            ),
            target_key,
        ))
    }

    pub(crate) fn vfs_key_for_fsspec(
        &mut self,
        vref: i16,
        dir_id: u32,
        filename: &str,
    ) -> Option<String> {
        let normalized = super::TrapDispatcher::normalize_hfs_lookup_path(filename);
        if normalized.is_empty() {
            return None;
        }
        if super::TrapDispatcher::is_unix_tmp_path(filename) {
            self.ensure_vfs_directory("Temporary Items");
        }

        // IM:Files 1992 pp. 2-28 and 2-34: File Manager pathname input can
        // be full or partial, but an FSSpec itself stores only vRefNum,
        // parent dirID, and the final name. If a multi-component pathname's
        // parent already exists from the volume root, prefer that canonical
        // VFS parent; otherwise resolve the pathname relative to vRefNum/dirID.
        if normalized.contains('/') {
            let absolute_parent = super::TrapDispatcher::vfs_parent_path(&normalized);
            if self.directory_id_for_vfs_path(absolute_parent).is_some() {
                return Some(normalized);
            }
        }

        let resolved_dir_id = self.resolve_directory_id(vref, dir_id);
        let dir_path = self.directory_path_for_id(resolved_dir_id)?;
        let candidate = if dir_path.is_empty() {
            normalized
        } else {
            format!("{dir_path}/{normalized}")
        };
        let candidate_parent = super::TrapDispatcher::vfs_parent_path(&candidate);
        self.directory_id_for_vfs_path(candidate_parent)?;
        Some(candidate)
    }

    /// Find a file in VFS by name, preserving explicit path components.
    ///
    /// Basename matching is retained for the classic search-path behavior of
    /// basename-only requests, but an explicit nested pathname must not fall
    /// through to an unrelated file with the same leaf name.
    pub(crate) fn find_vfs_file(&self, name: &str) -> Option<String> {
        let normalized = super::TrapDispatcher::normalize_vfs_path(name);
        // Absolute HFS paths start with a volume name; boot-volume VFS keys
        // start at its root. Preserve partial paths and other volume names.
        // Inside Macintosh: Files (1992), pp. 2-27 to 2-30.
        let hfs_normalized = super::TrapDispatcher::normalize_hfs_lookup_path(name);
        // Sort key iteration so the first match is stable across runs.
        let mut sorted_keys: Vec<&String> = self.vfs.keys().collect();
        sorted_keys.sort_unstable();
        if let Some(found) = sorted_keys
            .iter()
            .copied()
            .find(|key| key.eq_ignore_ascii_case(&hfs_normalized))
        {
            return Some(found.clone());
        }
        if let Some(found) = sorted_keys.iter().copied().find(|key| {
            super::TrapDispatcher::normalize_vfs_path(key).eq_ignore_ascii_case(&normalized)
        }) {
            return Some(found.clone());
        }
        if let Some(found) = super::TrapDispatcher::find_case_insensitive_relative_key(
            sorted_keys.iter().copied(),
            &normalized,
        ) {
            return Some(found);
        }
        // Do not discard explicit directory components after exact and
        // relative-path matching fail. For example, a request for
        // `:Data Files:Data CD` must not open `Character Files/Data CD`.
        // Basename-only requests retain the historical search-path fallback.
        // A colon-free HFS name is a basename even when it contains a slash,
        // which is a legal HFS filename character ("F/A-18 Data").
        // Inside Macintosh: Files (1992), pp. 2-27 to 2-30.
        if !hfs_normalized.contains('/') {
            let hfs_basename = hfs_normalized
                .rsplit('/')
                .next()
                .unwrap_or(hfs_normalized.as_str());
            for key in &sorted_keys {
                let key_base = key.rsplit('/').next().unwrap_or(key);
                if key_base.eq_ignore_ascii_case(hfs_basename) {
                    return Some((*key).clone());
                }
            }
        }
        if !hfs_normalized.contains('/') && !normalized.contains('/') {
            let basename = normalized.rsplit('/').next().unwrap_or(normalized.as_str());
            for key in &sorted_keys {
                let key_base = key.rsplit('/').next().unwrap_or(key);
                if key_base.eq_ignore_ascii_case(basename) {
                    return Some((*key).clone());
                }
            }
        }
        None
    }
}

#[cfg(test)]
mod tests;