pmdshodh 0.3.5

Per-read post-mortem damage (PMD) scoring and filtering of ancient DNA alignments, compatible with PMDtools
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
use std::fs::File;
use std::io::{self, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum};
use noodles_util::alignment;

use noodles::sam::alignment::Record as _;
use pmdshodh::damage::DamageCounts;
use pmdshodh::model::Params;
use pmdshodh::reads::{Outcome, ReadFilters, SkipReason, process, process_bam};
use pmdshodh::reference::Reference;
use pmdshodh::sites::ReadScore;
use pmdshodh::sites::{Library, Settings, Treatment};
use pmdshodh::summary::{RunInfo, Summary};

mod display;

/// Per-read post-mortem damage (PMD) scores for ancient DNA alignments.
#[derive(Parser)]
#[command(name = "pmdshodh", bin_name = "pmdshodh", version, after_help = TOP_EXAMPLES)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Keep reads by PMD score and write them as SAM or BAM.
    #[command(after_help = FILTER_EXAMPLES)]
    Filter(FilterArgs),
    /// Write a table of per-read PMD scores (TSV).
    #[command(after_help = SCORE_EXAMPLES)]
    Score(ScoreArgs),
    /// Write the JSON run summary only: read counts, score histogram and damage table.
    #[command(after_help = DAMAGE_EXAMPLES)]
    Damage(DamageArgs),
    /// Write an HTML damage report from one or more JSON run summaries.
    #[command(after_help = REPORT_EXAMPLES)]
    Report(ReportArgs),
}

const TOP_EXAMPLES: &str = "\
Examples:
  # Keep reads with PMD score >= 3 (reference bases from MD tags, or from -r)
  pmdshodh filter -t 3 -@ 8 in.bam -o out.bam
  pmdshodh filter -t 3 -@ 8 -r ref.fa in.cram -o out.bam

  # Damage tables and a JSON summary, then an HTML report
  pmdshodh damage -@ 8 in.bam -o run.json
  pmdshodh report run.json -o report.html

Run 'pmdshodh <command> --help' for each command's options and examples.";

const FILTER_EXAMPLES: &str = "\
Examples:
  # Keep reads with PMD score >= 3, as
  # samtools view -h in.bam | pmdtools --threshold 3 --header | samtools view -b -o out.bam -
  pmdshodh filter -t 3 -@ 8 in.bam -o out.bam

  # Single-stranded, UDG-half library; add the score as a pm tag and write a JSON summary
  pmdshodh filter -t 3 --library ss --treatment half --tag --summary run.json in.bam -o out.bam

  # In a pipe: SAM or BAM in on stdin, BAM out on stdout
  samtools view -h -q 30 in.bam | pmdshodh filter -t 3 - -o - | samtools sort -o out.bam";

const SCORE_EXAMPLES: &str = "\
Examples:
  # One line per read: read_name, flag, pmds, n_sites
  pmdshodh score -@ 8 in.bam -o scores.tsv

  # Scores as PMDtools 0.60 computes them, including its known bugs (for comparisons)
  pmdshodh score --pmdtools-compat in.bam -o scores.tsv";

const DAMAGE_EXAMPLES: &str = "\
Examples:
  # Substitution rates by position, score histogram and read counts as JSON
  pmdshodh damage -@ 8 in.bam -o damage.json

  # Only the first 100,000 reads (PMDtools -n)
  pmdshodh damage -n 100000 in.bam -o damage.json";

const REPORT_EXAMPLES: &str = "Examples:
  # One sample, from a summary written by damage -o, filter --summary or score --summary
  pmdshodh report run.json -o report.html

  # Several samples in one report, with their damage curves and score histograms overlaid
  pmdshodh report run.json damage.json -o report.html";

#[derive(Args)]
struct ReportArgs {
    /// JSON run summaries (from damage -o, filter --summary or score --summary).
    #[arg(required = true)]
    summaries: Vec<PathBuf>,
    /// Output HTML file ("-" for stdout).
    #[arg(help_heading = "Output", short, long)]
    output: PathBuf,
    /// Do not print the one-line note to stderr.
    #[arg(long)]
    quiet: bool,
}

#[derive(Args)]
struct DamageArgs {
    /// Input SAM, BAM or CRAM file ("-" for stdin; CRAM needs -r).
    input: PathBuf,
    /// Output JSON file (default: stdout).
    #[arg(help_heading = "Output", short, long)]
    output: Option<PathBuf>,
    /// Positions from each read end in the damage table (PMDtools --range).
    #[arg(
        help_heading = "Summary",
        long,
        default_value_t = 30,
        allow_negative_numbers = true
    )]
    range: usize,
    /// Stop after this many input reads (PMDtools -n). Exits normally.
    #[arg(
        help_heading = "Input",
        short = 'n',
        long,
        visible_alias = "number",
        allow_negative_numbers = true
    )]
    max_reads: Option<u64>,
    #[command(flatten)]
    model: ModelArgs,
    /// Do not print the run summary to stderr.
    #[arg(long)]
    quiet: bool,
}

#[derive(Args)]
#[command(group(ArgGroup::new("bounds").args(["threshold", "upper_threshold"]).required(true).multiple(true)))]
struct FilterArgs {
    /// Input SAM, BAM or CRAM file ("-" for stdin; CRAM needs -r).
    input: PathBuf,
    /// Output file; format from the extension (.bam or .sam). "-" writes BAM to stdout.
    #[arg(help_heading = "Output", short, long)]
    output: PathBuf,
    /// Output format for stdout ("-o -") and devices such as /dev/null [default: bam].
    #[arg(help_heading = "Output", long, value_enum)]
    output_format: Option<OutputFormat>,
    /// Keep reads with PMD score >= this (PMDtools -t/--threshold).
    #[arg(
        help_heading = "Filtering",
        short = 't',
        long,
        allow_negative_numbers = true
    )]
    threshold: Option<f64>,
    /// Keep reads with PMD score < this (PMDtools --upperthreshold). Reads with no informative
    /// sites carry no evidence and are not kept (PMDtools keeps them; so does --pmdtools-compat).
    #[arg(
        help_heading = "Filtering",
        long,
        visible_alias = "upperthreshold",
        allow_negative_numbers = true
    )]
    upper_threshold: Option<f64>,
    /// Add the PMD score to kept reads as a tag (overwrites an existing tag of that name).
    #[arg(help_heading = "Output", long)]
    tag: bool,
    /// Tag name: "pm" (pm:f, 32-bit float) or "DS" (DS:Z, 3 decimals, as PMDtools --writesamfield).
    #[arg(
        help_heading = "Output",
        long,
        value_enum,
        default_value = "pm",
        requires = "tag"
    )]
    tag_name: TagName,
    /// Accepted for PMDtools compatibility and ignored: a header is always written.
    #[arg(long, hide = true)]
    header: bool,
    #[command(flatten)]
    summary: SummaryArgs,
    #[command(flatten)]
    model: ModelArgs,
    /// Do not print the run summary to stderr.
    #[arg(long)]
    quiet: bool,
}

#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
enum OutputFormat {
    Bam,
    Sam,
}

#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
enum TagName {
    #[value(name = "pm")]
    Pm,
    #[value(name = "DS")]
    Ds,
}

#[derive(Args)]
struct ScoreArgs {
    /// Input SAM, BAM or CRAM file ("-" for stdin; CRAM needs -r).
    input: PathBuf,
    /// Output TSV file (default: stdout; "-" also writes to stdout).
    #[arg(help_heading = "Output", short, long)]
    output: Option<PathBuf>,
    #[command(flatten)]
    summary: SummaryArgs,
    #[command(flatten)]
    model: ModelArgs,
    /// Do not print the run summary to stderr.
    #[arg(long)]
    quiet: bool,
}

#[derive(Clone, Copy, ValueEnum)]
enum LibraryArg {
    Ds,
    Ss,
}

#[derive(Clone, Copy, ValueEnum)]
enum TreatmentArg {
    None,
    Half,
    Full,
}

