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
//! Zeiss CZI (ZISRAWFILE) format reader.
//!
//! Segments use a 32-byte header:
//!   bytes  0-15: segment type (ASCII, zero-padded) e.g. "ZISRAWFILE"
//!   bytes 16-23: allocated size (int64 LE)
//!   bytes 24-31: used size (int64 LE)
//!
//! Supported compressions: Uncompressed, JPEG (new-style), LZW, Zstd.
//! JPEG-XR is detected but not decoded (needs a JXRC decoder).

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

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

// ---- pixel types (from DirectoryEntry) -------------------------------------

fn czi_pixel_type(code: i32) -> std::io::Result<(PixelType, u32)> {
    // Returns (pixel_type, samples_per_pixel)
    match code {
        0 => Ok((PixelType::Uint8, 1)),    // Gray8
        1 => Ok((PixelType::Uint16, 1)),   // Gray16
        2 => Ok((PixelType::Float32, 1)),  // GrayFloat
        3 => Ok((PixelType::Uint8, 3)),    // Bgr24
        4 => Ok((PixelType::Uint16, 3)),   // Bgr48
        8 => Ok((PixelType::Float32, 3)),  // BgrFloat
        9 => Ok((PixelType::Uint8, 4)),    // Bgra32
        10 => Ok((PixelType::Float32, 2)), // Complex (re+im)
        11 => Ok((PixelType::Float32, 2)), // ComplexFloat
        12 => Ok((PixelType::Uint32, 1)),  // Gray32
        13 => Ok((PixelType::Float64, 1)), // GrayDouble
        other => Err(czi_invalid_data(format!(
            "CZI unsupported pixel type code {other}"
        ))),
    }
}

// ---- segment header --------------------------------------------------------

const SEG_HEADER: usize = 32;

fn read_seg_type(data: &[u8]) -> String {
    let end = data[..16].iter().position(|&b| b == 0).unwrap_or(16);
    String::from_utf8_lossy(&data[..end]).into_owned()
}

fn read_i32(data: &[u8], off: usize) -> i32 {
    i32::from_le_bytes([data[off], data[off + 1], data[off + 2], data[off + 3]])
}
fn read_i64(data: &[u8], off: usize) -> i64 {
    i64::from_le_bytes(data[off..off + 8].try_into().unwrap_or([0; 8]))
}
fn read_u64(data: &[u8], off: usize) -> u64 {
    u64::from_le_bytes(data[off..off + 8].try_into().unwrap_or([0; 8]))
}

fn read_seg_sizes(data: &[u8]) -> (u64, u64) {
    let allocated = read_u64(data, 16);
    let mut used = read_u64(data, 24);
    if used == 0 {
        used = allocated;
    }
    (allocated, used)
}

fn valid_segment_position(pos: u64, file_len: u64) -> bool {
    pos > 0 && pos.saturating_add(SEG_HEADER as u64) <= file_len
}

// ---- DirectoryEntry (256 bytes) -------------------------------------------

#[derive(Debug, Clone)]
struct DirEntry {
    pixel_type: i32,
    file_position: i64,
    compression: i32,
    // Dimensions from DimensionEntry array
    dims: HashMap<String, (i32, i32)>, // dim_name -> (start, size)
    // storedSize per dimension (physical/decoded extent of the tile, which may
    // differ from `size` for downsampled or compressed subblocks).
    stored: HashMap<String, i32>, // dim_name -> storedSize
}

impl DirEntry {
    fn dim_start(&self, name: &str) -> i32 {
        self.dims.get(name).map(|&(start, _)| start).unwrap_or(0)
    }

    fn dim_size(&self, name: &str) -> i32 {
        self.dims.get(name).map(|&(_, size)| size).unwrap_or(1)
    }

    fn has_dim(&self, name: &str) -> bool {
        self.dims.contains_key(name)
    }

    /// Stored (physical) size of a dimension, falling back to the logical size.
    fn dim_stored_size(&self, name: &str) -> i32 {
        match self.stored.get(name) {
            Some(&s) if s > 0 => s,
            _ => self.dim_size(name),
        }
    }

    fn matches_plane(&self, z: u32, c: u32, t: u32) -> bool {
        self.dims
            .get("Z")
            .map(|&(s, _)| s as u32 == z)
            .unwrap_or(z == 0)
            && self
                .dims
                .get("C")
                .map(|&(s, _)| s as u32 == c)
                .unwrap_or(c == 0)
            && self
                .dims
                .get("T")
                .map(|&(s, _)| s as u32 == t)
                .unwrap_or(t == 0)
    }
}

#[derive(Debug, Clone)]
struct CziResolution {
    r: i32,
    width: u32,
    height: u32,
}

/// One series corresponds to one combination of the CZI "extra" dimensions that
/// ZeissCZIReader.assignPlaneIndices folds into the series axis: scene ("S"),
/// acquisition ("B"), angle ("V") and — unless prestitched — mosaic ("M"). Each
/// series carries its own pyramid resolution list and per-pixel-type slot.
///
/// Port of the per-series core split: `seriesCount = positions * acquisitions *
/// angles * mosaics` (mosaics only when `maxResolution == 0` and not
/// prestitched), with an extra factor of `pixelTypes.size()` for the per-pixel-
/// type core split.
#[derive(Debug, Clone)]
struct CziSeries {
    /// Selector for the "S" dimension start, or `None` to match any scene.
    scene: Option<i32>,
    /// Selector for the "B" (acquisition) dimension start, or `None` to match any.
    acquisition: Option<i32>,
    /// Selector for the "V" (angle) dimension start, or `None` to match any.
    angle: Option<i32>,
    /// Selector for the "M" (mosaic) dimension start when mosaics are exposed as
    /// separate series (not prestitched). `None` => match any / stitch all M.
    mosaic: Option<i32>,
    /// Index into the distinct-pixel-type list (per-pixel-type core split).
    /// When `pixel_types.len() > 1`, this also selects the logical channel offset.
    pixel_type_index: usize,
    /// PALM series selector: the stored (X,Y) tile size that identifies which of
    /// the two PALM planes this series exposes (ZeissCZIReader:1155-1172 splits by
    /// stored size). `None` for non-PALM series.
    palm_size: Option<(u32, u32)>,
    resolutions: Vec<CziResolution>,
}

fn parse_dir_entry(data: &[u8]) -> DirEntry {
    // schema 0-1 (2 bytes)
    let pixel_type = read_i32(data, 2);
    let file_position = read_i64(data, 6);
    let compression = read_i32(data, 18);
    let dim_count = read_i32(data, 28) as usize;

    let mut dims: HashMap<String, (i32, i32)> = HashMap::new();
    let mut stored: HashMap<String, i32> = HashMap::new();
    let dim_array_start = 32;
    for i in 0..dim_count {
        let off = dim_array_start + i * 20;
        if off + 20 > data.len() {
            break;
        }
        // DimensionEntry layout (20 bytes):
        //   0  dimension (4 chars)
        //   4  start (int)
        //   8  size (int)
        //   12 startCoordinate (float)
        //   16 storedSize (int)
        let dim_name = std::str::from_utf8(&data[off..off + 4])
            .unwrap_or("")
            .trim_end_matches('\0')
            .trim()
            .to_string();
        let start = read_i32(data, off + 4);
        let size = read_i32(data, off + 8);
        let stored_size = read_i32(data, off + 16);
        if !dim_name.is_empty() {
            dims.insert(dim_name.clone(), (start, size));
            stored.insert(dim_name, stored_size);
        }
    }

    DirEntry {
        pixel_type,
        file_position,
        compression,
        dims,
        stored,
    }
}

fn czi_invalid_data(message: impl Into<String>) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
}

fn parse_directory_entries(data: &[u8], entry_count: usize) -> std::io::Result<Vec<DirEntry>> {
    let mut entries = Vec::with_capacity(entry_count);

    if entry_count == 0 {
        return Ok(entries);
    }

    // Synthetic fixtures in this crate historically wrote each directory entry
    // into the 256-byte subblock slot. Real CZI directory segments store compact
    // entries: 32 bytes plus 20 bytes per DimensionEntry.
    let fixed_stride = if entry_count
        .checked_mul(256)
        .is_some_and(|bytes| data.len() >= bytes)
    {
        Some(256)
    } else {
        None
    };

    let mut off = 0usize;
    for entry_index in 0..entry_count {
        if off + 32 > data.len() {
            return Err(czi_invalid_data(format!(
                "CZI directory entry {entry_index} is truncated before its fixed header"
            )));
        }
        let dim_count = read_i32(data, off + 28).max(0) as usize;
        let compact_len = 32usize
            .checked_add(dim_count.checked_mul(20).ok_or_else(|| {
                czi_invalid_data(format!(
                    "CZI directory entry {entry_index} dimension table size overflows"
                ))
            })?)
            .ok_or_else(|| {
                czi_invalid_data(format!(
                    "CZI directory entry {entry_index} dimension table size overflows"
                ))
            })?;
        let entry_len = fixed_stride.unwrap_or(compact_len);
        let compact_end = off.checked_add(compact_len).ok_or_else(|| {
            czi_invalid_data(format!(
                "CZI directory entry {entry_index} offset overflows"
            ))
        })?;
        if compact_end > data.len() {
            return Err(czi_invalid_data(format!(
                "CZI directory entry {entry_index} is truncated: need {compact_len} bytes, have {}",
                data.len() - off
            )));
        }

        let parse_len = entry_len.min(data.len() - off);
        entries.push(parse_dir_entry(&data[off..off + parse_len]));
        off = off.checked_add(entry_len).ok_or_else(|| {
            czi_invalid_data(format!(
                "CZI directory entry {entry_index} offset overflows"
            ))
        })?;
    }

    Ok(entries)
}

// ---- file parsing ----------------------------------------------------------

struct CziParsed {
    meta_xml: String,
    entries: Vec<DirEntry>,
    z_count: u32,
    c_count: u32,
    t_count: u32,
    pixel_type: PixelType,
    spp: u32,
    /// One entry per series (extra-dimension combination). Always non-empty.
    series: Vec<CziSeries>,
    /// Distinct CZI pixel-type codes seen across subblocks, in first-seen order.
    /// `len() > 1` triggers the per-pixel-type core split.
    pixel_types: Vec<i32>,
    /// True when mosaic ("M") tiles are stitched into a single image per series.
    prestitched: bool,
    /// Modulo annotations (rotations->Z, illuminations->C, phases->T).
    modulo_z: Option<ModuloAnnotation>,
    modulo_c: Option<ModuloAnnotation>,
    modulo_t: Option<ModuloAnnotation>,
    /// Sub-dimension fold factors used by plane-index/selection math.
    rotations: i32,
    illuminations: i32,
    phases: i32,
    /// True when "R" acts as the rotation axis (folded into Z) rather than the
    /// pyramid-resolution selector.
    rotation_axis: bool,
    /// True when PALM data was detected and split into two series by stored size.
    palm: bool,
}

/// Counts of the CZI "extra" dimensions, computed like
/// ZeissCZIReader.calculateDimensions.
#[derive(Default)]
struct DimCounts {
    positions: i32,     // S
    acquisitions: i32,  // B
    angles: i32,        // V
    mosaics: i32,       // M
    rotations: i32,     // R -> modulo Z
    illuminations: i32, // I -> modulo C
    phases: i32,        // H -> modulo T
    /// True when "R" is a genuine rotation axis (some R.size > 1), as opposed to
    /// this crate's pyramid-resolution repurposing of "R".
    rotation_axis: bool,
    min_scene: i32,
    min_acq: i32,
    min_angle: i32,
    min_mosaic: i32,
}

