nanalogue 0.1.9

BAM/Mod BAM parsing and analysis tool with a single-molecule focus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
//! # Makes a table of information on reads
//!
//! This file contains routines used to calculate some information per
//! read such as sequence length, alignment length, type of alignment,
//! and modification counts, and displays them in table using the run
//! function. The routine reads both BAM and sequencing summary files
//! if provided, otherwise only reads the BAM file.

use crate::{
    CurrRead, Error, InputMods, ModChar, OptionalTag, ReadState, SeqCoordCalls, SeqDisplayOptions,
    ThresholdState,
};
use csv::ReaderBuilder;
use itertools::join;
use polars::prelude::*;
use rust_htslib::bam;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fmt, fs::File, iter, rc::Rc, str};

/// Write a vector as a CSV-formatted string
macro_rules! vec_csv {
    ( $b: expr ) => {
        join($b, ", ")
    };
}

/// Declare a custom type for ease of use
#[derive(Debug, Clone, PartialEq)]
struct ModCountTbl(HashMap<ModChar, u32>);

/// Implements a constructor
impl ModCountTbl {
    /// construct from a hashmap given as input
    fn new(value: HashMap<ModChar, u32>) -> Self {
        Self(value)
    }
}

/// Implements a display method
impl fmt::Display for ModCountTbl {
    /// display contents as key:value separated by semicolons.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut v: Vec<(ModChar, u32)> = self.0.clone().into_iter().collect();
        v.sort_by_key(|k| k.0);
        (if v.is_empty() {
            "NA".to_owned()
        } else {
            join(v.into_iter().map(|k| format!("{}:{}", k.0, k.1)), ";")
        })
        .fmt(f)
    }
}

/// Enum with instructions on how a base should be formatted
#[derive(Debug, Clone, PartialEq)]
enum BaseFmt {
    /// No special formatting needed
    No,
    /// Show as lowercase
    LowerCase,
    /// Show as highlight
    Highlight,
    /// Show as lowercase, highlight
    LowerCaseHighlight,
}

/// Enum showing state of a read composed from BAM and optionally
/// a sequencing summary file.
/// - only BAM file alignment information is available
/// - only sequencing summary file information is available
/// - both are available
#[derive(Debug, Clone, PartialEq)]
enum ReadInstance {
    /// Only information from the alignment file is available.
    /// NOTE that these are vectors as a read can have multiple BAM records.
    /// Sequencing length is not a vector as it is supposed to be unique.
    /// If multiple BAM records of one read have different sequencing lengths,
    /// we will have to make a choice.
    OnlyAlign {
        /// Alignment length from the BAM file
        align_len: Vec<u64>,
        /// Sequence length from the BAM file
        seq_len: u64,
        /// Count of various mods from the BAM file
        mod_count: Vec<ModCountTbl>,
        /// Alignment type (primary, secondary, reverse etc.) from the BAM file.
        read_state: Vec<ReadState>,
        /// Sequence from the BAM file.
        seq: Vec<Vec<(u8, BaseFmt)>>,
        /// Basecalling qualities from the BAM file.
        qual: Vec<Vec<u8>>,
    },
    /// Only basecalled info i.e. from the sequencing summary file is available
    OnlyBc(u64),
    /// Information from both sequencing summary and alignment file are available.
    /// NOTE that these are vectors as a read can have multiple BAM records,
    /// but the basecalled length is not a vector as a sequencing summary file
    /// has unique information per read. If the basecalled length from the
    /// sequencing summary file does not match that from the BAM file record(s),
    /// then we will have to make a choice.
    BothAlignBc {
        /// Alignment length from the BAM file
        align_len: Vec<u64>,
        /// Sequence length from the sequencing summary file
        bc_len: u64,
        /// Count of various mods from the BAM file
        mod_count: Vec<ModCountTbl>,
        /// Alignment type (primary, secondary, reverse etc.) from the BAM file.
        read_state: Vec<ReadState>,
        /// Sequence from the BAM file.
        seq: Vec<Vec<(u8, BaseFmt)>>,
        /// Basecalling qualities from the BAM file.
        qual: Vec<Vec<u8>>,
    },
}

impl fmt::Display for ReadInstance {
    #[expect(
        clippy::pattern_type_mismatch,
        reason = "expect no confusion from this code"
    )]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // we are fine with `unsafe` here as `rust-htslib` guarantees
        // that only 16 printable characters are allowed in the sequence.
        match self {
            ReadInstance::OnlyBc(u64) => format!("{u64}"),
            ReadInstance::OnlyAlign {
                align_len: al,
                seq_len: sl,
                mod_count: mc,
                read_state: rs,
                seq: sq,
                qual: q,
            }
            | ReadInstance::BothAlignBc {
                align_len: al,
                bc_len: sl,
                mod_count: mc,
                read_state: rs,
                seq: sq,
                qual: q,
            } => format!(
                "{}\t{sl}\t{}{}{}{}",
                vec_csv!(al),
                vec_csv!(rs),
                match vec_csv!(mc) {
                    v if !v.is_empty() => format!("\t{v}"),
                    _ => String::new(),
                },
                match vec_csv!(sq.iter().map(|v| unsafe {
                    String::from_utf8_unchecked(
                        v.clone()
                            .into_iter()
                            .map(|w| match w.1 {
                                BaseFmt::No => w.0,
                                BaseFmt::LowerCase => w.0.to_ascii_lowercase(),
                                BaseFmt::Highlight => b'Z',
                                BaseFmt::LowerCaseHighlight => b'z',
                            })
                            .collect::<Vec<u8>>(),
                    )
                })) {
                    v if !v.is_empty() => format!("\t{v}"),
                    _ => String::new(),
                },
                match vec_csv!(q.iter().map(|k| join(k, "."))) {
                    v if !v.is_empty() => format!("\t{v}"),
                    _ => String::new(),
                },
            ),
        }
        .fmt(f)
    }
}

/// Implements a structure representing the state of a read w.r.t
/// sequencing summary information and BAM information
struct Read(ReadInstance);

/// Implements functions for Read
impl Read {
    /// initialization using basecalled length
    fn new_bc_len(l: u64) -> Self {
        Self(ReadInstance::OnlyBc(l))
    }

    /// initialization using alignment information
    fn new_align_len(
        align_len: u64,
        seq_len: u64,
        mod_count: Option<ModCountTbl>,
        read_state: ReadState,
        seq: Option<Vec<(u8, BaseFmt)>>,
        qual: Option<Vec<u8>>,
    ) -> Self {
        Self(ReadInstance::OnlyAlign {
            align_len: vec![align_len],
            seq_len,
            mod_count: mod_count.into_iter().collect(),
            read_state: vec![read_state],
            seq: seq.into_iter().collect(),
            qual: qual.into_iter().collect(),
        })
    }

    /// adding alignment information to an entry
    #[expect(
        clippy::pattern_type_mismatch,
        reason = "expect no confusion from this code"
    )]
    fn add_align_len(
        &mut self,
        align_len: u64,
        seq_len: u64,
        mod_count: Option<ModCountTbl>,
        read_state: ReadState,
        seq: Option<Vec<(u8, BaseFmt)>>,
        qual: Option<Vec<u8>>,
    ) {
        match &mut self.0 {
            ReadInstance::OnlyAlign {
                align_len: al,
                mod_count: mc,
                read_state: rs,
                seq: sq,
                qual: q,
                seq_len: l,
            } => {
                al.push(align_len);
                rs.push(read_state);
                mc.extend(mod_count);
                sq.extend(seq);
                q.extend(qual);

                // BAM files are not supposed to have different sequence lengths for
                // the same read if there are multiple records corresponding to one read.
                // But, it is possible that some BAM files are in violation, or the sequence
                // is not stored in all reads. To account for this, we set our sequence length
                // to be the largest of all these records.
                if *l < seq_len {
                    *l = seq_len;
                }
            }
            ReadInstance::BothAlignBc {
                align_len: al,
                mod_count: mc,
                read_state: rs,
                seq: sq,
                qual: q,
                ..
            } => {
                // we ignore the seq length here, as we want the seq len from the
                // sequencing summary file to take precedence over the seq length
                // from the BAM file.
                al.push(align_len);
                rs.push(read_state);
                mc.extend(mod_count);
                sq.extend(seq);
                q.extend(qual);
            }
            ReadInstance::OnlyBc(bl) => {
                self.0 = ReadInstance::BothAlignBc {
                    align_len: vec![align_len],
                    bc_len: *bl,
                    mod_count: mod_count.into_iter().collect(),
                    read_state: vec![read_state],
                    seq: seq.into_iter().collect(),
                    qual: qual.into_iter().collect(),
                };
            }
        }
    }
}

