radbeeper 0.5.0

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

pub const DEFAULT_TITLE: &str = "Radiation monitor";
pub const RANDOM_TITLE: &str = "Where the random comes from";
const VERSION: &str = env!("CARGO_PKG_VERSION");
const HOMEPAGE: &str = "https://github.com/vonglurt/radbeeper";
const TAGLINE: &str = "A GQ GMC Geiger-Muller counter on the desk";
const ENTROPY_BITS: i64 = entropy::ENTROPY_BITS as i64;

/// The screenshots the index links, when they are beside it.
const SHOTS: [&str; 9] = [
    "probe", "watch", "watch-filling", "watch-spectrum", "watch-plain",
    "log-output", "log-tabs", "commands", "watch-20s",
];

// ------------------------------------------------------- python's numbers ---

/// `"%.Nf"`. Rust's fixed formatting rounds the exact binary value half to
/// even, which is what C's printf does and so what Python's `%` does.
fn f(places: usize, v: f64) -> String {
    format!("{:.*}", places, v)
}

/// `"{:,}".format(n)`.
fn commas(n: i64) -> String {
    let digits = n.unsigned_abs().to_string();
    let mut out = String::new();
    for (i, ch) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(ch);
    }
    if n < 0 {
        format!("-{}", out)
    } else {
        out
    }
}

/// `"%.0e"`, which writes a two-digit signed exponent where Rust writes `e-4`.
fn e0(v: f64) -> String {
    let s = format!("{:.0e}", v);
    match s.split_once('e') {
        Some((m, e)) => {
            let exp: i32 = e.parse().unwrap_or(0);
            format!("{}e{}{:02}", m, if exp < 0 { '-' } else { '+' }, exp.abs())
        }
        None => s,
    }
}

/// Python's `max(a, b)`: `a` unless `b` is strictly greater.
fn pymax(a: f64, b: f64) -> f64 {
    if b > a {
        b
    } else {
        a
    }
}

/// C's `pow`, called the way Python's `**` calls it. black_box keeps LLVM from
/// turning `pow(x, 2.0)` into `x * x` or `pow(10.0, x)` into `exp10(x)`, which
/// are close to the same number and not always the same bits.
fn pow(x: f64, y: f64) -> f64 {
    black_box(x).powf(black_box(y))
}

/// `math.log(x, 2)`, which is log(x) / log(2) and not log2(x).
fn log_2(x: f64) -> f64 {
    x.ln() / 2.0f64.ln()
}

/// CPython's `sum()` over floats (3.12 onwards): Neumaier's compensated sum.
fn py_sum(values: impl Iterator<Item = f64>) -> f64 {
    let (mut hi, mut lo) = (0.0f64, 0.0f64);
    for x in values {
        let t = hi + x;
        if hi.abs() >= x.abs() {
            lo += (hi - t) + x;
        } else {
            lo += (x - t) + hi;
        }
        hi = t;
    }
    if lo != 0.0 && lo.is_finite() {
        hi + lo
    } else {
        hi
    }
}

fn factorial(k: u32) -> f64 {
    (1..=k as u64).product::<u64>() as f64
}

fn poisson_pmf(lam: f64, k: u32) -> f64 {
    (-lam).exp() * pow(lam, k as f64) / factorial(k)
}

/// Python's `int()` and `float()` on a cell: surrounding whitespace allowed.
fn int_cell(s: &str) -> Option<i64> {
    s.trim().parse().ok()
}

fn float_cell(s: &str) -> Option<f64> {
    s.trim().parse().ok()
}

// ------------------------------------------------------------------ paths ---
//
// os.path's lexical rules, because the links on the page are relative paths
// the Python worked out, and a `./` or a `..` that differs is a byte that
// differs.

/// `os.path.abspath`: joined to the working directory, then normalised
/// lexically -- no symlinks resolved.
fn abspath(p: &str) -> String {
    let joined = if p.starts_with('/') {
        p.to_string()
    } else {
        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
        join(&cwd.to_string_lossy(), p)
    };
    let mut parts: Vec<&str> = Vec::new();
    for part in joined.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            other => parts.push(other),
        }
    }
    format!("/{}", parts.join("/"))
}

/// `os.path.join(a, b)` for two parts.
fn join(a: &str, b: &str) -> String {
    if b.starts_with('/') || a.is_empty() {
        b.to_string()
    } else if a.ends_with('/') {
        format!("{}{}", a, b)
    } else {
        format!("{}/{}", a, b)
    }
}

fn dirname(p: &str) -> String {
    match p.rfind('/') {
        Some(i) => {
            let head = &p[..=i];
            let trimmed = head.trim_end_matches('/');
            if trimmed.is_empty() {
                head.to_string()
            } else {
                trimmed.to_string()
            }
        }
        None => String::new(),
    }
}

fn basename(p: &str) -> &str {
    match p.rfind('/') {
        Some(i) => &p[i + 1..],
        None => p,
    }
}

/// `os.path.relpath(path, start)`.
fn relpath(path: &str, start: &str) -> String {
    let s = abspath(start);
    let p = abspath(path);
    let sl: Vec<&str> = s.split('/').filter(|x| !x.is_empty()).collect();
    let pl: Vec<&str> = p.split('/').filter(|x| !x.is_empty()).collect();
    let common = sl.iter().zip(pl.iter()).take_while(|(a, b)| a == b).count();
    let mut rel: Vec<&str> = vec![".."; sl.len() - common];
    rel.extend(&pl[common..]);
    if rel.is_empty() {
        ".".to_string()
    } else {
        rel.join("/")
    }
}

fn path_str(p: &Path) -> String {
    p.to_string_lossy().into_owned()
}

// -------------------------------------------------------------- the clock ---

/// When the pages say they were generated.
///
/// SOURCE_DATE_EPOCH when it is set -- the reproducible-builds convention, and
/// the one hook the Python honours too -- so that two runs, or two
/// implementations, on the same logs write the same bytes. The wall clock
/// otherwise.
pub fn now() -> f64 {
    std::env::var("SOURCE_DATE_EPOCH")
        .ok()
        .and_then(|v| v.trim().parse::<f64>().ok())
        .unwrap_or_else(clock::now)
}

// -------------------------------------------------------------- summarise ---

#[derive(Default)]
pub struct Day {
    pub rows: u64,
    pub counts: i64,
    pub seconds: f64,
    pub peak: Option<f64>,
}

#[derive(Default)]
pub struct Hour {
    pub counts: i64,
    pub seconds: f64,
    pub peak: Option<f64>,
}

/// One counter's worth of logs, as the page draws it.
#[derive(Default)]
pub struct Counter {
    pub serial: String,
    pub rows: u64,
    pub counts: i64,
    pub seconds: f64,
    pub first: Option<f64>,
    pub last: Option<f64>,
    pub peak: Option<f64>,
    pub days: BTreeMap<String, Day>,
    pub hours: BTreeMap<i64, Hour>,
    /// The last sixty rows, oldest first, as the raw cells of the file.
    pub latest: Vec<(f64, Vec<String>)>,
    pub cpm: f64,
    pub usvh: f64,
    /// (file name, link relative to the page) for every log of this counter.
    pub links: Vec<(String, String)>,
}

fn raise(slot: &mut Option<f64>, v: Option<f64>) {
    if let Some(p) = v {
        if slot.map(|s| p > s).unwrap_or(true) {
            *slot = Some(p);
        }
    }
}

/// The cells the page reads, in the order it reads them: counts at 2,
/// seconds at 3, the first peak at 7, source at 10, site at 11. It is the
/// three-window header, which is what the page was written against.
const PAGE_COLUMNS: [&str; 12] = [
    "time", "cps", "counts", "seconds", "cpm_3", "cpm_30", "cpm_300",
    "peak_3", "peak_30", "peak_300", "src", "site",
];

/// (when, cells) for every row of a dated log, re-columned BY NAME into
/// `PAGE_COLUMNS`, header and blanks skipped.
///
/// IT WAS POSITIONAL, and every log written since the fourth window was added
/// was misread by it: `cpm_3000` came out under "Peak 3s", `peak_300` under
/// "Source" and `peak_3000` under "Site", and the peak card and the chart's
/// peaks were the 3000-second average. Each row is now read under the last
/// header above it -- a file can carry two, where the windows changed -- and
/// a file with no header at all is taken to be the three-window layout the
/// positions were written for.
fn read_rows(path: &Path) -> Vec<(f64, Vec<String>)> {
    let text = match fs::read_to_string(path) {
        Ok(t) => t,
        Err(_) => return Vec::new(),
    };
    let page: Vec<String> = PAGE_COLUMNS.iter().map(|s| s.to_string()).collect();
    let mut names = page.clone();
    let mut out = Vec::new();
    for line in text.lines() {
        if line.starts_with('#') {
            let found = log::columns(line);
            if !found.is_empty() {
                names = found;
            }
            continue;
        }
        if let Some(when) = log::row_time(line) {
            let cells: Vec<&str> = line.split('\t').collect();
            out.push((when, log::align_row(&cells, &names, &page)));
        }
    }
    out
}

/// Per counter: the totals, the daily rollup, and the last rows seen.
///
/// The daily rollup is counts over seconds, not a mean of the per-row CPMs:
/// rows are not all the same length -- a service stopped mid-interval writes
/// a short one -- and averaging averages would weight a four-second row like
/// a thirty-second one.
pub fn summarise(directory: &Path, cpm_per_usvh: f64) -> BTreeMap<String, Counter> {
    let mut counters: BTreeMap<String, Counter> = BTreeMap::new();
    for (serial, path) in log::files(directory) {
        let c = counters.entry(serial.clone()).or_insert_with(|| Counter {
            serial: serial.clone(),
            ..Counter::default()
        });
        for (when, cells) in read_rows(&path) {
            let (counts, seconds) = match (
                cells.get(2).and_then(|s| int_cell(s)),
                cells.get(3).and_then(|s| float_cell(s)),
            ) {
                (Some(n), Some(s)) => (n, s),
                _ => continue,
            };
            let peak = cells.get(7).filter(|s| !s.is_empty()).and_then(|s| float_cell(s));
            c.rows += 1;
            c.counts += counts;
            c.seconds += seconds;
            c.first = Some(c.first.map_or(when, |f| if when < f { when } else { f }));
            c.last = Some(c.last.map_or(when, |l| if when > l { when } else { l }));
            raise(&mut c.peak, peak);
            // An hour is the plot's resolution: eleven days of thirty-second
            // rows is 28,000 points, which is more ink than the page is wide.
            let h = c.hours.entry((when / 3600.0).floor() as i64).or_default();
            h.counts += counts;
            h.seconds += seconds;
            raise(&mut h.peak, peak);
            let d = c.days.entry(clock::format(when, "%Y-%m-%d")).or_default();
            d.rows += 1;
            d.counts += counts;
            d.seconds += seconds;
            raise(&mut d.peak, peak);
            c.latest.push((when, cells));
        }
    }
    for c in counters.values_mut() {
        c.latest.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
        // Sixty rows is half an hour and about four screens. The rest of the
        // record is one link away as the file it already lives in.
        let keep = c.latest.len().saturating_sub(60);
        c.latest.drain(..keep);
        c.cpm = if c.seconds != 0.0 { c.counts as f64 * 60.0 / c.seconds } else { 0.0 };
        c.usvh = if cpm_per_usvh != 0.0 { c.cpm / cpm_per_usvh } else { 0.0 };
    }
    counters
}


/// The merged record: the room, at the precision the per-counter files round
/// away.
///
/// READ FROM ITS OWN FILE, NOT RECONSTRUCTED FROM THEIRS. `together` below
/// does the reconstruction -- it adds up the per-counter totals and reports
/// the pair -- and it is exactly as good as the rounded figures it is adding.
/// What it cannot recover at all is the INTERLEAVE: whether the tubes took
/// turns or fired together is a fact about arrival times that no per-counter
/// row records, and it is the difference between n tubes buying time
/// resolution and n tubes buying only precision. That is measured as it
/// happens and written down in `cpm-merged-*.tsv`; here it is read back.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Merged {
    pub rows: u64,
    /// RAW: every arrival off every tube, as integers, lossless.
    pub counts: i64,
    /// Wall seconds the rows cover, and the instrument-seconds behind them.
    /// With n tubes the second is n times the first, which is the whole
    /// arithmetic of a merge in two numbers.
    pub seconds: f64,
    pub tube_seconds: f64,
    /// The most tubes any row was written under.
    pub tubes: usize,
    /// MERGED: counts over tube-seconds, which is the rate of the ROOM and
    /// not the sum of the instruments.
    pub cpm: f64,
    pub usvh: f64,
    pub sigma: f64,
    /// INTERLEAVED: the mean gap between one tube's sample and the next
    /// tube's, weighted by the rows that measured it.
    pub interleave: Option<f64>,
    pub first: Option<f64>,
    pub last: Option<f64>,
    /// The last rows, oldest first, for the table.
    pub latest: Vec<(f64, Vec<String>)>,
}

/// The columns the page reads out of a merged log, by name.
const MERGED_COLUMNS: [&str; 10] = [
    "time", "tubes", "interleave", "counts", "seconds", "tube_seconds",
    "cps", "cps_raw", "cpm_30", "sigma_30",
];