fn parse_czi_file(f: &mut BufReader<File>) -> std::io::Result<CziParsed> {
    let file_len = f.get_ref().metadata()?.len();

    // --- Read file header segment ---
    let mut hdr = vec![0u8; SEG_HEADER];
    f.read_exact(&mut hdr)?;
    let seg_type = read_seg_type(&hdr);
    if !seg_type.starts_with("ZISRAWFILE") {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Not a CZI file",
        ));
    }

    // FileHeader data starts after the 32-byte segment header.
    // Layout (matching ZeissCZIReader.FileHeader.fillInData):
    //   0  majorVersion (int)
    //   4  minorVersion (int)
    //   8  reserved1 (int)
    //   12 reserved2 (int)
    //   16 primaryFileGUID (long)
    //   24 fileGUID (long)
    //   32 filePart (int)
    //   36 directoryPosition (long)
    //   44 metadataPosition (long)
    let mut fh = vec![0u8; 80];
    f.read_exact(&mut fh)?;
    let dir_position = read_u64(&fh, 36);
    let meta_position = read_u64(&fh, 44);
    let dir_position = if valid_segment_position(dir_position, file_len) {
        dir_position
    } else {
        0
    };
    let meta_position = if valid_segment_position(meta_position, file_len) {
        meta_position
    } else {
        0
    };

    // --- Read metadata segment ---
    let mut meta_xml = String::new();
    if meta_position > 0 {
        f.seek(SeekFrom::Start(meta_position))?;
        let mut seg_hdr = vec![0u8; SEG_HEADER];
        f.read_exact(&mut seg_hdr)?;
        // Metadata segment body: xml_size (i32), attach_size (i32), reserved (248), xml data
        let mut meta_body_hdr = vec![0u8; 256];
        f.read_exact(&mut meta_body_hdr)?;
        let xml_size = read_i32(&meta_body_hdr, 0) as usize;
        if xml_size > 0 {
            let mut xml_bytes = vec![0u8; xml_size];
            f.read_exact(&mut xml_bytes)?;
            meta_xml = String::from_utf8_lossy(&xml_bytes).into_owned();
        }
    }

    // --- Read directory segment ---
    let mut entries: Vec<DirEntry> = Vec::new();
    if dir_position > 0 {
        f.seek(SeekFrom::Start(dir_position))?;
        let mut seg_hdr = vec![0u8; SEG_HEADER];
        f.read_exact(&mut seg_hdr)?;
        let (allocated_size, used_size) = read_seg_sizes(&seg_hdr);
        // Directory body: entry_count (i32), reserved (124), DirectoryEntry[]
        let mut dir_hdr = vec![0u8; 128];
        f.read_exact(&mut dir_hdr)?;
        let entry_count = read_i32(&dir_hdr, 0) as usize;
        let body_size = used_size.max(allocated_size).saturating_sub(128);
        let remaining = file_len.saturating_sub(f.stream_position()?);
        let body_size = body_size.min(remaining);
        if body_size > 0 {
            let mut entry_bytes = vec![0u8; body_size as usize];
            f.read_exact(&mut entry_bytes)?;
            entries = parse_directory_entries(&entry_bytes, entry_count)?;
        }
    }

    // Compute dimensions from entries.
    let parsed = build_dimensions(meta_xml, entries)?;
    Ok(parsed)
}

/// Port of ZeissCZIReader.calculateDimensions + the prestitching / series-split /
/// per-pixel-type core split machinery (the part of `initFile` from
/// calculateDimensions through assignPlaneIndices and the mosaic tile min/max
/// row-col logic).
fn build_dimensions(meta_xml: String, entries: Vec<DirEntry>) -> std::io::Result<CziParsed> {
    if entries.is_empty() {
        return Err(czi_invalid_data("CZI directory contains no subblocks"));
    }
    // --- calculateDimensions: per-dimension extents (ZeissCZIReader:1942-2048) ---
    let mut max_z = 0i32;
    let mut max_c = 0i32;
    // Largest Z.size seen: a single subblock may encode the full Z range via its
    // dimension.size rather than per-Z starts (ZeissCZIReader:1982-1983).
    let mut max_z_size = 0i32;
    // Distinct T index values across all subblocks: Java accumulates a uniqueT set
    // over [start, start+size) and uses its cardinality (ZeissCZIReader:1986-1995).
    let mut unique_t: std::collections::HashSet<i32> = std::collections::HashSet::new();
    let mut first_pixel_type = 0i32;

    // Distinct pixel-type codes in first-seen order (ZeissCZIReader:969-977).
    let mut pixel_types: Vec<i32> = Vec::new();

    let mut c = DimCounts {
        positions: 1,
        acquisitions: 1,
        angles: 1,
        mosaics: 1,
        rotations: 1,
        illuminations: 1,
        phases: 1,
        rotation_axis: false,
        min_scene: 0,
        min_acq: 0,
        min_angle: 0,
        min_mosaic: 0,
    };

    let (mut min_s, mut max_s) = (i32::MAX, i32::MIN);
    let (mut min_b, mut max_b) = (i32::MAX, i32::MIN);
    let (mut min_v, mut max_v) = (i32::MAX, i32::MIN);
    let (mut min_m, mut max_m) = (i32::MAX, i32::MIN);
    let (mut min_r, mut max_r) = (i32::MAX, i32::MIN);
    // Java-style rotation extent (start + size) and the largest R.size seen, used
    // to distinguish genuine rotation files from the pyramid repurposing of "R".
    let (mut min_rot, mut max_rot) = (i32::MAX, i32::MIN);
    let mut max_r_size = 0i32;
    // Max X tile size observed at each R level, used to tell a downscaled pyramid
    // (sizes differ across R) from a rotation axis (sizes equal across R).
    let mut r_level_xsize: HashMap<i32, i32> = HashMap::new();
    let (mut min_i, mut max_i) = (i32::MAX, i32::MIN);
    let (mut min_h, mut max_h) = (i32::MAX, i32::MIN);

    for e in &entries {
        if pixel_types.is_empty() {
            first_pixel_type = e.pixel_type;
        }
        if !pixel_types.contains(&e.pixel_type) {
            pixel_types.push(e.pixel_type);
        }

        // C/Z/T (logical max, ZeissCZIReader case 'C'/'Z'/'T').
        if let Some(&(start, size)) = e.dims.get("Z") {
            // ZeissCZIReader:1978-1984. Prefer the per-Z start extent; otherwise a
            // single subblock may encode the whole Z range via its dimension.size.
            if start > 0 && start > max_z {
                max_z = start;
            } else if size > max_z_size {
                max_z_size = size;
            }
        }
        if let Some(&(start, _)) = e.dims.get("C") {
            if start > max_c {
                max_c = start;
            }
        }
        if let Some(&(start, size)) = e.dims.get("T") {
            // ZeissCZIReader:1986-1995. Count distinct T values over [start,start+size).
            for i in start..start + size.max(1) {
                unique_t.insert(i);
            }
        }
        // Extra/modulo dimensions (ZeissCZIReader case 'S'/'I'/'B'/'M'/'H'/'V').
        //
        // The "R" dimension carries two distinct meanings in CZI files:
        //
        //   * Upstream ZeissCZIReader treats "R" as the *rotation* axis and folds
        //     it into Z via a moduloZ annotation (ZeissCZIReader:1997-1999,
        //     2043-2044, 846-849, 2216-2217). There, `rotations = maxRotation -
        //     minRotation` with `maxRotation = max(start + size)`. Resolution is
        //     instead derived from a scale-factor pyramid (ZeissCZIReader:772-784):
        //     a higher pyramid level stores a *smaller* X/Y tile.
        //
        //   * This crate repurposes the "R" *start* as the discrete pyramid
        //     resolution level (see czi_selects_pyramid_resolution_level), since it
        //     does not implement the scale-factor pyramid detection.
        //
        // Both rotation and the pyramid repurposing typically write R.size == 1 and
        // vary only the start, so size alone cannot disambiguate. We instead apply
        // Java's pyramid signal: distinct R levels are a *pyramid* iff their X tile
        // size differs (downscaling); if every R level shares the same X size, "R"
        // is a genuine rotation axis (no downsampling) and folds into Z. R.size > 1
        // is also treated as an explicit rotation signal.
        if let Some(&(start, size)) = e.dims.get("R") {
            min_r = min_r.min(start);
            max_r = max_r.max(start + 1);
            // Java-style rotation extent: maxRotation = max(start + size).
            min_rot = min_rot.min(start);
            max_rot = max_rot.max(start + size);
            max_r_size = max_r_size.max(size);
            // Track the X tile size seen at each R level to detect downscaling.
            let x_size = e.dim_size("X").max(0);
            let cur = r_level_xsize.entry(start).or_insert(x_size);
            *cur = (*cur).max(x_size);
        }
        if let Some(&(start, _)) = e.dims.get("S") {
            min_s = min_s.min(start);
            max_s = max_s.max(start);
        }
        if let Some(&(start, size)) = e.dims.get("I") {
            min_i = min_i.min(start);
            max_i = max_i.max(start + size);
        }
        if let Some(&(start, _)) = e.dims.get("B") {
            min_b = min_b.min(start);
            max_b = max_b.max(start);
        }
        if let Some(&(start, _)) = e.dims.get("M") {
            min_m = min_m.min(start);
            max_m = max_m.max(start);
        }
        if let Some(&(start, size)) = e.dims.get("H") {
            min_h = min_h.min(start);
            max_h = max_h.max(start + size);
        }
        if let Some(&(start, _)) = e.dims.get("V") {
            min_v = min_v.min(start);
            max_v = max_v.max(start);
        }
    }

    // ZeissCZIReader:2037-2048. positions = maxS - minS + 1; acquisitions/angles/
    // mosaics use start+1 (max start + 1); illuminations/phases use
    // max(start+size) - min(start), i.e. a range count.
    if max_s != i32::MIN {
        c.positions = (max_s - min_s + 1).max(1);
        c.min_scene = min_s;
    }
    if max_b != i32::MIN {
        c.acquisitions = (max_b + 1).max(1);
        c.min_acq = min_b;
    }
    if max_v != i32::MIN {
        c.angles = (max_v + 1).max(1);
        c.min_angle = min_v;
    }
    if max_m != i32::MIN {
        c.mosaics = (max_m + 1).max(1);
        c.min_mosaic = min_m;
    }
    // Rotation -> moduloZ (ZeissCZIReader:2043-2044). Treat "R" as a rotation axis
    // (rather than the crate's pyramid repurposing) when either:
    //   * some subblock explicitly records R.size > 1, or
    //   * there are multiple R levels that all share the same X tile size (i.e.
    //     no downscaling, so they are not a pyramid).
    // When R levels have differing X sizes, "R" is a downscaled pyramid and stays
    // the resolution selector.
    let distinct_r_levels = r_level_xsize.len();
    let all_r_same_xsize = {
        let mut sizes = r_level_xsize.values().copied();
        match sizes.next() {
            Some(first) => sizes.all(|s| s == first),
            None => true,
        }
    };
    let rotation_axis = max_r_size > 1 || (distinct_r_levels > 1 && all_r_same_xsize);
    if rotation_axis && max_rot != i32::MIN && min_rot != i32::MAX {
        c.rotations = (max_rot - min_rot).max(1);
        c.rotation_axis = true;
    }
    let _ = min_r;
    if max_i != i32::MIN && min_i != i32::MAX {
        c.illuminations = (max_i - min_i).max(1);
    }
    if max_h != i32::MIN && min_h != i32::MAX {
        c.phases = (max_h - min_h).max(1);
    }

    // sizeZ: max of the per-Z-start extent (max_z + 1) and any single subblock
    // that spanned the whole Z range via dimension.size (ZeissCZIReader:1978-1984).
    let mut z_count = ((max_z + 1) as u32).max(max_z_size.max(0) as u32);
    let mut c_count = (max_c + 1) as u32;
    // sizeT = |uniqueT| (ZeissCZIReader:1986-1995), falling back to 1 when no
    // subblock declared a T dimension.
    let mut t_count = (unique_t.len() as u32).max(1);

    let (pt, spp) = czi_pixel_type(first_pixel_type)?;

    // --- modulo annotations (ZeissCZIReader:832-860) ---
    // rotations -> modulo Z, illuminations -> modulo C, phases -> modulo T.
    let mut modulo_z = None;
    let mut modulo_c = None;
    let mut modulo_t = None;
    // Rotation/illumination/phase labels parsed from "...|Rotations|" etc. keys in
    // the metadata XML (ZeissCZIReader:3733-3741).
    let rotation_labels = parse_modulo_labels(&meta_xml, "Rotations");
    let illumination_labels = parse_modulo_labels(&meta_xml, "Illuminations");
    let phase_labels = parse_modulo_labels(&meta_xml, "Phases");
    if c.rotations > 1 {
        // ZeissCZIReader:846-849. step = original sizeZ, end = sizeZ*(rotations-1).
        // When rotation labels are present, Java collapses end to start
        // (ZeissCZIReader:1246-1249) since the labels enumerate the axis.
        let mut end = (z_count as i32 * (c.rotations - 1)) as f64;
        if !rotation_labels.is_empty() {
            end = 0.0;
        }
        modulo_z = Some(ModuloAnnotation {
            parent_dimension: "Z".into(),
            modulo_type: "rotation".into(),
            start: 0.0,
            step: z_count as f64,
            end,
            unit: String::new(),
            labels: rotation_labels,
        });
        z_count *= c.rotations as u32;
    }
    if c.illuminations > 1 {
        let mut end = (c_count as i32 * (c.illuminations - 1)) as f64;
        if !illumination_labels.is_empty() {
            end = 0.0;
        }
        modulo_c = Some(ModuloAnnotation {
            parent_dimension: "C".into(),
            modulo_type: "illumination".into(),
            start: 0.0,
            step: c_count as f64,
            end,
            unit: String::new(),
            labels: illumination_labels,
        });
        c_count *= c.illuminations as u32;
    }
    if c.phases > 1 {
        let mut end = (t_count as i32 * (c.phases - 1)) as f64;
        if !phase_labels.is_empty() {
            end = 0.0;
        }
        modulo_t = Some(ModuloAnnotation {
            parent_dimension: "T".into(),
            modulo_type: "phase".into(),
            start: 0.0,
            step: t_count as f64,
            end,
            unit: String::new(),
            labels: phase_labels,
        });
        t_count *= c.phases as u32;
    }

    // --- maxResolution / pyramid scale detection ---
    // The "R" dimension supplies discrete resolution levels in this crate's model,
    // UNLESS it is acting as a rotation axis (R.size > 1). In the rotation case the
    // R start indexes rotation (folded into Z), so there is a single resolution.
    let max_resolution = if !c.rotation_axis && max_r != i32::MIN {
        (max_r - 1).max(0)
    } else {
        0
    };

    // --- seriesCount and prestitching (ZeissCZIReader:864-1003) ---
    // seriesCount = positions * acquisitions * angles, *= mosaics only when there
    // is no pyramid (maxResolution == 0); otherwise prestitched = true.
    let mut prestitched = false;
    let mosaics_as_series = if max_resolution == 0 {
        c.mosaics > 1 && c.mosaics_exposed_as_series()
    } else {
        prestitched = true;
        false
    };
    if c.mosaics > 1 && !mosaics_as_series {
        // Mosaic tiles are stitched into a single image per series.
        prestitched = true;
    }

    // --- mosaic image-fusion series rebalancing (ZeissCZIReader:941-1003) ---
    //
    // Faithful port of Java's plane-count-driven `seriesCount` collapse. When the
    // calculated plane budget (`imageCount * seriesCount`) exceeds what the file
    // actually stores (`planes.size() * scanDim`), the mosaics were fused at
    // acquisition time and Java collapses or re-balances the series count. This
    // is independent of the scale-factor pyramid model: it depends only on the
    // integer relationships between imageCount / seriesCount / plane count /
    // sizeZ / sizeT / positions / mosaics, all of which this crate already has.
    //
    // Scope: ported for the non-pyramid case (`max_resolution == 0`). When a
    // pyramid is present Java's `planes.size()` excludes reduced-resolution
    // subblocks (which this crate keeps as "R" buckets in `entries`) and `scanDim`
    // is derived from the size/planeSize ratio (not computed here), so the
    // precondition cannot be reproduced faithfully; in that case Java already
    // forces `prestitched = true` and the relevant collapse branches at 999-1003
    // only fire when `max_resolution == 0` regardless.
    //
    // `scanDim` is the line-scan-cytometry stored/plane size ratio
    // (ZeissCZIReader:804/817). This crate does not detect line-scan cytometry, so
    // every full-resolution plane has ratio 1, i.e. scanDim == 1.
    //
    // `seriesCount` here is the extra-dimension product *before* the per-pixel-
    // type split (Java applies the per-pixel-type multiplication afterwards at
    // 979-993). `image_count_full` is Java's `getImageCount()` (sizeZ * logical
    // sizeC * sizeT) computed before the per-pixel-type sizeC division.
    let image_count_full = z_count * c_count * t_count;
    let scan_dim: u32 = 1;
    // Number of valid full-resolution planes. With no pyramid, every directory
    // entry is a full-resolution plane (Java's `planes.size()` / `fullResBlockCount`
    // after removing reduced-resolution subblocks).
    let plane_count = entries.len() as u32;
    let mut series_count = (c.positions * c.acquisitions * c.angles).max(1);
    if max_resolution == 0 {
        series_count *= c.mosaics.max(1);
    }
    // When the collapse fires (952-960) we drop all extra-dimension splitting and
    // expose a single series matching every subblock. When only positions are
    // collapsed (947-950 / 999-1003), the surviving series no longer split by S,
    // so the scene selector must match every position.
    let mut collapse_all = false;
    let mut position_collapsed = false;
    if max_resolution == 0 && plane_count > 0 {
        let lhs = image_count_full as u64 * series_count as u64;
        let rhs = plane_count as u64 * scan_dim as u64;
        if lhs > rhs {
            let sz = z_count.max(1);
            if plane_count != image_count_full
                && plane_count != t_count
                && (plane_count % (series_count as u32 * sz)) == 0
            {
                // ZeissCZIReader:947-950 (guarded by !isGroupFiles(); this crate
                // never groups files, so the guard is always satisfied).
                if c.positions > 1
                    && plane_count == (image_count_full * series_count as u32) / c.positions as u32
                {
                    series_count /= c.positions;
                    c.positions = 1;
                    position_collapsed = true;
                }
            } else if plane_count == t_count || plane_count == image_count_full || c.positions > 1 {
                // ZeissCZIReader:952-960: image was fully fused; collapse to one
                // series. (!isGroupFiles() is always true here.)
                c.positions = 1;
                c.acquisitions = 1;
                c.mosaics = 1;
                c.angles = 1;
                series_count = 1;
                collapse_all = true;
            } else if series_count > c.mosaics && c.mosaics > 1 && prestitched {
                // ZeissCZIReader:961-964.
                series_count /= c.mosaics;
                c.mosaics = 1;
            }
        }
    }

    // ZeissCZIReader:999-1003: a prestitched image whose series count equals
    // mosaics * positions is a big single image expecting (absent) pyramids;
    // expose one series per position.
    if prestitched
        && max_resolution == 0
        && series_count == (c.mosaics.max(1) * c.positions.max(1))
        && series_count != c.positions
    {
        series_count = c.positions.max(1);
        c.mosaics = 1;
    }
    let _ = series_count;

    // --- per-pixel-type core split (ZeissCZIReader:969-995) ---
    // Each distinct pixel type yields its own core/series with sizeC divided.
    let original_c = c_count;
    let pixel_type_count = pixel_types.len().max(1);
    if pixel_type_count > 1 {
        c_count = (original_c / pixel_type_count as u32).max(1);
    }

    // --- build the extra-dimension series list (assignPlaneIndices) ---
    // Series = positions * acquisitions * angles * (mosaics if exposed) *
    // pixel_type_count. Each series selects its subblocks via the extra-dim
    // selectors; resolutions come from the "R" buckets within that selection.
    let mosaic_factor = if mosaics_as_series { c.mosaics } else { 1 };

    let mut series: Vec<CziSeries> = Vec::new();
    for ptype in 0..pixel_type_count {
        for s_idx in 0..c.positions {
            for b_idx in 0..c.acquisitions {
                for v_idx in 0..c.angles {
                    for m_idx in 0..mosaic_factor {
                        // When the fusion rebalancing collapsed everything into a
                        // single series (ZeissCZIReader:952-960), the series must
                        // match every subblock regardless of S/B/V/M, so leave all
                        // extra-dimension selectors unset.
                        let scene = if !collapse_all && !position_collapsed && max_s != i32::MIN {
                            Some(c.min_scene + s_idx)
                        } else {
                            None
                        };
                        let acquisition = if !collapse_all && max_b != i32::MIN {
                            Some(c.min_acq + b_idx)
                        } else {
                            None
                        };
                        let angle = if !collapse_all && max_v != i32::MIN {
                            Some(c.min_angle + v_idx)
                        } else {
                            None
                        };
                        let mosaic = if mosaics_as_series {
                            Some(c.min_mosaic + m_idx)
                        } else {
                            None
                        };
                        let resolutions = compute_resolutions(
                            &entries,
                            scene,
                            acquisition,
                            angle,
                            mosaic,
                            prestitched,
                            c.rotation_axis,
                        );
                        series.push(CziSeries {
                            scene,
                            acquisition,
                            angle,
                            mosaic,
                            pixel_type_index: ptype,
                            palm_size: None,
                            resolutions,
                        });
                    }
                }
            }
        }
    }
    if series.is_empty() {
        series.push(CziSeries {
            scene: None,
            acquisition: None,
            angle: None,
            mosaic: None,
            pixel_type_index: 0,
            palm_size: None,
            resolutions: vec![CziResolution {
                r: 0,
                width: 0,
                height: 0,
            }],
        });
    }

    // --- PALM detection and per-size series split (ZeissCZIReader:1123-1193) ---
    // PALM requires <= 2 planes and an image count of <= 2; if the XML marks the
    // file as PALM, the two planes are split into two series (one channel each)
    // when they have *different* stored sizes (a same-size pair is reverted to a
    // single 2-channel series, ZeissCZIReader:1174-1192).
    let image_count = z_count * c_count * t_count;
    let mut palm = false;
    if entries.len() <= 2 && image_count <= 2 && check_palm(&meta_xml) {
        // Distinct stored-size buckets among the (<= 2) subblocks.
        let mut sizes: Vec<(u32, u32)> = Vec::new();
        for e in &entries {
            let sx = e.dim_stored_size("X").max(0) as u32;
            let sy = e.dim_stored_size("Y").max(0) as u32;
            if !sizes.contains(&(sx, sy)) {
                sizes.push((sx, sy));
            }
        }
        if sizes.len() == 2 {
            // Genuine PALM: split into two single-channel series, each sized to its
            // own stored tile (ZeissCZIReader:1150-1173).
            palm = true;
            c_count = 1;
            series.clear();
            for &(sx, sy) in &sizes {
                series.push(CziSeries {
                    scene: None,
                    acquisition: None,
                    angle: None,
                    mosaic: None,
                    pixel_type_index: 0,
                    palm_size: Some((sx, sy)),
                    resolutions: vec![CziResolution {
                        r: 0,
                        width: sx,
                        height: sy,
                    }],
                });
            }
        }
        // Same-size pair => not PALM; leave the existing 2-channel series untouched.
    }

    Ok(CziParsed {
        meta_xml,
        entries,
        z_count: z_count.max(1),
        c_count: c_count.max(1),
        t_count: t_count.max(1),
        pixel_type: pt,
        spp,
        series,
        pixel_types: if pixel_types.is_empty() {
            vec![first_pixel_type]
        } else {
            pixel_types
        },
        prestitched,
        modulo_z,
        modulo_c,
        modulo_t,
        rotations: c.rotations,
        illuminations: c.illuminations,
        phases: c.phases,
        rotation_axis: c.rotation_axis,
        palm,
    })
}