/// Represents a record with the columns of interest from the TSV file.
#[derive(Debug, Serialize, Deserialize)]
struct TSVRecord {
    /// Read id of the molecule in the current row
    read_id: String,
    /// Sequence length of the molecule in the current row
    sequence_length_template: u64,
}

/// Opens a TSV file, extracts '`read_id`' and '`sequence_length_template`' columns,
/// and builds a `HashMap`.
fn process_tsv(file_path: &str) -> Result<HashMap<String, Read>, Error> {
    let mut data_map = HashMap::<String, Read>::new();

    match file_path {
        "" => {}
        fp => {
            let file = File::open(fp)?;
            let mut rdr = ReaderBuilder::new()
                .comment(Some(b'#'))
                .delimiter(b'\t')
                .from_reader(file);

            for result in rdr.deserialize() {
                let record: TSVRecord = result?;
                if data_map
                    .insert(
                        record.read_id.clone(),
                        Read::new_bc_len(record.sequence_length_template),
                    )
                    .is_some()
                {
                    return Err(Error::InvalidDuplicates(format!(
                        "file: {file_path}, read: {0}",
                        record.read_id
                    )));
                }
            }
        }
    }

    Ok(data_map)
}

/// Processes a BAM file and optionally a sequencing summary file
/// to print a table of reads with alignment length, sequence length,
/// and optionally modification count per row.
///
/// # Errors
/// Returns an error if TSV processing, BAM record reading, sequence retrieval, or output writing fails.
///
/// # Panics
/// If lists associated with sequence, modification, and/or base quality are malformed i.e.
/// not of correct lengths or missing data etc.
#[expect(clippy::too_many_lines, reason = "needs to process many options")]
pub fn run<W, D>(
    handle: &mut W,
    bam_records: D,
    mut mods: Option<InputMods<OptionalTag>>,
    seq_display: SeqDisplayOptions,
    seq_summ_path: &str,
) -> Result<(), Error>
where
    W: std::io::Write,
    D: IntoIterator<Item = Result<Rc<bam::Record>, rust_htslib::errors::Error>>,
{
    // read TSV file and convert into hashmap
    let mut data_map = process_tsv(seq_summ_path)?;

    // set up a flag to check if sequencing summary file has data
    let is_seq_summ_data: bool = !data_map.is_empty();

    match mods.as_mut() {
        None => {}
        Some(p) => match p.mod_prob_filter {
            ref mut v @ ThresholdState::GtEq(w) => *v = ThresholdState::GtEq(u8::max(128, w)),
            ref mut v @ ThresholdState::InvertGtEqLtEq(w) => *v = ThresholdState::Both((128, w)),
            ref mut v @ ThresholdState::Both((w, x)) => {
                *v = ThresholdState::Both((u8::max(128, w), x));
            }
        },
    }

    // Go record by record in the BAM file,
    // get the read id and the alignment length, and put it in the hashmap
    for r in bam_records {
        // read records
        let record = r?;

        // get information of current read
        let curr_read_state = {
            let (temp, is_non_zero_len) = match CurrRead::default().try_from_only_alignment(&record)
            {
                Ok(v) => (v, true),
                Err(Error::ZeroSeqLen(_)) => (
                    CurrRead::default().try_from_only_alignment_zero_seq_len(&record)?,
                    false,
                ),
                Err(e) => return Err(e),
            };
            let record_to_be_used = if mods.is_some() && is_non_zero_len {
                &record
            } else {
                // A new record contains no mod information.
                &bam::Record::new()
            };
            match mods.as_ref() {
                Some(v) => temp.set_mod_data_restricted_options(record_to_be_used, v)?,
                None => temp.set_mod_data(record_to_be_used, ThresholdState::GtEq(0), 0)?,
            }
        };

        let qname = String::from(curr_read_state.read_id());
        let read_state = curr_read_state.read_state();
        let align_len = match curr_read_state.align_len() {
            Ok(v) => v,
            Err(Error::Unmapped(_)) => 0,
            Err(_) => continue,
        };
        let Ok(seq_len) = curr_read_state.seq_len() else {
            continue;
        };

        // get sequence and basecalling qualities
        let (sequence, qualities) = {
            let seq = record.seq().as_bytes();
            let qual = record.qual().to_vec();
            match seq_display {
                SeqDisplayOptions::No => (None, None),
                SeqDisplayOptions::Full { show_base_qual } => (
                    Some({
                        if seq.is_empty() {
                            vec![(b'*', BaseFmt::No)]
                        } else {
                            seq.into_iter().zip(iter::repeat(BaseFmt::No)).collect()
                        }
                    }),
                    show_base_qual.then_some(if qual.is_empty() { vec![255u8] } else { qual }),
                ),
                SeqDisplayOptions::Region {
                    show_ins_lowercase,
                    show_base_qual,
                    region,
                    show_mod_z,
                } => {
                    let error_message = "no coordinate errors anticipated";
                    let (o_1, o_2): (Vec<(u8, BaseFmt)>, Vec<u8>) = {
                        let coord_map =
                            match curr_read_state.seq_coords_from_ref_coords(&record, &region) {
                                Err(Error::UnavailableData(_)) => vec![],
                                Err(e) => return Err(e),
                                Ok(x) => x,
                            };
                        if coord_map.is_empty() || seq.is_empty() {
                            (vec![(b'*', BaseFmt::No)], vec![255u8])
                        } else {
                            let mod_data =
                                match SeqCoordCalls::try_from(&curr_read_state.mod_data().0) {
                                    Err(Error::UnavailableData(_)) => vec![false; seq.len()],
                                    Err(e) => return Err(e),
                                    Ok(v) => v.collapse_mod_calls(),
                                };
                            coord_map
                                .into_iter()
                                .map(|y| {
                                    y.map_or(((b'.', BaseFmt::No), 255u8), |z| {
                                        (
                                            (
                                                *seq.get(z.1).expect(error_message),
                                                match (
                                                    show_ins_lowercase && !z.0,
                                                    show_mod_z
                                                        && *mod_data.get(z.1).expect(error_message),
                                                ) {
                                                    (true, true) => BaseFmt::LowerCaseHighlight,
                                                    (true, false) => BaseFmt::LowerCase,
                                                    (false, true) => BaseFmt::Highlight,
                                                    (false, false) => BaseFmt::No,
                                                },
                                            ),
                                            *qual.get(z.1).expect(error_message),
                                        )
                                    })
                                })
                                .collect()
                        }
                    };

                    (Some(o_1), show_base_qual.then_some(o_2))
                }
            }
        };

        // get modification information
        let mod_count = mods
            .as_ref()
            .map(|_| ModCountTbl::new(curr_read_state.base_count_per_mod()));

        // add data depending on whether an entry is already present
        // in the hashmap from the sequencing summary file
        let _: &mut _ = data_map
            .entry(qname)
            .and_modify(|entry| {
                entry.add_align_len(
                    align_len,
                    seq_len,
                    mod_count.clone(),
                    read_state,
                    sequence.clone(),
                    qualities.clone(),
                );
            })
            .or_insert(Read::new_align_len(
                align_len, seq_len, mod_count, read_state, sequence, qualities,
            ));
    }

    // print the output header
    writeln!(
        handle,
        "{}{}read_id\talign_length\tsequence_length_template\talignment_type{}{}{}",
        is_seq_summ_data
            .then_some(format!("# seq summ file: {seq_summ_path}\n"))
            .map_or(String::new(), |v| v),
        mods.clone()
            .map_or("", |_| "# mod-unmod threshold is 0.5\n"),
        mods.map_or("", |_| "\tmod_count"),
        match seq_display {
            SeqDisplayOptions::No => "",
            SeqDisplayOptions::Full { .. } | SeqDisplayOptions::Region { .. } => "\tsequence",
        },
        match seq_display {
            SeqDisplayOptions::No
            | SeqDisplayOptions::Full {
                show_base_qual: false,
            }
            | SeqDisplayOptions::Region {
                show_base_qual: false,
                ..
            } => "",
            SeqDisplayOptions::Full {
                show_base_qual: true,
            }
            | SeqDisplayOptions::Region {
                show_base_qual: true,
                ..
            } => "\tqualities",
        },
    )?;

    // print output tsv data
    // If both seq summ and BAM file are available, then the length in the seq
    // summ file takes precedence. If only the BAM file is available, then
    // we use the sequence length in the BAM file as the basecalled sequence length.
    #[expect(
        clippy::iter_over_hash_type,
        reason = "sorting would add unnecessary performance overhead; random iteration order is acceptable"
    )]
    for (key, val) in data_map {
        match (val, is_seq_summ_data) {
            (Read(ReadInstance::OnlyBc(_)), _) | (Read(ReadInstance::OnlyAlign { .. }), true) => {}
            (Read(ReadInstance::BothAlignBc { .. }), false) => {
                unreachable!("invalid state while writing output");
            }
            (Read(v), _) => writeln!(handle, "{key}\t{v}")?,
        }
    }

    Ok(())
}

