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
//! Scanning Electron Microscopy (SEM) and related format readers.
//!
//! Includes binary readers for INR, FEI/Philips, Veeco/Nanoscope, and several
//! SEM-adjacent formats. Readers without a decoded native layout require
//! explicit strict raw fixtures rather than heuristic dimensions.

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

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

// ---------------------------------------------------------------------------
// Macro: thin TIFF wrapper
// ---------------------------------------------------------------------------
macro_rules! tiff_wrapper {
    (
        $(#[$attr:meta])*
        pub struct $name:ident;
        extensions: [$($ext:literal),+];
    ) => {
        $(#[$attr])*
        pub struct $name {
            inner: crate::tiff::TiffReader,
        }

        impl $name {
            pub fn new() -> Self {
                $name { inner: crate::tiff::TiffReader::new() }
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

            fn set_resolution(&mut self, level: usize) -> Result<()> {
                self.inner.set_resolution(level)
            }
        }
    };
}

// ===========================================================================
// Real binary reader 1 — INR format
// ===========================================================================

/// INRIMAGE-4 volumetric format (`.inr`).
///
/// Header is 256 ASCII bytes with `#INRIMAGE-4#{` magic, followed by raw
/// pixel data. Key=value pairs in the header define dimensions and pixel type.
pub struct InrReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
}

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

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

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

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        header.len() >= 13 && &header[0..13] == b"#INRIMAGE-4#{"
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        let data = std::fs::read(path).map_err(BioFormatsError::Io)?;

        // Header is first 256 bytes interpreted as ASCII text
        if data.len() < 256 || !data.starts_with(b"#INRIMAGE-4#{") {
            return Err(BioFormatsError::UnsupportedFormat(
                "INR file is missing the 256-byte INRIMAGE-4 header".into(),
            ));
        }
        let header_bytes = &data[..256];
        let header_text = String::from_utf8_lossy(header_bytes);

        let mut size_x: Option<u32> = None;
        let mut size_y: Option<u32> = None;
        let mut size_z: u32 = 1;
        let mut size_t: u32 = 1;
        let mut bpp: Option<u32> = None;
        // Java: isSigned = TYPE.toLowerCase().startsWith("signed")
        let mut is_signed = false;
        let mut little_endian = true;

        for line in header_text.split('\n') {
            let line = line.trim();
            if let Some(pos) = line.find('=') {
                let key = line[..pos].trim();
                let val = line[pos + 1..].trim();
                match key {
                    "XDIM" => {
                        if let Ok(n) = val.parse::<u32>() {
                            size_x = Some(n);
                        }
                    }
                    "YDIM" => {
                        if let Ok(n) = val.parse::<u32>() {
                            size_y = Some(n);
                        }
                    }
                    "ZDIM" => {
                        if let Ok(n) = val.parse::<u32>() {
                            size_z = n;
                        }
                    }
                    "VDIM" => {
                        // Java INRReader.java:124-126 maps VDIM -> sizeT
                        if let Ok(n) = val.parse::<u32>() {
                            size_t = n;
                        }
                    }
                    "PIXSIZE" => {
                        // Format: "N bits"
                        if let Some(n_str) = val.split_whitespace().next() {
                            if let Ok(n) = n_str.parse::<u32>() {
                                bpp = Some(n);
                            }
                        }
                    }
                    "TYPE" => {
                        // Java INRReader.java:127-129:
                        //   isSigned = value.toLowerCase().startsWith("signed")
                        is_signed = val.to_ascii_lowercase().starts_with("signed");
                    }
                    "CPU" => {
                        little_endian = matches!(val, "decm" | "pc");
                        if val == "sun" || val == "sgi" {
                            little_endian = false;
                        }
                    }
                    _ => {}
                }
            }
        }

        let size_x = size_x
            .filter(|&v| v > 0)
            .ok_or_else(|| BioFormatsError::UnsupportedFormat("INR header missing XDIM".into()))?;
        let size_y = size_y
            .filter(|&v| v > 0)
            .ok_or_else(|| BioFormatsError::UnsupportedFormat("INR header missing YDIM".into()))?;
        let bpp = bpp.ok_or_else(|| {
            BioFormatsError::UnsupportedFormat("INR header missing PIXSIZE".into())
        })?;
        // Java INRReader.java:158-159:
        //   pixelType = FormatTools.pixelTypeFromBytes(nBits / 8, isSigned, false)
        // Map purely by byte width; signed-ness chosen by `is_signed`. There is
        // no floating-point branch in Java for INR (fp is always false), so an
        // 8-byte sample maps to DOUBLE (Float64).
        let bytes = bpp / 8;
        let pixel_type = match bytes {
            1 if is_signed => PixelType::Int8,
            1 => PixelType::Uint8,
            2 if is_signed => PixelType::Int16,
            2 => PixelType::Uint16,
            4 if is_signed => PixelType::Int32,
            4 => PixelType::Uint32,
            8 => PixelType::Float64,
            _ => {
                return Err(BioFormatsError::UnsupportedFormat(format!(
                    "INR unsupported pixel size: {bpp} bits"
                )));
            }
        };

        // Java forces sizeC = 1 and imageCount = sizeZ * sizeT * sizeC.
        let size_c: u32 = 1;
        if size_z == 0 || size_t == 0 {
            return Err(BioFormatsError::UnsupportedFormat(
                "INR header dimensions must be positive".into(),
            ));
        }
        let image_count = size_z
            .checked_mul(size_t)
            .and_then(|v| v.checked_mul(size_c))
            .ok_or_else(|| BioFormatsError::Format("INR image count overflows".into()))?;
        let bps = (bpp / 8) as u64;
        let expected = 256u64
            .checked_add(
                (size_x as u64)
                    .checked_mul(size_y as u64)
                    .and_then(|v| v.checked_mul(image_count as u64))
                    .and_then(|v| v.checked_mul(bps))
                    .ok_or_else(|| BioFormatsError::Format("INR image size overflows".into()))?,
            )
            .ok_or_else(|| BioFormatsError::Format("INR image size overflows".into()))?;
        if (data.len() as u64) < expected {
            return Err(BioFormatsError::UnsupportedFormat(
                "INR pixel payload is shorter than declared dimensions".into(),
            ));
        }

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

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

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

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

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

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

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let meta = self.meta.as_ref().ok_or(BioFormatsError::NotInitialized)?;
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let bps = (meta.bits_per_pixel / 8) as usize;
        let plane_bytes = meta.size_x as usize * meta.size_y as usize * bps;
        let offset = 256u64 + (plane_index as u64) * (plane_bytes as u64);

        let path = self.path.clone().ok_or(BioFormatsError::NotInitialized)?;
        let mut f = std::fs::File::open(&path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(offset))
            .map_err(BioFormatsError::Io)?;
        let mut buf = vec![0u8; plane_bytes];
        f.read_exact(&mut buf).map_err(BioFormatsError::Io)?;
        Ok(buf)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        _x: u32,
        _y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self
            .meta
            .as_ref()
            .ok_or(BioFormatsError::NotInitialized)?
            .clone();
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        // Read full plane then crop (simple approach)
        let full = self.open_bytes(plane_index)?;
        crop_full_plane("INR", &full, &meta, 1, _x, _y, w, h)
    }

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

    fn resolution_count(&self) -> usize {
        1
    }

    fn set_resolution(&mut self, level: usize) -> Result<()> {
        if level != 0 {
            Err(BioFormatsError::Format(format!(
                "resolution {} out of range",
                level
            )))
        } else {
            Ok(())
        }
    }
}