/// Port of ZeissCZIReader.checkPALM (ZeissCZIReader:2277-2335): the file is PALM
/// when the metadata XML carries a `CustomAttributes/LsmTag` whose `Name`
/// attribute starts with "palm", or an
/// Experiment/ExperimentBlocks/AcquisitionBlock/MultiTrackSetup/TrackSetup/
/// PalmSlider element whose text content is "true".
///
/// The crate keeps the metadata as a raw XML string (no DOM), so this performs a
/// string/regex-free scan equivalent to the Java DOM walk.
fn check_palm(xml: &str) -> bool {
    if xml.is_empty() {
        return false;
    }
    // LsmTag Name starting with "palm" (case-insensitive). Scan each <LsmTag ...>
    // opening tag for a Name="..." attribute.
    let lower = xml.to_ascii_lowercase();
    let mut search_from = 0usize;
    while let Some(rel) = lower[search_from..].find("<lsmtag") {
        let tag_start = search_from + rel;
        let tag_end = lower[tag_start..]
            .find('>')
            .map(|e| tag_start + e)
            .unwrap_or(lower.len());
        let tag = &lower[tag_start..tag_end];
        if let Some(npos) = tag.find("name=") {
            let rest = &tag[npos + 5..];
            let trimmed = rest.trim_start_matches(['"', '\'']);
            if trimmed.starts_with("palm") {
                return true;
            }
        }
        search_from = tag_end.max(tag_start + 1);
    }

    // PalmSlider element with text content "true". The PalmSlider tag only appears
    // under the MultiTrack/TrackSetup path in PALM acquisitions, so a positive
    // text match is sufficient here.
    if let Some(pos) = lower.find("<palmslider>") {
        let value_start = pos + "<palmslider>".len();
        if let Some(rel_end) = lower[value_start..].find("</palmslider>") {
            let value = lower[value_start..value_start + rel_end].trim();
            if value == "true" {
                return true;
            }
        }
    }
    false
}

/// Parse a space-separated modulo label list from the metadata XML for a key
/// ending in `|<name>|` (ZeissCZIReader:3733-3741, e.g. "...|Rotations|").
/// The crate keeps metadata as a raw XML/key-value string, so we scan for the
/// `<Key>...|Name|</Key><Value>label0 label1 ...</Value>` pairing heuristically.
fn parse_modulo_labels(xml: &str, name: &str) -> Vec<String> {
    if xml.is_empty() {
        return Vec::new();
    }
    // Match an element whose tag name ends with the modulo name, e.g.
    // <Rotations>a b c</Rotations>, which is how CZI metadata stores these axes.
    let open_needle = format!("<{}>", name);
    let close_needle = format!("</{}>", name);
    if let Some(start) = xml.find(&open_needle) {
        let value_start = start + open_needle.len();
        if let Some(rel_end) = xml[value_start..].find(&close_needle) {
            let value = &xml[value_start..value_start + rel_end];
            let labels: Vec<String> = value.split_whitespace().map(|s| s.to_string()).collect();
            if labels.len() > 1 {
                return labels;
            }
        }
    }
    Vec::new()
}