/// Scoring options shared by all subcommands. PMDtools option names are accepted as aliases.
#[derive(Args)]
#[command(group(ArgGroup::new("library_choice").args(["library", "ss"])))]
#[command(group(ArgGroup::new("treatment_choice").args(["treatment", "udg_minus", "udg_half", "udg_plus"])))]
struct ModelArgs {
    /// Library type: double-stranded (ds) or single-stranded (ss). Never guessed from the data.
    #[arg(help_heading = "Scoring model", long, value_enum, default_value = "ds")]
    library: LibraryArg,
    /// Same as --library ss (PMDtools option).
    #[arg(help_heading = "Scoring model", long)]
    ss: bool,
    /// UDG treatment: none (all C/G sites), half (CpG sites plus the terminal base), full (CpG only).
    #[arg(
        help_heading = "Scoring model",
        long,
        value_enum,
        default_value = "none"
    )]
    treatment: TreatmentArg,
    /// Same as --treatment none (PMDtools option).
    #[arg(help_heading = "Scoring model", long = "UDGminus")]
    udg_minus: bool,
    /// Same as --treatment half (PMDtools option).
    #[arg(help_heading = "Scoring model", long = "UDGhalf")]
    udg_half: bool,
    /// Same as --treatment full (PMDtools --UDGplus / --CpG).
    #[arg(
        help_heading = "Scoring model",
        long = "UDGplus",
        visible_alias = "CpG"
    )]
    udg_plus: bool,
    /// Geometric decay of damage away from the read end (PMDtools --PMDpparam).
    #[arg(
        help_heading = "Scoring model",
        long,
        visible_alias = "PMDpparam",
        default_value_t = 0.3,
        allow_negative_numbers = true
    )]
    pmd_p: f64,
    /// Damage added at every position (PMDtools --PMDconstant).
    #[arg(
        help_heading = "Scoring model",
        long,
        visible_alias = "PMDconstant",
        default_value_t = 0.01,
        allow_negative_numbers = true
    )]
    pmd_c: f64,
    /// Polymorphism rate in the ancient model (PMDtools --polymorphism_ancient).
    #[arg(
        help_heading = "Scoring model",
        long,
        visible_alias = "polymorphism_ancient",
        default_value_t = 0.001,
        allow_negative_numbers = true
    )]
    pi_ancient: f64,
    /// Polymorphism rate in the null model (PMDtools --polymorphism_contamination).
    #[arg(
        help_heading = "Scoring model",
        long,
        visible_alias = "polymorphism_contamination",
        default_value_t = 0.001,
        allow_negative_numbers = true
    )]
    pi_contamination: f64,
    /// Skip reads with mapping quality below this (PMDtools -m).
    #[arg(
        help_heading = "Read filters",
        short = 'm',
        long,
        visible_alias = "requiremapq",
        default_value_t = 0,
        allow_negative_numbers = true
    )]
    min_mapq: u8,
    /// Ignore bases with base quality below this (PMDtools -q).
    #[arg(
        help_heading = "Read filters",
        short = 'q',
        long,
        visible_alias = "requirebaseq",
        default_value_t = 0,
        allow_negative_numbers = true
    )]
    min_baseq: u8,
    /// Skip reads with soft or hard clips (PMDtools --noclips).
    #[arg(help_heading = "Read filters", long, visible_alias = "noclips")]
    no_clips: bool,
    /// Skip reads with insertions or deletions (PMDtools --noindels).
    #[arg(help_heading = "Read filters", long, visible_alias = "noindels")]
    no_indels: bool,
    /// Reproduce PMDtools 0.60 exactly, including its bugs: the reference rebuilt wrongly for reads
    /// combining an insertion or soft clip with a deletion or '=' CIGAR operations, CpG context
    /// wrapping around the read ends, and PMDtools' CpG rule for damage tables. For comparisons.
    #[arg(help_heading = "Scoring model", long)]
    pmdtools_compat: bool,
    /// Threads to use: at most this many do work at once (reading, scoring, BGZF
    /// compression and writing). Output is identical for any value.
    #[arg(
        help_heading = "Performance",
        short = '@',
        long,
        default_value_t = 1,
        allow_negative_numbers = true
    )]
    threads: usize,
    /// Reference FASTA, indexed with samtools faidx (bgzip also needs its .gzi). Reference bases
    /// come from it instead of MD tags, so reads need no MD tag; MD tags are checked against it.
    /// Required for CRAM input.
    #[arg(help_heading = "Input", short = 'r', long)]
    reference: Option<PathBuf>,
}

impl ModelArgs {
    fn settings(&self) -> Result<(Settings, ReadFilters), String> {
        for (name, v) in [
            ("--pmd-p", self.pmd_p),
            ("--pmd-c", self.pmd_c),
            ("--pi-ancient", self.pi_ancient),
            ("--pi-contamination", self.pi_contamination),
        ] {
            if !(0.0..=1.0).contains(&v) {
                return Err(format!("{name} must be between 0 and 1, got {v}"));
            }
        }
        // The damage rate is largest at the read end, p + c; above 1 the scores are NaN.
        if pmdshodh::model::damage(1, self.pmd_p, self.pmd_c) > 1.0 {
            return Err(format!(
                "--pmd-p + --pmd-c is the damage rate at the read end and must be at most 1, got {} + {}",
                self.pmd_p, self.pmd_c
            ));
        }
        let library = if self.ss {
            Library::SingleStranded
        } else {
            match self.library {
                LibraryArg::Ds => Library::DoubleStranded,
                LibraryArg::Ss => Library::SingleStranded,
            }
        };
        let treatment = if self.udg_half {
            Treatment::Half
        } else if self.udg_plus {
            Treatment::Full
        } else if self.udg_minus {
            Treatment::None
        } else {
            match self.treatment {
                TreatmentArg::None => Treatment::None,
                TreatmentArg::Half => Treatment::Half,
                TreatmentArg::Full => Treatment::Full,
            }
        };
        let settings = Settings {
            library,
            treatment,
            params: Params {
                p: self.pmd_p,
                c: self.pmd_c,
                pi_ancient: self.pi_ancient,
                pi_contamination: self.pi_contamination,
            },
            min_baseq: self.min_baseq,
            pmdtools_compat: self.pmdtools_compat,
        };
        let filters = ReadFilters {
            min_mapq: self.min_mapq,
            no_clips: self.no_clips,
            no_indels: self.no_indels,
        };
        Ok((settings, filters))
    }
}

/// Exit status: 1 for runtime failures, 2 for invalid options or input (docs/design.md 4.5).
enum Failure {
    Input(String),
    Runtime(String),
    /// The reader of stdout closed it (`| head`): exit quietly with status 141, as a process
    /// killed by SIGPIPE does (samtools behaves this way).
    BrokenPipe,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    clean_up_on_signals();
    let result = match cli.command {
        Command::Filter(args) => run_filter(&args),
        Command::Score(args) => run_score(&args),
        Command::Damage(args) => run_damage(&args),
        Command::Report(args) => run_report(&args),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(Failure::BrokenPipe) => ExitCode::from(141),
        Err(Failure::Input(msg)) => {
            eprintln!("pmdshodh: error: {msg}");
            ExitCode::from(2)
        }
        Err(Failure::Runtime(msg)) => {
            eprintln!("pmdshodh: error: {msg}");
            ExitCode::from(1)
        }
    }
}

fn open_input(path: &PathBuf) -> Result<Box<dyn Read + Send>, Failure> {
    if path.as_os_str() == "-" {
        Ok(Box::new(io::stdin()))
    } else {
        let file = File::open(path)
            .map_err(|e| Failure::Input(format!("cannot open {}: {e}", path.display())))?;
        if let Ok(m) = file.metadata()
            && m.is_file()
        {
            display::set_input_size(m.len());
        }
        Ok(Box::new(display::Counting(file)))
    }
}

/// Options for the JSON run summary.
#[derive(Args)]
struct SummaryArgs {
    /// Also write a JSON run summary (counts, score histogram, damage table) to this file.
    #[arg(help_heading = "Summary", long)]
    summary: Option<PathBuf>,
    /// Positions from each read end in the damage table (PMDtools --range).
    #[arg(
        help_heading = "Summary",
        long,
        default_value_t = 30,
        allow_negative_numbers = true
    )]
    range: usize,
}

/// SAM and BAM go through noodles' reader; CRAM is decoded container by container on the pool.
enum InputReader {
    Alignment(alignment::io::Reader<Box<dyn Read + Send>>),
    Cram(pmdshodh::cram::Reader),
}
type AlignmentRecord = alignment::Record;