/// Creates a `DataFrame` from read table data
///
/// This function calls [`run`] with a buffer handle, then parses the output into a Polars `DataFrame`.
/// Lines starting with '#' are removed as comments, and the remaining first line contains
/// tab-separated column names. Subsequent lines contain tab-separated data values.
///
/// The schema adapts to the columns present based on the options passed to [`run`]:
/// - Always present: `read_id`, `align_length`, `sequence_length_template`, `alignment_type`
/// - Optional: `mod_count` (if mods are requested)
/// - Optional: `sequence` (if `seq_display` is not `No`)
/// - Optional: `qualities` (if `seq_display` requests base quality)
///
/// # Errors
/// Returns an error if BAM record reading, output writing, or `DataFrame` construction fails.
///
#[expect(
    clippy::needless_pass_by_value,
    reason = "mods must be cloned to pass to run() which takes ownership and mutates it"
)]
pub fn run_df<D>(
    bam_records: D,
    mods: Option<InputMods<OptionalTag>>,
    seq_display: SeqDisplayOptions,
    seq_summ_path: &str,
) -> Result<DataFrame, Error>
where
    D: IntoIterator<Item = Result<Rc<bam::Record>, rust_htslib::errors::Error>>,
{
    // Create a buffer to capture output
    let mut buffer = Vec::new();

    // Call run with the buffer
    run(
        &mut buffer,
        bam_records,
        mods.clone(),
        seq_display,
        seq_summ_path,
    )?;

    // Convert buffer to string
    let output = String::from_utf8(buffer)?;

    // Remove comment lines (starting with '#') and find the header
    let lines: Vec<&str> = output
        .lines()
        .filter(|line| !line.starts_with('#'))
        .collect();

    if lines.is_empty() {
        return Err(Error::InvalidState("Output has no header line".to_string()));
    }

    // First non-comment line is the header
    let header_line = lines
        .first()
        .ok_or_else(|| Error::InvalidState("Output has no header line".to_string()))?;

    // Parse header to determine which columns are present
    let column_names: Vec<&str> = header_line.split('\t').collect();

    // Build schema dynamically based on detected columns
    let mut schema_fields = Vec::new();

    for col_name in &column_names {
        let field = match *col_name {
            "read_id" => Field::new("read_id".into(), DataType::String),
            "align_length" => Field::new("align_length".into(), DataType::String),
            "sequence_length_template" => {
                Field::new("sequence_length_template".into(), DataType::UInt64)
            }
            "alignment_type" => Field::new("alignment_type".into(), DataType::String),
            "mod_count" => Field::new("mod_count".into(), DataType::String),
            "sequence" => Field::new("sequence".into(), DataType::String),
            "qualities" => Field::new("qualities".into(), DataType::String),
            _ => {
                return Err(Error::InvalidState(format!(
                    "Unknown column name: {col_name}"
                )));
            }
        };
        schema_fields.push(field);
    }

    let schema = Schema::from_iter(schema_fields);

    // Reconstruct TSV without comment lines for parsing
    let tsv_without_comments = lines.join("\n");

    // Parse the TSV data with the schema
    let cursor = std::io::Cursor::new(tsv_without_comments.as_bytes());
    let df = CsvReadOptions::default()
        .with_has_header(true)
        .map_parse_options(|parse_options| parse_options.with_separator(b'\t'))
        .with_schema(Some(Arc::new(schema)))
        .into_reader_with_file_handle(cursor)
        .finish()?;

    Ok(df)
}