// ===========================================================================
// Real binary reader 2 — FEI/Philips XL SEM
// ===========================================================================

const FEI_PHILIPS_MAGIC: &[u8; 2] = b"XL";
const FEI_INVALID_PIXELS: u32 = 112;
const FEI_DIMENSION_OFFSET: u64 = 514;

/// FEI/Philips XL `.img` SEM files.
///
/// Ported from Bio-Formats `FEIReader`: the header stores the physical scan
/// parameters at fixed offsets, width/height at offset 514, and pixels as an
/// 8-bit grayscale plane split into four row passes and two column passes.
pub struct FeiPhilipsReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    header_size: u64,
}

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

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

fn read_le_u16_at(data: &[u8], offset: usize, label: &str) -> Result<u16> {
    let bytes = data.get(offset..offset + 2).ok_or_else(|| {
        BioFormatsError::UnsupportedFormat(format!("FEI/Philips header missing {label}"))
    })?;
    Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
}

fn read_le_f32_at(data: &[u8], offset: usize) -> Option<f32> {
    let bytes = data.get(offset..offset + 4)?;
    Some(f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}

impl FormatReader for FeiPhilipsReader {
    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("img"))
            .unwrap_or(false)
    }

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

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        let data = std::fs::read(path).map_err(BioFormatsError::Io)?;
        if !self.is_this_type_by_bytes(&data) {
            return Err(BioFormatsError::UnsupportedFormat(
                "FEI/Philips IMG header does not start with XL".into(),
            ));
        }

        let stored_width = read_le_u16_at(&data, 514, "width")? as u32;
        let height = read_le_u16_at(&data, 516, "height")? as u32;
        let header_size = read_le_u16_at(&data, 522, "pixel offset")? as u64;
        if stored_width <= FEI_INVALID_PIXELS || height == 0 || header_size < FEI_DIMENSION_OFFSET {
            return Err(BioFormatsError::UnsupportedFormat(
                "FEI/Philips IMG header contains invalid dimensions or pixel offset".into(),
            ));
        }

        let width = stored_width - FEI_INVALID_PIXELS;
        if width % 2 != 0 {
            return Err(BioFormatsError::UnsupportedFormat(
                "FEI/Philips IMG width must be even for interlaced decode".into(),
            ));
        }

        let encoded_row_bytes = (width / 2 + FEI_INVALID_PIXELS / 2) as u64 * 2;
        let encoded_bytes = encoded_row_bytes
            .checked_mul(height as u64)
            .ok_or_else(|| BioFormatsError::Format("FEI/Philips payload size overflows".into()))?;
        let expected = header_size
            .checked_add(encoded_bytes)
            .ok_or_else(|| BioFormatsError::Format("FEI/Philips file size overflows".into()))?;
        if (data.len() as u64) < expected {
            return Err(BioFormatsError::UnsupportedFormat(
                "FEI/Philips IMG payload is shorter than declared dimensions".into(),
            ));
        }

        let mut series_metadata = HashMap::new();
        if let Some(v) = read_le_f32_at(&data, 44) {
            series_metadata.insert("Magnification".into(), MetadataValue::Float(v as f64));
        }
        if let Some(v) = read_le_f32_at(&data, 48) {
            series_metadata.insert("kV".into(), MetadataValue::Float((v / 1000.0) as f64));
        }
        if let Some(v) = read_le_f32_at(&data, 52) {
            series_metadata.insert("Working distance".into(), MetadataValue::Float(v as f64));
        }
        if let Some(v) = read_le_f32_at(&data, 68) {
            series_metadata.insert("Spot".into(), MetadataValue::Float(v as f64));
        }

        self.path = Some(path.to_path_buf());
        self.header_size = header_size;
        self.meta = Some(ImageMetadata {
            size_x: width,
            size_y: height,
            size_z: 1,
            size_c: 1,
            size_t: 1,
            pixel_type: PixelType::Uint8,
            bits_per_pixel: 8,
            image_count: 1,
            dimension_order: DimensionOrder::XYCZT,
            is_rgb: false,
            is_interleaved: false,
            is_indexed: false,
            is_little_endian: true,
            resolution_count: 1,
            series_metadata,
            lookup_table: None,
            modulo_z: None,
            modulo_c: None,
            modulo_t: None,
        });
        Ok(())
    }

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

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

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

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

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

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

        let path = self.path.clone().ok_or(BioFormatsError::NotInitialized)?;
        let mut f = std::fs::File::open(&path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(self.header_size))
            .map_err(BioFormatsError::Io)?;

        let width = meta.size_x as usize;
        let height = meta.size_y as usize;
        let segment_len = width / 2;
        let invalid_len = (FEI_INVALID_PIXELS / 2) as usize;
        let mut segment = vec![0u8; segment_len];
        let mut invalid = vec![0u8; invalid_len];
        let mut plane = vec![0u8; width * height];

        for row_pass in 0..4 {
            let mut row = row_pass;
            while row < height {
                for col_pass in 0..2 {
                    f.read_exact(&mut segment).map_err(BioFormatsError::Io)?;
                    f.read_exact(&mut invalid).map_err(BioFormatsError::Io)?;
                    let mut col = col_pass;
                    while col < width {
                        plane[row * width + col] = segment[col / 2];
                        col += 2;
                    }
                }
                row += 4;
            }
        }

        Ok(plane)
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self
            .meta
            .as_ref()
            .ok_or(BioFormatsError::NotInitialized)?
            .clone();
        let full = self.open_bytes(plane_index)?;
        crop_full_plane("FEI/Philips IMG", &full, &meta, 1, x, y, w, h)
    }

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