/// Input format, detected from the file contents.
#[derive(Clone, Copy)]
enum InputFormat {
    Sam,
    Bam,
    Cram,
}

impl InputFormat {
    fn name(self) -> &'static str {
        match self {
            InputFormat::Sam => "sam",
            InputFormat::Bam => "bam",
            InputFormat::Cram => "cram",
        }
    }
}

/// Open `-r` (if given) and the input, and check the input header against the reference before
/// any record is read. CRAM is decoded with `-r` only (docs/design.md section 11). Also returns
/// how many header sequences are missing from the reference.
fn open_alignments(
    path: &Path,
    model: &ModelArgs,
) -> Result<
    (
        InputReader,
        noodles::sam::Header,
        Option<Reference>,
        InputFormat,
        usize,
    ),
    Failure,
> {
    use std::io::BufRead;
    let reference_path = model.reference.as_deref();
    let mut reference = open_reference(reference_path)?;
    let cannot_read = |e: io::Error| Failure::Input(format!("cannot read {}: {e}", path.display()));
    let mut input = io::BufReader::new(open_input(&path.to_path_buf())?);
    let head = input.fill_buf().map_err(cannot_read)?;
    // No bytes at all is not an alignment file (samtools refuses it too); it usually means an
    // upstream step failed. A file with only a header is valid input.
    if head.is_empty() {
        return Err(Failure::Input(empty_input(path)));
    }
    let bgzf = head.starts_with(&[0x1f, 0x8b]);
    // BGZF sets FEXTRA (for its block size); plain gzip, as `gzip` writes it, does not.
    if bgzf && head.get(3).is_some_and(|flags| flags & 0x04 == 0) {
        return Err(Failure::Input(format!(
            "{} is gzip-compressed but not BGZF: recompress it with bgzip",
            path.display()
        )));
    }
    let mut source: Box<dyn BufRead + Send> = if bgzf {
        Box::new(io::BufReader::new(pmdshodh::bgzf::Reader::new(
            input,
            model.threads > 1,
        )))
    } else {
        Box::new(input)
    };
    let magic = source.fill_buf().map_err(cannot_read)?;
    if magic.is_empty() {
        return Err(Failure::Input(empty_input(path)));
    }
    let format = if magic.starts_with(b"CRAM") {
        InputFormat::Cram
    } else if magic.starts_with(b"BAM\x01") {
        InputFormat::Bam
    } else {
        if let Some(what) = not_sam(magic) {
            return Err(Failure::Input(format!(
                "{} is not SAM, BAM or CRAM: {what}",
                shown(path)
            )));
        }
        InputFormat::Sam
    };
    let source: Box<dyn Read + Send> = Box::new(source);
    let invalid_header = |e: io::Error| Failure::Input(format!("invalid header: {e}"));
    let (reader, header) = if let InputFormat::Cram = format {
        let (Some(r), Some(p)) = (reference.as_mut(), reference_path) else {
            return Err(Failure::Input(format!(
                "{} is CRAM, which needs its reference: pass it with -r FILE",
                path.display()
            )));
        };
        let mut reader = pmdshodh::cram::Reader::new(source);
        let header = reader.read_header().map_err(invalid_header)?;
        r.enable_cram(p, &header)
            .map_err(|e| reference_error(p, e))?;
        (InputReader::Cram(reader), header)
    } else {
        use noodles_util::alignment::io::Format;
        let mut reader = alignment::io::reader::Builder::default()
            .set_compression_method(None)
            .set_format(match format {
                InputFormat::Bam => Format::Bam,
                _ => Format::Sam,
            })
            .build_from_reader(source)
            .map_err(cannot_read)?;
        let header = reader.read_header().map_err(invalid_header)?;
        (InputReader::Alignment(reader), header)
    };
    let missing = match (reference.as_ref(), reference_path) {
        (Some(r), Some(p)) => check_reference(r, p, &header)?,
        _ => 0,
    };
    Ok((reader, header, reference, format, missing))
}

/// The input as the user named it ("-" is standard input).
fn shown(path: &Path) -> String {
    if path.as_os_str() == "-" {
        "standard input".into()
    } else {
        path.display().to_string()
    }
}

fn empty_input(path: &Path) -> String {
    format!(
        "{} is empty (no data): expected SAM, BAM or CRAM",
        shown(path)
    )
}

/// Why the start of an input that is neither BAM nor CRAM cannot be SAM, if it cannot.
fn not_sam(start: &[u8]) -> Option<&'static str> {
    let start = &start[..start.len().min(512)];
    if start
        .iter()
        .any(|&b| (b < 0x20 && !matches!(b, b'\t' | b'\n' | b'\r')) || b == 0x7f)
    {
        return Some("it is binary data");
    }
    match start.first() {
        Some(b'>') => Some("it looks like FASTA (sequences, not alignments)"),
        // SAM header lines are @HD, @SQ, @RG, @PG or @CO followed by a tab; FASTQ starts with @name.
        Some(b'@')
            if start.len() >= 4
                && !(matches!(&start[1..3], b"HD" | b"SQ" | b"RG" | b"PG" | b"CO")
                    && start[3] == b'\t') =>
        {
            Some("it looks like FASTQ (reads that are not aligned yet)")
        }
        _ => None,
    }
}

/// A record names its reference and its mate's by @SQ line; BAM stores the line's index, so a
/// name the header lacks cannot be written.
fn check_reference_ids(
    record: &AlignmentRecord,
    header: &noodles::sam::Header,
) -> Result<(), String> {
    let n = header.reference_sequences().len();
    for (what, id) in [
        ("reference", record.reference_sequence_id(header)),
        (
            "mate's reference",
            record.mate_reference_sequence_id(header),
        ),
    ] {
        match id {
            Some(Ok(i)) if i < n => {}
            None => {}
            _ => {
                return Err(format!(
                    "its {what} is not in the header (no @SQ line for it)"
                ));
            }
        }
    }
    Ok(())
}

/// Read every record (or the first `max_reads`), count it in `summary`, and pass scored reads to
/// `on_scored`, which returns whether the read was kept (`None` when there is no filtering).
/// Records read and scored per batch; bounds memory independently of the input size.
const BATCH: usize = 10_000;

/// Read every record (or the first `max_reads`), count it in `summary`, and pass scored reads to
/// `on_scored` in input order; it returns whether the read was kept (`None` without filtering).
/// Scoring runs on the rayon thread pool; results and summary are independent of the thread count.
///
/// With more than one thread, the stages overlap: the pool scores up to [`SCORED_AHEAD`] batches
/// while one pool thread reads the next and consumes the oldest. That thread does all serial work
/// (reading, consuming, writing) and runs other pool jobs (scoring, BGZF) while it waits. Batches are consumed in input
/// order, so output and summary are the same as the sequential loop used with one thread.
#[allow(clippy::too_many_arguments)]
fn scan(
    reader: &mut InputReader,
    header: &noodles::sam::Header,
    reference: &mut Option<Reference>,
    settings: &Settings,
    filters: &ReadFilters,
    summary: &mut Summary,
    count_damage: bool,
    max_reads: Option<u64>,
    threads: usize,
    progress: &mut display::Progress,
    mut on_scored: impl FnMut(&AlignmentRecord, &ReadScore) -> Result<Option<bool>, Failure> + Send,
) -> Result<(), Failure> {
    // Damage tables are only written to the JSON summary; counting them is a quarter of the work.
    let range = count_damage.then_some(summary.damage.range);
    if threads == 1 {
        let mut n_read = 0u64;
        loop {
            let mut batch = read_batch(reader, header, reference, max_reads, &mut n_read)?;
            if batch.is_empty() {
                return Ok(());
            }
            progress.tick(n_read);
            batch.decode(header)?;
            let parts = score_batch(&batch, settings, filters, range);
            let first = n_read - batch.len() as u64;
            consume_batch(&batch.records, &parts, first, summary, &mut on_scored)?;
        }
    }

    // The serial loop runs on a pool thread, so the pool's `threads` threads are all there is;
    // the calling thread just waits.
    rayon::scope(|s| {
        let spawn = |mut batch: Batch| {
            let (tx, rx) = std::sync::mpsc::sync_channel(1);
            s.spawn(move |_| {
                let parts = batch
                    .decode(header)
                    .map(|()| score_batch(&batch, settings, filters, range));
                let _ = tx.send((batch, parts));
            });
            rx
        };
        // A task that panicked drops its sender; the scope then re-raises that panic.
        let join = |rx: std::sync::mpsc::Receiver<(Batch, Result<Scored, Failure>)>| {
            pmdshodh::bgzf::wait_for(&rx).expect("scoring task panicked")
        };
        let mut n_read = 0u64;
        let mut first = 0u64;
        let mut in_flight = std::collections::VecDeque::new();
        let mut consume_oldest = |in_flight: &mut std::collections::VecDeque<_>| {
            let (batch, parts) = join(in_flight.pop_front().unwrap());
            consume_batch(&batch.records, &parts?, first, summary, &mut on_scored)?;
            first += batch.len() as u64;
            Ok::<(), Failure>(())
        };
        loop {
            match read_batch(reader, header, reference, max_reads, &mut n_read) {
                Ok(batch) if !batch.is_empty() => {
                    progress.tick(n_read);
                    in_flight.push_back(spawn(batch));
                }
                Ok(_) => {
                    while !in_flight.is_empty() {
                        consume_oldest(&mut in_flight)?;
                    }
                    return Ok(());
                }
                Err(e) => {
                    // Earlier reads come first: report their errors before the read error.
                    while !in_flight.is_empty() {
                        consume_oldest(&mut in_flight)?;
                    }
                    return Err(e);
                }
            }
            if in_flight.len() > SCORED_AHEAD {
                consume_oldest(&mut in_flight)?;
            }
        }
    })
}