/// Sorts string that represents tabular data by first column (removing empty lines).
///
///
/// Useful in testing to compare expected and observed output.
/// Header must either start with '#' or with "`read_id`".
///
/// Example
///
/// ```
/// use nanalogue_core::reads_table::sort_output_lines;
/// let output = String::from("#comment\n\nread_id value\nbb 100\naa 50\ncc 75");
/// let expected_output = vec!["#comment","read_id value","aa 50","bb 100","cc 75"];
/// assert_eq!(expected_output, sort_output_lines(&output));
/// ```
#[must_use]
pub fn sort_output_lines(output: &str) -> Vec<String> {
    let (mut header, mut data): (Vec<String>, Vec<String>) = output
        .lines()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .partition(|x| x.starts_with('#') | x.starts_with("read_id"));

    // our output table can return reads in any order, so we need to sort it
    // so that we can compare an expected and an observed output
    data.sort();
    header.append(&mut data);
    header
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nanalogue_bam_reader;
    use bedrs::Bed3;
    use rand::random;
    use rust_htslib::bam::Read as _;

    #[test]
    fn read_instance_only_bc_len_display() {
        assert_eq!("1000".to_owned(), ReadInstance::OnlyBc(1000u64).to_string());
    }

    fn run_read_table_test(
        bam_file: &str,
        mods: Option<InputMods<OptionalTag>>,
        seq_region: SeqDisplayOptions,
        seq_summ_file: Option<&str>,
        expected_output_file: &str,
    ) -> Result<(), Error> {
        let mut reader = nanalogue_bam_reader(bam_file).expect("no error");
        let records = reader.rc_records();

        let mut output = Vec::new();
        run(
            &mut output,
            records,
            mods,
            seq_region,
            seq_summ_file.unwrap_or(""),
        )?;

        let actual_output = String::from_utf8(output).expect("Invalid UTF-8");
        let expected_output = std::fs::read_to_string(expected_output_file)
            .expect("Failed to read expected output file");

        let actual_lines = sort_output_lines(&actual_output);
        let expected_lines = sort_output_lines(&expected_output);

        assert_eq!(
            actual_lines,
            expected_lines,
            "\nActual output:\n{}\n\nExpected output:\n{}\n",
            actual_lines.join("\n"),
            expected_lines.join("\n")
        );

        Ok(())
    }

    #[test]
    fn read_table_hide_mods() {
        run_read_table_test(
            "./examples/example_1.bam",
            None,
            SeqDisplayOptions::No,
            None,
            "./examples/example_1_read_table_hide_mods",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_show_mods() {
        run_read_table_test(
            "./examples/example_1.bam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::No,
            None,
            "./examples/example_1_read_table_show_mods",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_show_mods_but_one_record_no_mods() {
        run_read_table_test(
            "./examples/example_6.sam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::No,
            None,
            "./examples/example_6_read_table_show_mods",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_show_mods_with_seq_summ() {
        run_read_table_test(
            "./examples/example_1.bam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::No,
            Some("./examples/example_1_sequencing_summary"),
            "./examples/example_1_read_table_show_mods_seq_summ",
        )
        .expect("no error");
    }

    #[test]
    #[should_panic(expected = "InvalidDuplicates")]
    fn read_table_show_mods_with_invalid_seq_summ() {
        // this sequencing summary file is invalid because a read id is repeated.
        run_read_table_test(
            "./examples/example_1.bam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::No,
            Some("./examples/example_1_invalid_sequencing_summary"),
            "./examples/example_1_read_table_show_mods_seq_summ",
        )
        .unwrap();
    }

    #[test]
    fn read_table_show_mods_seq_qual() {
        run_read_table_test(
            "./examples/example_5_valid_basequal.sam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::Full {
                show_base_qual: true,
            },
            None,
            "./examples/example_5_valid_basequal_read_table_show_mods",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_show_mods_seq_qual_subset() {
        run_read_table_test(
            "./examples/example_5_valid_basequal.sam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::Region {
                region: Bed3::<i32, u64>::new(0, 10, 12),
                show_ins_lowercase: false,
                show_base_qual: true,
                show_mod_z: false,
            },
            None,
            "./examples/example_5_valid_basequal_read_table_show_mods_subset",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_show_mods_seq_qual_subset_no_overlap() {
        // the region specified below does not overlap with the read in the sam file,
        // so we are testing read table outputs when sequence and basecalling quality
        // are requested in this scenario.
        run_read_table_test(
            "./examples/example_5_valid_basequal.sam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::Region {
                region: Bed3::<i32, u64>::new(1, 0, 2000),
                show_ins_lowercase: false,
                show_base_qual: true,
                show_mod_z: false,
            },
            None,
            "./examples/example_5_valid_basequal_read_table_show_mods_subset_no_overlap",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_with_zero_seq_len_hide_mods() {
        run_read_table_test(
            "./examples/example_2_zero_len.sam",
            None,
            SeqDisplayOptions::No,
            None,
            "./examples/example_2_table_w_zero_hide_mods",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_with_zero_seq_len_show_mods() {
        run_read_table_test(
            "./examples/example_2_zero_len.sam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::No,
            None,
            "./examples/example_2_table_w_zero_show_mods",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_with_zero_seq_len_hide_mods_seq_summ() {
        run_read_table_test(
            "./examples/example_2_zero_len.sam",
            None,
            SeqDisplayOptions::No,
            Some("./examples/example_2_sequencing_summary"),
            "./examples/example_2_table_w_zero_hide_mods_seq_summ",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_with_zero_seq_len_show_mods_seq_summ() {
        run_read_table_test(
            "./examples/example_2_zero_len.sam",
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::No,
            Some("./examples/example_2_sequencing_summary"),
            "./examples/example_2_table_w_zero_show_mods_seq_summ",
        )
        .expect("no error");
    }

    #[test]
    fn read_table_hide_mods_ins_lowercase_with_and_without() {
        run_read_table_test(
            "./examples/example_7.sam",
            None,
            SeqDisplayOptions::Region {
                region: Bed3::<i32, u64>::new(0, 0, 1000),
                show_ins_lowercase: true,
                show_base_qual: false,
                show_mod_z: false,
            },
            None,
            "./examples/example_7_table_hide_mods_ins_lowercase",
        )
        .expect("no error");

        run_read_table_test(
            "./examples/example_7.sam",
            None,
            SeqDisplayOptions::Region {
                region: Bed3::<i32, u64>::new(0, 0, 1000),
                show_ins_lowercase: false,
                show_base_qual: false,
                show_mod_z: false,
            },
            None,
            "./examples/example_7_table_hide_mods",
        )
        .expect("no error");
    }

    /// If a read has many sequence lengths (multiple records in the BAM file
    /// having mismatched lengths), and no sequencing summary file entry,
    /// test that we choose the largest length.
    #[test]
    #[expect(clippy::panic, reason = "panics are fine in tests")]
    #[expect(
        clippy::indexing_slicing,
        reason = "this is fine in tests, lists below are very short"
    )]
    fn maximum_length_replacement_test() {
        let lengths = [10, 20, 30, 40];
        let n = lengths.len();
        for count in 0..n {
            let random_state_1: ReadState = random();
            let mut read = Read::new_align_len(1, lengths[count], None, random_state_1, None, None);
            for l in 1..n {
                let random_state: ReadState = random();
                let indx = if count + l < n {
                    count + l
                } else {
                    count + l - n
                };
                read.add_align_len(1, lengths[indx], None, random_state, None, None);
            }
            match read.0 {
                ReadInstance::OnlyAlign { seq_len: 40, .. } => {}
                ReadInstance::OnlyAlign { seq_len, .. } => {
                    panic!("maximum length replacement test failed, we got {seq_len} instead of 40")
                }
                ReadInstance::BothAlignBc { .. } | ReadInstance::OnlyBc(_) => {
                    panic!("maximum length replacement test failed, wrong state")
                }
            }
        }
    }

    /// If a read has many sequence lengths (multiple records in the BAM file
    /// having mismatched lengths), and we have sequence length from the sequencing
    /// summary file, test that we retain the sequence length from the summary file
    /// no matter what.
    #[test]
    #[expect(clippy::panic, reason = "panics are fine in tests")]
    #[expect(
        clippy::indexing_slicing,
        reason = "this is fine in tests, lists below are very short"
    )]
    fn no_length_replacement_test() {
        let lengths = [10, 20, 30, 40];
        let n = lengths.len();
        for count in 0..n {
            let mut read = Read::new_bc_len(lengths[count]);
            for l in 1..n {
                let random_state: ReadState = random();
                let indx = if count + l < n {
                    count + l
                } else {
                    count + l - n
                };
                read.add_align_len(1, lengths[indx], None, random_state, None, None);
            }
            match read.0 {
                ReadInstance::BothAlignBc { bc_len, .. } if bc_len == lengths[count] => {}
                ReadInstance::BothAlignBc { bc_len, .. } => {
                    panic!(
                        "maximum length replacement test failed, we got {bc_len} instead of {}",
                        lengths[count]
                    )
                }
                ReadInstance::OnlyAlign { .. } | ReadInstance::OnlyBc(_) => {
                    panic!("maximum length replacement test failed, wrong state")
                }
            }
        }
    }

    /// Test that a record with zero sequence length outputs "*" for sequence
    /// and "255" for qualities when both sequence and qualities are requested.
    #[test]
    #[expect(
        clippy::indexing_slicing,
        reason = "this is fine in tests, parsing known output"
    )]
    fn zero_seq_len_record_with_sequence_and_qualities() {
        let mut reader = nanalogue_bam_reader("./examples/example_2_zero_len.sam")
            .expect("Failed to open example file");
        let mut bam_records = reader.rc_records();
        let first_record = bam_records.next().expect("No records in file");

        let mut output = Vec::new();
        run(
            &mut output,
            vec![first_record],
            None,
            SeqDisplayOptions::Full {
                show_base_qual: true,
            },
            "",
        )
        .expect("no error");

        let actual_output = String::from_utf8(output).expect("Invalid UTF-8");

        // Parse TSV using csv crate (similar to process_tsv)
        let mut rdr = ReaderBuilder::new()
            .comment(Some(b'#'))
            .delimiter(b'\t')
            .from_reader(actual_output.as_bytes());

        let headers = rdr.headers().expect("Failed to read headers");
        let seq_col_idx = headers
            .iter()
            .position(|h| h == "sequence")
            .expect("sequence column not found");
        let qual_col_idx = headers
            .iter()
            .position(|h| h == "qualities")
            .expect("qualities column not found");

        let mut csv_records = rdr.records();
        let record = csv_records
            .next()
            .expect("No data row found")
            .expect("Failed to parse row");

        assert_eq!(
            &record[seq_col_idx], "*",
            "Sequence column should contain '*'"
        );
        assert_eq!(
            &record[qual_col_idx], "255",
            "Qualities column should contain '255'"
        );
    }

    /// Test that a record with zero sequence length outputs "*" for sequence
    /// but no qualities column when only sequence is requested.
    #[test]
    #[expect(
        clippy::indexing_slicing,
        reason = "this is fine in tests, parsing known output"
    )]
    fn zero_seq_len_record_with_sequence_only() {
        let mut reader = nanalogue_bam_reader("./examples/example_2_zero_len.sam")
            .expect("Failed to open example file");
        let mut bam_records = reader.rc_records();
        let first_record = bam_records.next().expect("No records in file");

        let mut output = Vec::new();
        run(
            &mut output,
            vec![first_record],
            None,
            SeqDisplayOptions::Full {
                show_base_qual: false,
            },
            "",
        )
        .expect("no error");

        let actual_output = String::from_utf8(output).expect("Invalid UTF-8");

        // Parse TSV using csv crate (similar to process_tsv)
        let mut rdr = ReaderBuilder::new()
            .comment(Some(b'#'))
            .delimiter(b'\t')
            .from_reader(actual_output.as_bytes());

        let headers = rdr.headers().expect("Failed to read headers");
        let seq_col_idx = headers
            .iter()
            .position(|h| h == "sequence")
            .expect("sequence column not found");

        // Verify qualities column does not exist
        assert!(
            !headers.iter().any(|h| h == "qualities"),
            "Qualities column should not be present when show_base_qual is false"
        );

        let mut csv_records = rdr.records();
        let record = csv_records
            .next()
            .expect("No data row found")
            .expect("Failed to parse row");

        assert_eq!(
            &record[seq_col_idx], "*",
            "Sequence column should contain '*'"
        );
    }
}

#[cfg(test)]
mod stochastic_tests {
    use super::*;
    use crate::simulate_mod_bam::{
        ContigConfigBuilder, ReadConfigBuilder, SimulationConfigBuilder, TempBamSimulation,
    };
    use bedrs::Bed3;
    use derive_builder::Builder;
    use rust_htslib::bam::Read as _;
    use std::ops::RangeInclusive;

    /// Helper to run reads table generation
    fn run_reads_table_generation(
        sim: &TempBamSimulation,
        mods: Option<InputMods<OptionalTag>>,
        seq_display: SeqDisplayOptions,
    ) -> Result<DataFrame, Error> {
        let mut bam_reader = bam::Reader::from_path(sim.bam_path())?;
        let bam_records = bam_reader.rc_records();
        run_df(bam_records, mods, seq_display, "")
    }

    /// Helper to keep track that all read states have been visited
    fn track_read_state_visits(val: &mut [bool; 7], state: &str) {
        match state {
            "unmapped" => val[0] = true,
            "primary_forward" => val[1] = true,
            "primary_reverse" => val[2] = true,
            "secondary_forward" => val[3] = true,
            "secondary_reverse" => val[4] = true,
            "supplementary_forward" => val[5] = true,
            "supplementary_reverse" => val[6] = true,
            &_ => unreachable!(),
        }
    }

    /// Helper struct used in the [`assert_expected_columns`] function
    /// to register what columns are expected.
    #[derive(Builder, Clone, Copy, Debug, Default, PartialEq)]
    #[builder(default, build_fn(error = "Error"))]
    struct Columns {
        /// Expect a `mod_count` column
        mod_count: bool,
        /// Expect a `sequence` column
        sequence: bool,
        /// Expect a `qualities` column
        qualities: bool,
    }

    /// Helper to assert dataframe has expected column headers
    fn assert_expected_columns(df: &DataFrame, columns: Columns) {
        let mut expected_columns = vec![
            "read_id",
            "align_length",
            "sequence_length_template",
            "alignment_type",
        ];
        if columns.mod_count {
            expected_columns.push("mod_count");
        }
        if columns.sequence {
            expected_columns.push("sequence");
        }
        if columns.qualities {
            expected_columns.push("qualities");
        }

        let actual_columns: Vec<String> = df
            .get_column_names()
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(
            actual_columns, expected_columns,
            "DataFrame should have correct column headers"
        );
    }

    /// Helper struct used in the `check_seq_qual` function
    /// to register expected/observed counts of different non-upper-case A/C/G/T
    /// characters in a sequence
    #[derive(Builder, Clone, Copy, Debug, Default, PartialEq)]
    #[builder(default, build_fn(error = "Error"))]
    struct Counts {
        /// Number of occurences of '.'
        period: usize,
        /// Number of occurences of lowercase bases
        lowercase: usize,
    }

    impl Counts {
        /// Increment appropriate count
        #[expect(
            clippy::arithmetic_side_effects,
            reason = "we are ok with this in tests"
        )]
        fn increment(&mut self, value: char) -> Result<(), Error> {
            match value {
                '.' => self.period += 1,
                'A' | 'C' | 'G' | 'T' => {}
                'a' | 'c' | 'g' | 't' => {
                    self.lowercase += 1;
                }
                v => {
                    return Err(Error::InvalidSeq(format!(
                        "Invalid character {v} found in sequence!"
                    )));
                }
            }

            Ok(())
        }
    }

    /// Helper to check if sequence and quality columns are as desired
    fn check_seq_qual(
        seq_col: &ChunkedArray<StringType>,
        qual_col: &ChunkedArray<StringType>,
        seq_len: usize,
        expected_count: &Counts,
        qual_allowed: RangeInclusive<u8>,
    ) {
        let mut data_present = false;

        #[expect(
            clippy::needless_continue,
            clippy::redundant_else,
            reason = "I prefer it this way; I think this is more readable"
        )]
        for k in seq_col.iter().zip(qual_col) {
            data_present = true;

            let seq = k.0.unwrap();

            let qual =
                k.1.unwrap()
                    .split('.')
                    .map(|x| x.parse::<u8>().unwrap())
                    .collect::<Vec<u8>>();

            if seq == "*" && qual == vec![255u8] {
                continue;
            } else {
                assert_eq!(seq.len(), seq_len, "Sequence length mismatch");
                assert_eq!(qual.len(), seq_len, "Quality length mismatch");

                let mut count: Counts = Counts::default();

                for l in seq.chars().zip(qual) {
                    match l {
                        ('.', 255u8) => count.increment('.').unwrap(),
                        (v, w) => {
                            count.increment(v).unwrap();
                            assert!(qual_allowed.contains(&w));
                        }
                    }
                }
                assert!(
                    count == *expected_count,
                    "need correct number of bases and/or special characters!"
                );
            }
        }

        assert!(data_present, "Some data must be present in the table");
    }

    /// Simple test, produce some reads and see if we get expected statistics.
    /// Here `alignment length == sequence_length_template` and all read ids
    /// start with "0." as there is only one read group. The `alignment_type`
    /// is equally likely to be one of seven.
    #[test]
    fn run_df_simple() -> Result<(), Error> {
        // Create simulation config with no modifications
        let contig_config = ContigConfigBuilder::default()
            .number(2)
            .len_range((1000, 2000))
            .build()?;

        let read_config = ReadConfigBuilder::default()
            .number(100)
            .mapq_range((10, 20))
            .base_qual_range((30, 40))
            .len_range((0.5, 0.6));

        let sim_config = SimulationConfigBuilder::default()
            .contigs(contig_config)
            .reads(vec![read_config.build()?])
            .build()?;

        let sim = TempBamSimulation::new(sim_config)?;
        let df = run_reads_table_generation(&sim, None, SeqDisplayOptions::No)?;

        // Verify the dataframe is not empty and has expected columns
        assert!(df.height() > 0, "DataFrame should have some rows");
        assert_expected_columns(&df, ColumnsBuilder::default().build()?);

        let mut read_states = [false; 7];

        let read_id = df.column("read_id")?.str()?;
        assert!(
            read_id.iter().all(|k| k.unwrap().starts_with("0.")),
            "only one RG, must start with 0"
        );

        let align_length = df.column("align_length")?.str()?;
        let seq_length = df.column("sequence_length_template")?.u64()?;
        let alignment_type = df.column("alignment_type")?.str()?;

        for k in align_length.iter().zip(seq_length).zip(alignment_type) {
            let al = k.0.0.unwrap().parse::<u64>().unwrap();
            let sl = k.0.1.unwrap();
            let rs = k.1.unwrap();
            assert!(al == 0 || al == sl);
            if al == 0 {
                assert_eq!(rs, "unmapped");
            }
            track_read_state_visits(&mut read_states, rs);
            assert!((500..=1200).contains(&sl));
        }

        assert!(read_states.into_iter().all(|k| k));

        Ok(())
    }

    /// More complex, now sequence and alignment lengths are systematically
    /// different due to an insertion and a barcode.
    #[test]
    fn run_df_al_sl_different() -> Result<(), Error> {
        // Create simulation config with no modifications
        let contig_config = ContigConfigBuilder::default()
            .number(2)
            .len_range((1000, 2000))
            .build()?;

        let read_config = ReadConfigBuilder::default()
            .number(100)
            .mapq_range((10, 20))
            .base_qual_range((30, 40))
            .len_range((0.5, 0.6))
            .barcode("AATTGAA".into())
            .insert_middle("GGTT".into());

        let sim_config = SimulationConfigBuilder::default()
            .contigs(contig_config)
            .reads(vec![read_config.build()?])
            .build()?;

        let sim = TempBamSimulation::new(sim_config)?;
        let df = run_reads_table_generation(&sim, None, SeqDisplayOptions::No)?;

        // Verify the dataframe is not empty and has expected columns
        assert!(df.height() > 0, "DataFrame should have some rows");
        assert_expected_columns(&df, ColumnsBuilder::default().build()?);

        let mut read_states = [false; 7];

        let read_id = df.column("read_id")?.str()?;
        assert!(
            read_id.iter().all(|k| k.unwrap().starts_with("0.")),
            "only one RG, must start with 0"
        );

        let align_length = df.column("align_length")?.str()?;
        let seq_length = df.column("sequence_length_template")?.u64()?;
        let alignment_type = df.column("alignment_type")?.str()?;

        for k in align_length.iter().zip(seq_length).zip(alignment_type) {
            let al = k.0.0.unwrap().parse::<u64>().unwrap();
            let sl = k.0.1.unwrap();
            let rs = k.1.unwrap();
            assert!(al == 0 || al == sl - 18); // barcode is 7 bp, insertion is 4 bp, so 2 * 7 + 4
            if al == 0 {
                assert_eq!(rs, "unmapped");
            } else {
                assert!((500..=1200).contains(&al));
            }
            track_read_state_visits(&mut read_states, rs);
        }

        assert!(read_states.into_iter().all(|k| k));

        Ok(())
    }

    /// Test retrieval of sequence and qualities
    #[test]
    fn run_df_seq_qual_retrieval() -> Result<(), Error> {
        // Create simulation config with no modifications
        let contig_config = ContigConfigBuilder::default()
            .number(2)
            .len_range((1000, 1000))
            .build()?;

        let read_config = ReadConfigBuilder::default()
            .number(100)
            .mapq_range((10, 20))
            .base_qual_range((71, 79))
            .len_range((0.5, 0.5));

        let sim_config = SimulationConfigBuilder::default()
            .contigs(contig_config)
            .reads(vec![read_config.build()?])
            .build()?;

        let sim = TempBamSimulation::new(sim_config)?;
        let df = run_reads_table_generation(
            &sim,
            None,
            SeqDisplayOptions::Full {
                show_base_qual: true,
            },
        )?;

        // Verify the dataframe has expected columns
        assert_expected_columns(
            &df,
            ColumnsBuilder::default()
                .sequence(true)
                .qualities(true)
                .build()?,
        );

        let seq_col = df.column("sequence")?.str()?;
        let qual_col = df.column("qualities")?.str()?;

        check_seq_qual(seq_col, qual_col, 500, &Counts::default(), 71u8..=79u8);

        // extract seq and mod_count but we won't be getting a column called qualities.
        // mod_count will all be NAs
        let df_2 = run_reads_table_generation(
            &sim,
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::Full {
                show_base_qual: false,
            },
        )?;

        // Verify the dataframe is not empty and has expected columns
        assert!(df_2.height() > 0, "DataFrame should have some rows");
        assert_expected_columns(
            &df_2,
            ColumnsBuilder::default()
                .sequence(true)
                .mod_count(true)
                .build()?,
        );

        let seq_col_2 = df_2.column("sequence")?.str()?;
        drop(df_2.column("qualities").unwrap_err());
        let mod_count = df_2.column("mod_count")?.str()?;

        assert!(
            seq_col_2.iter().all(|x| x.unwrap().len() == 500),
            "500 bp seq expected"
        );
        assert!(
            mod_count.iter().all(|x| x == Some("NA")),
            "no mod information expected"
        );

        Ok(())
    }

    /// Test retrieval of sequence and qualities of the full
    /// sequence even with indels and barcode.
    #[test]
    fn run_df_seq_qual_retrieval_indels_barcode() -> Result<(), Error> {
        // Create simulation config with no modifications
        let contig_config = ContigConfigBuilder::default()
            .number(2)
            .len_range((1000, 1000))
            .build()?;

        let read_config = ReadConfigBuilder::default()
            .number(100)
            .mapq_range((10, 20))
            .base_qual_range((71, 79))
            .len_range((0.5, 0.5))
            .barcode("AATT".into())
            .delete((0.5, 0.6))
            .insert_middle("GGTTGG".into())
            .mismatch(0.1);

        let sim_config = SimulationConfigBuilder::default()
            .contigs(contig_config)
            .reads(vec![read_config.build()?])
            .build()?;

        let sim = TempBamSimulation::new(sim_config)?;
        let df = run_reads_table_generation(
            &sim,
            None,
            SeqDisplayOptions::Full {
                show_base_qual: true,
            },
        )?;

        // Verify the dataframe has expected columns
        assert_expected_columns(
            &df,
            ColumnsBuilder::default()
                .sequence(true)
                .qualities(true)
                .build()?,
        );

        let seq_col = df.column("sequence")?.str()?;
        let qual_col = df.column("qualities")?.str()?;

        check_seq_qual(seq_col, qual_col, 464, &Counts::default(), 71u8..=79u8);

        Ok(())
    }

    /// Helper function to create a simulation with indels and barcodes for region testing.
    fn create_indels_barcode_simulation() -> Result<TempBamSimulation, Error> {
        let contig_config = ContigConfigBuilder::default()
            .number(1)
            .len_range((1000, 1000))
            .repeated_seq("ACGT".into())
            .build()?;

        let read_config = ReadConfigBuilder::default()
            .number(100)
            .mapq_range((10, 20))
            .base_qual_range((41, 49))
            .len_range((1.0, 1.0))
            .barcode("AATT".into())
            .delete((0.1, 0.2))
            .insert_middle("GGTTGG".into());

        let sim_config = SimulationConfigBuilder::default()
            .contigs(contig_config)
            .reads(vec![read_config.build()?])
            .build()?;

        TempBamSimulation::new(sim_config)
    }

    /// Helper function to test sequence retrieval from a specific region.
    fn test_region_retrieval(
        sim: &TempBamSimulation,
        seq_display_options: SeqDisplayOptions,
        expected_seq: &str,
        seq_len: usize,
        counts: &Counts,
    ) -> Result<(), Error> {
        // check that we get the correct kind of `SeqDisplayOptions`
        assert!(matches!(
            seq_display_options,
            SeqDisplayOptions::Region { .. }
        ));

        // first, do a check without retrieving mods
        let df = run_reads_table_generation(sim, None, seq_display_options)?;

        assert_expected_columns(
            &df,
            ColumnsBuilder::default()
                .sequence(true)
                .qualities(true)
                .build()?,
        );

        let seq_col = df.column("sequence")?.str()?;
        let qual_col = df.column("qualities")?.str()?;
        let alignment_type = df.column("alignment_type")?.str()?;

        for k in seq_col.iter().zip(alignment_type) {
            if k.1.unwrap() == "unmapped" {
                assert_eq!(k.0.unwrap(), "*");
            } else {
                assert_eq!(k.0.unwrap(), expected_seq);
            }
        }

        check_seq_qual(seq_col, qual_col, seq_len, counts, 41u8..=49u8);

        // do a check with retrieving mods. Must get N/As in the mod count column
        let df_2 = run_reads_table_generation(
            sim,
            Some(InputMods::<OptionalTag>::default()),
            seq_display_options,
        )?;

        assert_expected_columns(
            &df_2,
            ColumnsBuilder::default()
                .mod_count(true)
                .sequence(true)
                .qualities(true)
                .build()?,
        );

        let mod_count = df_2.column("mod_count")?.str()?;

        assert!(
            mod_count.iter().all(|k| k == Some("NA")),
            "should not get mod counts as no mod info available!"
        );

        Ok(())
    }

    #[test]
    fn region_0_to_10() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        test_region_retrieval(
            &sim,
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: true,
                show_mod_z: false,
                region: Bed3::<i32, u64>::new(0, 0, 10),
            },
            "ACGTACGTAC",
            10,
            &Counts::default(),
        )
    }

    #[test]
    fn region_100_to_110() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        test_region_retrieval(
            &sim,
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: true,
                show_mod_z: false,
                region: Bed3::<i32, u64>::new(0, 100, 110),
            },
            "..........",
            10,
            &CountsBuilder::default().period(10).build()?,
        )
    }

    #[test]
    fn region_195_to_205() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        test_region_retrieval(
            &sim,
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: true,
                show_mod_z: false,
                region: Bed3::<i32, u64>::new(0, 195, 205),
            },
            ".....ACGTA",
            10,
            &CountsBuilder::default().period(5).build()?,
        )
    }

    #[test]
    fn region_495_to_505() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        test_region_retrieval(
            &sim,
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: true,
                show_mod_z: false,
                region: Bed3::<i32, u64>::new(0, 495, 505),
            },
            "TACGTggttggACGTA",
            16,
            &CountsBuilder::default().lowercase(6).build()?,
        )
    }

    #[test]
    fn region_495_to_505_no_ins_lowercase() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        test_region_retrieval(
            &sim,
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: false,
                show_mod_z: false,
                region: Bed3::<i32, u64>::new(0, 495, 505),
            },
            "TACGTGGTTGGACGTA",
            16,
            &CountsBuilder::default().build()?,
        )
    }

    #[test]
    fn region_990_to_1000() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        test_region_retrieval(
            &sim,
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: true,
                show_mod_z: false,
                region: Bed3::<i32, u64>::new(0, 990, 1000),
            },
            "GTACGTACGT",
            10,
            &CountsBuilder::default().build()?,
        )
    }
}

