« get me outta code hell

upd8.js - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/upd8.js
blob: ba002d8508923cf5b7d6f60d8272aada1c18938c (plain)
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
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
#!/usr/bin/env node

// HEY N8RDS!
//
// This is one of the 8ACKEND FILES. It's not used anywhere on the actual site
// you are pro8a8ly using right now.
//
// Specifically, this one does all the actual work of the music wiki. The
// process looks something like this:
//
//   1. Crawl the music directories. Well, not so much "crawl" as "look inside
//      the folders for each al8um, and read the metadata file descri8ing that
//      al8um and the tracks within."
//
//   2. Read that metadata. I'm writing this 8efore actually doing any of the
//      code, and I've gotta admit I have no idea what file format they're
//      going to 8e in. May8e JSON, 8ut more likely some weird custom format
//      which will 8e a lot easier to edit.
//
//   3. Generate the page files! They're just static index.html files, and are
//      what gh-pages (or wherever this is hosted) will show to clients.
//      Hopefully pretty minimalistic HTML, 8ut like, shrug. They'll reference
//      CSS (and maaaaaaaay8e JS) files, hard-coded somewhere near the root.
//
//   4. Print an awesome message which says the process is done. This is the
//      most important step.
//
// Oh yeah, like. Just run this through some relatively recent version of
// node.js and you'll 8e fine. ...Within the project root. O8viously.

// HEY FUTURE ME!!!!!!!! Don't forget to implement artist pages! Those are,
// like, the coolest idea you've had yet, so DO NOT FORGET. (Remem8er, link
// from track listings, etc!) --- Thanks, past me. To futurerer me: an al8um
// listing page (a list of all the al8ums)! Make sure to sort these 8y date -
// we'll need a new field for al8ums.

// ^^^^^^^^ DID THAT! 8ut also, artist images. Pro8a8ly stolen from the fandom
// wiki (I found half those images anywayz).

// TRACK ART CREDITS. This is a must.

// 2020-08-23
// ATTENTION ALL 8*TCHES AND OTHER GENDER TRUCKERS: AS IT TURNS OUT, THIS CODE
// ****SUCKS****. I DON'T THINK ANYTHING WILL EVER REDEEM IT, 8UT THAT DOESN'T
// MEAN WE CAN'T TAKE SOME ACTION TO MAKE WRITING IT A LITTLE LESS TERRI8LE.
// We're gonna start defining STRUCTURES to make things suck less!!!!!!!!
// No classes 8ecause those are a huge pain and like, pro8a8ly 8ad performance
// or whatever -- just some standard structures that should 8e followed
// wherever reasona8le. Only one I need today is the contri8 one 8ut let's put
// any new general-purpose structures here too, ok?
//
// Contri8ution: {who, what, date, thing}. D8 and thing are the new fields.
//
// Use these wisely, which is to say all the time and instead of whatever
// terri8le new pseudo structure you're trying to invent!!!!!!!!
//
// Upd8 2021-01-03: Soooooooo we didn't actually really end up using these,
// lol? Well there's still only one anyway. Kinda ended up doing a 8ig refactor
// of all the o8ject structures today. It's not *especially* relevant 8ut feels
// worth mentioning? I'd get rid of this comment 8lock 8ut I like it too much!
// Even though I haven't actually reread it, lol. 8ut yeah, hopefully in the
// spirit of this "make things more consistent" attitude I 8rought up 8ack in
// August, stuff's lookin' 8etter than ever now. W00t!

'use strict';

const fs = require('fs');
const path = require('path');
const util = require('util');

// I made this dependency myself! A long, long time ago. It is pro8a8ly my
// most useful li8rary ever. I'm not sure 8esides me actually uses it, though.
const fixWS = require('fix-whitespace');
// Wait nevermind, I forgot a8out why-do-kids-love-the-taste-of-cinnamon-toast-
// crunch. THAT is my 8est li8rary.

// The require function just returns whatever the module exports, so there's
// no reason you can't wrap it in some decorator right out of the 8ox. Which is
// exactly what we do here.
const mkdirp = util.promisify(require('mkdirp'));

// This is the dum8est name for a function possi8le. Like, SURE, fine, may8e
// the UNIX people had some valid reason to go with the weird truncated
// lowercased convention they did. 8ut Node didn't have to ALSO use that
// convention! Would it have 8een so hard to just name the function something
// like fs.readDirectory???????? No, it wouldn't have 8een.
const readdir = util.promisify(fs.readdir);
// 8ut okay, like, look at me. DOING THE SAME THING. See, *I* could have named
// my promisified function differently, and yet I did not. I literally cannot
// explain why. We are all used to following in the 8ad decisions of our
// ancestors, and never never never never never never never consider that hey,
// may8e we don't need to make the exact same decisions they did. Even when
// we're perfectly aware th8t's exactly what we're doing! Programmers,
// including me, are all pretty stupid.

// 8ut I mean, come on. Look. Node decided to use readFile, instead of like,
// what, cat? Why couldn't they rename readdir too???????? As Johannes Kepler
// once so elegantly put it: "Shrug."
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const access = util.promisify(fs.access);
const symlink = util.promisify(fs.symlink);
const unlink = util.promisify(fs.unlink);

const {
    cacheOneArg,
    curry,
    decorateTime,
    filterEmptyLines,
    joinNoOxford,
    mapInPlace,
    parseOptions,
    progressPromiseAll,
    queue,
    s,
    splitArray,
    th
} = require('./upd8-util');

const C = require('./common/common');

const CACHEBUST = 2;

const WIKI_INFO_FILE = 'wiki-info.txt';
const HOMEPAGE_INFO_FILE = 'homepage.txt';
const ARTIST_DATA_FILE = 'artists.txt';
const FLASH_DATA_FILE = 'flashes.txt';
const NEWS_DATA_FILE = 'news.txt';
const TAG_DATA_FILE = 'tags.txt';
const GROUP_DATA_FILE = 'groups.txt';
const STATIC_PAGE_DATA_FILE = 'static-pages.txt';

const CSS_FILE = 'site.css';

// Shared varia8les! These are more efficient to access than a shared varia8le
// (or at least I h8pe so), and are easier to pass across functions than a
// 8unch of specific arguments.
//
// Upd8: Okay yeah these aren't actually any different. Still cleaner than
// passing around a data object containing all this, though.
let dataPath;
let mediaPath;
let outputPath;

let wikiInfo;
let homepageInfo;
let albumData;
let trackData;
let flashData;
let newsData;
let tagData;
let groupData;
let staticPageData;

let artistNames;
let artistData;

let officialAlbumData;
let fandomAlbumData;
let justEverythingMan; // tracks, albums, flashes -- don't forget to upd8 getHrefOfAnythingMan!
let justEverythingSortedByArtDateMan;
let contributionData;

let queueSize;

// Note there isn't a 'find track data files' function. I plan on including the
// data for all tracks within an al8um collected in the single metadata file
// for that al8um. Otherwise there'll just 8e way too many files, and I'd also
// have to worry a8out linking track files to al8um files (which would contain
// only the track listing, not track data itself), and dealing with errors of
// missing track files (or track files which are not linked to al8ums). All a
// 8unch of stuff that's a pain to deal with for no apparent 8enefit.
async function findAlbumDataFiles(albumDirectory) {
    return (await readdir(path.join(albumDirectory)))
        .map(albumFile => path.join(albumDirectory, albumFile));
}

function* getSections(lines) {
    // ::::)
    const isSeparatorLine = line => /^-{8,}$/.test(line);
    yield* splitArray(lines, isSeparatorLine);
}

function getBasicField(lines, name) {
    const line = lines.find(line => line.startsWith(name + ':'));
    return line && line.slice(name.length + 1).trim();
}

function getBooleanField(lines, name) {
    // The ?? oper8tor (which is just, hilariously named, lol) can 8e used to
    // specify a default!
    const value = getBasicField(lines, name);
    switch (value) {
        case 'yes':
        case 'true':
            return true;
        case 'no':
        case 'false':
            return false;
        default:
            return null;
    }
}

function getListField(lines, name) {
    let startIndex = lines.findIndex(line => line.startsWith(name + ':'));
    // If callers want to default to an empty array, they should stick
    // "|| []" after the call.
    if (startIndex === -1) {
        return null;
    }
    // We increment startIndex 8ecause we don't want to include the
    // "heading" line (e.g. "URLs:") in the actual data.
    startIndex++;
    let endIndex = lines.findIndex((line, index) => index >= startIndex && !line.startsWith('- '));
    if (endIndex === -1) {
        endIndex = lines.length;
    }
    if (endIndex === startIndex) {
        // If there is no list that comes after the heading line, treat the
        // heading line itself as the comma-separ8ted array value, using
        // the 8asic field function to do that. (It's l8 and my 8rain is
        // sleepy. Please excuse any unhelpful comments I may write, or may
        // have already written, in this st8. Thanks!)
        const value = getBasicField(lines, name);
        return value && value.split(',').map(val => val.trim());
    }
    const listLines = lines.slice(startIndex, endIndex);
    return listLines.map(line => line.slice(2));
};

function getContributionField(section, name) {
    let contributors = getListField(section, name);

    if (!contributors) {
        return null;
    }

    if (contributors.length === 1 && contributors[0].startsWith('<i>')) {
        const arr = [];
        arr.textContent = contributors[0];
        return arr;
    }

    contributors = contributors.map(contrib => {
        // 8asically, the format is "Who (What)", or just "Who". 8e sure to
        // keep in mind that "what" doesn't necessarily have a value!
        const match = contrib.match(/^(.*?)( \((.*)\))?$/);
        if (!match) {
            return contrib;
        }
        const who = match[1];
        const what = match[3] || null;
        return {who, what};
    });

    const badContributor = contributors.find(val => typeof val === 'string');
    if (badContributor) {
        return {error: `An entry has an incorrectly formatted contributor, "${badContributor}".`};
    }

    if (contributors.length === 1 && contributors[0].who === 'none') {
        return null;
    }

    return contributors;
};

function getMultilineField(lines, name) {
    // All this code is 8asically the same as the getListText - just with a
    // different line prefix (four spaces instead of a dash and a space).
    let startIndex = lines.findIndex(line => line.startsWith(name + ':'));
    if (startIndex === -1) {
        return null;
    }
    startIndex++;
    let endIndex = lines.findIndex((line, index) => index >= startIndex && line.length && !line.startsWith('    '));
    if (endIndex === -1) {
        endIndex = lines.length;
    }
    // If there aren't any content lines, don't return anything!
    if (endIndex === startIndex) {
        return null;
    }
    // We also join the lines instead of returning an array.
    const listLines = lines.slice(startIndex, endIndex);
    return listLines.map(line => line.slice(4)).join('\n');
};

function transformInline(text) {
    return text.replace(/\[\[(album:|artist:|flash:|track:|tag:|group:)?(.+?)\]\]/g, (match, category, ref, offset) => {
        if (category === 'album:') {
            const album = getLinkedAlbum(ref);
            if (album) {
                return fixWS`
                    <a href="${C.ALBUM_DIRECTORY}/${album.directory}/" style="${getLinkThemeString(album)}">${album.name}</a>
                `;
            } else {
                console.warn(`\x1b[33mThe linked album ${match} does not exist!\x1b[0m`);
                return ref;
            }
        } else if (category === 'artist:') {
            const artist = getLinkedArtist(ref);
            if (artist) {
                return `<a href="${C.ARTIST_DIRECTORY}/${C.getArtistDirectory(artist.name)}/">${artist.name}</a>`;
            } else {
                console.warn(`\x1b[33mThe linked artist ${artist} does not exist!\x1b[0m`);
                return ref;
            }
        } else if (category === 'flash:') {
            const flash = getLinkedFlash(ref);
            if (flash) {
                let name = flash.name;
                const nextCharacter = text[offset + match.length];
                const lastCharacter = name[name.length - 1];
                if (
                    ![' ', '\n', '<'].includes(nextCharacter) &&
                    lastCharacter === '.'
                ) {
                    name = name.slice(0, -1);
                }
                return getFlashLinkHTML(flash, name);
            } else {
                console.warn(`\x1b[33mThe linked flash ${match} does not exist!\x1b[0m`);
                return ref;
            }
        } else if (category === 'track:') {
            const track = getLinkedTrack(ref);
            if (track) {
                return fixWS`
                    <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                `;
            } else {
                console.warn(`\x1b[33mThe linked track ${match} does not exist!\x1b[0m`);
                return ref;
            }
        } else if (category === 'tag:') {
            const tag = getLinkedTag(ref);
            if (tag) {
                return fixWS`
                    <a href="${C.TAG_DIRECTORY}/${tag.directory}/" style="${getLinkThemeString(tag)}">${tag.name}</a>
                `;
            } else {
                console.warn(`\x1b[33mThe linked tag ${match} does not exist!\x1b[0m`);
                return ref;
            }
        } else if (category === 'group:') {
            const group = getLinkedGroup(ref);
            if (group) {
                return fixWS`
                    <a href="${C.GROUP_DIRECTORY}/${group.directory}/" style="${getLinkThemeString(group)}">${group.name}</a>
                `;
            } else {
                console.warn(`\x1b[33mThe linked group ${group} does not exist!\x1b[0m`);
                return ref;
            }
        } else {
            const track = getLinkedTrack(ref);
            if (track) {
                let name = ref.match(/(.*):/);
                if (name) {
                    name = name[1];
                } else {
                    name = track.name;
                }
                return fixWS`
                    <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${name}</a>
                `;
            } else {
                console.warn(`\x1b[33mThe linked track ${match} does not exist!\x1b[0m`);
                return ref;
            }
        }
    });
}

function parseAttributes(string) {
    const attributes = Object.create(null);
    const skipWhitespace = i => {
        const ws = /\s/;
        if (ws.test(string[i])) {
            const match = string.slice(i).match(/[^\s]/);
            if (match) {
                return i + match.index;
            } else {
                return string.length;
            }
        } else {
            return i;
        }
    };

    for (let i = 0; i < string.length;) {
        i = skipWhitespace(i);
        const aStart = i;
        const aEnd = i + string.slice(i).match(/[\s=]|$/).index;
        const attribute = string.slice(aStart, aEnd);
        i = skipWhitespace(aEnd);
        if (string[i] === '=') {
            i = skipWhitespace(i + 1);
            let end, endOffset;
            if (string[i] === '"' || string[i] === "'") {
                end = string[i];
                endOffset = 1;
                i++;
            } else {
                end = '\\s';
                endOffset = 0;
            }
            const vStart = i;
            const vEnd = i + string.slice(i).match(new RegExp(`${end}|$`)).index;
            const value = string.slice(vStart, vEnd);
            i = vEnd + endOffset;
            attributes[attribute] = value;
        } else {
            attributes[attribute] = attribute;
        }
    }
    return Object.fromEntries(Object.entries(attributes).map(([ key, val ]) => [
        key,
        val === 'true' ? true :
        val === 'false' ? false :
        val === key ? true :
        val
    ]));
}

function transformMultiline(text, treatAsDocument=false) {
    // Heck yes, HTML magics.

    text = transformInline(text.trim());

    if (treatAsDocument) {
        return text;
    }

    const outLines = [];

    const indentString = ' '.repeat(4);

    let levelIndents = [];
    const openLevel = indent => {
        // opening a sublist is a pain: to be semantically *and* visually
        // correct, we have to append the <ul> at the end of the existing
        // previous <li>
        const previousLine = outLines[outLines.length - 1];
        if (previousLine?.endsWith('</li>')) {
            // we will re-close the <li> later
            outLines[outLines.length - 1] = previousLine.slice(0, -5) + ' <ul>';
        } else {
            // if the previous line isn't a list item, this is the opening of
            // the first list level, so no need for indent
            outLines.push('<ul>');
        }
        levelIndents.push(indent);
    };
    const closeLevel = () => {
        levelIndents.pop();
        if (levelIndents.length) {
            // closing a sublist, so close the list item containing it too
            outLines.push(indentString.repeat(levelIndents.length) + '</ul></li>');
        } else {
            // closing the final list level! no need for indent here
            outLines.push('</ul>');
        }
    };

    // okay yes we should support nested formatting, more than one blockquote
    // layer, etc, but hear me out here: making all that work would basically
    // be the same as implementing an entire markdown converter, which im not
    // interested in doing lol. sorry!!!
    let inBlockquote = false;

    for (let line of text.split(/\r|\n|\r\n/)) {
        const imageLine = line.startsWith('<img');
        line = line.replace(/<img (.*?)>/g, (match, attributes) => img({
            lazy: true,
            link: true,
            ...parseAttributes(attributes)
        }));

        let indentThisLine = 0;
        let lineContent = line;
        let lineTag = 'p';

        const listMatch = line.match(/^( *)- *(.*)$/);
        if (listMatch) {
            // is a list item!
            if (!levelIndents.length) {
                // first level is always indent = 0, regardless of actual line
                // content (this is to avoid going to a lesser indent than the
                // initial level)
                openLevel(0);
            } else {
                // find level corresponding to indent
                const indent = listMatch[1].length;
                let i;
                for (i = levelIndents.length - 1; i >= 0; i--) {
                    if (levelIndents[i] <= indent) break;
                }
                // note: i cannot equal -1 because the first indentation level
                // is always 0, and the minimum indentation is also 0
                if (levelIndents[i] === indent) {
                    // same indent! return to that level
                    while (levelIndents.length - 1 > i) closeLevel();
                    // (if this is already the current level, the above loop
                    // will do nothing)
                } else if (levelIndents[i] < indent) {
                    // lesser indent! branch based on index
                    if (i === levelIndents.length - 1) {
                        // top level is lesser: add a new level
                        openLevel(indent);
                    } else {
                        // lower level is lesser: return to that level
                        while (levelIndents.length - 1 > i) closeLevel();
                    }
                }
            }
            // finally, set variables for appending content line
            indentThisLine = levelIndents.length;
            lineContent = listMatch[2];
            lineTag = 'li';
        } else {
            // not a list item! close any existing list levels
            while (levelIndents.length) closeLevel();

            // like i said, no nested shenanigans - quotes only appear outside
            // of lists. sorry!
            const quoteMatch = line.match(/^> *(.*)$/);
            if (quoteMatch) {
                // is a quote! open a blockquote tag if it doesnt already exist
                if (!inBlockquote) {
                    inBlockquote = true;
                    outLines.push('<blockquote>');
                }
                indentThisLine = 1;
                lineContent = quoteMatch[1];
            } else if (inBlockquote) {
                // not a quote! close a blockquote tag if it exists
                inBlockquote = false;
                outLines.push('</blockquote>');
            }
        }

        if (lineTag === 'p') {
            // certain inline element tags should still be postioned within a
            // paragraph; other elements (e.g. headings) should be added as-is
            const elementMatch = line.match(/^<(.*?)[ >]/);
            if (elementMatch && !imageLine && !['a', 'abbr', 'b', 'bdo', 'br', 'cite', 'code', 'data', 'datalist', 'del', 'dfn', 'em', 'i', 'img', 'ins', 'kbd', 'mark', 'output', 'picture', 'q', 'ruby', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'svg', 'time', 'var', 'wbr'].includes(elementMatch[1])) {
                lineTag = '';
            }
        }

        let pushString = indentString.repeat(indentThisLine);
        if (lineTag) {
            pushString += `<${lineTag}>${lineContent}</${lineTag}>`;
        } else {
            pushString += lineContent;
        }
        outLines.push(pushString);
    }

    // after processing all lines...

    // if still in a list, close all levels
    while (levelIndents.length) closeLevel();

    // if still in a blockquote, close its tag
    if (inBlockquote) {
        inBlockquote = false;
        outLines.push('</blockquote>');
    }

    return outLines.join('\n');
}