/// Batches scored on the pool while the serial thread consumes an older one (several threads).
const SCORED_AHEAD: usize = 2;

/// Outcomes and damage counts (if counted) of one batch, in input order, one entry per scoring
/// chunk.
type Scored = Vec<(Vec<Result<Outcome, String>>, Option<DamageCounts>)>;

/// Records read together, and with `-r` each mapped record's reference window.
struct Batch {
    records: Vec<AlignmentRecord>,
    /// All windows back to back; `windows[i]` is record `i`'s range in it.
    bases: Vec<u8>,
    windows: Vec<Option<std::ops::Range<usize>>>,
    /// CRAM containers still to decode into `records`, `bases` and `windows`.
    cram: Option<CramBatch>,
}

/// CRAM containers read on the serial thread and decoded with the batch's scoring, on the pool,
/// so the serial thread can load the next batch's reference sequences meanwhile.
struct CramBatch {
    containers: Vec<noodles::cram::io::reader::Container>,
    repository: noodles::fasta::Repository,
    /// `M5` checks of the reference sequences this batch loaded; all must pass before its records
    /// are used.
    checks: std::sync::Mutex<Vec<pmdshodh::reference::Md5Check>>,
    /// Records kept (fewer than decoded when `max_reads` ends in this batch).
    keep: usize,
    /// Records before this batch.
    first: u64,
}

impl Batch {
    fn len(&self) -> usize {
        self.records.len() + self.cram.as_ref().map_or(0, |c| c.keep)
    }

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Decode CRAM containers, if any (on the pool).
    fn decode(&mut self, header: &noodles::sam::Header) -> Result<(), Failure> {
        let Some(c) = self.cram.take() else {
            return Ok(());
        };
        let error = |e: io::Error| {
            Failure::Input(format!(
                "CRAM records {} to {}: {e}",
                c.first + 1,
                c.first + c.keep as u64
            ))
        };
        for check in c.checks.into_inner().unwrap() {
            pmdshodh::bgzf::wait_for(&check)
                .unwrap_or_else(|| Err(io::Error::other("M5 check stopped")))
                .map_err(error)?;
        }
        let decoded =
            pmdshodh::cram::decode(&c.containers, &c.repository, header).map_err(error)?;
        self.bases = decoded.bases;
        self.windows = decoded.windows;
        self.windows.truncate(c.keep);
        self.records = decoded
            .records
            .into_iter()
            .take(c.keep)
            .map(AlignmentRecord::Cram)
            .collect();
        Ok(())
    }

    fn window(&self, i: usize) -> Option<&[u8]> {
        self.windows.get(i)?.clone().map(|r| &self.bases[r])
    }
}

/// Read up to [`BATCH`] records (CRAM: one container per pool thread); an empty batch means the
/// end of the input (or of `max_reads`). With a reference, fetch each mapped record's window
/// here, on the serial thread (CRAM: on the pool, while decoding).
fn read_batch(
    reader: &mut InputReader,
    header: &noodles::sam::Header,
    reference: &mut Option<Reference>,
    max_reads: Option<u64>,
    n_read: &mut u64,
) -> Result<Batch, Failure> {
    let reader = match reader {
        InputReader::Alignment(reader) => reader,
        InputReader::Cram(reader) => {
            return read_cram_batch(reader, header, reference, max_reads, n_read);
        }
    };
    let mut batch = Batch {
        records: Vec::with_capacity(BATCH),
        bases: Vec::new(),
        windows: Vec::new(),
        cram: None,
    };
    while batch.len() < BATCH && max_reads.is_none_or(|m| *n_read < m) {
        let mut record = AlignmentRecord::default();
        let n = reader
            .read_record(header, &mut record)
            .map_err(|e| Failure::Input(format!("record {}: {e}", *n_read + 1)))?;
        if n == 0 {
            break;
        }
        *n_read += 1;
        if let Some(reference) = reference.as_mut() {
            let window =
                fetch_window(reference, header, &record, &mut batch.bases).map_err(|e| {
                    let name = record.name().map_or_else(|| "*".into(), |n| n.to_string());
                    Failure::Input(format!("record {} (read {name}): {e}", *n_read))
                })?;
            batch.windows.push(window);
        }
        batch.records.push(record);
    }
    Ok(batch)
}

/// Read one CRAM container per pool thread and load their reference sequences; they are decoded
/// on the pool (`Batch::decode`). Records are counted from the container headers.
fn read_cram_batch(
    reader: &mut pmdshodh::cram::Reader,
    header: &noodles::sam::Header,
    reference: &mut Option<Reference>,
    max_reads: Option<u64>,
    n_read: &mut u64,
) -> Result<Batch, Failure> {
    let error = |e: io::Error| Failure::Input(format!("CRAM records after record {n_read}: {e}"));
    let mut batch = Batch {
        records: Vec::new(),
        bases: Vec::new(),
        windows: Vec::new(),
        cram: None,
    };
    if max_reads.is_some_and(|m| *n_read >= m) {
        return Ok(batch);
    }
    let containers = reader
        .read_containers(rayon::current_num_threads())
        .map_err(error)?;
    let ids: Vec<usize> = containers
        .iter()
        .filter_map(pmdshodh::cram::reference_sequence_id)
        .collect();
    let (repository, checks) = reference
        .as_mut()
        .expect("CRAM input is opened with -r")
        .cram_batch(header, &ids)
        .map_err(error)?;
    let records: u64 = containers
        .iter()
        .map(|c| c.header().record_count() as u64)
        .sum();
    let keep = max_reads.map_or(records, |m| records.min(m - *n_read));
    if keep > 0 {
        batch.cram = Some(CramBatch {
            containers,
            repository,
            checks: checks.into(),
            keep: keep as usize,
            first: *n_read,
        });
        *n_read += keep;
    }
    Ok(batch)
}

/// Append a mapped record's reference bases (alignment start, CIGAR reference span) to `bases`
/// and return their range; `None` for an unmapped record.
fn fetch_window(
    reference: &mut Reference,
    header: &noodles::sam::Header,
    record: &AlignmentRecord,
    bases: &mut Vec<u8>,
) -> io::Result<Option<std::ops::Range<usize>>> {
    if record.flags()?.is_unmapped() {
        return Ok(None);
    }
    let invalid = |msg: &str| io::Error::new(io::ErrorKind::InvalidData, msg.to_string());
    let id = record
        .reference_sequence_id(header)
        .transpose()?
        .ok_or_else(|| invalid("mapped read has no reference sequence"))?;
    let start = record
        .alignment_start()
        .transpose()?
        .ok_or_else(|| invalid("mapped read has no position"))?;
    let span = record.alignment_span().transpose()?.unwrap_or(0);
    let (name, _) = header
        .reference_sequences()
        .get_index(id)
        .ok_or_else(|| invalid("reference sequence ID is not in the header"))?;
    let name = std::str::from_utf8(name).map_err(|_| invalid("reference name is not UTF-8"))?;
    let from = bases.len();
    reference.fetch(name, usize::from(start) - 1, span, bases)?;
    Ok(Some(from..bases.len()))
}