#[cfg(test)]
mod stochastic_tests_with_mods {
    use super::*;
    use crate::InputModsBuilder;
    use crate::simulate_mod_bam::{
        ContigConfigBuilder, ModConfigBuilder, ReadConfigBuilder, SimulationConfigBuilder,
        TempBamSimulation,
    };
    use bedrs::Bed3;
    use itertools::izip;
    use rust_htslib::bam::Read as _;

    /// Helper to run reads table generation
    fn run_reads_table_generation(
        sim: &TempBamSimulation,
        mods: Option<InputMods<OptionalTag>>,
        seq_display: SeqDisplayOptions,
    ) -> Result<DataFrame, Error> {
        let mut bam_reader = bam::Reader::from_path(sim.bam_path())?;
        let bam_records = bam_reader.rc_records();
        run_df(bam_records, mods, seq_display, "")
    }

    /// Helper function to create a simulation with indels and barcodes for region testing.
    fn create_indels_barcode_simulation() -> Result<TempBamSimulation, Error> {
        let contig_config = ContigConfigBuilder::default()
            .number(1)
            .len_range((1000, 1000))
            .repeated_seq("ACGT".into())
            .build()?;

        let mod_config = ModConfigBuilder::default()
            .base('G')
            .is_strand_plus(true)
            .mod_code("g".into())
            .win(vec![1, 1])
            .mod_range(vec![(0.0, 0.0), (0.6, 0.6)])
            .build()?;

        let read_config = ReadConfigBuilder::default()
            .number(100)
            .mapq_range((10, 20))
            .base_qual_range((35, 35))
            .len_range((1.0, 1.0))
            .barcode("AATT".into())
            .delete((0.1, 0.2))
            .insert_middle("GGTTGG".into())
            .mods(vec![mod_config]);

        let sim_config = SimulationConfigBuilder::default()
            .contigs(contig_config)
            .reads(vec![read_config.build()?])
            .build()?;

        TempBamSimulation::new(sim_config)
    }