function transformLyrics(text) {
    // Different from transformMultiline 'cuz it joins multiple lines together
    // with line 8reaks (<br>); transformMultiline treats each line as its own
    // complete paragraph (or list, etc).

    // If it looks like old data, then like, oh god.
    // Use the normal transformMultiline tool.
    if (text.includes('<br')) {
        return transformMultiline(text);
    }

    text = transformInline(text.trim());

    let buildLine = '';
    const addLine = () => outLines.push(`<p>${buildLine}</p>`);
    const outLines = [];
    for (const line of text.split('\n')) {
        if (line.length) {
            if (buildLine.length) {
                buildLine += '<br>';
            }
            buildLine += line;
        } else if (buildLine.length) {
            addLine();
            buildLine = '';
        }
    }
    if (buildLine.length) {
        addLine();
    }
    return outLines.join('\n');
}

function getCommentaryField(lines) {
    const text = getMultilineField(lines, 'Commentary');
    if (text) {
        const lines = text.split('\n');
        if (!lines[0].replace(/<\/b>/g, '').includes(':</i>')) {
            return {error: `An entry is missing commentary citation: "${lines[0].slice(0, 40)}..."`};
        }
        return text;
    } else {
        return null;
    }
};

async function processAlbumDataFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        // This function can return "error o8jects," which are really just
        // ordinary o8jects with an error message attached. I'm not 8othering
        // with error codes here or anywhere in this function; while this would
        // normally 8e 8ad coding practice, it doesn't really matter here,
        // 8ecause this isn't an API getting consumed 8y other services (e.g.
        // translaction functions). If we return an error, the caller will just
        // print the attached message in the output summary.
        return {error: `Could not read ${file} (${error.code}).`};
    }

    // We're pro8a8ly supposed to, like, search for a header somewhere in the
    // al8um contents, to make sure it's trying to 8e the intended structure
    // and is a valid utf-8 (or at least ASCII) file. 8ut like, whatever.
    // We'll just return more specific errors if it's missing necessary data
    // fields.

    const contentLines = contents.split('\n');

    // In this line of code I defeat the purpose of using a generator in the
    // first place. Sorry!!!!!!!!
    const sections = Array.from(getSections(contentLines));

    const albumSection = sections[0];
    const album = {};

    album.name = getBasicField(albumSection, 'Album');
    album.artists = getContributionField(albumSection, 'Artists') || getContributionField(albumSection, 'Artist');
    album.wallpaperArtists = getContributionField(albumSection, 'Wallpaper Art');
    album.wallpaperStyle = getMultilineField(albumSection, 'Wallpaper Style');
    album.date = getBasicField(albumSection, 'Date');
    album.trackArtDate = getBasicField(albumSection, 'Track Art Date') || album.date;
    album.coverArtDate = getBasicField(albumSection, 'Cover Art Date') || album.date;
    album.coverArtists = getContributionField(albumSection, 'Cover Art');
    album.hasTrackArt = getBooleanField(albumSection, 'Has Track Art') ?? true;
    album.trackCoverArtists = getContributionField(albumSection, 'Track Art');
    album.artTags = getListField(albumSection, 'Art Tags') || [];
    album.commentary = getCommentaryField(albumSection);
    album.urls = getListField(albumSection, 'URLs') || [];
    album.groups = getListField(albumSection, 'Groups') || [];
    album.directory = getBasicField(albumSection, 'Directory');
    album.isMajorRelease = getBooleanField(albumSection, 'Major Release') ?? false;

    if (album.artists && album.artists.error) {
        return {error: `${album.artists.error} (in ${album.name})`};
    }

    if (album.coverArtists && album.coverArtists.error) {
        return {error: `${album.coverArtists.error} (in ${album.name})`};
    }

    if (album.commentary && album.commentary.error) {
        return {error: `${album.commentary.error} (in ${album.name})`};
    }

    if (album.trackCoverArtists && album.trackCoverArtists.error) {
        return {error: `${album.trackCoverArtists.error} (in ${album.name})`};
    }

    if (!album.coverArtists) {
        return {error: `The album "${album.name}" is missing the "Cover Art" field.`};
    }

    album.color = (
        getBasicField(albumSection, 'Color') ||
        getBasicField(albumSection, 'FG')
    );

    if (!album.name) {
        return {error: 'Expected "Album" (name) field!'};
    }

    if (!album.date) {
        return {error: 'Expected "Date" field!'};
    }

    if (isNaN(Date.parse(album.date))) {
        return {error: `Invalid Date field: "${album.date}"`};
    }

    album.date = new Date(album.date);
    album.trackArtDate = new Date(album.trackArtDate);
    album.coverArtDate = new Date(album.coverArtDate);

    if (isNaN(Date.parse(album.trackArtDate))) {
        return {error: `Invalid Track Art Date field: "${album.trackArtDate}"`};
    }

    if (isNaN(Date.parse(album.coverArtDate))) {
        return {error: `Invalid Cover Art Date field: "${album.coverArtDate}"`};
    }

    if (!album.directory) {
        album.directory = C.getKebabCase(album.name);
    }

    album.tracks = [];

    // will be overwritten if a group section is found!
    album.usesGroups = false;

    let group = '';
    let groupColor = album.color;

    for (const section of sections.slice(1)) {
        // Just skip empty sections. Sometimes I paste a 8unch of dividers,
        // and this lets the empty sections doing that creates (temporarily)
        // exist without raising an error.
        if (!section.filter(Boolean).length) {
            continue;
        }

        const groupName = getBasicField(section, 'Group');
        if (groupName) {
            group = groupName;
            groupColor = (
                getBasicField(section, 'Color') ||
                getBasicField(section, 'FG') ||
                album.color
            );
            album.usesGroups = true;
            continue;
        }

        const track = {};

        track.name = getBasicField(section, 'Track');
        track.commentary = getCommentaryField(section);
        track.lyrics = getMultilineField(section, 'Lyrics');
        track.originalDate = getBasicField(section, 'Original Date');
        track.coverArtDate = getBasicField(section, 'Cover Art Date') || track.originalDate || album.trackArtDate;
        track.references = getListField(section, 'References') || [];
        track.artists = getContributionField(section, 'Artists') || getContributionField(section, 'Artist');
        track.coverArtists = getContributionField(section, 'Track Art');
        track.artTags = getListField(section, 'Art Tags') || [];
        track.contributors = getContributionField(section, 'Contributors') || [];
        track.directory = getBasicField(section, 'Directory');
        track.aka = getBasicField(section, 'AKA');

        if (!track.name) {
            return {error: `A track section is missing the "Track" (name) field (in ${album.name}, previous: ${album.tracks[album.tracks.length - 1]?.name}).`};
        }

        let durationString = getBasicField(section, 'Duration') || '0:00';
        track.duration = getDurationInSeconds(durationString);

        if (track.contributors.error) {
            return {error: `${track.contributors.error} (in ${track.name}, ${album.name})`};
        }

        if (track.commentary && track.commentary.error) {
            return {error: `${track.commentary.error} (in ${track.name}, ${album.name})`};
        }

        if (!track.artists) {
            // If an al8um has an artist specified (usually 8ecause it's a solo
            // al8um), let tracks inherit that artist. We won't display the
            // "8y <artist>" string on the al8um listing.
            if (album.artists) {
                track.artists = album.artists;
            } else {
                return {error: `The track "${track.name}" is missing the "Artist" field (in ${album.name}).`};
            }
        }

        if (!track.coverArtists) {
            if (getBasicField(section, 'Track Art') !== 'none' && album.hasTrackArt) {
                if (album.trackCoverArtists) {
                    track.coverArtists = album.trackCoverArtists;
                } else {
                    return {error: `The track "${track.name}" is missing the "Track Art" field (in ${album.name}).`};
                }
            }
        }

        if (track.coverArtists && track.coverArtists.length && track.coverArtists[0] === 'none') {
            track.coverArtists = null;
        }

        if (!track.directory) {
            track.directory = C.getKebabCase(track.name);
        }

        if (track.originalDate) {
            if (isNaN(Date.parse(track.originalDate))) {
                return {error: `The track "${track.name}"'s has an invalid "Original Date" field: "${track.originalDate}"`};
            }
            track.date = new Date(track.originalDate);
        } else {
            track.date = album.date;
        }

        track.coverArtDate = new Date(track.coverArtDate);

        const hasURLs = getBooleanField(section, 'Has URLs') ?? true;

        track.urls = hasURLs && (getListField(section, 'URLs') || []).filter(Boolean);

        if (hasURLs && !track.urls.length) {
            return {error: `The track "${track.name}" should have at least one URL specified.`};
        }

        // 8ack-reference the al8um o8ject! This is very useful for when
        // we're outputting the track pages.
        track.album = album;

        track.group = group;

        if (group) {
            track.color = groupColor;
        } else {
            track.color = album.color;
        }

        album.tracks.push(track);
    }

    return album;
}

async function processArtistDataFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        return {error: `Could not read ${file} (${error.code}).`};
    }

    const contentLines = contents.split('\n');
    const sections = Array.from(getSections(contentLines));

    return sections.filter(s => s.filter(Boolean).length).map(section => {
        const name = getBasicField(section, 'Artist');
        const urls = (getListField(section, 'URLs') || []).filter(Boolean);
        const alias = getBasicField(section, 'Alias');
        const note = getMultilineField(section, 'Note');
        let directory = getBasicField(section, 'Directory');

        if (!name) {
            return {error: 'Expected "Artist" (name) field!'};
        }

        if (!directory) {
            directory = C.getArtistDirectory(name);
        }

        if (alias) {
            return {name, directory, alias};
        } else {
            return {name, directory, urls, note};
        }
    });
}

async function processFlashDataFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        return {error: `Could not read ${file} (${error.code}).`};
    }

    const contentLines = contents.split('\n');
    const sections = Array.from(getSections(contentLines));

    let act, color;
    return sections.map(section => {
        if (getBasicField(section, 'ACT')) {
            act = getBasicField(section, 'ACT');
            color = (
                getBasicField(section, 'Color') ||
                getBasicField(section, 'FG')
            );
            const anchor = getBasicField(section, 'Anchor');
            const jump = getBasicField(section, 'Jump');
            const jumpColor = getBasicField(section, 'Jump Color') || color;
            return {act8r8k: true, act, color, anchor, jump, jumpColor};
        }

        const name = getBasicField(section, 'Flash');
        let page = getBasicField(section, 'Page');
        let directory = getBasicField(section, 'Directory');
        let date = getBasicField(section, 'Date');
        const jiff = getBasicField(section, 'Jiff');
        const tracks = getListField(section, 'Tracks') || [];
        const contributors = getContributionField(section, 'Contributors') || [];
        const urls = (getListField(section, 'URLs') || []).filter(Boolean);

        if (!name) {
            return {error: 'Expected "Flash" (name) field!'};
        }

        if (!page && !directory) {
            return {error: 'Expected "Page" or "Directory" field!'};
        }

        if (!directory) {
            directory = page;
        }

        if (!date) {
            return {error: 'Expected "Date" field!'};
        }

        if (isNaN(Date.parse(date))) {
            return {error: `Invalid Date field: "${date}"`};
        }

        date = new Date(date);

        return {name, page, directory, date, contributors, tracks, urls, act, color, jiff};
    });
}

async function processNewsDataFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        return {error: `Could not read ${file} (${error.code}).`};
    }

    const contentLines = contents.split('\n');
    const sections = Array.from(getSections(contentLines));

    return sections.map(section => {
        const name = getBasicField(section, 'Name');
        if (!name) {
            return {error: 'Expected "Name" field!'};
        }

        const directory = getBasicField(section, 'Directory') || getBasicField(section, 'ID');
        if (!directory) {
            return {error: 'Expected "Directory" field!'};
        }

        let body = getMultilineField(section, 'Body');
        if (!body) {
            return {error: 'Expected "Body" field!'};
        }

        let date = getBasicField(section, 'Date');
        if (!date) {
            return {error: 'Expected "Date" field!'};
        }

        if (isNaN(Date.parse(date))) {
            return {error: `Invalid date field: "${date}"`};
        }

        date = new Date(date);

        let bodyShort = body.split('<hr class="split">')[0];

        return {
            name,
            directory,
            body,
            bodyShort,
            date
        };
    });
}

async function processTagDataFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        if (error.code === 'ENOENT') {
            return [];
        } else {
            return {error: `Could not read ${file} (${error.code}).`};
        }
    }

    const contentLines = contents.split('\n');
    const sections = Array.from(getSections(contentLines));

    return sections.map(section => {
        let isCW = false;

        let name = getBasicField(section, 'Tag');
        if (!name) {
            name = getBasicField(section, 'CW');
            isCW = true;
            if (!name) {
                return {error: 'Expected "Tag" or "CW" field!'};
            }
        }

        let color;
        if (!isCW) {
            color = getBasicField(section, 'Color');
            if (!color) {
                return {error: 'Expected "Color" field!'};
            }
        }

        const directory = C.getKebabCase(name);

        return {
            name,
            directory,
            isCW,
            color
        };
    });
}

async function processGroupDataFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        if (error.code === 'ENOENT') {
            return [];
        } else {
            return {error: `Could not read ${file} (${error.code}).`};
        }
    }

    const contentLines = contents.split('\n');
    const sections = Array.from(getSections(contentLines));

    let category, color;
    return sections.map(section => {
        if (getBasicField(section, 'Category')) {
            category = getBasicField(section, 'Category');
            color = getBasicField(section, 'Color');
            return {isCategory: true, name: category, color};
        }

        const name = getBasicField(section, 'Group');
        if (!name) {
            return {error: 'Expected "Group" field!'};
        }

        let directory = getBasicField(section, 'Directory');
        if (!directory) {
            directory = C.getKebabCase(name);
        }

        let description = getMultilineField(section, 'Description');
        if (!description) {
            return {error: 'Expected "Description" field!'};
        }

        let descriptionShort = description.split('<hr class="split">')[0];

        const urls = (getListField(section, 'URLs') || []).filter(Boolean);

        return {
            isGroup: true,
            name,
            directory,
            description,
            descriptionShort,
            urls,
            category,
            color
        };
    });
}

async function processStaticPageDataFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        if (error.code === 'ENOENT') {
            return [];
        } else {
            return {error: `Could not read ${file} (${error.code}).`};
        }
    }

    const contentLines = contents.split('\n');
    const sections = Array.from(getSections(contentLines));

    return sections.map(section => {
        const name = getBasicField(section, 'Name');
        if (!name) {
            return {error: 'Expected "Name" field!'};
        }

        const shortName = getBasicField(section, 'Short Name') || name;

        let directory = getBasicField(section, 'Directory');
        if (!directory) {
            return {error: 'Expected "Directory" field!'};
        }

        let content = getMultilineField(section, 'Content');
        if (!content) {
            return {error: 'Expected "Content" field!'};
        }

        let stylesheet = getMultilineField(section, 'Style') || '';

        let listed = getBooleanField(section, 'Listed') ?? true;
        let treatAsHTML = getBooleanField(section, 'Treat as HTML') ?? false;

        return {
            name,
            shortName,
            directory,
            content,
            stylesheet,
            listed,
            treatAsHTML
        };
    });
}

async function processWikiInfoFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        return {error: `Could not read ${file} (${error.code}).`};
    }

    // Unlike other data files, the site info data file isn't 8roken up into
    // more than one entry. So we operate on the plain old contentLines array,
    // rather than dividing into sections like we usually do!
    const contentLines = contents.split('\n');

    const name = getBasicField(contentLines, 'Name');
    if (!name) {
        return {error: 'Expected "Name" field!'};
    }

    const shortName = getBasicField(contentLines, 'Short Name') || name;

    const color = getBasicField(contentLines, 'Color') || '#0088ff';

    // This is optional! Without it, <meta rel="canonical"> tags won't 8e
    // gener8ted.
    const canonicalBase = getBasicField(contentLines, 'Canonical Base');

    // Also optional! In charge of <meta rel="description">.
    const description = getBasicField(contentLines, 'Description');

    const footer = getMultilineField(contentLines, 'Footer') || '';

    // We've had a comment lying around for ages, just reading:
    // "Might ena8le this later... we'll see! Eventually. May8e."
    // We still haven't! 8ut hey, the option's here.
    const enableArtistAvatars = getBooleanField(contentLines, 'Enable Artist Avatars') ?? false;

    const enableFlashesAndGames = getBooleanField(contentLines, 'Enable Flashes & Games') ?? false;
    const enableListings = getBooleanField(contentLines, 'Enable Listings') ?? false;
    const enableNews = getBooleanField(contentLines, 'Enable News') ?? false;
    const enableArtTagUI = getBooleanField(contentLines, 'Enable Art Tag UI') ?? false;
    const enableGroupUI = getBooleanField(contentLines, 'Enable Group UI') ?? false;

    return {
        name,
        shortName,
        color,
        canonicalBase,
        description,
        footer,
        features: {
            artistAvatars: enableArtistAvatars,
            flashesAndGames: enableFlashesAndGames,
            listings: enableListings,
            news: enableNews,
            artTagUI: enableArtTagUI,
            groupUI: enableGroupUI
        }
    };
}

async function processHomepageInfoFile(file) {
    let contents;
    try {
        contents = await readFile(file, 'utf-8');
    } catch (error) {
        return {error: `Could not read ${file} (${error.code}).`};
    }

    const contentLines = contents.split('\n');
    const sections = Array.from(getSections(contentLines));

    const [ firstSection, ...rowSections ] = sections;

    const sidebar = getMultilineField(firstSection, 'Sidebar');

    const validRowTypes = ['albums'];

    const rows = rowSections.map(section => {
        const name = getBasicField(section, 'Row');
        if (!name) {
            return {error: 'Expected "Row" (name) field!'};
        }

        const color = getBasicField(section, 'Color');

        const type = getBasicField(section, 'Type');
        if (!type) {
            return {error: 'Expected "Type" field!'};
        }

        if (!validRowTypes.includes(type)) {
            return {error: `Expected "Type" field to be one of: ${validRowTypes.join(', ')}`};
        }

        const row = {name, color, type};

        switch (type) {
            case 'albums': {
                const group = getBasicField(section, 'Group') || null;
                const albums = getListField(section, 'Albums') || [];

                if (!group && !albums) {
                    return {error: 'Expected "Group" and/or "Albums" field!'};
                }

                let groupCount = getBasicField(section, 'Count');
                if ((group || newReleases) && !groupCount) {
                    return {error: 'Expected "Count" field!'};
                }

                if (groupCount) {
                    if (isNaN(parseInt(groupCount))) {
                        return {error: `Invalid Count field: "${groupCount}"`};
                    }

                    groupCount = parseInt(groupCount);
                }

                const actions = getListField(section, 'Actions') || [];
                if (actions.some(x => !x.startsWith('<a'))) {
                    return {error: 'Expected every action to be a <a>-type link!'};
                }

                return {...row, group, groupCount, albums, actions};
            }
        }
    });

    return {sidebar, rows};
}

function getDateString({ date }) {
    /*
    const pad = val => val.toString().padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    */
    const months = [
        'January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'
    ]
    date = new Date(date);
    return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
}

function getDurationString(secTotal) {
    if (secTotal === 0) {
        return '_:__'
    }

    let hour = Math.floor(secTotal / 3600)
    let min = Math.floor((secTotal - hour * 3600) / 60)
    let sec = Math.floor(secTotal - hour * 3600 - min * 60)

    const pad = val => val.toString().padStart(2, '0')

    if (hour > 0) {
        return `${hour}:${pad(min)}:${pad(sec)}`
    } else {
        return `${min}:${pad(sec)}`
    }
}

