fits-io 0.2.0

A pure-Rust FITS file reading and writing library inspired by CFITSIO, focused on safety, clarity, and performance.
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
use crate::ascii_table::AsciiColumnFormat;
use crate::header::card::Card;
use crate::header::card_keys;
use crate::header::extension_type::ExtensionType;
use crate::header::value::Value;
use crate::header::{BayerPattern, Bitpix, ImageType, TableColumnFormat, TableNullValue};
use crate::util::ReadSeek;
use chrono::{DateTime, Utc};
use std::error::Error;
use std::fmt::Formatter;
use std::io::Read;
use std::{fmt, vec};

pub(crate) const CARD_NUM_BYTES: usize = 80;

/// FITS files are laid out in blocks of this many bytes; headers and data
/// sections are both padded up to a whole number of them.
pub(crate) const BLOCK_NUM_BYTES: usize = 2880;

/// Joins each value that was split across CONTINUE cards back into one card.
///
/// The convention marks a value as continuing by ending it with `&`, which the
/// next CONTINUE card carries on from. Left unjoined, a long value reads as
/// whatever fitted on its first card, `&` and all.
fn join_continuations(cards: Vec<Card>) -> Vec<Card> {
    let mut joined: Vec<Card> = Vec::with_capacity(cards.len());

    for card in cards {
        let Card::Continuation { string, comment } = &card else {
            joined.push(card);
            continue;
        };

        // A continuation only belongs to a card whose value said it was coming.
        let continues = joined
            .last_mut()
            .and_then(Card::string_value_mut)
            .filter(|value| value.ends_with('&'));

        let Some(value) = continues else {
            joined.push(card);
            continue;
        };

        value.pop();
        value.push_str(string.as_deref().unwrap_or_default());

        // The comment for the whole value rides on the last continuation.
        if let Some(comment) = comment
            && let Some(last) = joined.last_mut()
        {
            last.set_comment(comment.clone());
        }
    }

    joined
}

/// Whether a keyword describes the table a compressed image is stored in, rather
/// than the image itself.
///
/// The `Z` keywords describe the image and are translated; the table's own
/// structural keywords, and the column definitions, have no meaning once the
/// image is unpacked.
fn describes_the_table(key: &str) -> bool {
    const STRUCTURAL: [&str; 6] = [
        card_keys::XTENSION,
        card_keys::BITPIX,
        card_keys::NAXIS,
        card_keys::PCOUNT,
        card_keys::GCOUNT,
        card_keys::TFIELDS,
    ];

    const COLUMN_PREFIXES: [&str; 9] = [
        card_keys::PREFIX_TFORM_N,
        card_keys::PREFIX_TTYPE_N,
        card_keys::PREFIX_TSCAL_N,
        card_keys::PREFIX_TZERO_N,
        card_keys::PREFIX_TNULL_N,
        card_keys::PREFIX_TDIM_N,
        card_keys::PREFIX_TUNIT_N,
        card_keys::PREFIX_TDISP_N,
        card_keys::PREFIX_TBCOL_N,
    ];

    if STRUCTURAL.contains(&key) {
        return true;
    }

    // Every `Z` keyword either describes the compression or restates a card that
    // `uncompressed` writes fresh, so none of them belong to the image.
    if key.starts_with('Z') {
        return true;
    }

    COLUMN_PREFIXES.iter().any(|prefix| {
        key.strip_prefix(prefix)
            .is_some_and(|index| !index.is_empty() && index.chars().all(|c| c.is_ascii_digit()))
    })
}

/// What a CHECKSUM card holds while the checksum that will replace it is being
/// computed.
///
/// ASCII zeros, not spaces: the encoded value carries an ASCII-zero offset in
/// every one of its sixteen characters, so a placeholder of zeros is what makes
/// swapping it for the real value change the sum by exactly that value. Spaces
/// would leave the result short by the difference.
const BLANK_CHECKSUM: &str = "0000000000000000";

/// Splits free text into the pieces a run of COMMENT or HISTORY cards holds.
///
/// The keyword takes the first eight columns, so seventy-two are left for the
/// text. A line of its own in the text stays a line of its own, and anything
/// longer than a card runs on to the next one.
fn comment_lines(text: &str) -> Vec<String> {
    const ROOM: usize = CARD_NUM_BYTES - 8;

    let mut lines = Vec::new();

    for line in text.lines() {
        let mut rest = line;

        loop {
            if rest.len() <= ROOM {
                lines.push(rest.to_string());
                break;
            }

            // Breaking on a space keeps words whole; a word longer than a card
            // is broken wherever it has to be.
            let mut at = rest[..=ROOM]
                .rfind(char::is_whitespace)
                .unwrap_or(ROOM)
                .max(1);
            while !rest.is_char_boundary(at) {
                at -= 1;
            }

            lines.push(rest[..at].trim_end().to_string());
            rest = rest[at..].trim_start();
        }
    }

    if lines.is_empty() {
        lines.push(String::new());
    }

    lines
}

/// A FITS header: the cards that describe an HDU and its data.
#[derive(Clone, Default)]
pub struct Header {
    cards: Vec<Card>,
    /// How many bytes this header occupied in the file it was read from.
    ///
    /// Joining a continued value takes several cards down to one, so the card
    /// count no longer says how far the data section is from the start of the
    /// header. A header built in memory has no such history and is measured
    /// from its cards.
    bytes_in_file: Option<usize>,
}

impl Header {
    /// How many cards this header writes out as, which is more than it holds
    /// when a value is long enough to need continuing.
    fn written_card_count(&self) -> usize {
        let cards: usize = self
            .cards
            .iter()
            .filter(|card| **card != Card::End)
            .map(|card| card.to_cards().len())
            .sum();

        // `to_bytes` always writes an END card, whether or not one is held.
        cards + 1
    }

    pub(crate) fn bytes_len(&self) -> usize {
        if let Some(bytes) = self.bytes_in_file {
            return bytes;
        }

        let num_bytes = self.written_card_count() * CARD_NUM_BYTES;
        let num_off_bytes = BLOCK_NUM_BYTES - (num_bytes % BLOCK_NUM_BYTES);
        if num_off_bytes == BLOCK_NUM_BYTES {
            num_bytes
        } else {
            num_bytes + num_off_bytes
        }
    }