/// Open `-r`; a missing file or index is an input error.
fn open_reference(path: Option<&Path>) -> Result<Option<Reference>, Failure> {
    let Some(path) = path else {
        return Ok(None);
    };
    if !path.exists() {
        return Err(Failure::Input(format!(
            "cannot open reference {}: no such file",
            path.display()
        )));
    }
    Reference::open(path)
        .map(Some)
        .map_err(|e| reference_error(path, e))
}

fn reference_error(path: &Path, e: io::Error) -> Failure {
    Failure::Input(format!(
        "cannot read reference {} or its index: {e} (index it with samtools faidx {})",
        path.display(),
        path.display()
    ))
}

/// Check the input header against the reference (docs/design.md section 11): a sequence in both
/// must have the same length, and at least one header sequence must be in the reference. Header
/// sequences missing from the reference are allowed, as with `samtools calmd` (issue #88); a read
/// mapped to one is an input error when it is read. Returns how many are missing.
fn check_reference(
    reference: &Reference,
    path: &Path,
    header: &noodles::sam::Header,
) -> Result<usize, Failure> {
    let mismatch = |what: String| {
        Failure::Input(format!(
            "reference {} does not match the input header ({what})",
            path.display()
        ))
    };
    let mut differ = Vec::new();
    let mut missing = Vec::new();
    for (name, seq) in header.reference_sequences() {
        let name = name.to_string();
        let len = usize::from(seq.length());
        match reference.length(&name) {
            Some(l) if l == len => {}
            Some(l) => differ.push(format!(
                "{name} has {len} bases in the header, {l} in the reference"
            )),
            None => missing.push(name),
        }
    }
    let n = header.reference_sequences().len();
    if let Some(first) = differ.first() {
        return Err(mismatch(format!(
            "{} of {n} sequences have a different length; {first}",
            differ.len()
        )));
    }
    if n > 0 && missing.len() == n {
        return Err(mismatch(if n == 1 {
            format!("{} is not in the reference", missing[0])
        } else {
            format!("none of the {n} header sequences is in the reference")
        }));
    }
    Ok(missing.len())
}

fn score_batch(
    batch: &Batch,
    settings: &Settings,
    filters: &ReadFilters,
    range: Option<usize>,
) -> Scored {
    use rayon::prelude::*;
    let chunk = batch.len().div_ceil(rayon::current_num_threads()).max(1);
    batch
        .records
        .par_chunks(chunk)
        .enumerate()
        .map(|(c, records)| {
            let mut damage = range.map(DamageCounts::new);
            let outcomes = records
                .iter()
                .enumerate()
                .map(|(k, r)| {
                    let window = batch.window(c * chunk + k);
                    match r {
                        AlignmentRecord::Bam(b) => {
                            process_bam(b, settings, filters, window, damage.as_mut())
                        }
                        _ => process(r, settings, filters, window, damage.as_mut()),
                    }
                })
                .collect();
            (outcomes, damage)
        })
        .collect()
}

/// Count a scored batch in `summary` and pass its scored reads to `on_scored`, in order.
/// `first` is the number of records before this batch (for error messages).
fn consume_batch(
    batch: &[AlignmentRecord],
    parts: &Scored,
    first: u64,
    summary: &mut Summary,
    on_scored: &mut impl FnMut(&AlignmentRecord, &ReadScore) -> Result<Option<bool>, Failure>,
) -> Result<(), Failure> {
    let outcomes = parts.iter().flat_map(|(o, _)| o.iter());
    for (k, (record, outcome)) in batch.iter().zip(outcomes).enumerate() {
        let flags = record.flags().map_err(|e| {
            Failure::Input(format!(
                "record {}: invalid FLAG: {e}",
                first + k as u64 + 1
            ))
        })?;
        summary.add_input(flags);
        match outcome {
            Ok(Outcome::Scored { score, length, md }) => {
                let kept = on_scored(record, score)?;
                summary.add_scored(score, *length, kept);
                summary.add_md_check(*md);
            }
            Ok(Outcome::Skipped(reason)) => summary.add_skipped(*reason),
            Err(msg) => {
                let name = record.name().map_or_else(|| "*".into(), |n| n.to_string());
                return Err(Failure::Input(format!("read {name}: {msg}")));
            }
        }
    }
    for damage in parts.iter().filter_map(|(_, d)| d.as_ref()) {
        summary.damage.merge(damage);
    }
    Ok(())
}

/// Largest --range: far beyond ancient DNA read lengths; each position costs memory per table.
const MAX_RANGE: usize = 1000;
/// Largest -@: far beyond any node, while still failing fast instead of starting threads for minutes.
const MAX_THREADS: usize = 1024;

/// The damage table needs at least the terminal position.
fn check_range(range: usize) -> Result<(), Failure> {
    if range == 0 {
        return Err(Failure::Input("--range must be at least 1".into()));
    }
    if range > MAX_RANGE {
        return Err(Failure::Input(format!(
            "--range must be at most {MAX_RANGE}, got {range}"
        )));
    }
    Ok(())
}

/// At most `threads` threads do work at once. With one, this thread does everything (the pool
/// thread only runs scoring while this thread waits). With more, the pool's `threads` threads do
/// all the work, one of them the serial part (scan, bgzf.rs), while this thread waits.
fn init_threads(threads: usize) -> Result<(), Failure> {
    if threads == 0 {
        return Err(Failure::Input("--threads must be at least 1".into()));
    }
    if threads > MAX_THREADS {
        return Err(Failure::Input(format!(
            "--threads must be at most {MAX_THREADS}, got {threads}"
        )));
    }
    rayon::ThreadPoolBuilder::new()
        .num_threads(threads)
        .build_global()
        .map_err(|e| Failure::Runtime(format!("cannot start threads: {e}")))
}

fn command_line() -> String {
    std::env::args().collect::<Vec<_>>().join(" ")
}

/// Write JSON to an output opened before the run, and commit it.
fn write_json(
    (output, mut w): (Output, Box<dyn Write + Send>),
    value: &serde_json::Value,
) -> Result<(), Failure> {
    let text = serde_json::to_string_pretty(value)
        .map_err(|e| Failure::Runtime(format!("cannot format summary: {e}")))?
        + "\n";
    let write_err = output.write_err();
    w.write_all(text.as_bytes()).map_err(&write_err)?;
    w.flush().map_err(&write_err)?;
    drop(w);
    output.commit()
}

/// Facts shared by the end of every subcommand.
struct Finish<'a> {
    subcommand: &'a str,
    input: &'a Path,
    input_format: InputFormat,
    settings: Settings,
    filters: ReadFilters,
    threshold: Option<f64>,
    upper_threshold: Option<f64>,
    reference: Option<&'a Path>,
    /// Header sequences missing from the reference (no read is mapped to them).
    missing_sequences: usize,
    /// The files written, as the user named them, for the summary block.
    outputs: Vec<String>,
}

/// An output as the user named it: `None` and "-" are standard output.
fn output_name(path: Option<&Path>) -> String {
    match path.filter(|p| p.as_os_str() != "-") {
        Some(p) => p.display().to_string(),
        None => "standard output".to_string(),
    }
}