// ===========================================================================
// Real binary reader 3 — Veeco/Nanoscope AFM
// ===========================================================================

/// Veeco/Bruker Nanoscope AFM format (numeric extensions like `.001`, `.afm`).
///
/// Text header followed by raw binary pixel data. Detects via `*` first byte
/// and "NANOSCOPE" in the first 30 bytes.
pub struct VeecoReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    data_offset: usize,
}

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

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

impl FormatReader for VeecoReader {
    fn is_this_type_by_name(&self, path: &Path) -> bool {
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        // Match .afm or purely numeric extensions of 1-3 chars (e.g. "001")
        ext.eq_ignore_ascii_case("afm")
            || (ext.len() >= 1 && ext.len() <= 3 && ext.chars().all(|c| c.is_ascii_digit()))
    }

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        if header.is_empty() || header[0] != b'*' {
            return false;
        }
        let s = String::from_utf8_lossy(&header[..header.len().min(30)]);
        s.to_ascii_uppercase().contains("NANOSCOPE")
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        let data = std::fs::read(path).map_err(BioFormatsError::Io)?;
        let text = String::from_utf8_lossy(&data).into_owned();

        let mut width: Option<u32> = None;
        let mut height: Option<u32> = None;
        let mut bpp: Option<u32> = None;
        let mut data_offset: Option<usize> = None;

        for line in text.lines() {
            if line.contains("\\Samps/line:") {
                if let Some(val) = line.split_whitespace().last() {
                    if let Ok(n) = val.parse::<u32>() {
                        width = Some(n);
                    }
                }
            } else if line.contains("\\Number of lines:") {
                if let Some(val) = line.split_whitespace().last() {
                    if let Ok(n) = val.parse::<u32>() {
                        height = Some(n);
                    }
                }
            } else if line.contains("\\Bytes/pixel:") {
                if let Some(val) = line.split_whitespace().last() {
                    if let Ok(n) = val.parse::<u32>() {
                        bpp = Some(n);
                    }
                }
            } else if line.contains("\\Data offset:") {
                if let Some(val) = line.split_whitespace().last() {
                    if let Ok(n) = val.parse::<usize>() {
                        data_offset = Some(n);
                    }
                }
            }
        }