impl DimCounts {
    /// Whether mosaics should be exposed as separate series rather than stitched.
    /// Mirrors the assignPlaneIndices guard that only adds 'M' to the extra-dim
    /// order when `mosaics <= seriesCount && (!prestitched || !autostitching)`.
    /// This crate always allows autostitching, so mosaics are stitched whenever
    /// there is more than one tile; they are exposed as series only when there is
    /// genuinely no overlap to stitch (single mosaic). In practice this means
    /// mosaics are always prestitched here.
    fn mosaics_exposed_as_series(&self) -> bool {
        false
    }
}

/// Build the sorted resolution list for one series selection. Each "R" level
/// becomes a resolution; the X/Y extent is the stitched bounding box of all
/// subblocks matching the selection at that level (mosaic prestitching).
fn compute_resolutions(
    entries: &[DirEntry],
    scene: Option<i32>,
    acquisition: Option<i32>,
    angle: Option<i32>,
    mosaic: Option<i32>,
    _prestitched: bool,
    rotation_axis: bool,
) -> Vec<CziResolution> {
    // R-level -> (min_col, min_row, max_x_end, max_y_end)
    //
    // The stitched extent is the bounding box of all subblocks in the selection;
    // this collapses to a single tile's size when there is only one tile, and to
    // the full mosaic span when there are several (ZeissCZIReader prestitching /
    // the calculateDimensions(s, true) min/max row-col logic at 1034-1076).
    let mut buckets: HashMap<i32, (i64, i64, i64, i64)> = HashMap::new();
    for e in entries {
        if !entry_in_series(e, scene, acquisition, angle, mosaic) {
            continue;
        }
        // When "R" is a rotation axis, its start indexes rotation (not resolution),
        // so collapse every subblock into the single resolution bucket (R = 0).
        let r = if rotation_axis { 0 } else { e.dim_start("R") };
        let col = e.dim_start("X").max(0) as i64;
        let row = e.dim_start("Y").max(0) as i64;
        let x_size = e.dim_size("X").max(0) as i64;
        let y_size = e.dim_size("Y").max(0) as i64;
        let entry = buckets
            .entry(r)
            .or_insert((i64::MAX, i64::MAX, i64::MIN, i64::MIN));
        entry.0 = entry.0.min(col);
        entry.1 = entry.1.min(row);
        entry.2 = entry.2.max(col + x_size);
        entry.3 = entry.3.max(row + y_size);
    }

    let mut resolutions: Vec<CziResolution> = buckets
        .into_iter()
        .map(|(r, (min_c, min_r, max_x, max_y))| CziResolution {
            r,
            width: (max_x - min_c).max(0) as u32,
            height: (max_y - min_r).max(0) as u32,
        })
        .collect();
    resolutions.sort_by_key(|res| res.r);
    if resolutions.is_empty() {
        resolutions.push(CziResolution {
            r: 0,
            width: 0,
            height: 0,
        });
    }
    resolutions
}

/// Whether a directory entry belongs to the given series selection.
fn entry_in_series(
    e: &DirEntry,
    scene: Option<i32>,
    acquisition: Option<i32>,
    angle: Option<i32>,
    mosaic: Option<i32>,
) -> bool {
    let ok = |sel: Option<i32>, name: &str| -> bool {
        match sel {
            // Selector active: entry must match (or lack the dimension entirely,
            // matching the "single position" fallback in calculateDimensions).
            Some(v) => !e.has_dim(name) || e.dim_start(name) == v,
            None => true,
        }
    };
    ok(scene, "S") && ok(acquisition, "B") && ok(angle, "V") && ok(mosaic, "M")
}

// ---- decompression ---------------------------------------------------------

fn decompress_subblock(
    data: &[u8],
    compression: i32,
    tile_width: usize,
    tile_height: usize,
    max_bytes: usize,
) -> Result<Vec<u8>> {
    match compression {
        0 => Ok(data.to_vec()), // Uncompressed
        1 => {
            // JPEG
            let mut dec = jpeg_decoder::Decoder::new(data);
            dec.decode()
                .map_err(|e| BioFormatsError::Codec(e.to_string()))
        }
        2 => {
            // LZW
            use weezl::{decode::Decoder, BitOrder};
            let mut dec = Decoder::with_tiff_size_switch(BitOrder::Msb, 8);
            dec.decode(data)
                .map_err(|e| BioFormatsError::Codec(e.to_string()))
        }
        4 => {
            // JPEG-XR
            crate::common::codec::decompress_jpegxr(data)
        }
        5 => {
            // Zstd
            crate::common::codec::zstd_decode_all(data)
        }
        6 => decompress_zstd_1(data),
        104 => {
            // Camera-specific 12-bit packed pixels, with column reversal.
            // (matches ZeissCZIReader case 104)
            let mut decoded = decode_12bit_camera(data, max_bytes)?;
            reverse_columns_16bit(&mut decoded, tile_width, tile_height);
            Ok(decoded)
        }
        504 => {
            // Camera-specific 12-bit packed pixels without column reversal.
            decode_12bit_camera(data, max_bytes)
        }
        _ => Err(BioFormatsError::UnsupportedFormat(format!(
            "CZI: unknown compression {}",
            compression
        ))),
    }
}

/// Decode 12-bit camera-packed pixel data into 16-bit samples.
///
/// Port of ZeissCZIReader.decode12BitCamera: unpacks the input into 4-bit
/// nibbles (3 nibbles per 2 output bytes), performs an in-place nibble reorder,
/// then reassembles 16-bit values.
fn decode_12bit_camera(data: &[u8], max_bytes: usize) -> Result<Vec<u8>> {
    let mut decoded = vec![0u8; max_bytes];

    let four_bits_len = (max_bytes / 2) * 3;
    let required_bytes = four_bits_len.div_ceil(2);
    if data.len() < required_bytes {
        return Err(BioFormatsError::InvalidData(format!(
            "CZI 12-bit camera payload is too short: got {}, expected at least {required_bytes}",
            data.len()
        )));
    }
    let mut four_bits = vec![0u8; four_bits_len];

    // Read 4-bit groups MSB-first from the packed input.
    let mut bit_pos = 0usize;
    for nibble in four_bits.iter_mut() {
        let byte_index = bit_pos / 8;
        let in_byte_shift = 4 - (bit_pos % 8);
        *nibble = (data[byte_index] >> in_byte_shift) & 0x0f;
        bit_pos += 4;
    }

    // In-place nibble reordering (matches the Java reference loop).
    if four_bits_len > 1 {
        for index in 1..four_bits_len - 1 {
            if (index as isize - 3) % 6 == 0 {
                let middle = four_bits[index];
                let last = four_bits[index + 1];
                let first = four_bits[index - 1];
                four_bits[index + 1] = middle;
                four_bits[index] = first;
                four_bits[index - 1] = last;
            }
        }
    }

    // Reassemble 16-bit values from the nibble stream.
    let mut current_byte = 0usize;
    let mut index = 0usize;
    while index < four_bits_len && current_byte < decoded.len() {
        if index % 3 == 0 {
            decoded[current_byte] = four_bits[index];
            current_byte += 1;
            index += 1;
        } else {
            let hi = four_bits[index];
            index += 1;
            let lo = if index < four_bits_len {
                four_bits[index]
            } else {
                0
            };
            index += 1;
            decoded[current_byte] = (hi << 4) | lo;
            current_byte += 1;
        }
    }

    Ok(decoded)
}

/// Reverse the column order of 16-bit pixels, row by row.
/// Port of the column-reversal loop in ZeissCZIReader case 104.
fn reverse_columns_16bit(data: &mut [u8], width: usize, height: usize) {
    if width == 0 {
        return;
    }
    for row in 0..height {
        for col in 0..width / 2 {
            let left = row * width * 2 + col * 2;
            let right = row * width * 2 + (width - col - 1) * 2;
            if right + 1 >= data.len() {
                continue;
            }
            data.swap(left, right);
            data.swap(left + 1, right + 1);
        }
    }
}

fn read_czi_varint(data: &[u8], offset: &mut usize) -> Result<usize> {
    if *offset >= data.len() {
        return Err(BioFormatsError::InvalidData(
            "CZI ZSTD_1 truncated varint".into(),
        ));
    }
    let a = data[*offset];
    *offset += 1;
    if a & 0x80 == 0 {
        return Ok(a as usize);
    }

    if *offset >= data.len() {
        return Err(BioFormatsError::InvalidData(
            "CZI ZSTD_1 truncated varint".into(),
        ));
    }
    let b = data[*offset];
    *offset += 1;
    if b & 0x80 == 0 {
        return Ok(((b as usize) << 7) | ((a & 0x7f) as usize));
    }

    if *offset >= data.len() {
        return Err(BioFormatsError::InvalidData(
            "CZI ZSTD_1 truncated varint".into(),
        ));
    }
    let c = data[*offset];
    *offset += 1;
    Ok(((c as usize) << 14) | (((b & 0x7f) as usize) << 7) | ((a & 0x7f) as usize))
}

fn decompress_zstd_1(data: &[u8]) -> Result<Vec<u8>> {
    let mut offset = 0usize;
    let header_end = read_czi_varint(data, &mut offset)?;
    if header_end > data.len() || header_end < offset {
        return Err(BioFormatsError::InvalidData(
            "CZI ZSTD_1 invalid header size".into(),
        ));
    }

    let mut high_low_unpacking = false;
    while offset < header_end {
        let chunk_id = read_czi_varint(data, &mut offset)?;
        match chunk_id {
            1 => {
                if offset >= header_end {
                    return Err(BioFormatsError::InvalidData(
                        "CZI ZSTD_1 missing chunk payload".into(),
                    ));
                }
                high_low_unpacking = (data[offset] & 1) == 1;
                offset += 1;
            }
            _ => {
                return Err(BioFormatsError::InvalidData(format!(
                    "CZI ZSTD_1 invalid chunk ID {chunk_id}"
                )));
            }
        }
    }

    let decoded = crate::common::codec::zstd_decode_all(&data[header_end..])?;
    if !high_low_unpacking {
        return Ok(decoded);
    }
    if decoded.len() % 2 != 0 {
        return Err(BioFormatsError::InvalidData(
            "CZI ZSTD_1 high/low decoded byte count is odd".into(),
        ));
    }

    let second_half = decoded.len() / 2;
    let mut out = vec![0; decoded.len()];
    for i in 0..decoded.len() {
        let half_offset = i / 2;
        out[i] = if i % 2 == 0 {
            decoded[half_offset]
        } else {
            decoded[second_half + half_offset]
        };
    }
    Ok(out)
}

// ---- reader ----------------------------------------------------------------

pub struct CziReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    entries: Vec<DirEntry>,
    meta_xml: String,
    packed_spp: u32,
    /// One series per extra-dimension combination (scene/acquisition/angle/
    /// mosaic/pixel-type). Each carries its own resolution list and selectors.
    series: Vec<CziSeries>,
    /// Distinct CZI pixel-type codes (per-pixel-type core split).
    pixel_types: Vec<i32>,
    /// Mosaic ("M") tiles are stitched into a single image per series.
    prestitched: bool,
    /// Sub-dimension fold factors (rotations->Z, illuminations->C, phases->T).
    rotations: u32,
    illuminations: u32,
    phases: u32,
    /// True when "R" is the rotation axis folded into Z (vs. pyramid resolution).
    rotation_axis: bool,
    current_series: usize,
    current_resolution: usize,
}

impl CziReader {
    pub fn new() -> Self {
        CziReader {
            path: None,
            meta: None,
            entries: Vec::new(),
            meta_xml: String::new(),
            packed_spp: 1,
            series: Vec::new(),
            pixel_types: Vec::new(),
            prestitched: false,
            rotations: 1,
            illuminations: 1,
            phases: 1,
            rotation_axis: false,
            current_series: 0,
            current_resolution: 0,
        }
    }

    fn plane_zct(&self, plane_index: u32) -> Option<(u32, u32, u32)> {
        let meta = self.meta.as_ref()?;
        let sz = meta.size_z;
        let sc = meta.size_c;
        let z = (plane_index / sc) % sz;
        let c = plane_index % sc;
        let t = plane_index / (sc * sz);
        Some((z, c, t))
    }

    /// Resolution list for the active series.
    fn current_resolutions(&self) -> &[CziResolution] {
        self.series
            .get(self.current_series)
            .map(|s| s.resolutions.as_slice())
            .unwrap_or(&[])
    }