impl Finish<'_> {
    fn json(&self, summary: &Summary) -> serde_json::Value {
        summary.to_json(&RunInfo {
            subcommand: self.subcommand,
            command: command_line(),
            input: self.input.display().to_string(),
            input_format: self.input_format.name(),
            settings: self.settings,
            filters: self.filters,
            threshold: self.threshold,
            upper_threshold: self.upper_threshold,
            reference: self.reference.map(|p| p.display().to_string()),
        })
    }

    /// The summary block on stderr, unless quiet (src/display.rs).
    fn report(
        &self,
        json: &serde_json::Value,
        summary: &Summary,
        quiet: bool,
        elapsed: std::time::Duration,
    ) {
        if quiet {
            return;
        }
        let r = &json["reads"];
        let count = |v: &serde_json::Value| v.as_u64().unwrap_or(0);
        let first = &json["damage"]["first_position"];
        let report = display::RunReport {
            subcommand: self.subcommand.to_string(),
            input: shown(self.input),
            format: self.input_format.name(),
            reference: self.reference.map(|p| p.display().to_string()),
            library: match self.settings.library {
                Library::DoubleStranded => "ds",
                Library::SingleStranded => "ss",
            },
            treatment: match self.settings.treatment {
                Treatment::None => "none",
                Treatment::Half => "half",
                Treatment::Full => "full",
            },
            compat: self.settings.pmdtools_compat,
            threshold: self.threshold,
            upper_threshold: self.upper_threshold,
            reads: count(&r["input"]),
            scored: count(&r["scored"]),
            no_sites: count(&r["no_informative_sites"]),
            kept: r["kept"].as_u64(),
            skipped: SkipReason::ALL
                .iter()
                .zip(summary.skipped())
                .filter(|(_, n)| **n > 0)
                .map(|(reason, n)| (reason.name(), *n))
                .collect(),
            first_base: (count(&first["n"]) > 0).then(|| {
                (
                    first["c_to_t"].as_f64().unwrap_or(0.0),
                    first["se"].as_f64().unwrap_or(0.0),
                    count(&first["n"]),
                )
            }),
            md_disagreeing: summary.md_disagreeing(),
            paired: count(&r["flags"]["paired"]),
            missing_sequences: self.missing_sequences,
            outputs: self.outputs.clone(),
            elapsed,
        };
        eprintln!("{}", report.render(display::Style::detect()));
    }
}

fn run_score(args: &ScoreArgs) -> Result<(), Failure> {
    let (settings, filters) = args.model.settings().map_err(Failure::Input)?;
    check_range(args.summary.range)?;
    init_threads(args.model.threads)?;
    check_outputs(
        &args.input,
        args.model.reference.as_deref(),
        &[args.output.as_deref(), args.summary.summary.as_deref()],
    )?;
    let mut progress = display::Progress::new("score", args.quiet);
    let (mut reader, header, mut reference, input_format, missing_sequences) =
        open_alignments(&args.input, &args.model)?;
    // Both outputs are created before any record is read, so a bad path fails at once.
    let (output, out) = Output::open(args.output.as_deref())?;
    let summary_out = args
        .summary
        .summary
        .as_deref()
        .map(|p| Output::open(Some(p)))
        .transpose()?;
    let mut out = BufWriter::new(out);
    let write_err = output.write_err();

    writeln!(out, "read_name\tflag\tpmds\tn_sites").map_err(&write_err)?;
    let mut summary = Summary::new(args.summary.range);
    let scanned = scan(
        &mut reader,
        &header,
        &mut reference,
        &settings,
        &filters,
        &mut summary,
        args.summary.summary.is_some(),
        None,
        args.model.threads,
        &mut progress,
        |record, s| {
            let name = record
                .name()
                .map_or_else(|| "*".to_string(), |n| n.to_string());
            let flag = record.flags().map(u16::from).unwrap_or_default();
            writeln!(out, "{name}\t{flag}\t{}\t{}", s.pmds, s.n_sites).map_err(&write_err)?;
            Ok(None)
        },
    );
    if let Err(e) = scanned {
        // Drop what is still buffered instead of flushing it: an error in the first records
        // then leaves stdout empty rather than holding a header and no reads.
        let _ = out.into_parts();
        return Err(e);
    }
    out.flush().map_err(&write_err)?;
    drop(out);
    output.commit()?;
    let fin = Finish {
        subcommand: "score",
        input: &args.input,
        input_format,
        settings,
        filters,
        threshold: None,
        upper_threshold: None,
        reference: args.model.reference.as_deref(),
        missing_sequences,
        outputs: [Some(output_name(args.output.as_deref()))]
            .into_iter()
            .chain([args
                .summary
                .summary
                .as_deref()
                .map(|p| output_name(Some(p)))])
            .flatten()
            .collect(),
    };
    let json = fin.json(&summary);
    if let Some(s) = summary_out {
        write_json(s, &json)?;
    }
    progress.clear();
    fin.report(&json, &summary, args.quiet, progress.elapsed());
    Ok(())
}

fn run_damage(args: &DamageArgs) -> Result<(), Failure> {
    let (settings, filters) = args.model.settings().map_err(Failure::Input)?;
    check_range(args.range)?;
    init_threads(args.model.threads)?;
    check_outputs(
        &args.input,
        args.model.reference.as_deref(),
        &[args.output.as_deref()],
    )?;
    let mut progress = display::Progress::new("damage", args.quiet);
    let (mut reader, header, mut reference, input_format, missing_sequences) =
        open_alignments(&args.input, &args.model)?;
    let json_out = Output::open(args.output.as_deref())?;
    let mut summary = Summary::new(args.range);
    scan(
        &mut reader,
        &header,
        &mut reference,
        &settings,
        &filters,
        &mut summary,
        true,
        args.max_reads,
        args.model.threads,
        &mut progress,
        |_, _| Ok(None),
    )?;
    let fin = Finish {
        subcommand: "damage",
        input: &args.input,
        input_format,
        settings,
        filters,
        threshold: None,
        upper_threshold: None,
        reference: args.model.reference.as_deref(),
        missing_sequences,
        outputs: vec![output_name(args.output.as_deref())],
    };
    let json = fin.json(&summary);
    write_json(json_out, &json)?;
    progress.clear();
    fin.report(&json, &summary, args.quiet, progress.elapsed());
    Ok(())
}

/// The report reads only the summaries, never alignments. The output is opened first, as for
/// the other subcommands, so a failed or interrupted run leaves nothing under its name.
fn run_report(args: &ReportArgs) -> Result<(), Failure> {
    for (i, path) in args.summaries.iter().enumerate() {
        if args.summaries[..i]
            .iter()
            .any(|earlier| earlier == path || same_file(earlier, path))
        {
            return Err(Failure::Input(format!("{} is given twice", path.display())));
        }
        check_outputs(path, None, &[Some(&args.output)])?;
    }
    let (output, mut w) = Output::open(Some(&args.output))?;
    let mut samples = Vec::new();
    for path in &args.summaries {
        let shown = path.display().to_string();
        let text =
            std::fs::read(path).map_err(|e| Failure::Input(format!("cannot read {shown}: {e}")))?;
        let json: serde_json::Value = serde_json::from_slice(&text)
            .map_err(|e| Failure::Input(format!("{shown} is not valid JSON: {e}")))?;
        samples.push(pmdshodh::report::parse(&shown, &json).map_err(Failure::Input)?);
    }
    let names: Vec<(&str, &str)> = samples
        .iter()
        .map(|s| (s.source.as_str(), s.input.as_str()))
        .collect();
    let labels = pmdshodh::report::labels(&names);
    for (s, label) in samples.iter_mut().zip(labels) {
        s.label = label;
    }
    let html = pmdshodh::report::render(&samples);
    let shown = output.shown.clone();
    let write_err = output.write_err();
    w.write_all(html.as_bytes()).map_err(&write_err)?;
    w.flush().map_err(&write_err)?;
    drop(w);
    output.commit()?;
    if !args.quiet {
        eprintln!(
            "pmdshodh report: {} sample{} written to {shown}",
            samples.len(),
            if samples.len() == 1 { "" } else { "s" }
        );
    }
    Ok(())
}

/// Format a score as PMDtools --writesamfield does: Python's str(round(x, 3)).
fn pmdtools_ds_text(x: f64) -> String {
    let mut s = format!("{x:.3}");
    while s.ends_with('0') && !s.ends_with(".0") {
        s.pop();
    }
    s
}

/// Where a command writes. A regular file, or a path that does not exist yet, is written under a
/// temporary name and renamed when the run succeeds, so a failed run leaves nothing under the
/// final name; a symlink is followed and the file it points to is replaced. Anything else that
/// exists (a FIFO, a device such as /dev/null, /dev/stdout, a process substitution) is written in
/// place: renaming over it would replace it.
struct Output {
    /// The output as the user named it, for messages.
    shown: String,
    /// Temporary file and final name, when written by rename.
    rename: Option<(PathBuf, PathBuf)>,
    to_stdout: bool,
}