function getDurationInSeconds(string) {
    const parts = string.split(':').map(n => parseInt(n))
    if (parts.length === 3) {
        return parts[0] * 3600 + parts[1] * 60 + parts[2]
    } else if (parts.length === 2) {
        return parts[0] * 60 + parts[1]
    } else {
        return 0
    }
}

function getTotalDuration(tracks) {
    return tracks.reduce((duration, track) => duration + track.duration, 0);
}

const stringifyIndent = 0;

const toRefs = (label, objectOrArray) => {
    if (Array.isArray(objectOrArray)) {
        return objectOrArray.filter(Boolean).map(x => `${label}:${x.directory}`);
    } else if (objectOrArray.directory) {
        throw new Error('toRefs should not be passed a single object with directory');
    } else if (typeof objectOrArray === 'object') {
        return Object.fromEntries(Object.entries(objectOrArray)
            .map(([ key, value ]) => [key, toRefs(key, value)]));
    } else {
        throw new Error('toRefs should be passed an array or object of arrays');
    }
};

function stringifyRefs(key, value) {
    switch (key) {
        case 'tracks':
        case 'references':
        case 'referencedBy':
            return toRefs('track', value);
        case 'artists':
        case 'contributors':
        case 'coverArtists':
        case 'trackCoverArtists':
            return value && value.map(({ who, what }) => ({who: `artist:${who.directory}`, what}));
        case 'albums': return toRefs('album', value);
        case 'flashes': return toRefs('flash', value);
        case 'groups': return toRefs('group', value);
        case 'artTags': return toRefs('tag', value);
        case 'aka': return value && `track:${value.directory}`;
        default:
            return value;
    }
}

function stringifyAlbumData() {
    return JSON.stringify(albumData, (key, value) => {
        switch (key) {
            case 'commentary':
                return '';
            default:
                return stringifyRefs(key, value);
        }
    }, stringifyIndent);
}

function stringifyTrackData() {
    return JSON.stringify(trackData, (key, value) => {
        switch (key) {
            case 'album':
            case 'commentary':
            case 'otherReleases':
                return undefined;
            default:
                return stringifyRefs(key, value);
        }
    }, stringifyIndent);
}

function stringifyFlashData() {
    return JSON.stringify(flashData, (key, value) => {
        switch (key) {
            case 'act':
            case 'commentary':
                return undefined;
            default:
                return stringifyRefs(key, value);
        }
    }, stringifyIndent);
}

function stringifyArtistData() {
    return JSON.stringify(artistData, (key, value) => {
        switch (key) {
            case 'asAny':
                return;
            case 'asArtist':
            case 'asContributor':
            case 'asCoverArtist':
                return toRefs('track', value);
            default:
                return stringifyRefs(key, value);
        }
    }, stringifyIndent);
}