/// The merged logs in a directory, folded into one summary.
///
/// None when there are none, which is every directory written before this
/// existed and every one written by the Python. The page simply leaves the
/// section out rather than drawing an empty one.
pub fn merged(directory: &Path, cpm_per_usvh: f64) -> Option<Merged> {
    let names: Vec<String> = MERGED_COLUMNS.iter().map(|s| s.to_string()).collect();
    let mut m = Merged::default();
    let mut gap = (0.0f64, 0u64);
    for path in log::merged_files(directory) {
        for (when, cells) in log::read_table(&path, &names) {
            let (counts, seconds) = match (
                cells.get(3).and_then(|s| int_cell(s)),
                cells.get(4).and_then(|s| float_cell(s)),
            ) {
                (Some(n), Some(s)) => (n, s),
                _ => continue,
            };
            m.rows += 1;
            m.counts += counts;
            m.seconds += seconds;
            m.tube_seconds += cells.get(5).and_then(|s| float_cell(s)).unwrap_or(seconds);
            if let Some(t) = cells.get(1).and_then(|s| int_cell(s)) {
                m.tubes = m.tubes.max(t.max(0) as usize);
            }
            // ROWS, NOT SECONDS, IS THE WEIGHT. Every row measured its own
            // interval's interleave over a similar number of hand-overs, and
            // a row that saw none contributes none rather than a zero -- a
            // zero gap means the tubes fired together, which is a real and
            // very different reading.
            if let Some(g) = cells.get(2).filter(|c| !c.is_empty()).and_then(|s| float_cell(s)) {
                gap.0 += g;
                gap.1 += 1;
            }
            m.first = Some(m.first.map_or(when, |f| if when < f { when } else { f }));
            m.last = Some(m.last.map_or(when, |l| if when > l { when } else { l }));
            m.latest.push((when, cells));
        }
    }
    if m.rows == 0 {
        return None;
    }
    m.latest.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
    let keep = m.latest.len().saturating_sub(20);
    m.latest.drain(..keep);
    m.cpm = if m.tube_seconds > 0.0 {
        m.counts as f64 * 60.0 / m.tube_seconds
    } else {
        0.0
    };
    m.usvh = if cpm_per_usvh != 0.0 { m.cpm / cpm_per_usvh } else { 0.0 };
    m.sigma = if m.counts > 0 { m.cpm / (m.counts as f64).sqrt() } else { 0.0 };
    m.interleave = (gap.1 > 0).then(|| gap.0 / gap.1 as f64);
    Some(m)
}

/// What two or more tubes in one room measured, taken together.
///
/// COUNTS-WEIGHTED, WHICH IS THE ONLY DEFENSIBLE MEAN. Adding the counts and
/// adding the seconds gives the rate of the pair; averaging the two rates
/// instead would give a tube that recorded for an hour the same say as one
/// that recorded for a week. Two counters do NOT double the dose -- what
/// doubles is the evidence, and the whole benefit lands in `sigma`.
#[derive(Debug, Clone, PartialEq)]
pub struct Together {
    pub tubes: usize,
    pub counts: i64,
    pub seconds: f64,
    pub cpm: f64,
    pub usvh: f64,
    /// One sigma on `cpm`, in CPM. Arrivals are Poisson, so the whole of the
    /// uncertainty is the count behind the number: N gives 1/sqrt(N).
    pub sigma: f64,
    /// The widest disagreement between any two tubes, in sigmas, and which
    /// pair it was. None when there is only one tube, or no overlap to judge.
    pub worst: Option<(f64, String, String)>,
}

/// One tube's rate and its uncertainty, in counts per second.
fn rate_of(c: &Counter) -> Option<(f64, f64)> {
    if c.seconds <= 0.0 || c.counts <= 0 {
        return None;
    }
    let r = c.counts as f64 / c.seconds;
    Some((r, r / (c.counts as f64).sqrt()))
}

/// The pair, taken together -- None unless at least two tubes have counts.
pub fn together(counters: &BTreeMap<String, Counter>, cpm_per_usvh: f64) -> Option<Together> {
    let live: Vec<(&String, &Counter)> = counters
        .iter()
        .filter(|(_, c)| c.seconds > 0.0 && c.counts > 0)
        .collect();
    if live.len() < 2 {
        return None;
    }
    let counts: i64 = live.iter().map(|(_, c)| c.counts).sum();
    let seconds: f64 = live.iter().map(|(_, c)| c.seconds).sum();
    let cpm = counts as f64 * 60.0 / seconds;
    // DO THEY AGREE? Two identical tubes in one room should, to within a
    // couple of sigma; a difference that keeps growing is the tubes being
    // different, not the room being interesting, and it is the one question
    // a second instrument exists to answer.
    let mut worst: Option<(f64, String, String)> = None;
    for i in 0..live.len() {
        for j in i + 1..live.len() {
            let (Some((ra, sa)), Some((rb, sb))) = (rate_of(live[i].1), rate_of(live[j].1))
            else {
                continue;
            };
            let sd = (sa * sa + sb * sb).sqrt();
            if sd <= 0.0 {
                continue;
            }
            let z = ((ra - rb) / sd).abs();
            if worst.as_ref().map_or(true, |(w, _, _)| z > *w) {
                worst = Some((z, live[i].0.clone(), live[j].0.clone()));
            }
        }
    }
    Some(Together {
        tubes: live.len(),
        counts,
        seconds,
        cpm,
        usvh: if cpm_per_usvh != 0.0 { cpm / cpm_per_usvh } else { 0.0 },
        sigma: cpm / (counts as f64).sqrt(),
        worst,
    })
}

/// How to read a disagreement, in the words it deserves.
pub fn agreement(z: f64) -> &'static str {
    if z < 2.0 {
        "they agree"
    } else if z < 4.0 {
        "they differ -- watch it"
    } else {
        "they disagree -- not the same measurement"
    }
}

/// A round number at or above value, for an axis somebody can read.
pub fn nice_ceiling(value: f64) -> f64 {
    if value <= 0.0 {
        return 1.0;
    }
    let power = pow(10.0, value.log10().floor());
    for step in [1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0] {
        if value <= step * power {
            return step * power;
        }
    }
    10.0 * power
}

/// [(unix time, mean CPM, peak CPM or None)] per hour, in order.
pub fn hour_series(c: &Counter) -> Vec<(f64, f64, Option<f64>)> {
    c.hours
        .iter()
        .filter(|(_, h)| h.seconds != 0.0)
        .map(|(hour, h)| (*hour as f64 * 3600.0, h.counts as f64 * 60.0 / h.seconds, h.peak))
        .collect()
}

// ------------------------------------------------------------- the charts ---

/// An inline SVG line chart of CPM by the hour, on a log axis.
///
/// THE LINE BREAKS OVER A GAP rather than running across it: an hour the
/// counter was not recording is not an hour of zero. THE AXIS IS LOGARITHMIC
/// because the data is -- background near 40 CPM, peaks two hundred times
/// that.
pub fn svg_plot(series: &[(f64, f64, Option<f64>)]) -> String {
    let (width, height, pad_l, pad_b, pad_t, pad_r) = (1120i64, 1200i64, 52i64, 26i64, 12i64, 10i64);
    if series.len() < 2 {
        return String::new();
    }
    let mut values: Vec<f64> = series.iter().map(|s| s.1).filter(|m| *m > 0.0).collect();
    values.extend(series.iter().filter_map(|s| s.2).filter(|p| *p != 0.0));
    if values.is_empty() {
        return String::new();
    }
    // min() and max() as Python's: the first of equals.
    let vmin = values.iter().copied().fold(values[0], |a, b| if b < a { b } else { a });
    let vmax = values.iter().copied().fold(values[0], |a, b| if b > a { b } else { a });
    let lo = pow(10.0, vmin.log10().floor());
    let mut hi = pow(10.0, vmax.log10().ceil());
    if hi <= lo {
        hi = lo * 10.0;
    }
    let span_y = hi.log10() - lo.log10();
    let t0 = series[0].0;
    let t1 = series[series.len() - 1].0;
    let span = if t1 - t0 != 0.0 { t1 - t0 } else { 1.0 };
    let iw = width - pad_l - pad_r;
    let ih = height - pad_t - pad_b;
    let x_of = |t: f64| pad_l as f64 + iw as f64 * (t - t0) / span;
    let y_of = |v: f64| {
        pad_t as f64 + ih as f64 * (1.0 - (pymax(v, lo).log10() - lo.log10()) / span_y)
    };
    // An hour and a half between points means an hour went unrecorded.
    let step = 3600.0 * 1.5;
    let path = |points: &[(f64, Option<f64>)]| -> String {
        let mut d: Vec<String> = Vec::new();
        let mut pen = false;
        let mut last: Option<f64> = None;
        for (t, v) in points {
            let v = match v {
                Some(v) => *v,
                None => {
                    pen = false;
                    last = Some(*t);
                    continue;
                }
            };
            let letter = if !pen || last.map(|l| t - l > step).unwrap_or(false) { "M" } else { "L" };
            d.push(format!("{}{} {}", letter, f(1, x_of(*t)), f(1, y_of(v))));
            pen = true;
            last = Some(*t);
        }
        d.join(" ")
    };

    let mut out = vec![format!(
        "<svg class=\"plot\" viewBox=\"0 0 {} {}\" width=\"100%\" \
         preserveAspectRatio=\"xMidYMid meet\" role=\"img\" \
         aria-label=\"counts per minute over time\">",
        width, height
    )];
    // y grid: one line per decade, with the halfway marks left unlabelled.
    let mut decade = lo;
    while decade <= hi * 1.0001 {
        let y = f(1, y_of(decade));
        out.push(format!(
            "<line class=\"grid\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
            pad_l, y, width - pad_r, y
        ));
        out.push(format!(
            "<text class=\"ylab\" x=\"{}\" y=\"{}\">{}</text>",
            pad_l - 8,
            f(1, y_of(decade) + 4.0),
            commas(decade as i64)
        ));
        for minor in [2.0, 5.0] {
            let v = decade * minor;
            if v < hi {
                let ym = f(1, y_of(v));
                out.push(format!(
                    "<line class=\"grid minor\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
                    pad_l, ym, width - pad_r, ym
                ));
            }
        }
        decade *= 10.0;
    }
    // x ticks at midnight
    let day = 86400.0;
    let mut t = t0 - t0.rem_euclid(day) + day;
    while t < t1 {
        let x = f(1, x_of(t));
        out.push(format!(
            "<line class=\"grid\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
            x, pad_t, x, pad_t + ih
        ));
        out.push(format!(
            "<text class=\"xlab\" x=\"{}\" y=\"{}\">{}</text>",
            x,
            height - 8,
            clock::format(t, "%b %-d")
        ));
        t += day;
    }
    let peaks: Vec<(f64, Option<f64>)> = series.iter().map(|s| (s.0, s.2)).collect();
    let means: Vec<(f64, Option<f64>)> = series.iter().map(|s| (s.0, Some(s.1))).collect();
    out.push(format!("<path class=\"peak\" d=\"{}\"/>", path(&peaks)));
    out.push(format!("<path class=\"mean\" d=\"{}\"/>", path(&means)));
    out.push(format!(
        "<text class=\"ycap\" x=\"{}\" y=\"{}\">CPM, log</text>",
        pad_l - 44,
        pad_t + 10
    ));
    out.push("</svg>".to_string());
    out.concat()
}


/// Every tube's hourly mean on one pair of axes, in one colour each.
///
/// THE POINT IS THE TRACKING, NOT THE VALUES. Two counters watching one room
/// should draw the same shape; where they part company is where something is
/// wrong with a tube, a cable or a pass-through, and no table of averages
/// shows that as fast as two lines that stop being parallel.
pub fn svg_overlay(series: &[(String, Vec<(f64, f64, Option<f64>)>)]) -> String {
    let (width, height, pad_l, pad_b, pad_t, pad_r) = (1120i64, 560i64, 52i64, 26i64, 12i64, 10i64);
    let live: Vec<&(String, Vec<(f64, f64, Option<f64>)>)> =
        series.iter().filter(|(_, s)| s.len() >= 2).collect();
    if live.len() < 2 {
        return String::new();
    }
    let values: Vec<f64> = live
        .iter()
        .flat_map(|(_, s)| s.iter().map(|p| p.1))
        .filter(|m| *m > 0.0)
        .collect();
    if values.is_empty() {
        return String::new();
    }
    let vmin = values.iter().copied().fold(values[0], |a, b| if b < a { b } else { a });
    let vmax = values.iter().copied().fold(values[0], |a, b| if b > a { b } else { a });
    let lo = pow(10.0, vmin.log10().floor());
    let mut hi = pow(10.0, vmax.log10().ceil());
    if hi <= lo {
        hi = lo * 10.0;
    }
    let span_y = hi.log10() - lo.log10();
    let t0 = live.iter().map(|(_, s)| s[0].0).fold(f64::INFINITY, f64::min);
    let t1 = live
        .iter()
        .map(|(_, s)| s[s.len() - 1].0)
        .fold(f64::NEG_INFINITY, f64::max);
    let span = if t1 - t0 != 0.0 { t1 - t0 } else { 1.0 };
    let iw = width - pad_l - pad_r;
    let ih = height - pad_t - pad_b;
    let x_of = |t: f64| pad_l as f64 + iw as f64 * (t - t0) / span;
    let y_of = |v: f64| {
        pad_t as f64 + ih as f64 * (1.0 - (pymax(v, lo).log10() - lo.log10()) / span_y)
    };
    let step = 3600.0 * 1.5;

    let mut out = vec![format!(
        "<svg class=\"plot\" viewBox=\"0 0 {} {}\" width=\"100%\" \
         preserveAspectRatio=\"xMidYMid meet\" role=\"img\" \
         aria-label=\"counts per minute over time, every counter\">",
        width, height
    )];
    let mut decade = lo;
    while decade <= hi * 1.0001 {
        let y = f(1, y_of(decade));
        out.push(format!(
            "<line class=\"grid\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
            pad_l, y, width - pad_r, y
        ));
        out.push(format!(
            "<text class=\"ylab\" x=\"{}\" y=\"{}\">{}</text>",
            pad_l - 8,
            f(1, y_of(decade) + 4.0),
            commas(decade as i64)
        ));
        decade *= 10.0;
    }
    let day = 86400.0;
    let mut t = t0 - t0.rem_euclid(day) + day;
    while t < t1 {
        let x = f(1, x_of(t));
        out.push(format!(
            "<line class=\"grid\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
            x, pad_t, x, pad_t + ih
        ));
        out.push(format!(
            "<text class=\"xlab\" x=\"{}\" y=\"{}\">{}</text>",
            x,
            height - 8,
            clock::format(t, "%b %-d")
        ));
        t += day;
    }
    for (i, (serial, points)) in live.iter().enumerate() {
        let mut d: Vec<String> = Vec::new();
        let mut last: Option<f64> = None;
        for (when, mean, _) in points.iter() {
            let letter = if last.map(|l| when - l > step).unwrap_or(true) { "M" } else { "L" };
            d.push(format!("{}{} {}", letter, f(1, x_of(*when)), f(1, y_of(*mean))));
            last = Some(*when);
        }
        out.push(format!(
            "<path class=\"tube t{}\" d=\"{}\"/>",
            i % 4,
            d.join(" ")
        ));
        out.push(format!(
            "<text class=\"key t{}\" x=\"{}\" y=\"{}\">{}</text>",
            i % 4,
            pad_l + 8,
            pad_t + 16 + 15 * i as i64,
            esc(serial)
        ));
    }
    out.push(format!(
        "<text class=\"ycap\" x=\"{}\" y=\"{}\">CPM, log</text>",
        pad_l - 44,
        pad_t + 10
    ));
    out.push("</svg>".to_string());
    out.concat()
}