impl Output {
    /// `None` or "-" is stdout.
    fn open(path: Option<&Path>) -> Result<(Self, Box<dyn Write + Send>), Failure> {
        let Some(path) = path.filter(|p| p.as_os_str() != "-") else {
            let out = Output {
                shown: "standard output".into(),
                rename: None,
                to_stdout: true,
            };
            return Ok((out, Box::new(io::stdout())));
        };
        let shown = path.display().to_string();
        let cannot = |e: io::Error| Failure::Runtime(format!("cannot create {shown}: {e}"));
        let dest = match std::fs::metadata(path) {
            _ if is_windows_device(path) => None,
            Ok(m) if m.is_dir() => {
                return Err(Failure::Input(format!("output {shown} is a directory")));
            }
            Ok(m) if m.is_file() => Some(std::fs::canonicalize(path).map_err(cannot)?),
            Ok(_) => None,
            // A dangling symlink: creating the file creates its target.
            Err(_) if path.symlink_metadata().is_ok() => None,
            Err(_) => Some(path.to_path_buf()),
        };
        let (file, rename) = match dest {
            Some(dest) => {
                let mut name = dest.file_name().unwrap_or_default().to_os_string();
                name.push(".pmdshodh-tmp");
                let tmp = dest.with_file_name(name);
                // Registered before it exists, so a signal at any point can remove it.
                temporary().push(tmp.clone());
                let file = File::create(&tmp).map_err(|e| {
                    forget_temporary(&tmp);
                    cannot(e)
                })?;
                (file, Some((tmp, dest)))
            }
            None => (File::create(path).map_err(cannot)?, None),
        };
        let out = Output {
            shown,
            rename,
            to_stdout: false,
        };
        Ok((out, Box::new(file)))
    }

    /// Error while writing; a reader that closed stdout ends the run quietly.
    fn write_err(&self) -> impl Fn(io::Error) -> Failure + Send + Sync + use<> {
        let (shown, to_stdout) = (self.shown.clone(), self.to_stdout);
        move |e| {
            if to_stdout && e.kind() == io::ErrorKind::BrokenPipe {
                Failure::BrokenPipe
            } else {
                Failure::Runtime(format!("cannot write {shown}: {e}"))
            }
        }
    }

    /// Give a renamed output its final name (call after the writer is closed).
    fn commit(mut self) -> Result<(), Failure> {
        if let Some((tmp, dest)) = self.rename.take() {
            let renamed = std::fs::rename(&tmp, &dest);
            if renamed.is_err() {
                let _ = std::fs::remove_file(&tmp);
            }
            forget_temporary(&tmp);
            if let Err(e) = renamed {
                return Err(Failure::Runtime(format!(
                    "cannot write {}: {e}",
                    self.shown
                )));
            }
        }
        Ok(())
    }
}

impl Drop for Output {
    fn drop(&mut self) {
        // Removes the temporary file if commit() was not reached.
        if let Some((tmp, _)) = &self.rename {
            let _ = std::fs::remove_file(tmp);
            forget_temporary(tmp);
        }
    }
}

/// Temporary files of outputs not yet renamed into place, removed if a signal ends the run.
static TEMPORARY: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());

fn temporary() -> std::sync::MutexGuard<'static, Vec<PathBuf>> {
    TEMPORARY.lock().unwrap_or_else(|e| e.into_inner())
}

fn forget_temporary(tmp: &Path) {
    temporary().retain(|p| p != tmp);
}

/// On SIGINT, SIGTERM or SIGHUP (Ctrl-C, a scheduler's time limit, a closed terminal), remove
/// the temporary files and end by the same signal, so the shell or scheduler still sees the
/// process as killed (status 130, 143 or 129). On Windows, Ctrl-C or Ctrl-Break removes them and
/// exits with status 130.
fn clean_up_on_signals() {
    fn remove_temporary() {
        for tmp in temporary().iter() {
            let _ = std::fs::remove_file(tmp);
        }
    }
    #[cfg(unix)]
    {
        use signal_hook::consts::{SIGHUP, SIGINT, SIGTERM};
        if let Ok(mut signals) = signal_hook::iterator::Signals::new([SIGINT, SIGTERM, SIGHUP]) {
            std::thread::spawn(move || {
                if let Some(signal) = signals.forever().next() {
                    remove_temporary();
                    let _ = signal_hook::low_level::emulate_default_handler(signal);
                    std::process::exit(128 + signal);
                }
            });
        }
    }
    #[cfg(windows)]
    {
        let _ = ctrlc::set_handler(|| {
            remove_temporary();
            std::process::exit(130);
        });
    }
}

/// An existing output that is not a regular file or directory: a FIFO or a device.
fn is_special(path: &Path) -> bool {
    is_windows_device(path) || std::fs::metadata(path).is_ok_and(|m| !m.is_file() && !m.is_dir())
}

/// Windows device names (NUL, CON, COM1, ...), which have no file metadata; a temporary file
/// next to one (NUL.pmdshodh-tmp) is the device again, so it cannot be renamed into place.
fn is_windows_device(path: &Path) -> bool {
    if !cfg!(windows) {
        return false;
    }
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    let name = name.to_ascii_uppercase();
    matches!(name.as_str(), "CON" | "PRN" | "AUX" | "NUL")
        || (name.len() == 4
            && (name.starts_with("COM") || name.starts_with("LPT"))
            && matches!(name.as_bytes()[3], b'1'..=b'9'))
}

/// Whether two paths name the same existing regular file (also through links or `./`).
fn same_file(a: &Path, b: &Path) -> bool {
    let (Ok(ma), Ok(mb)) = (std::fs::metadata(a), std::fs::metadata(b)) else {
        return false;
    };
    if !ma.is_file() || !mb.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        ma.dev() == mb.dev() && ma.ino() == mb.ino()
    }
    #[cfg(not(unix))]
    {
        std::fs::canonicalize(a).ok() == std::fs::canonicalize(b).ok()
    }
}

/// Refuse to write over the input or the reference, or two outputs to one file: renaming the
/// output into place would silently replace the file being read.
fn check_outputs(
    input: &Path,
    reference: Option<&Path>,
    outputs: &[Option<&Path>],
) -> Result<(), Failure> {
    let outputs: Vec<&Path> = outputs
        .iter()
        .flatten()
        .copied()
        .filter(|p| p.as_os_str() != "-")
        .collect();
    for (i, out) in outputs.iter().enumerate() {
        for (what, other) in [("input", Some(input)), ("reference", reference)] {
            if other.is_some_and(|o| same_file(out, o)) {
                return Err(Failure::Input(format!(
                    "output {} is the {what} file: write to a different file",
                    out.display()
                )));
            }
        }
        if outputs[i + 1..]
            .iter()
            .any(|later| same_file(out, later) || (out == later && !is_special(out)))
        {
            return Err(Failure::Input(format!(
                "{} is given for two outputs",
                out.display()
            )));
        }
    }
    Ok(())
}