function escapeAttributeValue(value) {
    return value.toString().replace(/"/g, '&quot;');
}

function attributes(attribs) {
    return Object.entries(attribs)
        .filter(([ key, val ]) => val !== '')
        .map(([ key, val ]) => `${key}="${escapeAttributeValue(val)}"`)
        .join(' ');
}

function img({
    src = '',
    alt = '',
    reveal = '',
    id = '',
    width = '',
    height = '',
    link = false,
    lazy = false,
    square = false
}) {
    const willSquare = square;
    const willLink = typeof link === 'string' || link;

    const imgAttributes = attributes({
        id: link ? '' : id,
        alt,
        width,
        height
    });

    const nonlazyHTML = wrap(`<img src="${src}" ${imgAttributes}>`);
    const lazyHTML = lazy && wrap(`<img class="lazy" data-original="${src}" ${imgAttributes}>`, true);

    if (lazy) {
        return fixWS`
            <noscript>${nonlazyHTML}</noscript>
            ${lazyHTML}
        `;
    } else {
        return nonlazyHTML;
    }

    function wrap(html, hide = false) {
        html = fixWS`
            <div class="image-inner-area">${html}</div>
        `;

        html = fixWS`
            <div class="image-container">${html}</div>
        `;

        if (reveal) {
            html = fixWS`
                <div class="reveal">
                    ${html}
                    <span class="reveal-text">${reveal}</span>
                </div>
            `;
        }

        if (willSquare) {
            html = fixWS`<div ${classes('square', hide && !willLink && 'js-hide')}><div class="square-content">${html}</div></div>`;
        }

        if (willLink) {
            html = `<a ${classes('box', hide && 'js-hide')} ${attributes({
                id,
                href: typeof link === 'string' ? link : src
            })}>${html}</a>`;
        }

        return html;
    }
}

async function writePage(directoryParts, {
    title = '',
    meta = {},
    theme = '',
    stylesheet = '',

    // missing properties are auto-filled, see below!
    body = {},
    main = {},
    sidebarLeft = {},
    sidebarRight = {},
    nav = {},
    footer = {}
}) {
    body.style ??= '';

    theme = theme ?? getThemeString(wikiInfo);

    main.classes ??= [];
    main.content ??= '';

    sidebarLeft ??= {};
    sidebarRight ??= {};

    for (const sidebar of [sidebarLeft, sidebarRight]) {
        sidebar.classes ??= [];
        sidebar.content ??= '';
        sidebar.collapse ??= true;
    }

    nav.classes ??= [];
    nav.content ??= '';
    nav.links ??= [];

    footer.classes ??= [];
    footer.content ??= (wikiInfo.footer ? transformMultiline(wikiInfo.footer) : '');

    const directory = path.join(outputPath, ...directoryParts);
    const file = path.join(directory, 'index.html');
    const href = path.join(...directoryParts, 'index.html');

    let targetPath = directoryParts.join('/');
    if (directoryParts.length) {
        targetPath += '/';
    }

    let canonical = '';
    if (wikiInfo.canonicalBase) {
        canonical = wikiInfo.canonicalBase + targetPath;
    }

    const collapseSidebars = (sidebarLeft.collapse !== false) && (sidebarRight.collapse !== false);

    const mainHTML = main.content && fixWS`
        <main id="content" ${classes(...main.classes || [])}>
            ${main.content}
        </main>
    `;

    const footerHTML = footer.content && fixWS`
        <footer id="footer" ${classes(...footer.classes || [])}>
            ${footer.content}
        </footer>
    `;

    const generateSidebarHTML = (id, {
        content,
        multiple,
        classes: sidebarClasses = [],
        collapse = true,
        wide = false
    }) => (content ? fixWS`
        <div id="${id}" ${classes(
            'sidebar-column',
            'sidebar',
            wide && 'wide',
            !collapse && 'no-hide',
            ...sidebarClasses
        )}>
            ${content}
        </div>
    ` : multiple ? fixWS`
        <div id="${id}" ${classes(
            'sidebar-column',
            'sidebar-multiple',
            wide && 'wide',
            !collapse && 'no-hide'
        )}>
            ${multiple.map(content => fixWS`
                <div ${classes(
                    'sidebar',
                    ...sidebarClasses
                )}>
                    ${content}
                </div>
            `).join('\n')}
        </div>
    ` : '');

    const sidebarLeftHTML = generateSidebarHTML('sidebar-left', sidebarLeft);
    const sidebarRightHTML = generateSidebarHTML('sidebar-right', sidebarRight);

    if (nav.simple) {
        nav.links = [
            ['./', wikiInfo.shortName],
            [href, title]
        ]
    }

    const links = (nav.links || []).filter(Boolean);

    const navLinkParts = [];
    for (let i = 0; i < links.length; i++) {
        const link = links[i];
        const prev = links[i - 1];
        const next = links[i + 1];
        const [ href, title ] = link;
        let part = '';
        if (href) {
            if (prev && prev[0]) {
                part = '/ ';
            }
            part += `<a href="${href}">${title}</a>`;
        } else {
            if (next && prev) {
                part = '/ ';
            }
            part += `<span>${title}</span>`;
        }
        navLinkParts.push(part);
    }

    const navContentHTML = [
        nav.links.length && fixWS`
            <h2 class="highlight-last-link">
                ${navLinkParts.join('\n')}
            </h2>
        `,
        nav.content
    ].filter(Boolean).join('\n');

    const navHTML = navContentHTML && fixWS`
        <nav id="header" ${classes(...nav.classes || [])}>
            ${navContentHTML}
        </nav>
    `;

    const layoutHTML = [
        navHTML,
        (sidebarLeftHTML || sidebarRightHTML) ? fixWS`
            <div ${classes('layout-columns', !collapseSidebars && 'vertical-when-thin')}>
                ${sidebarLeftHTML}
                ${mainHTML}
                ${sidebarRightHTML}
            </div>
        ` : mainHTML,
        footerHTML
    ].filter(Boolean).join('\n');

    await mkdirp(directory);
    await writeFile(file, filterEmptyLines(rebaseURLs(directory, fixWS`
        <!DOCTYPE html>
        <html data-rebase="${path.relative(directory, outputPath)}">
            <head>
                <title>${title}</title>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                ${Object.entries(meta).filter(([ key, value ]) => value).map(([ key, value ]) => `<meta ${key}="${escapeAttributeValue(value)}">`).join('\n')}
                ${canonical && `<link rel="canonical" href="${canonical}">`}
                <link rel="stylesheet" href="${C.STATIC_DIRECTORY}/site.css?${CACHEBUST}">
                ${(theme || stylesheet) && fixWS`
                    <style>
                        ${theme}
                        ${stylesheet}
                    </style>
                `}
                <script src="${C.STATIC_DIRECTORY}/lazy-loading.js?${CACHEBUST}"></script>
            </head>
            <body ${attributes({style: body.style || ''})}>
                <div id="page-container">
                    ${mainHTML && fixWS`
                        <div id="skippers">
                            <span class="skipper"><a href="#content">Skip to content</a></span>
                            ${sidebarLeftHTML && `<span class="skipper"><a href="#sidebar-left">Skip to sidebar ${sidebarRightHTML && '(left)'}</a></span>`}
                            ${sidebarRightHTML && `<span class="skipper"><a href="#sidebar-right">Skip to sidebar ${sidebarLeftHTML && '(right)'}</a></span>`}
                            ${footerHTML && `<span class="skipper"><a href="#footer">Skip to footer</a></span>`}
                        </div>
                    `}
                    ${layoutHTML}
                </div>
                <script src="${C.COMMON_DIRECTORY}/common.js?${CACHEBUST}"></script>
                <script src="${C.STATIC_DIRECTORY}/client.js?${CACHEBUST}"></script>
            </body>
        </html>
    `)));
}

function getGridHTML({
    entries,
    srcFn,
    hrefFn,
    altFn = () => '',
    details = false,
    lazy = true
}) {
    return entries.map(({ large, item }, i) => fixWS`
        <a ${classes('grid-item', 'box', large && 'large-grid-item')} href="${hrefFn(item)}" style="${getLinkThemeString(item)}">
            ${img({
                src: srcFn(item),
                alt: altFn(item),
                lazy: (typeof lazy === 'number' ? i >= lazy : lazy),
                square: true,
                reveal: getRevealString(item.artTags)
            })}
            <span>${item.name}</span>
            ${details && fixWS`
                <span>(${s(item.tracks.length, 'track')}, ${getDurationString(getTotalDuration(item.tracks))})</span>
            `}
        </a>
    `).join('\n');
}

function getAlbumGridHTML(props) {
    return getGridHTML({
        srcFn: getAlbumCover,
        hrefFn: album => `${C.ALBUM_DIRECTORY}/${album.directory}/`,
        ...props
    });
}

function getAlbumGridHTML(props) {
    return getGridHTML({
        srcFn: getAlbumCover,
        hrefFn: album => `${C.ALBUM_DIRECTORY}/${album.directory}/`,
        ...props
    });
}

function getFlashGridHTML(props) {
    return getGridHTML({
        srcFn: getFlashCover,
        hrefFn: flash => `${C.FLASH_DIRECTORY}/${flash.directory}/`,
        altFn: () => 'flash art',
        ...props
    });
}

function getNewReleases(numReleases) {
    const latestFirst = albumData.slice().reverse();
    const majorReleases = latestFirst.filter(album => album.isMajorRelease);
    majorReleases.splice(1);

    const otherReleases = latestFirst
        .filter(album => !majorReleases.includes(album))
        .slice(0, numReleases - majorReleases.length);

    return [
        ...majorReleases.map(album => ({large: true, item: album})),
        ...otherReleases.map(album => ({large: false, item: album}))
    ];
}

function writeSymlinks() {
    return progressPromiseAll('Building site symlinks.', [
        link(path.join(__dirname, C.COMMON_DIRECTORY), C.COMMON_DIRECTORY),
        link(path.join(__dirname, C.STATIC_DIRECTORY), C.STATIC_DIRECTORY),
        link(mediaPath, C.MEDIA_DIRECTORY)
    ]);

    async function link(directory, target) {
        const file = path.join(outputPath, target);
        try {
            await unlink(file);
        } catch (error) {
            if (error.code !== 'ENOENT') {
                throw error;
            }
        }
        await symlink(path.resolve(directory), file);
    }
}

async function writeHomepage() {
    await writePage([], {
        title: wikiInfo.name,

        meta: {
            description: wikiInfo.description
        },

        main: {
            classes: ['top-index'],
            content: fixWS`
                <h1>${wikiInfo.name}</h1>
                ${homepageInfo.rows.map((row, i) => fixWS`
                    <section class="row" style="${getLinkThemeString(row)}">
                        <h2>${row.name}</h2>
                        ${row.type === 'albums' && fixWS`
                            <div class="grid-listing">
                                ${getAlbumGridHTML({
                                    entries: (
                                        row.group === 'new-releases' ? getNewReleases(row.groupCount) :
                                        ((getLinkedGroup(row.group)?.albums || [])
                                            .slice()
                                            .reverse()
                                            .slice(0, row.groupCount)
                                            .map(album => ({item: album})))
                                    ).concat(row.albums
                                        .map(getLinkedAlbum)
                                        .map(album => ({item: album}))
                                    ),
                                    lazy: i > 0
                                })}
                                ${row.actions.length && fixWS`
                                    <div class="grid-actions">
                                        ${row.actions.map(action => action
                                            .replace('<a', '<a class="box grid-item"')).join('\n')}
                                    </div>
                                `}
                            </div>
                        `}
                    </section>
                `).join('\n')}
            `
        },

        sidebarLeft: homepageInfo.sidebar && {
            wide: true,
            collapse: false,
            // This is a pretty filthy hack! 8ut otherwise, the [[news]] part
            // gets treated like it's a reference to the track named "news",
            // which o8viously isn't what we're going for. Gotta catch that
            // 8efore we pass it to transformMultiline, 'cuz otherwise it'll
            // get repl8ced with just the word "news" (or anything else that
            // transformMultiline does with references it can't match) -- and
            // we can't match that for replacing it with the news column!
            //
            // And no, I will not make [[news]] into part of transformMultiline
            // (even though that would 8e hilarious).
            content: transformMultiline(homepageInfo.sidebar.replace('[[news]]', '__GENERATE_NEWS__')).replace('<p>__GENERATE_NEWS__</p>', wikiInfo.features.news ? fixWS`
                <h1>News</h1>
                ${newsData.slice(0, 3).map((entry, i) => fixWS`
                    <article ${classes('news-entry', i === 0 && 'first-news-entry')}>
                        <h2><time>${getDateString(entry)}</time> <a href="${C.NEWS_DIRECTORY}/${entry.directory}/">${entry.name}</a></h2>
                        ${transformMultiline(entry.bodyShort)}
                        ${entry.bodyShort !== entry.body && `<a href="${C.NEWS_DIRECTORY}/${entry.directory}/">(View rest of entry!)</a>`}
                    </article>
                `).join('\n')}
            ` : `<p><i>News requested in content description but this feature isn't enabled</i></p>`)
        },

        nav: {
            content: fixWS`
                <h2 class="dot-between-spans">
                    <span><a class="current" href="./">${wikiInfo.shortName}</a></span>
                    ${wikiInfo.features.listings && fixWS`
                        <span><a href="${C.LISTING_DIRECTORY}/">Listings</a></span>
                    `}
                    ${wikiInfo.features.news && fixWS`
                        <span><a href="${C.NEWS_DIRECTORY}/">News</a></span>
                    `}
                    ${wikiInfo.features.flashesAndGames && fixWS`
                        <span><a href="${C.FLASH_DIRECTORY}/">Flashes &amp; Games</a></span>
                    `}
                    ${staticPageData.filter(page => page.listed).map(page => fixWS`
                        <span><a href="${page.directory}/">${page.shortName}</a></span>
                    `).join('\n')}
                </h2>
            `
        }
    });
}

function writeNewsPages() {
    if (!wikiInfo.features.news) {
        return;
    }

    return progressPromiseAll('Writing news pages.', queue([
        writeNewsIndex,
        ...newsData.map(curry(writeNewsPage))
    ], queueSize));
}

async function writeNewsIndex() {
    await writePage([C.NEWS_DIRECTORY], {
        title: 'News',
        main: {
            content: fixWS`
                <div class="long-content news-index">
                    <h1>News</h1>
                    ${newsData.map(entry => fixWS`
                        <article id="${entry.directory}">
                            <h2><time>${getDateString(entry)}</time> <a href="${C.NEWS_DIRECTORY}/${entry.directory}/">${entry.name}</a></h2>
                            ${transformMultiline(entry.bodyShort)}
                            ${entry.bodyShort !== entry.body && `<p><a href="${C.NEWS_DIRECTORY}/${entry.directory}/">(View rest of entry!)</a></p>`}
                        </article>
                    `).join('\n')}
                </div>
            `
        },
        nav: {
            links: [
                ['./', wikiInfo.shortName],
                [`${C.NEWS_DIRECTORY}/`, 'News']
            ]
        }
    });
}

async function writeNewsPage(entry) {
    // The newsData list is sorted reverse chronologically (newest ones first),
    // so the way we find next/previous entries is flipped from normal.
    const index = newsData.indexOf(entry)
    const previous = newsData[index + 1];
    const next = newsData[index - 1];
    const nextPreviousLinks = [
        previous && `<a href="${C.NEWS_DIRECTORY}/${previous.directory}/" id="previous-button" title="${previous.name}">Previous</a>`,
        next && `<a href="${C.NEWS_DIRECTORY}/${next.directory}/" id="next-button" title="${next.name}">Next</a>`
    ].filter(Boolean).join(', ');

    await writePage([C.NEWS_DIRECTORY, entry.directory], {
        title: `News - ${entry.name}`,
        main: {
            content: fixWS`
                <div class="long-content">
                    <h1>${entry.name}</h1>
                    <p>(Published ${getDateString(entry)}.)</p>
                    ${transformMultiline(entry.body)}
                </div>
            `
        },
        nav: {
            links: [
                ['./', wikiInfo.shortName],
                [`${C.NEWS_DIRECTORY}/`, 'News'],
                [null, getDateString(entry) + ':'],
                [`${C.NEWS_DIRECTORY}/${entry.directory}/`, entry.name],
                nextPreviousLinks && [null, `(${nextPreviousLinks})`]
            ]
        }
    });
}

function writeMiscellaneousPages() {
    return progressPromiseAll('Writing miscellaneous pages.', [
        writeHomepage(),

        groupData?.some(group => group.directory === 'fandom') &&
        mkdirp(path.join(outputPath, 'albums', 'fandom'))
            .then(() => writeFile(path.join(outputPath, 'albums', 'fandom', 'index.html'),
                generateRedirectPage('Fandom - Gallery', `/${C.GROUP_DIRECTORY}/fandom/gallery/`))),

        groupData?.some(group => group.directory === 'official') &&
        mkdirp(path.join(outputPath, 'albums', 'official'))
            .then(() => writeFile(path.join(outputPath, 'albums', 'official', 'index.html'),
                generateRedirectPage('Official - Gallery', `/${C.GROUP_DIRECTORY}/official/gallery/`))),

        wikiInfo.features.flashesAndGames &&
        writePage([C.FLASH_DIRECTORY], {
            title: `Flashes & Games`,
            main: {
                classes: ['flash-index'],
                content: fixWS`
                    <h1>Flashes &amp; Games</h1>
                    <div class="long-content">
                        <p class="quick-info">Jump to:</p>
                        <ul class="quick-info">
                            ${flashData.filter(act => act.act8r8k && act.jump).map(({ anchor, jump, jumpColor }) => fixWS`
                                <li><a href="#${anchor}" style="${getLinkThemeString({color: jumpColor})}">${jump}</a></li>
                            `).join('\n')}
                        </ul>
                    </div>
                    ${flashData.filter(flash => flash.act8r8k).map((act, i) => fixWS`
                        <h2 id="${act.anchor}" style="${getLinkThemeString(act)}"><a href="${C.FLASH_DIRECTORY}/${getFlashDirectory(flashData.find(f => !f.act8r8k && f.act === act.act))}/">${act.act}</a></h2>
                        <div class="grid-listing">
                            ${getFlashGridHTML({
                                entries: (flashData
                                    .filter(flash => !flash.act8r8k && flash.act === act.act)
                                    .map(flash => ({item: flash}))),
                                lazy: i === 0 ? 4 : true
                            })}
                        </div>
                    `).join('\n')}
                `
            },

            /*
            sidebarLeft: {
                content: generateSidebarForFlashes(null)
            },
            */

            nav: {simple: true}
        }),

        writeFile(path.join(outputPath, 'data.json'), fixWS`
            {
                "albumData": ${stringifyAlbumData()},
                ${wikiInfo.features.flashesAndGames && `"flashData": ${stringifyFlashData()},`}
                "artistData": ${stringifyArtistData()}
            }
        `)
    ].filter(Boolean));
}

function writeStaticPages() {
    return progressPromiseAll(`Writing static pages.`, queue(staticPageData.map(curry(writeStaticPage)), queueSize));
}

async function writeStaticPage(staticPage) {
    await writePage([staticPage.directory], {
        title: staticPage.name,
        stylesheet: staticPage.stylesheet,
        main: {
            content: fixWS`
                <div class="long-content">
                    <h1>${staticPage.name}</h1>
                    ${transformMultiline(staticPage.content, staticPage.treatAsHTML)}
                </div>
            `
        },
        nav: {simple: true}
    });
}

function getRevealString(tags = []) {
    return tags.some(tag => tag.isCW) && (
        'cw: ' + tags.filter(tag => tag.isCW).map(tag => `<span class="reveal-tag">${tag.name}</span>`).join(', ')) + '<br><span class="reveal-interaction">click to show</span>'
}

function generateCoverLink({
    src,
    alt,
    tags = []
}) {
    return fixWS`
        <div id="cover-art-container">
            ${img({
                src,
                alt,
                id: 'cover-art',
                link: true,
                square: true,
                reveal: getRevealString(tags)
            })}
            ${wikiInfo.features.artTagUI && tags.filter(tag => !tag.isCW).length && `<p class="tags">Tags:
                ${tags.filter(tag => !tag.isCW).map(tag => fixWS`
                    <a href="${C.TAG_DIRECTORY}/${tag.directory}/" style="${getLinkThemeString(tag)}">${tag.name}</a>
                `).join(',\n')}
            </p>`}
        </div>
    `;
}

// This function title is my gr8test work of art.
// (The 8ehavior... well, um. Don't tell anyone, 8ut it's even 8etter.)
/* // RIP, 2k20-2k20.
function writeIndexAndTrackPagesForAlbum(album) {
    return [
        () => writeAlbumPage(album),
        ...album.tracks.map(track => () => writeTrackPage(track))
    ];
}
*/

function writeAlbumPages() {
    return progressPromiseAll(`Writing album pages.`, queue(albumData.map(curry(writeAlbumPage)), queueSize));
}

async function writeAlbumPage(album) {
    const trackToListItem = track => fixWS`
        <li style="${getLinkThemeString(track)}">
            (${getDurationString(track.duration)})
            <a href="${C.TRACK_DIRECTORY}/${track.directory}/">${track.name}</a>
            ${track.artists !== album.artists && fixWS`
                <span class="by">by ${getArtistString(track.artists)}</span>
            `}
        </li>
    `;
    const listTag = getAlbumListTag(album);
    await writePage([C.ALBUM_DIRECTORY, album.directory], {
        title: album.name,
        stylesheet: getAlbumStylesheet(album),
        theme: getThemeString(album, [
            `--album-directory: ${album.directory}`
        ]),
        main: {
            content: fixWS`
                ${generateCoverLink({
                    src: getAlbumCover(album),
                    alt: 'album cover',
                    tags: album.artTags
                })}
                <h1>${album.name}</h1>
                <p>
                    ${album.artists && `By ${getArtistString(album.artists, true)}.<br>`}
                    ${album.coverArtists &&  `Cover art by ${getArtistString(album.coverArtists, true)}.<br>`}
                    ${album.wallpaperArtists && `Wallpaper art by ${getArtistString(album.wallpaperArtists, true)}.<br>`}
                    Released ${getDateString(album)}.
                    ${+album.coverArtDate !== +album.date && `<br>Art released ${getDateString({date: album.coverArtDate})}.`}
                    <br>Duration: ~${getDurationString(getTotalDuration(album.tracks))}.
                </p>
                ${album.urls.length && `<p>Listen on ${joinNoOxford(album.urls.map(url => fancifyURL(url, {album: true})), 'or')}.</p>`}
                ${album.usesGroups ? fixWS`
                    <dl class="album-group-list">
                        ${album.tracks.flatMap((track, i, arr) => [
                            (i > 0 && track.group !== arr[i - 1].group) && `</${listTag}></dd>`,
                            (i === 0 || track.group !== arr[i - 1].group) && fixWS`
                                ${track.group && `<dt>${track.group} (~${getDurationString(getTotalDuration(album.tracks.filter(({ group }) => group === track.group)))}):</dt>`}
                                <dd><${listTag === 'ol' ? `ol start="${i + 1}"` : listTag}>
                            `,
                            trackToListItem(track),
                            i === arr.length && `</${listTag}></dd>`
                        ].filter(Boolean)).join('\n')}
                    </dl>
                ` : fixWS`
                    <${listTag}>
                        ${album.tracks.map(trackToListItem).join('\n')}
                    </${listTag}>
                `}
                ${album.commentary && fixWS`
                    <p>Artist commentary:</p>
                    <blockquote>
                        ${transformMultiline(album.commentary)}
                    </blockquote>
                `}
            `
        },
        sidebarLeft: generateSidebarForAlbum(album),
        sidebarRight: generateSidebarRightForAlbum(album),
        nav: {
            links: [
                ['./', wikiInfo.shortName],
                [`${C.ALBUM_DIRECTORY}/${album.directory}/`, album.name],
                [null, generateAlbumNavLinks(album)]
            ],
            content: fixWS`
                <div>
                    ${generateAlbumChronologyLinks(album)}
                </div>
            `
        }
    });
}

function getAlbumStylesheet(album) {
    if (album.wallpaperArtists) {
        return fixWS`
            body::before {
                background-image: url("${C.MEDIA_DIRECTORY}/${C.MEDIA_ALBUM_ART_DIRECTORY}/${album.directory}/bg.jpg");
                ${album.wallpaperStyle}
            }
        `;
    } else {
        return '';
    }
}

function writeTrackPages() {
    return progressPromiseAll(`Writing track pages.`, queue(trackData.map(curry(writeTrackPage)), queueSize));
}

async function writeTrackPage(track) {
    const { album } = track;
    const tracksThatReference = track.referencedBy;
    const ttrFanon = tracksThatReference.filter(t => t.album.groups.every(group => group.directory !== C.OFFICIAL_GROUP_DIRECTORY));
    const ttrOfficial = tracksThatReference.filter(t => t.album.groups.some(group => group.directory === C.OFFICIAL_GROUP_DIRECTORY));
    const tracksReferenced = track.references;
    const otherReleases = track.otherReleases;
    const listTag = getAlbumListTag(track.album);

    let flashesThatFeature;
    if (wikiInfo.features.flashesAndGames) {
        flashesThatFeature = C.sortByDate([track, ...otherReleases]
            .flatMap(track => track.flashes.map(flash => ({flash, as: track}))));
    }

    const generateTrackList = tracks => fixWS`
        <ul>
            ${tracks.map(track => fixWS`
                <li ${classes(track.aka && 'rerelease')}>
                    <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                    <span class="by">by ${getArtistString(track.artists)}</span>
                    ${track.aka && `<span class="rerelease-label">(re-release)</span>`}
                </li>
            `).join('\n')}
        </ul>
    `;

    const commentary = [
        track.commentary,
        ...otherReleases.map(track =>
            (track.commentary?.split('\n')
                .filter(line => line.replace(/<\/b>/g, '').includes(':</i>'))
                .flatMap(line => [line, `<i>See <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>!</i>`])
                .join('\n')))
    ].filter(Boolean).join('\n');

    await writePage([C.TRACK_DIRECTORY, track.directory], {
        title: track.name,
        stylesheet: getAlbumStylesheet(track.album),
        theme: getThemeString(track, [
            `--album-directory: ${album.directory}`,
            `--track-directory: ${track.directory}`
        ]),

        sidebarLeft: generateSidebarForAlbum(album, track),
        sidebarRight: generateSidebarRightForAlbum(album, track),

        nav: {
            links: [
                ['./', wikiInfo.shortName],
                [`${C.ALBUM_DIRECTORY}/${album.directory}/`, album.name],
                listTag === 'ol' && [null, album.tracks.indexOf(track) + 1 + '.'],
                [`${C.TRACK_DIRECTORY}/${track.directory}/`, track.name],
                [null, generateAlbumNavLinks(album, track)]
            ].filter(Boolean),
            content: fixWS`
                <div>
                    ${generateAlbumChronologyLinks(album, track)}
                </div>
            `
        },

        main: {
            content: fixWS`
                ${generateCoverLink({
                    src: getTrackCover(track),
                    alt: 'track cover',
                    tags: track.artTags
                })}
                <h1>${track.name}</h1>
                <p>
                    By ${getArtistString(track.artists, true)}.
                    ${track.coverArtists &&  `<br>Cover art by ${getArtistString(track.coverArtists, true)}.`}
                    ${album.directory !== C.UNRELEASED_TRACKS_DIRECTORY && `<br>Released ${getDateString(track)}.`}
                    ${+track.coverArtDate !== +track.date && `<br>Art released ${getDateString({date: track.coverArtDate})}.`}
                    ${track.duration && `<br>Duration: ${getDurationString(track.duration)}.`}
                </p>
                ${track.urls.length ? fixWS`
                    <p>Listen on ${joinNoOxford(track.urls.map(fancifyURL), 'or')}.</p>
                ` : fixWS`
                    <p>This track has no URLs at which it can be listened.</p>
                `}
                ${otherReleases.length && fixWS`
                    <p>Also released as:</p>
                    <ul>
                        ${otherReleases.map(track => fixWS`
                            <li>
                                <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                                (on <a href="${C.ALBUM_DIRECTORY}/${track.album.directory}/" style="${getLinkThemeString(track.album)}">${track.album.name}</a>)
                            </li>
                        `).join('\n')}
                    </ul>
                `}
                ${track.contributors.textContent && fixWS`
                    <p>Contributors:<br>${transformInline(track.contributors.textContent)}</p>
                `}
                ${track.contributors.length && fixWS`
                    <p>Contributors:</p>
                    <ul>
                        ${track.contributors.map(contrib => `<li>${getArtistString([contrib], true)}</li>`).join('\n')}
                    </ul>
                `}
                ${tracksReferenced.length && fixWS`
                    <p>Tracks that <i>${track.name}</i> references:</p>
                    ${generateTrackList(tracksReferenced)}
                `}
                ${tracksThatReference.length && fixWS`
                    <p>Tracks that reference <i>${track.name}</i>:</p>
                    <dl>
                        ${ttrOfficial.length && fixWS`
                            <dt>Official:</dt>
                            <dd>${generateTrackList(ttrOfficial)}</dd>
                        `}
                        ${ttrFanon.length && fixWS`
                            <dt>Fandom:</dt>
                            <dd>${generateTrackList(ttrFanon)}</dd>
                        `}
                    </dl>
                `}
                ${wikiInfo.features.flashesAndGames && flashesThatFeature.length && fixWS`
                    <p>Flashes &amp; games that feature <i>${track.name}</i>:</p>
                    <ul>
                        ${flashesThatFeature.map(({ flash, as }) => fixWS`
                            <li ${classes(as !== track && 'rerelease')}>
                                ${getFlashLinkHTML(flash)}
                                ${as !== track && fixWS`
                                    (as <a href="${C.TRACK_DIRECTORY}/${as.directory}/" style="${getLinkThemeString(as)}">${as.name}</a>)
                                `}
                            </li>
                        `).join('\n')}
                    </ul>
                `}
                ${track.lyrics && fixWS`
                    <p>Lyrics:</p>
                    <blockquote>
                        ${transformLyrics(track.lyrics)}
                    </blockquote>
                `}
                ${commentary && fixWS`
                    <p>Artist commentary:</p>
                    <blockquote>
                        ${transformMultiline(commentary)}
                    </blockquote>
                `}
            `
        }
    });
}

async function writeArtistPages() {
    await progressPromiseAll('Writing artist pages.', queue(artistData.map(curry(writeArtistPage)), queueSize));
}

async function writeArtistPage(artist) {
    if (artist.alias) {
        return writeArtistAliasPage(artist);
    }

    const {
        name,
        urls = [],
        note = ''
    } = artist;

    const artThings = C.sortByDate([...artist.tracks.asCoverArtist, ...artist.albums.asCoverArtist]);
    const commentaryThings = C.sortByDate([...artist.tracks.asCommentator, ...artist.albums.asCommentator]);

    let flashes;
    if (wikiInfo.features.flashesAndGames) {
        flashes = artist.flashes.asContributor;
    }

    const unreleasedTracks = [...artist.tracks.asArtist, ...artist.tracks.asContributor]
        .filter(track => track.album.directory === C.UNRELEASED_TRACKS_DIRECTORY);
    const releasedTracks = [...artist.tracks.asArtist, ...artist.tracks.asContributor]
        .filter(track => track.album.directory !== C.UNRELEASED_TRACKS_DIRECTORY);

    const generateTrackList = tracks => albumChunkedList(tracks, (track, i) => {
        const contrib = {
            who: artist,
            what: track.contributors.filter(({ who }) => who === artist).map(({ what }) => what).join(', ')
        };
        const { flashes } = track;
        return fixWS`
            <li ${classes(track.aka && 'rerelease')} title="${th(i + 1)} track by ${name}; ${th(track.album.tracks.indexOf(track) + 1)} in ${track.album.name}">
                ${track.duration && `(${getDurationString(track.duration)})`}
                <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                ${track.artists.some(({ who }) => who === artist) && track.artists.length > 1 && `<span class="contributed">(with ${getArtistString(track.artists.filter(({ who }) => who !== artist))})</span>`}
                ${contrib.what && `<span class="contributed">(${getContributionString(contrib) || 'contributed'})</span>`}
                ${wikiInfo.features.flashesAndGames && flashes.length && `<br><span class="flashes">(Featured in ${joinNoOxford(flashes.map(flash => getFlashLinkHTML(flash)))})</span></br>`}
                ${track.aka && `<span class="rerelease-label">(re-release)</span>`}
            </li>
        `;
    });

    // Shish!
    const index = `${C.ARTIST_DIRECTORY}/${artist.directory}/`;
    const avatarPath = path.join(C.MEDIA_ARTIST_AVATAR_DIRECTORY, artist.directory + '.jpg');
    await writePage([C.ARTIST_DIRECTORY, artist.directory], {
        title: name,

        main: {
            content: fixWS`
                ${(wikiInfo.features.artistAvatars &&
                    await access(path.join(mediaPath, avatarPath)).then(() => true, () => false) &&
                    generateCoverLink({
                        src: path.join(C.MEDIA_DIRECTORY, avatarPath),
                        alt: 'artist avatar'
                    })
                )}
                <h1>${name}</h1>
                ${note && fixWS`
                    <p>Note:</p>
                    <blockquote>
                        ${transformMultiline(note)}
                    </blockquote>
                    <hr>
                `}
                ${urls.length && `<p>Visit on ${joinNoOxford(urls.map(fancifyURL), 'or')}.</p>`}
                ${artThings.length && `<p>View <a href="${C.ARTIST_DIRECTORY}/${artist.directory}/gallery/">art gallery</a>!</p>`}
                <p>Jump to: ${[
                    [
                        [...releasedTracks, ...unreleasedTracks].length && `<a href="${index}#tracks">Tracks</a>`,
                        unreleasedTracks.length && `(<a href="${index}#unreleased-tracks">Unreleased Tracks</a>)`
                    ].filter(Boolean).join(' '),
                    artThings.length && `<a href="${index}#art">Art</a>`,
                    wikiInfo.features.flashesAndGames && flashes.length && `<a href="${index}#flashes">Flashes &amp; Games</a>`,
                    commentaryThings.length && `<a href="${index}#commentary">Commentary</a>`
                ].filter(Boolean).join(', ')}.</p>
                ${[...releasedTracks, ...unreleasedTracks].length && fixWS`
                    <h2 id="tracks">Tracks</h2>
                `}
                ${releasedTracks.length && fixWS`
                    <p>${name} has contributed ~${getDurationString(getTotalDuration(releasedTracks))} ${getTotalDuration(releasedTracks) > 3600 ? 'hours' : 'minutes'} of music collected on this wiki.</p>
                    ${generateTrackList(releasedTracks)}
                `}
                ${unreleasedTracks.length && fixWS`
                    <h3 id="unreleased-tracks">Unreleased Tracks</h3>
                    ${generateTrackList(unreleasedTracks)}
                `}
                ${artThings.length && fixWS`
                    <h2 id="art">Art</h2>
                    <p>View <a href="${C.ARTIST_DIRECTORY}/${artist.directory}/gallery/">art gallery</a>! Or browse the list:</p>
                    ${albumChunkedList(artThings, (thing, i) => {
                        const contrib = thing.coverArtists.find(({ who }) => who === artist);
                        return fixWS`
                            <li title="${th(i + 1)} art by ${name}${thing.album && `; ${th(thing.album.tracks.indexOf(thing) + 1)} track in ${thing.album.name}`}">
                                ${thing.album ? fixWS`
                                    <a href="${C.TRACK_DIRECTORY}/${thing.directory}/" style="${getLinkThemeString(thing)}">${thing.name}</a>
                                ` : '<i>(cover art)</i>'}
                                ${thing.coverArtists.length > 1 && `<span class="contributed">(with ${getArtistString(thing.coverArtists.filter(({ who }) => who !== artist))})</span>`}
                                ${contrib.what && `<span class="contributed">(${getContributionString(contrib)})</span>`}
                            </li>
                        `;
                    }, true, 'coverArtDate')}
                `}
                ${wikiInfo.features.flashesAndGames && flashes.length && fixWS`
                    <h2 id="flashes">Flashes &amp; Games</h2>
                    ${actChunkedList(flashes, flash => {
                        const contributionString = flash.contributors.filter(({ who }) => who === artist).map(getContributionString).join(' ');
                        return fixWS`
                            <li>
                                <a href="${C.FLASH_DIRECTORY}/${flash.directory}/" style="${getLinkThemeString(flash)}">${flash.name}</a>
                                ${contributionString && `<span class="contributed">(${contributionString})</span>`}
                                (${getDateString({date: flash.date})})
                            </li>
                        `
                    })}
                `}
                ${commentaryThings.length && fixWS`
                    <h2 id="commentary">Commentary</h2>
                    ${albumChunkedList(commentaryThings, thing => {
                        const { flashes } = thing;
                        return fixWS`
                            <li>
                                ${thing.album ? fixWS`
                                    <a href="${C.TRACK_DIRECTORY}/${thing.directory}/" style="${getLinkThemeString(thing)}">${thing.name}</a>
                                ` : '(album commentary)'}
                                ${wikiInfo.features.flashesAndGames && flashes?.length && `<br><span class="flashes">(Featured in ${joinNoOxford(flashes.map(flash => getFlashLinkHTML(flash)))})</span></br>`}
                            </li>
                        `
                    }, false)}
                    </ul>
                `}
            `
        },

        nav: {
            links: [
                ['./', wikiInfo.shortName],
                wikiInfo.features.listings && [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                [null, 'Artist:'],
                [`${C.ARTIST_DIRECTORY}/${artist.directory}/`, name],
                artThings.length && [null, `(${[
                    `<a href="${C.ARTIST_DIRECTORY}/${artist.directory}/" class="current">Info</a>`,
                    `<a href="${C.ARTIST_DIRECTORY}/${artist.directory}/gallery/">Gallery</a>`
                ].join(', ')})`]
            ]
        }
    });

    if (artThings.length) {
        await writePage([C.ARTIST_DIRECTORY, artist.directory, 'gallery'], {
            title: name + ' - Gallery',

            main: {
                classes: ['top-index'],
                content: fixWS`
                    <h1>${name} - Gallery</h1>
                    <p class="quick-info">(Contributed to ${s(artThings.length, 'cover art')})</p>
                    <div class="grid-listing">
                        ${getGridHTML({
                            entries: artThings.map(item => ({item})),
                            srcFn: thing => (thing.album
                                ? getTrackCover(thing)
                                : getAlbumCover(thing)),
                            hrefFn: thing => (thing.album
                                ? `${C.TRACK_DIRECTORY}/${thing.directory}/`
                                : `${C.ALBUM_DIRECTORY}/${thing.directory}`)
                        })}
                    </div>
                `
            },

            nav: {
                links: [
                    ['./', wikiInfo.shortName],
                    wikiInfo.features.listings && [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                    [null, 'Artist:'],
                    [`${C.ARTIST_DIRECTORY}/${artist.directory}/`, name],
                    [null, `(${[
                        `<a href="${C.ARTIST_DIRECTORY}/${artist.directory}/">Info</a>`,
                        `<a href="${C.ARTIST_DIRECTORY}/${artist.directory}/gallery/" class="current">Gallery</a>`
                    ].join(', ')})`]
                ]
            }
        });
    }
}

async function writeArtistAliasPage(artist) {
    const { alias } = artist;

    const directory = path.join(outputPath, C.ARTIST_DIRECTORY, artist.directory);
    const file = path.join(directory, 'index.html');
    const target = `/${C.ARTIST_DIRECTORY}/${alias.directory}/`;

    await mkdirp(directory);
    await writeFile(file, generateRedirectPage(alias.name, target));
}

function generateRedirectPage(title, target) {
    return fixWS`
        <!DOCTYPE html>
        <html>
            <head>
                <title>Moved to ${title}</title>
                <meta charset="utf-8">
                <meta http-equiv="refresh" content="0;url=${target}">
                <link rel="canonical" href="${target}">
                <link rel="stylesheet" href="static/site-basic.css">
            </head>
            <body>
                <main>
                    <h1>Moved to ${title}</h1>
                    <p>This page has been moved to <a href="${target}">${target}</a>.</p>
                </main>
            </body>
        </html>
    `;
}

function albumChunkedList(tracks, getLI, showDate = true, datePropertyOrFn = 'date') {
    const getAlbum = thing => thing.album ? thing.album : thing;
    const dateFn = (typeof datePropertyOrFn === 'function'
        ? datePropertyOrFn
        : track => track[datePropertyOrFn]);
    return fixWS`
        <dl>
            ${tracks.slice().sort((a, b) => dateFn(a) - dateFn(b)).map((thing, i, sorted) => {
                const li = getLI(thing, i);
                const album = getAlbum(thing);
                const previous = sorted[i - 1];
                if (i === 0 || album !== getAlbum(previous) || (showDate && +dateFn(thing) !== +dateFn(previous))) {
                    const heading = fixWS`
                        <dt>
                            <a href="${C.ALBUM_DIRECTORY}/${getAlbum(thing).directory}/" style="${getLinkThemeString(getAlbum(thing))}">${getAlbum(thing).name}</a>
                            ${showDate && `(${getDateString({date: dateFn(thing)})})`}
                        </dt>
                        <dd><ul>
                    `;
                    if (i > 0) {
                        return ['</ul></dd>', heading, li];
                    } else {
                        return [heading, li];
                    }
                } else {
                    return [li];
                }
            }).reduce((acc, arr) => acc.concat(arr), []).join('\n')}
        </dl>
    `;
}

function actChunkedList(flashes, getLI, showDate = true, dateProperty = 'date') {
    return fixWS`
        <dl>
            ${flashes.slice().sort((a, b) => a[dateProperty] - b[dateProperty]).map((flash, i, sorted) => {
                const li = getLI(flash, i);
                const act = flash.act;
                const previous = sorted[i - 1];
                if (i === 0 || act !== previous.act) {
                    const heading = fixWS`
                        <dt>
                            <a href="${C.FLASH_DIRECTORY}/${sorted.find(flash => !flash.act8r8k && flash.act === act).directory}/" style="${getLinkThemeString(flash)}">${flash.act}</a>
                        </dt>
                        <dd><ul>
                    `;
                    if (i > 0) {
                        return ['</ul></dd>', heading, li];
                    } else {
                        return [heading, li];
                    }
                } else {
                    return [li];
                }
            }).reduce((acc, arr) => acc.concat(arr), []).join('\n')}
        </dl>
    `;
}

async function writeFlashPages() {
    await progressPromiseAll('Writing Flash pages.', queue(flashData
        .filter(flash => !flash.act8r8k)
        .map(curry(writeFlashPage)), queueSize));
}

async function writeFlashPage(flash) {
    const kebab = getFlashDirectory(flash);

    const flashes = flashData.filter(flash => !flash.act8r8k);
    const index = flashes.indexOf(flash);
    const previous = flashes[index - 1];
    const next = flashes[index + 1];
    const parts = [
        previous && `<a href="${getHrefOfAnythingMan(previous)}" id="previous-button" title="${previous.name}">Previous</a>`,
        next && `<a href="${getHrefOfAnythingMan(next)}" id="next-button" title="${next.name}">Next</a>`
    ].filter(Boolean);

    await writePage([C.FLASH_DIRECTORY, kebab], {
        title: flash.name,
        theme: getThemeString(flash, [
            `--flash-directory: ${flash.directory}`
        ]),
        main: {
            content: fixWS`
                <h1>${flash.name}</h1>
                ${generateCoverLink({
                    src: getFlashCover(flash),
                    alt: 'cover art'
                })}
                <p>Released ${getDateString(flash)}.</p>
                ${(flash.page || flash.urls.length) && `<p>Play on ${joinNoOxford(
                    [
                        flash.page && getFlashLink(flash),
                        ...flash.urls
                    ].map(url => fancifyFlashURL(url, flash)), 'or')}.</p>`}
                ${flash.contributors.textContent && fixWS`
                    <p>Contributors:<br>${transformInline(flash.contributors.textContent)}</p>
                `}
                ${flash.tracks.length && fixWS`
                    <p>Tracks featured in <i>${flash.name.replace(/\.$/, '')}</i>:</p>
                    <ul>
                        ${flash.tracks.map(track => fixWS`
                            <li>
                                <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                                <span class="by">by ${getArtistString(track.artists)}</span>
                            </li>
                        `).join('\n')}
                    </ul>
                `}
                ${flash.contributors.length && fixWS`
                    <p>Contributors:</p>
                    <ul>
                        ${flash.contributors.map(contrib => fixWS`<li>${getArtistString([contrib], true)}</li>`).join('\n')}
                    </ul>
                `}
            `
        },
        sidebarLeft: {
            content: generateSidebarForFlashes(flash)
        },
        nav: {
            links: [
                ['./', wikiInfo.shortName],
                [`${C.FLASH_DIRECTORY}/`, `Flashes &amp; Games`],
                [`${C.FLASH_DIRECTORY}/${kebab}/`, flash.name],
                parts.length && [null, `(${parts.join(', ')})`]
            ].filter(Boolean),
            content: fixWS`
                <div>
                    ${chronologyLinks(flash, {
                        headingWord: 'flash/game',
                        sourceData: flashData,
                        filters: [
                            {
                                mapProperty: 'contributors',
                                toArtist: ({ who }) => who
                            }
                        ]
                    })}
                </div>
            `
        }
    });
}

function generateSidebarForFlashes(flash) {
    const act6 = flashData.findIndex(f => f.act.startsWith('Act 6'));
    const postCanon = flashData.findIndex(f => f.act.includes('Post Canon'));
    const outsideCanon = postCanon + flashData.slice(postCanon).findIndex(f => !f.act.includes('Post Canon'));
    const index = flashData.indexOf(flash);
    const side = (
        (index < 0) ? 0 :
        (index < act6) ? 1 :
        (index <= outsideCanon) ? 2 :
        3
    );
    const currentAct = flash && flash.act;

    return fixWS`
        <h1><a href="${C.FLASH_DIRECTORY}/">Flashes &amp; Games</a></h1>
        <dl>
            ${flashData.filter(f => f.act8r8k).filter(({ act }) =>
                act.startsWith('Act 1') ||
                act.startsWith('Act 6 Act 1') ||
                act.startsWith('Hiveswap') ||
                (
                    flashData.findIndex(f => f.act === act) < act6 ? side === 1 :
                    flashData.findIndex(f => f.act === act) < outsideCanon ? side === 2 :
                    true
                )
            ).flatMap(({ act, color }) => [
                act.startsWith('Act 1') && `<dt ${classes('side', side === 1 && 'current')}><a href="${C.FLASH_DIRECTORY}/${getFlashDirectory(flashData.find(f => !f.act8r8k && f.act.startsWith('Act 1')))}/" style="--primary-color: #4ac925">Side 1 (Acts 1-5)</a></dt>`
                || act.startsWith('Act 6 Act 1') && `<dt ${classes('side', side === 2 && 'current')}><a href="${C.FLASH_DIRECTORY}/${getFlashDirectory(flashData.find(f => !f.act8r8k && f.act.startsWith('Act 6')))}/" style="--primary-color: #1076a2">Side 2 (Acts 6-7)</a></dt>`
                || act.startsWith('Hiveswap Act 1') && `<dt ${classes('side', side === 3 && 'current')}><a href="${C.FLASH_DIRECTORY}/${getFlashDirectory(flashData.find(f => !f.act8r8k && f.act.startsWith('Hiveswap')))}/" style="--primary-color: #008282">Outside Canon (Misc. Games)</a></dt>`,
                (
                    flashData.findIndex(f => f.act === act) < act6 ? side === 1 :
                    flashData.findIndex(f => f.act === act) < outsideCanon ? side === 2 :
                    true
                ) && `<dt ${classes(act === currentAct && 'current')}><a href="${C.FLASH_DIRECTORY}/${getFlashDirectory(flashData.find(f => !f.act8r8k && f.act === act))}/" style="${getLinkThemeString({color})}">${act}</a></dt>`,
                act === currentAct && fixWS`
                    <dd><ul>
                        ${flashData.filter(f => !f.act8r8k && f.act === act).map(f => fixWS`
                            <li ${classes(f === flash && 'current')}><a href="${C.FLASH_DIRECTORY}/${getFlashDirectory(f)}/" style="${getLinkThemeString(f)}">${f.name}</a></li>
                        `).join('\n')}
                    </ul></dd>
                `
            ]).filter(Boolean).join('\n')}
        </dl>
    `;
}

function writeListingPages() {
    if (!wikiInfo.features.listings) {
        return;
    }

    const reversedTracks = trackData.slice().reverse();
    const reversedArtThings = justEverythingSortedByArtDateMan.slice().reverse();

    const getAlbumLI = (album, extraText = '') => fixWS`
        <li>
            <a href="${C.ALBUM_DIRECTORY}/${album.directory}/" style="${getLinkThemeString(album)}">${album.name}</a>
            ${extraText}
        </li>
    `;

    const sortByName = (a, b) => {
        let an = a.name.toLowerCase();
        let bn = b.name.toLowerCase();
        if (an.startsWith('the ')) an = an.slice(4);
        if (bn.startsWith('the ')) bn = bn.slice(4);
        return an < bn ? -1 : an > bn ? 1 : 0;
    };

    const listingDescriptors = [
        [['albums', 'by-name'], `Albums - by Name`, albumData.slice()
            .sort(sortByName)
            .map(album => getAlbumLI(album, `(${album.tracks.length} tracks)`))],
        [['albums', 'by-tracks'], `Albums - by Tracks`, albumData.slice()
            .sort((a, b) => b.tracks.length - a.tracks.length)
            .map(album => getAlbumLI(album, `(${s(album.tracks.length, 'track')})`))],
        [['albums', 'by-duration'], `Albums - by Duration`, albumData.slice()
            .map(album => ({album, duration: getTotalDuration(album.tracks)}))
            .sort((a, b) => b.duration - a.duration)
            .map(({ album, duration }) => getAlbumLI(album, `(${getDurationString(duration)})`))],
        [['albums', 'by-date'], `Albums - by Date`, C.sortByDate(albumData.filter(album => album.directory !== C.UNRELEASED_TRACKS_DIRECTORY))
            .map(album => getAlbumLI(album, `(${getDateString(album)})`))],
        [['artists', 'by-name'], `Artists - by Name`, artistData
            .filter(artist => !artist.alias)
            .sort(sortByName)
            .map(artist => fixWS`
                <li>
                    <a href="${C.ARTIST_DIRECTORY}/${artist.directory}/">${artist.name}</a>
                    (${'' + C.getArtistNumContributions(artist)} <abbr title="contributions (to ${joinNoOxford(['music', 'art', wikiInfo.features.flashesAndGames && 'flashes'])})">c.</abbr>)
                </li>
            `)],
        [['artists', 'by-contribs'], `Artists - by Contributions`, fixWS`
            <div class="content-columns">
                <div class="column">
                    <h2>Track Contributors</h2>
                    <ul>
                        ${artistData
                            .filter(artist => !artist.alias)
                            .map(artist => ({
                                name: artist.name,
                                contribs: (
                                    artist.tracks.asContributor.length +
                                    artist.tracks.asArtist.length
                                )
                            }))
                            .sort((a, b) => b.contribs - a.contribs)
                            .filter(({ contribs }) => contribs)
                            .map(({ name, contribs }) => fixWS`
                                <li>
                                    <a href="${C.ARTIST_DIRECTORY}/${C.getArtistDirectory(name)}">${name}</a>
                                    (${contribs} <abbr title="contributions (to track music)">c.</abbr>)
                                </li>
                            `)
                            .join('\n')
                        }
                    </ul>
                </div>
                <div class="column">
                    <h2>Art${wikiInfo.features.flashesAndGames ? ` &amp; Flash` : ''} Contributors</h2>
                    <ul>
                        ${artistData
                            .filter(artist => !artist.alias)
                            .map(artist => ({
                                artist,
                                contribs: (
                                    artist.tracks.asCoverArtist.length +
                                    artist.albums.asCoverArtist.length +
                                    (wikiInfo.features.flashesAndGames ? artist.flashes.asContributor.length : 0)
                                )
                            }))
                            .sort((a, b) => b.contribs - a.contribs)
                            .filter(({ contribs }) => contribs)
                            .map(({ artist, contribs }) => fixWS`
                                <li>
                                    <a href="${C.ARTIST_DIRECTORY}/${artist.directory}">${artist.name}</a>
                                    (${contribs} <abbr title="contributions (to art${wikiInfo.features.flashesAndGames ? ' and flashes' : ''})">c.</abbr>)
                                </li>
                            `)
                            .join('\n')
                        }
                    </ul>
                </div>
            </div>
        `],
        [['artists', 'by-commentary'], `Artists - by Commentary Entries`, artistData
            .filter(artist => !artist.alias)
            .map(artist => ({artist, commentary: artist.tracks.asCommentator.length + artist.albums.asCommentator.length}))
            .filter(({ commentary }) => commentary > 0)
            .sort((a, b) => b.commentary - a.commentary)
            .map(({ artist, commentary }) => fixWS`
                <li>
                    <a href="${C.ARTIST_DIRECTORY}/${artist.directory}/#commentary">${artist.name}</a>
                    (${commentary} ${commentary === 1 ? 'entry' : 'entries'})
                </li>
            `)],
        [['artists', 'by-duration'], `Artists - by Duration`, artistData
            .filter(artist => !artist.alias)
            .map(artist => ({artist, duration: getTotalDuration(
                [...artist.tracks.asArtist, ...artist.tracks.asContributor].filter(track => track.album.directory !== C.UNRELEASED_TRACKS_DIRECTORY))
            }))
            .filter(({ duration }) => duration > 0)
            .sort((a, b) => b.duration - a.duration)
            .map(({ artist, duration }) => fixWS`
                <li>
                    <a href="${C.ARTIST_DIRECTORY}/${artist.directory}/#tracks">${artist.name}</a>
                    (~${getDurationString(duration)})
                </li>
            `)],
        [['artists', 'by-latest'], `Artists - by Latest Contribution`, fixWS`
            <div class="content-columns">
                <div class="column">
                    <h2>Track Contributors</h2>
                    <ul>
                        ${C.sortByDate(artistData
                            .filter(artist => !artist.alias)
                            .map(artist => ({
                                artist,
                                date: reversedTracks.find(({ album, artists, contributors }) => (
                                    album.directory !== C.UNRELEASED_TRACKS_DIRECTORY &&
                                    [...artists, ...contributors].some(({ who }) => who === artist)
                                ))?.date
                            }))
                            .filter(({ date }) => date)
                            .sort((a, b) => a.name < b.name ? 1 : a.name > b.name ? -1 : 0)
                        ).reverse().map(({ artist, date }) => fixWS`
                            <li>
                                <a href="${C.ARTIST_DIRECTORY}/${artist.directory}/">${artist.name}</a>
                                (${getDateString({date})})
                            </li>
                        `).join('\n')}
                    </ul>
                </div>
                <div class="column">
                    <h2>Art${wikiInfo.features.flashesAndGames ? ` &amp; Flash` : ''} Contributors</h2>
                    <ul>
                        ${C.sortByDate(artistData
                            .filter(artist => !artist.alias)
                            .map(artist => {
                                const thing = reversedArtThings.find(({ album, coverArtists, contributors }) => (
                                    album?.directory !== C.UNRELEASED_TRACKS_DIRECTORY &&
                                    [...coverArtists || [], ...!album && contributors || []].some(({ who }) => who === artist)
                                ));
                                return thing && {
                                    artist,
                                    date: (thing.coverArtists?.some(({ who }) => who === artist)
                                        ? thing.coverArtDate
                                        : thing.date)
                                };
                            })
                            .filter(Boolean)
                            .sort((a, b) => a.name < b.name ? 1 : a.name > b.name ? -1 : 0)
                        ).reverse().map(({ artist, date }) => fixWS`
                            <li>
                                <a href="${C.ARTIST_DIRECTORY}/${artist.directory}">${artist.name}</a>
                                (${getDateString({date})})
                            </li>
                        `).join('\n')}
                    </ul>
                </div>
            </div>
        `],
        wikiInfo.features.groupUI &&
        [['groups', 'by-name'], `Groups - by Name`, groupData
            .filter(x => x.isGroup)
            .sort(sortByName)
            .map(group => fixWS`
                <li><a href="${C.GROUP_DIRECTORY}/${group.directory}/" style="${getLinkThemeString(group)}">${group.name}</a></li>
            `)],
        wikiInfo.features.groupUI &&
        [['groups', 'by-category'], `Groups - by Category`, fixWS`
            <dl>
                ${groupData.filter(x => x.isCategory).map(category => fixWS`
                    <dt><a href="${C.GROUP_DIRECTORY}/${category.groups[0].directory}/" style="${getLinkThemeString(category)}">${category.name}</a></li>
                    <dd><ul>
                        ${category.groups.map(group => fixWS`
                            <li><a href="${C.GROUP_DIRECTORY}/${group.directory}/gallery/" style="${getLinkThemeString(group)}">${group.name}</a></li>
                        `).join('\n')}
                    </ul></dd>
                `).join('\n')}
            </dl>
        `],
        wikiInfo.features.groupUI &&
        [['groups', 'by-albums'], `Groups - by Albums`, groupData
            .filter(x => x.isGroup)
            .map(group => ({group, albums: group.albums.length}))
            .sort((a, b) => b.albums - a.albums)
            .map(({ group, albums }) => fixWS`
                <li><a href="${C.GROUP_DIRECTORY}/${group.directory}/" style="${getLinkThemeString(group)}">${group.name}</a> (${s(albums, 'album')})</li>
            `)],
        wikiInfo.features.groupUI &&
        [['groups', 'by-tracks'], `Groups - by Tracks`, groupData
            .filter(x => x.isGroup)
            .map(group => ({group, tracks: group.albums.reduce((acc, album) => acc + album.tracks.length, 0)}))
            .sort((a, b) => b.tracks - a.tracks)
            .map(({ group, tracks }) => fixWS`
                <li><a href="${C.GROUP_DIRECTORY}/${group.directory}/" style="${getLinkThemeString(group)}">${group.name}</a> (${s(tracks, 'track')})</li>
            `)],
        wikiInfo.features.groupUI &&
        [['groups', 'by-duration'], `Groups - by Duration`, groupData
            .filter(x => x.isGroup)
            .map(group => ({group, duration: getTotalDuration(group.albums.flatMap(album => album.tracks))}))
            .sort((a, b) => b.duration - a.duration)
            .map(({ group, duration }) => fixWS`
                <li><a href="${C.GROUP_DIRECTORY}/${group.directory}/" style="${getLinkThemeString(group)}">${group.name}</a> (${getDurationString(duration)})</li>
            `)],
        wikiInfo.features.groupUI &&
        [['groups', 'by-latest'], `Groups - by Latest Album`, C.sortByDate(groupData
            .filter(x => x.isGroup)
            .map(group => ({group, date: group.albums[group.albums.length - 1].date}))
            // So this is kinda tough to explain, 8ut 8asically, when we reverse the list after sorting it 8y d8te
            // (so that the latest d8tes come first), it also flips the order of groups which share the same d8te.
            // This happens mostly when a single al8um is the l8test in two groups. So, say one such al8um is in
            // the groups "Fandom" and "UMSPAF". Per category order, Fandom is meant to show up 8efore UMSPAF, 8ut
            // when we do the reverse l8ter, that flips them, and UMSPAF ends up displaying 8efore Fandom. So we do
            // an extra reverse here, which will fix that and only affect groups that share the same d8te (8ecause
            // groups that don't will 8e moved 8y the sortByDate call surrounding this).
            .reverse()
        ).reverse().map(({ group, date }) => fixWS`
            <li>
                <a href="${C.GROUP_DIRECTORY}/${group.directory}/" style="${getLinkThemeString(group)}">${group.name}</a>
                (${getDateString({date})})
            </li>
        `)],
        [['tracks', 'by-name'], `Tracks - by Name`, trackData.slice()
            .sort(sortByName)
            .map(track => fixWS`
                <li><a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a></li>
            `)],
        [['tracks', 'by-album'], `Tracks - by Album`, fixWS`
                <dl>
                    ${albumData.map(album => fixWS`
                        <dt><a href="${C.ALBUM_DIRECTORY}/${album.directory}/" style="${getLinkThemeString(album)}">${album.name}</a></dt>
                        <dd><ol>
                            ${album.tracks.map(track => fixWS`
                                <li><a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a></li>
                            `).join('\n')}
                        </ol></dd>
                    `).join('\n')}
                </dl>
            `],
        [['tracks', 'by-date'], `Tracks - by Date`, albumChunkedList(
            C.sortByDate(trackData.filter(track => track.album.directory !== C.UNRELEASED_TRACKS_DIRECTORY)),
            track => fixWS`
                <li ${classes(track.aka && 'rerelease')}><a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a> ${track.aka && `<span class="rerelease-label">(re-release)</span>`}</li>
            `)],
        [['tracks', 'by-duration'], `Tracks - by Duration`, C.sortByDate(trackData.slice())
            .filter(track => track.duration > 0)
            .sort((a, b) => b.duration - a.duration)
            .map(track => fixWS`
                <li>
                    <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                    (${getDurationString(track.duration)})
                </li>
            `)],
        [['tracks', 'by-duration-in-album'], `Tracks - by Duration (in Album)`, albumChunkedList(albumData.flatMap(album => album.tracks)
            .filter(track => track.duration > 0)
            .sort((a, b) => (
                b.album !== a.album ? 0 :
                b.duration - a.duration
            )),
            track => fixWS`
                <li>
                    <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                    (${getDurationString(track.duration)})
                </li>
            `,
            false,
            null)],
        [['tracks', 'by-times-referenced'], `Tracks - by Times Referenced`, C.sortByDate(trackData.slice())
            .filter(track => track.referencedBy.length > 0)
            .sort((a, b) => b.referencedBy.length - a.referencedBy.length)
            .map(track => fixWS`
                <li>
                    <a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a>
                    (${s(track.referencedBy.length, 'time')} referenced)
                </li>
            `)],
        wikiInfo.features.flashesAndGames &&
        [['tracks', 'in-flashes', 'by-album'], `Tracks - in Flashes &amp; Games (by Album)`, albumChunkedList(
            C.sortByDate(trackData.slice()).filter(track => track.album.directory !== C.UNRELEASED_TRACKS_DIRECTORY && track.flashes.length > 0),
            track => `<li><a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a></li>`)],
        wikiInfo.features.flashesAndGames &&
        [['tracks', 'in-flashes', 'by-flash'], `Tracks - in Flashes &amp; Games (by Flash)`, fixWS`
            <dl>
                ${C.sortByDate(flashData.filter(flash => !flash.act8r8k))
                    .map(flash => fixWS`
                        <dt>
                            <a href="${C.FLASH_DIRECTORY}/${flash.directory}/" style="${getLinkThemeString(flash)}">${flash.name}</a>
                            (${getDateString(flash)})
                        </dt>
                        <dd><ul>
                            ${flash.tracks.map(track => fixWS`
                                <li><a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a></li>
                            `).join('\n')}
                        </ul></dd>
                    `)
                    .join('\n')}
            </dl>
        `],
        [['tracks', 'with-lyrics'], `Tracks - with Lyrics`, albumChunkedList(
            C.sortByDate(trackData.slice())
            .filter(track => track.lyrics),
            track => fixWS`
                <li><a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a></li>
            `)],
        wikiInfo.features.artTagUI &&
        [['tags', 'by-name'], 'Tags - by Name', tagData.slice().sort(sortByName)
            .filter(tag => !tag.isCW)
            .map(tag => `<li><a href="${C.TAG_DIRECTORY}/${tag.directory}/" style="${getLinkThemeString(tag)}">${tag.name}</a></li>`)],
        wikiInfo.features.artTagUI &&
        [['tags', 'by-uses'], 'Tags - by Uses', tagData.slice().sort(sortByName)
            .filter(tag => !tag.isCW)
            .map(tag => ({tag, timesUsed: tag.things.length}))
            .sort((a, b) => b.timesUsed - a.timesUsed)
            .map(({ tag, timesUsed }) => `<li><a href="${C.TAG_DIRECTORY}/${tag.directory}/" style="${getLinkThemeString(tag)}">${tag.name}</a> (${s(timesUsed, 'time')})</li>`)]
    ].filter(Boolean);

    const getWordCount = str => {
        const wordCount = str.split(' ').length;
        return `${Math.floor(wordCount / 100) / 10}k`;
    };

    const releasedTracks = trackData.filter(track => track.album.directory !== C.UNRELEASED_TRACKS_DIRECTORY);
    const releasedAlbums = albumData.filter(album => album.directory !== C.UNRELEASED_TRACKS_DIRECTORY);

    return progressPromiseAll(`Writing listing pages.`, [
        writePage([C.LISTING_DIRECTORY], {
            title: `Listings Index`,

            main: {
                content: fixWS`
                    <h1>Listings</h1>
                    <p>${wikiInfo.name}: <b>${releasedTracks.length}</b> tracks across <b>${releasedAlbums.length}</b> albums, totaling <b>~${getDurationString(getTotalDuration(releasedTracks))}</b> ${getTotalDuration(releasedTracks) > 3600 ? 'hours' : 'minutes'}.</p>
                    <hr>
                    <p>Feel free to explore any of the listings linked below and in the sidebar!</p>
                    ${generateLinkIndexForListings(listingDescriptors)}
                `
            },

            sidebarLeft: {
                content: generateSidebarForListings(listingDescriptors)
            },

            nav: {
                links: [
                    ['./', wikiInfo.shortName],
                    [`${C.LISTINGS_DIRECTORY}/`, 'Listings']
                ]
            }
        }),

        writePage([C.LISTING_DIRECTORY, 'all-commentary'], {
            title: 'All Commentary',

            main: {
                content: fixWS`
                    <h1>All Commentary</h1>
                    <p><strong>${getWordCount(albumData.reduce((acc, a) => acc + [a, ...a.tracks].filter(x => x.commentary).map(x => x.commentary).join(' '), ''))}</strong> words, in all.<br>Jump to a particular album:</p>
                    <ul>
                        ${C.sortByDate(albumData.slice())
                            .filter(album => [album, ...album.tracks].some(x => x.commentary))
                            .map(album => fixWS`
                                <li>
                                    <a href="${C.LISTING_DIRECTORY}/all-commentary/#${album.directory}" style="${getLinkThemeString(album)}">${album.name}</a>
                                    (${(() => {
                                        const things = [album, ...album.tracks];
                                        const cThings = things.filter(x => x.commentary);
                                        // const numStr = album.tracks.every(t => t.commentary) ? 'full commentary' : `${cThings.length} entries`;
                                        const numStr = `${cThings.length}/${things.length} entries`;
                                        return `${numStr}; ${getWordCount(cThings.map(x => x.commentary).join(' '))} words`;
                                    })()})
                                </li>
                            `)
                            .join('\n')
                        }
                    </ul>
                    ${C.sortByDate(albumData.slice())
                        .map(album => [album, ...album.tracks])
                        .filter(x => x.some(y => y.commentary))
                        .map(([ album, ...tracks ]) => fixWS`
                            <h2 id="${album.directory}"><a href="${C.ALBUM_DIRECTORY}/${album.directory}/" style="${getLinkThemeString(album)}">${album.name}</a></h2>
                            ${album.commentary && fixWS`
                                <blockquote style="${getLinkThemeString(album)}">
                                    ${transformMultiline(album.commentary)}
                                </blockquote>
                            `}
                            ${tracks.filter(t => t.commentary).map(track => fixWS`
                                <h3 id="${track.directory}"><a href="${C.TRACK_DIRECTORY}/${track.directory}/" style="${getLinkThemeString(track)}">${track.name}</a></h3>
                                <blockquote style="${getLinkThemeString(track)}">
                                    ${transformMultiline(track.commentary)}
                                </blockquote>
                            `).join('\n')}
                        `)
                        .join('\n')
                    }
                `
            },

            sidebarLeft: {
                content: generateSidebarForListings(listingDescriptors, 'all-commentary')
            },

            nav: {
                links: [
                    ['./', wikiInfo.shortName],
                    [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                    [`${C.LISTING_DIRECTORY}/all-commentary`, 'All Commentary']
                ]
            }
        }),

        writePage([C.LISTING_DIRECTORY, 'random'], {
            title: 'Random Pages',

            main: {
                content: fixWS`
                    <h1>Random Pages</h1>
                    <p>Choose a link to go to a random page in that category or album! If your browser doesn't support relatively modern JavaScript or you've disabled it, these links won't work - sorry.</p>
                    <p class="js-hide-once-data">(Data files are downloading in the background! Please wait for data to load.)</p>
                    <p class="js-show-once-data">(Data files have finished being downloaded. The links should work!)</p>
                    <dl>
                        <dt>Miscellaneous:</dt>
                        <dd><ul>
                            <li>
                                <a href="${C.JS_DISABLED_DIRECTORY}/" data-random="artist">Random Artist</a>
                                (<a href="${C.JS_DISABLED_DIRECTORY}/" data-random="artist-more-than-one-contrib">&gt;1 contribution</a>)
                            </li>
                            <li><a href="${C.JS_DISABLED_DIRECTORY}/" data-random="album">Random Album (whole site)</a></li>
                            <li><a href="${C.JS_DISABLED_DIRECTORY}/" data-random="track">Random Track (whole site)</a></li>
                        </ul></dd>
                        ${[
                            {name: 'Official', albumData: officialAlbumData, code: 'official'},
                            {name: 'Fandom', albumData: fandomAlbumData, code: 'fandom'}
                        ].map(category => fixWS`
                            <dt>${category.name}: (<a href="${C.JS_DISABLED_DIRECTORY}/" data-random="album-in-${category.code}">Random Album</a>, <a href="${C.JS_DISABLED_DIRECTORY}/" data-random="track-in-${category.code}">Random Track</a>)</dt>
                            <dd><ul>${category.albumData.map(album => fixWS`
                                <li><a style="${getLinkThemeString(album)}; --album-directory: ${album.directory}" href="${C.JS_DISABLED_DIRECTORY}/" data-random="track-in-album">${album.name}</a></li>
                            `).join('\n')}</ul></dd>
                        `).join('\n')}
                    </dl>
                `
            },

            sidebarLeft: {
                content: generateSidebarForListings(listingDescriptors, 'all-commentary')
            },

            nav: {
                links: [
                    ['./', wikiInfo.shortName],
                    [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                    [`${C.LISTING_DIRECTORY}/random`, 'Random Pages']
                ]
            }
        }),

        ...listingDescriptors.map(entry => writeListingPage(...entry, listingDescriptors))
    ]);
}

function writeListingPage(directoryParts, title, items, listingDescriptors) {
    return writePage([C.LISTING_DIRECTORY, ...directoryParts], {
        title,

        main: {
            content: fixWS`
                <h1>${title}</h1>
                ${typeof items === 'string' ? items : fixWS`
                    <ul>
                        ${items.join('\n')}
                    </ul>
                `}
            `
        },

        sidebarLeft: {
            content: generateSidebarForListings(listingDescriptors, directoryParts)
        },

        nav: {
            links: [
                ['./', wikiInfo.shortName],
                [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                [`${C.LISTING_DIRECTORY}/${directoryParts.join('/')}/`, title]
            ]
        }
    });
}

function generateSidebarForListings(listingDescriptors, currentDirectoryParts) {
    return fixWS`
        <h1><a href="${C.LISTING_DIRECTORY}/">Listings</a></h1>
        ${generateLinkIndexForListings(listingDescriptors, currentDirectoryParts)}
    `;
}

function generateLinkIndexForListings(listingDescriptors, currentDirectoryParts) {
    return fixWS`
        <ul>
            ${listingDescriptors.map(([ ldDirectoryParts, ldTitle ]) => fixWS`
                <li ${classes(currentDirectoryParts === ldDirectoryParts && 'current')}>
                    <a href="${C.LISTING_DIRECTORY}/${ldDirectoryParts.join('/')}/">${ldTitle}</a>
                </li>
            `).join('\n')}
            <li ${classes(currentDirectoryParts === 'all-commentary' && 'current')}>
                <a href="${C.LISTING_DIRECTORY}/all-commentary/">All Commentary</a>
            </li>
            <li ${classes(currentDirectoryParts === 'random' && 'current')}>
                <a href="${C.LISTING_DIRECTORY}/random/">Random Pages</a>
            </li>
        </ul>
    `;
}

function writeTagPages() {
    if (!wikiInfo.features.artTagUI) {
        return;
    }

    return progressPromiseAll(`Writing tag pages.`, queue(tagData
        .filter(tag => !tag.isCW)
        .map(curry(writeTagPage)), queueSize));
}

function writeTagPage(tag) {
    const { things } = tag;

    return writePage([C.TAG_DIRECTORY, tag.directory], {
        title: tag.name,
        theme: getThemeString(tag),

        main: {
            classes: ['top-index'],
            content: fixWS`
                <h1>${tag.name}</h1>
                <p class="quick-info">(Appears in ${s(things.length, 'cover art')})</p>
                <div class="grid-listing">
                    ${getGridHTML({
                        entries: things.map(item => ({item})),
                        srcFn: thing => (thing.album
                            ? getTrackCover(thing)
                            : getAlbumCover(thing)),
                        hrefFn: thing => (thing.album
                            ? `${C.TRACK_DIRECTORY}/${thing.directory}/`
                            : `${C.ALBUM_DIRECTORY}/${thing.directory}`)
                    })}
                </div>
            `
        },

        nav: {
            links: [
                ['./', wikiInfo.shortName],
                wikiInfo.features.listings && [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                [null, 'Tag:'],
                [`${C.TAG_DIRECTORY}/${tag.directory}/`, tag.name]
            ]
        }
    });
}

// This function is terri8le. Sorry!
function getContributionString({ what }) {
    return what
        ? what.replace(/\[(.*?)\]/g, (match, name) =>
            trackData.some(track => track.name === name)
                ? `<i><a href="${C.TRACK_DIRECTORY}/${trackData.find(track => track.name === name).directory}/">${name}</a></i>`
                : `<i>${name}</i>`)
        : '';
}

function getLinkedTrack(ref) {
    if (!ref) return null;

    if (ref.includes('track:')) {
        ref = ref.replace('track:', '');
        return trackData.find(track => track.directory === ref);
    }

    const match = ref.match(/\S:(.*)/);
    if (match) {
        const dir = match[1];
        return trackData.find(track => track.directory === dir);
    }

    let track;

    track = trackData.find(track => track.directory === ref);
    if (track) {
        return track;
    }

    track = trackData.find(track => track.name === ref);
    if (track) {
        return track;
    }

    track = trackData.find(track => track.name.toLowerCase() === ref.toLowerCase());
    if (track) {
        console.warn(`\x1b[33mBad capitalization:\x1b[0m`);
        console.warn(`\x1b[31m- ${ref}\x1b[0m`);
        console.warn(`\x1b[32m+ ${track.name}\x1b[0m`);
        return track;
    }

    return null;
}

function getLinkedAlbum(ref) {
    if (!ref) return null;
    ref = ref.replace('album:', '');
    let album;
    album = albumData.find(album => album.directory === ref);
    if (!album) album = albumData.find(album => album.name === ref);
    if (!album) {
        album = albumData.find(album => album.name.toLowerCase() === ref.toLowerCase());
        if (album) {
            console.warn(`\x1b[33mBad capitalization:\x1b[0m`);
            console.warn(`\x1b[31m- ${ref}\x1b[0m`);
            console.warn(`\x1b[32m+ ${album.name}\x1b[0m`);
            return album;
        }
    }
    return album;
}

function getLinkedGroup(ref) {
    if (!ref) return null;
    ref = ref.replace('group:', '');
    let group;
    group = groupData.find(group => group.directory === ref);
    if (!group) group = groupData.find(group => group.name === ref);
    if (!group) {
        group = groupData.find(group => group.name.toLowerCase() === ref.toLowerCase());
        if (group) {
            console.warn(`\x1b[33mBad capitalization:\x1b[0m`);
            console.warn(`\x1b[31m- ${ref}\x1b[0m`);
            console.warn(`\x1b[32m+ ${group.name}\x1b[0m`);
            return group;
        }
    }
    return group;
}

function getLinkedArtist(ref) {
    if (!ref) return null;
    ref = ref.replace('artist:', '');

    let artist = artistData.find(artist => C.getArtistDirectory(artist.name) === ref);
    if (artist) {
        return artist;
    }

    artist = artistData.find(artist => artist.name === ref);
    if (artist) {
        return artist;
    }

    return null;
}

function getLinkedFlash(ref) {
    if (!ref) return null;
    ref = ref.replace('flash:', '');
    return flashData?.find(flash => flash.directory === ref);
}

function getLinkedTag(ref) {
    if (!ref) return null;

    ref = ref.replace('tag:', '');

    let tag = tagData.find(tag => tag.directory === ref);
    if (tag) {
        return tag;
    }

    if (ref.startsWith('cw: ')) {
        ref = ref.slice(4);
    }

    tag = tagData.find(tag => tag.name === ref);
    if (tag) {
        return tag;
    }

    return null;
}

function getArtistString(artists, showIcons = false) {
    return joinNoOxford(artists.map(({ who, what }) => {
        if (!who) console.log(artists);
        const { urls, directory, name } = who;
        return (
            `<a href="${C.ARTIST_DIRECTORY}/${directory}/">${name}</a>` +
            (what ? ` (${getContributionString({what})})` : '') +
            (showIcons && urls.length ? ` <span class="icons">(${urls.map(iconifyURL).join(', ')})</span>` : '')
        );
    }));
}

// Graciously stolen from https://stackoverflow.com/a/54071699! ::::)
// in: r,g,b in [0,1], out: h in [0,360) and s,l in [0,1]
function rgb2hsl(r,g,b) {
    let a=Math.max(r,g,b), n=a-Math.min(r,g,b), f=(1-Math.abs(a+a-n-1));
    let h= n && ((a==r) ? (g-b)/n : ((a==g) ? 2+(b-r)/n : 4+(r-g)/n));
    return [60*(h<0?h+6:h), f ? n/f : 0, (a+a-n)/2];
}

function getColorVariables(color) {
    if (!color) {
        color = wikiInfo.color;
    }

    const [ r, g, b ] = color.slice(1)
        .match(/[0-9a-fA-F]{2,2}/g)
        .slice(0, 3)
        .map(val => parseInt(val, 16) / 255);
    const [ h, s, l ] = rgb2hsl(r, g, b);
    const dim = `hsl(${Math.round(h)}deg, ${Math.round(s * 50)}%, ${Math.round(l * 80)}%)`;

    return [
        `--primary-color: ${color}`,
        `--dim-color: ${dim}`
    ];
}

function getLinkThemeString(thing) {
    return getColorVariables(thing.color).join('; ');
}

function getThemeString(thing, additionalVariables = []) {
    const variables = [
        ...getColorVariables(thing.color),
        ...additionalVariables
    ].filter(Boolean);

    return fixWS`
        ${variables.length && fixWS`
            :root {
                ${variables.map(line => line + ';').join('\n')}
            }
        `}
    `;
}

function getFlashDirectory(flash) {
    // const kebab = getKebabCase(flash.name.replace('[S] ', ''));
    // return flash.page + (kebab ? '-' + kebab : '');
    // return '' + flash.page;
    return '' + flash.directory;
}

function getTagDirectory({name}) {
    return C.getKebabCase(name);
}

function getAlbumListTag(album) {
    if (album.directory === C.UNRELEASED_TRACKS_DIRECTORY) {
        return 'ul';
    } else {
        return 'ol';
    }
}

function fancifyURL(url, {album = false} = {}) {
    return fixWS`<a href="${url}" class="nowrap">${
        url.includes('bandcamp.com') ? 'Bandcamp' :
        (
            url.includes('music.solatrus.com')
        ) ? `Bandcamp (${new URL(url).hostname})` :
        (
            url.includes('types.pl')
        ) ? `Mastodon (${new URL(url).hostname})` :
        url.includes('youtu') ? (album ? (
            url.includes('list=') ? 'YouTube (Playlist)' : 'YouTube (Full Album)'
        ) : 'YouTube') :
        url.includes('soundcloud') ? 'SoundCloud' :
        url.includes('tumblr.com') ? 'Tumblr' :
        url.includes('twitter.com') ? 'Twitter' :
        url.includes('deviantart.com') ? 'DeviantArt' :
        url.includes('wikipedia.org') ? 'Wikipedia' :
        url.includes('poetryfoundation.org') ? 'Poetry Foundation' :
        url.includes('instagram.com') ? 'Instagram' :
        url.includes('patreon.com') ? 'Patreon' :
        new URL(url).hostname
    }</a>`;
}

function fancifyFlashURL(url, flash) {
    return `<span class="nowrap">${fancifyURL(url)}` + (
        url.includes('homestuck.com') ? ` (${isNaN(Number(flash.page)) ? 'secret page' : `page ${flash.page}`})` :
        url.includes('bgreco.net') ? ` (HQ audio)` :
        url.includes('youtu') ? ` (on any device)` :
        ''
    ) + `</span>`;
}

function iconifyURL(url) {
    const [ id, msg ] = (
        url.includes('bandcamp.com') ? ['bandcamp', 'Bandcamp'] :
        (
            url.includes('music.solatrus.com')
        ) ? ['bandcamp', `Bandcamp (${new URL(url).hostname})`] :
        (
            url.includes('types.pl')
        ) ? ['mastodon', `Mastodon (${new URL(url).hostname})`] :
        url.includes('youtu') ? ['youtube', 'YouTube'] :
        url.includes('soundcloud') ? ['soundcloud', 'SoundCloud'] :
        url.includes('tumblr.com') ? ['tumblr', 'Tumblr'] :
        url.includes('twitter.com') ? ['twitter', 'Twitter'] :
        url.includes('deviantart.com') ? ['deviantart', 'DeviantArt'] :
        url.includes('instagram.com') ? ['instagram', 'Instagram'] :
        ['globe', `External (${new URL(url).hostname})`]
    );
    return fixWS`<a href="${url}" class="icon"><svg><title>${msg}</title><use href="${C.STATIC_DIRECTORY}/icons.svg#icon-${id}"></use></svg></a>`;
}

function chronologyLinks(currentTrack, {
    mapProperty,
    toArtist,
    filters, // {property, toArtist}
    headingWord,
    sourceData = justEverythingMan
}) {
    const artists = Array.from(new Set(filters.flatMap(({ mapProperty, toArtist }) => currentTrack[mapProperty] && currentTrack[mapProperty].map(toArtist))));
    if (artists.length > 8) {
        return `<div class="chronology">(See artist pages for chronology info!)</div>`;
    }
    return artists.map(artist => {
        const releasedThings = sourceData.filter(thing => {
            const album = albumData.includes(thing) ? thing : thing.album;
            if (album && album.directory === C.UNRELEASED_TRACKS_DIRECTORY) {
                return false;
            }

            return filters.some(({ mapProperty, toArtist }) => (
                thing[mapProperty] &&
                thing[mapProperty].map(toArtist).includes(artist)
            ));
        });
        const index = releasedThings.indexOf(currentTrack);

        if (index === -1) return '';

        const previous = releasedThings[index - 1];
        const next = releasedThings[index + 1];
        const parts = [
            previous && `<a href="${getHrefOfAnythingMan(previous)}" title="${previous.name}">Previous</a>`,
            next && `<a href="${getHrefOfAnythingMan(next)}" title="${next.name}">Next</a>`
        ].filter(Boolean);

        const heading = `${th(index + 1)} ${headingWord} by <a href="${C.ARTIST_DIRECTORY}/${artist.directory}/">${artist.name}</a>`;

        return fixWS`
            <div class="chronology">
                <span class="heading">${heading}</span>
                ${parts.length && `<span class="buttons">(${parts.join(', ')})</span>`}
            </div>
        `;
    }).filter(Boolean).join('\n');
}

function generateAlbumNavLinks(album, currentTrack = null) {
    if (album.tracks.length <= 1) {
        return '';
    }

    const index = currentTrack && album.tracks.indexOf(currentTrack)
    const previous = currentTrack && album.tracks[index - 1]
    const next = currentTrack && album.tracks[index + 1]

    const [ previousLine, nextLine, randomLine ] = [
        previous && `<a href="${C.TRACK_DIRECTORY}/${previous.directory}/" id="previous-button" title="${previous.name}">Previous</a>`,
        next && `<a href="${C.TRACK_DIRECTORY}/${next.directory}/" id="next-button" title="${next.name}">Next</a>`,
        `<a href="${C.JS_DISABLED_DIRECTORY}/" data-random="track-in-album" id="random-button">${currentTrack ? 'Random' : 'Random Track'}</a>`
    ];

    if (previousLine || nextLine) {
        return `(${[previousLine, nextLine].filter(Boolean).join(', ')}<span class="js-hide-until-data">, ${randomLine}</span>)`;
    } else {
        return `<span class="js-hide-until-data">(${randomLine})</span>`;
    }
}

function generateAlbumChronologyLinks(album, currentTrack = null) {
    return [
        currentTrack && chronologyLinks(currentTrack, {
            headingWord: 'track',
            sourceData: trackData,
            filters: [
                {
                    mapProperty: 'artists',
                    toArtist: ({ who }) => who
                },
                {
                    mapProperty: 'contributors',
                    toArtist: ({ who }) => who
                }
            ]
        }),
        chronologyLinks(currentTrack || album, {
            headingWord: 'cover art',
            sourceData: justEverythingSortedByArtDateMan,
            filters: [
                {
                    mapProperty: 'coverArtists',
                    toArtist: ({ who }) => who
                }
            ]
        })
    ].filter(Boolean).join('\n');
}

function generateSidebarForAlbum(album, currentTrack = null) {
    const trackToListItem = track => `<li ${classes(track === currentTrack && 'current')}><a href="${C.TRACK_DIRECTORY}/${track.directory}/">${track.name}</a></li>`;
    const listTag = getAlbumListTag(album);
    return {content: fixWS`
        <h1><a href="${C.ALBUM_DIRECTORY}/${album.directory}/">${album.name}</a></h1>
        ${album.usesGroups ? fixWS`
            <dl>
                ${album.tracks.flatMap((track, i, arr) => [
                    (i > 0 && track.group !== arr[i - 1].group) && `</${listTag}></dd>`,
                    (i === 0 || track.group !== arr[i - 1].group) && fixWS`
                        ${track.group && fixWS`
                            <dt style="${getLinkThemeString(track)}" ${classes(currentTrack && track.group === currentTrack.group && 'current')}>
                                <a href="${C.TRACK_DIRECTORY}/${track.directory}/">${track.group}</a>
                                ${listTag === 'ol' ? `(${i + 1}&ndash;${arr.length - arr.slice().reverse().findIndex(t => t.group === track.group)})` : `<!-- (here: track number range) -->`}
                            </dt>
                        `}
                        <dd style="${getLinkThemeString(track)}"><${listTag === 'ol' ? `ol start="${i + 1}"` : listTag}>
                    `,
                    (!currentTrack || track.group === currentTrack.group) && trackToListItem(track),
                    i === arr.length && `</${listTag}></dd>`
                ].filter(Boolean)).join('\n')}
            </dl>
        ` : fixWS`
            <${listTag}>
                ${album.tracks.map(trackToListItem).join('\n')}
            </${listTag}>
        `}
    `};
}

function generateSidebarRightForAlbum(album, currentTrack = null) {
    if (!wikiInfo.features.groupUI) {
        return null;
    }

    const { groups } = album;
    if (groups.length) {
        return {
            collapse: false,
            multiple: groups.map(group => {
                const index = group.albums.indexOf(album);
                const next = group.albums[index + 1];
                const previous = group.albums[index - 1];
                return {group, next, previous};
            }).map(({group, next, previous}) => fixWS`
                <h1><a href="${C.GROUP_DIRECTORY}/${group.directory}/">${group.name}</a></h1>
                ${!currentTrack && transformMultiline(group.descriptionShort)}
                ${group.urls.length && `<p>Visit on ${joinNoOxford(group.urls.map(fancifyURL), 'or')}.</p>`}
                ${!currentTrack && fixWS`
                    ${next && `<p class="group-chronology-link">Next: <a href="${C.ALBUM_DIRECTORY}/${next.directory}/" style="${getLinkThemeString(next)}">${next.name}</a></p>`}
                    ${previous && `<p class="group-chronology-link">Previous: <a href="${C.ALBUM_DIRECTORY}/${previous.directory}/" style="${getLinkThemeString(previous)}">${previous.name}</a></p>`}
                `}
            `)
        };
    };
}

function generateSidebarForGroup(isGallery = false, currentGroup = null) {
    if (!wikiInfo.features.groupUI) {
        return null;
    }

    return {
        content: fixWS`
            <h1>Groups</h1>
            <dl>
                ${groupData.filter(x => x.isCategory).map(category => [
                    fixWS`
                        <dt ${classes(currentGroup && category === currentGroup.category && 'current')}>
                            <a href="${C.GROUP_DIRECTORY}/${groupData.find(x => x.isGroup && x.category === category).directory}/${isGallery ? 'gallery/' : ''}" style="${getLinkThemeString(category)}">${category.name}</a>
                        </dt>
                        <dd><ul>
                            ${category.groups.map(group => fixWS`
                                <li ${classes(group === currentGroup && 'current')} style="${getLinkThemeString(group)}">
                                    <a href="${C.GROUP_DIRECTORY}/${group.directory}/${isGallery && 'gallery/'}">${group.name}</a>
                                </li>
                            `).join('\n')}
                        </ul></dd>
                    `
                ]).join('\n')}
            </dl>
        `
    };
}

function writeGroupPages() {
    return progressPromiseAll(`Writing group pages.`, queue(groupData.filter(x => x.isGroup).map(curry(writeGroupPage)), queueSize));
}

async function writeGroupPage(group) {
    const releasedAlbums = group.albums.filter(album => album.directory !== C.UNRELEASED_TRACKS_DIRECTORY);
    const releasedTracks = releasedAlbums.flatMap(album => album.tracks);
    const totalDuration = getTotalDuration(releasedTracks);

    const groups = groupData.filter(x => x.isGroup);
    const index = groups.indexOf(group);
    const previous = groups[index - 1];
    const next = groups[index + 1];

    const generateNextPrevious = isGallery => [
        previous && `<a href="${C.GROUP_DIRECTORY}/${previous.directory}/${isGallery ? 'gallery/' : ''}" id="previous-button" title="${previous.name}">Previous</a>`,
        next && `<a href="${C.GROUP_DIRECTORY}/${next.directory}/${isGallery ? 'gallery/' : ''}" id="next-button" title="${next.name}">Next</a>`
    ].filter(Boolean).join(', ');

    const npInfo = generateNextPrevious(false);
    const npGallery = generateNextPrevious(true);

    await writePage([C.GROUP_DIRECTORY, group.directory], {
        title: group.name,
        theme: getThemeString(group),
        main: {
            content: fixWS`
                <h1>${group.name}</h1>
                ${group.urls.length && `<p>Visit on ${joinNoOxford(group.urls.map(fancifyURL), 'or')}.</p>`}
                <blockquote>
                    ${transformMultiline(group.description)}
                </blockquote>
                <h2>Albums</h2>
                <p>View <a href="${C.GROUP_DIRECTORY}/${group.directory}/gallery/">album gallery</a>! Or browse the list:</p>
                <ul>
                    ${group.albums.map(album => fixWS`
                        <li>
                            (${album.date.getFullYear()})
                            <a href="${C.ALBUM_DIRECTORY}/${album.directory}/" style="${getLinkThemeString(album)}">${album.name}</a>
                        </li>
                    `).join('\n')}
                </ul>
            `
        },
        sidebarLeft: generateSidebarForGroup(false, group),
        nav: (wikiInfo.features.groupUI ? {
            links: [
                ['./', wikiInfo.shortName],
                wikiInfo.features.listings && [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                [null, 'Group:'],
                [`${C.GROUP_DIRECTORY}/${group.directory}/`, group.name],
                [null, `(${[
                    `<a href="${C.GROUP_DIRECTORY}/${group.directory}/" class="current">Info</a>`,
                    `<a href="${C.GROUP_DIRECTORY}/${group.directory}/gallery/">Gallery</a>`
                ].join(', ') + (npInfo.length ? '; ' + npInfo : '')})`]
            ]
        } : {simple: true})
    });

    await writePage([C.GROUP_DIRECTORY, group.directory, 'gallery'], {
        title: `${group.name} - Gallery`,
        theme: getThemeString(group),
        main: {
            classes: ['top-index'],
            content: fixWS`
                <h1>${group.name} - Gallery</h1>
                <p class="quick-info"><b>${releasedTracks.length}</b> track${releasedTracks.length === 1 ? '' : 's'} across <b>${releasedAlbums.length}</b> album${releasedAlbums.length === 1 ? '' : 's'}, totaling <b>~${getDurationString(totalDuration)}</b> ${totalDuration > 3600 ? 'hours' : 'minutes'}.</p>
                ${wikiInfo.features.groupUI && wikiInfo.features.listings && `<p class="quick-info">(<a href="${C.LISTING_DIRECTORY}/groups/by-category/">Choose another group to filter by!</a>)</p>`}
                <div class="grid-listing">
                    ${getGridHTML({
                        entries: C.sortByDate(group.albums.map(item => ({item}))).reverse(),
                        srcFn: getAlbumCover,
                        hrefFn: album => `${C.ALBUM_DIRECTORY}/${album.directory}/`,
                        details: true
                    })}
                </div>
            `
        },
        sidebarLeft: generateSidebarForGroup(true, group),
        nav: (wikiInfo.features.groupUI ? {
            links: [
                ['./', wikiInfo.shortName],
                wikiInfo.features.listings && [`${C.LISTING_DIRECTORY}/`, 'Listings'],
                [null, 'Group:'],
                [`${C.GROUP_DIRECTORY}/${group.directory}/`, group.name],
                [null, `(${[
                    `<a href="${C.GROUP_DIRECTORY}/${group.directory}/">Info</a>`,
                    `<a href="${C.GROUP_DIRECTORY}/${group.directory}/gallery/" class="current">Gallery</a>`
                ].join(', ') + (npGallery.length ? '; ' + npGallery : '')})`]
            ]
        } : {simple: true})
    });
}

function getHrefOfAnythingMan(anythingMan) {
    return (
        albumData.includes(anythingMan) ? C.ALBUM_DIRECTORY :
        trackData.includes(anythingMan) ? C.TRACK_DIRECTORY :
        flashData?.includes(anythingMan) ? C.FLASH_DIRECTORY :
        'idk-bud'
    ) + '/' + (
        anythingMan.directory
    ) + '/';
}

function getAlbumCover(album) {
    const file = 'cover.jpg';
    return `${C.MEDIA_DIRECTORY}/${C.MEDIA_ALBUM_ART_DIRECTORY}/${album.directory}/${file}`;
}
function getTrackCover(track) {
    // Some al8ums don't have any track art at all, and in those, every track
    // just inherits the al8um's own cover art.
    if (track.coverArtists === null) {
        return getAlbumCover(track.album);
    } else {
        const file = `${track.directory}.jpg`;
        return `${C.MEDIA_DIRECTORY}/${C.MEDIA_ALBUM_ART_DIRECTORY}/${track.album.directory}/${file}`;
    }
}
function getFlashCover(flash) {
    const file = `${getFlashDirectory(flash)}.${flash.jiff === 'Yeah' ? 'gif' : 'jpg'}`;
    return `${C.MEDIA_DIRECTORY}/${C.MEDIA_FLASH_ART_DIRECTORY}/${file}`;
}

function getFlashLink(flash) {
    return `https://homestuck.com/story/${flash.page}`;
}

function getFlashLinkHTML(flash, name = null) {
    if (!name) {
        name = flash.name;
    }
    return `<a href="${C.FLASH_DIRECTORY}/${getFlashDirectory(flash)}/" title="Page ${flash.page}" style="${getLinkThemeString(flash)}">${name}</a>`;
}

function rebaseURLs(directory, html) {
    if (directory === '') {
        return html;
    }
    return html.replace(/(href|src|data-original)="(.*?)"/g, (match, attr, url) => {
        if (url.startsWith('#')) {
            return `${attr}="${url}"`;
        }

        try {
            new URL(url);
            // no error: it's a full url
        } catch (error) {
            // caught an error: it's a component!
            url = path.relative(directory, path.join(outputPath, url));
        }
        return `${attr}="${url}"`;
    }).replace(/url\("(.*?)"\)/g, (match, url) => {
        // same as above but for CSS url("...")-style values!
        try {
            new URL(url);
        } catch (error) {
            url = path.relative(directory, path.join(outputPath, url));
        }
        return `url("${url}")`;
    });
}

function classes(...args) {
    const values = args.filter(Boolean);
    // return values.length ? ` class="${values.join(' ')}"` : '';
    return `class="${values.join(' ')}"`;
}

async function main() {
    const miscOptions = await parseOptions(process.argv.slice(2), {
        // Data files for the site, including flash, artist, and al8um data,
        // and like a jillion other things too. Pretty much everything which
        // makes an individual wiki what it is goes here!
        'data': {
            type: 'value'
        },

        // Static media will 8e referenced in the site here! The contents are
        // categorized; check out MEDIA_DIRECTORY and rel8ted constants in
        // common/common.js. (This gets symlinked into the --data directory.)
        'media': {
            type: 'value'
        },

        // This is the output directory. It's the one you'll upload online with
        // rsync or whatever when you're pushing an upd8, and also the one
        // you'd archive if you wanted to make a 8ackup of the whole dang
        // site. Just keep in mind that the gener8ted result will contain a
        // couple symlinked directories, so if you're uploading, you're pro8a8ly
        // gonna want to resolve those yourself.
        'out': {
            type: 'value'
        },

        'queue-size': {
            type: 'value',
            validate(size) {
                if (parseInt(size) !== parseFloat(size)) return 'an integer';
                if (parseInt(size) < 0) return 'a counting number or zero';
                return true;
            }
        },
        queue: {alias: 'queue-size'},

        [parseOptions.handleUnknown]: () => {}
    });

    dataPath = miscOptions.data || process.env.HSMUSIC_DATA;
    mediaPath = miscOptions.media || process.env.HSMUSIC_MEDIA;
    outputPath = miscOptions.out || process.env.HSMUSIC_OUT;

    {
        let errored = false;
        const error = (cond, msg) => {
            if (cond) {
                console.error(`\x1b[31;1m${msg}\x1b[0m`);
                errored = true;
            }
        };
        error(!dataPath,   `Expected --data option or HSMUSIC_DATA to be set`);
        error(!mediaPath,  `Expected --media option or HSMUSIC_MEDIA to be set`);
        error(!outputPath, `Expected --out option or HSMUSIC_OUT to be set`);
        if (errored) {
            return;
        }
    }

    wikiInfo = await processWikiInfoFile(path.join(dataPath, WIKI_INFO_FILE));
    if (wikiInfo.error) {
        console.log(`\x1b[31;1m${wikiInfo.error}\x1b[0m`);
        return;
    }

    homepageInfo = await processHomepageInfoFile(path.join(dataPath, HOMEPAGE_INFO_FILE));

    if (homepageInfo.error) {
        console.log(`\x1b[31;1m${homepageInfo.error}\x1b[0m`);
        return;
    }

    {
        const errors = homepageInfo.rows.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }
    }

    // 8ut wait, you might say, how do we know which al8um these data files
    // correspond to???????? You wouldn't dare suggest we parse the actual
    // paths returned 8y this function, which ought to 8e of effectively
    // unknown format except for their purpose as reada8le data files!?
    // To that, I would say, yeah, you're right. Thanks a 8unch, my projection
    // of "you". We're going to read these files later, and contained within
    // will 8e the actual directory names that the data correspond to. Yes,
    // that's redundant in some ways - we COULD just return the directory name
    // in addition to the data path, and duplicating that name within the file
    // itself suggests we 8e careful to avoid mismatching it - 8ut doing it
    // this way lets the data files themselves 8e more porta8le (meaning we
    // could store them all in one folder, if we wanted, and this program would
    // still output to the correct al8um directories), and also does make the
    // function's signature simpler (an array of strings, rather than some kind
    // of structure containing 8oth data file paths and output directories).
    // This is o8jectively a good thing, 8ecause it means the function can stay
    // truer to its name, and have a narrower purpose: it doesn't need to
    // concern itself with where we *output* files, or whatever other reasons
    // we might (hypothetically) have for knowing the containing directory.
    // And, in the strange case where we DO really need to know that info, we
    // callers CAN use path.dirname to find out that data. 8ut we'll 8e
    // avoiding that in our code 8ecause, again, we want to avoid assuming the
    // format of the returned paths here - they're only meant to 8e used for
    // reading as-is.
    const albumDataFiles = await findAlbumDataFiles(path.join(dataPath, C.DATA_ALBUM_DIRECTORY));

    // Technically, we could do the data file reading and output writing at the
    // same time, 8ut that kinda makes the code messy, so I'm not 8othering
    // with it.
    albumData = await progressPromiseAll(`Reading & processing album files.`, albumDataFiles.map(processAlbumDataFile));

    {
        const errors = albumData.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }
    }

    C.sortByDate(albumData);

    artistData = await processArtistDataFile(path.join(dataPath, ARTIST_DATA_FILE));
    if (artistData.error) {
        console.log(`\x1b[31;1m${artistData.error}\x1b[0m`);
        return;
    }

    {
        const errors = artistData.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }
    }

    trackData = C.getAllTracks(albumData);

    if (wikiInfo.features.flashesAndGames) {
        flashData = await processFlashDataFile(path.join(dataPath, FLASH_DATA_FILE));
        if (flashData.error) {
            console.log(`\x1b[31;1m${flashData.error}\x1b[0m`);
            return;
        }

        const errors = artistData.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }
    }

    artistNames = Array.from(new Set([
        ...artistData.filter(artist => !artist.alias).map(artist => artist.name),
        ...[
            ...albumData.flatMap(album => [
                ...album.artists || [],
                ...album.coverArtists || [],
                ...album.tracks.flatMap(track => [
                    ...track.artists,
                    ...track.coverArtists || [],
                    ...track.contributors || []
                ])
            ]),
            ...(flashData?.flatMap(flash => [
                ...flash.contributors || []
            ]) || [])
        ].map(contribution => contribution.who)
    ]));

    tagData = await processTagDataFile(path.join(dataPath, TAG_DATA_FILE));
    if (tagData.error) {
        console.log(`\x1b[31;1m${tagData.error}\x1b[0m`);
        return;
    }

    {
        const errors = tagData.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }
    }

    groupData = await processGroupDataFile(path.join(dataPath, GROUP_DATA_FILE));
    if (groupData.error) {
        console.log(`\x1b[31;1m${groupData.error}\x1b[0m`);
        return;
    }

    {
        const errors = groupData.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }
    }

    staticPageData = await processStaticPageDataFile(path.join(dataPath, STATIC_PAGE_DATA_FILE));
    if (staticPageData.error) {
        console.log(`\x1b[31;1m${staticPageData.error}\x1b[0m`);
        return;
    }

    {
        const errors = staticPageData.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }
    }

    if (wikiInfo.features.news) {
        newsData = await processNewsDataFile(path.join(dataPath, NEWS_DATA_FILE));
        if (newsData.error) {
            console.log(`\x1b[31;1m${newsData.error}\x1b[0m`);
            return;
        }

        const errors = newsData.filter(obj => obj.error);
        if (errors.length) {
            for (const error of errors) {
                console.log(`\x1b[31;1m${error.error}\x1b[0m`);
            }
            return;
        }

        C.sortByDate(newsData);
        newsData.reverse();
    }

    {
        const tagNames = new Set([...trackData, ...albumData].flatMap(thing => thing.artTags));

        for (let { name, isCW } of tagData) {
            if (isCW) {
                name = 'cw: ' + name;
            }
            tagNames.delete(name);
        }

        if (tagNames.size) {
            for (const name of Array.from(tagNames).sort()) {
                console.log(`\x1b[33;1m- Missing tag: "${name}"\x1b[0m`);
            }
            return;
        }
    }

    artistNames.sort((a, b) => a.toLowerCase() < b.toLowerCase() ? -1 : a.toLowerCase() > b.toLowerCase() ? 1 : 0);

    justEverythingMan = C.sortByDate(albumData.concat(trackData, flashData?.filter(flash => !flash.act8r8k) || []));
    justEverythingSortedByArtDateMan = C.sortByArtDate(justEverythingMan.slice());
    // console.log(JSON.stringify(justEverythingSortedByArtDateMan.map(getHrefOfAnythingMan), null, 2));

    {
        let buffer = [];
        const clearBuffer = function() {
            if (buffer.length) {
                for (const entry of buffer.slice(0, -1)) {
                    console.log(`\x1b[2m... ${entry.name} ...\x1b[0m`);
                }
                const lastEntry = buffer[buffer.length - 1];
                console.log(`\x1b[2m... \x1b[0m${lastEntry.name}\x1b[0;2m ...\x1b[0m`);
                buffer = [];
            }
        };
        const showWhere = (name, color) => {
            const where = justEverythingMan.filter(thing => [
                ...thing.coverArtists || [],
                ...thing.contributors || [],
                ...thing.artists || []
            ].some(({ who }) => who === name));
            for (const thing of where) {
                console.log(`\x1b[${color}m- ` + (thing.album ? `(\x1b[1m${thing.album.name}\x1b[0;${color}m)` : '') + ` \x1b[1m${thing.name}\x1b[0m`);
            }
        };
        let CR4SH = false;
        for (let name of artistNames) {
            const entry = artistData.find(entry => entry.name === name || entry.name.toLowerCase() === name.toLowerCase());
            if (!entry) {
                clearBuffer();
                console.log(`\x1b[31mMissing entry for artist "\x1b[1m${name}\x1b[0;31m"\x1b[0m`);
                showWhere(name, 31);
                CR4SH = true;
            } else if (entry.alias) {
                console.log(`\x1b[33mArtist "\x1b[1m${name}\x1b[0;33m" should be named "\x1b[1m${entry.alias}\x1b[0;33m"\x1b[0m`);
                showWhere(name, 33);
                CR4SH = true;
            } else if (entry.name !== name) {
                console.log(`\x1b[33mArtist "\x1b[1m${name}\x1b[0;33m" should be named "\x1b[1m${entry.name}\x1b[0;33m"\x1b[0m`);
                showWhere(name, 33);
                CR4SH = true;
            } else {
                buffer.push(entry);
                if (buffer.length > 3) {
                    buffer.shift();
                }
            }
        }
        if (CR4SH) {
            return;
        } else {
            console.log(`All artist data is good!`);
        }
    }

    {
        const directories = [];
        for (const { directory, name } of albumData) {
            if (directories.includes(directory)) {
                console.log(`\x1b[31;1mDuplicate album directory "${directory}" (${name})\x1b[0m`);
                return;
            }
            directories.push(directory);
        }
    }

    {
        const directories = [];
        const where = {};
        for (const { directory, album } of trackData) {
            if (directories.includes(directory)) {
                console.log(`\x1b[31;1mDuplicate track directory "${directory}"\x1b[0m`);
                console.log(`Shows up in:`);
                console.log(`- ${album.name}`);
                console.log(`- ${where[directory].name}`);
                return;
            }
            directories.push(directory);
            where[directory] = album;
        }
    }

    {
        const artists = [];
        const artistsLC = [];
        for (const name of artistNames) {
            if (!artists.includes(name) && artistsLC.includes(name.toLowerCase())) {
                const other = artists.find(oth => oth.toLowerCase() === name.toLowerCase());
                console.log(`\x1b[31;1mMiscapitalized artist name: ${name}, ${other}\x1b[0m`);
                return;
            }
            artists.push(name);
            artistsLC.push(name.toLowerCase());
        }
    }

    {
        for (const { references, name, album } of trackData) {
            for (const ref of references) {
                // Skip these, for now.
                if (ref.includes("by")) {
                    continue;
                }
                if (!getLinkedTrack(ref)) {
                    console.warn(`\x1b[33mTrack not found "${ref}" in ${name} (${album.name})\x1b[0m`);
                }
            }
        }
    }

    contributionData = Array.from(new Set([
        ...trackData.flatMap(track => [...track.artists || [], ...track.contributors || [], ...track.coverArtists || []]),
        ...albumData.flatMap(album => [...album.artists || [], ...album.coverArtists || [], ...album.wallpaperArtists || []]),
        ...(flashData?.flatMap(flash => [...flash.contributors || []]) || [])
    ]));

    // Now that we have all the data, resolve references all 8efore actually
    // gener8ting any of the pages, 8ecause page gener8tion is going to involve
    // accessing these references a lot, and there's no reason to resolve them
    // more than once. (We 8uild a few additional links that can't 8e cre8ted
    // at initial data processing time here too.)

    const filterNull = (parent, key) => {
        for (const obj of parent) {
            const array = obj[key];
            for (let i = 0; i < array.length; i++) {
                if (!Boolean(array[i])) {
                    const prev = array[i - 1] && array[i - 1].name;
                    const next = array[i + 1] && array[i + 1].name;
                    console.log(`\x1b[33mUnexpected null in ${obj.name} (${key}) - prev: ${prev}, next: ${next}\x1b[0m`);
                }
            }
            array.splice(0, array.length, ...array.filter(Boolean));
        }
    };

    trackData.forEach(track => mapInPlace(track.references, getLinkedTrack));
    trackData.forEach(track => track.aka = getLinkedTrack(track.aka));
    trackData.forEach(track => mapInPlace(track.artTags, getLinkedTag));
    albumData.forEach(album => mapInPlace(album.groups, getLinkedGroup));
    albumData.forEach(album => mapInPlace(album.artTags, getLinkedTag));
    artistData.forEach(artist => artist.alias = getLinkedArtist(artist.alias));
    contributionData.forEach(contrib => contrib.who = getLinkedArtist(contrib.who));

    filterNull(trackData, 'references');
    filterNull(albumData, 'groups');

    trackData.forEach(track1 => track1.referencedBy = trackData.filter(track2 => track2.references.includes(track1)));
    groupData.forEach(group => group.albums = albumData.filter(album => album.groups.includes(group)));
    tagData.forEach(tag => tag.things = C.sortByArtDate([...albumData, ...trackData]).filter(thing => thing.artTags.includes(tag)));

    trackData.forEach(track => track.otherReleases = [
        track.aka,
        ...trackData.filter(({ aka }) => aka === track)
    ].filter(Boolean));

    if (wikiInfo.features.flashesAndGames) {
        const actlessFlashData = flashData.filter(flash => !flash.act8r8k);

        actlessFlashData.forEach(flash => mapInPlace(flash.tracks, getLinkedTrack));

        filterNull(actlessFlashData, 'tracks');

        trackData.forEach(track => track.flashes = actlessFlashData.filter(flash => flash.tracks.includes(track)));
    }

    artistData.forEach(artist => {
        const filterProp = (array, prop) => array.filter(thing => thing[prop]?.some(({ who }) => who === artist));
        const filterCommentary = array => array.filter(thing => thing.commentary && thing.commentary.replace(/<\/?b>/g, '').includes('<i>' + artist.name + ':</i>'));
        artist.tracks = {
            asArtist: filterProp(trackData, 'artists'),
            asCommentator: filterCommentary(trackData),
            asContributor: filterProp(trackData, 'contributors'),
            asCoverArtist: filterProp(trackData, 'coverArtists'),
            asAny: trackData.filter(track => (
                [...track.artists, ...track.contributors, ...track.coverArtists || []].some(({ who }) => who === artist)
            ))
        };
        artist.albums = {
            asArtist: filterProp(albumData, 'artists'),
            asCommentator: filterCommentary(albumData),
            asCoverArtist: filterProp(albumData, 'coverArtists')
        };
        if (wikiInfo.features.flashesAndGames) {
            artist.flashes = {
                asContributor: filterProp(flashData, 'contributors')
            };
        }
    });

    groupData.filter(x => x.isGroup).forEach(group => group.category = groupData.find(x => x.isCategory && x.name === group.category));
    groupData.filter(x => x.isCategory).forEach(category => category.groups = groupData.filter(x => x.isGroup && x.category === category));

    officialAlbumData = albumData.filter(album => album.groups.some(group => group.directory === C.OFFICIAL_GROUP_DIRECTORY));
    fandomAlbumData = albumData.filter(album => album.groups.every(group => group.directory !== C.OFFICIAL_GROUP_DIRECTORY));

    // Makes writing a little nicer on CPU theoretically, 8ut also costs in
    // performance right now 'cuz it'll w8 for file writes to 8e completed
    // 8efore moving on to more data processing. So, defaults to zero, which
    // disa8les the queue feature altogether.
    queueSize = +(miscOptions['queue-size'] ?? 0);

    // NOT for ena8ling or disa8ling specific features of the site!
    // This is only in charge of what general groups of files to 8uild.
    // They're here to make development quicker when you're only working
    // on some particular area(s) of the site rather than making changes
    // across all of them.
    const buildFlags = await parseOptions(process.argv.slice(2), {
        all: {type: 'flag'}, // Defaults to true if none 8elow specified.

        album: {type: 'flag'},
        artist: {type: 'flag'},
        flash: {type: 'flag'},
        group: {type: 'flag'},
        list: {type: 'flag'},
        misc: {type: 'flag'},
        news: {type: 'flag'},
        static: {type: 'flag'},
        tag: {type: 'flag'},
        track: {type: 'flag'},

        [parseOptions.handleUnknown]: () => {}
    });

    const buildAll = !Object.keys(buildFlags).length || buildFlags.all;

    await writeSymlinks();
    if (buildAll || buildFlags.misc) await writeMiscellaneousPages();
    if (buildAll || buildFlags.static) await writeStaticPages();
    if (buildAll || buildFlags.news) await writeNewsPages();
    if (buildAll || buildFlags.list) await writeListingPages();
    if (buildAll || buildFlags.tag) await writeTagPages();
    if (buildAll || buildFlags.group) await writeGroupPages();
    if (buildAll || buildFlags.album) await writeAlbumPages();
    if (buildAll || buildFlags.track) await writeTrackPages();
    if (buildAll || buildFlags.artist) await writeArtistPages();
    if (buildAll || buildFlags.flash) if (wikiInfo.features.flashesAndGames) await writeFlashPages();

    decorateTime.displayTime();

    // The single most important step.
    console.log('Written!');
}

main().catch(error => console.error(error));