        let width = width.filter(|&v| v > 0).ok_or_else(|| {
            BioFormatsError::UnsupportedFormat("Nanoscope header missing Samps/line".into())
        })?;
        let height = height.filter(|&v| v > 0).ok_or_else(|| {
            BioFormatsError::UnsupportedFormat("Nanoscope header missing Number of lines".into())
        })?;
        let bpp = bpp.filter(|&v| v == 1 || v == 2).ok_or_else(|| {
            BioFormatsError::UnsupportedFormat(
                "Nanoscope header missing supported Bytes/pixel".into(),
            )
        })?;
        let data_offset = data_offset.ok_or_else(|| {
            BioFormatsError::UnsupportedFormat("Nanoscope header missing Data offset".into())
        })?;
        let expected = (data_offset as u64)
            .checked_add(
                (width as u64)
                    .saturating_mul(height as u64)
                    .saturating_mul(bpp as u64),
            )
            .ok_or_else(|| BioFormatsError::Format("Nanoscope plane size overflows".into()))?;
        if expected > data.len() as u64 {
            return Err(BioFormatsError::UnsupportedFormat(
                "Nanoscope pixel payload is shorter than declared dimensions".into(),
            ));
        }

        let pixel_type = if bpp == 1 {
            PixelType::Uint8
        } else {
            PixelType::Uint16
        };
        let bits_per_pixel = (bpp * 8) as u8;

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

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

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

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

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

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

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

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        _x: u32,
        _y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let meta = self
            .meta
            .as_ref()
            .ok_or(BioFormatsError::NotInitialized)?
            .clone();
        if plane_index >= meta.image_count {
            return Err(BioFormatsError::PlaneOutOfRange(plane_index));
        }
        let full = self.open_bytes(plane_index)?;
        crop_full_plane("Nanoscope", &full, &meta, 1, _x, _y, w, h)
    }

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

    fn resolution_count(&self) -> usize {
        1
    }

    fn set_resolution(&mut self, level: usize) -> Result<()> {
        if level != 0 {
            Err(BioFormatsError::Format(format!(
                "resolution {} out of range",
                level
            )))
        } else {
            Ok(())
        }
    }
}

// ===========================================================================
// TIFF wrapper — Zeiss
// ===========================================================================

// ---------------------------------------------------------------------------
// ZeissTiffReader
// ---------------------------------------------------------------------------
tiff_wrapper! {
    /// Zeiss TIFF wrapper (`.tif`). Extension-only, no distinct magic.
    pub struct ZeissTiffReader;
    extensions: ["tif"];
}

// ===========================================================================
// Strict raw readers for formats whose native layout is not decoded.
// ===========================================================================

// ===========================================================================
// Shared strict raw helper.
// ===========================================================================

fn unsupported_raw_sem(format_name: &str) -> BioFormatsError {
    BioFormatsError::UnsupportedFormat(format!(
        "{format_name} native binary layout is unsupported unless explicit strict raw data is present; refusing heuristic dimensions"
    ))
}

const JEOL_STRICT_MAGIC: &[u8] = b"BIOFORMATS-RS-JEOL-SEM-STRICT-RAW-V1\n";
const ZEISS_LMS_STRICT_MAGIC: &[u8] = b"BIOFORMATS-RS-ZEISS-LMS-STRICT-RAW-V1\n";
const IMROD_STRICT_MAGIC: &[u8] = b"BIOFORMATS-RS-IMROD-STRICT-RAW-V1\n";

fn read_le_u32_strict(data: &[u8], offset: usize, label: &str, format_name: &str) -> Result<u32> {
    let bytes = data.get(offset..offset + 4).ok_or_else(|| {
        BioFormatsError::UnsupportedFormat(format!("{format_name} strict header missing {label}"))
    })?;
    Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}

fn read_le_u16_strict(data: &[u8], offset: usize, label: &str, format_name: &str) -> Result<u16> {
    let bytes = data.get(offset..offset + 2).ok_or_else(|| {
        BioFormatsError::UnsupportedFormat(format!("{format_name} strict header missing {label}"))
    })?;
    Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
}