fn run_filter(args: &FilterArgs) -> Result<(), Failure> {
    use noodles::sam;
    use noodles::sam::alignment::RecordBuf;
    use noodles::sam::alignment::record::data::field::Tag;
    use noodles::sam::alignment::record_buf::data::field::Value;
    use noodles::sam::header::record::value::{Map, map::program::tag as pg};

    let (settings, filters) = args.model.settings().map_err(Failure::Input)?;
    for (name, bound) in [
        ("--threshold", args.threshold),
        ("--upper-threshold", args.upper_threshold),
    ] {
        if bound.is_some_and(|b| !b.is_finite()) {
            return Err(Failure::Input(format!(
                "{name} must be a finite number, got {}",
                bound.unwrap()
            )));
        }
    }
    // PMDtools 0.60 filters only when --threshold > -10000 or --upperthreshold < 1,000,000;
    // otherwise it acts as if neither was given and writes no reads (docs/blackbox.md 1.7b,
    // audit finding B7). Compat does the same; default mode applies any finite bound.
    let compat_keeps_none = settings.pmdtools_compat
        && args.threshold.is_none_or(|t| t <= -10000.0)
        && args.upper_threshold.is_none_or(|u| u >= 1e6);
    if compat_keeps_none && !args.quiet {
        eprintln!(
            "pmdshodh filter: with --pmdtools-compat, --threshold <= -10000 and \
             --upper-threshold >= 1000000 count as not given, as in PMDtools 0.60, so no reads \
             are kept"
        );
    }
    check_range(args.summary.range)?;
    init_threads(args.model.threads)?;
    let format = output_format(&args.output, args.output_format)?;
    check_outputs(
        &args.input,
        args.model.reference.as_deref(),
        &[Some(&args.output), args.summary.summary.as_deref()],
    )?;

    let mut progress = display::Progress::new("filter", args.quiet);
    let (mut reader, in_header, mut reference, input_format, missing_sequences) =
        open_alignments(&args.input, &args.model)?;

    let mut out_header = in_header.clone();
    let program = Map::<sam::header::record::value::map::Program>::builder()
        .insert(pg::NAME, "pmdshodh")
        .insert(pg::VERSION, env!("CARGO_PKG_VERSION"))
        .insert(pg::COMMAND_LINE, command_line())
        .build()
        .map_err(|e| Failure::Runtime(format!("cannot build @PG line: {e}")))?;
    out_header
        .programs_mut()
        .add("pmdshodh", program)
        .map_err(|e| Failure::Runtime(format!("cannot add @PG line: {e}")))?;

    // Both outputs are created before any record is read, so a bad path fails at once.
    let (output, sink) = Output::open(Some(&args.output))?;
    let summary_out = args
        .summary
        .summary
        .as_deref()
        .map(|p| Output::open(Some(p)))
        .transpose()?;
    let mut writer = OutWriter::new(format, sink, args.model.threads)?;
    let write_err = output.write_err();
    writer.write_header(&out_header).map_err(&write_err)?;

    let tag = match args.tag_name {
        TagName::Pm => Tag::new(b'p', b'm'),
        TagName::Ds => Tag::new(b'D', b'S'),
    };
    let mut summary = Summary::new(args.summary.range);
    scan(
        &mut reader,
        &in_header,
        &mut reference,
        &settings,
        &filters,
        &mut summary,
        args.summary.summary.is_some(),
        None,
        args.model.threads,
        &mut progress,
        |record, score| {
            let keep = !compat_keeps_none
                && args.threshold.is_none_or(|t| score.pmds >= t)
                && args.upper_threshold.is_none_or(|u| {
                    score.pmds < u && (score.n_sites > 0 || settings.pmdtools_compat)
                });
            if !keep {
                return Ok(Some(false));
            }
            // score and damage read SAM without a header (`samtools view | ...`); a kept record
            // can only be written if its references are @SQ lines.
            check_reference_ids(record, &in_header).map_err(|msg| {
                let name = record.name().map_or_else(|| "*".into(), |n| n.to_string());
                Failure::Input(format!("read {name}: {msg}"))
            })?;
            // BAM keeps a CIGAR of more than 65,535 operations in a CG tag. Written as read, such
            // a record got the writer's CG tag besides the one in its data: two CG tags.
            let long_cigar = record.cigar().len() > usize::from(u16::MAX);
            if args.tag || long_cigar {
                let mut buf = RecordBuf::try_from_alignment_record(&in_header, record)
                    .map_err(|e| Failure::Input(format!("cannot copy record: {e}")))?;
                if long_cigar {
                    buf.data_mut().remove(&Tag::new(b'C', b'G'));
                }
                if args.tag {
                    let value = match args.tag_name {
                        TagName::Pm => Value::Float(score.pmds as f32),
                        TagName::Ds => Value::String(pmdtools_ds_text(score.pmds).into()),
                    };
                    buf.data_mut().insert(tag, value);
                }
                writer.write_record(&out_header, &buf).map_err(&write_err)?;
            } else {
                writer
                    .write_record(&out_header, record)
                    .map_err(&write_err)?;
            }
            Ok(Some(true))
        },
    )?;
    writer.finish(&out_header).map_err(&write_err)?;
    drop(writer);
    output.commit()?;

    let fin = Finish {
        subcommand: "filter",
        input: &args.input,
        input_format,
        settings,
        filters,
        threshold: args.threshold,
        upper_threshold: args.upper_threshold,
        reference: args.model.reference.as_deref(),
        missing_sequences,
        outputs: [Some(output_name(Some(&args.output)))]
            .into_iter()
            .chain([args
                .summary
                .summary
                .as_deref()
                .map(|p| output_name(Some(p)))])
            .flatten()
            .collect(),
    };
    let json = fin.json(&summary);
    if let Some(s) = summary_out {
        write_json(s, &json)?;
    }
    progress.clear();
    fin.report(&json, &summary, args.quiet, progress.elapsed());
    Ok(())
}

/// The format of `filter`'s output: from a .bam or .sam extension (any case). Stdout and devices
/// such as /dev/null have none, so --output-format decides there, BAM by default.
fn output_format(
    path: &Path,
    flag: Option<OutputFormat>,
) -> Result<noodles_util::alignment::io::Format, Failure> {
    use noodles_util::alignment::io::Format;
    let name = |f: OutputFormat| match f {
        OutputFormat::Bam => "bam",
        OutputFormat::Sam => "sam",
    };
    let to_stdout = path.as_os_str() == "-";
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase);
    let from_ext = match ext.as_deref() {
        _ if to_stdout => None,
        Some("bam") => Some(OutputFormat::Bam),
        Some("sam") => Some(OutputFormat::Sam),
        Some("cram") => {
            return Err(Failure::Input(format!(
                "cannot write {}: CRAM output is not supported; use .bam or .sam",
                path.display()
            )));
        }
        _ => None,
    };
    let format = match (from_ext, flag) {
        (Some(e), Some(f)) if e != f => {
            return Err(Failure::Input(format!(
                "--output-format {} contradicts the .{} extension of {}",
                name(f),
                name(e),
                path.display()
            )));
        }
        (Some(e), _) => e,
        (None, f) if to_stdout || is_special(path) => f.unwrap_or(OutputFormat::Bam),
        (None, _) => {
            return Err(Failure::Input(format!(
                "cannot tell the output format of {}: use a .bam or .sam extension",
                path.display()
            )));
        }
    };
    Ok(match format {
        OutputFormat::Bam => Format::Bam,
        OutputFormat::Sam => Format::Sam,
    })
}

/// Alignment output. BAM goes through pmdshodh's BGZF writer, whose bytes do not depend on the
/// number of threads.
enum OutWriter {
    Sam(alignment::io::Writer<BufWriter<Box<dyn Write + Send>>>),
    Bam(noodles::bam::io::Writer<pmdshodh::bgzf::Writer<Box<dyn Write + Send>>>),
}

impl OutWriter {
    fn new(
        format: noodles_util::alignment::io::Format,
        sink: Box<dyn Write + Send>,
        threads: usize,
    ) -> Result<Self, Failure> {
        use noodles_util::alignment::io::Format;
        Ok(match format {
            Format::Bam => OutWriter::Bam(noodles::bam::io::Writer::from(
                pmdshodh::bgzf::Writer::new(sink, threads > 1),
            )),
            _ => OutWriter::Sam(
                alignment::io::writer::Builder::default()
                    .set_format(format)
                    .build_from_writer(BufWriter::new(sink))
                    .map_err(|e| Failure::Runtime(format!("cannot open output: {e}")))?,
            ),
        })
    }

    fn write_header(&mut self, header: &noodles::sam::Header) -> io::Result<()> {
        match self {
            OutWriter::Sam(w) => w.write_header(header),
            OutWriter::Bam(w) => w.write_header(header),
        }
    }

    fn write_record<R: noodles::sam::alignment::Record>(
        &mut self,
        header: &noodles::sam::Header,
        record: &R,
    ) -> io::Result<()> {
        use noodles::sam::alignment::io::Write as _;
        match self {
            OutWriter::Sam(w) => w.write_record(header, record),
            OutWriter::Bam(w) => w.write_alignment_record(header, record),
        }
    }

    fn finish(&mut self, header: &noodles::sam::Header) -> io::Result<()> {
        match self {
            OutWriter::Sam(w) => w.finish(header),
            // Writes the BGZF end-of-file block and waits for the compression workers.
            OutWriter::Bam(w) => w.get_mut().finish(),
        }
    }
}