    fn matching_entries(&self, plane_index: u32) -> Option<Vec<DirEntry>> {
        let (z, c, t) = self.plane_zct(plane_index)?;
        let series = self.series.get(self.current_series)?;
        let r = self.current_resolutions().get(self.current_resolution)?.r;

        // Invert the modulo folding (ZeissCZIReader:2216-2223). The requested
        // expanded z/c/t decompose into the per-subblock coordinate plus the
        // rotation/illumination/phase sub-index. origZ = sizeZ / rotations etc.
        let meta = self.meta.as_ref()?;
        let orig_z = (meta.size_z / self.rotations.max(1)).max(1);
        let orig_c = (meta.size_c / self.illuminations.max(1)).max(1);
        let orig_t = (meta.size_t / self.phases.max(1)).max(1);
        let rotation = z / orig_z; // R.start when rotation_axis
        let z = z % orig_z;
        let illum = c / orig_c; // I.start
        let c = c % orig_c;
        let phase = t / orig_t; // H.start
        let t = t % orig_t;

        // Per-pixel-type core split: the logical channel of an entry is its "C"
        // start minus the pixel-type index (ZeissCZIReader:2152), so entries with
        // the active pixel type carry channels [ptype*sizeC .. ). We select by the
        // entry's pixel-type rank within the distinct list.
        let want_pt = self.pixel_types.get(series.pixel_type_index).copied();
        let multi_pt = self.pixel_types.len() > 1;
        // Logical-channel offset for the per-pixel-type split (ZeissCZIReader:2152
        // `c = dimension.start - plane.pixelTypeIndex`): the requested channel `c`
        // corresponds to entry C-start `c + pixelTypeIndex`.
        let c_with_offset = c + if multi_pt {
            series.pixel_type_index as u32
        } else {
            0
        };

        // "R" selects rotation (rotation_axis) or pyramid resolution otherwise.
        let want_r = if self.rotation_axis {
            rotation as i32
        } else {
            r
        };
        let match_r = |e: &DirEntry| -> bool {
            if !e.has_dim("R") {
                // Subblocks without an explicit R default to level/rotation 0.
                want_r == 0
            } else {
                e.dim_start("R") == want_r
            }
        };
        // Illumination ("I") and phase ("H") sub-index selectors. Subblocks lacking
        // the dimension default to sub-index 0.
        let match_sub = |e: &DirEntry, name: &str, want: u32| -> bool {
            if !e.has_dim(name) {
                want == 0
            } else {
                e.dim_start(name) as u32 == want
            }
        };

        let entries: Vec<DirEntry> = self
            .entries
            .iter()
            .filter(|e| {
                entry_in_series(e, series.scene, series.acquisition, series.angle, series.mosaic)
                    && match_r(e)
                    && (self.illuminations <= 1 || match_sub(e, "I", illum))
                    && (self.phases <= 1 || match_sub(e, "H", phase))
                    && e.matches_plane(z, c_with_offset, t)
                    && (!multi_pt || want_pt == Some(e.pixel_type))
                    // PALM: a series exposes only the subblock matching its stored
                    // tile size (ZeissCZIReader:1155-1172).
                    && series.palm_size.map_or(true, |(sx, sy)| {
                        e.dim_stored_size("X").max(0) as u32 == sx
                            && e.dim_stored_size("Y").max(0) as u32 == sy
                    })
            })
            .cloned()
            .collect();
        (!entries.is_empty()).then_some(entries)
    }

    /// Apply the active series/resolution's X/Y size to the cached metadata.
    fn refresh_meta_dimensions(&mut self) {
        let (width, height, res_count) = {
            let resolutions = self.current_resolutions();
            let res_count = resolutions.len().max(1) as u32;
            let res = resolutions.get(self.current_resolution);
            (
                res.map(|r| r.width).unwrap_or(0),
                res.map(|r| r.height).unwrap_or(0),
                res_count,
            )
        };
        if let Some(meta) = self.meta.as_mut() {
            meta.size_x = width;
            meta.size_y = height;
            meta.resolution_count = res_count;
        }
    }

    fn read_subblock(path: &Path, entry: &DirEntry, pixel_bytes: usize) -> Result<Vec<u8>> {
        let mut f = File::open(path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(entry.file_position as u64))
            .map_err(BioFormatsError::Io)?;
        let mut seg_hdr = vec![0u8; SEG_HEADER];
        f.read_exact(&mut seg_hdr).map_err(BioFormatsError::Io)?;

        // SubBlock body (matching ZeissCZIReader.SubBlock.fillInData:4175-4183):
        //   body_start (fp) = file_position + HEADER_SIZE
        //   metadataSize (int), attachmentSize (int), dataSize (long) -> 16 bytes
        //   DirectoryEntry, then skip max(256 - (filePointer - fp), 0) so the
        //   fixed part of the body is *at least* 256 bytes (measured from fp),
        //   then metadata of metadataSize bytes. Pixel data therefore starts at
        //   fp + max(256, 16 + dirEntryLen) + metadataSize.
        let mut sb_hdr = vec![0u8; 16];
        f.read_exact(&mut sb_hdr).map_err(BioFormatsError::Io)?;
        let metadata_size = read_i32(&sb_hdr, 0) as u64;
        let data_size = read_u64(&sb_hdr, 8);

        // Read the subblock's own DirectoryEntry header far enough to learn its
        // dimensionCount, then compute its on-disk length. The DirectoryEntry is
        // a 32-byte fixed header (dimensionCount at offset 28) followed by 20
        // bytes per DimensionEntry (ZeissCZIReader.DirectoryEntry:4604-4630).
        let mut de_hdr = vec![0u8; 32];
        f.read_exact(&mut de_hdr).map_err(BioFormatsError::Io)?;
        let dim_count = read_i32(&de_hdr, 28).max(0) as i64;
        let dir_entry_len = 32 + 20 * dim_count;

        // Java skips max(256 - (filePointer - fp), 0) once positioned just after
        // the full DirectoryEntry, where (filePointer - fp) == 16 + dir_entry_len.
        // We have so far consumed only 16 + 32 bytes (size header + DirectoryEntry
        // fixed header), so to reach Java's post-DirectoryEntry position we must
        // first skip the remaining DimensionEntry array (20*dim_count bytes), then
        // apply Java's padding skip of max(256 - 16 - dir_entry_len, 0), then the
        // metadata. When dim_count is large (dir_entry_len > 240) the padding skip
        // is 0, so pixel data starts immediately after metadata (no fixed 256).
        let skip = 20 * dim_count + (256 - 16 - dir_entry_len).max(0) + metadata_size as i64;
        f.seek(SeekFrom::Current(skip)).map_err(BioFormatsError::Io)?;

        let mut compressed = vec![0u8; data_size as usize];
        f.read_exact(&mut compressed).map_err(BioFormatsError::Io)?;

        // For compressed/downsampled tiles Java uses the stored (physical) X/Y
        // sizes to size the decoded buffer.
        let tile_w = entry.dim_stored_size("X").max(0) as usize;
        let tile_h = entry.dim_stored_size("Y").max(0) as usize;
        let max_bytes = tile_w * tile_h * pixel_bytes;
        decompress_subblock(&compressed, entry.compression, tile_w, tile_h, max_bytes)
    }

    #[allow(clippy::too_many_arguments)]
    fn assemble_entry(
        out: &mut [u8],
        out_width: u32,
        out_height: u32,
        tile: &[u8],
        entry: &DirEntry,
        pixel_bytes: usize,
        off_x: i32,
        off_y: i32,
    ) -> Result<()> {
        let tile_x = (entry.dim_start("X").max(0) - off_x).max(0) as u32;
        let tile_y = (entry.dim_start("Y").max(0) - off_y).max(0) as u32;
        let tile_w = entry.dim_stored_size("X").max(0) as u32;
        let tile_h = entry.dim_stored_size("Y").max(0) as u32;
        if tile_w > 0 && tile_x >= out_width {
            return Err(BioFormatsError::Format(format!(
                "CZI tile X bounds exceed output plane: x={tile_x}, width={tile_w}, output width={out_width}"
            )));
        }
        if tile_h > 0 && tile_y >= out_height {
            return Err(BioFormatsError::Format(format!(
                "CZI tile Y bounds exceed output plane: y={tile_y}, height={tile_h}, output height={out_height}"
            )));
        }
        let copy_w = tile_w.min(out_width.saturating_sub(tile_x));
        let copy_h = tile_h.min(out_height.saturating_sub(tile_y));
        let src_row_bytes = (tile_w as usize).checked_mul(pixel_bytes).ok_or_else(|| {
            BioFormatsError::Format("CZI tile source row byte count overflows".into())
        })?;
        let dst_row_bytes = (out_width as usize)
            .checked_mul(pixel_bytes)
            .ok_or_else(|| {
                BioFormatsError::Format("CZI tile destination row byte count overflows".into())
            })?;
        let copy_bytes = (copy_w as usize)
            .checked_mul(pixel_bytes)
            .ok_or_else(|| BioFormatsError::Format("CZI tile copy byte count overflows".into()))?;

        for row in 0..copy_h as usize {
            let src_off = row * src_row_bytes;
            let dst_off = ((tile_y as usize + row) * dst_row_bytes) + tile_x as usize * pixel_bytes;
            if src_off + copy_bytes > tile.len() {
                return Err(BioFormatsError::Format(format!(
                    "CZI tile row {row} exceeds decoded tile buffer: need {} bytes, have {}",
                    src_off + copy_bytes,
                    tile.len()
                )));
            }
            if dst_off + copy_bytes > out.len() {
                return Err(BioFormatsError::Format(format!(
                    "CZI tile row {row} exceeds output plane buffer: need {} bytes, have {}",
                    dst_off + copy_bytes,
                    out.len()
                )));
            }
            out[dst_off..dst_off + copy_bytes]
                .copy_from_slice(&tile[src_off..src_off + copy_bytes]);
        }
        Ok(())
    }
}

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

impl FormatReader for CziReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        path.extension()
            .and_then(|e| e.to_str())
            .map(|e| e.eq_ignore_ascii_case("czi"))
            .unwrap_or(false)
    }

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

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        let f = File::open(path).map_err(BioFormatsError::Io)?;
        let mut reader = BufReader::new(f);
        let parsed = parse_czi_file(&mut reader).map_err(BioFormatsError::Io)?;

        let image_count = parsed.z_count * parsed.c_count * parsed.t_count;
        let bps = (parsed.pixel_type.bytes_per_sample() * 8) as u8;
        let is_rgb = parsed.spp >= 3;

        let mut series_metadata: HashMap<String, MetadataValue> = HashMap::new();
        series_metadata.insert(
            "czi_subblocks".into(),
            MetadataValue::Int(parsed.entries.len() as i64),
        );
        if parsed.palm {
            series_metadata.insert("czi_palm".into(), MetadataValue::Bool(true));
        }

        let first = parsed.series.first();
        let (init_w, init_h, init_res_count) = first
            .and_then(|s| {
                s.resolutions
                    .first()
                    .map(|r| (r.width, r.height, s.resolutions.len()))
            })
            .unwrap_or((0, 0, 1));

        self.meta = Some(ImageMetadata {
            size_x: init_w,
            size_y: init_h,
            size_z: parsed.z_count,
            size_c: parsed.c_count,
            size_t: parsed.t_count,
            pixel_type: parsed.pixel_type,
            bits_per_pixel: bps,
            image_count,
            dimension_order: DimensionOrder::XYCZT,
            is_rgb,
            is_interleaved: true,
            is_indexed: false,
            is_little_endian: true,
            resolution_count: init_res_count as u32,
            series_metadata,
            lookup_table: None,
            modulo_z: parsed.modulo_z,
            modulo_c: parsed.modulo_c,
            modulo_t: parsed.modulo_t,
        });
        self.packed_spp = parsed.spp.max(1);
        self.entries = parsed.entries;
        self.series = parsed.series;
        self.pixel_types = parsed.pixel_types;
        self.prestitched = parsed.prestitched;
        self.rotations = parsed.rotations.max(1) as u32;
        self.illuminations = parsed.illuminations.max(1) as u32;
        self.phases = parsed.phases.max(1) as u32;
        self.rotation_axis = parsed.rotation_axis;
        self.current_series = 0;
        self.current_resolution = 0;
        self.meta_xml = parsed.meta_xml;
        self.path = Some(path.to_path_buf());
        Ok(())
    }

    fn close(&mut self) -> Result<()> {
        self.path = None;
        self.meta = None;
        self.entries.clear();
        self.meta_xml.clear();
        self.packed_spp = 1;
        self.series.clear();
        self.pixel_types.clear();
        self.prestitched = false;
        self.rotations = 1;
        self.illuminations = 1;
        self.phases = 1;
        self.rotation_axis = false;
        self.current_series = 0;
        self.current_resolution = 0;
        Ok(())
    }

    fn series_count(&self) -> usize {
        if self.meta.is_some() {
            self.series.len().max(1)
        } else {
            0
        }
    }
    fn set_series(&mut self, s: usize) -> Result<()> {
        if s >= self.series_count() {
            return Err(BioFormatsError::SeriesOutOfRange(s));
        }
        self.current_series = s;
        // Switching scenes resets the active resolution to full-res (level 0),
        // matching how setSeries resets the core/resolution index in Java.
        self.current_resolution = 0;
        self.refresh_meta_dimensions();
        Ok(())
    }
    fn series(&self) -> usize {
        self.current_series
    }
    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 entries = self
            .matching_entries(plane_index)
            .ok_or_else(|| BioFormatsError::PlaneOutOfRange(plane_index))?;
        let path = self.path.as_ref().ok_or(BioFormatsError::NotInitialized)?;

        let bps = meta.pixel_type.bytes_per_sample();
        let expected = meta.size_x as usize * meta.size_y as usize * self.packed_spp as usize * bps;
        let pixel_bytes = self.packed_spp as usize * bps;
        let mut out = vec![0; expected];

        // Prestitching: normalize tile placement so the minimum tile col/row maps
        // to the stitched-image origin (ZeissCZIReader.openBytes:435-439). A tile
        // whose stored size already equals the full image is placed at (0,0).
        let (min_col, min_row) = if self.prestitched {
            entries.iter().fold((i32::MAX, i32::MAX), |(mc, mr), e| {
                (mc.min(e.dim_start("X")), mr.min(e.dim_start("Y")))
            })
        } else {
            (0, 0)
        };
        let (min_col, min_row) = (min_col.max(0), min_row.max(0));

        for entry in entries {
            let tile_w = entry.dim_stored_size("X").max(0) as usize;
            let tile_h = entry.dim_stored_size("Y").max(0) as usize;
            let tile_expected = tile_w
                .checked_mul(tile_h)
                .and_then(|n| n.checked_mul(pixel_bytes))
                .ok_or_else(|| BioFormatsError::Format("CZI tile byte count overflows".into()))?;
            let tile = Self::read_subblock(path, &entry, pixel_bytes)?;
            if tile.len() != tile_expected {
                return Err(BioFormatsError::Format(format!(
                    "CZI decoded tile byte count {} does not match expected {}",
                    tile.len(),
                    tile_expected
                )));
            }
            // Place the tile at its normalized position. When a tile's stored size
            // already spans the whole stitched image, it sits at the origin.
            let full_tile =
                self.prestitched && tile_w as u32 == meta.size_x && tile_h as u32 == meta.size_y;
            let (off_x, off_y) = if full_tile {
                (0, 0)
            } else {
                (min_col, min_row)
            };
            Self::assemble_entry(
                &mut out,
                meta.size_x,
                meta.size_y,
                &tile,
                &entry,
                pixel_bytes,
                off_x,
                off_y,
            )?;
        }
        if meta.is_rgb && self.packed_spp >= 3 {
            swap_bgr_to_rgb(&mut out, bps, self.packed_spp as usize);
        }
        Ok(out)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let full = self.open_bytes(plane_index)?;
        let meta = self.meta.as_ref().unwrap();
        crop_full_plane("CZI", &full, meta, self.packed_spp as usize, 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, th) = (meta.size_x.min(256), meta.size_y.min(256));
        let (tx, ty) = ((meta.size_x - tw) / 2, (meta.size_y - th) / 2);
        self.open_bytes_region(plane_index, tx, ty, tw, th)
    }

    fn resolution_count(&self) -> usize {
        self.current_resolutions().len().max(1)
    }

    fn set_resolution(&mut self, level: usize) -> Result<()> {
        let count = self.current_resolutions().len();
        if level >= count {
            return Err(BioFormatsError::Format(format!(
                "CZI resolution level {} out of range (max {})",
                level,
                count.saturating_sub(1)
            )));
        }
        self.current_resolution = level;
        self.refresh_meta_dimensions();
        Ok(())
    }

    fn resolution(&self) -> usize {
        self.current_resolution
    }

    fn ome_metadata(&self) -> Option<crate::common::ome_metadata::OmeMetadata> {
        if self.meta_xml.is_empty() {
            return None;
        }
        Some(crate::common::ome_metadata::OmeMetadata::from_czi_xml(
            &self.meta_xml,
        ))
    }
}