fn parse_strict_sem_raw(
    path: &Path,
    magic: &[u8],
    format_name: &str,
) -> Result<(ImageMetadata, u64)> {
    let data = std::fs::read(path).map_err(BioFormatsError::Io)?;
    if !data.starts_with(magic) {
        return Err(unsupported_raw_sem(format_name));
    }

    let width_offset = magic.len();
    let height_offset = width_offset + 4;
    let pixel_type_offset = height_offset + 4;
    let reserved_offset = pixel_type_offset + 2;
    let data_offset = reserved_offset + 2;
    let width = read_le_u32_strict(&data, width_offset, "width", format_name)?;
    let height = read_le_u32_strict(&data, height_offset, "height", format_name)?;
    if width == 0 || height == 0 {
        return Err(BioFormatsError::UnsupportedFormat(format!(
            "{format_name} strict header dimensions must be non-zero"
        )));
    }

    let pixel_type_code = read_le_u16_strict(&data, pixel_type_offset, "pixel type", format_name)?;
    let (pixel_type, bits_per_pixel) = match pixel_type_code {
        1 => (PixelType::Uint8, 8),
        2 => (PixelType::Uint16, 16),
        _ => {
            return Err(BioFormatsError::UnsupportedFormat(format!(
                "{format_name} strict header has unsupported pixel type code {pixel_type_code}"
            )));
        }
    };
    let reserved = read_le_u16_strict(&data, reserved_offset, "reserved field", format_name)?;
    if reserved != 0 {
        return Err(BioFormatsError::UnsupportedFormat(format!(
            "{format_name} strict header reserved field must be zero"
        )));
    }

    let payload_len = (width as u64)
        .checked_mul(height as u64)
        .and_then(|n| n.checked_mul(pixel_type.bytes_per_sample() as u64))
        .ok_or_else(|| BioFormatsError::Format(format!("{format_name} payload size overflows")))?;
    let expected_len = (data_offset as u64)
        .checked_add(payload_len)
        .ok_or_else(|| BioFormatsError::Format(format!("{format_name} file size overflows")))?;
    if data.len() as u64 != expected_len {
        return Err(BioFormatsError::UnsupportedFormat(format!(
            "{format_name} strict payload length mismatch: got {}, expected {expected_len}",
            data.len()
        )));
    }

    Ok((
        ImageMetadata {
            size_x: width,
            size_y: height,
            size_z: 1,
            size_c: 1,
            size_t: 1,
            pixel_type,
            bits_per_pixel,
            image_count: 1,
            dimension_order: DimensionOrder::XYCZT,
            is_rgb: false,
            is_interleaved: false,
            is_indexed: false,
            is_little_endian: true,
            resolution_count: 1,
            series_metadata: HashMap::new(),
            lookup_table: None,
            modulo_z: None,
            modulo_c: None,
            modulo_t: None,
        },
        data_offset as u64,
    ))
}

// ===========================================================================
// Real binary reader — JEOL SEM
// ===========================================================================

/// JEOL SEM data file reader (`.dat`).
///
/// Supports only the conservative BioFormats-rs strict raw subset identified
/// by `BIOFORMATS-RS-JEOL-SEM-STRICT-RAW-V1\n`.
pub struct JeolReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    data_offset: u64,
}

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

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

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

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

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        let (meta, data_offset) = parse_strict_sem_raw(path, JEOL_STRICT_MAGIC, "JEOL SEM")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.data_offset = data_offset;
        Ok(())
    }

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

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

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

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

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

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

        let n_bytes = (meta.size_x as usize)
            .checked_mul(meta.size_y as usize)
            .and_then(|n| n.checked_mul(meta.pixel_type.bytes_per_sample()))
            .ok_or_else(|| BioFormatsError::Format("JEOL SEM plane size overflows".into()))?;
        let path = self.path.clone().ok_or(BioFormatsError::NotInitialized)?;
        let mut f = std::fs::File::open(&path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(self.data_offset))
            .map_err(BioFormatsError::Io)?;
        let mut buf = vec![0u8; n_bytes];
        f.read_exact(&mut buf).map_err(BioFormatsError::Io)?;
        Ok(buf)
    }

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

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

    fn resolution_count(&self) -> usize {
        1
    }

    fn set_resolution(&mut self, level: usize) -> Result<()> {
        if level != 0 {
            Err(BioFormatsError::Format(format!(
                "resolution {} out of range",
                level
            )))
        } else {
            Ok(())
        }
    }
}

// ===========================================================================
// Hitachi S-4800 SEM — INI text file + companion pixels file
// ===========================================================================

/// Hitachi S-4800 SEM reader.
///
/// Ported from `HitachiReader.java`. A Hitachi dataset is a `.txt` INI file
/// whose `[SemImageFile]` section names the actual pixels file (`ImageName`),
/// a similarly-named `.tif`, `.bmp`, or `.jpg` placed alongside the `.txt`.
/// Detection requires the magic string `[SemImageFile]` (the file may be
/// either ASCII or UTF-16 encoded). The pixels are read by delegating to the
/// auto-detecting `ImageReader`, exactly as the Java reader delegates to a
/// helper `ImageReader` with `HitachiReader` removed from the class list.
pub struct HitachiReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    /// Resolved path to the companion pixels file (.tif/.bmp/.jpg).
    pixels_file: Option<PathBuf>,
    /// Parsed `[SemImageFile]` key/value pairs.
    ini: HashMap<String, String>,
}

impl HitachiReader {
    const MAGIC: &'static str = "[SemImageFile]";

    pub fn new() -> Self {
        HitachiReader {
            path: None,
            meta: None,
            pixels_file: None,
            ini: HashMap::new(),
        }
    }