    /// Helper function to test sequence retrieval from a specific region.
    fn test_region_retrieval(
        sim: &TempBamSimulation,
        seq_display_options: SeqDisplayOptions,
        expected_seq_fwd: &str,
        expected_seq_rev: &str,
        qual_col_str: &str,
        mod_count_fwd_str: &str,
        mod_count_rev_str: &str,
    ) -> Result<(), Error> {
        // check that we get the correct kind of `SeqDisplayOptions`
        assert!(matches!(
            seq_display_options,
            SeqDisplayOptions::Region { .. }
        ));

        // first, do a check without retrieving mods
        let df = run_reads_table_generation(
            sim,
            Some(InputMods::<OptionalTag>::default()),
            seq_display_options,
        )?;
        let seq_col = df.column("sequence")?.str()?;
        let qual_col = df.column("qualities")?.str()?;
        let mod_count = df.column("mod_count")?.str()?;
        let alignment_type = df.column("alignment_type")?.str()?;

        for k in izip!(seq_col, qual_col, mod_count, alignment_type) {
            match k.3.unwrap() {
                "unmapped" => {
                    assert_eq!(k.0.unwrap(), "*");
                    assert_eq!(k.1.unwrap(), "255");
                    assert_eq!(k.2.unwrap(), mod_count_fwd_str);
                }
                "primary_forward" | "secondary_forward" | "supplementary_forward" => {
                    assert_eq!(k.0.unwrap(), expected_seq_fwd);
                    assert_eq!(k.1.unwrap(), qual_col_str);
                    assert_eq!(k.2.unwrap(), mod_count_fwd_str);
                }
                "primary_reverse" | "secondary_reverse" | "supplementary_reverse" => {
                    assert_eq!(k.0.unwrap(), expected_seq_rev);
                    assert_eq!(k.1.unwrap(), qual_col_str);
                    assert_eq!(k.2.unwrap(), mod_count_rev_str);
                }
                _ => unreachable!("read states fall in the above 7 categories"),
            }
        }

        Ok(())
    }

