bioformats 0.1.3

Pure Rust reimplementation of Bio-Formats — read/write scientific image formats
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
//! Readers and explicit unsupported detectors for obscure and proprietary formats.
//!
//! Partial readers decode only simple documented/raw payload cases. Formats
//! without enough structure to read pixels fail with `UnsupportedFormat` instead
//! of exposing placeholder metadata or synthetic planes.

use std::collections::HashMap;
use std::io::{ErrorKind, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

use crate::common::error::{BioFormatsError, Result};
use crate::common::metadata::{DimensionOrder, ImageMetadata, MetadataValue};
use crate::common::pixel_type::PixelType;
use crate::common::reader::FormatReader;

fn checked_plane_len(meta: &ImageMetadata) -> Result<usize> {
    let bytes_per_pixel = (meta.bits_per_pixel as usize)
        .checked_div(8)
        .filter(|bps| *bps > 0)
        .ok_or_else(|| BioFormatsError::Format("invalid bits per pixel".to_string()))?;
    (meta.size_x as usize)
        .checked_mul(meta.size_y as usize)
        .and_then(|px| px.checked_mul(bytes_per_pixel))
        .ok_or_else(|| BioFormatsError::Format("image plane is too large".to_string()))
}

fn crop_plane(
    plane: &[u8],
    meta: &ImageMetadata,
    x: u32,
    y: u32,
    w: u32,
    h: u32,
) -> Result<Vec<u8>> {
    if x.checked_add(w).is_none_or(|end| end > meta.size_x)
        || y.checked_add(h).is_none_or(|end| end > meta.size_y)
    {
        return Err(BioFormatsError::Format(
            "requested region is outside the image bounds".to_string(),
        ));
    }
    let bytes_per_pixel = (meta.bits_per_pixel / 8) as usize;
    let row_bytes = meta.size_x as usize * bytes_per_pixel;
    let crop_row_bytes = w as usize * bytes_per_pixel;
    let x_offset = x as usize * bytes_per_pixel;
    let mut out = Vec::with_capacity(crop_row_bytes * h as usize);
    for row in y as usize..(y + h) as usize {
        let start = row
            .checked_mul(row_bytes)
            .and_then(|base| base.checked_add(x_offset))
            .ok_or_else(|| BioFormatsError::Format("requested region is too large".to_string()))?;
        let end = start
            .checked_add(crop_row_bytes)
            .ok_or_else(|| BioFormatsError::Format("requested region is too large".to_string()))?;
        if end > plane.len() {
            return Err(BioFormatsError::Format(
                "decoded plane is shorter than expected".to_string(),
            ));
        }
        out.extend_from_slice(&plane[start..end]);
    }
    Ok(out)
}

const MISC4_STRICT_RAW_HEADER_LEN: usize = 32;

#[derive(Clone, Copy)]
struct StrictRawLayout {
    data_offset: u64,
    plane_bytes: usize,
}

fn read_u16_le(buf: &[u8], offset: usize) -> u16 {
    u16::from_le_bytes([buf[offset], buf[offset + 1]])
}

fn read_u32_le(buf: &[u8], offset: usize) -> u32 {
    u32::from_le_bytes([
        buf[offset],
        buf[offset + 1],
        buf[offset + 2],
        buf[offset + 3],
    ])
}

fn read_u64_le(buf: &[u8], offset: usize) -> u64 {
    u64::from_le_bytes([
        buf[offset],
        buf[offset + 1],
        buf[offset + 2],
        buf[offset + 3],
        buf[offset + 4],
        buf[offset + 5],
        buf[offset + 6],
        buf[offset + 7],
    ])
}

fn strict_raw_unsupported(format_name: &str) -> BioFormatsError {
    BioFormatsError::UnsupportedFormat(format!(
        "{format_name} native decoding is unsupported unless explicit strict raw data is present; refusing guessed proprietary metadata"
    ))
}

fn strict_raw_pixel_type(code: u16, format_name: &str) -> Result<PixelType> {
    match code {
        1 => Ok(PixelType::Uint8),
        2 => Ok(PixelType::Uint16),
        3 => Ok(PixelType::Float32),
        _ => Err(BioFormatsError::Format(format!(
            "{format_name} strict raw subset has unsupported pixel type code {code}"
        ))),
    }
}

fn parse_strict_raw_subset(
    path: &Path,
    magic: &[u8; 8],
    format_name: &str,
) -> Result<(ImageMetadata, StrictRawLayout)> {
    let mut file = match std::fs::File::open(path) {
        Ok(file) => file,
        Err(err) if err.kind() == ErrorKind::NotFound => {
            return Err(strict_raw_unsupported(format_name));
        }
        Err(err) => return Err(BioFormatsError::Io(err)),
    };
    let file_len = file.metadata().map_err(BioFormatsError::Io)?.len();
    if file_len < magic.len() as u64 {
        return Err(BioFormatsError::Format(format!(
            "{format_name} file is too short for strict raw subset magic"
        )));
    }

    let mut prefix = [0u8; 8];
    file.read_exact(&mut prefix).map_err(BioFormatsError::Io)?;
    if &prefix != magic {
        return Err(strict_raw_unsupported(format_name));
    }
    if file_len < MISC4_STRICT_RAW_HEADER_LEN as u64 {
        return Err(BioFormatsError::Format(format!(
            "{format_name} strict raw subset header is truncated"
        )));
    }

    let mut header = [0u8; MISC4_STRICT_RAW_HEADER_LEN];
    header[..8].copy_from_slice(&prefix);
    file.read_exact(&mut header[8..])
        .map_err(BioFormatsError::Io)?;

    let size_x = read_u32_le(&header, 8);
    let size_y = read_u32_le(&header, 12);
    let image_count = read_u32_le(&header, 16);
    let pixel_type_code = read_u16_le(&header, 20);
    let reserved = read_u16_le(&header, 22);
    let data_offset = read_u64_le(&header, 24);
    if size_x == 0 || size_y == 0 || image_count == 0 {
        return Err(BioFormatsError::Format(format!(
            "{format_name} strict raw subset dimensions must be non-zero"
        )));
    }
    if reserved != 0 {
        return Err(BioFormatsError::Format(format!(
            "{format_name} strict raw subset reserved header bytes must be zero"
        )));
    }
    if data_offset < MISC4_STRICT_RAW_HEADER_LEN as u64 {
        return Err(BioFormatsError::Format(format!(
            "{format_name} strict raw subset data offset points into header"
        )));
    }

    let pixel_type = strict_raw_pixel_type(pixel_type_code, format_name)?;
    let plane_bytes = (size_x as usize)
        .checked_mul(size_y as usize)
        .and_then(|px| px.checked_mul(pixel_type.bytes_per_sample()))
        .ok_or_else(|| {
            BioFormatsError::Format(format!(
                "{format_name} strict raw subset plane size overflows"
            ))
        })?;
    let payload_bytes = (plane_bytes as u64)
        .checked_mul(image_count as u64)
        .ok_or_else(|| {
            BioFormatsError::Format(format!(
                "{format_name} strict raw subset payload size overflows"
            ))
        })?;
    let required_len = data_offset.checked_add(payload_bytes).ok_or_else(|| {
        BioFormatsError::Format(format!(
            "{format_name} strict raw subset file size overflows"
        ))
    })?;
    if file_len < required_len {
        return Err(BioFormatsError::Format(format!(
            "{format_name} strict raw subset payload is truncated: got {file_len} bytes, expected at least {required_len}"
        )));
    }

    let meta = ImageMetadata {
        size_x,
        size_y,
        size_z: 1,
        size_c: 1,
        size_t: image_count,
        pixel_type,
        bits_per_pixel: (pixel_type.bytes_per_sample() * 8) as u8,
        image_count,
        dimension_order: DimensionOrder::XYCZT,
        is_little_endian: true,
        ..ImageMetadata::default()
    };
    Ok((
        meta,
        StrictRawLayout {
            data_offset,
            plane_bytes,
        },
    ))
}

fn read_strict_raw_plane(
    path: &Path,
    layout: StrictRawLayout,
    plane_index: u32,
) -> Result<Vec<u8>> {
    let offset = layout
        .data_offset
        .checked_add(
            (layout.plane_bytes as u64)
                .checked_mul(plane_index as u64)
                .ok_or_else(|| {
                    BioFormatsError::Format("strict raw subset plane offset overflows".to_string())
                })?,
        )
        .ok_or_else(|| {
            BioFormatsError::Format("strict raw subset plane offset overflows".to_string())
        })?;
    let mut file = std::fs::File::open(path).map_err(BioFormatsError::Io)?;
    file.seek(SeekFrom::Start(offset))
        .map_err(BioFormatsError::Io)?;
    let mut plane = vec![0u8; layout.plane_bytes];
    file.read_exact(&mut plane).map_err(BioFormatsError::Io)?;
    Ok(plane)
}

// ---------------------------------------------------------------------------
// Macro for extension-only placeholder readers
// ---------------------------------------------------------------------------
#[allow(unused_macros)]
macro_rules! placeholder_reader {
    (
        $(#[$attr:meta])*
        pub struct $name:ident;
        extensions: [$($ext:literal),+];
        magic_bytes: false;
    ) => {
        $(#[$attr])*
        pub struct $name {
            path: Option<PathBuf>,
            meta: Option<ImageMetadata>,
        }

        impl $name {
            pub fn new() -> Self {
                $name { path: None, meta: None }
            }
        }

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

        impl FormatReader for $name {
            fn is_this_type_by_name(&self, path: &Path) -> bool {
                let ext = path.extension()
                    .and_then(|e| e.to_str())
                    .map(|e| e.to_ascii_lowercase());
                matches!(ext.as_deref(), $(Some($ext))|+)
            }

            fn is_this_type_by_bytes(&self, _header: &[u8]) -> bool { false }

            fn set_id(&mut self, _path: &Path) -> Result<()> {
                Err(BioFormatsError::UnsupportedFormat(format!(
                    "{} native decoding is unsupported; refusing guessed proprietary metadata",
                    stringify!($name)
                )))
            }

            fn close(&mut self) -> Result<()> {
                self.path = None;
                self.meta = None;
                Ok(())
            }

            fn series_count(&self) -> usize { 0 }

            fn set_series(&mut self, s: usize) -> Result<()> {
                let _ = s;
                Err(BioFormatsError::NotInitialized)
            }

            fn series(&self) -> usize { 0 }

            fn metadata(&self) -> &ImageMetadata {
                self.meta.as_ref().unwrap_or(crate::common::reader::uninitialized_metadata())
            }

            fn open_bytes(&mut self, _plane_index: u32) -> Result<Vec<u8>> {
                Err(BioFormatsError::UnsupportedFormat(format!(
                    "{} native decoding is unsupported; refusing guessed proprietary metadata",
                    stringify!($name)
                )))
            }

            fn open_bytes_region(&mut self, _plane_index: u32, _x: u32, _y: u32, _w: u32, _h: u32) -> Result<Vec<u8>> {
                Err(BioFormatsError::UnsupportedFormat(format!(
                    "{} native decoding is unsupported; refusing guessed proprietary metadata",
                    stringify!($name)
                )))
            }

            fn open_thumb_bytes(&mut self, _plane_index: u32) -> Result<Vec<u8>> {
                Err(BioFormatsError::UnsupportedFormat(format!(
                    "{} native decoding is unsupported; refusing guessed proprietary metadata",
                    stringify!($name)
                )))
            }
        }
    };
}

// ---------------------------------------------------------------------------
// 1. Applied Precision APL
// ---------------------------------------------------------------------------
/// Applied Precision format reader (`.apl`).
///
/// Applied Precision APL is a proprietary binary format used by DeltaVision
/// instruments. The internal structure requires vendor documentation.
pub struct AplReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl AplReader {
    pub fn new() -> Self {
        AplReader {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for AplReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("apl"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFAPL\0\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) =
            parse_strict_raw_subset(path, b"BFAPL\0\0\0", "Applied Precision APL")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 2. ARF format — raw uint16 heuristic
// ---------------------------------------------------------------------------
/// Axon Raw Format (ARF) reader (`.arf`).
///
/// Reads the real file header per the upstream Java ARFReader:
/// 2 endianness bytes, "AR" signature, then version/width/height/bitsPerPixel
/// as unsigned shorts. Pixel data begins at `PIXELS_OFFSET` (524).
pub struct ArfReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
}

const ARF_PIXELS_OFFSET: u64 = 524;

impl ArfReader {
    pub fn new() -> Self {
        ArfReader {
            path: None,
            meta: None,
        }
    }
}

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

impl FormatReader for ArfReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("arf"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        // 2 endianness bytes followed by the "AR" signature.
        if header.len() < 4 {
            return false;
        }
        let valid_endian = (header[0] == 1 && header[1] == 0) || (header[0] == 0 && header[1] == 1);
        valid_endian && &header[2..4] == b"AR"
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;

        let mut f = std::fs::File::open(path).map_err(BioFormatsError::Io)?;
        let mut hdr = [0u8; 12];
        f.read_exact(&mut hdr).map_err(BioFormatsError::Io)?;

        // Determine endianness from the first two bytes.
        let little = if hdr[0] == 1 && hdr[1] == 0 {
            true
        } else if hdr[0] == 0 && hdr[1] == 1 {
            false
        } else {
            return Err(BioFormatsError::InvalidData(
                "ARF: undefined endianness".to_string(),
            ));
        };

        if &hdr[2..4] != b"AR" {
            return Err(BioFormatsError::InvalidData(
                "ARF: missing 'AR' signature".to_string(),
            ));
        }

        let read_u16 = |b: &[u8]| -> u32 {
            if little {
                u16::from_le_bytes([b[0], b[1]]) as u32
            } else {
                u16::from_be_bytes([b[0], b[1]]) as u32
            }
        };

        let version = read_u16(&hdr[4..6]);
        let width = read_u16(&hdr[6..8]);
        let height = read_u16(&hdr[8..10]);
        let bits_per_pixel = read_u16(&hdr[10..12]);
        if width == 0 || height == 0 {
            return Err(BioFormatsError::UnsupportedFormat(
                "ARF header has zero image dimensions".to_string(),
            ));
        }

        // For version 2, the image count follows; otherwise a single image.
        let num_images = if version == 2 {
            let mut nb = [0u8; 2];
            f.read_exact(&mut nb).map_err(BioFormatsError::Io)?;
            let count = read_u16(&nb);
            if count == 0 {
                return Err(BioFormatsError::UnsupportedFormat(
                    "ARF header declares zero image count".to_string(),
                ));
            }
            count
        } else {
            1
        };

        // pixelTypeFromBytes(bpp, false, false): unsigned integer of bpp bytes.
        let mut bpp = bits_per_pixel / 8;
        if bits_per_pixel % 8 != 0 {
            bpp += 1;
        }
        let pixel_type = match bpp {
            1 => PixelType::Uint8,
            2 => PixelType::Uint16,
            4 => PixelType::Uint32,
            _ => {
                return Err(BioFormatsError::UnsupportedFormat(format!(
                    "ARF: unsupported bits per pixel {}",
                    bits_per_pixel
                )))
            }
        };
        let plane_bytes = (width as u64)
            .checked_mul(height as u64)
            .and_then(|px| px.checked_mul(pixel_type.bytes_per_sample() as u64))
            .ok_or_else(|| BioFormatsError::Format("ARF image plane is too large".to_string()))?;
        let required_len = ARF_PIXELS_OFFSET
            .checked_add(plane_bytes.checked_mul(num_images as u64).ok_or_else(|| {
                BioFormatsError::Format("ARF image payload size overflows".to_string())
            })?)
            .ok_or_else(|| BioFormatsError::Format("ARF file size overflows".to_string()))?;
        let file_len = f.metadata().map_err(BioFormatsError::Io)?.len();
        if file_len < required_len {
            return Err(BioFormatsError::UnsupportedFormat(
                "ARF payload is shorter than declared image dimensions".to_string(),
            ));
        }

        self.path = Some(path.to_path_buf());
        self.meta = Some(ImageMetadata {
            size_x: width,
            size_y: height,
            size_z: 1,
            size_c: 1,
            size_t: num_images,
            pixel_type,
            bits_per_pixel: bits_per_pixel as u8,
            image_count: num_images,
            dimension_order: DimensionOrder::XYCZT,
            is_rgb: false,
            is_interleaved: false,
            is_indexed: false,
            is_little_endian: little,
            resolution_count: 1,
            series_metadata: HashMap::new(),
            lookup_table: None,
            modulo_z: None,
            modulo_c: None,
            modulo_t: None,
        });
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let n_bytes = checked_plane_len(meta)?;
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let mut f = std::fs::File::open(path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(
            ARF_PIXELS_OFFSET + plane_index as u64 * n_bytes as u64,
        ))
        .map_err(BioFormatsError::Io)?;
        let mut buf = vec![0u8; n_bytes];
        f.read_exact(&mut buf).map_err(BioFormatsError::Io)?;
        Ok(buf)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 3. I2I format
// ---------------------------------------------------------------------------
/// I2I format reader (`.i2i`).
///
/// I2I is a proprietary format with undocumented structure.
pub struct I2iReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl I2iReader {
    pub fn new() -> Self {
        I2iReader {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for I2iReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("i2i"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFI2I\0\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) = parse_strict_raw_subset(path, b"BFI2I\0\0\0", "I2I")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 4. JDCE format
// ---------------------------------------------------------------------------
/// JDCE format reader (`.jdce`).
///
/// JDCE is a proprietary format with undocumented structure.
pub struct JdceReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl JdceReader {
    pub fn new() -> Self {
        JdceReader {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for JdceReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("jdce"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFJDCE\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) = parse_strict_raw_subset(path, b"BFJDCE\0\0", "JDCE")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 5. JPX (JPEG 2000 Part 2)
// ---------------------------------------------------------------------------
/// JPX (JPEG 2000 Part 2) format reader (`.jpx`).
///
/// JPX files are JPEG 2000 Part 2; delegates to `Jpeg2000Reader`.
pub struct JpxReader {
    inner: crate::formats::misc::Jpeg2000Reader,
}

impl JpxReader {
    pub fn new() -> Self {
        JpxReader {
            inner: crate::formats::misc::Jpeg2000Reader::new(),
        }
    }
}

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

impl FormatReader for JpxReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("jpx"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        self.inner.is_this_type_by_bytes(header)
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.inner.set_id(path)
    }

    fn close(&mut self) -> Result<()> {
        self.inner.close()
    }

    fn series_count(&self) -> usize {
        self.inner.series_count()
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        self.inner.set_series(s)
    }

    fn series(&self) -> usize {
        self.inner.series()
    }

    fn metadata(&self) -> &ImageMetadata {
        self.inner.metadata()
    }

    fn open_bytes(&mut self, p: u32) -> Result<Vec<u8>> {
        self.inner.open_bytes(p)
    }

    fn open_bytes_region(&mut self, p: u32, x: u32, y: u32, w: u32, h: u32) -> Result<Vec<u8>> {
        self.inner.open_bytes_region(p, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, p: u32) -> Result<Vec<u8>> {
        self.inner.open_thumb_bytes(p)
    }
}

// ---------------------------------------------------------------------------
// 6. Capture Pro Image (PCI)
// ---------------------------------------------------------------------------
/// Capture Pro Image format reader (`.pci`).
///
/// Capture Pro is a proprietary format from Media Cybernetics with
/// undocumented binary structure.
pub struct PciReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl PciReader {
    pub fn new() -> Self {
        PciReader {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for PciReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("pci"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFPCI\0\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) =
            parse_strict_raw_subset(path, b"BFPCI\0\0\0", "Capture Pro Image (PCI)")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 7. PDS — Perkin Elmer Densitometer format
// ---------------------------------------------------------------------------
/// PDS (Perkin Elmer Densitometer) format reader.
///
/// Faithful port of Bio-Formats `loci.formats.in.PDSReader`. PDS is NOT the
/// NASA Planetary-Data-System format: it is a Perkin Elmer densitometer dataset
/// consisting of a text header (`.hdr`/`.pds`, magic ` IDENTIFICATION`) holding
/// `KEY = value / comment` lines, plus a companion binary pixel file
/// (`.IMG`/`.img`). Pixels are always UINT16 little-endian. Each on-disk row is
/// `recordWidth`-aligned: there are `pad = recordWidth - (sizeX % recordWidth)`
/// extra samples of padding after each row of `sizeX` samples. `SIGNX`/`SIGNY`
/// values of `-` request horizontal/vertical mirroring of the plane.
///
/// Relevant Java fields (PDSReader.java):
///   - magic `" IDENTIFICATION"` (15 bytes), `isThisType` (lines 76-92).
///   - `NXP`→sizeX, `NYP`→sizeY (lines 214-219).
///   - `SIGNX`/`SIGNY` (`-` ⇒ reverseX/reverseY, lines 230-235).
///   - `COLOR`: 4 ⇒ RGB sizeC=3; else sizeC=1, lutIndex=color-1 (lines 242-254).
///   - `FILE REC LEN` ⇒ recordWidth = value / 2 (lines 255-257).
///   - pixelType UINT16, littleEndian, dimensionOrder XYCZT (lines 262-267).
///   - companion `base + ".IMG"` then `base + ".img"` (lines 269-273).
///   - `openBytes` pad = recordWidth - (sizeX % recordWidth), realX/realY for
///     reverse, readPlane, then byte-swap mirroring (lines 120-162).
pub struct PdsReader {
    /// Path passed to `set_id` (the header file once resolved).
    header_path: Option<PathBuf>,
    /// Companion pixel file (`.IMG`/`.img`).
    pixels_file: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    record_width: u32,
    reverse_x: bool,
    reverse_y: bool,
}

impl PdsReader {
    pub fn new() -> Self {
        PdsReader {
            header_path: None,
            pixels_file: None,
            meta: None,
            record_width: 0,
            reverse_x: false,
            reverse_y: false,
        }
    }

    /// True if `data` begins with the PDS magic `" IDENTIFICATION"`.
    fn header_has_magic(data: &[u8]) -> bool {
        const MAGIC: &[u8] = b" IDENTIFICATION";
        data.len() >= MAGIC.len() && &data[..MAGIC.len()] == MAGIC
    }

    /// Replace the extension of `path` with `ext` (case as given). Mirrors the
    /// Java `name.substring(0, name.lastIndexOf(".")) + ext` logic.
    fn with_extension(path: &Path, ext: &str) -> Option<PathBuf> {
        let s = path.to_str()?;
        let dot = s.rfind('.')?;
        Some(PathBuf::from(format!("{}.{}", &s[..dot], ext)))
    }

    /// Resolve `path` to its header file (the `.hdr`/`.HDR` sibling when `path`
    /// is a `.img`/companion) and read its raw bytes.
    fn resolve_header(path: &Path) -> Result<(PathBuf, Vec<u8>)> {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        // Java initFile: if the id is not a .hdr, look for sibling .hdr then .HDR.
        if ext.as_deref() != Some("hdr") && ext.as_deref() != Some("pds") {
            for hdr_ext in ["hdr", "HDR"] {
                if let Some(hdr) = Self::with_extension(path, hdr_ext) {
                    if hdr.exists() {
                        let data = std::fs::read(&hdr).map_err(BioFormatsError::Io)?;
                        return Ok((hdr, data));
                    }
                }
            }
            return Err(BioFormatsError::Format(
                "Could not find matching .hdr file.".to_string(),
            ));
        }
        let data = std::fs::read(path).map_err(BioFormatsError::Io)?;
        Ok((path.to_path_buf(), data))
    }
}

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

impl FormatReader for PdsReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        match ext.as_deref() {
            // Java accepts "hdr" (and we also accept "pds") directly when the
            // file content matches; isThisType(name, open=true) defers to the
            // byte check, which we approximate by reading the header here.
            Some("hdr") | Some("pds") => std::fs::read(path)
                .map(|d| Self::header_has_magic(&d))
                .unwrap_or(false),
            // Java: for ".img", look up the sibling ".hdr" and check its magic.
            Some("img") => {
                if let Some(hdr) = Self::with_extension(path, "hdr") {
                    if hdr.exists() {
                        return std::fs::read(&hdr)
                            .map(|d| Self::header_has_magic(&d))
                            .unwrap_or(false);
                    }
                }
                if let Some(hdr) = Self::with_extension(path, "HDR") {
                    if hdr.exists() {
                        return std::fs::read(&hdr)
                            .map(|d| Self::header_has_magic(&d))
                            .unwrap_or(false);
                    }
                }
                false
            }
            _ => false,
        }
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        // Java isThisType(stream): the first 15 bytes equal " IDENTIFICATION".
        Self::header_has_magic(header)
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.header_path = None;
        self.pixels_file = None;
        self.meta = None;
        self.record_width = 0;
        self.reverse_x = false;
        self.reverse_y = false;

        let (header_path, header_data) = Self::resolve_header(path)?;

        // Java splits on "\r\n"; if that yields one element, it re-splits on
        // "\r". We normalize all line endings and iterate lines.
        let header_text = String::from_utf8_lossy(&header_data);

        let mut size_x: Option<u32> = None;
        let mut size_y: Option<u32> = None;
        let mut size_c: u32 = 1;
        let mut is_rgb = false;
        let mut is_indexed = false;
        let mut record_width: u32 = 0;
        let mut reverse_x = false;
        let mut reverse_y = false;

        for raw_line in header_text.split(['\n', '\r']) {
            let line = raw_line;
            // Java: int eq = line.indexOf('='); if (eq < 0) continue;
            let Some(eq) = line.find('=') else { continue };
            // Java: int end = line.indexOf('/'); if (end < 0) end = line.length();
            let value_end = line.find('/').unwrap_or(line.len());
            if value_end < eq + 1 {
                // A '/' before '=' would make the slice invalid; skip such lines.
                continue;
            }
            let key = line[..eq].trim();
            let value = line[eq + 1..value_end].trim();

            match key {
                "NXP" => {
                    size_x = Some(value.parse::<u32>().map_err(|_| {
                        BioFormatsError::Format("PDS NXP is not a valid integer".to_string())
                    })?);
                }
                "NYP" => {
                    size_y = Some(value.parse::<u32>().map_err(|_| {
                        BioFormatsError::Format("PDS NYP is not a valid integer".to_string())
                    })?);
                }
                "SIGNX" => {
                    reverse_x = value.replace('\'', "").trim() == "-";
                }
                "SIGNY" => {
                    reverse_y = value.replace('\'', "").trim() == "-";
                }
                "COLOR" => {
                    let color = value.parse::<i32>().map_err(|_| {
                        BioFormatsError::Format("PDS COLOR is not a valid integer".to_string())
                    })?;
                    if color == 4 {
                        size_c = 3;
                        is_rgb = true;
                    } else {
                        size_c = 1;
                        is_rgb = false;
                        let lut_index = color - 1;
                        is_indexed = lut_index >= 0;
                    }
                }
                "FILE REC LEN" => {
                    record_width = value
                        .parse::<u32>()
                        .map_err(|_| {
                            BioFormatsError::Format(
                                "PDS FILE REC LEN is not a valid integer".to_string(),
                            )
                        })?
                        / 2;
                }
                _ => {}
            }
        }

        let size_x = size_x.ok_or_else(|| {
            BioFormatsError::Format("PDS header missing NXP keyword".to_string())
        })?;
        let size_y = size_y.ok_or_else(|| {
            BioFormatsError::Format("PDS header missing NYP keyword".to_string())
        })?;
        if size_x == 0 || size_y == 0 {
            return Err(BioFormatsError::Format(
                "PDS NXP/NYP must be non-zero".to_string(),
            ));
        }
        // pad = recordWidth - (sizeX % recordWidth) requires recordWidth > 0.
        if record_width == 0 {
            return Err(BioFormatsError::Format(
                "PDS header missing FILE REC LEN keyword".to_string(),
            ));
        }

        // Resolve companion pixel file: base + ".IMG" then base + ".img".
        let base = Self::with_extension(&header_path, "IMG").ok_or_else(|| {
            BioFormatsError::Format("PDS header path has no extension".to_string())
        })?;
        let pixels_file = if base.exists() {
            base
        } else {
            Self::with_extension(&header_path, "img").ok_or_else(|| {
                BioFormatsError::Format("PDS header path has no extension".to_string())
            })?
        };
        if !pixels_file.exists() {
            return Err(BioFormatsError::Format(
                "PDS companion .IMG/.img pixel file not found".to_string(),
            ));
        }

        // Validate the companion file is large enough for the declared plane,
        // so truncated datasets fail in set_id like the reference would on read.
        let pad = record_width - (size_x % record_width);
        let scanline = (size_x as u64) + (pad as u64);
        let required = scanline
            .checked_mul(size_y as u64)
            .and_then(|rows| rows.checked_mul(size_c as u64))
            .and_then(|samples| samples.checked_mul(2)) // UINT16
            .ok_or_else(|| BioFormatsError::Format("PDS plane is too large".to_string()))?;
        let available = std::fs::metadata(&pixels_file)
            .map_err(BioFormatsError::Io)?
            .len();
        if available < required {
            return Err(BioFormatsError::UnsupportedFormat(
                "PDS companion file is shorter than declared image dimensions".to_string(),
            ));
        }

        self.record_width = record_width;
        self.reverse_x = reverse_x;
        self.reverse_y = reverse_y;
        self.header_path = Some(header_path);
        self.pixels_file = Some(pixels_file);
        self.meta = Some(ImageMetadata {
            size_x,
            size_y,
            size_z: 1,
            size_c,
            size_t: 1,
            pixel_type: PixelType::Uint16,
            bits_per_pixel: 16,
            image_count: 1,
            // Java: dimensionOrder = "XYCZT".
            dimension_order: DimensionOrder::XYCZT,
            is_rgb,
            // Java leaves interleaved at its default (false) -> planar RGB.
            is_interleaved: false,
            is_indexed,
            is_little_endian: true,
            resolution_count: 1,
            series_metadata: HashMap::new(),
            lookup_table: None,
            modulo_z: None,
            modulo_c: None,
            modulo_t: None,
        });
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.header_path = None;
        self.pixels_file = None;
        self.meta = None;
        self.record_width = 0;
        self.reverse_x = false;
        self.reverse_y = false;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let (size_x, size_y) = (meta.size_x, meta.size_y);
        self.open_bytes_region(plane_index, 0, 0, size_x, size_y)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let size_x = meta.size_x;
        let size_y = meta.size_y;
        let size_c = meta.size_c;
        if x.checked_add(w).is_none_or(|end| end > size_x)
            || y.checked_add(h).is_none_or(|end| end > size_y)
        {
            return Err(BioFormatsError::Format(
                "requested region is outside the image bounds".to_string(),
            ));
        }

        let pixels_file = self
            .pixels_file
            .as_ref()
            .ok_or(BioFormatsError::NotInitialized)?;
        let data = std::fs::read(pixels_file).map_err(BioFormatsError::Io)?;

        let bpp = 2usize; // UINT16
        // Java: pad = recordWidth - (sizeX % recordWidth)
        let pad = self.record_width - (size_x % self.record_width);
        let scanline = (size_x + pad) as usize; // samples per on-disk row
        // On-disk size (in samples) of one full padded channel plane.
        let channel_plane = scanline
            .checked_mul(size_y as usize)
            .ok_or_else(|| BioFormatsError::Format("PDS plane is too large".to_string()))?;

        // Java: realX/realY flip the read origin when mirroring is requested.
        let real_x = if self.reverse_x {
            size_x - w - x
        } else {
            x
        };
        let real_y = if self.reverse_y {
            size_y - h - y
        } else {
            y
        };

        // Output buffer: planar, tightly packed (w*h per channel), w*bpp stride.
        let out_channel_bytes = (w as usize)
            .checked_mul(h as usize)
            .and_then(|px| px.checked_mul(bpp))
            .ok_or_else(|| BioFormatsError::Format("PDS region is too large".to_string()))?;
        let total = out_channel_bytes
            .checked_mul(size_c as usize)
            .ok_or_else(|| BioFormatsError::Format("PDS region is too large".to_string()))?;
        let mut buf = vec![0u8; total];

        // readPlane (non-interleaved): for each channel, for each row, copy a
        // contiguous run of w samples starting at realX within that on-disk row.
        for channel in 0..size_c as usize {
            let channel_base_samples = channel * channel_plane;
            for row in 0..h as usize {
                let src_sample =
                    channel_base_samples + (real_y as usize + row) * scanline + real_x as usize;
                let src_byte = src_sample * bpp;
                let run = w as usize * bpp;
                let src_end = src_byte + run;
                if src_end > data.len() {
                    return Err(BioFormatsError::Format(
                        "PDS companion file is shorter than expected".to_string(),
                    ));
                }
                let dst = channel * out_channel_bytes + row * (w as usize) * bpp;
                buf[dst..dst + run].copy_from_slice(&data[src_byte..src_end]);
            }
        }

        // Java reverseX: swap UINT16 samples within each row (per channel).
        if self.reverse_x {
            for channel in 0..size_c as usize {
                let cbase = channel * out_channel_bytes;
                for row in 0..h as usize {
                    let rbase = cbase + row * (w as usize) * bpp;
                    for col in 0..(w as usize) / 2 {
                        let begin = rbase + 2 * col;
                        let end = rbase + 2 * (w as usize - col - 1);
                        buf.swap(begin, end);
                        buf.swap(begin + 1, end + 1);
                    }
                }
            }
        }

        // Java reverseY: swap whole rows top-to-bottom (per channel).
        if self.reverse_y {
            let row_bytes = (w as usize) * bpp;
            for channel in 0..size_c as usize {
                let cbase = channel * out_channel_bytes;
                for row in 0..(h as usize) / 2 {
                    let start = cbase + row * row_bytes;
                    let end = cbase + (h as usize - row - 1) * row_bytes;
                    for k in 0..row_bytes {
                        buf.swap(start + k, end + k);
                    }
                }
            }
        }

        Ok(buf)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 8. Hiscan HIS format
// ---------------------------------------------------------------------------
/// Hamamatsu HIS format reader (`.his`).
///
/// Translated from Bio-Formats `HISReader`: each series starts with the `IM`
/// magic, a compact little-endian header, an optional semicolon-delimited
/// comment block, and then one image plane. Packed 12-bit variants are unpacked
/// to little-endian `u16` samples; byte-aligned UINT8/UINT16 grayscale and RGB
/// planes are decoded directly.
pub struct HisReader {
    path: Option<PathBuf>,
    metas: Vec<ImageMetadata>,
    pixel_offsets: Vec<u64>,
    packed_12_bit: Vec<bool>,
    current_series: usize,
}

impl HisReader {
    pub fn new() -> Self {
        HisReader {
            path: None,
            metas: Vec::new(),
            pixel_offsets: Vec::new(),
            packed_12_bit: Vec::new(),
            current_series: 0,
        }
    }

    fn current_meta(&self) -> Result<&ImageMetadata> {
        self.metas
            .get(self.current_series)
            .ok_or(BioFormatsError::NotInitialized)
    }
}

fn unpack_his_packed_12(data: &[u8], samples: usize) -> Vec<u8> {
    let mut out = Vec::with_capacity(samples * 2);
    for sample in 0..samples {
        let mut value = 0u16;
        let bit_base = sample * 12;
        for bit_offset in 0..12 {
            let bit = bit_base + bit_offset;
            let byte = data.get(bit / 8).copied().unwrap_or(0);
            let bit_value = (byte >> (7 - (bit % 8))) & 1;
            value = (value << 1) | bit_value as u16;
        }
        out.extend_from_slice(&value.to_le_bytes());
    }
    out
}

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

impl FormatReader for HisReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("his"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.len() >= 2 && &header[..2] == b"IM"
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.metas.clear();
        self.pixel_offsets.clear();
        self.packed_12_bit.clear();
        self.current_series = 0;

        let data = std::fs::read(path).map_err(BioFormatsError::Io)?;
        if data.len() < 16 || &data[..2] != b"IM" {
            return Err(BioFormatsError::UnsupportedFormat(
                "HIS header missing IM magic".to_string(),
            ));
        }

        let series_count = u16::from_le_bytes([data[14], data[15]]) as usize;
        if series_count == 0 {
            return Err(BioFormatsError::UnsupportedFormat(
                "HIS header declares zero image series".to_string(),
            ));
        }

        let mut metas: Vec<ImageMetadata> = Vec::with_capacity(series_count);
        let mut pixel_offsets: Vec<u64> = Vec::with_capacity(series_count);
        let mut packed_12_bit: Vec<bool> = Vec::with_capacity(series_count);
        let mut offset = 0usize;
        // Java HISReader.initFile (lines 129, 138-148): a series after the first
        // that does not start with the "IM" magic indicates that the previous
        // 12-bit plane was actually stored padded to 16 bits. When that happens
        // we retroactively promote the previous series to 16-bit, recompute its
        // (padded) plane size so the current series begins at the correct
        // offset, and latch `adjusted_bit_depth` so the 12-bit data types (6 and
        // 14) are treated as 16-bit for the remainder of the file.
        let mut adjusted_bit_depth = false;
        for series in 0..series_count {
            if offset.checked_add(64).is_none_or(|end| end > data.len()) {
                return Err(BioFormatsError::UnsupportedFormat(format!(
                    "HIS series {series} header is truncated"
                )));
            }
            if &data[offset..offset + 2] != b"IM" {
                // Mirror Java: only the previous series being 12-bit allows us to
                // recover; otherwise the magic really is missing/corrupt.
                if series > 0 && metas[series - 1].bits_per_pixel == 12 {
                    let prev = &mut metas[series - 1];
                    prev.bits_per_pixel = 16;
                    // prevSkip = sizeX*sizeY*sizeC*12/8 (already-consumed packed
                    // plane); totalBytes = sizeX*sizeY*sizeC*2 (16-bit padded).
                    let prev_samples = (prev.size_x as u64)
                        .checked_mul(prev.size_y as u64)
                        .and_then(|px| px.checked_mul(prev.size_c as u64))
                        .ok_or_else(|| {
                            BioFormatsError::Format("HIS image plane is too large".to_string())
                        })?;
                    let prev_pixel_offset = pixel_offsets[series - 1];
                    let total_bytes = prev_samples.checked_mul(2).ok_or_else(|| {
                        BioFormatsError::Format("HIS image plane is too large".to_string())
                    })?;
                    // The previous (12-bit packed) plane is no longer valid; this
                    // series really starts after the 16-bit padded plane.
                    packed_12_bit[series - 1] = false;
                    offset = (prev_pixel_offset + total_bytes) as usize;
                    adjusted_bit_depth = true;

                    if offset.checked_add(64).is_none_or(|end| end > data.len()) {
                        return Err(BioFormatsError::UnsupportedFormat(format!(
                            "HIS series {series} header is truncated"
                        )));
                    }
                    if &data[offset..offset + 2] != b"IM" {
                        return Err(BioFormatsError::UnsupportedFormat(format!(
                            "HIS series {series} missing IM magic"
                        )));
                    }
                } else {
                    return Err(BioFormatsError::UnsupportedFormat(format!(
                        "HIS series {series} missing IM magic"
                    )));
                }
            }

            let comment_bytes = u16::from_le_bytes([data[offset + 2], data[offset + 3]]) as usize;
            let w = u16::from_le_bytes([data[offset + 4], data[offset + 5]]) as u32;
            let h = u16::from_le_bytes([data[offset + 6], data[offset + 7]]) as u32;
            let data_type = u16::from_le_bytes([data[offset + 12], data[offset + 13]]);
            if w == 0 || h == 0 {
                return Err(BioFormatsError::UnsupportedFormat(
                    "HIS header is missing image dimensions".to_string(),
                ));
            }

            // Java: data types 6 and 14 are nominally 12-bit, but once a prior
            // series has been promoted (`adjusted_bit_depth`) they are stored as
            // unpacked 16-bit samples.
            let (pixel_type, bits_per_pixel, size_c, bytes_per_sample, is_packed_12) =
                match data_type {
                    1 => (PixelType::Uint8, 8u8, 1u32, 1u64, false),
                    2 => (PixelType::Uint16, 16u8, 1u32, 2u64, false),
                    6 if adjusted_bit_depth => (PixelType::Uint16, 16u8, 1u32, 2u64, false),
                    6 => (PixelType::Uint16, 12u8, 1u32, 2u64, true),
                    11 => (PixelType::Uint8, 8u8, 3u32, 1u64, false),
                    12 => (PixelType::Uint16, 16u8, 3u32, 2u64, false),
                    14 if adjusted_bit_depth => (PixelType::Uint16, 16u8, 3u32, 2u64, false),
                    14 => (PixelType::Uint16, 12u8, 3u32, 2u64, true),
                    other => {
                        return Err(BioFormatsError::UnsupportedFormat(format!(
                            "HIS data type {other} is not supported"
                        )));
                    }
                };

            let pixel_offset = offset
                .checked_add(64)
                .and_then(|base| base.checked_add(comment_bytes))
                .ok_or_else(|| BioFormatsError::Format("HIS header is too large".to_string()))?;
            let samples = (w as u64)
                .checked_mul(h as u64)
                .and_then(|px| px.checked_mul(size_c as u64))
                .ok_or_else(|| {
                    BioFormatsError::Format("HIS image plane is too large".to_string())
                })?;
            let plane_bytes = if is_packed_12 {
                samples
                    .checked_mul(12)
                    .and_then(|bits| bits.checked_add(7))
                    .map(|bits| bits / 8)
                    .ok_or_else(|| {
                        BioFormatsError::Format("HIS image plane is too large".to_string())
                    })?
            } else {
                samples.checked_mul(bytes_per_sample).ok_or_else(|| {
                    BioFormatsError::Format("HIS image plane is too large".to_string())
                })?
            };
            let next_offset = (pixel_offset as u64)
                .checked_add(plane_bytes)
                .ok_or_else(|| {
                    BioFormatsError::Format("HIS image plane is too large".to_string())
                })?;
            if next_offset > data.len() as u64 {
                return Err(BioFormatsError::UnsupportedFormat(
                    "HIS payload is shorter than declared image dimensions".to_string(),
                ));
            }

            let mut series_metadata = HashMap::new();
            if comment_bytes > 0 {
                let comment_end = pixel_offset;
                let comment_start = comment_end - comment_bytes;
                let comment = String::from_utf8_lossy(&data[comment_start..comment_end]);
                for token in comment.split(';') {
                    if let Some((key, value)) = token.split_once('=') {
                        series_metadata
                            .insert(key.to_string(), MetadataValue::String(value.to_string()));
                    }
                }
            }

            metas.push(ImageMetadata {
                size_x: w,
                size_y: h,
                size_z: 1,
                size_c,
                size_t: 1,
                pixel_type,
                bits_per_pixel,
                image_count: 1,
                dimension_order: DimensionOrder::XYCZT,
                is_rgb: size_c > 1,
                is_interleaved: size_c > 1,
                is_indexed: false,
                is_little_endian: true,
                resolution_count: 1,
                series_metadata,
                lookup_table: None,
                modulo_z: None,
                modulo_c: None,
                modulo_t: None,
            });
            pixel_offsets.push(pixel_offset as u64);
            packed_12_bit.push(is_packed_12);
            offset = next_offset as usize;
        }

        self.path = Some(path.to_path_buf());
        self.metas = metas;
        self.pixel_offsets = pixel_offsets;
        self.packed_12_bit = packed_12_bit;
        self.current_series = 0;
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.metas.clear();
        self.pixel_offsets.clear();
        self.packed_12_bit.clear();
        self.current_series = 0;
        Ok(())
    }

    fn series_count(&self) -> usize {
        self.metas.len()
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.metas.is_empty() {
            Err(BioFormatsError::NotInitialized)
        } else if s >= self.metas.len() {
            Err(BioFormatsError::SeriesOutOfRange(s))
        } else {
            self.current_series = s;
            Ok(())
        }
    }

    fn series(&self) -> usize {
        self.current_series
    }

    fn metadata(&self) -> &ImageMetadata {
        self.metas
            .get(self.current_series)
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.current_meta()?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let sample_count = (meta.size_x as usize)
            .checked_mul(meta.size_y as usize)
            .and_then(|px| px.checked_mul(meta.size_c as usize))
            .ok_or_else(|| BioFormatsError::Format("HIS image plane is too large".to_string()))?;
        let is_packed_12 = *self
            .packed_12_bit
            .get(self.current_series)
            .ok_or(BioFormatsError::NotInitialized)?;
        let n_bytes = if is_packed_12 {
            sample_count
                .checked_mul(12)
                .and_then(|bits| bits.checked_add(7))
                .map(|bits| bits / 8)
                .ok_or_else(|| {
                    BioFormatsError::Format("HIS image plane is too large".to_string())
                })?
        } else {
            sample_count
                .checked_mul(meta.pixel_type.bytes_per_sample())
                .ok_or_else(|| {
                    BioFormatsError::Format("HIS image plane is too large".to_string())
                })?
        };
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let pixel_offset = *self
            .pixel_offsets
            .get(self.current_series)
            .ok_or(BioFormatsError::NotInitialized)?;
        let mut f = std::fs::File::open(path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(pixel_offset))
            .map_err(BioFormatsError::Io)?;
        let mut buf = vec![0u8; n_bytes];
        f.read_exact(&mut buf).map_err(BioFormatsError::Io)?;
        if is_packed_12 {
            Ok(unpack_his_packed_12(&buf, sample_count))
        } else {
            Ok(buf)
        }
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.current_meta()?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        if x.checked_add(w).is_none_or(|end| end > meta.size_x)
            || y.checked_add(h).is_none_or(|end| end > meta.size_y)
        {
            return Err(BioFormatsError::Format(
                "requested region is outside the image bounds".to_string(),
            ));
        }
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        let bytes_per_pixel = meta.pixel_type.bytes_per_sample() * meta.size_c as usize;
        let row_bytes = meta.size_x as usize * bytes_per_pixel;
        let crop_row_bytes = w as usize * bytes_per_pixel;
        let x_offset = x as usize * bytes_per_pixel;
        let mut out = Vec::with_capacity(crop_row_bytes * h as usize);
        for row in y as usize..(y + h) as usize {
            let start = row
                .checked_mul(row_bytes)
                .and_then(|base| base.checked_add(x_offset))
                .ok_or_else(|| {
                    BioFormatsError::Format("requested region is too large".to_string())
                })?;
            let end = start.checked_add(crop_row_bytes).ok_or_else(|| {
                BioFormatsError::Format("requested region is too large".to_string())
            })?;
            out.extend_from_slice(&plane[start..end]);
        }
        Ok(out)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.current_meta()?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 9. HRDC GDF format
// ---------------------------------------------------------------------------
/// HRDC GDF format reader (`.gdf`).
///
/// HRDC GDF is a proprietary format from the Health Research Data Council
/// with undocumented binary structure.
pub struct HrdgdfReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl HrdgdfReader {
    pub fn new() -> Self {
        HrdgdfReader {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for HrdgdfReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("gdf"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFGDF\0\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) = parse_strict_raw_subset(path, b"BFGDF\0\0\0", "HRDC GDF")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 10. Text/CSV image format
// ---------------------------------------------------------------------------
/// Text/CSV image reader (`.csv`).
///
/// Reads a CSV/TSV text file where each row is a line and columns are separated
/// by commas, tabs, or spaces. Each cell is parsed as f64, then stored as Float32
/// pixel data.
pub struct TextImageReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    pixel_data: Vec<u8>,
}

impl TextImageReader {
    pub fn new() -> Self {
        TextImageReader {
            path: None,
            meta: None,
            pixel_data: Vec::new(),
        }
    }
}

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

impl FormatReader for TextImageReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("csv"))
    }

    fn is_this_type_by_bytes(&self, _header: &[u8]) -> bool {
        false
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.pixel_data.clear();

        let text = std::fs::read_to_string(path).map_err(BioFormatsError::Io)?;
        let mut rows: Vec<Vec<f32>> = Vec::new();
        for line in text.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            let mut cells: Vec<f32> = Vec::new();
            for cell in line
                .split(|c: char| c == ',' || c == '\t' || c == ' ')
                .filter(|s| !s.is_empty())
            {
                let value = cell.trim().parse::<f64>().map_err(|_| {
                    BioFormatsError::UnsupportedFormat(format!(
                        "TextImageReader: non-numeric cell {cell:?}"
                    ))
                })?;
                cells.push(value as f32);
            }
            if !cells.is_empty() {
                rows.push(cells);
            }
        }
        if rows.is_empty() {
            return Err(BioFormatsError::UnsupportedFormat(
                "TextImageReader: file contains no numeric data".to_string(),
            ));
        }
        let height = u32::try_from(rows.len())
            .map_err(|_| BioFormatsError::Format("TextImageReader: too many rows".to_string()))?;
        let width = rows[0].len();
        if rows.iter().any(|row| row.len() != width) {
            return Err(BioFormatsError::UnsupportedFormat(
                "TextImageReader: rows have inconsistent column counts".to_string(),
            ));
        }
        let width = u32::try_from(width).map_err(|_| {
            BioFormatsError::Format("TextImageReader: too many columns".to_string())
        })?;
        // Build Float32 pixel buffer (row-major).
        let pixel_bytes = (width as usize)
            .checked_mul(height as usize)
            .and_then(|px| px.checked_mul(4))
            .ok_or_else(|| {
                BioFormatsError::Format("TextImageReader: pixel buffer is too large".to_string())
            })?;
        let mut pixel_data = Vec::with_capacity(pixel_bytes);
        for row in &rows {
            for &val in row {
                pixel_data.extend_from_slice(&val.to_le_bytes());
            }
        }
        self.path = Some(path.to_path_buf());
        self.pixel_data = pixel_data;
        self.meta = Some(ImageMetadata {
            size_x: width,
            size_y: height,
            size_z: 1,
            size_c: 1,
            size_t: 1,
            pixel_type: PixelType::Float32,
            bits_per_pixel: 32,
            image_count: 1,
            dimension_order: DimensionOrder::XYZCT,
            is_rgb: false,
            is_interleaved: false,
            is_indexed: false,
            is_little_endian: true,
            resolution_count: 1,
            series_metadata: HashMap::new(),
            lookup_table: None,
            modulo_z: None,
            modulo_c: None,
            modulo_t: None,
        });
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.pixel_data.clear();
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        Ok(self.pixel_data.clone())
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        crop_plane(&self.pixel_data, meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 11. FilePatternReader - reads file patterns
// ---------------------------------------------------------------------------
/// File pattern reader (`.pattern`).
///
/// Pattern files describe a set of files to combine into a multi-dimensional
/// dataset. Native glob/regex expansion is unsupported; explicit synthetic raw
/// pattern fixtures are supported.
pub struct FilePatternReaderStub {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl FilePatternReaderStub {
    pub fn new() -> Self {
        FilePatternReaderStub {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for FilePatternReaderStub {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("pattern"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFPATT\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) =
            parse_strict_raw_subset(path, b"BFPATT\0\0", "FilePattern synthetic raw")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 12. KLB (Keller Lab Block) format
// ---------------------------------------------------------------------------
/// KLB (Keller Lab Block) format reader (`.klb`).
///
/// KLB is a compressed block-based format for light-sheet microscopy data.
/// Requires a dedicated KLB decoder library which is not available in pure Rust.
pub struct KlbReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl KlbReader {
    pub fn new() -> Self {
        KlbReader {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for KlbReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("klb"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFKLB\0\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) = parse_strict_raw_subset(path, b"BFKLB\0\0\0", "KLB")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}

// ---------------------------------------------------------------------------
// 13. OBF (Imspector OBF)
// ---------------------------------------------------------------------------
/// OBF/MSR Imspector format reader (`.obf`).
///
/// OBF files are handled by ImspectorReader in the extended module.
/// This reader exists as a fallback for files that do not match the
/// Imspector magic bytes.
pub struct ObfReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    layout: Option<StrictRawLayout>,
}

impl ObfReader {
    pub fn new() -> Self {
        ObfReader {
            path: None,
            meta: None,
            layout: None,
        }
    }
}

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

impl FormatReader for ObfReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());
        matches!(ext.as_deref(), Some("obf"))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.starts_with(b"BFOBF\0\0\0")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        let (meta, layout) =
            parse_strict_raw_subset(path, b"BFOBF\0\0\0", "OBF fallback synthetic raw")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.layout = Some(layout);
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.layout = None;
        Ok(())
    }

    fn series_count(&self) -> usize {
        usize::from(self.meta.is_some())
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            Err(BioFormatsError::NotInitialized)
        } else if s == 0 {
            Ok(())
        } else {
            Err(BioFormatsError::SeriesOutOfRange(s))
        }
    }

    fn series(&self) -> usize {
        0
    }

    fn metadata(&self) -> &ImageMetadata {
        self.meta
            .as_ref()
            .unwrap_or(crate::common::reader::uninitialized_metadata())
    }

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let layout = self.layout.ok_or(BioFormatsError::NotInitialized)?;
        read_strict_raw_plane(path, layout, plane_index)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let meta = meta.clone();
        let plane = self.open_bytes(plane_index)?;
        crop_plane(&plane, &meta, x, y, w, h)
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        let tw = meta.size_x.min(256);
        let th = meta.size_y.min(256);
        let tx = (meta.size_x - tw) / 2;
        let ty = (meta.size_y - th) / 2;
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }
}


#[cfg(test)]
mod pds_tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    /// Build a unique base path (no intermediate dots) in the temp directory.
    fn unique_base(tag: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("bioformats_pds_{tag}_{nanos}_{n}"))
    }

    /// Encode `samples` as little-endian UINT16 bytes.
    fn le_u16(samples: &[u16]) -> Vec<u8> {
        let mut v = Vec::with_capacity(samples.len() * 2);
        for s in samples {
            v.extend_from_slice(&s.to_le_bytes());
        }
        v
    }

    /// Write a minimal grayscale PDS fixture: `.hdr` + companion `.IMG`.
    ///
    /// Header carries the ` IDENTIFICATION` magic, `NXP`/`NYP`, `COLOR = 1`
    /// (grayscale, lutIndex 0), `FILE REC LEN` (= 2 * record_width), and the
    /// requested SIGNX/SIGNY. The companion holds `(size_x + pad)` UINT16
    /// samples per row, where `pad = record_width - (size_x % record_width)`.
    /// `pixels` must be a row-major `size_x * size_y` grid of sample values.
    fn write_gray_fixture(
        tag: &str,
        size_x: u32,
        size_y: u32,
        record_width: u32,
        signx: &str,
        signy: &str,
        pixels: &[u16],
    ) -> (PathBuf, PathBuf) {
        assert_eq!(pixels.len(), (size_x * size_y) as usize);
        let base = unique_base(tag);
        let hdr = base.with_extension("hdr");
        let img = base.with_extension("IMG");

        let header = format!(
            " IDENTIFICATION\r\n\
             NXP = {size_x} / x samples\r\n\
             NYP = {size_y} / y samples\r\n\
             SIGNX = '{signx}' / x sign\r\n\
             SIGNY = '{signy}' / y sign\r\n\
             COLOR = 1 / grayscale\r\n\
             FILE REC LEN = {rec_len} / record length in bytes\r\n\
             END\r\n",
            rec_len = record_width * 2,
        );
        std::fs::write(&hdr, header.as_bytes()).unwrap();

        // Companion: one padded row at a time. Padding samples are sentinel
        // 0xFFFF so a bug that reads padding instead of real data is visible.
        let pad = record_width - (size_x % record_width);
        let mut img_samples: Vec<u16> = Vec::new();
        for row in 0..size_y as usize {
            let start = row * size_x as usize;
            img_samples.extend_from_slice(&pixels[start..start + size_x as usize]);
            img_samples.extend(std::iter::repeat(0xFFFFu16).take(pad as usize));
        }
        std::fs::write(&img, le_u16(&img_samples)).unwrap();

        (hdr, img)
    }

    fn cleanup(paths: &[&PathBuf]) {
        for p in paths {
            let _ = std::fs::remove_file(p);
        }
    }

    #[test]
    fn pds_grayscale_full_and_region() {
        // 3x2 image; record_width = 4 => pad = 4 - (3 % 4) = 1 sample per row.
        let size_x = 3u32;
        let size_y = 2u32;
        let record_width = 4u32;
        let pixels: Vec<u16> = vec![
            10, 20, 30, // row 0
            40, 50, 60, // row 1
        ];
        let (hdr, img) =
            write_gray_fixture("gray", size_x, size_y, record_width, "+", "+", &pixels);

        let mut r = PdsReader::new();
        // Detection by name (header magic present).
        assert!(r.is_this_type_by_name(&hdr));
        // Detection of the companion via sibling header.
        assert!(r.is_this_type_by_name(&img));
        // Magic byte detection.
        assert!(r.is_this_type_by_bytes(b" IDENTIFICATION extra"));
        assert!(!r.is_this_type_by_bytes(b"NOT A PDS FILE."));

        r.set_id(&hdr).unwrap();
        let meta = r.metadata();
        assert_eq!(meta.size_x, size_x);
        assert_eq!(meta.size_y, size_y);
        assert_eq!(meta.size_c, 1);
        assert_eq!(meta.pixel_type, PixelType::Uint16);
        assert!(meta.is_little_endian);
        assert!(!meta.is_rgb);

        // Full plane: padding must be stripped, row-major order preserved.
        let full = r.open_bytes(0).unwrap();
        assert_eq!(full, le_u16(&pixels));

        // Region crop: 2x2 starting at (1,0) => columns 1,2 of both rows.
        let region = r.open_bytes_region(0, 1, 0, 2, 2).unwrap();
        assert_eq!(region, le_u16(&[20, 30, 50, 60]));

        // Single-pixel crop bottom-right.
        let one = r.open_bytes_region(0, 2, 1, 1, 1).unwrap();
        assert_eq!(one, le_u16(&[60]));

        // Out-of-bounds region rejected.
        assert!(r.open_bytes_region(0, 2, 0, 2, 1).is_err());

        cleanup(&[&hdr, &img]);
    }

    #[test]
    fn pds_grayscale_reverse_xy() {
        // SIGNX = '-' and SIGNY = '-' mirror horizontally and vertically.
        let size_x = 3u32;
        let size_y = 2u32;
        let record_width = 4u32;
        let pixels: Vec<u16> = vec![
            10, 20, 30, // row 0
            40, 50, 60, // row 1
        ];
        let (hdr, img) =
            write_gray_fixture("rev", size_x, size_y, record_width, "-", "-", &pixels);

        let mut r = PdsReader::new();
        r.set_id(&hdr).unwrap();
        assert!(r.reverse_x);
        assert!(r.reverse_y);

        // Full plane mirrored in both axes:
        // Original rows: [10,20,30],[40,50,60]
        // reverseX per row: [30,20,10],[60,50,40]
        // reverseY swaps rows: [60,50,40],[30,20,10]
        let full = r.open_bytes(0).unwrap();
        assert_eq!(full, le_u16(&[60, 50, 40, 30, 20, 10]));

        cleanup(&[&hdr, &img]);
    }

    #[test]
    fn pds_reject_missing_companion() {
        // Header present and valid, but no .IMG/.img companion exists.
        let base = unique_base("nocomp");
        let hdr = base.with_extension("hdr");
        let header = " IDENTIFICATION\r\n\
             NXP = 4 / x\r\n\
             NYP = 4 / y\r\n\
             COLOR = 1 /\r\n\
             FILE REC LEN = 8 /\r\n\
             END\r\n";
        std::fs::write(&hdr, header).unwrap();

        let mut r = PdsReader::new();
        assert!(r.set_id(&hdr).is_err());
        // State stays uninitialized after the failure.
        assert_eq!(r.series_count(), 0);

        cleanup(&[&hdr]);
    }

    #[test]
    fn pds_reject_truncated_companion() {
        // Companion exists but is shorter than the declared (padded) plane.
        let base = unique_base("trunc");
        let hdr = base.with_extension("hdr");
        let img = base.with_extension("IMG");
        let header = " IDENTIFICATION\r\n\
             NXP = 8 / x\r\n\
             NYP = 8 / y\r\n\
             COLOR = 1 /\r\n\
             FILE REC LEN = 16 /\r\n\
             END\r\n";
        std::fs::write(&hdr, header).unwrap();
        // Only a handful of bytes, far short of 8 rows of (8 + pad) UINT16.
        std::fs::write(&img, [0u8; 16]).unwrap();

        let mut r = PdsReader::new();
        assert!(r.set_id(&hdr).is_err());

        cleanup(&[&hdr, &img]);
    }
}