    /// Decode the header text as ASCII, falling back to UTF-16 (matching the
    /// Java reader's `new String(b, ENCODING)` then `new String(b, "UTF-16")`).
    fn decode_header(bytes: &[u8]) -> String {
        let ascii = String::from_utf8_lossy(bytes);
        if ascii.contains(Self::MAGIC) {
            return ascii.into_owned();
        }
        // UTF-16: try little-endian then big-endian.
        for be in [false, true] {
            let units: Vec<u16> = bytes
                .chunks_exact(2)
                .map(|c| {
                    if be {
                        u16::from_be_bytes([c[0], c[1]])
                    } else {
                        u16::from_le_bytes([c[0], c[1]])
                    }
                })
                .collect();
            let s = String::from_utf16_lossy(&units);
            if s.contains(Self::MAGIC) {
                return s;
            }
        }
        ascii.into_owned()
    }

    /// Parse a flat INI: lines `key=value` after the `[SemImageFile]` header.
    fn parse_ini(text: &str) -> HashMap<String, String> {
        let mut map = HashMap::new();
        let mut in_section = false;
        for line in text.lines() {
            let line = line.trim();
            if line.starts_with('[') && line.ends_with(']') {
                in_section = line.eq_ignore_ascii_case(Self::MAGIC);
                continue;
            }
            if !in_section {
                continue;
            }
            if let Some((k, v)) = line.split_once('=') {
                map.insert(k.trim().to_string(), v.trim().to_string());
            }
        }
        map
    }
}

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

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

    fn is_this_type_by_bytes(&self, header: &[u8]) -> bool {
        // Accept ASCII or UTF-16 occurrences of the magic.
        Self::decode_header(header).contains(Self::MAGIC)
    }

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        // If handed the companion pixels file, redirect to the sibling .txt
        // (Java initFile() does the same).
        let txt_path = if path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.eq_ignore_ascii_case("txt"))
            .unwrap_or(false)
        {
            path.to_path_buf()
        } else {
            path.with_extension("txt")
        };

        let bytes = std::fs::read(&txt_path).map_err(BioFormatsError::Io)?;
        let text = Self::decode_header(&bytes);
        if !text.contains(Self::MAGIC) {
            return Err(BioFormatsError::UnsupportedFormat(
                "Hitachi: missing [SemImageFile] section".into(),
            ));
        }
        let ini = Self::parse_ini(&text);

        // Resolve the pixels file: stored ImageName next to the .txt, else
        // fall back to a same-base .tif/.jpg/.bmp.
        let parent = txt_path.parent().unwrap_or_else(|| Path::new("."));
        let mut pixels_file: Option<PathBuf> = None;
        if let Some(name) = ini.get("ImageName") {
            let candidate = parent.join(name);
            if candidate.exists() {
                pixels_file = Some(candidate);
            }
        }
        if pixels_file.is_none() {
            for ext in ["tif", "jpg", "bmp"] {
                let candidate = txt_path.with_extension(ext);
                if candidate.exists() {
                    pixels_file = Some(candidate);
                    break;
                }
            }
        }
        let pixels_file = pixels_file.ok_or_else(|| {
            BioFormatsError::UnsupportedFormat("Hitachi: could not find pixels file".into())
        })?;

        // Delegate to the auto-detecting reader for the companion image.
        let mut helper = crate::registry::ImageReader::open(&pixels_file)?;
        let mut meta = helper.metadata().clone();
        helper.close().ok();

        // Carry the [SemImageFile] metadata into series_metadata.
        for (k, v) in &ini {
            meta.series_metadata.insert(
                k.clone(),
                crate::common::metadata::MetadataValue::String(v.clone()),
            );
        }
        meta.series_metadata.insert(
            "format".into(),
            crate::common::metadata::MetadataValue::String("Hitachi".into()),
        );

        self.ini = ini;
        self.pixels_file = Some(pixels_file);
        self.path = Some(txt_path);
        self.meta = Some(meta);
        Ok(())
    }

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

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

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

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

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

    fn open_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let pixels = self
            .pixels_file
            .clone()
            .ok_or(BioFormatsError::NotInitialized)?;
        let mut helper = crate::registry::ImageReader::open(&pixels)?;
        let bytes = helper.open_bytes(plane_index);
        helper.close().ok();
        bytes
    }

    fn open_bytes_region(
        &mut self,
        plane_index: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> Result<Vec<u8>> {
        let pixels = self
            .pixels_file
            .clone()
            .ok_or(BioFormatsError::NotInitialized)?;
        let mut helper = crate::registry::ImageReader::open(&pixels)?;
        let bytes = helper.open_bytes_region(plane_index, x, y, w, h);
        helper.close().ok();
        bytes
    }

    fn open_thumb_bytes(&mut self, plane_index: u32) -> Result<Vec<u8>> {
        let pixels = self
            .pixels_file
            .clone()
            .ok_or(BioFormatsError::NotInitialized)?;
        let mut helper = crate::registry::ImageReader::open(&pixels)?;
        let bytes = helper.open_thumb_bytes(plane_index);
        helper.close().ok();
        bytes
    }

    fn resolution_count(&self) -> usize {
        1
    }

    fn set_resolution(&mut self, level: usize) -> Result<()> {
        if level != 0 {
            Err(BioFormatsError::Format(format!(
                "resolution {} out of range",
                level
            )))
        } else {
            Ok(())
        }
    }
}