    #[test]
    fn region_0_to_10() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        for k in [
            (false, "ACGTACGTAC", "ACGTACGTAC"),
            (true, "ACGTACZTAC", "ACGTAZGTAC"),
        ] {
            test_region_retrieval(
                &sim,
                SeqDisplayOptions::Region {
                    show_base_qual: true,
                    show_ins_lowercase: true,
                    show_mod_z: k.0,
                    region: Bed3::<i32, u64>::new(0, 0, 10),
                },
                k.1,
                k.2,
                "35.35.35.35.35.35.35.35.35.35",
                "g:114",
                "g:112",
            )?;
        }

        Ok(())
    }

    #[test]
    fn region_100_to_110() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        for k in [false, true] {
            test_region_retrieval(
                &sim,
                SeqDisplayOptions::Region {
                    show_base_qual: true,
                    show_ins_lowercase: true,
                    show_mod_z: k,
                    region: Bed3::<i32, u64>::new(0, 100, 110),
                },
                "..........",
                "..........",
                "255.255.255.255.255.255.255.255.255.255",
                "g:114",
                "g:112",
            )?;
        }

        Ok(())
    }

    #[test]
    fn region_195_to_205() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        for k in [
            (false, ".....ACGTA", ".....ACGTA"),
            (true, ".....ACZTA", ".....AZGTA"),
        ] {
            test_region_retrieval(
                &sim,
                SeqDisplayOptions::Region {
                    show_base_qual: true,
                    show_ins_lowercase: true,
                    show_mod_z: k.0,
                    region: Bed3::<i32, u64>::new(0, 195, 205),
                },
                k.1,
                k.2,
                "255.255.255.255.255.35.35.35.35.35",
                "g:114",
                "g:112",
            )?;
        }

        Ok(())
    }

    #[test]
    fn region_495_to_505() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        for k in [
            (false, "TACGTggttggACGTA", "TACGTggttggACGTA"),
            (true, "TACZTgzttgzACGTA", "TAZGTggttggACGTA"),
        ] {
            test_region_retrieval(
                &sim,
                SeqDisplayOptions::Region {
                    show_base_qual: true,
                    show_ins_lowercase: true,
                    show_mod_z: k.0,
                    region: Bed3::<i32, u64>::new(0, 495, 505),
                },
                k.1,
                k.2,
                "35.35.35.35.35.35.35.35.35.35.35.35.35.35.35.35",
                "g:114",
                "g:112",
            )?;
        }

        Ok(())
    }

    #[test]
    fn region_990_to_1000() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;
        for k in [
            (false, "GTACGTACGT", "GTACGTACGT"),
            (true, "GTACZTACGT", "GTAZGTACGT"),
        ] {
            test_region_retrieval(
                &sim,
                SeqDisplayOptions::Region {
                    show_base_qual: true,
                    show_ins_lowercase: true,
                    show_mod_z: k.0,
                    region: Bed3::<i32, u64>::new(0, 990, 1000),
                },
                k.1,
                k.2,
                "35.35.35.35.35.35.35.35.35.35",
                "g:114",
                "g:112",
            )?;
        }

        Ok(())
    }

    /// Region-based modification counting
    /// This test verifies that when `InputMods::region_bed3` is set,
    /// mod counts reflect only modifications within that region
    #[test]
    fn region_based_mod_counting() -> Result<(), Error> {
        let sim = create_indels_barcode_simulation()?;

        // Test region 0-10
        let mods_for_region = InputModsBuilder::<OptionalTag>::default()
            .region_bed3(Bed3::<i32, u64>::new(0, 0, 10))
            .build()?;

        let df = run_reads_table_generation(
            &sim,
            Some(mods_for_region),
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: true,
                show_mod_z: false,
                region: Bed3::<i32, u64>::new(0, 0, 10),
            },
        )?;

        let mod_count_col = df.column("mod_count")?.str()?;
        let alignment_type = df.column("alignment_type")?.str()?;

        // Count mods in region 0-10 for forward and reverse reads
        for (mod_count, aln_type) in izip!(mod_count_col, alignment_type) {
            match aln_type.unwrap() {
                "unmapped" => {
                    // Unmapped reads show mod count of 0
                    assert_eq!(
                        mod_count.unwrap(),
                        "g:0",
                        "unmapped reads should have g:0 mod_count"
                    );
                }
                "primary_forward" | "secondary_forward" | "supplementary_forward" => {
                    let count_str = mod_count.unwrap();
                    // Parse the count (format is "g:N")
                    if let Some(count_part) = count_str.strip_prefix("g:") {
                        let count: u32 = count_part.parse().expect("valid number");
                        // Region 0-10 has 10 bases, with "ACGTACGTAC" pattern
                        assert_eq!(count, 1, "expected 1 'g' mod in region 0-10, got {count}");
                    } else {
                        unreachable!("unexpected mod_count format: {count_str}");
                    }
                }
                "primary_reverse" | "secondary_reverse" | "supplementary_reverse" => {
                    let count_str = mod_count.unwrap();
                    if let Some(count_part) = count_str.strip_prefix("g:") {
                        let count: u32 = count_part.parse().expect("valid number");
                        assert_eq!(count, 1, "expected 1 'g' mod in region 0-10, got {count}");
                    } else {
                        unreachable!("unexpected mod_count format: {count_str}");
                    }
                }
                _ => unreachable!("read states fall in the above 7 categories"),
            }
        }

        Ok(())
    }

    /// Test Multiple modifications on the same read
    /// This test creates reads with two different modification types
    /// and verifies both are counted correctly
    fn create_multi_mod_simulation() -> Result<TempBamSimulation, Error> {
        let contig_config = ContigConfigBuilder::default()
            .number(1)
            .len_range((1000, 1000))
            .repeated_seq("ACGT".into())
            .build()?;

        // First mod: 'm' on 'C' bases
        let mod_config_c = ModConfigBuilder::default()
            .base('C')
            .is_strand_plus(true)
            .mod_code("m".into())
            .win(vec![1])
            .mod_range(vec![(0.55, 0.55)])
            .build()?;

        // Second mod: 'a' on 'A' bases but on the opposite
        // strand to the basecalled strand
        let mod_config_a = ModConfigBuilder::default()
            .base('A')
            .is_strand_plus(false)
            .mod_code("a".into())
            .win(vec![1, 1])
            .mod_range(vec![(0.6, 0.6), (0.1, 0.1)])
            .build()?;

        let read_config = ReadConfigBuilder::default()
            .number(100)
            .mapq_range((10, 20))
            .base_qual_range((35, 35))
            .len_range((1.0, 1.0))
            .barcode("AATT".into())
            .delete((0.1, 0.2))
            .insert_middle("GGTTGG".into())
            .mods(vec![mod_config_c, mod_config_a]);

        let sim_config = SimulationConfigBuilder::default()
            .contigs(contig_config)
            .reads(vec![read_config.build()?])
            .build()?;

        TempBamSimulation::new(sim_config)
    }

    #[test]
    fn multiple_mod_count_on_same_read() -> Result<(), Error> {
        let sim = create_multi_mod_simulation()?;

        let df = run_reads_table_generation(
            &sim,
            Some(InputMods::<OptionalTag>::default()),
            SeqDisplayOptions::Full {
                show_base_qual: true,
            },
        )?;

        let mod_count_col = df.column("mod_count")?.str()?;
        let alignment_type = df.column("alignment_type")?.str()?;

        // Check that both 'a' and 'm' modifications are present
        for (mod_count, aln_type) in izip!(mod_count_col, alignment_type) {
            match aln_type.unwrap() {
                "unmapped" | "primary_forward" | "secondary_forward" | "supplementary_forward" => {
                    let count_str = mod_count.unwrap();
                    assert_eq!(
                        count_str, "a:115;m:225",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                }
                "primary_reverse" | "secondary_reverse" | "supplementary_reverse" => {
                    // we have an insertion in the middle of the read,
                    // which will have mods on it if it is reverse complemented,
                    // as we assign mods to A and C.
                    let count_str = mod_count.unwrap();
                    assert_eq!(
                        count_str, "a:116;m:229",
                        "incorrect mod counts in reverse: {count_str}"
                    );
                }
                _ => unreachable!("read states fall in the above 7 categories"),
            }
        }

        Ok(())
    }

    #[test]
    fn multiple_mod_count_on_same_read_with_stronger_thresholding() -> Result<(), Error> {
        let sim = create_multi_mod_simulation()?;

        let df = run_reads_table_generation(
            &sim,
            Some(
                InputModsBuilder::<OptionalTag>::default()
                    .mod_prob_filter(ThresholdState::InvertGtEqLtEq((100u8, 150u8).try_into()?))
                    .build()?,
            ),
            SeqDisplayOptions::Full {
                show_base_qual: true,
            },
        )?;

        let mod_count_col = df.column("mod_count")?.str()?;
        let alignment_type = df.column("alignment_type")?.str()?;

        // Check that both 'a' and 'm' modifications are present
        for (mod_count, aln_type) in izip!(mod_count_col, alignment_type) {
            match aln_type.unwrap() {
                "unmapped" | "primary_forward" | "secondary_forward" | "supplementary_forward" => {
                    let count_str = mod_count.unwrap();
                    assert_eq!(
                        count_str, "a:115;m:0",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                }
                "primary_reverse" | "secondary_reverse" | "supplementary_reverse" => {
                    // we have an insertion in the middle of the read,
                    // which will have mods on it if it is reverse complemented,
                    // as we assign mods to A and C.
                    let count_str = mod_count.unwrap();
                    assert_eq!(
                        count_str, "a:116;m:0",
                        "incorrect mod counts in reverse: {count_str}"
                    );
                }
                _ => unreachable!("read states fall in the above 7 categories"),
            }
        }

        Ok(())
    }

    /// Test multiple modifications with region filtering.
    /// Verifies that region filtering and retrieval works correctly when
    /// multiple mod types are present
    #[test]
    fn multiple_mods_with_region_filtering() -> Result<(), Error> {
        let sim = create_multi_mod_simulation()?;

        // Test a small region
        let mods_for_region = InputModsBuilder::<OptionalTag>::default()
            .region_bed3(Bed3::<i32, u64>::new(0, 495, 505))
            .build()?;

        let df = run_reads_table_generation(
            &sim,
            Some(mods_for_region),
            SeqDisplayOptions::Region {
                show_base_qual: true,
                show_ins_lowercase: true,
                show_mod_z: true,
                region: Bed3::<i32, u64>::new(0, 495, 505),
            },
        )?;

        let mod_count_col = df.column("mod_count")?.str()?;
        let alignment_type_col = df.column("alignment_type")?.str()?;
        let seq_col = df.column("sequence")?.str()?;

        // Verify both mod types are present but with region-limited counts and correct sequence.
        // The sequence here is "TACGTggttggACGTA"
        for (mod_count, aln_type, seq) in izip!(mod_count_col, alignment_type_col, seq_col) {
            match aln_type.unwrap() {
                "unmapped" => {
                    // Unmapped reads show mod count of 0 when region filtering is applied
                    assert_eq!(
                        mod_count.unwrap(),
                        "a:0;m:0",
                        "unmapped reads should have zero counts with region filtering"
                    );
                    assert_eq!(
                        seq,
                        Some("*"),
                        "unmapped reads should have a * for sequence"
                    );
                }
                "primary_forward" | "secondary_forward" | "supplementary_forward" => {
                    let count_str = mod_count.unwrap();
                    let seq_str = seq.unwrap();
                    assert_eq!(
                        count_str, "a:1;m:2",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                    assert_eq!(
                        seq_str, "TAZGTggttggZZGTA",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                }
                "primary_reverse" | "secondary_reverse" | "supplementary_reverse" => {
                    let count_str = mod_count.unwrap();
                    let seq_str = seq.unwrap();
                    assert_eq!(
                        count_str, "a:3;m:6",
                        "incorrect mod counts in reverse: {count_str}"
                    );
                    assert_eq!(
                        seq_str, "ZACZTzzztzzACZZA",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                }
                _ => unreachable!("read states fall in the above 7 categories"),
            }
        }

        Ok(())
    }

    /// Test multiple modifications with region filtering and with
    /// very strict filters that would let nothing through and with
    /// inserts set to same case as the others.
    #[test]
    fn multiple_mods_with_region_filtering_strict_mod_prob_filter_no_ins_lowercase()
    -> Result<(), Error> {
        let sim = create_multi_mod_simulation()?;

        // Test a small region
        let mods_for_region = InputModsBuilder::<OptionalTag>::default()
            .region_bed3(Bed3::<i32, u64>::new(0, 495, 505))
            .mod_prob_filter(ThresholdState::Both((250u8, (100u8, 150u8).try_into()?)))
            .build()?;

        let df = run_reads_table_generation(
            &sim,
            Some(mods_for_region),
            SeqDisplayOptions::Region {
                show_base_qual: false,
                show_ins_lowercase: false,
                show_mod_z: true,
                region: Bed3::<i32, u64>::new(0, 495, 505),
            },
        )?;

        let mod_count_col = df.column("mod_count")?.str()?;
        let alignment_type_col = df.column("alignment_type")?.str()?;
        let seq_col = df.column("sequence")?.str()?;

        // Verify both mod types are present but with region-limited counts and correct sequence.
        // The sequence here is "TACGTggttggACGTA" but without lowercase for the insert.
        for (mod_count, aln_type, seq) in izip!(mod_count_col, alignment_type_col, seq_col) {
            match aln_type.unwrap() {
                "unmapped" => {
                    // Unmapped reads show mod count of 0 when region filtering is applied
                    assert_eq!(
                        mod_count.unwrap(),
                        "a:0;m:0",
                        "unmapped reads should have zero counts with region filtering"
                    );
                    assert_eq!(
                        seq,
                        Some("*"),
                        "unmapped reads should have a * for sequence"
                    );
                }
                "primary_forward" | "secondary_forward" | "supplementary_forward" => {
                    let count_str = mod_count.unwrap();
                    let seq_str = seq.unwrap();
                    assert_eq!(
                        count_str, "a:0;m:0",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                    assert_eq!(
                        seq_str, "TACGTGGTTGGACGTA",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                }
                "primary_reverse" | "secondary_reverse" | "supplementary_reverse" => {
                    let count_str = mod_count.unwrap();
                    let seq_str = seq.unwrap();
                    assert_eq!(
                        count_str, "a:0;m:0",
                        "incorrect mod counts in reverse: {count_str}"
                    );
                    assert_eq!(
                        seq_str, "TACGTGGTTGGACGTA",
                        "incorrect mod counts in unmapped/forward: {count_str}"
                    );
                }
                _ => unreachable!("read states fall in the above 7 categories"),
            }
        }

        Ok(())
    }
}