pub fn esc(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// The <head> and the one stylesheet both generated pages use.
///
/// Two pages that look like two different projects is how a reader stops
/// believing they came from the same program, so the rules live here once
/// and random.html adds only what is peculiar to it.
pub fn page_head(title: &str, extra: &[&str]) -> Vec<String> {
    let mut out: Vec<String> = [
        "<!doctype html>",
        "<html lang=\"en\"><head><meta charset=\"utf-8\">",
        "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    out.push(format!("<title>{}</title>", esc(title)));
    out.push("<style>".to_string());
    for rule in STYLE.iter().chain(extra.iter()) {
        out.push(rule.to_string());
    }
    out.push("</style></head><body><main>".to_string());
    out
}

const STYLE: &[&str] = &[
    ":root{color-scheme:light dark;--fg:#181818;--bg:#faf9f7;\
     --dim:#6b6b6b;--line:#e0ddd8;--card:#fff;--accent:#2f6f4f;\
     --warn:#b0642a}",
    "@media (prefers-color-scheme:dark){:root{--fg:#e8e6e3;--bg:#16161a;\
     --dim:#9a9a9a;--line:#2e2e35;--card:#1e1e24;--accent:#6cc08c;\
     --warn:#e0a06a}}",
    "body{margin:0;padding:2rem 1rem;background:var(--bg);color:var(--fg);\
     font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif}",
    "main{max-width:1100px;margin:0 auto}",
    "h1{font-size:1.6rem;margin:0 0 .2rem}",
    "h2{font-size:1.1rem;margin:2.2rem 0 .6rem;font-weight:600}",
    ".sub{color:var(--dim);margin:0 0 1rem}",
    ".lede{max-width:70ch;margin:0 0 2rem;font-size:1rem;line-height:1.6}",
    ".lede a{color:var(--accent)}",
    ".how{margin-top:2.6rem}",
    ".how h3{margin:1.6rem 0 .3rem;font-size:1rem}",
    ".how p{margin:.35rem 0;max-width:68ch}",
    ".how pre{background:var(--card);border:1px solid var(--line);\
     border-radius:8px;padding:.6rem .9rem;overflow-x:auto;\
     font-size:.84rem;margin:.5rem 0}",
    ".how img{border:1px solid var(--line);border-radius:8px;\
     margin:.6rem 0;max-width:100%}",
    ".how figure{margin:.8rem 0 1.2rem}",
    ".how figcaption{color:var(--dim);font-size:.82rem;margin-top:.3rem}",
    ".cards{display:grid;gap:.9rem;\
     grid-template-columns:repeat(auto-fit,minmax(190px,1fr))}",
    ".card{background:var(--card);border:1px solid var(--line);\
     border-radius:10px;padding:.9rem 1rem}",
    ".card .k{color:var(--dim);font-size:.78rem;text-transform:uppercase;\
     letter-spacing:.04em}",
    ".card .v{font-size:1.5rem;font-variant-numeric:tabular-nums;\
     margin-top:.15rem}",
    ".card .n{color:var(--dim);font-size:.8rem}",
    ".plotwrap{background:var(--card);border:1px solid var(--line);\
     border-radius:10px;padding:.9rem 1rem 0;margin-top:.9rem}",
    ".plot{display:block;height:auto}",
    ".plot .grid{stroke:var(--line);stroke-width:1}",
    ".plot .minor{opacity:.45}",
    ".plot .mean{fill:none;stroke:var(--accent);stroke-width:1.6;\
     stroke-linejoin:round;stroke-linecap:round}",
    ".plot .peak{fill:none;stroke:var(--warn);stroke-width:1;opacity:.55}",
    // One colour per tube, shared by its line and its key, so the overlay is
    // read by colour and needs no legend anywhere else.
    ".plot .tube{fill:none;stroke-width:1.6;stroke-linejoin:round;\
      stroke-linecap:round;opacity:.9}",
    ".plot .key{font-size:12px;text-anchor:start}",
    ".plot .t0{stroke:#6cc6ff;fill:#6cc6ff}",
    ".plot .t1{stroke:#c9a0ff;fill:#c9a0ff}",
    ".plot .t2{stroke:#7ee787;fill:#7ee787}",
    ".plot .t3{stroke:#ffa657;fill:#ffa657}",
    ".plot text{fill:var(--dim);font-size:11px;\
     font-family:system-ui,sans-serif}",
    ".plot .ylab{text-anchor:end}",
    ".plot .xlab{text-anchor:middle}",
    ".plot .ycap{text-anchor:start;font-size:10px;letter-spacing:.05em;\
     text-transform:uppercase}",
    ".legend{display:flex;gap:1.2rem;color:var(--dim);font-size:.8rem;\
     padding:.1rem 0 .8rem}",
    ".legend i{display:inline-block;width:18px;height:0;\
     border-top-width:2px;border-top-style:solid;vertical-align:middle;\
     margin-right:.4rem}",
    ".about{background:var(--card);border:1px solid var(--line);\
     border-radius:10px;padding:1.2rem 1.4rem;margin-top:2.6rem}",
    ".about h3{margin:0 0 .4rem;font-size:1.05rem}",
    ".about p{margin:.4rem 0;max-width:62ch}",
    ".about pre{background:var(--bg);border:1px solid var(--line);\
     border-radius:6px;padding:.6rem .8rem;overflow-x:auto;font-size:.82rem}",
    ".windows{display:grid;gap:.7rem;margin:.9rem 0 0;padding:0;\
     list-style:none;grid-template-columns:repeat(auto-fit,minmax(190px,1fr))}",
    ".windows li{border-left:2px solid var(--accent);padding-left:.7rem}",
    ".windows b{display:block;font-size:1.05rem}",
    ".windows span{color:var(--dim);font-size:.85rem}",
    "table{border-collapse:collapse;width:100%;font-size:.86rem;\
     font-variant-numeric:tabular-nums;background:var(--card);\
     border:1px solid var(--line);border-radius:10px;overflow:hidden}",
    "th{text-align:left;font-weight:600;color:var(--dim);font-size:.76rem;\
     text-transform:uppercase;letter-spacing:.04em}",
    "th,td{padding:.36rem .7rem;border-bottom:1px solid var(--line)}",
    "tbody tr:last-child td{border-bottom:0}",
    "td:not(:first-child),th:not(:first-child){text-align:right}",
    ".more{margin:.6rem 0 0;font-size:.85rem}",
    ".more a{color:var(--accent)}",
    ".tablewrap{overflow-x:auto}",
    "footer{color:var(--dim);font-size:.82rem;margin-top:3rem;\
     border-top:1px solid var(--line);padding-top:1rem}",
    "code{background:var(--card);padding:.1rem .3rem;border-radius:4px}",
];

// -------------------------------------------------------------- index.html ---

/// One self-contained page: no scripts, no fetches, no web fonts.
#[allow(clippy::too_many_arguments)]
pub fn render_html(
    counters: &BTreeMap<String, Counter>,
    sites: &[(String, f64, String)],
    cpm_per_usvh: f64,
    title: &str,
    shots: &BTreeMap<String, String>,
    // `randoms`: one audit page per counter that has emissions, by serial.
    randoms: &BTreeMap<String, String>,
    // The merged record, when the directory has one. Read by the caller
    // rather than here, because this function is handed summaries and not a
    // directory -- which is what lets a test render a page from nothing but
    // structs.
    merge: Option<&Merged>,
) -> String {
    // The lede links the first, because the paragraph is about the idea
    // rather than about any one tube. Each counter's own section links its
    // own page below.
    let random_link = randoms.values().next().map(|s| s.as_str());
    let when = |t: f64| clock::format(t, "%Y-%m-%d %H:%M");
    let mut out = page_head(title, &[]);
    macro_rules! a {
        ($($arg:tt)*) => { out.push(format!($($arg)*)) };
    }
    a!("<h1>{}</h1>", esc(title));
    a!(
        "<p class=\"sub\">{} &middot; generated {} by radbeeper {} &middot; tube factor {} CPM per &micro;Sv/h</p>",
        esc(TAGLINE),
        esc(&when(now())),
        VERSION,
        f(1, cpm_per_usvh)
    );
    a!(
        "<p class=\"lede\">A <strong>GQ GMC-320 Plus</strong> Geiger&ndash;M&uuml;ller \
         counter, plugged into a machine running <strong>Alpine Linux</strong> \
         &mdash; or <strong><a href=\"https://github.com/vonglurt/copal\">Copal\
         </a></strong>, its distillation, which carries this as a stage and \
         installs the <code>linux-lts</code> kernel package the counter needs to \
         be seen at all &mdash; as a USB serial device, here shared into a \
         virtual machine over USB pass-through. RadBeeper reads the counter, logs it to tab-separated \
         files, and <strong>this page is regenerated from those files by a \
         GitHub Action</strong> on every push. The whole of it is forkable: copy \
         your own logs into <code>logs/</code> and you get a page like this \
         one. <a href=\"{}\">Source and instructions</a>.{}</p>",
        HOMEPAGE,
        match random_link {
            Some(l) => format!(" <a href=\"{}\">Where the random comes from</a>.", esc(l)),
            None => String::new(),
        }
    );

    if counters.is_empty() {
        a!("<p>No logs found. Put <code>cpm-&lt;serial&gt;-YYYY-MM.tsv</code> \
            files beside this page and run <code>radbeeper export</code>.</p>");
    }
    // BOTH TUBES, BEFORE EITHER OF THEM. With one counter this is not drawn
    // at all; with two it is the first thing on the page, because the pair is
    // the measurement and the individual tubes are how it was arrived at.
    if let Some(t) = together(counters, cpm_per_usvh) {
        a!("<h2>Both counters</h2>");
        a!("<div class=\"cards\">");
        let card = |k: &str, v: &str, n: &str| {
            format!(
                "<div class=\"card\"><div class=\"k\">{}</div><div class=\"v\">{}</div>{}</div>",
                esc(k),
                esc(v),
                if n.is_empty() { String::new() } else { format!("<div class=\"n\">{}</div>", esc(n)) }
            )
        };
        out.push(card(
            "Mean, together",
            &format!("{} CPM", f(1, t.cpm)),
            &format!("{} uSv/h", f(3, t.usvh)),
        ));
        out.push(card(
            "Precision",
            // THE CHARACTER, NOT THE ENTITY. `card` escapes its value, so
            // "&plusmn;" arrives on the page as those nine letters. The
            // document is utf-8 and has been since the first line of it.
            &format!("\u{b1}{} CPM", f(1, t.sigma)),
            &format!("{}% of the mean", f(2, 100.0 * t.sigma / pymax(t.cpm, 1e-9))),
        ));
        out.push(card(
            "Arrivals behind it",
            &commas(t.counts),
            &format!("over {} tube-hours", f(1, t.seconds / 3600.0)),
        ));
        out.push(match &t.worst {
            Some((z, _, _)) => card(
                "Do they agree?",
                agreement(*z),
                &format!("widest gap {} sigma", f(1, *z)),
            ),
            None => card("Do they agree?", "--", "not enough counts yet"),
        });
        a!("</div>");
        a!(
            "<p class=\"note\">Two tubes watching one room are two measurements of \
             one number: they do <strong>not</strong> double the dose &mdash; what \
             doubles is the evidence. The mean above is counts-weighted across \
             {} tubes, and the precision is all a second counter buys: arrivals \
             are Poisson, so N of them are known to 1/&radic;N and twice the \
             counts is a factor of &radic;2 better. The agreement is the one \
             question a second instrument exists to answer &mdash; identical \
             tubes in one room should sit within about two sigma of each other, \
             and a gap that keeps growing is the tubes differing, not the room \
             being interesting.</p>",
            t.tubes
        );
        let series: Vec<(String, Vec<(f64, f64, Option<f64>)>)> = counters
            .iter()
            .map(|(serial, c)| (serial.clone(), hour_series(c)))
            .collect();
        let plot = svg_overlay(&series);
        if !plot.is_empty() {
            a!("<div class=\"plotwrap\">{}</div>", plot);
            a!("<p class=\"note\">Every counter's hourly mean, one colour each. \
                Two tubes in one room draw the same shape; where they stop being \
                parallel is where something is wrong with a tube, a cable or a \
                pass-through, and no table of averages shows that as quickly.</p>");
        }
    }

    // ---- the merged record, between the pair and the tubes -------------
    //
    // WHERE IT SITS AND WHY. "Both counters" above is arithmetic done HERE,
    // on the rounded per-counter totals; this is arithmetic done at the time,
    // by the process that held the ports, and written down at full precision.
    // The two should agree, and where they do not the merged file is the one
    // that was there. It also carries the one fact the per-counter files
    // cannot hold between them, which is the interleave.
    if let Some(m) = merge {
        a!("<h2>The merged record</h2>");
        a!("<div class=\"cards\">");
        let card = |k: &str, v: &str, n: &str| {
            format!(
                "<div class=\"card\"><div class=\"k\">{}</div><div class=\"v\">{}</div>{}</div>",
                esc(k),
                esc(v),
                if n.is_empty() { String::new() } else { format!("<div class=\"n\">{}</div>", esc(n)) }
            )
        };
        out.push(card(
            "The room",
            &format!("{} CPM", f(3, m.cpm)),
            &format!("\u{b1}{} CPM \u{b7} {} uSv/h", f(3, m.sigma), f(4, m.usvh)),
        ));
        out.push(card(
            "Raw arrivals",
            &commas(m.counts),
            &format!(
                "{} tube-hours over {} hours of room",
                f(2, m.tube_seconds / 3600.0),
                f(2, m.seconds / 3600.0)
            ),
        ));
        out.push(match m.interleave {
            Some(g) => card(
                "Interleave",
                &format!("{} s", f(3, g)),
                &format!(
                    "{}% of what {} tubes could manage",
                    f(0, 100.0 * analysis::interleave_quality(g, m.tubes)),
                    m.tubes
                ),
            ),
            None => card("Interleave", "--", "one tube has nothing to interleave with"),
        });
        out.push(card(
            "Merged rows",
            &commas(m.rows as i64),
            &match (m.first, m.last) {
                (Some(a), Some(b)) => format!("{} to {}", when(a), when(b)),
                _ => String::new(),
            },
        ));
        a!("</div>");
        a!(
            "<p class=\"note\">Every counter keeps its own file and nothing is \
             ever merged into it &mdash; a row that blended two instruments \
             could not be taken apart again, and whether the two agree is the \
             one question a second tube exists to answer. So the merge is a \
             file of its own, <code>cpm-merged-YYYY-MM.tsv</code>, written \
             beside them as the counters are read. It carries both halves of \
             every interval: the <strong>raw</strong> arrivals as integers, \
             with the tube-seconds behind them and a per-tube breakdown, and \
             the <strong>merged</strong> rate of the room &mdash; counts over \
             tube-seconds, which is the mean the tubes agree on and emphatically \
             not their sum. Its numbers are written so that reading them back \
             gives the same number: the per-counter files round to a tenth of a \
             CPM, and this one does not.</p>"
        );
        a!(
            "<p class=\"note\">The <strong>interleave</strong> is the fact no \
             per-counter file can hold. Each tube has its own clock and its own \
             phase and none can be steered, so the gap between one tube\u{2019}s \
             sample and the next tube\u{2019}s is whatever it is &mdash; and the \
             ideal is 1/n of a second, not half of one. Near it, the tubes are \
             taking turns and the pair resolves time n times as finely as one \
             of them could. Near zero they are firing together, which still \
             multiplies the counts and still buys the precision above, and adds \
             no time resolution at all.</p>"
        );
        if !m.latest.is_empty() {
            a!("<h3>The last merged rows</h3>");
            a!("<div class=\"tablewrap\"><table><thead><tr>");
            for h in ["Time", "Tubes", "Interleave", "Raw counts", "Room s",
                      "Tube s", "Room CPM", "Arrivals/s", "CPM 30s"] {
                a!("<th>{}</th>", esc(h));
            }
            a!("</tr></thead><tbody>");
            for (_, cells) in m.latest.iter().rev() {
                a!("<tr>");
                // RAW AND MERGED IN ONE ROW, side by side and labelled, which
                // is the only way to see that they are two readings of the
                // same seconds rather than two different measurements.
                for (i, places) in [
                    (0usize, usize::MAX), (1, 0), (2, 3), (3, 0), (4, 0),
                    (5, 0), (6, 3), (7, 3), (8, 3),
                ] {
                    let raw = cells.get(i).map(String::as_str).unwrap_or("");
                    let text = if places == usize::MAX {
                        raw.replace('T', " ")
                    } else if raw.is_empty() {
                        "\u{2014}".to_string()
                    } else {
                        match float_cell(raw) {
                            // cps is per tube-second; a reader wants it a
                            // minute at a time, as everything else here is.
                            Some(v) if i == 6 => f(places, v * 60.0),
                            Some(v) => f(places, v),
                            None => raw.to_string(),
                        }
                    };
                    a!("<td>{}</td>", esc(&text));
                }
                a!("</tr>");
            }
            a!("</tbody></table></div>");
        }
    }

    for (serial, c) in counters {
        let at = match c.last {
            Some(l) if l != 0.0 => l,
            _ => now(),
        };
        let here = log::site_at(serial, at, sites);
        a!("<h2>Counter {}</h2>", esc(serial));
        a!("<div class=\"cards\">");
        let card = |k: &str, v: &str, n: &str| {
            format!(
                "<div class=\"card\"><div class=\"k\">{}</div><div class=\"v\">{}</div>{}</div>",
                esc(k),
                esc(v),
                if n.is_empty() { String::new() } else { format!("<div class=\"n\">{}</div>", esc(n)) }
            )
        };
        out.push(card("Mean", &format!("{} CPM", f(1, c.cpm)), &format!("{} uSv/h", f(3, c.usvh))));
        out.push(match c.peak {
            None => card("Highest 3s peak", "--", ""),
            Some(p) => card(
                "Highest 3s peak",
                &format!("{} CPM", f(0, p)),
                &format!("{} uSv/h", f(3, p / cpm_per_usvh)),
            ),
        });
        out.push(card(
            "Rows",
            &commas(c.rows as i64),
            &format!("{} hours counted", f(1, c.seconds / 3600.0)),
        ));
        let stamp = |t: Option<f64>| match t {
            Some(t) if t != 0.0 => when(t),
            _ => "--".to_string(),
        };
        out.push(card("Covering", &stamp(c.first), &format!("to {}", stamp(c.last))));
        if let Some(name) = here {
            out.push(card("Site", &name, ""));
        }
        a!("</div>");

        let chart = svg_plot(&hour_series(c));
        if !chart.is_empty() {
            a!("<h2>Counts per minute, by the hour</h2>");
            a!("<div class=\"plotwrap\">{}", chart);
            a!("<div class=\"legend\">\
                <span><i style=\"border-top-color:var(--accent)\"></i>\
                hourly mean</span>\
                <span><i style=\"border-top-color:var(--warn)\"></i>\
                highest 3-second peak in the hour</span>\
                <span>a break in the line is an hour with no recording</span>\
                </div></div>");
        }

        a!("<h2>By day</h2>");
        a!("<div class=\"tablewrap\"><table><thead><tr><th>Day</th>\
            <th>Mean CPM</th>\
            <th>&micro;Sv/h</th><th>Peak 3s CPM</th><th>Rows</th>\
            <th>Hours</th></tr></thead><tbody>");
        for (day, d) in c.days.iter().rev() {
            let cpm = if d.seconds != 0.0 { d.counts as f64 * 60.0 / d.seconds } else { 0.0 };
            a!(
                "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>",
                esc(day),
                f(1, cpm),
                f(3, cpm / cpm_per_usvh),
                d.peak.map(|p| f(0, p)).unwrap_or_else(|| "--".to_string()),
                d.rows,
                f(1, d.seconds / 3600.0)
            );
        }
        a!("</tbody></table></div>");

        a!("<h2>Latest rows</h2>");
        a!("<div class=\"tablewrap\"><table><thead><tr><th>Time</th>\
            <th>CPS</th><th>3s</th><th>30s</th><th>300s</th><th>Peak 3s</th>\
            <th>Source</th><th>Site</th></tr></thead><tbody>");
        for (_t, cells) in c.latest.iter().rev() {
            let cell = |i: usize| match cells.get(i) {
                Some(s) if !s.is_empty() => esc(s),
                _ => "--".to_string(),
            };
            a!(
                "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>",
                esc(&cells[0]),
                cell(1),
                cell(4),
                cell(5),
                cell(6),
                cell(7),
                cell(10),
                cell(11)
            );
        }
        a!("</tbody></table></div>");
        if !c.links.is_empty() {
            let links: Vec<String> = c
                .links
                .iter()
                .map(|(name, href)| format!("<a href=\"{}\">{}</a>", href, esc(name)))
                .collect();
            a!(
                "<p class=\"more\">The last {} rows of {}. Read the full chart: {} &mdash; tab-separated, one row every 30 seconds.</p>",
                c.latest.len(),
                commas(c.rows as i64),
                links.join(" &middot; ")
            );
        }
        // THIS TUBE'S OWN AUDIT PAGE. Each counter's emissions are recomputed
        // from that counter's own counts and belong to it alone, so the link
        // lives in its section rather than once at the top of the page.
        if let Some(href) = randoms.get(serial) {
            a!(
                "<p class=\"more\"><a href=\"{}\">Where this counter's random \
                 comes from</a> &mdash; every line it has emitted, with the \
                 counts behind it.</p>",
                esc(href)
            );
        }
    }

    // THE HOW-TO AND THE DATA ON ONE PAGE. Somebody arriving from a link
    // wants to know what they are looking at and how to get their own.
    a!("<section class=\"how\">");
    a!("<h2>How to use it</h2>");
    let shot = |out: &mut Vec<String>, name: &str, caption: &str| {
        if let Some(src) = shots.get(name) {
            out.push(format!(
                "<figure><img src=\"{}\" alt=\"{}\" loading=\"lazy\"><figcaption>{}</figcaption></figure>",
                esc(src),
                esc(caption),
                esc(caption)
            ));
        }
    };

    a!("<h3>What you need</h3>");
    a!("<p><b>A GQ GMC-320 Plus, plugged into a USB port, switched on.</b> \
        That is the hardware, and no amount of software substitutes for it: \
        every number on this page came off a real tube over a real serial \
        port. A <b>GMC-300</b> works too &mdash; RadBeeper tries its 57600 \
        baud as well as the 320's 115200 &mdash; and a 500 or 600 is found \
        and read, but its tube is not an M4011, so it needs its own \
        <code>--cpm-per-usvh</code>.</p>");
    a!("<ul>");
    a!("<li><b>The USB cable that came with it.</b> A charge-only cable \
        carries no data, and is indistinguishable from an empty port until \
        you try another one.</li>");
    a!("<li><b>The counter switched on.</b> Its USB-serial chip is powered \
        by the counter, not by the bus &mdash; a flat 320 enumerates as \
        nothing.</li>");
    a!("<li><b>A kernel with <code>ch341</code>.</b> The 320 Plus presents \
        as a CH340. <code>linux-lts</code> and <code>linux-rpi</code> carry \
        the driver; Alpine's <code>linux-virt</code> does not, which is the \
        commonest reason a counter that is plugged in cannot be found. \
        <a href=\"https://github.com/vonglurt/copal\">Copal</a> installs the \
        <code>linux-lts</code> Alpine package, so the case does not arise \
        there.</li>");
    a!("<li><b>Membership of <code>dialout</code>.</b> The serial node is \
        <code>root:dialout</code> and RadBeeper does not want root.</li>");
    a!("</ul>");
    a!("<p>Plugged in and working, Linux says so: <code>dmesg</code> ends \
        with <code>ch341-uart converter now attached to ttyUSB0</code> and \
        <code>/dev/ttyUSB0</code> exists. USB pass-through into a VM counts \
        &mdash; these logs came from one &mdash; provided the guest kernel \
        is one of the two that has the driver.</p>");
    a!("<p>No counter yet? <code>radbeeper --source sim watch</code> draws \
        the whole monitor against a synthetic Poisson background.</p>");

    a!("<h3>Install</h3>");
    a!("<p>One stdlib Python file. No packages, no build, nothing to compile \
        &mdash; the install is a copy.</p>");
    a!("<pre>git clone {}.git\n\
        cd radbeeper &amp;&amp; make install\n\n\
        doas adduser $USER dialout    # then log in again</pre>", HOMEPAGE);
    a!("<p>The read side is also a Rust crate, if a native binary suits the \
        machine better: <code>cargo install radbeeper</code>, or a static \
        musl build from the <a href=\"{}/releases\">releases \
        page</a> for x86_64, aarch64, armv7 or the Pi Zero's armv6. It does \
        <code>probe</code>, <code>cpm</code> and <code>watch</code>; \
        everything that writes these logs stays in the Python.</p>", HOMEPAGE);

    a!("<h3>Find the counter</h3>");
    a!("<pre>radbeeper probe</pre>");
    shot(&mut out, "probe", "radbeeper probe, against the counter these logs came from");
    a!("<p>If it finds nothing it says which of four things went wrong, because \
        they have four different fixes: no serial node at all (often a kernel \
        with no <code>ch341</code> &mdash; Alpine's <code>linux-virt</code> has \
        none, <code>linux-lts</code> does), permission on the node, something \
        that is not a GMC, or a port another reader already holds.</p>");

    a!("<h3>Watch it</h3>");
    a!("<pre>radbeeper watch</pre>");
    shot(&mut out, "watch", "the monitor: five time constants, the counts, the \
        spectrum and a line of decay-derived random");
    shot(&mut out, "watch-20s", "twenty seconds of a real session, at ten times speed");
    a!("<p>The counter's own reading is a rolling 60-second count &mdash; one \
        number with one time constant. RadBeeper counts the blips itself and \
        keeps five windows at once, each a factor of ten apart.</p>");
    a!("<ul class=\"windows\">");
    a!("<li><b>3 s</b><span>Three seconds is too short to be a measurement. \
        On a 40 CPM background it swings between 0 and 80, because at this \
        rate three seconds is two counts. Watch it to see a source come and \
        go as you move it, and do not write it down.</span></li>");
    a!("<li><b>30 s</b><span>Half a minute, and the shortest window that is a \
        count rather than a flicker. Settled enough to compare two places, \
        quick enough to follow your hands &mdash; which is why it is the \
        number in the big digits, and what <code>radbeeper cpm</code> \
        reports.</span></li>");
    a!("<li><b>300 s</b><span>Five minutes. A number worth writing \
        down.</span></li>");
    a!("<li><b>3000 s</b><span>Fifty minutes. What the background here \
        actually is, once the day's traffic through the room has averaged \
        out.</span></li>");
    a!("<li><b>30000 s</b><span>Eight hours twenty &mdash; a working day. It \
        is not a faster answer to the same question, it is the only window \
        that spans one; a shift's worth of background, against which a day \
        that was different is visible as a difference.</span></li>");
    a!("</ul>");
    a!("<p><strong>A window shows nothing until it is full</strong>, and says \
        how long it still needs. A three-second CPM built from one sample is \
        twenty times noisier than it looks, and drawing it as though it were \
        settled is how a 25 CPM background reads as 60 and somebody goes \
        hunting for a leak.</p>");
    shot(&mut out, "watch-filling", "the long window still filling, and saying so");
    a!("<h3>Is anything periodic?</h3>");
    a!("<p>The monitor also accumulates a power spectrum of the per-second \
        counts. <strong>Decay is a Poisson process and the spectrum of a \
        Poisson process is flat</strong> &mdash; so a featureless strip is the \
        good answer, and says that nothing is arriving on a schedule.</p>");
    shot(&mut out, "watch-spectrum", "the accumulating spectrum: flat is healthy");
    a!("<p>A peak is the interesting case: mains hum on the tube's supply, a \
        fan carrying a source past, a loose connector, firmware that batches \
        its reporting. In the time domain all of those look exactly like more \
        counts. Averaging successive windows is what makes a real line climb \
        out of the noise &mdash; one periodogram of a Poisson process is flat \
        in expectation and violently noisy in fact.</p>");
    a!("<p>No counter on the desk? Every command runs against a built-in \
        source, and it is a real one &mdash; radioactive decay is a Poisson \
        process, so the simulator draws Poisson samples.</p>");
    a!("<pre>radbeeper --source sim --sim-cpm 400 watch</pre>");

    a!("<h3>Random numbers out of decay</h3>");
    a!("<p>The monitor also keeps an entropy pool and prints a line of hex \
        whenever the samples have <strong>earned</strong> it. Not modelled \
        &mdash; measured: the counts coming back over the serial link are \
        measurably burstier than Poisson, so the bits per second are \
        estimated from the samples themselves and pushed to the far end of a \
        99% confidence interval before anything is emitted.</p>");
    a!("<pre>radbeeper random</pre>");
    if let Some(l) = random_link {
        a!("<p><a href=\"{}\"><strong>Where the random \
            comes from</strong></a> &mdash; the counts against the model, the \
            bits accumulating second by second, what the serial link's \
            one-second resolution costs, and every line emitted with the \
            counts behind it.</p>", esc(l));
    }

    a!("<h3>Log it</h3>");
    a!("<pre>radbeeper service</pre>");
    a!("<p>A row every 30 seconds into a dated file per counter, \
        <code>cpm-&lt;serial&gt;-YYYY-MM.tsv</code> &mdash; which is rotation \
        by construction, with no cron entry and nothing renaming a file while \
        a service appends to it. Each row carries the <strong>peak</strong> \
        every window reached since the last one, so a source that came and \
        went between two rows still leaves a trace.</p>");
    shot(&mut out, "log-output", "the log on disk, and what a row holds");
    a!("<p>Tabs are invisible, and that matters here: an <strong>empty field is \
        not a zero</strong>, it is a window that was not full yet.</p>");
    shot(&mut out, "log-tabs", "the same rows with every tab made visible");
    a!("<p>The counter also records to its own flash whether or not anything \
        is listening. <code>radbeeper backfill</code> reads that back and \
        fills the gaps &mdash; one row per slot, never over a live \
        measurement, and an hour nobody recorded stays an hour nobody \
        recorded.</p>");
    a!("<pre>radbeeper backfill</pre>");

    a!("<h3>Publish it</h3>");
    a!("<pre>radbeeper export --logs logs -o index.html</pre>");
    a!("<p>This page. Fork the repository, copy your <code>cpm-*.tsv</code> \
        into <code>logs/</code>, push, and the workflow rebuilds and commits \
        it &mdash; served by GitHub Pages with no build step. There is nothing \
        to install in the workflow: the generator is the same one file, which \
        is also why the page cannot drift from the log format.</p>");
    a!(
        "<p>MIT License &mdash; Copyright (c) 2026 Paul Richeson &middot; <a href=\"{}\">{}</a></p>",
        HOMEPAGE,
        HOMEPAGE.split_once("//").map(|(_, rest)| rest).unwrap_or(HOMEPAGE)
    );
    a!("</section>");
    a!("<footer>MIT License &mdash; Copyright (c) 2026 Paul Richeson. \
        Rows marked <code>live</code> were measured by a monitor on \
        this machine; rows marked <code>flash</code> were reconstructed from \
        the counter's own recorded history. Gaps are gaps: nothing is \
        interpolated. Built by \
        <code>radbeeper export</code>.</footer>");
    a!("</main>");
    a!("</body></html>");
    out.join("\n") + "\n"
}

// ------------------------------------------------------------- random.html ---

/// [(serial, path)] for every emission log in a directory.
pub fn random_files(directory: &Path) -> Vec<(String, PathBuf)> {
    let mut names: Vec<String> = match fs::read_dir(directory) {
        Ok(entries) => entries
            .filter_map(|e| e.ok())
            .filter_map(|e| e.file_name().into_string().ok())
            .collect(),
        Err(_) => return Vec::new(),
    };
    names.sort();
    names
        .into_iter()
        .filter(|n| n.starts_with("random-") && n.ends_with(".tsv") && n.len() >= 11)
        .map(|n| (n[7..n.len() - 4].to_string(), directory.join(&n)))
        .collect()
}

/// Per-second counts, tallied in the order each value first appeared -- the
/// order a Python `Counter` iterates in, which decides ties.
pub struct Freq {
    order: Vec<u32>,
    counts: BTreeMap<u32, usize>,
}

impl Freq {
    fn of(samples: &[u32]) -> Freq {
        let mut f = Freq { order: Vec::new(), counts: BTreeMap::new() };
        for s in samples {
            let n = f.counts.entry(*s).or_insert(0);
            if *n == 0 {
                f.order.push(*s);
            }
            *n += 1;
        }
        f
    }

    fn get(&self, k: u32) -> usize {
        self.counts.get(&k).copied().unwrap_or(0)
    }

    /// The most common value; the first seen of equals.
    fn mode(&self) -> u32 {
        let mut best = self.order[0];
        for k in &self.order {
            if self.get(*k) > self.get(best) {
                best = *k;
            }
        }
        best
    }
}

/// Everything the page says about a set of per-second counts: measured
/// first, modelled second, and the ratio between them.
pub struct Budget {
    pub n: usize,
    pub mean: f64,
    pub var: f64,
    pub dispersion: f64,
    pub pmax: f64,
    pub measured: f64,
    pub modelled: f64,
    pub ratio: f64,
    pub freq: Freq,
    pub seconds_for: Option<f64>,
    pub seconds_modelled: Option<f64>,
}

pub fn entropy_budget(samples: &[u32]) -> Option<Budget> {
    let n = samples.len();
    if n < 2 {
        return None;
    }
    let freq = Freq::of(samples);
    let total: u64 = samples.iter().map(|x| *x as u64).sum();
    let mean = total as f64 / n as f64;
    let var = py_sum(samples.iter().map(|x| pow(*x as f64 - mean, 2.0))) / (n - 1) as f64;
    let most = freq.get(freq.mode());
    let measured = entropy::mcv_min_entropy(samples);
    let modelled = entropy::poisson_min_entropy(mean);
    let bits = entropy::ENTROPY_BITS;
    Some(Budget {
        n,
        mean,
        var,
        dispersion: if mean != 0.0 { var / mean } else { 0.0 },
        pmax: most as f64 / n as f64,
        measured,
        modelled,
        ratio: if measured != 0.0 { modelled / measured } else { 0.0 },
        freq,
        seconds_for: (measured != 0.0).then(|| bits / measured),
        seconds_modelled: (modelled != 0.0).then(|| bits / modelled),
    })
}

/// Observed counts against the Poisson the model assumed, side by side, on a
/// log axis -- the interesting disagreement is in the tail.
pub fn svg_hist(freq: &Freq, lam: f64) -> String {
    let (width, height, pad_l, pad_b, pad_t, pad_r) = (1120i64, 340i64, 54i64, 34i64, 14i64, 12i64);
    let n: usize = freq.counts.values().sum();
    if n == 0 {
        return String::new();
    }
    let top = freq.counts.keys().next_back().copied().unwrap_or(0);
    let kmax = top.max(8).min(12);
    let lo = 1e-5f64;
    let hi = 1.0f64;
    let span = hi.log10() - lo.log10();
    let iw = width - pad_l - pad_r;
    let ih = height - pad_t - pad_b;
    let slot = iw as f64 / (kmax + 1) as f64;
    let bw = slot * 0.36;
    let y_of = |p: f64| pad_t as f64 + ih as f64 * (1.0 - (pymax(p, lo).log10() - lo.log10()) / span);

    let mut out = vec![format!(
        "<svg class=\"plot hist\" viewBox=\"0 0 {} {}\" width=\"100%\" \
         preserveAspectRatio=\"xMidYMid meet\" role=\"img\" aria-label=\"\
         observed counts per second against the Poisson model\">",
        width, height
    )];
    for decade in [1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001] {
        let y = y_of(decade);
        out.push(format!(
            "<line class=\"grid\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
            pad_l, f(1, y), width - pad_r, f(1, y)
        ));
        out.push(format!(
            "<text class=\"ylab\" x=\"{}\" y=\"{}\">{}</text>",
            pad_l - 8,
            f(1, y + 4.0),
            if decade >= 0.001 { log::g(decade) } else { e0(decade) }
        ));
    }
    let base = y_of(lo);
    for k in 0..=kmax {
        let x = pad_l as f64 + slot * k as f64 + slot / 2.0;
        let bars = [
            (poisson_pmf(lam, k), "modelled"),
            (freq.get(k) as f64 / n as f64, "seen"),
        ];
        for (i, (p, cls)) in bars.iter().enumerate() {
            if *p <= 0.0 {
                continue;
            }
            let y = y_of(*p);
            out.push(format!(
                "<rect class=\"{}\" x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/>",
                cls,
                f(1, x + (i as i64 - 1) as f64 * bw),
                f(1, y),
                f(1, bw),
                f(1, pymax(0.0, base - y))
            ));
        }
        out.push(format!(
            "<text class=\"xlab\" x=\"{}\" y=\"{}\">{}</text>",
            f(1, x),
            height - 12,
            k
        ));
    }
    out.push(format!(
        "<text class=\"xcap\" x=\"{}\" y=\"{}\">counts in one second</text>",
        pad_l,
        height - 1
    ));
    out.push(format!(
        "<text class=\"ycap\" x=\"{}\" y=\"{}\">share of seconds</text>",
        pad_l - 46,
        pad_t - 2
    ));
    out.push("</svg>".to_string());
    out.concat()
}

/// Bits accumulating against seconds: measured, and what was claimed. Where
/// the measured line crosses the target is when a line is emitted.
pub fn svg_bits(samples: &[u32]) -> String {
    let want = ENTROPY_BITS;
    let (width, height, pad_l, pad_b, pad_t, pad_r) = (1120i64, 320i64, 54i64, 34i64, 14i64, 12i64);
    let n = samples.len();
    if n < 30 {
        return String::new();
    }
    let step = (n / 240).max(1);
    let mut xs: Vec<usize> = Vec::new();
    let mut meas: Vec<f64> = Vec::new();
    let mut model: Vec<f64> = Vec::new();
    let mut pool = entropy::Entropy::new(want as f64);
    for (i, x) in samples.iter().enumerate() {
        let i = i + 1;
        pool.add(*x);
        if i % step != 0 && i != n {
            continue;
        }
        xs.push(i);
        meas.push(pool.bits());
        model.push(entropy::poisson_min_entropy(pool.rate()) * i as f64);
    }
    let top = model.iter().copied().fold(model[0], |a, b| if b > a { b } else { a });
    let hi = pymax(top, want as f64) * 1.05;
    let iw = width - pad_l - pad_r;
    let ih = height - pad_t - pad_b;
    let x_of = |t: usize| pad_l as f64 + (iw * t as i64) as f64 / n as f64;
    let y_of = |v: f64| pad_t as f64 + ih as f64 * (1.0 - v / hi);
    let path = |ys: &[f64]| -> String {
        xs.iter()
            .zip(ys)
            .enumerate()
            .map(|(i, (x, y))| {
                format!("{}{} {}", if i == 0 { "M" } else { "L" }, f(1, x_of(*x)), f(1, y_of(*y)))
            })
            .collect::<Vec<_>>()
            .join(" ")
    };

    let mut out = vec![format!(
        "<svg class=\"plot bits\" viewBox=\"0 0 {} {}\" width=\"100%\" \
         preserveAspectRatio=\"xMidYMid meet\" role=\"img\" aria-label=\"\
         bits of min-entropy accumulating against seconds\">",
        width, height
    )];
    // A gridline every 64 bits is twenty-one labels on a long pool. Pick the
    // coarsest step that still leaves five or more.
    let tick = [64i64, 128, 256, 512, 1024]
        .iter()
        .copied()
        .find(|t| hi / *t as f64 <= 8.0)
        .unwrap_or(1024);
    let mut v = 0i64;
    while v as f64 <= hi {
        let y = y_of(v as f64);
        out.push(format!(
            "<line class=\"grid\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
            pad_l, f(1, y), width - pad_r, f(1, y)
        ));
        out.push(format!(
            "<text class=\"ylab\" x=\"{}\" y=\"{}\">{}</text>",
            pad_l - 8,
            f(1, y + 4.0),
            v
        ));
        v += tick;
    }
    out.push(format!(
        "<line class=\"target\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\"/>",
        pad_l,
        f(1, y_of(want as f64)),
        width - pad_r,
        f(1, y_of(want as f64))
    ));
    let every = ((n / 8 / 60).max(1) * 60).max(60);
    for t in (every..=n).step_by(every) {
        out.push(format!(
            "<text class=\"xlab\" x=\"{}\" y=\"{}\">{}s</text>",
            f(1, x_of(t)),
            height - 12,
            t
        ));
    }
    out.push(format!("<path class=\"peak\" d=\"{}\"/>", path(&model)));
    out.push(format!("<path class=\"mean\" d=\"{}\"/>", path(&meas)));
    out.push(format!(
        "<text class=\"ycap\" x=\"{}\" y=\"{}\">bits</text>",
        pad_l - 46,
        pad_t - 2
    ));
    out.push("</svg>".to_string());
    out.concat()
}

/// The frame viewer, compiled in from the one copy of it.
///
/// tools/embedjs.py pastes these same characters into the Python between
/// markers, and tests/test_frames_js.py fails if the two ever drift. See the
/// header of src/frames.js for why it is done that way round.
const VIEWER_JS: &str = include_str!("frames.js");

/// A payload's text, made safe to sit inside a <script> element.
///
/// THE ONLY SEQUENCE THAT MATTERS IS `</`. Inside a <script>, the HTML parser
/// is not looking for entities -- escaping `&` or `"` here would corrupt the
/// data, since the browser hands it back verbatim -- it is looking for the
/// end of the element, which any `</` can start. Breaking that one digraph is
/// necessary and sufficient, and the viewer puts it back.
fn esc_payload(text: &str) -> String {
    text.replace("</", "<\\/")
}

/// The meta block the viewer reads: strings only, and none of them user HTML.
fn json_meta(serial: &str, audit: &Audit) -> String {
    format!(
        "{{\"version\":{},\"serial\":{},\"place\":{},\"fix\":{},\"summary\":{}}}",
        json_str(VERSION),
        json_str(serial),
        json_str(&audit.place),
        json_str(&audit.fix),
        json_str(&audit.summary())
    )
}

/// A JSON string literal, with the two escapes a <script> payload needs.
fn json_str(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '<' => out.push_str("\\u003c"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

const RANDOM_CSS: &[&str] = &[
    ".hist .seen{fill:var(--accent)}",
    ".hist .modelled{fill:var(--dim);opacity:.45}",
    ".bits .target{stroke:var(--warn);stroke-width:1;stroke-dasharray:4 3}",
    ".plot .xcap{text-anchor:start;font-size:10px;letter-spacing:.05em;\
     text-transform:uppercase}",
    ".ledger{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;\
     font-size:.78rem;word-break:break-all}",
    ".budget td:first-child{width:52%}",
    ".note{color:var(--dim);font-size:.85rem;max-width:68ch}",
];

/// The audit page: what the source is, what it is worth, and every line.
///
/// Written because the claim on the front page -- 256 bits out of decay --
/// is the one thing on it a reader cannot check by looking.
/// Everything the audit page needs that is not in the emission log itself.
pub struct Audit {
    /// Where the counter was, and how coarse a fix, when one was recorded.
    pub place: String,
    pub fix: String,
    /// The joined table: one row per emission, as the file and as the payload.
    pub joined: String,
    /// The frame files embedded in the page, base64, and which they were.
    pub frames: String,
    pub embedded: Vec<String>,
    /// Every emission file for this counter, for the download list.
    pub files: Vec<(String, u64)>,
    /// How many other counters this machine is logging beside this one.
    pub siblings: Vec<String>,
}

impl Audit {
    /// The line the viewer prints above itself.
    pub fn summary(&self) -> String {
        let embedded = self.embedded.len();
        let files = self.files.len();
        format!(
            "{} emission file{} on record; {} month{} of raw seconds carried in \
             this page.",
            files,
            if files == 1 { "" } else { "s" },
            embedded,
            if embedded == 1 { "" } else { "s" }
        )
    }

    /// An audit page for a counter with nothing recorded about it.
    pub fn bare() -> Audit {
        Audit {
            place: String::new(), fix: String::new(), joined: String::new(),
            frames: String::new(), embedded: Vec::new(), files: Vec::new(),
            siblings: Vec::new(),
        }
    }
}

/// `n` bytes, as a person reads them.
fn bytes_text(n: u64) -> String {
    if n >= 1024 * 1024 {
        format!("{} MiB", f(1, n as f64 / (1024.0 * 1024.0)))
    } else if n >= 1024 {
        format!("{} KiB", f(1, n as f64 / 1024.0))
    } else {
        format!("{} B", n)
    }
}

pub fn render_random_html(serial: &str, pools: &[entropy::Emission], title: &str, index: &str,
                          audit: &Audit) -> String {
    let samples: Vec<u32> = pools.iter().flat_map(|p| p.counts.iter().copied()).collect();
    let budget = entropy_budget(&samples);
    let mut out = page_head(title, RANDOM_CSS);
    macro_rules! a {
        ($($arg:tt)*) => { out.push(format!($($arg)*)) };
    }
    a!("<h1>{}</h1>", esc(title));
    a!(
        "<p class=\"sub\">radbeeper {} &middot; counter {} &middot; {}{} &middot; generated {}</p>",
        VERSION,
        esc(serial),
        pools.len(),
        if pools.len() == 1 { " emission" } else { " emissions" },
        esc(&clock::format(now(), "%Y-%m-%d %H:%M"))
    );
    // WHERE, BEFORE HOW MUCH. A count rate without a place is half a
    // measurement: 40 CPM means one thing in a cellar and another on granite
    // at altitude, and a reader who cannot see which has been given a number
    // they cannot use. The fix is as coarse as whoever recorded it chose --
    // see `radbeeper site --precision`.
    if !audit.place.is_empty() || !audit.fix.is_empty() {
        a!("<p class=\"sub\">{}{}{}</p>",
           if audit.place.is_empty() { String::new() } else { format!("at {}", esc(&audit.place)) },
           if !audit.place.is_empty() && !audit.fix.is_empty() { " &middot; " } else { "" },
           if audit.fix.is_empty() { String::new() } else { format!("<span title=\"rounded when it was recorded, not when it was shown\">{}</span>", esc(&audit.fix)) });
    }
    a!("<p class=\"lede\">The moment a nucleus decays is not determined by \
        anything, which makes a Geiger&ndash;M&uuml;ller counter the textbook \
        hardware entropy source. What is <em>not</em> textbook is how much \
        randomness survives the journey down a serial cable, and that is what \
        this page is for. \
        <a href=\"{}\">Back to the monitor</a>.</p>", esc(index));

    // ------------------------------------------------------- the braid ---
    //
    // THE HONEST VERSION OF THE TWO-COUNTER STORY. It would be easy, and
    // wrong, to write that two tubes are pooled into one key. They are not,
    // and the reason is in the export driver: an emission is an audit trail
    // of ONE source and is recomputed from that source's own counts, so it
    // cannot be merged with another's without becoming uncheckable. What two
    // tubes actually buy is throughput and a witness, and that is what this
    // says.
    if !audit.siblings.is_empty() {
        let n = audit.siblings.len() + 1;
        a!("<h2>The braid: {} tubes, one record</h2>", n);
        a!("<p class=\"lede\"><b>Braided decay.</b> This machine is watching \
            {} independent tubes, and their seconds are brokered into one \
            interleaved record &mdash; the braid &mdash; rather than being \
            averaged into one number. Each strand stays whole and stays \
            attributable, which is what makes the arrangement worth more than \
            a second opinion.</p>", n);
        a!("<div class=\"tablewrap\"><table class=\"budget\"><tbody>");
        let rows: Vec<(String, String)> = vec![
            ("Tubes braided".into(),
             format!("<b>{}</b> &mdash; this page is {}; the others are {}",
                     n, esc(serial),
                     audit.siblings.iter().map(|s| esc(s)).collect::<Vec<_>>().join(", "))),
            ("Lines per hour".into(),
             format!("<b>{}&times;</b> a single tube. Each tube fills its own                       pool at its own rate, so {} pools reach {} bits {} times                       as often as one does", n, n, ENTROPY_BITS, n)),
            ("What the braid is".into(),
             "the <a href=\"docs/cascade.html\">cascade</a>: whole seconds, interleaved in arrival order, one tier per tube. Nothing is summed, so a second can always be traced back to the tube that counted it".into()),
            ("What it is <em>not</em>".into(),
             "<b>one key out of two tubes.</b> The digest of an emission is taken over the counts of a single tube, and deliberately: a key mixed from two sources cannot be recomputed from either one, so nobody downstream could ever check it. Independence is spent on <em>confidence</em> here, not on the bits".into()),
            ("What it buys instead".into(),
             "<b>a witness.</b> Two tubes in one room should agree, to within counting statistics. When they stop agreeing, one of them is wrong &mdash; drifting, dying, shielded, or being pointed at something &mdash; and a single tube cannot tell you that about itself at any price. The monitor prints the agreement as a z-score".into()),
        ];
        for (k, v) in &rows {
            a!("<tr><th>{}</th><td>{}</td></tr>", k, v);
        }
        a!("</tbody></table></div>");
        a!("<p class=\"note\">The catchphrase is doing real work, so it is \
            worth unpacking once: <b>a braid, not a blend.</b> A blend would \
            average the tubes and throw away which was which; the braid keeps \
            every strand separate and legible along its whole length, and \
            gets its strength from the fact that the strands were spun \
            independently.</p>");
    }

    let b = match budget {
        Some(b) => b,
        None => {
            a!("<p>No emissions recorded yet.</p>");
            a!("</main></body></html>");
            return out.join("\n");
        }
    };

    // ---------------------------------------------------------- the link ---
    a!("<h2>What the serial link gives you</h2>");
    a!("<p class=\"note\">Everything below follows from one line of the \
        protocol. <code>&lt;HEARTBEAT1&gt;&gt;</code> makes the counter send \
        <b>two bytes once per second</b>, and those two bytes are a count: \
        how many arrivals landed in that second. The device drives the clock, \
        so there is no drift between its second and ours &mdash; but there is \
        also nothing finer. <b>One integer per second is the entire raw \
        material.</b></p>");
    a!("<div class=\"tablewrap\"><table class=\"budget\"><tbody>");
    // A pool that measured nothing has no "seconds for": the Python cannot
    // print that row at all (it formats None), so there is no byte to match.
    let secs = |v: Option<f64>| v.map(|s| f(0, s)).unwrap_or_else(|| "--".to_string());
    let rows: Vec<(String, String)> = vec![
        ("Link".into(), "115200 baud &mdash; not the limit, and never has been".into()),
        ("What arrives".into(), "2 bytes per second, masked to 14 bits of count".into()),
        ("Sampling resolution".into(), "<b>1 second</b>, the finest the protocol offers".into()),
        ("Samples measured here".into(), commas(b.n as i64)),
        ("Mean".into(), format!("{} counts per second", f(3, b.mean))),
        ("Variance".into(), format!("{} &mdash; Poisson requires this to equal the mean", f(3, b.var))),
        ("Variance / mean".into(), format!("<b>{}</b>, so the arrivals are over-dispersed", f(2, b.dispersion))),
        (
            "Most common value".into(),
            format!("{} counts, in {}% of seconds", b.freq.mode(), f(1, 100.0 * b.pmax)),
        ),
        (
            "Min-entropy, measured".into(),
            format!("<b>{} bits per second</b> (SP 800-90B, 99% bound)", f(3, b.measured)),
        ),
        (
            "Min-entropy, Poisson model".into(),
            format!("{} bits per second &mdash; {}&times; too generous", f(3, b.modelled), f(1, b.ratio)),
        ),
        (
            format!("Seconds for {} bits", ENTROPY_BITS),
            format!(
                "<b>{} s</b> measured, against {} s the model would have claimed",
                secs(b.seconds_for),
                secs(b.seconds_modelled)
            ),
        ),
    ];
    for (k, v) in rows {
        a!("<tr><td>{}</td><td>{}</td></tr>", k, v);
    }
    a!("</tbody></table></div>");

    // ------------------------------------------------- what it is not ---
    a!("<h2>Why the spectrum contributes nothing</h2>");
    a!("<p class=\"note\">The monitor accumulates a power spectrum of the same \
        per-second counts, and it would be easy to think the bits come partly \
        from there. They do not, and cannot. The FFT is a <b>deterministic \
        function</b> of the samples, and for any deterministic \
        <i>f</i>, H<sub>&infin;</sub>(<i>f</i>(X)) &le; H<sub>&infin;</sub>(X): \
        a transform moves information about, it does not make any. Worse, \
        these coefficients come from a mean-subtracted, Hann-tapered window, \
        so neighbouring bins are correlated by construction &mdash; bits \
        pulled from them would look beautiful and carry less than they \
        appear to. <b>The entropy is in the counts. The spectrum is a \
        view of them</b>, used as a health check: a peak means something \
        periodic is contaminating the arrivals, and the emission is marked \
        suspect.</p>");

    // --------------------------------------------------- the distribution ---
    a!("<h2>The counts, against the model that was assumed</h2>");
    a!("<div class=\"plotwrap\">");
    out.push(svg_hist(&b.freq, b.mean));
    a!("</div>");
    a!("<div class=\"legend\"><span><i style=\"border-color:var(--accent)\"></i>\
        observed</span><span><i style=\"border-color:var(--dim)\"></i>\
        Poisson at the same mean</span></div>");
    // Only bins the model expected to see AT ALL. The ratio at k=10 is six
    // figures, which is arithmetic on a denominator of nothing.
    let mut worst: Option<(u32, f64)> = None;
    for (k, count) in b.freq.counts.iter() {
        if *k < 3 {
            continue;
        }
        let o = *count as f64 / b.n as f64;
        let e = poisson_pmf(b.mean, *k);
        if e * b.n as f64 >= 1.0 {
            let r = o / e;
            if worst.map(|w| r > w.1).unwrap_or(true) {
                worst = Some((*k, r));
            }
        }
    }
    let empty = 100.0
        * (b.freq.get(0) as f64 / b.n as f64 / pymax(poisson_pmf(b.mean, 0), 1e-12) - 1.0);
    a!(
        "<p class=\"note\">Empty seconds are <b>{}% more common</b> than \
         Poisson allows, and the tail runs far past it{}. Both push in the \
         same direction: an over-dispersed distribution is piled onto its \
         mode, and the mode is exactly what min-entropy is about. That is why \
         the measured figure is smaller than the modelled one, not larger.",
        f(0, empty),
        match worst {
            Some((k, r)) => format!(
                " &mdash; {} counts in a second happens {}&times; more often \
                 than the model says it should",
                k,
                f(0, r)
            ),
            None => String::new(),
        }
    );

    // ----------------------------------------------------- accumulation ---
    let chart = svg_bits(&samples);
    if !chart.is_empty() {
        a!("<h2>How the bits accumulate</h2>");
        a!("<div class=\"plotwrap\">{}</div>", chart);
        a!("<div class=\"legend\"><span><i style=\"border-color:var(--accent)\">\
            </i>measured</span><span><i style=\"border-color:var(--warn)\">\
            </i>Poisson model</span></div>");
        a!("<p class=\"note\">Every second recorded here, run as one pool. The \
            measured line is flat at first because the confidence bound has \
            nothing to say until there are about a dozen samples; it then \
            straightens as the estimate settles, and where it crosses the \
            dashed target a line is emitted. The modelled line reaches that \
            height in roughly half the time, which is precisely the error \
            this replaced &mdash; and why the pools listed below, collected \
            while the model was believed, all stop short of it.</p>");
    }

    // ------------------------------------------------------- the ceiling ---
    let lam = b.mean;
    let per_ms = if lam > 0.0 { -log_2(1.0 - (-lam * 0.001).exp()) } else { 0.0 };
    a!("<h2>What the resolution costs</h2>");
    a!(
        "<p class=\"note\">Bucketing arrivals into whole seconds throws most of \
         the randomness away, and it is worth knowing how much. If the link \
         reported the <em>time</em> of each arrival rather than a count per \
         second, the gap between two arrivals would be exponential, and \
         quantised to a millisecond it would carry about \
         <b>{} bits per arrival</b> &mdash; roughly {} bits a second at \
         this background rate, against the {} actually available. The \
         counter's protocol has no such message: <code>&lt;GETCPS&gt;&gt;</code> \
         and the heartbeat both answer with a count, never a timestamp. So \
         this is not a limit of the physics or of the tube. <b>It is the \
         cost of the interface</b>, and the honest thing is to measure what \
         gets through it rather than to claim the ceiling.</p>",
        f(1, per_ms),
        f(0, per_ms * lam),
        f(2, b.measured)
    );

    // ---------------------------------------------------------- the audit ---
    a!("<h2>Every line, and the counts behind it</h2>");
    a!("<p class=\"note\">Reproducible is not the same as predictable. Each \
        emission is SHA-256 over a label, its sequence number, the second the \
        pool opened, and the counts &mdash; all of which are here, so anyone \
        can recompute a past line and see it was not invented. That says \
        nothing whatever about the next one, which comes from decays that \
        have not happened.</p>");
    a!("<pre>radbeeper random --check {}</pre>", esc(&format!("random-{}.tsv", serial)));
    // THE BITS COLUMN IS RECOMPUTED HERE, not read out of the file. Rows
    // written before the estimator changed hold a Poisson figure.
    a!("<div class=\"tablewrap\"><table><thead><tr>\
        <th>seq</th><th>opened</th><th>s</th><th>counts/s</th>\
        <th>bits, measured</th><th>Poisson</th><th>flat</th>\
        </tr></thead><tbody>");
    let mut stale = false;
    for p in pools.iter().rev() {
        let mut when = p.time.as_str();
        if when < "2000" {
            // Written by a build that put time.monotonic() where the wall
            // clock belonged, so every such row dates itself to 1969.
            when = "not kept";
            stale = true;
        }
        let measured = entropy::mcv_min_entropy(&p.counts) * p.counts.len() as f64;
        let modelled = entropy::poisson_min_entropy(p.rate) * p.counts.len() as f64;
        a!(
            "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td><b>{}</b></td><td>{}</td><td>{}</td></tr>",
            p.seq,
            esc(when),
            p.seconds,
            f(3, p.rate),
            f(0, measured),
            f(0, modelled),
            if p.flat { "yes" } else { "<b>no</b>" }
        );
        a!("<tr><td colspan=\"7\" class=\"ledger\">{}</td></tr>", esc(&entropy::group_hex(&p.hex)));
    }
    a!("</tbody></table></div>");
    if stale {
        a!("<p class=\"note\">Rows marked <b>not kept</b> were written by a \
            build that recorded <code>time.monotonic()</code> &mdash; seconds \
            since this machine booted &mdash; where the wall clock belonged, \
            so they dated themselves to 1969. The digest used the same \
            number, so those lines still recompute; it was the label that \
            was wrong, and it is fixed. Those rows also stopped collecting on \
            the Poisson figure, which is why their measured column falls \
            short of {} &mdash; they are the evidence, not a warning.</p>", ENTROPY_BITS);
    }
    a!("<p class=\"note\"><b>Treat this as a good physical entropy source, not \
        a certified one.</b> It has not been through a statistical test \
        battery, and {} bits of measured min-entropy is a claim about the \
        samples that were seen, not a proof about the output.</p>", ENTROPY_BITS);

    // ------------------------------------------------ where the photons were ---
    a!("<h2>Where these photons were</h2>");
    a!("<p class=\"note\">A tube counts what arrives, and what arrives \
        depends on where it is standing. Granite gives more than chalk, \
        altitude gives more than sea level, and a cellar gives less than \
        either &mdash; so a count rate without a place is a number nobody \
        else can use. The place is recorded against the counter's serial \
        number <em>over time</em>, because these things get carried about: \
        a reading from last month resolves to where the counter was last \
        month, not to where it is now.</p>");
    if audit.fix.is_empty() {
        a!("<p class=\"note\">No fix has been recorded for this counter. \
            <code>radbeeper site --name \"the north window\" --at \
            51.317,0.891</code> writes one.</p>");
    }
    a!("<p class=\"note\"><b>The precision is the privacy control, and it is \
        applied on the way in.</b> A fix is rounded when it is written down, \
        not when it is displayed, so the file cannot be made to give up a \
        precision it was never told. Three decimal places &mdash; about 110 \
        m &mdash; is the default and is as fine as a fixed monitoring station \
        needs: enough to put it on a map and compare it with somebody else's, \
        not enough to knock on. One place is a town, two a district, four a \
        building, six a doorstep.</p>");

    // ----------------------------------------------------------- the viewer ---
    a!("<h2>Every second, as it was counted</h2>");
    a!("<p class=\"note\">The table below is one row per emission, joined to \
        the count log that was running at the time. Click a row to open the \
        raw seconds behind it. Drag across the chart to narrow the range, \
        drag its edges to resize, scroll to zoom.</p>");
    a!("<p class=\"note\"><b>The chain column is the point of it.</b> Every \
        emission carries <code>link = H(previous link || this key)</code>, so \
        the emissions form a hash chain: any one of them can still be \
        recomputed from its own counts, and the chain additionally says that \
        they were emitted <em>in this order</em> and that none has been taken \
        out. Per-emission integrity cannot see a deletion. The chain can. It \
        is tamper-<em>evidence</em> and not tamper-proofing &mdash; anybody \
        who can rewrite the file can recompute the whole chain &mdash; but \
        the realistic accident is a truncated copy or a log stitched back \
        together wrongly, and it catches those.</p>");
    a!("<p class=\"note\">The link is hashed <em>alongside</em> the key and \
        never into it. Folding it in would change every hex line this program \
        has ever produced and would make each one uncheckable by the \
        reference implementation, which knows nothing about chains.</p>");
    a!("<div id=\"rb-viewer\"></div>");
    a!("<script id=\"rb-meta\" type=\"application/json\">{}</script>",
       json_meta(serial, audit));
    a!("<script id=\"rb-joined\" type=\"text/tab-separated-values\">{}</script>",
       esc_payload(&audit.joined));
    a!("<script id=\"rb-frames\" type=\"text/plain\">{}</script>",
       audit.frames.trim_end());
    a!("<script>{}</script>", VIEWER_JS);

    // --------------------------------------------------------- the downloads ---
    if !audit.files.is_empty() {
        a!("<h2>Take the evidence with you</h2>");
        a!("<p class=\"note\">Nothing on this page is a summary you have to \
            take on trust. These are the files it was built from.</p>");
        a!("<div class=\"tablewrap\"><table class=\"budget\"><tbody>");
        for (name, size) in &audit.files {
            let what = if name.ends_with(".bin") {
                "the raw seconds, one byte each &mdash; open it in the viewer above, or <code>radbeeper random --frames</code>"
            } else if name.ends_with(".hex") {
                "the digits alone, one line per emission"
            } else {
                "the audit trail: every emission with the counts it came from &mdash; <code>radbeeper random --check</code> recomputes them"
            };
            a!("<tr><th><a href=\"logs/{}\">{}</a></th><td>{} &mdash; {}</td></tr>",
               esc(name), esc(name), bytes_text(*size), what);
        }
        a!("</tbody></table></div>");
        if audit.embedded.is_empty() {
            a!("<p class=\"note\">No frames are embedded in this page: the \
                viewer above is showing the summary rows only. The raw \
                seconds are in the <code>.bin</code> files.</p>");
        } else {
            a!("<p class=\"note\">{} of those are carried <em>inside</em> this \
                page, so a copy saved to a disk still audits with nothing to \
                fetch and no server to fetch it from: {}. Older months stay in \
                the files.</p>",
               audit.embedded.len(),
               audit.embedded.iter().map(|n| format!("<code>{}</code>", esc(n)))
                    .collect::<Vec<_>>().join(", "));
        }
    }

    a!("<footer>Generated by <code>radbeeper export</code> \
        {}. <a href=\"{}\">Back to the monitor</a>. \
        &middot; MIT License &mdash; Copyright (c) 2026 Paul Richeson\
        </footer>", VERSION, esc(index));
    a!("</main></body></html>");
    out.join("\n")
}

// ------------------------------------------------------------------ export ---

/// What an export wrote.
pub struct Report {
    /// The index, as the path was given.
    pub index: PathBuf,
    pub counters: usize,
    pub rows: u64,
    /// The audit pages and how many emissions each accounts for: one per
    /// counter that has any, in the order the counters are listed.
    pub randoms: Vec<(PathBuf, usize)>,
}

/// Build index.html -- and random.html beside it, when there are emissions
/// and `random_page` -- from the logs in `logs`.
///
/// The links on the page are relative to the page, so it works wherever it is
/// served from: a repository root on Pages, or a directory opened off a disk.
/// Screenshots are linked only when they are actually beside the page, so an
/// export into some other directory does not litter it with broken images.
pub fn export(
    logs: &Path,
    output: &Path,
    random_page: bool,
    cpm_per_usvh: f64,
    title: &str,
    random_output: Option<&Path>,
    frame_budget: u64,
) -> io::Result<Report> {
    let mut counters = summarise(logs, cpm_per_usvh);
    let out = path_str(output);
    let out_dir = dirname(&abspath(&out));
    for (serial, path) in log::files(logs) {
        if let Some(c) = counters.get_mut(&serial) {
            let p = path_str(&path);
            c.links.push((basename(&p).to_string(), relpath(&p, &out_dir)));
        }
    }
    let sites = log::read_sites(logs);
    let mut shots = BTreeMap::new();
    for name in SHOTS {
        let ext = if name == "watch-20s" { ".gif" } else { ".png" };
        let rel = format!("docs/screenshots/{}{}", name, ext);
        if Path::new(&join(&out_dir, &rel)).exists() {
            shots.insert(name.to_string(), rel);
        }
    }
    // The audit page, when there is anything to audit. Written first so the
    // front page only links to it if it exists.
    let randoms: Vec<(String, Vec<entropy::Emission>)> = random_files(logs)
        .into_iter()
        .map(|(serial, path)| (serial, entropy::read_emissions(&path)))
        .filter(|(_, pools)| !pools.is_empty())
        .collect();
    // ONE AUDIT PAGE PER COUNTER, NOT ONE PER MACHINE. This used to write the
    // first counter's emissions and silently drop every other tube's: with two
    // counters plugged in, half the record simply had no page and nothing said
    // so. An emission is an audit trail of ONE source and is recomputed from
    // that source's own counts, so it cannot be merged with another's either.
    //
    // The first keeps the name `random.html` -- or whatever --random-output
    // asked for -- so a page that has always been at that address still is.
    // The rest go beside it as `random-<serial>.html`.
    let mut random_pages: Vec<(String, String, usize)> = Vec::new();
    if random_page {
        let site_rows = log::read_site_rows(logs);
        let every: Vec<String> = randoms.iter().map(|(s, _)| s.clone()).collect();
        for (i, (serial, pools)) in randoms.iter().enumerate() {
            let target = if i == 0 {
                match random_output.filter(|p| !p.as_os_str().is_empty()) {
                    Some(p) => path_str(p),
                    None => join(&out_dir, "random.html"),
                }
            } else {
                join(&out_dir, &format!("random-{}.html", serial))
            };
            // The place as it was at the LAST emission, not as it is now:
            // the page describes a stretch of recording, and wherever the
            // counter has been moved to since is not where those counts were
            // taken.
            let last = pools.last().and_then(|p| clock::parse_stamp(&p.time))
                            .unwrap_or_else(now);
            let here = log::site_row_at(serial, last, &site_rows);
            let joined = audit::join(logs, serial, pools, cpm_per_usvh);
            let mut head = vec![
                format!("radbeeper {} -- counter {}", VERSION, serial),
                format!("emissions {}", pools.len()),
            ];
            if let Some(h) = here.as_ref() {
                head.push(format!("place {}", h.name));
                let fix = h.fix(log::FIX_PRECISION);
                if !fix.is_empty() {
                    head.push(format!("fix {}", fix));
                }
            }
            head.push(
                "counts is clamped at fifteen a second, as the emission log \
                 records it; the .bin frames hold it unclamped".into(),
            );
            let tsv = audit::joined_tsv(&joined, &head);
            // The table goes out as a file as well as into the page, because
            // a table somebody can only read through javascript is a table
            // they cannot check with anything else.
            let table = join(&out_dir, &format!("frames-{}.tsv", serial));
            fs::write(&table, &tsv)?;
            let embed = audit::frames_to_embed(logs, serial, frame_budget);
            let audit_data = Audit {
                place: here.as_ref().map(|h| h.name.clone()).unwrap_or_default(),
                fix: here.as_ref().map(|h| h.fix(log::FIX_PRECISION))
                         .unwrap_or_default(),
                joined: tsv,
                frames: audit::base64(&audit::frames_bytes(&embed)),
                embedded: embed.iter()
                    .map(|p| basename(&path_str(p)).to_string()).collect(),
                files: audit::downloads(logs, serial),
                siblings: every.iter().filter(|s| *s != serial).cloned().collect(),
            };
            fs::write(&target, render_random_html(serial, pools, RANDOM_TITLE,
                                                  basename(&out), &audit_data))?;
            random_pages.push((serial.clone(), target, pools.len()));
        }
    }
    let links: BTreeMap<String, String> = random_pages
        .iter()
        .map(|(serial, p, _)| (serial.clone(), relpath(p, &out_dir)))
        .collect();
    let merge = merged(logs, cpm_per_usvh);
    let html = render_html(&counters, &sites, cpm_per_usvh, title, &shots, &links,
                           merge.as_ref());
    fs::write(output, html)?;
    Ok(Report {
        index: output.to_path_buf(),
        counters: counters.len(),
        rows: counters.values().map(|c| c.rows).sum(),
        randoms: random_pages
            .into_iter()
            .map(|(_, p, n)| (PathBuf::from(p), n))
            .collect(),
    })
}

/// `radbeeper export`, as the command line runs it: the export, then the same
/// two lines the Python prints.
pub fn run(
    logs: &Path,
    output: &Path,
    random_page: bool,
    cpm_per_usvh: f64,
    title: &str,
    random_output: Option<&Path>,
    frame_budget: u64,
) -> i32 {
    match export(logs, output, random_page, cpm_per_usvh, title, random_output,
                 frame_budget) {
        Ok(r) => {
            println!(
                "radbeeper: {} -- {} counter{}, {} rows",
                r.index.display(),
                r.counters,
                if r.counters == 1 { "" } else { "s" },
                r.rows
            );
            for (p, n) in &r.randoms {
                println!(
                    "radbeeper: {} -- {} emission{}",
                    p.display(),
                    n,
                    if *n == 1 { "" } else { "s" }
                );
            }
            0
        }
        Err(e) => {
            eprintln!("radbeeper: export: {}", e);
            1
        }
    }
}

// ----------------------------------------------------------------- tests ---
#[cfg(test)]
mod tests {
    use super::*;

    /// THE MERGED RECORD SURVIVES THE ROUND TRIP: written by the service,
    /// read back by the page, and the two halves of every interval still
    /// distinguishable at the other end.
    ///
    /// The raw arrivals are integers and stay integers; the room's rate is
    /// counts over TUBE-seconds and not over the wall clock, which is the one
    /// arithmetic mistake a second instrument makes easy; and the interleave
    /// -- the fact no per-counter file can hold -- comes back as it went in.
    #[test]
    fn the_merged_record_is_written_and_read_back_whole() {
        let spans = [3.0, 30.0, 300.0];
        let dir = std::env::temp_dir()
            .join(format!("radbeeper-export-merged-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let mut text = log::merged_header(&spans);
        // Three rows: thirty seconds of room each, two tubes, so sixty
        // tube-seconds behind every one of them.
        for (i, counts) in [30u64, 60, 90].iter().enumerate() {
            text.push('\n');
            text.push_str(&log::merged_row(
                1_700_000_000.0 + 30.0 * i as f64,
                2,
                Some(0.5),
                *counts,
                30.0,
                60.0,
                &[Some(*counts as f64), Some(*counts as f64), None],
                Some(1.0),
                &[None, None, None],
                &[("AAA".into(), counts / 2), ("BBB".into(), counts / 2)],
                log::SRC_LIVE,
                "",
            ));
        }
        fs::write(dir.join("cpm-merged-2023-11.tsv"), text).unwrap();

        let m = merged(&dir, 100.0).expect("a merged log was written");
        assert_eq!(m.rows, 3);
        assert_eq!(m.tubes, 2);
        // RAW: every arrival, as an integer, none of them lost.
        assert_eq!(m.counts, 180);
        // Ninety seconds of room, from a hundred and eighty tube-seconds.
        assert_eq!(m.seconds, 90.0);
        assert_eq!(m.tube_seconds, 180.0);
        // MERGED: 180 arrivals over 180 tube-seconds is sixty a minute --
        // the rate of the ROOM. Over the wall clock it would read 120, which
        // is the pair reported as twice the background.
        assert!((m.cpm - 60.0).abs() < 1e-9, "{}", m.cpm);
        assert!((m.usvh - 0.6).abs() < 1e-9);
        // Poisson: 180 arrivals know the rate to 1/sqrt(180).
        assert!((m.sigma - 60.0 / 180.0f64.sqrt()).abs() < 1e-9, "{}", m.sigma);
        // INTERLEAVED: half a second, which for a pair is a perfect grid.
        assert_eq!(m.interleave, Some(0.5));
        assert!((analysis::interleave_quality(m.interleave.unwrap(), m.tubes) - 1.0).abs() < 1e-9);

        // And it is not a counter. The directory has no per-counter file in
        // it at all, so the report has nothing to double-count.
        assert!(summarise(&dir, 100.0).is_empty());
        assert!(merged(&dir.join("nowhere"), 100.0).is_none());
        let _ = fs::remove_dir_all(&dir);
    }

    /// TWO TUBES DO NOT DOUBLE THE DOSE. Two identical counters, each a
    /// thousand counts in a thousand seconds, read sixty CPM together and not
    /// a hundred and twenty -- and the counts behind that number are the sum,
    /// which is the whole of what a second tube buys.
    #[test]
    fn two_tubes_report_the_mean_rate_and_not_the_sum() {
        let mut counters = BTreeMap::new();
        for serial in ["A", "B"] {
            counters.insert(
                serial.to_string(),
                Counter {
                    serial: serial.to_string(),
                    counts: 1000,
                    seconds: 1000.0,
                    ..Counter::default()
                },
            );
        }
        let t = together(&counters, 100.0).expect("two tubes with counts");
        assert_eq!(t.tubes, 2);
        assert!((t.cpm - 60.0).abs() < 1e-9, "the mean rate, not the sum: {}", t.cpm);
        assert_eq!(t.counts, 2000, "both tubes' arrivals are behind it");
        // 60 CPM from 2000 arrivals: 60/sqrt(2000).
        assert!((t.sigma - 60.0 / 2000f64.sqrt()).abs() < 1e-9);
        // One tube alone would have had 60/sqrt(1000) -- worse by root two.
        let one = 60.0 / 1000f64.sqrt();
        assert!(t.sigma < one, "the pair is the more precise");
        assert!(((one / t.sigma) - 2f64.sqrt()).abs() < 1e-9, "by exactly root two");
    }

    /// Identical tubes agree; wildly different ones are called out. This is
    /// the one question a second instrument exists to answer.
    #[test]
    fn the_pair_is_asked_whether_it_agrees_with_itself() {
        let tube = |counts: i64| Counter { counts, seconds: 1000.0, ..Counter::default() };
        let mut same = BTreeMap::new();
        same.insert("A".to_string(), tube(1000));
        same.insert("B".to_string(), tube(1000));
        let (z, _, _) = together(&same, 100.0).unwrap().worst.unwrap();
        assert!(z < 2.0, "identical tubes agree, got {} sigma", z);
        assert_eq!(agreement(z), "they agree");

        let mut apart = BTreeMap::new();
        apart.insert("A".to_string(), tube(1000));
        apart.insert("B".to_string(), tube(4000));
        let (z, _, _) = together(&apart, 100.0).unwrap().worst.unwrap();
        assert!(z > 4.0, "four times the rate is not the same measurement");
        assert_eq!(agreement(z), "they disagree -- not the same measurement");
    }

    /// One counter is not a pair, and the section is not drawn for it.
    #[test]
    fn one_tube_is_not_asked_to_agree_with_anybody() {
        let mut one = BTreeMap::new();
        one.insert(
            "A".to_string(),
            Counter { counts: 1000, seconds: 1000.0, ..Counter::default() },
        );
        assert!(together(&one, 100.0).is_none());
        // Nor is a second tube that has recorded nothing at all.
        one.insert("B".to_string(), Counter::default());
        assert!(together(&one, 100.0).is_none());
    }

    /// The overlay needs two tubes with a line each; anything less is no
    /// picture and is left out rather than drawn empty.
    #[test]
    fn the_overlay_draws_a_line_per_tube_and_nothing_for_one() {
        let hours = |base: f64| -> Vec<(f64, f64, Option<f64>)> {
            (0..6).map(|i| (i as f64 * 3600.0, base + i as f64, None)).collect()
        };
        let pair = vec![("A".to_string(), hours(40.0)), ("B".to_string(), hours(44.0))];
        let svg = svg_overlay(&pair);
        assert!(svg.contains("<svg"), "a pair is a picture");
        assert_eq!(svg.matches("class=\"tube t").count(), 2, "one line each");
        assert!(svg.contains(">A<") && svg.contains(">B<"), "each line is named");

        assert!(svg_overlay(&pair[..1]).is_empty(), "one tube overlays nothing");
        let stub = vec![
            ("A".to_string(), hours(40.0)),
            ("B".to_string(), vec![(0.0, 40.0, None)]),
        ];
        assert!(svg_overlay(&stub).is_empty(), "a single point is not a line");
    }

    #[test]
    fn numbers_are_written_the_way_python_writes_them() {
        assert_eq!(commas(0), "0");
        assert_eq!(commas(999), "999");
        assert_eq!(commas(1000), "1,000");
        assert_eq!(commas(28544), "28,544");
        assert_eq!(commas(1234567), "1,234,567");
        assert_eq!(e0(0.0001), "1e-04");
        assert_eq!(e0(0.00001), "1e-05");
        assert_eq!(f(0, 2.5), "2", "half to even, as printf does");
        assert_eq!(f(1, 0.25), "0.2");
    }

    #[test]
    fn paths_are_worked_out_the_way_os_path_does() {
        assert_eq!(relpath("/a/b/c.tsv", "/a"), "b/c.tsv");
        assert_eq!(relpath("/a/logs/x.tsv", "/a/site"), "../logs/x.tsv");
        assert_eq!(relpath("/a", "/a"), ".");
        assert_eq!(abspath("/a/./b/../c"), "/a/c");
        assert_eq!(abspath("/"), "/");
        assert_eq!(dirname("/a/b/index.html"), "/a/b");
        assert_eq!(dirname("/index.html"), "/");
        assert_eq!(join("/", "random.html"), "/random.html");
        assert_eq!(basename("out/index.html"), "index.html");
    }

    #[test]
    fn a_tie_for_the_most_common_value_goes_to_the_first_seen() {
        assert_eq!(Freq::of(&[2, 1, 1, 2, 0]).mode(), 2);
        assert_eq!(Freq::of(&[1, 2, 2, 1]).mode(), 1);
    }

    #[test]
    fn the_compensated_sum_is_not_a_running_total() {
        let xs = [1e16, 1.0, -1e16];
        assert_eq!(py_sum(xs.iter().copied()), 1.0);
        assert_eq!(xs.iter().sum::<f64>(), 0.0);
    }

    #[test]
    fn an_axis_ceiling_is_a_round_number() {
        assert_eq!(nice_ceiling(0.0), 1.0);
        assert_eq!(nice_ceiling(37.0), 40.0);
        assert_eq!(nice_ceiling(100.0), 100.0);
        assert_eq!(nice_ceiling(101.0), 150.0);
    }

    #[test]
    fn a_gap_breaks_the_line() {
        let series = vec![
            (0.0, 40.0, Some(80.0)),
            (3600.0, 41.0, None),
            (7200.0 * 4.0, 39.0, Some(90.0)),
        ];
        let svg = svg_plot(&series);
        let mean = svg.split("class=\"mean\" d=\"").nth(1).unwrap();
        assert_eq!(mean.split('"').next().unwrap().matches('M').count(), 2);
    }
}