// ===========================================================================
// LEO / Zeiss EM — TIFF with proprietary LEO tag (34118)
// ===========================================================================

/// LEO EM reader (`.sxm`, `.tif`, `.tiff`).
///
/// Ported from `LEOReader.java` (extends `BaseTiffReader`). LEO files are
/// ordinary TIFFs distinguished by the presence of private tag 34118
/// (`LEO_TAG`), an ISO-8859-1 text blob of `AP_`/`DP_`/`SV_` key/value lines.
/// Pixel reading is plain TIFF; this reader delegates pixels to `TiffReader`
/// and parses the LEO tag for metadata.
pub struct LeoReader {
    inner: crate::tiff::TiffReader,
    meta: Option<ImageMetadata>,
}

impl LeoReader {
    const LEO_TAG: u16 = 34118;

    pub fn new() -> Self {
        LeoReader {
            inner: crate::tiff::TiffReader::new(),
            meta: None,
        }
    }
}

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

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

    fn is_this_type_by_bytes(&self, _header: &[u8]) -> bool {
        // Like Java (suffixSufficient=false), detection requires opening the
        // TIFF and checking for the LEO tag; header bytes alone are not enough.
        false
    }

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

        // Require the LEO private tag in the first IFD.
        let first = self
            .inner
            .ifd(0)
            .ok_or_else(|| BioFormatsError::UnsupportedFormat("LEO: no IFD".into()))?;
        if first.get(Self::LEO_TAG).is_none() {
            let _ = self.inner.close();
            return Err(BioFormatsError::UnsupportedFormat(
                "LEO: TIFF is missing the LEO tag (34118)".into(),
            ));
        }

        let mut meta = self.inner.metadata().clone();
        meta.series_metadata
            .insert("format".into(), MetadataValue::String("LEO".into()));

        // Parse the LEO tag text: lines of `AP_*`/`DP_*`/`SV_*` keys whose
        // value lives on the following line (Java initStandardMetadata()).
        if let Some(tag_text) = first.get_str(Self::LEO_TAG) {
            let lines: Vec<&str> = tag_text.split('\n').collect();
            let mut i = 0usize;
            while i < lines.len() {
                let t = lines[i].trim();
                if (t.starts_with("AP_") || t.starts_with("DP_") || t.starts_with("SV_"))
                    && i + 1 < lines.len()
                {
                    let sep = if t == "AP_TIME" || t == "AP_DATE" {
                        ':'
                    } else {
                        '='
                    };
                    let val_line = lines[i + 1].trim();
                    if let Some((k, v)) = val_line.split_once(sep) {
                        meta.series_metadata.insert(
                            k.trim().to_string(),
                            MetadataValue::String(v.trim().to_string()),
                        );
                    }
                    i += 2;
                } else {
                    i += 1;
                }
            }
        }

        self.meta = Some(meta);
        Ok(())
    }

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

    fn series_count(&self) -> usize {
        if self.meta.is_some() {
            self.inner.series_count()
        } else {
            0
        }
    }

    fn set_series(&mut self, s: usize) -> Result<()> {
        if self.meta.is_none() {
            return Err(BioFormatsError::NotInitialized);
        }
        self.inner.set_series(s)
    }

    fn series(&self) -> usize {
        self.inner.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>> {
        self.inner.open_bytes(plane_index)
    }

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

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

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

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

// ===========================================================================
// Real binary reader — Zeiss LMS
// ===========================================================================

/// Zeiss LMS reader (`.lms`).
///
/// Supports only the conservative BioFormats-rs strict raw subset identified
/// by `BIOFORMATS-RS-ZEISS-LMS-STRICT-RAW-V1\n`.
pub struct ZeissLmsReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    data_offset: u64,
}

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

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

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

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

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        let (meta, data_offset) = parse_strict_sem_raw(path, ZEISS_LMS_STRICT_MAGIC, "Zeiss LMS")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.data_offset = data_offset;
        Ok(())
    }

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

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

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

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

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

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

        let n_bytes = (meta.size_x as usize)
            .checked_mul(meta.size_y as usize)
            .and_then(|n| n.checked_mul(meta.pixel_type.bytes_per_sample()))
            .ok_or_else(|| BioFormatsError::Format("Zeiss LMS plane size overflows".into()))?;
        let path = self.path.clone().ok_or(BioFormatsError::NotInitialized)?;
        let mut f = std::fs::File::open(&path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(self.data_offset))
            .map_err(BioFormatsError::Io)?;
        let mut buf = vec![0u8; n_bytes];
        f.read_exact(&mut buf).map_err(BioFormatsError::Io)?;
        Ok(buf)
    }

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

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

    fn resolution_count(&self) -> usize {
        1
    }

    fn set_resolution(&mut self, level: usize) -> Result<()> {
        if level != 0 {
            Err(BioFormatsError::Format(format!(
                "resolution {} out of range",
                level
            )))
        } else {
            Ok(())
        }
    }
}