fn swap_bgr_to_rgb(buf: &mut [u8], bytes_per_sample: usize, samples_per_pixel: usize) {
    if samples_per_pixel < 3 || bytes_per_sample == 0 {
        return;
    }

    let pixel_bytes = bytes_per_sample * samples_per_pixel;
    for pixel in buf.chunks_exact_mut(pixel_bytes) {
        for i in 0..bytes_per_sample {
            pixel.swap(i, 2 * bytes_per_sample + i);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write;

    #[test]
    fn czi_12bit_camera_rejects_truncated_payload() {
        let err = decode_12bit_camera(&[0xab, 0xcd], 8).unwrap_err();
        assert!(
            err.to_string()
                .contains("12-bit camera payload is too short"),
            "unexpected error: {err}"
        );
    }

    fn put_i32(buf: &mut [u8], off: usize, value: i32) {
        buf[off..off + 4].copy_from_slice(&value.to_le_bytes());
    }

    fn put_i64(buf: &mut [u8], off: usize, value: i64) {
        buf[off..off + 8].copy_from_slice(&value.to_le_bytes());
    }

    fn put_u64(buf: &mut [u8], off: usize, value: u64) {
        buf[off..off + 8].copy_from_slice(&value.to_le_bytes());
    }

    fn segment_header(name: &str, used_size: u64) -> Vec<u8> {
        let mut header = vec![0; SEG_HEADER];
        header[..name.len()].copy_from_slice(name.as_bytes());
        put_u64(&mut header, 16, used_size);
        put_u64(&mut header, 24, used_size);
        header
    }

    fn dimension_entry(name: &str, start: i32, size: i32) -> [u8; 20] {
        let mut dim = [0; 20];
        dim[..name.len()].copy_from_slice(name.as_bytes());
        put_i32(&mut dim, 4, start);
        put_i32(&mut dim, 8, size);
        dim
    }

    fn directory_entry(pixel_type: i32, file_position: i64, c: i32, x: i32, y: i32) -> Vec<u8> {
        directory_entry_dims(pixel_type, file_position, c, 0, 0, x, y, 0)
    }

    fn directory_entry_dims(
        pixel_type: i32,
        file_position: i64,
        c: i32,
        x_start: i32,
        y_start: i32,
        x_size: i32,
        y_size: i32,
        r: i32,
    ) -> Vec<u8> {
        let mut entry = vec![0; 256];
        put_i32(&mut entry, 2, pixel_type);
        put_i64(&mut entry, 6, file_position);
        put_i32(&mut entry, 18, 0);
        put_i32(&mut entry, 28, 4);
        entry[32..52].copy_from_slice(&dimension_entry("X", x_start, x_size));
        entry[52..72].copy_from_slice(&dimension_entry("Y", y_start, y_size));
        entry[72..92].copy_from_slice(&dimension_entry("C", c, 1));
        entry[92..112].copy_from_slice(&dimension_entry("R", r, 1));
        entry
    }

    /// Directory entry carrying X/Y tile placement plus one extra dimension
    /// (e.g. "M" mosaic, "B" acquisition, "V" angle) with the given start.
    /// Used to exercise mosaic stitching and the extra-dimension series split.
    fn directory_entry_extra(
        pixel_type: i32,
        x_start: i32,
        y_start: i32,
        x_size: i32,
        y_size: i32,
        extra_dim: &str,
        extra_start: i32,
    ) -> Vec<u8> {
        let mut entry = vec![0; 256];
        put_i32(&mut entry, 2, pixel_type);
        put_i32(&mut entry, 18, 0);
        put_i32(&mut entry, 28, 5);
        entry[32..52].copy_from_slice(&dimension_entry("X", x_start, x_size));
        entry[52..72].copy_from_slice(&dimension_entry("Y", y_start, y_size));
        entry[72..92].copy_from_slice(&dimension_entry("C", 0, 1));
        entry[92..112].copy_from_slice(&dimension_entry("R", 0, 1));
        entry[112..132].copy_from_slice(&dimension_entry(extra_dim, extra_start, 1));
        entry
    }

    /// Directory entry carrying an explicit scene ("S") dimension, used to test
    /// the multi-series scene split (one series per S position).
    fn directory_entry_scene(
        pixel_type: i32,
        file_position: i64,
        scene: i32,
        x_size: i32,
        y_size: i32,
    ) -> Vec<u8> {
        let mut entry = vec![0; 256];
        put_i32(&mut entry, 2, pixel_type);
        put_i64(&mut entry, 6, file_position);
        put_i32(&mut entry, 18, 0);
        put_i32(&mut entry, 28, 5);
        entry[32..52].copy_from_slice(&dimension_entry("X", 0, x_size));
        entry[52..72].copy_from_slice(&dimension_entry("Y", 0, y_size));
        entry[72..92].copy_from_slice(&dimension_entry("C", 0, 1));
        entry[92..112].copy_from_slice(&dimension_entry("R", 0, 1));
        entry[112..132].copy_from_slice(&dimension_entry("S", scene, 1));
        entry
    }

    /// Directory entry carrying both a scene ("S") and a Z dimension, used to
    /// exercise the mosaic image-fusion series rebalancing
    /// (ZeissCZIReader:941-960).
    fn directory_entry_scene_z(
        pixel_type: i32,
        scene: i32,
        z: i32,
        x_size: i32,
        y_size: i32,
    ) -> Vec<u8> {
        let mut entry = vec![0; 256];
        put_i32(&mut entry, 2, pixel_type);
        put_i32(&mut entry, 18, 0);
        put_i32(&mut entry, 28, 5);
        entry[32..52].copy_from_slice(&dimension_entry("X", 0, x_size));
        entry[52..72].copy_from_slice(&dimension_entry("Y", 0, y_size));
        entry[72..92].copy_from_slice(&dimension_entry("Z", z, 1));
        entry[92..112].copy_from_slice(&dimension_entry("R", 0, 1));
        entry[112..132].copy_from_slice(&dimension_entry("S", scene, 1));
        entry
    }

    fn directory_entry_zc_dims(
        pixel_type: i32,
        file_position: i64,
        z: i32,
        c: i32,
        x_size: i32,
        y_size: i32,
    ) -> Vec<u8> {
        let mut entry = vec![0; 256];
        put_i32(&mut entry, 2, pixel_type);
        put_i64(&mut entry, 6, file_position);
        put_i32(&mut entry, 18, 0);
        put_i32(&mut entry, 28, 5);
        entry[32..52].copy_from_slice(&dimension_entry("X", 0, x_size));
        entry[52..72].copy_from_slice(&dimension_entry("Y", 0, y_size));
        entry[72..92].copy_from_slice(&dimension_entry("Z", z, 1));
        entry[92..112].copy_from_slice(&dimension_entry("C", c, 1));
        entry[112..132].copy_from_slice(&dimension_entry("R", 0, 1));
        entry
    }

    fn write_synthetic_bgr_czi(name: &str, pixel_type: i32, planes: &[Vec<u8>]) -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "bioformats_czi_{name}_{}_{}.czi",
            std::process::id(),
            planes.len()
        ));
        let width = 2;
        let height = 1;
        let file_header_size = SEG_HEADER + 80;
        let dir_size = SEG_HEADER + 128 + planes.len() * 256;
        // Java-correct subblock layout: the fixed body (from body_start) is 256
        // bytes total, which includes the 16-byte size header. Pixel data follows.
        let subblock_size = |plane: &Vec<u8>| SEG_HEADER + 256 + plane.len();
        let dir_pos = file_header_size as u64;
        let mut subblock_pos = (file_header_size + dir_size) as u64;

        let mut data = Vec::new();
        data.extend_from_slice(&segment_header("ZISRAWFILE", file_header_size as u64));
        let mut file_header = vec![0; 80];
        put_u64(&mut file_header, 36, dir_pos);
        data.extend_from_slice(&file_header);

        data.extend_from_slice(&segment_header("ZISRAWDIRECTORY", dir_size as u64));
        let mut dir_header = vec![0; 128];
        put_i32(&mut dir_header, 0, planes.len() as i32);
        data.extend_from_slice(&dir_header);
        let mut entries = Vec::new();
        for (c, plane) in planes.iter().enumerate() {
            entries.push(directory_entry(
                pixel_type,
                subblock_pos as i64,
                c as i32,
                width,
                height,
            ));
            subblock_pos += subblock_size(plane) as u64;
        }
        for entry in &entries {
            data.extend_from_slice(entry);
        }

        for (_entry, plane) in entries.iter().zip(planes) {
            let used_size = (SEG_HEADER + 256 + plane.len()) as u64;
            data.extend_from_slice(&segment_header("ZISRAWSUBBLOCK", used_size));
            // 256-byte fixed body: 16-byte size header followed by 240 reserved bytes.
            let mut subblock_body = vec![0; 256];
            put_u64(&mut subblock_body, 8, plane.len() as u64);
            data.extend_from_slice(&subblock_body);
            data.extend_from_slice(plane);
        }

        let mut file = fs::File::create(&path).unwrap();
        file.write_all(&data).unwrap();
        path
    }

    fn write_synthetic_czi_entries(
        name: &str,
        entries_and_pixels: Vec<(Vec<u8>, Vec<u8>)>,
    ) -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "bioformats_czi_{name}_{}_{}.czi",
            std::process::id(),
            entries_and_pixels.len()
        ));
        let file_header_size = SEG_HEADER + 80;
        let dir_size = SEG_HEADER + 128 + entries_and_pixels.len() * 256;
        let dir_pos = file_header_size as u64;
        let mut subblock_pos = (file_header_size + dir_size) as u64;
        let mut entries = Vec::new();

        for (mut entry, pixels) in entries_and_pixels {
            put_i64(&mut entry, 6, subblock_pos as i64);
            subblock_pos += (SEG_HEADER + 256 + pixels.len()) as u64;
            entries.push((entry, pixels));
        }

        let mut data = Vec::new();
        data.extend_from_slice(&segment_header("ZISRAWFILE", file_header_size as u64));
        let mut file_header = vec![0; 80];
        put_u64(&mut file_header, 36, dir_pos);
        data.extend_from_slice(&file_header);

        data.extend_from_slice(&segment_header("ZISRAWDIRECTORY", dir_size as u64));
        let mut dir_header = vec![0; 128];
        put_i32(&mut dir_header, 0, entries.len() as i32);
        data.extend_from_slice(&dir_header);
        for (entry, _) in &entries {
            data.extend_from_slice(entry);
        }

        for (_entry, pixels) in &entries {
            let used_size = (SEG_HEADER + 256 + pixels.len()) as u64;
            data.extend_from_slice(&segment_header("ZISRAWSUBBLOCK", used_size));
            // 256-byte fixed body: 16-byte size header followed by 240 reserved bytes.
            let mut subblock_body = vec![0; 256];
            put_u64(&mut subblock_body, 8, pixels.len() as u64);
            data.extend_from_slice(&subblock_body);
            data.extend_from_slice(pixels);
        }

        let mut file = fs::File::create(&path).unwrap();
        file.write_all(&data).unwrap();
        path
    }

    /// Like `write_synthetic_czi_entries` but also writes a metadata (ZISRAWMETADATA)
    /// segment carrying `xml`, wiring its file-header offset so `set_id` parses it.
    /// Used to exercise XML-guided behavior (PALM detection, modulo labels).
    fn write_synthetic_czi_with_xml(
        name: &str,
        entries_and_pixels: Vec<(Vec<u8>, Vec<u8>)>,
        xml: &str,
    ) -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "bioformats_czi_{name}_{}_{}.czi",
            std::process::id(),
            entries_and_pixels.len()
        ));
        let file_header_size = SEG_HEADER + 80;
        let dir_size = SEG_HEADER + 128 + entries_and_pixels.len() * 256;
        let xml_bytes = xml.as_bytes();
        // Metadata segment: header + 256-byte body header (xml_size at off 0) + xml.
        let meta_size = SEG_HEADER + 256 + xml_bytes.len();
        let dir_pos = file_header_size as u64;
        let meta_pos = (file_header_size + dir_size) as u64;
        let mut subblock_pos = (file_header_size + dir_size + meta_size) as u64;
        let mut entries = Vec::new();

        for (mut entry, pixels) in entries_and_pixels {
            put_i64(&mut entry, 6, subblock_pos as i64);
            subblock_pos += (SEG_HEADER + 256 + pixels.len()) as u64;
            entries.push((entry, pixels));
        }

        let mut data = Vec::new();
        data.extend_from_slice(&segment_header("ZISRAWFILE", file_header_size as u64));
        let mut file_header = vec![0; 80];
        put_u64(&mut file_header, 36, dir_pos);
        put_u64(&mut file_header, 44, meta_pos);
        data.extend_from_slice(&file_header);

        data.extend_from_slice(&segment_header("ZISRAWDIRECTORY", dir_size as u64));
        let mut dir_header = vec![0; 128];
        put_i32(&mut dir_header, 0, entries.len() as i32);
        data.extend_from_slice(&dir_header);
        for (entry, _) in &entries {
            data.extend_from_slice(entry);
        }

        // Metadata segment.
        data.extend_from_slice(&segment_header("ZISRAWMETADATA", meta_size as u64));
        let mut meta_body = vec![0; 256];
        put_i32(&mut meta_body, 0, xml_bytes.len() as i32);
        data.extend_from_slice(&meta_body);
        data.extend_from_slice(xml_bytes);

        for (_entry, pixels) in &entries {
            let used_size = (SEG_HEADER + 256 + pixels.len()) as u64;
            data.extend_from_slice(&segment_header("ZISRAWSUBBLOCK", used_size));
            let mut subblock_body = vec![0; 256];
            put_u64(&mut subblock_body, 8, pixels.len() as u64);
            data.extend_from_slice(&subblock_body);
            data.extend_from_slice(pixels);
        }

        let mut file = fs::File::create(&path).unwrap();
        file.write_all(&data).unwrap();
        path
    }

    #[test]
    fn czi_varint_matches_java_encoding() {
        let mut offset = 0;
        assert_eq!(read_czi_varint(&[0x7f], &mut offset).unwrap(), 0x7f);
        assert_eq!(offset, 1);

        let mut offset = 0;
        assert_eq!(read_czi_varint(&[0x80, 0x01], &mut offset).unwrap(), 0x80);
        assert_eq!(offset, 2);

        let mut offset = 0;
        assert_eq!(
            read_czi_varint(&[0x80, 0x80, 0x01], &mut offset).unwrap(),
            0x4000
        );
        assert_eq!(offset, 3);
    }

    #[test]
    fn czi_zstd_1_plain_payload() {
        let payload = crate::common::codec::zstd_encode_all(b"\x11\x22\x33\x44", 0).unwrap();
        let mut wrapped = vec![3, 1, 0];
        wrapped.extend_from_slice(&payload);
        assert_eq!(
            decompress_zstd_1(&wrapped).unwrap(),
            vec![0x11, 0x22, 0x33, 0x44]
        );
    }

    #[test]
    fn czi_zstd_1_high_low_unpacking() {
        let payload = crate::common::codec::zstd_encode_all(b"\x11\x33\x22\x44", 0).unwrap();
        let mut wrapped = vec![3, 1, 1];
        wrapped.extend_from_slice(&payload);
        assert_eq!(
            decompress_zstd_1(&wrapped).unwrap(),
            vec![0x11, 0x22, 0x33, 0x44]
        );
    }

    #[test]
    fn czi_directory_rejects_truncated_declared_entry() {
        let mut entry = directory_entry_dims(0, 0, 0, 0, 0, 2, 1, 0);
        entry.truncate(40);

        let err = parse_directory_entries(&entry, 1).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert!(
            err.to_string().contains("directory entry 0 is truncated"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn czi_bgr24_keeps_logical_channels_separate_from_packed_samples() {
        let planes = vec![vec![1, 2, 3, 4, 5, 6], vec![7, 8, 9, 10, 11, 12]];
        let path = write_synthetic_bgr_czi("bgr24_logical_c", 3, &planes);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let meta = reader.metadata();
        assert_eq!(meta.size_c, 2);
        assert_eq!(meta.image_count, 2);
        assert!(meta.is_rgb);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![3, 2, 1, 6, 5, 4]);
        assert_eq!(reader.open_bytes(1).unwrap(), vec![9, 8, 7, 12, 11, 10]);
        assert_eq!(
            reader.open_bytes_region(1, 1, 0, 1, 1).unwrap(),
            vec![12, 11, 10]
        );

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_bgr48_keeps_logical_channels_separate_from_packed_samples() {
        let planes = vec![
            vec![1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0],
            vec![7, 0, 8, 0, 9, 0, 10, 0, 11, 0, 12, 0],
        ];
        let path = write_synthetic_bgr_czi("bgr48_logical_c", 4, &planes);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let meta = reader.metadata();
        assert_eq!(meta.size_c, 2);
        assert_eq!(meta.image_count, 2);
        assert_eq!(meta.pixel_type, PixelType::Uint16);
        assert!(meta.is_rgb);
        assert_eq!(
            reader.open_bytes(0).unwrap(),
            vec![3, 0, 2, 0, 1, 0, 6, 0, 5, 0, 4, 0]
        );
        assert_eq!(
            reader.open_bytes(1).unwrap(),
            vec![9, 0, 8, 0, 7, 0, 12, 0, 11, 0, 10, 0]
        );
        assert_eq!(
            reader.open_bytes_region(1, 1, 0, 1, 1).unwrap(),
            vec![12, 0, 11, 0, 10, 0]
        );

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_assembles_mosaic_tiles_into_single_plane() {
        let entries = vec![
            (directory_entry_dims(0, 0, 0, 0, 0, 2, 1, 0), vec![1, 2]),
            (directory_entry_dims(0, 0, 0, 2, 0, 2, 1, 0), vec![3, 4]),
            (directory_entry_dims(0, 0, 0, 0, 1, 2, 1, 0), vec![5, 6]),
            (directory_entry_dims(0, 0, 0, 2, 1, 2, 1, 0), vec![7, 8]),
        ];
        let path = write_synthetic_czi_entries("mosaic_tiles", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let meta = reader.metadata();
        assert_eq!((meta.size_x, meta.size_y), (4, 2));
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2, 3, 4, 5, 6, 7, 8]);
        assert_eq!(
            reader.open_bytes_region(0, 1, 0, 2, 2).unwrap(),
            vec![2, 3, 6, 7]
        );

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_rejects_short_decoded_tile_instead_of_padding() {
        let entries = vec![(directory_entry_dims(0, 0, 0, 0, 0, 2, 1, 0), vec![1])];
        let path = write_synthetic_czi_entries("short_tile", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let err = reader.open_bytes(0).unwrap_err();
        assert!(
            err.to_string()
                .contains("decoded tile byte count 1 does not match expected 2"),
            "unexpected error: {err}"
        );

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_rejects_long_decoded_tile_instead_of_truncating() {
        let entries = vec![(directory_entry_dims(0, 0, 0, 0, 0, 2, 1, 0), vec![1, 2, 3])];
        let path = write_synthetic_czi_entries("long_tile", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let err = reader.open_bytes(0).unwrap_err();
        assert!(
            err.to_string()
                .contains("decoded tile byte count 3 does not match expected 2"),
            "unexpected error: {err}"
        );

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_rejects_tile_outside_output_instead_of_skipping_copy() {
        let entry = parse_dir_entry(&directory_entry_dims(0, 0, 0, 1, 0, 1, 1, 0));
        let mut out = vec![0u8; 1];

        let err = CziReader::assemble_entry(&mut out, 1, 1, &[7], &entry, 1, 0, 0).unwrap_err();
        assert!(
            err.to_string()
                .contains("tile X bounds exceed output plane"),
            "unexpected error: {err}"
        );
        assert_eq!(out, vec![0]);
    }

    #[test]
    fn czi_uses_java_xyczt_plane_order() {
        let entries = vec![
            (directory_entry_zc_dims(0, 0, 0, 0, 1, 1), vec![10]),
            (directory_entry_zc_dims(0, 0, 0, 1, 1, 1), vec![11]),
            (directory_entry_zc_dims(0, 0, 1, 0, 1, 1), vec![12]),
            (directory_entry_zc_dims(0, 0, 1, 1, 1, 1), vec![13]),
        ];
        let path = write_synthetic_czi_entries("xyczt_order", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let meta = reader.metadata();
        assert_eq!(meta.dimension_order, DimensionOrder::XYCZT);
        assert_eq!((meta.size_z, meta.size_c, meta.size_t), (2, 2, 1));
        assert_eq!(meta.image_count, 4);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![10]);
        assert_eq!(reader.open_bytes(1).unwrap(), vec![11]);
        assert_eq!(reader.open_bytes(2).unwrap(), vec![12]);
        assert_eq!(reader.open_bytes(3).unwrap(), vec![13]);

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_selects_pyramid_resolution_level() {
        let entries = vec![
            (
                directory_entry_dims(0, 0, 0, 0, 0, 4, 2, 0),
                vec![1, 2, 3, 4, 5, 6, 7, 8],
            ),
            (directory_entry_dims(0, 0, 0, 0, 0, 2, 1, 1), vec![9, 10]),
        ];
        let path = write_synthetic_czi_entries("pyramid_levels", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        assert_eq!(reader.resolution_count(), 2);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2, 3, 4, 5, 6, 7, 8]);

        reader.set_resolution(1).unwrap();
        let meta = reader.metadata();
        assert_eq!((meta.size_x, meta.size_y), (2, 1));
        assert_eq!(reader.resolution(), 1);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![9, 10]);

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_splits_scenes_into_separate_series() {
        // Two scenes (S=0, S=1), each a single 2x1 plane. ZeissCZIReader treats
        // each "S" position as its own series (positions = maxS - minS + 1).
        let entries = vec![
            (directory_entry_scene(0, 0, 0, 2, 1), vec![1, 2]),
            (directory_entry_scene(0, 0, 1, 2, 1), vec![3, 4]),
        ];
        let path = write_synthetic_czi_entries("scene_series", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        assert_eq!(reader.series_count(), 2);

        // Series 0 -> scene S=0.
        assert_eq!(reader.series(), 0);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2]);

        // Series 1 -> scene S=1.
        reader.set_series(1).unwrap();
        assert_eq!(reader.series(), 1);
        let meta = reader.metadata();
        assert_eq!((meta.size_x, meta.size_y), (2, 1));
        assert_eq!(reader.open_bytes(0).unwrap(), vec![3, 4]);

        // Switch back to series 0.
        reader.set_series(0).unwrap();
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2]);

        assert!(reader.set_series(2).is_err());

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_prestitches_mosaic_tiles_into_single_series() {
        // Four mosaic tiles (M=0..3) laid out 2x2 with absolute X/Y placement.
        // ZeissCZIReader collapses the mosaic ("M") dimension into a single
        // prestitched image (seriesCount stays 1, dimensions span all tiles).
        let entries = vec![
            (directory_entry_extra(0, 0, 0, 2, 1, "M", 0), vec![1, 2]),
            (directory_entry_extra(0, 2, 0, 2, 1, "M", 1), vec![3, 4]),
            (directory_entry_extra(0, 0, 1, 2, 1, "M", 2), vec![5, 6]),
            (directory_entry_extra(0, 2, 1, 2, 1, "M", 3), vec![7, 8]),
        ];
        let path = write_synthetic_czi_entries("mosaic_M_prestitch", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        // Mosaics are stitched, not exposed as separate series.
        assert_eq!(reader.series_count(), 1);
        let meta = reader.metadata();
        assert_eq!((meta.size_x, meta.size_y), (4, 2));
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2, 3, 4, 5, 6, 7, 8]);

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_prestitches_mosaic_with_nonzero_origin() {
        // Mosaic tiles whose absolute X/Y origin is not 0: the prestitching
        // normalization subtracts the minimum tile col/row so the stitched image
        // starts at (0,0) (ZeissCZIReader.openBytes tile.x -= minTileX).
        let entries = vec![
            (directory_entry_extra(0, 10, 20, 2, 1, "M", 0), vec![1, 2]),
            (directory_entry_extra(0, 12, 20, 2, 1, "M", 1), vec![3, 4]),
        ];
        let path = write_synthetic_czi_entries("mosaic_M_origin", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        assert_eq!(reader.series_count(), 1);
        let meta = reader.metadata();
        assert_eq!((meta.size_x, meta.size_y), (4, 1));
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2, 3, 4]);

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_splits_acquisitions_into_separate_series() {
        // Two acquisitions (B=0, B=1). ZeissCZIReader.calculateDimensions sets
        // acquisitions = maxB + 1 and seriesCount = positions * acquisitions *
        // angles, so each B becomes its own series.
        let entries = vec![
            (directory_entry_extra(0, 0, 0, 2, 1, "B", 0), vec![1, 2]),
            (directory_entry_extra(0, 0, 0, 2, 1, "B", 1), vec![3, 4]),
        ];
        let path = write_synthetic_czi_entries("acq_series", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        assert_eq!(reader.series_count(), 2);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2]);
        reader.set_series(1).unwrap();
        assert_eq!(reader.open_bytes(0).unwrap(), vec![3, 4]);

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_splits_angles_into_separate_series() {
        // Two angles (V=0, V=1) -> two series (angles = maxV + 1).
        let entries = vec![
            (directory_entry_extra(0, 0, 0, 2, 1, "V", 0), vec![1, 2]),
            (directory_entry_extra(0, 0, 0, 2, 1, "V", 1), vec![3, 4]),
        ];
        let path = write_synthetic_czi_entries("angle_series", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        assert_eq!(reader.series_count(), 2);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2]);
        reader.set_series(1).unwrap();
        assert_eq!(reader.open_bytes(0).unwrap(), vec![3, 4]);

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_fuses_mosaic_collapses_series_count() {
        // Mosaic image-fusion series rebalancing (ZeissCZIReader:941-960).
        //
        // Two scenes (S=0, S=1) are declared, each carrying a distinct Z plane, so
        // the dimension scan yields positions = 2 and sizeZ = 2. The expected plane
        // budget is imageCount(=sizeZ=2) * seriesCount(=positions=2) = 4, but the
        // file only stores 2 fused planes. ZeissCZIReader detects this
        // (imageCount * seriesCount > planes.size() * scanDim, i.e. 4 > 2) and,
        // because planes.size() == imageCount (2 == 2), collapses everything to a
        // single series (positions = acquisitions = mosaics = angles = seriesCount
        // = 1, ZeissCZIReader:952-960). Without this rebalancing the reader would
        // wrongly expose 2 scene series for a fused acquisition.
        let entries = vec![
            (directory_entry_scene_z(0, 0, 0, 2, 1), vec![1, 2]),
            (directory_entry_scene_z(0, 1, 1, 2, 1), vec![3, 4]),
        ];
        let path = write_synthetic_czi_entries("fused_collapse", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        // Series collapsed to one; the single series matches both subblocks.
        assert_eq!(reader.series_count(), 1);
        let meta = reader.metadata();
        assert_eq!((meta.size_x, meta.size_y), (2, 1));
        assert_eq!((meta.size_z, meta.size_c, meta.size_t), (2, 1, 1));
        assert_eq!(meta.image_count, 2);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2]);
        assert_eq!(reader.open_bytes(1).unwrap(), vec![3, 4]);

        fs::remove_file(path).unwrap();
    }

    /// Directory entry carrying an explicit Z dimension plus a rotation ("R")
    /// dimension at the given rotation index. Each subblock is one rotation
    /// (R.size == 1, distinct starts, equal X size), which the reader detects as a
    /// rotation axis because the R levels are not downscaled (no pyramid).
    fn directory_entry_rotation(z: i32, r_start: i32, x_size: i32, y_size: i32) -> Vec<u8> {
        let mut entry = vec![0; 256];
        put_i32(&mut entry, 2, 0); // Gray8
        put_i32(&mut entry, 18, 0);
        put_i32(&mut entry, 28, 5);
        entry[32..52].copy_from_slice(&dimension_entry("X", 0, x_size));
        entry[52..72].copy_from_slice(&dimension_entry("Y", 0, y_size));
        entry[72..92].copy_from_slice(&dimension_entry("C", 0, 1));
        entry[92..112].copy_from_slice(&dimension_entry("Z", z, 1));
        entry[112..132].copy_from_slice(&dimension_entry("R", r_start, 1));
        entry
    }

    #[test]
    fn czi_rotation_folds_into_modulo_z() {
        // ZeissCZIReader treats the "R" dimension as a rotation axis (size > 1) and
        // exposes it as a moduloZ annotation, multiplying sizeZ by the rotation
        // count (ZeissCZIReader:846-849) and folding the plane index via
        // z = r * (sizeZ / rotations) + z (ZeissCZIReader:2216-2217).
        //
        // Two real Z planes (Z=0,1) each acquired at two rotations (R=0,1, size 2):
        //   expanded Z order is rotation-major:
        //     z=0 -> rot=0,Z=0 ; z=1 -> rot=0,Z=1 ; z=2 -> rot=1,Z=0 ; z=3 -> rot=1,Z=1
        let entries = vec![
            (directory_entry_rotation(0, 0, 2, 1), vec![10, 11]),
            (directory_entry_rotation(1, 0, 2, 1), vec![12, 13]),
            (directory_entry_rotation(0, 1, 2, 1), vec![20, 21]),
            (directory_entry_rotation(1, 1, 2, 1), vec![22, 23]),
        ];
        let path = write_synthetic_czi_entries("rotation_modulo_z", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let meta = reader.metadata();
        // rotations = maxRotation - minRotation = (0+2) - 0 = 2; sizeZ = 2 * 2 = 4.
        assert_eq!(meta.size_z, 4);
        assert_eq!(meta.image_count, 4);
        // Rotation is exposed as a single resolution, not a pyramid.
        assert_eq!(reader.resolution_count(), 1);
        let mz = meta.modulo_z.as_ref().expect("moduloZ annotation");
        assert_eq!(mz.parent_dimension, "Z");
        assert_eq!(mz.modulo_type, "rotation");
        assert_eq!(mz.step, 2.0); // original sizeZ
        assert_eq!(mz.end, 2.0); // sizeZ * (rotations - 1)

        // Plane order: XYCZT with z fastest after c. sizeC=1 so plane==z.
        assert_eq!(reader.open_bytes(0).unwrap(), vec![10, 11]); // rot0 z0
        assert_eq!(reader.open_bytes(1).unwrap(), vec![12, 13]); // rot0 z1
        assert_eq!(reader.open_bytes(2).unwrap(), vec![20, 21]); // rot1 z0
        assert_eq!(reader.open_bytes(3).unwrap(), vec![22, 23]); // rot1 z1

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_r_size_one_stays_pyramid_not_rotation() {
        // Regression guard: when R.size == 1 (the crate's pyramid repurposing),
        // distinct R starts must remain resolution levels and NOT be folded into Z.
        let entries = vec![
            (
                directory_entry_dims(0, 0, 0, 0, 0, 4, 2, 0),
                vec![1, 2, 3, 4, 5, 6, 7, 8],
            ),
            (directory_entry_dims(0, 0, 0, 0, 0, 2, 1, 1), vec![9, 10]),
        ];
        let path = write_synthetic_czi_entries("r_size_one_pyramid", entries);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        let meta = reader.metadata();
        assert_eq!(meta.size_z, 1); // not multiplied by rotation
        assert!(meta.modulo_z.is_none());
        assert_eq!(reader.resolution_count(), 2); // pyramid preserved

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_check_palm_detects_lsmtag_and_palmslider() {
        // ZeissCZIReader.checkPALM: LsmTag Name starting with "palm" (case-insens.).
        assert!(check_palm(
            r#"<CustomAttributes><LsmTag Name="PALMExperiment">x</LsmTag></CustomAttributes>"#
        ));
        // ...or a PalmSlider element whose text content is "true".
        assert!(check_palm(
            "<TrackSetup><PalmSlider>true</PalmSlider></TrackSetup>"
        ));
        // Negative cases.
        assert!(!check_palm(
            "<TrackSetup><PalmSlider>false</PalmSlider></TrackSetup>"
        ));
        assert!(!check_palm(r#"<LsmTag Name="Gain">3</LsmTag>"#));
        assert!(!check_palm(""));
    }

    #[test]
    fn czi_parse_modulo_labels_splits_on_whitespace() {
        // ZeissCZIReader:3733-3741 splits the "...|Rotations|" value on spaces.
        let xml = "<Rotations>0 90 180 270</Rotations><Phases>a b</Phases>";
        assert_eq!(
            parse_modulo_labels(xml, "Rotations"),
            vec!["0", "90", "180", "270"]
        );
        assert_eq!(parse_modulo_labels(xml, "Phases"), vec!["a", "b"]);
        // Single (or no) label yields an empty list (no modulo labeling).
        assert!(parse_modulo_labels("<Rotations>0</Rotations>", "Rotations").is_empty());
        assert!(parse_modulo_labels("", "Rotations").is_empty());
    }

    #[test]
    fn czi_palm_splits_two_planes_by_stored_size() {
        // ZeissCZIReader PALM heuristic (1123-1193): <= 2 planes, imageCount <= 2,
        // checkPALM(xml) true, and the two planes have *different* stored sizes ->
        // split into two single-channel series, each sized to its own tile.
        let palm_xml = "<TrackSetup><PalmSlider>true</PalmSlider></TrackSetup>";
        // Both planes at C=0; PALM distinguishes the two series purely by the
        // stored tile size, not by channel (ZeissCZIReader recomputes planeIndex).
        let entries = vec![
            (directory_entry(0, 0, 0, 2, 1), vec![1, 2]),
            (directory_entry(0, 0, 0, 4, 1), vec![3, 4, 5, 6]),
        ];
        let path = write_synthetic_czi_with_xml("palm_split", entries, palm_xml);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        // PALM forces sizeC = 1 and exposes two series (one per distinct size).
        assert_eq!(reader.series_count(), 2);
        let meta = reader.metadata();
        assert_eq!(meta.size_c, 1);
        assert_eq!((meta.size_x, meta.size_y), (2, 1));
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2]);

        reader.set_series(1).unwrap();
        let meta = reader.metadata();
        assert_eq!((meta.size_x, meta.size_y), (4, 1));
        assert_eq!(reader.open_bytes(0).unwrap(), vec![3, 4, 5, 6]);

        fs::remove_file(path).unwrap();
    }

    #[test]
    fn czi_palm_same_size_pair_is_not_palm() {
        // Same-size pair => not PALM; revert to a single 2-channel series
        // (ZeissCZIReader:1174-1192).
        let palm_xml = "<TrackSetup><PalmSlider>true</PalmSlider></TrackSetup>";
        let entries = vec![
            (directory_entry(0, 0, 0, 2, 1), vec![1, 2]),
            (directory_entry(0, 0, 1, 2, 1), vec![3, 4]),
        ];
        let path = write_synthetic_czi_with_xml("palm_same_size", entries, palm_xml);
        let mut reader = CziReader::new();
        reader.set_id(&path).unwrap();

        assert_eq!(reader.series_count(), 1);
        let meta = reader.metadata();
        assert_eq!(meta.size_c, 2);
        assert_eq!(reader.open_bytes(0).unwrap(), vec![1, 2]);
        assert_eq!(reader.open_bytes(1).unwrap(), vec![3, 4]);

        fs::remove_file(path).unwrap();
    }
}