    /// The AUTHOR card: who prepared the data.
    pub fn author(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Author { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The BITPIX card: the type of the values in the data section.
    ///
    /// BITPIX is mandatory, and a header lacking it is rejected when the file is
    /// opened, so this returns `Some` for any header read from a file. It is
    /// `None` only for a header built by hand and left incomplete.
    pub fn bitpix(&self) -> Option<Bitpix> {
        self.cards.iter().find_map(|card| {
            if let Card::Bitpix { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The BLANK card: the raw value that stands for an undefined pixel.
    ///
    /// The standard defines it only for the integer BITPIX types; a floating point
    /// array says the same thing with a NaN.
    pub fn blank(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::Blank { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The BLOCKED card, a deprecated hint about the file's block size.
    pub fn blocked(&self) -> Option<bool> {
        self.cards.iter().find_map(|card| {
            if let Card::Blocked { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The BSCALE card: the factor a raw array value is multiplied by.
    ///
    /// See [`Header::bscale_or_default`] for the standard's default of 1.
    pub fn bscale(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::BScale { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// BSCALE, defaulting to 1.0 when the card is absent.
    ///
    /// BSCALE is optional; the FITS standard defines its default as 1.0, so a
    /// missing card means unscaled data rather than unknown data.
    pub fn bscale_or_default(&self) -> f64 {
        self.bscale().unwrap_or(1.0)
    }

    /// The BUNIT card: the physical unit the array's values are in.
    pub fn bunit(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::BUnit { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The BZERO card: the offset added to a scaled array value.
    ///
    /// See [`Header::bzero_or_default`] for the standard's default of 0.
    pub fn bzero(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::BZero { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// BZERO, defaulting to 0.0 when the card is absent.
    ///
    /// BZERO is optional; the FITS standard defines its default as 0.0, so a
    /// missing card means unshifted data rather than unknown data.
    pub fn bzero_or_default(&self) -> f64 {
        self.bzero().unwrap_or(0.0)
    }

    /// The DATAMAX card: the largest physical value in the array.
    pub fn data_max(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::DataMax { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The DATAMIN card: the smallest physical value in the array.
    pub fn data_min(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::DataMin { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The DATE card: when the file was written.
    pub fn date(&self) -> Option<&DateTime<Utc>> {
        self.cards.iter().find_map(|card| {
            if let Card::Date { value, .. } = card {
                Some(value)
            } else {
                None
            }
        })
    }

    /// The DATE-OBS card: when the observation was made.
    pub fn date_observed(&self) -> Option<&DateTime<Utc>> {
        self.cards.iter().find_map(|card| {
            if let Card::DateObserved { value, .. } = card {
                Some(value)
            } else {
                None
            }
        })
    }

    /// The EPOCH card, which EQUINOX supersedes.
    pub fn epoch(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::Epoch { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The EQUINOX card: the epoch of the coordinate system, in years.
    pub fn equinox(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::Equinox { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The EXTEND card: whether extensions may follow the primary HDU.
    pub fn extend(&self) -> Option<bool> {
        self.cards.iter().find_map(|card| {
            if let Card::Extend { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The EXTLEVEL card: this extension's level in a hierarchy of them.
    pub fn extension_level(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::ExtensionLevel { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The EXTNAME card: this extension's name.
    pub fn extension_name(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::ExtensionName { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The EXTVER card: this extension's version.
    pub fn extension_version(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::ExtensionVersion { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The GCOUNT card: how many groups the data section holds.
    ///
    /// One for everything but a random-groups HDU.
    pub fn group_count(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::GroupCount { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The GROUPS card: whether this HDU uses the random-groups convention.
    ///
    /// See [`Header::is_random_groups`], which also checks the axis that marks it.
    pub fn groups(&self) -> Option<bool> {
        self.cards.iter().find_map(|card| {
            if let Card::Groups { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The INSTRUME card: the instrument the data came from.
    pub fn instrument(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Instrument { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The NAXIS card: how many axes the data section has.
    ///
    /// NAXIS is mandatory, and a header lacking it is rejected when the file is
    /// opened, so this returns `Some` for any header read from a file. It is
    /// `None` only for a header built by hand and left incomplete.
    pub fn naxis(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::NAxis { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The OBJECT card: what was observed.
    pub fn object(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Object { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The OBSERVER card: who made the observation.
    pub fn observer(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Observer { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The ORIGIN card: the organisation that wrote the file.
    pub fn origin(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Origin { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The PCOUNT card: how many extra values follow the array.
    ///
    /// This is a binary table's heap, or the parameters of a random-groups HDU.
    pub fn pcount(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::ParameterCount { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The REFERENC card: a publication describing the data.
    pub fn reference(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Reference { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The SIMPLE card: whether the file conforms to the FITS standard.
    ///
    /// Only a primary header carries it.
    pub fn simple(&self) -> Option<bool> {
        self.cards.iter().find_map(|card| {
            if let Card::Simple { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The TELESCOP card: the telescope the data came from.
    pub fn telescope(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Telescope { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The TFIELDS card: how many columns the table has.
    pub fn table_fields(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::TableFields { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The THEAP card: where a binary table's heap starts, as a byte offset
    /// into the data section.
    pub fn table_heap(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::TableHeap { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The XTENSION card: which kind of extension this is.
    ///
    /// `None` for a primary header, which is not an extension.
    pub fn extension(&self) -> Option<ExtensionType> {
        self.cards.iter().find_map(|card| {
            if let Card::Xtension { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The FOCALLEN card: the telescope's focal length.
    ///
    /// A widespread convention among astrophotography software rather than part of
    /// the standard, as are the other camera keywords near it.
    pub fn focal_length(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::FocalLength { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The EXPTIME card: how long the exposure lasted.
    pub fn exposure_time(&self) -> Option<std::time::Duration> {
        self.cards.iter().find_map(|card| {
            if let Card::ExposureTime { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The CCD-TEMP card: the sensor's temperature, in degrees Celsius.
    pub fn ccd_temperature(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::CCDTemperature { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The BAYERPAT card: the colour filter layout over the sensor.
    ///
    /// `None` for a monochrome sensor, or one that did not record the pattern.
    pub fn bayer_pattern(&self) -> Option<BayerPattern> {
        self.cards.iter().find_map(|card| {
            if let Card::BayerPattern { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The CREATOR card: the software that wrote the file.
    pub fn creator(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::Creator { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The XORGSUBF card: where a subframe starts on the sensor, horizontally.
    pub fn subframe_x_position_in_binned_pixels(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::SubframeXPositionInBinnedPixels { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The YORGSUBF card: where a subframe starts on the sensor, vertically.
    pub fn subframe_y_position_in_binned_pixels(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::SubframeYPositionInBinnedPixels { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The XBINNING card: how many sensor pixels were binned into one, horizontally.
    pub fn binned_pixels_x(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::BinnedPixelsX { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The YBINNING card: how many sensor pixels were binned into one, vertically.
    pub fn binned_pixels_y(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::BinnedPixelsY { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The CCDXBIN card, another spelling of XBINNING.
    pub fn ccd_binned_pixels_x(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::CCDBinnedPixelsX { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The CCDYBIN card, another spelling of YBINNING.
    pub fn ccd_binned_pixels_y(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::CCDBinnedPixelsY { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The XPIXSZ card: the width of a pixel in microns, binning included.
    pub fn pixel_size_x_with_binning_in_microns(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::PixelSizeXWithBinningInMicrons { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The YPIXSZ card: the height of a pixel in microns, binning included.
    pub fn pixel_size_y_with_binning_in_microns(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::PixelSizeYWithBinningInMicrons { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The IMAGETYP card: whether this is a light, dark, flat or bias frame.
    pub fn image_type(&self) -> Option<&ImageType> {
        self.cards.iter().find_map(|card| {
            if let Card::ImageType { value, .. } = card {
                Some(value)
            } else {
                None
            }
        })
    }

    /// The EXPOSURE card, another spelling of EXPTIME.
    pub fn exposure(&self) -> Option<std::time::Duration> {
        self.cards.iter().find_map(|card| {
            if let Card::Exposure { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The RA card: the right ascension the telescope was pointed at.
    pub fn ra(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::Ra { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The DEC card: the declination the telescope was pointed at.
    pub fn dec(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::Dec { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The GUIDECAM card: the guide camera in use.
    pub fn guide_cam(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::GuideCam { value, .. } = card {
                Some(value.as_str())
            } else {
                None
            }
        })
    }

    /// The FOCUSPOS card: where the focuser was.
    pub fn focus_position(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::FocusPosition { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The SITELONG card: the observing site's longitude.
    pub fn site_longitude(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::SiteLongitude { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The SITELAT card: the observing site's latitude.
    pub fn site_latitude(&self) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::SiteLatitude { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The IMAGEW card: the image's width, as the writing software recorded it.
    pub fn image_width(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::ImageWidth { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The IMAGEH card: the image's height, as the writing software recorded it.
    pub fn image_height(&self) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::ImageHeight { value, .. } = card {
                Some(*value)
            } else {
                None
            }
        })
    }

    /// The CDELTn card for axis `index`: how far the world coordinate moves
    /// per pixel.
    pub fn coordinate_delta(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::CoordinateDeltaN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The CROTAn card for axis `index`: the rotation between the pixel and
    /// world axes, in degrees.
    pub fn coordinate_rotation(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::CoordinateRotationN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The CRPIXn card for axis `index`: the pixel that the reference value
    /// sits at, counting from 1.
    pub fn coordinate_reference_pixel(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::CoordinateReferencePixelN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The CRVALn card for axis `index`: the world coordinate at the
    /// reference pixel.
    pub fn coordinate_value_at_pixel(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::CoordinateValueAtPixelN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The CDi_j card: one element of the matrix taking pixel offsets to
    /// intermediate world coordinates.
    ///
    /// `row` and `column` count from 0, so CD1_1 is `coordinate_transform(0, 0)`.
    /// This matrix carries the scale as well as the rotation, which is why a
    /// header using it has no CDELTn cards.
    pub fn coordinate_transform(&self, row: usize, column: usize) -> Option<f64> {
        self.matrix_element("CD", row, column)
    }

    /// The PCi_j card: one element of the dimensionless matrix that rotates and
    /// skews pixel offsets, before CDELTn scales them.
    ///
    /// `row` and `column` count from 0, so PC1_1 is
    /// `coordinate_rotation_matrix(0, 0)`.
    pub fn coordinate_rotation_matrix(&self, row: usize, column: usize) -> Option<f64> {
        self.matrix_element("PC", row, column)
    }

    /// Reads one element of a two-index keyword family such as CDi_j.
    ///
    /// These are not among the keywords this crate models individually, so they
    /// arrive as plain value cards and are looked up by name.
    fn matrix_element(&self, prefix: &str, row: usize, column: usize) -> Option<f64> {
        let key = format!("{}{}_{}", prefix, row + 1, column + 1);

        self.raw_card(&key)
            .into_iter()
            .find_map(|value| match value {
                Value::Float { value, .. } => Some(value),
                // A whole number is commonly written without a decimal point.
                Value::Integer { value, .. } => Some(value as f64),
                _ => None,
            })
    }

    /// The CTYPEn card for axis `index`: what the axis measures, and the
    /// projection it uses.
    pub fn coordinate_axis_name(&self, index: usize) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::CoordinateAxisNameN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value.as_str());
            };
            None
        })
    }

    /// The NAXISn card for axis `index`: how long that axis is.
    ///
    /// `index` counts from 0, so NAXIS1 is `naxis_n(0)`.
    pub fn naxis_n(&self, index: usize) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::NAxisN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The PSCALn card for group parameter `index`.
    pub fn parameter_scaling_factor(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::ParameterScalingFactorN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The PTYPEn card for group parameter `index`: what it measures.
    pub fn parameter_type(&self, index: usize) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::ParameterTypeN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value.as_str());
            };
            None
        })
    }

    /// The PZEROn card for group parameter `index`.
    pub fn parameter_scaling_zero_point(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::ParameterScalingZeroPointN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The TBCOLn card for column `index`: where the column starts within an
    /// ASCII table's row, counting from 1.
    pub fn table_column(&self, index: usize) -> Option<i64> {
        self.cards.iter().find_map(|card| {
            if let Card::TableColumnN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The TDIMn card for column `index`: the shape of a multidimensional
    /// column, as written.
    pub fn table_dimensions(&self, index: usize) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::TableDimensionsN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value.as_str());
            };
            None
        })
    }

    /// The TDISPn card for column `index`: how the column is best displayed.
    pub fn table_display_format(&self, index: usize) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::TableDisplayFormatN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value.as_str());
            };
            None
        })
    }

    /// The TNULLn card for column `index`: the value that marks an undefined
    /// entry in that column.
    pub fn table_null_value(&self, index: usize) -> Option<&TableNullValue> {
        self.cards.iter().find_map(|card| {
            if let Card::TableNullValueN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value);
            };
            None
        })
    }

    /// The TSCALn card for column `index`: the factor a stored entry is
    /// multiplied by.
    pub fn table_scaling_factor(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::TableScalingFactorN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    /// The TTYPEn card for column `index`: the column's name.
    pub fn table_column_type(&self, index: usize) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::TableTypeN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value.as_str());
            };
            None
        })
    }

    /// The TFORMn card for column `index`, exactly as written.
    pub fn table_format(&self, index: usize) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::TableFormatN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value.as_str());
            };
            None
        })
    }

    /// The TFORMn card for column `index`, read as a binary table format.
    ///
    /// `None` when the card is absent or does not name a binary table format,
    /// which is the case for every ASCII table; use
    /// [`Header::ascii_column_format`] for those.
    pub fn table_column_format(&self, index: usize) -> Option<TableColumnFormat> {
        TableColumnFormat::try_from(self.table_format(index)?.to_string()).ok()
    }

    /// The TFORMn card for column `index`, read as an ASCII table format.
    ///
    /// `None` when the card is absent or does not name an ASCII table format.
    pub fn ascii_column_format(&self, index: usize) -> Option<AsciiColumnFormat> {
        AsciiColumnFormat::try_from(self.table_format(index)?.to_string()).ok()
    }

    /// The TUNITn card for column `index`: the column's physical unit.
    pub fn table_unit(&self, index: usize) -> Option<&str> {
        self.cards.iter().find_map(|card| {
            if let Card::TableUnitN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(value.as_str());
            };
            None
        })
    }

    /// The TZEROn card for column `index`: the offset added after scaling.
    pub fn table_scaling_zero_point(&self, index: usize) -> Option<f64> {
        self.cards.iter().find_map(|card| {
            if let Card::TableScalingZeroPointN {
                value, index: idx, ..
            } = card
                && index == *idx
            {
                return Some(*value);
            };
            None
        })
    }

    pub(crate) fn data_block_len(&self) -> usize {
        let data_size = self.data_bytes_len();

        let num_off_bytes = BLOCK_NUM_BYTES - (data_size % BLOCK_NUM_BYTES);
        if num_off_bytes == BLOCK_NUM_BYTES {
            data_size
        } else {
            data_size + num_off_bytes
        }
    }

    /// Size of this HDU's data section in bytes, excluding block padding.
    ///
    /// This is the standard's
    /// `BITPIX/8 * GCOUNT * (PCOUNT + NAXIS1 * ... * NAXISn)`. PCOUNT matters
    /// for binary tables: it is the size of the heap that follows the rows, and
    /// leaving it out puts the *next* HDU at the wrong offset in every file
    /// whose table has variable length array columns.
    ///
    /// Returns 0 for a header that declares no data, and also for an incomplete
    /// header — a header missing BITPIX, NAXIS or one of its NAXISn cards cannot
    /// describe a data section. [`Header::validate_primary`] and
    /// [`Header::validate_extension`] reject such headers up front, so this
    /// fallback is only reachable for hand-built headers.
    pub(crate) fn data_bytes_len(&self) -> usize {
        let (Some(bitpix), Some(number_of_axis)) = (self.bitpix(), self.naxis()) else {
            return 0;
        };

        if number_of_axis <= 0 {
            return 0;
        }

        let mut elements: usize = 1;
        for axis in 0..number_of_axis {
            // NAXISn is untrusted input: a negative or absurd length must not
            // overflow the running product.
            let Some(length) = self.naxis_n(axis as usize) else {
                return 0;
            };
            let Ok(length) = usize::try_from(length) else {
                return 0;
            };
            let Some(product) = elements.checked_mul(length) else {
                return 0;
            };
            elements = product;
        }

        // PCOUNT and GCOUNT are mandatory on extensions and absent from a
        // conforming primary header, where they are 0 and 1.
        let pcount = self.pcount().unwrap_or(0).max(0) as usize;
        let gcount = self.group_count().unwrap_or(1).max(0) as usize;

        let Some(bytes) = elements.checked_add(pcount) else {
            return 0;
        };
        let Some(bytes) = bytes.checked_mul(gcount) else {
            return 0;
        };
        let Some(bytes) = bytes.checked_mul(bitpix.byte_size()) else {
            return 0;
        };

        bytes
    }

    /// Whether this HDU is an image stored compressed inside a table.
    ///
    /// The tiled image convention keeps a compressed image in a binary table,
    /// one tile per row, and describes the image it stands for with keywords
    /// beginning `Z`. Such an HDU reads as a table unless it is decompressed;
    /// see [`BinTableHDU::read_compressed_image`](crate::hdu::BinTableHDU::read_compressed_image).
    pub fn is_compressed_image(&self) -> bool {
        matches!(
            self.raw_card(card_keys::ZIMAGE).first(),
            Some(Value::Logical { value: true, .. })
        )
    }

    /// The ZBITPIX card: the type of the values in the image once decompressed.
    pub fn compressed_bitpix(&self) -> Option<Bitpix> {
        Bitpix::try_from(self.z_integer(card_keys::ZBITPIX)?).ok()
    }

    /// The ZNAXIS card: how many axes the decompressed image has.
    pub fn compressed_naxis(&self) -> Option<i64> {
        self.z_integer(card_keys::ZNAXIS)
    }

    /// The ZNAXISn card for axis `index`: the decompressed image's length along
    /// it. `index` counts from 0.
    pub fn compressed_naxis_n(&self, index: usize) -> Option<i64> {
        self.z_integer(&format!("{}{}", card_keys::PREFIX_ZNAXIS_N, index + 1))
    }

    /// The ZTILEn card for axis `index`: how far a tile reaches along it.
    ///
    /// The convention's default is a tile one row of the image wide, which is
    /// what a header that leaves the card out means.
    pub fn compressed_tile_size(&self, index: usize) -> i64 {
        if let Some(size) = self.z_integer(&format!("{}{}", card_keys::PREFIX_ZTILE_N, index + 1)) {
            return size;
        }

        match index {
            0 => self.compressed_naxis_n(0).unwrap_or(1),
            _ => 1,
        }
    }

    /// The ZCMPTYPE card: which algorithm the tiles were compressed with.
    pub fn compression_type(&self) -> Option<&str> {
        self.cards.iter().find_map(|card| match card {
            Card::Value {
                name,
                value: Value::String { value, .. },
            } if name == card_keys::ZCMPTYPE => Some(value.as_str()),
            _ => None,
        })
    }

    /// A compression parameter, looked up by the name a ZNAMEn card gives it.
    ///
    /// The algorithms take their settings as name and value pairs rather than as
    /// keywords of their own, so Rice's block size arrives as `ZNAME1 =
    /// 'BLOCKSIZE'` with the value in `ZVAL1`.
    pub fn compression_parameter(&self, name: &str) -> Option<i64> {
        for index in 1.. {
            let key = format!("{}{}", card_keys::PREFIX_ZNAME_N, index);
            let found = self.cards.iter().find_map(|card| match card {
                Card::Value {
                    name: key_name,
                    value: Value::String { value, .. },
                } if *key_name == key => Some(value.clone()),
                _ => None,
            });

            let found = found?;

            if found.trim() == name {
                return self.z_integer(&format!("{}{}", card_keys::PREFIX_ZVAL_N, index));
            }
        }

        None
    }

    /// The ZQUANTIZ card: how a floating point image's values were turned into
    /// the integers the compressor works on.
    ///
    /// `NO_DITHER` quantises plainly; the two `SUBTRACTIVE_DITHER` methods add a
    /// known pseudo-random number to each value before rounding it and take the
    /// same number off again on the way back, which keeps quantisation from
    /// laying a pattern over a smooth background.
    pub fn quantization_method(&self) -> Option<&str> {
        self.z_string(card_keys::ZQUANTIZ)
    }

    /// The ZDITHER0 card: which entry of the dithering sequence the first tile
    /// starts at.
    pub fn dither_seed(&self) -> Option<i64> {
        self.z_integer(card_keys::ZDITHER0)
    }

    /// The ZBLANK card: the quantised value that stands for a pixel the image
    /// does not define.
    ///
    /// A tile may carry its own ZBLANK column instead, which takes precedence
    /// over this for that tile.
    pub fn compressed_blank(&self) -> Option<i64> {
        self.z_integer(card_keys::ZBLANK)
    }

    /// One of the `Z` keywords as a string.
    fn z_string(&self, key: &str) -> Option<&str> {
        self.cards.iter().find_map(|card| match card {
            Card::Value {
                name,
                value: Value::String { value, .. },
            } if name == key => Some(value.as_str()),
            _ => None,
        })
    }

    /// One of the `Z` keywords as an integer.
    ///
    /// None of them are among the keywords this crate models individually, so
    /// they arrive as plain value cards and are looked up by name.
    fn z_integer(&self, key: &str) -> Option<i64> {
        self.raw_card(key)
            .into_iter()
            .find_map(|value| match value {
                Value::Integer { value, .. } => Some(value),
                Value::Float { value, .. } => Some(value as i64),
                _ => None,
            })
    }

    /// How many two-dimensional planes the image inside a compressed table
    /// holds.
    pub(crate) fn compressed_plane_count(&self) -> usize {
        let Some(axes) = self.compressed_naxis() else {
            return 0;
        };

        if axes < 2 {
            return 0;
        }

        let mut planes = 1_usize;
        for axis in 2..axes as usize {
            let length = self.compressed_naxis_n(axis).unwrap_or(0).max(0) as usize;
            let Some(product) = planes.checked_mul(length) else {
                return 0;
            };
            planes = product;
        }

        planes
    }

    /// The header the decompressed image would have.
    ///
    /// Every card that describes the table rather than the image is dropped, and
    /// BITPIX and the NAXISn cards are taken from their `Z` counterparts, so
    /// that the result describes the image the HDU stands for. Anything else the
    /// header carried — WCS keywords especially — comes across untouched.
    pub fn uncompressed(&self) -> Self {
        let mut header = Self {
            cards: self
                .cards
                .iter()
                .filter(|card| !describes_the_table(&card.key()))
                .cloned()
                .collect(),
            bytes_in_file: None,
        };

        header.remove_prefixed(card_keys::PREFIX_NAXIS_N);

        if let Some(bitpix) = self.compressed_bitpix() {
            header.set(Card::Bitpix {
                value: bitpix,
                comment: None,
            });
        }

        let axes = self.compressed_naxis().unwrap_or(0).max(0);
        header.set(Card::NAxis {
            value: axes,
            comment: None,
        });
        for axis in 0..axes as usize {
            header.set(Card::NAxisN {
                index: axis,
                value: self.compressed_naxis_n(axis).unwrap_or(0),
                comment: None,
            });
        }

        header
    }

    /// Whether this HDU uses the random-groups convention.
    ///
    /// Such an HDU's data section is not an image but GCOUNT groups, each one a
    /// run of PCOUNT parameters followed by an array. The convention is marked
    /// by `GROUPS = T`, and by a first axis of length zero standing in for the
    /// axis the groups occupy.
    pub fn is_random_groups(&self) -> bool {
        self.groups() == Some(true) && self.naxis_n(0) == Some(0)
    }

    /// How many values each group's array holds, for a random-groups HDU.
    ///
    /// The first axis is the placeholder that marks the convention, so the array
    /// is the axes after it.
    pub(crate) fn group_array_len(&self) -> usize {
        let Some(axes) = self.naxis() else {
            return 0;
        };

        let mut elements = 1_usize;
        for axis in 1..axes.max(0) as usize {
            let length = self.naxis_n(axis).unwrap_or(0).max(0) as usize;
            let Some(product) = elements.checked_mul(length) else {
                return 0;
            };
            elements = product;
        }

        elements
    }

    /// How many two-dimensional planes an image HDU's data section holds.
    ///
    /// The first two axes are the image; every axis beyond them multiplies the
    /// number of images, so a NAXIS = 4 array with NAXIS3 = 2 and NAXIS4 = 3
    /// holds six planes, not two. An HDU with fewer than two axes holds no
    /// image at all.
    pub(crate) fn image_plane_count(&self) -> usize {
        let Some(axes) = self.naxis() else {
            return 0;
        };

        if axes < 2 {
            return 0;
        }

        let mut planes = 1_usize;
        for axis in 2..axes as usize {
            let length = self.naxis_n(axis).unwrap_or(0).max(0) as usize;

            // A zero-length axis means no data at all, not "ignore this axis".
            let Some(product) = planes.checked_mul(length) else {
                return 0;
            };
            planes = product;
        }

        planes
    }

    /// Byte offset of a binary table's heap from the start of its data section.
    ///
    /// THEAP names it explicitly; a table without that card puts the heap
    /// directly after the last row.
    pub(crate) fn table_heap_offset(&self) -> usize {
        if let Some(offset) = self.table_heap()
            && let Ok(offset) = usize::try_from(offset)
        {
            return offset;
        }

        let rows = |axis| self.naxis_n(axis).unwrap_or(0).max(0) as usize;
        rows(0).saturating_mul(rows(1))
    }

    /// Renders this header as the bytes it occupies in a file.
    ///
    /// The result is always a whole number of 2880-byte blocks, padded with
    /// spaces, and always ends with an END card — a header without one is not a
    /// header a reader can find the end of.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(self.bytes_len());

        for card in &self.cards {
            if card == &Card::End {
                break;
            }
            for written in card.to_cards() {
                bytes.extend_from_slice(&written);
            }
        }

        bytes.extend_from_slice(&Card::End.to_bytes());

        let padding = (BLOCK_NUM_BYTES - bytes.len() % BLOCK_NUM_BYTES) % BLOCK_NUM_BYTES;
        bytes.resize(bytes.len() + padding, b' ');

        bytes
    }

    /// Writes the DATASUM and CHECKSUM cards for an HDU whose data section is
    /// `data`.
    ///
    /// CHECKSUM covers the whole HDU including its own card, so it cannot be
    /// known until the header has been rendered. It is set to blanks here and
    /// filled in by [`Header::checksummed_bytes`] once there is a header to sum.
    pub(crate) fn set_checksum_placeholders(&mut self, data: &[u8]) {
        self.set(Card::Value {
            name: card_keys::DATASUM.to_string(),
            value: Value::String {
                value: crate::checksum::sum32(data, 0).to_string(),
                comment: Some("checksum of the data section".into()),
            },
        });
        self.set(Card::Value {
            name: card_keys::CHECKSUM.to_string(),
            value: Value::String {
                value: BLANK_CHECKSUM.to_string(),
                comment: Some("checksum of the whole HDU".into()),
            },
        });
    }

    /// This header rendered with a CHECKSUM that is correct for it and `data`.
    ///
    /// The card is written blank, the whole HDU is summed, and the card is then
    /// filled in with the complement of that sum — so that summing the finished
    /// HDU gives all ones. The blank value and the final one are the same width,
    /// so filling it in does not move anything.
    pub(crate) fn checksummed_bytes(&self, data: &[u8]) -> Vec<u8> {
        let mut header = self.clone();
        header.set_checksum_placeholders(data);

        let blank = header.to_bytes();

        let sum = crate::checksum::sum32(data, crate::checksum::sum32(&blank, 0));
        let checksum = crate::checksum::encode(crate::checksum::complement(sum));

        header.set(Card::Value {
            name: card_keys::CHECKSUM.to_string(),
            value: Value::String {
                value: checksum,
                comment: Some("checksum of the whole HDU".into()),
            },
        });

        let bytes = header.to_bytes();
        debug_assert_eq!(
            bytes.len(),
            blank.len(),
            "filling in the checksum must not change the header's length"
        );

        bytes
    }

    /// Sets the NAXISn card for axis `index`, which counts from 0.
    ///
    /// # Errors
    ///
    /// Returns an error for a negative length, which no axis can have.
    pub fn set_naxis_n(
        &mut self,
        index: usize,
        length: i64,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        if length < 0 {
            return Err(format!("An axis cannot be {} long", length).into());
        }

        self.set(Card::NAxisN {
            index,
            value: length,
            comment: None,
        });

        Ok(())
    }

    /// Checks that this header describes a data section of `actual` bytes.
    ///
    /// The header is the only thing that says how to read the data after it, so
    /// one that disagrees with what follows produces a file nothing can read:
    /// the next HDU is looked for at the wrong offset, and the array comes back
    /// the wrong shape. Setting an image or a table keeps the two in step, but a
    /// caller who edits NAXISn through [`Header::header_mut`] can put them out
    /// of step again, and this is where that is caught.
    ///
    /// This can only catch an HDU that carries its own data. Where the data is
    /// still in a file, the header is what says how much of it to read, so the
    /// two cannot disagree — a header edited to describe more than the file
    /// holds fails when the read runs off the end instead.
    ///
    /// [`Header::header_mut`]: crate::hdu::HDU::header_mut
    pub(crate) fn validate_against_data(
        &self,
        actual: usize,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        let declared = self.data_bytes_len();

        // The data section is padded out to whole blocks, so anything from the
        // declared length up to the end of its last block is consistent.
        let padded = declared.div_ceil(BLOCK_NUM_BYTES) * BLOCK_NUM_BYTES;

        if actual < declared || actual > padded {
            return Err(format!(
                "This header describes {} bytes of data, but the HDU holds {}. A header that \
                 disagrees with its data produces a file that cannot be read back.",
                declared, actual
            )
            .into());
        }

        Ok(())
    }

    /// This header with its mandatory cards present and in the order the FITS
    /// standard requires.
    ///
    /// The standard is strict about the front of a header: a primary header
    /// opens with SIMPLE, BITPIX, NAXIS and then one NAXISn per axis, and an
    /// extension header opens with XTENSION and continues through PCOUNT and
    /// GCOUNT. A reader is entitled to reject anything else, so a header that is
    /// being written out is put in that order here rather than left however it
    /// was assembled.
    ///
    /// Missing mandatory cards are filled in with the values the standard
    /// defines: a header built from nothing has no SIMPLE card at all, and a
    /// file written from one would not be readable.
    ///
    /// `extension` names the kind of extension this header belongs to, or
    /// `None` for the primary header.
    pub(crate) fn conformed(&self, extension: Option<ExtensionType>) -> Self {
        let mut mandatory = Vec::new();

        match extension {
            None => mandatory.push(Card::Simple {
                // A file this crate wrote conforms to the standard, so SIMPLE is
                // true even if the header it came from said otherwise.
                value: true,
                comment: self.comment_for(card_keys::SIMPLE),
            }),
            Some(extension) => mandatory.push(Card::Xtension {
                value: extension,
                comment: self.comment_for(card_keys::XTENSION),
            }),
        }

        mandatory.push(Card::Bitpix {
            value: self.bitpix().unwrap_or(Bitpix::U8),
            comment: self.comment_for(card_keys::BITPIX),
        });

        let axes = self.naxis().unwrap_or(0).max(0);
        mandatory.push(Card::NAxis {
            value: axes,
            comment: self.comment_for(card_keys::NAXIS),
        });

        for axis in 0..axes as usize {
            mandatory.push(Card::NAxisN {
                index: axis,
                value: self.naxis_n(axis).unwrap_or(0),
                comment: self.comment_for(&format!("{}{}", card_keys::PREFIX_NAXIS_N, axis + 1)),
            });
        }

        // PCOUNT and GCOUNT are mandatory on every extension and are not written
        // in a conforming primary header.
        if extension.is_some() {
            mandatory.push(Card::ParameterCount {
                value: self.pcount().unwrap_or(0),
                comment: self.comment_for(card_keys::PCOUNT),
            });
            mandatory.push(Card::GroupCount {
                value: self.group_count().unwrap_or(1),
                comment: self.comment_for(card_keys::GCOUNT),
            });
        }

        // A table's TFIELDS belongs immediately after GCOUNT.
        if matches!(
            extension,
            Some(ExtensionType::BinTable | ExtensionType::AsciiTable)
        ) {
            mandatory.push(Card::TableFields {
                value: self.table_fields().unwrap_or(0),
                comment: self.comment_for(card_keys::TFIELDS),
            });
        }

        let placed: Vec<String> = mandatory.iter().map(Card::key).collect();

        // Everything else keeps the order it already had, minus the cards that
        // have just been placed at the front and any END, which `to_bytes` adds.
        let rest = self
            .cards
            .iter()
            .filter(|card| **card != Card::End && !placed.contains(&card.key()));

        Self {
            cards: mandatory.iter().cloned().chain(rest.cloned()).collect(),
            // A header being written out is measured by what it writes.
            bytes_in_file: None,
        }
    }

    /// The comment on the existing card for `key`, so that rewriting a header
    /// does not throw away what its cards said about themselves.
    fn comment_for(&self, key: &str) -> Option<String> {
        self.cards
            .iter()
            .find(|card| card.key() == key)
            .and_then(|card| match Value::from(card) {
                Value::Integer { comment, .. }
                | Value::Float { comment, .. }
                | Value::Logical { comment, .. }
                | Value::String { comment, .. } => comment,
                _ => None,
            })
    }

    /// Replaces the card for `key`, or adds it before the END card.
    ///
    /// Writing an image means bringing BITPIX and the NAXISn cards into line
    /// with the data, and those cards are already there in a header that was
    /// read from a file.
    pub(crate) fn set(&mut self, card: Card) {
        let key = card.key();

        if let Some(existing) = self.cards.iter_mut().find(|existing| existing.key() == key) {
            *existing = card;
            return;
        }

        match self.cards.iter().position(|card| card == &Card::End) {
            Some(end) => self.cards.insert(end, card),
            None => self.cards.push(card),
        }
    }

    /// Removes every indexed card whose keyword starts with `prefix`, such as
    /// every TFORMn.
    ///
    /// The index has to be there: `NAXIS` is not one of the `NAXISn` cards, and
    /// removing it along with them would leave a header that no longer says how
    /// many axes it has.
    pub(crate) fn remove_prefixed(&mut self, prefix: &str) {
        self.cards.retain(|card| {
            let key = card.key();
            let Some(index) = key.strip_prefix(prefix) else {
                return true;
            };

            !(!index.is_empty() && index.chars().all(|c| c.is_ascii_digit()))
        });
    }

    /// Every card with the keyword `key`, as raw values.
    ///
    /// Most keywords appear once, but COMMENT and HISTORY may repeat, and an
    /// unrecognised keyword can appear as often as the writer liked.
    pub fn raw_card(&self, key: &str) -> Vec<Value> {
        self.cards
            .iter()
            .filter_map(|card| {
                if key == card.key() {
                    Some(Value::from(card))
                } else {
                    None
                }
            })
            .collect()
    }

    /// The value of the card with the keyword `key`, if there is one.
    ///
    /// Where a keyword repeats — COMMENT and HISTORY do, and an unrecognised one
    /// may — this is the first of them; [`Header::raw_card`] returns them all.
    ///
    /// ```
    /// # use fits_io::header::Header;
    /// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let mut header = Header::default();
    /// header.set_card("OBJECT", "M31")?;
    ///
    /// assert_eq!(header.card("OBJECT").map(|v| v.value_to_string()), Some("M31".into()));
    /// assert!(header.card("MISSING").is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn card(&self, key: &str) -> Option<Value> {
        self.cards
            .iter()
            .find(|card| card.key() == key)
            .map(Value::from)
    }

    /// Whether this header carries a card with the keyword `key`.
    pub fn contains_card(&self, key: &str) -> bool {
        self.cards.iter().any(|card| card.key() == key)
    }

    /// Every keyword this header holds, in the order the cards are in.
    ///
    /// A repeated keyword appears once per card, and the blank keyword of a
    /// COMMENT-style card with no keyword appears as an empty string.
    pub fn card_keys(&self) -> impl Iterator<Item = String> + '_ {
        self.cards
            .iter()
            .filter(|card| **card != Card::End)
            .map(Card::key)
    }

    /// Sets the card with the keyword `key` to `value`, adding it if the header
    /// does not already have one.
    ///
    /// The value may be any of the types a FITS card can hold — an integer, a
    /// float, a bool, a string, or `None` for a keyword written with no value —
    /// and [`Value::with_comment`] puts a comment beside it.
    ///
    /// A keyword of up to eight characters drawn from `A`–`Z`, `0`–`9`, `-` and
    /// `_` is written as an ordinary card, upper-cased on the way in. A longer
    /// or otherwise unconventional keyword is written with the `HIERARCH`
    /// convention, which keeps its case. Setting a keyword this crate reads
    /// through one of its typed accessors — `OBJECT`, `DATE-OBS`, `BUNIT` and
    /// the rest — leaves that accessor returning the new value.
    ///
    /// # Errors
    ///
    /// Returns an error for a keyword that is empty, holds characters a card
    /// cannot carry, or is one of the repeatable and structural keywords that
    /// have setters of their own: use [`Header::add_comment`],
    /// [`Header::add_history`] and [`Header::set_naxis_n`] for those. Also
    /// returns an error when the value is too long for the one card it has to
    /// fit on — a long *string* is written across CONTINUE cards instead and is
    /// never too long.
    ///
    /// ```
    /// # use fits_io::header::{Header, Value};
    /// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let mut header = Header::default();
    ///
    /// header.set_card("OBJECT", "NGC 7000")?;
    /// header.set_card("EXPTIME", Value::from(120.0).with_comment("seconds"))?;
    /// header.set_card("MOONLIT", true)?;
    ///
    /// // A keyword too long for the eight columns a card gives it becomes a
    /// // HIERARCH card.
    /// header.set_card("ESO INS FILT1 NAME", "Halpha")?;
    ///
    /// assert_eq!(header.object(), Some("NGC 7000"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_card(
        &mut self,
        key: &str,
        value: impl Into<Value>,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        self.set(Self::card_for(key, value.into())?);
        Ok(())
    }

    /// Removes every card with the keyword `key`, and says how many went.
    ///
    /// A mandatory card removed this way comes back when the header is written:
    /// SIMPLE, BITPIX, NAXIS and the rest are filled in from the data whatever
    /// the cards say.
    pub fn remove_card(&mut self, key: &str) -> usize {
        let before = self.cards.len();
        self.cards.retain(|card| card.key() != key);
        before - self.cards.len()
    }

    /// Adds a COMMENT card carrying `text`.
    ///
    /// COMMENT cards repeat, so this always adds one rather than replacing what
    /// is there. Text too long for a card is split across as many as it needs.
    pub fn add_comment(&mut self, text: impl AsRef<str>) {
        for line in comment_lines(text.as_ref()) {
            self.push(Card::Comment(line));
        }
    }

    /// Adds a HISTORY card carrying `text`.
    ///
    /// As with [`Header::add_comment`], this adds rather than replaces, and text
    /// too long for one card is split across several.
    pub fn add_history(&mut self, text: impl AsRef<str>) {
        for line in comment_lines(text.as_ref()) {
            self.push(Card::History(line));
        }
    }

    /// The text of every COMMENT card, in order.
    pub fn comments(&self) -> impl Iterator<Item = &str> {
        self.cards.iter().filter_map(|card| match card {
            Card::Comment(text) => Some(text.as_str()),
            _ => None,
        })
    }

    /// The text of every HISTORY card, in order.
    pub fn history(&self) -> impl Iterator<Item = &str> {
        self.cards.iter().filter_map(|card| match card {
            Card::History(text) => Some(text.as_str()),
            _ => None,
        })
    }

    /// The card `key` and `value` should be written as.
    ///
    /// A keyword the fixed format can hold becomes an ordinary card, and one it
    /// cannot becomes a HIERARCH card.
    fn card_for(key: &str, value: Value) -> Result<Card, Box<dyn Error + Send + Sync>> {
        const RESERVED: [&str; 5] = [
            card_keys::COMMENT,
            card_keys::HISTORY,
            card_keys::END,
            "CONTINUE",
            "HIERARCH",
        ];

        let key = key.trim();

        if key.is_empty() {
            return Err("A card needs a keyword, and this one is empty".into());
        }

        let upper = key.to_ascii_uppercase();

        if RESERVED.contains(&upper.as_str()) {
            return Err(format!(
                "{} cards are not set by keyword: use add_comment, add_history, or let the \
                 header write END and CONTINUE itself",
                upper
            )
            .into());
        }

        if upper
            .strip_prefix(card_keys::PREFIX_NAXIS_N)
            .is_some_and(|index| !index.is_empty() && index.chars().all(|c| c.is_ascii_digit()))
        {
            return Err(format!(
                "{} says how much data follows the header, so it is set with set_naxis_n and \
                 checked against the data",
                upper
            )
            .into());
        }

        if !key.chars().all(|c| (' '..='~').contains(&c)) {
            return Err(format!(
                "A FITS keyword holds only printable ASCII, but {:?} does not",
                key
            )
            .into());
        }

        let conventional = upper.len() <= 8
            && upper
                .chars()
                .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '-' || c == '_');

        let card = if conventional {
            Self::specialised(Card::Value { name: upper, value })
        } else {
            if key.contains('=') || key.contains('\'') {
                return Err(format!(
                    "A HIERARCH keyword cannot hold a quote or an equals sign, but {:?} does",
                    key
                )
                .into());
            }

            Card::Hierarch {
                name: key.to_string(),
                value,
            }
        };

        // A string is written across CONTINUE cards when it does not fit, so
        // only the cards that have to fit on one are measured. A HIERARCH card
        // has no continuation convention and always has to fit.
        let continues = matches!(Value::from(&card), Value::String { .. })
            && !matches!(card, Card::Hierarch { .. });

        if !continues && card.text_len() > CARD_NUM_BYTES {
            return Err(format!(
                "{} = {} needs {} bytes, and a card holds {}",
                card.key(),
                Value::from(&card).value_to_string(),
                card.text_len(),
                CARD_NUM_BYTES
            )
            .into());
        }

        Ok(card)
    }

    /// The typed card for a keyword this crate knows, or the generic card it was
    /// given.
    ///
    /// The typed accessors match on their own variants, so a card set by keyword
    /// has to become one of those variants for `header.object()` to see an
    /// OBJECT that was set by name. Rendering the card and reading it back is
    /// what the file itself would do, so it produces exactly the variant a
    /// round trip through a file would. It is only adopted when the value
    /// survives that trip — a value the fixed format cannot hold keeps the
    /// generic card, which writes it as given.
    fn specialised(card: Card) -> Card {
        match Card::try_from(&card.to_bytes()) {
            Ok(parsed)
                if parsed.key() == card.key() && Value::from(&parsed) == Value::from(&card) =>
            {
                parsed
            }
            _ => card,
        }
    }

    /// Adds `card` before the END card, keeping any card with the same keyword.
    fn push(&mut self, card: Card) {
        match self.cards.iter().position(|card| card == &Card::End) {
            Some(end) => self.cards.insert(end, card),
            None => self.cards.push(card),
        }
    }

    pub(crate) fn from_reader(
        reader: &mut Box<dyn ReadSeek>,
    ) -> Result<Option<Self>, Box<dyn Error + Send + Sync>> {
        let cards = Self::read_all_cards(reader)?;

        if let Some(Card::End) = cards.last() {
            let bytes_in_file = {
                let bytes = cards.len() * CARD_NUM_BYTES;
                let over = bytes % BLOCK_NUM_BYTES;
                if over == 0 {
                    bytes
                } else {
                    bytes + BLOCK_NUM_BYTES - over
                }
            };

            Ok(Some(Self {
                cards: join_continuations(cards),
                bytes_in_file: Some(bytes_in_file),
            }))
        } else {
            Ok(None)
        }
    }

    pub(crate) fn validate_primary(&self) -> Result<(), Box<dyn Error + Send + Sync>> {
        if self.simple().is_none() {
            return Err("This is not a valid fits file. Card SIMPLE is missing".into());
        }
        if let Some(false) = self.simple() {
            return Err(
                "This is not a valid fits file. It must contain card simple with value true".into(),
            );
        }
        self.validate_structure("fits file")?;

        Ok(())
    }

    pub(crate) fn validate_extension(&self) -> Result<(), Box<dyn Error + Send + Sync>> {
        if self.extension().is_none() {
            return Err("This is not a valid fits extension. Card XTENSION is missing".into());
        }
        self.validate_structure("fits extension")?;

        Ok(())
    }

    /// Checks the structural cards every HDU must carry: BITPIX, NAXIS and one
    /// NAXISn per axis.
    ///
    /// Callers rely on this: once a header has been validated, [`Header::bitpix`],
    /// [`Header::naxis`] and [`Header::naxis_n`] are known to return `Some`, and
    /// [`Header::data_bytes_len`] is known to describe the real data section.
    fn validate_structure(&self, kind: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
        if self.bitpix().is_none() {
            return Err(format!("This is not a valid {}. Card BITPIX is missing", kind).into());
        }

        let Some(number_of_axis) = self.naxis() else {
            return Err(format!("This is not a valid {}. Card NAXIS is missing", kind).into());
        };

        if number_of_axis < 0 {
            return Err(format!(
                "This is not a valid {}. Card NAXIS must not be negative, but was {}",
                kind, number_of_axis
            )
            .into());
        }

        for axis in 0..number_of_axis {
            let Some(length) = self.naxis_n(axis as usize) else {
                return Err(format!(
                    "This is not a valid {}. NAXIS is {} but card NAXIS{} is missing",
                    kind,
                    number_of_axis,
                    axis + 1
                )
                .into());
            };

            if length < 0 {
                return Err(format!(
                    "This is not a valid {}. Card NAXIS{} must not be negative, but was {}",
                    kind,
                    axis + 1,
                    length
                )
                .into());
            }
        }

        Ok(())
    }

    fn read_all_cards(
        reader: &mut Box<dyn ReadSeek>,
    ) -> Result<Vec<Card>, Box<dyn Error + Send + Sync>> {
        let mut block = [0_u8; BLOCK_NUM_BYTES];
        let mut cards = vec![];

        while Self::read_block(reader, &mut block)? {
            // `as_chunks` hands back fixed-size arrays, so there is nothing to
            // convert and no length to assert.
            for card in block.as_chunks::<CARD_NUM_BYTES>().0 {
                let card = Card::try_from(card)?;

                let is_end = card == Card::End;
                cards.push(card);

                // Everything after END is padding.
                if is_end {
                    return Ok(cards);
                }
            }
        }

        Ok(cards)
    }

    /// Fills `block` with exactly one 2880-byte FITS block.
    ///
    /// Returns `false` at a clean end of file. `Read::read` is free to return
    /// fewer bytes than asked for even mid-file, so the read is repeated until
    /// the block is full; stopping early would misalign every following card.
    fn read_block(
        reader: &mut Box<dyn ReadSeek>,
        block: &mut [u8; BLOCK_NUM_BYTES],
    ) -> Result<bool, Box<dyn Error + Send + Sync>> {
        let mut filled = 0;

        while filled < BLOCK_NUM_BYTES {
            match reader.read(&mut block[filled..])? {
                0 if filled == 0 => return Ok(false),
                0 => {
                    return Err(format!(
                        "Truncated FITS header: a block is {} bytes but only {} were left",
                        BLOCK_NUM_BYTES, filled
                    )
                    .into());
                }
                bytes => filled += bytes,
            }
        }

        Ok(true)
    }
}

impl fmt::Debug for Header {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "Flexible Image Transport System (FITS) Data Unit Header:"
        )?;
        for card in &self.cards {
            if card != &Card::End {
                let value = Value::from(card);
                writeln!(
                    f,
                    "{: <8} = {: >72} / {}",
                    card.key(),
                    value.value_to_string(),
                    value.comment_to_string()
                )?;
            } else {
                write!(f, "END")?;
            }
        }

        Ok(())
    }
}