/// IMOD mesh format reader (`.mod`).
///
/// Supports only the conservative BioFormats-rs strict raw subset identified
/// by `BIOFORMATS-RS-IMROD-STRICT-RAW-V1\n`.
pub struct ImrodReader {
    path: Option<PathBuf>,
    meta: Option<ImageMetadata>,
    data_offset: u64,
}

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

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

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

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

    fn set_id(&mut self, path: &Path) -> Result<()> {
        self.close()?;
        let (meta, data_offset) = parse_strict_sem_raw(path, IMROD_STRICT_MAGIC, "IMROD")?;
        self.path = Some(path.to_path_buf());
        self.meta = Some(meta);
        self.data_offset = data_offset;
        Ok(())
    }

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

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

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

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

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

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

        let n_bytes = (meta.size_x as usize)
            .checked_mul(meta.size_y as usize)
            .and_then(|n| n.checked_mul(meta.pixel_type.bytes_per_sample()))
            .ok_or_else(|| BioFormatsError::Format("IMROD plane size overflows".into()))?;
        let path = self.path.clone().ok_or(BioFormatsError::NotInitialized)?;
        let mut f = std::fs::File::open(&path).map_err(BioFormatsError::Io)?;
        f.seek(SeekFrom::Start(self.data_offset))
            .map_err(BioFormatsError::Io)?;
        let mut buf = vec![0u8; n_bytes];
        f.read_exact(&mut buf).map_err(BioFormatsError::Io)?;
        Ok(buf)
    }

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

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

    fn resolution_count(&self) -> usize {
        1
    }

    fn set_resolution(&mut self, level: usize) -> Result<()> {
        if level != 0 {
            Err(BioFormatsError::Format(format!(
                "resolution {} out of range",
                level
            )))
        } else {
            Ok(())
        }
    }
}

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

    /// Build a minimal 256-byte INRIMAGE-4 header followed by raw pixels.
    fn write_inr(dir: &std::path::Path, name: &str, header_body: &str, payload: &[u8]) -> PathBuf {
        let mut header = String::from("#INRIMAGE-4#{\n");
        header.push_str(header_body);
        header.push_str("##}\n");
        let mut bytes = header.into_bytes();
        assert!(bytes.len() <= 256, "test header exceeds 256 bytes");
        bytes.resize(256, b'\n');
        bytes.extend_from_slice(payload);
        let path = dir.join(name);
        let mut f = std::fs::File::create(&path).unwrap();
        f.write_all(&bytes).unwrap();
        path
    }

    /// VDIM must map to size_t (Java INRReader.java:124-126), size_c forced to 1,
    /// dimension order XYZTC (Java line 160), image_count = z*t*c (line 157).
    #[test]
    fn vdim_maps_to_size_t() {
        let tmp = std::env::temp_dir();
        // 2x2 plane, ZDIM=3, VDIM=4 -> z=3,t=4,c=1,count=12, 8-bit unsigned
        let body = "XDIM=2\nYDIM=2\nZDIM=3\nVDIM=4\nPIXSIZE=8 bits\nTYPE=unsigned fixed\n";
        let payload = vec![0u8; 2 * 2 * 3 * 4];
        let path = write_inr(&tmp, "inr_vdim_test.inr", body, &payload);

        let mut r = InrReader::new();
        r.set_id(&path).unwrap();
        let m = r.metadata();
        assert_eq!(m.size_z, 3);
        assert_eq!(m.size_t, 4, "VDIM should populate size_t");
        assert_eq!(m.size_c, 1, "size_c must be forced to 1");
        assert_eq!(m.image_count, 12, "image_count = z*t*c");
        assert_eq!(m.dimension_order, DimensionOrder::XYZTC);
        assert_eq!(m.pixel_type, PixelType::Uint8);
        let _ = std::fs::remove_file(&path);
    }

    /// Pixel type derives from byte width + signed flag (Java line 158-159);
    /// 8 bytes maps to Float64/DOUBLE, never a 32-bit Float branch.
    #[test]
    fn pixel_type_by_byte_width() {
        let tmp = std::env::temp_dir();
        let cases: &[(&str, u32, PixelType)] = &[
            ("signed fixed", 8, PixelType::Int8),
            ("unsigned fixed", 8, PixelType::Uint8),
            ("signed fixed", 16, PixelType::Int16),
            ("unsigned fixed", 16, PixelType::Uint16),
            ("signed fixed", 32, PixelType::Int32),
            ("unsigned fixed", 32, PixelType::Uint32),
            ("float", 64, PixelType::Float64),
            // 32-bit float has no Java-specific branch; width 4 unsigned -> Uint32
            ("float", 32, PixelType::Uint32),
        ];
        for (i, (ty, bits, expected)) in cases.iter().enumerate() {
            let body = format!("XDIM=1\nYDIM=1\nPIXSIZE={} bits\nTYPE={}\n", bits, ty);
            let payload = vec![0u8; (bits / 8) as usize];
            let name = format!("inr_pt_{}.inr", i);
            let path = write_inr(&tmp, &name, &body, &payload);
            let mut r = InrReader::new();
            r.set_id(&path).unwrap();
            assert_eq!(r.metadata().pixel_type, *expected, "case {}: {} {}", i, ty, bits);
            let _ = std::fs::remove_file(&path);
        }
    }
}