summaryrefslogtreecommitdiff
path: root/src/contrib/SDL-3.2.20/build-scripts/wikiheaders.pl
blob: d4205b8ffd802c0f311906b1ffb761736100140c (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
#!/usr/bin/perl -w

# Simple DirectMedia Layer
# Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
#
# This software is provided 'as-is', without any express or implied
# warranty.  In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
#    claim that you wrote the original software. If you use this software
#    in a product, an acknowledgment in the product documentation would be
#    appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
#    misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.

use warnings;
use strict;
use File::Path;
use Text::Wrap;

$Text::Wrap::huge = 'overflow';

my $projectfullname = 'Simple Directmedia Layer';
my $projectshortname = 'SDL';
my $wikisubdir = '';
my $incsubdir = 'include';
my $readmesubdir = undef;
my $apiprefixregex = undef;
my $versionfname = 'include/SDL_version.h';
my $versionmajorregex = '\A\#define\s+SDL_MAJOR_VERSION\s+(\d+)\Z';
my $versionminorregex = '\A\#define\s+SDL_MINOR_VERSION\s+(\d+)\Z';
my $versionmicroregex = '\A\#define\s+SDL_MICRO_VERSION\s+(\d+)\Z';
my $mainincludefname = 'SDL.h';
my $selectheaderregex = '\ASDL.*?\.h\Z';
my $projecturl = 'https://libsdl.org/';
my $wikiurl = 'https://wiki.libsdl.org';
my $bugreporturl = 'https://github.com/libsdl-org/sdlwiki/issues/new';
my $srcpath = undef;
my $wikipath = undef;
my $wikireadmesubdir = 'README';
my $warn_about_missing = 0;
my $copy_direction = 0;
my $optionsfname = undef;
my $wikipreamble = undef;
my $wikiheaderfiletext = 'Defined in %fname%';
my $manpageheaderfiletext = 'Defined in %fname%';
my $manpagesymbolfilterregex = undef;
my $headercategoryeval = undef;
my $quickrefenabled = 0;
my @quickrefcategoryorder;
my $quickreftitle = undef;
my $quickrefurl = undef;
my $quickrefdesc = undef;
my $quickrefmacroregex = undef;
my $changeformat = undef;
my $manpath = undef;
my $gitrev = undef;

foreach (@ARGV) {
    $warn_about_missing = 1, next if $_ eq '--warn-about-missing';
    $copy_direction = 1, next if $_ eq '--copy-to-headers';
    $copy_direction = 1, next if $_ eq '--copy-to-header';
    $copy_direction = -1, next if $_ eq '--copy-to-wiki';
    $copy_direction = -2, next if $_ eq '--copy-to-manpages';
    $copy_direction = -3, next if $_ eq '--report-coverage-gaps';
    $copy_direction = -4, next if $_ eq '--copy-to-latex';
    if (/\A--options=(.*)\Z/) {
        $optionsfname = $1;
        next;
    } elsif (/\A--changeformat=(.*)\Z/) {
        $changeformat = $1;
        next;
    } elsif (/\A--manpath=(.*)\Z/) {
        $manpath = $1;
        next;
    } elsif (/\A--rev=(.*)\Z/) {
        $gitrev = $1;
        next;
    }
    $srcpath = $_, next if not defined $srcpath;
    $wikipath = $_, next if not defined $wikipath;
}

my $default_optionsfname = '.wikiheaders-options';
$default_optionsfname = "$srcpath/$default_optionsfname" if defined $srcpath;

if ((not defined $optionsfname) && (-f $default_optionsfname)) {
    $optionsfname = $default_optionsfname;
}

if (defined $optionsfname) {
    open OPTIONS, '<', $optionsfname or die("Failed to open options file '$optionsfname': $!\n");
    while (<OPTIONS>) {
        next if /\A\s*\#/;  # Skip lines that start with (optional whitespace, then) '#' as comments.

        chomp;
        if (/\A(.*?)\=(.*)\Z/) {
            my $key = $1;
            my $val = $2;
            $key =~ s/\A\s+//;
            $key =~ s/\s+\Z//;
            $val =~ s/\A\s+//;
            $val =~ s/\s+\Z//;
            $warn_about_missing = int($val), next if $key eq 'warn_about_missing';
            $srcpath = $val, next if $key eq 'srcpath';
            $wikipath = $val, next if $key eq 'wikipath';
            $apiprefixregex = $val, next if $key eq 'apiprefixregex';
            $projectfullname = $val, next if $key eq 'projectfullname';
            $projectshortname = $val, next if $key eq 'projectshortname';
            $wikisubdir = $val, next if $key eq 'wikisubdir';
            $incsubdir = $val, next if $key eq 'incsubdir';
            $readmesubdir = $val, next if $key eq 'readmesubdir';
            $versionmajorregex = $val, next if $key eq 'versionmajorregex';
            $versionminorregex = $val, next if $key eq 'versionminorregex';
            $versionmicroregex = $val, next if $key eq 'versionmicroregex';
            $versionfname = $val, next if $key eq 'versionfname';
            $mainincludefname = $val, next if $key eq 'mainincludefname';
            $selectheaderregex = $val, next if $key eq 'selectheaderregex';
            $projecturl = $val, next if $key eq 'projecturl';
            $wikiurl = $val, next if $key eq 'wikiurl';
            $bugreporturl = $val, next if $key eq 'bugreporturl';
            $wikipreamble = $val, next if $key eq 'wikipreamble';
            $wikiheaderfiletext = $val, next if $key eq 'wikiheaderfiletext';
            $manpageheaderfiletext = $val, next if $key eq 'manpageheaderfiletext';
            $manpagesymbolfilterregex = $val, next if $key eq 'manpagesymbolfilterregex';
            $headercategoryeval = $val, next if $key eq 'headercategoryeval';
            $quickrefenabled = int($val), next if $key eq 'quickrefenabled';
            @quickrefcategoryorder = split(/,/, $val), next if $key eq 'quickrefcategoryorder';
            $quickreftitle = $val, next if $key eq 'quickreftitle';
            $quickrefurl = $val, next if $key eq 'quickrefurl';
            $quickrefdesc = $val, next if $key eq 'quickrefdesc';
            $quickrefmacroregex = $val, next if $key eq 'quickrefmacroregex';
        }
    }
    close(OPTIONS);
}

sub escLaTeX {
    my $str = shift;
    $str =~ s/([_\#\&\^])/\\$1/g;
    return $str;
}

my $wordwrap_mode = 'mediawiki';
sub wordwrap_atom {   # don't call this directly.
    my $str = shift;
    my $retval = '';

    # wordwrap but leave links intact, even if they overflow.
    if ($wordwrap_mode eq 'mediawiki') {
        while ($str =~ s/(.*?)\s*(\[https?\:\/\/.*?\s+.*?\])\s*//ms) {
            $retval .= fill('', '', $1); # wrap it.
            $retval .= "\n$2\n";  # don't wrap it.
        }
    } elsif ($wordwrap_mode eq 'md') {
        while ($str =~ s/(.*?)\s*(\[.*?\]\(https?\:\/\/.*?\))\s*//ms) {
            $retval .= fill('', '', $1); # wrap it.
            $retval .= "\n$2\n";  # don't wrap it.
        }
    }

    return $retval . fill('', '', $str);
}

sub wordwrap_with_bullet_indent {  # don't call this directly.
    my $bullet = shift;
    my $str = shift;
    my $retval = '';

    #print("WORDWRAP BULLET ('$bullet'):\n\n$str\n\n");

    # You _can't_ (at least with Pandoc) have a bullet item with a newline in
    #  MediaWiki, so _remove_ wrapping!
    if ($wordwrap_mode eq 'mediawiki') {
        $retval = "$bullet$str";
        $retval =~ s/\n/ /gms;
        $retval =~ s/\s+$//gms;
        #print("WORDWRAP BULLET DONE:\n\n$retval\n\n");
        return "$retval\n";
    }

    my $bulletlen = length($bullet);

    # wrap it and then indent each line to be under the bullet.
    $Text::Wrap::columns -= $bulletlen;
    my @wrappedlines = split /\n/, wordwrap_atom($str);
    $Text::Wrap::columns += $bulletlen;

    my $prefix = $bullet;
    my $usual_prefix = ' ' x $bulletlen;

    foreach (@wrappedlines) {
        s/\s*\Z//;
        $retval .= "$prefix$_\n";
        $prefix = $usual_prefix;
    }

    return $retval;
}

sub wordwrap_one_paragraph {  # don't call this directly.
    my $retval = '';
    my $p = shift;
    #print "\n\n\nPARAGRAPH: [$p]\n\n\n";
    if ($p =~ s/\A([\*\-] )//) {  # bullet list, starts with "* " or "- ".
        my $bullet = $1;
        my $item = '';
        my @items = split /\n/, $p;
        foreach (@items) {
            if (s/\A([\*\-] )//) {
                $retval .= wordwrap_with_bullet_indent($bullet, $item);
                $item = '';
            }
            s/\A\s*//;
            $item .= "$_\n";   # accumulate lines until we hit the end or another bullet.
        }
        if ($item ne '') {
            $retval .= wordwrap_with_bullet_indent($bullet, $item);
        }
    } elsif ($p =~ /\A\s*\|.*\|\s*\n/) {  # Markdown table
        $retval = "$p\n";  # don't wrap it (!!! FIXME: but maybe parse by lines until we run out of table...)
    } else {
        $retval = wordwrap_atom($p) . "\n";
    }

    return $retval;
}

sub wordwrap_paragraphs {  # don't call this directly.
    my $str = shift;
    my $retval = '';
    my @paragraphs = split /\n\n/, $str;
    foreach (@paragraphs) {
        next if $_ eq '';
        $retval .= wordwrap_one_paragraph($_);
        $retval .= "\n";
    }
    return $retval;
}

my $wordwrap_default_columns = 76;
sub wordwrap {
    my $str = shift;
    my $columns = shift;

    $columns = $wordwrap_default_columns if not defined $columns;
    $columns += $wordwrap_default_columns if $columns < 0;
    $Text::Wrap::columns = $columns;

    my $retval = '';

    #print("\n\nWORDWRAP:\n\n$str\n\n\n");

    $str =~ s/\A\n+//ms;

    while ($str =~ s/(.*?)(\`\`\`.*?\`\`\`|\<syntaxhighlight.*?\<\/syntaxhighlight\>)//ms) {
        #print("\n\nWORDWRAP BLOCK:\n\n$1\n\n ===\n\n$2\n\n\n");
        $retval .= wordwrap_paragraphs($1); # wrap it.
        $retval .= "$2\n\n";  # don't wrap it.
    }

    $retval .= wordwrap_paragraphs($str);  # wrap what's left.
    $retval =~ s/\n+\Z//ms;

    #print("\n\nWORDWRAP DONE:\n\n$retval\n\n\n");
    return $retval;
}

# This assumes you're moving from Markdown (in the Doxygen data) to Wiki, which
#  is why the 'md' section is so sparse.
sub wikify_chunk {
    my $wikitype = shift;
    my $str = shift;
    my $codelang = shift;
    my $code = shift;

    #print("\n\nWIKIFY CHUNK:\n\n$str\n\n\n");

    if ($wikitype eq 'mediawiki') {
        # convert `code` things first, so they aren't mistaken for other markdown items.
        my $codedstr = '';
        while ($str =~ s/\A(.*?)\`(.*?)\`//ms) {
            my $codeblock = $2;
            $codedstr .= wikify_chunk($wikitype, $1, undef, undef);
            if (defined $apiprefixregex) {
                # Convert obvious API things to wikilinks, even inside `code` blocks.
                $codeblock =~ s/(\A|[^\/a-zA-Z0-9_])($apiprefixregex[a-zA-Z0-9_]+)/$1\[\[$2\]\]/gms;
            }
            $codedstr .= "<code>$codeblock</code>";
        }

        # Convert obvious API things to wikilinks.
        if (defined $apiprefixregex) {
            $str =~ s/(\A|[^\/a-zA-Z0-9_])($apiprefixregex[a-zA-Z0-9_]+)/$1\[\[$2\]\]/gms;
        }

        # Make some Markdown things into MediaWiki...

        # links
        $str =~ s/\[(.*?)\]\((https?\:\/\/.*?)\)/\[$2 $1\]/g;

        # bold+italic
        $str =~ s/\*\*\*(.*?)\*\*\*/'''''$1'''''/gms;

        # bold
        $str =~ s/\*\*(.*?)\*\*/'''$1'''/gms;

        # italic
        $str =~ s/\*(.*?)\*/''$1''/gms;

        # bullets
        $str =~ s/^\- /* /gm;

        $str = $codedstr . $str;

        if (defined $code) {
            $str .= "<syntaxhighlight lang='$codelang'>$code<\/syntaxhighlight>";
        }
    } elsif ($wikitype eq 'md') {
        # convert `code` things first, so they aren't mistaken for other markdown items.
        my $codedstr = '';
        while ($str =~ s/\A(.*?)(\`.*?\`)//ms) {
            my $codeblock = $2;
            $codedstr .= wikify_chunk($wikitype, $1, undef, undef);
            if (defined $apiprefixregex) {
                # Convert obvious API things to wikilinks, even inside `code` blocks,
                # BUT ONLY IF the entire code block is the API thing,
                # So something like "just call `SDL_Whatever`" will become
                # "just call [`SDL_Whatever`](SDL_Whatever)", but
                # "just call `SDL_Whatever(7)`" will not. It's just the safest
                # way to do this without resorting to wrapping things in html <code> tags.
                $codeblock =~ s/\A\`($apiprefixregex[a-zA-Z0-9_]+)\`\Z/[`$1`]($1)/gms;
            }
            $codedstr .= $codeblock;
        }

        # Convert obvious API things to wikilinks.
        if (defined $apiprefixregex) {
            $str =~ s/(\A|[^\/a-zA-Z0-9_])($apiprefixregex[a-zA-Z0-9_]+)/$1\[$2\]\($2\)/gms;
        }

        $str = $codedstr . $str;

        if (defined $code) {
            $str .= "```$codelang\n$code\n```\n";
        }
    }

    #print("\n\nWIKIFY CHUNK DONE:\n\n$str\n\n\n");

    return $str;
}

sub wikify {
    my $wikitype = shift;
    my $str = shift;
    my $retval = '';

    #print("WIKIFY WHOLE:\n\n$str\n\n\n");

    while ($str =~ s/\A(.*?)\`\`\`(.*?)\n(.*?)\n\`\`\`(\n|\Z)//ms) {
        $retval .= wikify_chunk($wikitype, $1, $2, $3);
    }
    $retval .= wikify_chunk($wikitype, $str, undef, undef);

    #print("WIKIFY WHOLE DONE:\n\n$retval\n\n\n");

    return $retval;
}


my $dewikify_mode = 'md';
my $dewikify_manpage_code_indent = 1;

sub dewikify_chunk {
    my $wikitype = shift;
    my $str = shift;
    my $codelang = shift;
    my $code = shift;

    #print("\n\nDEWIKIFY CHUNK:\n\n$str\n\n\n");

    if ($dewikify_mode eq 'md') {
        if ($wikitype eq 'mediawiki') {
            # Doxygen supports Markdown (and it just simply looks better than MediaWiki
            # when looking at the raw headers), so do some conversions here as necessary.

            # Dump obvious wikilinks.
            if (defined $apiprefixregex) {
                $str =~ s/\[\[($apiprefixregex[a-zA-Z0-9_]+)\]\]/$1/gms;
            }

            # links
            $str =~ s/\[(https?\:\/\/.*?)\s+(.*?)\]/\[$2\]\($1\)/g;

            # <code></code> is also popular.  :/
            $str =~ s/\<code>(.*?)<\/code>/`$1`/gms;

            # bold+italic
            $str =~ s/'''''(.*?)'''''/***$1***/gms;

            # bold
            $str =~ s/'''(.*?)'''/**$1**/gms;

            # italic
            $str =~ s/''(.*?)''/*$1*/gms;

            # bullets
            $str =~ s/^\* /- /gm;
        } elsif ($wikitype eq 'md') {
            # Dump obvious wikilinks. The rest can just passthrough.
            if (defined $apiprefixregex) {
                $str =~ s/\[(\`?$apiprefixregex[a-zA-Z0-9_]+\`?)\]\($apiprefixregex[a-zA-Z0-9_]+\)/$1/gms;
            }
        }

        if (defined $code) {
            $str .= "\n```$codelang\n$code\n```\n";
        }
    } elsif ($dewikify_mode eq 'manpage') {
        # make sure these can't become part of roff syntax.
        $str =~ s/\./\\[char46]/gms;
        $str =~ s/"/\\(dq/gms;
        $str =~ s/'/\\(aq/gms;

        if ($wikitype eq 'mediawiki') {
            # Dump obvious wikilinks.
            if (defined $apiprefixregex) {
                $str =~ s/\s*\[\[($apiprefixregex[a-zA-Z0-9_]+)\]\]\s*/\n.BR $1\n/gms;
            }

            # links
            $str =~ s/\[(https?\:\/\/.*?)\s+(.*?)\]/\n.URL "$1" "$2"\n/g;

            # <code></code> is also popular.  :/
            $str =~ s/\s*\<code>(.*?)<\/code>\s*/\n.BR $1\n/gms;

            # bold+italic (this looks bad, just make it bold).
            $str =~ s/\s*'''''(.*?)'''''\s*/\n.B $1\n/gms;

            # bold
            $str =~ s/\s*'''(.*?)'''\s*/\n.B $1\n/gms;

            # italic
            $str =~ s/\s*''(.*?)''\s*/\n.I $1\n/gms;

            # bullets
            $str =~ s/^\* /\n\\\(bu /gm;
        } elsif ($wikitype eq 'md') {
            # bullets
            $str =~ s/^\- /\n\\(bu /gm;
            # merge paragraphs
            $str =~ s/^[ \t]+//gm;
            $str =~ s/([^\-\n])\n([^\-\n])/$1 $2/g;
            $str =~ s/\n\n/\n.PP\n/g;

            # Dump obvious wikilinks.
            if (defined $apiprefixregex) {
                my $apr = $apiprefixregex;
                if(!($apr =~ /\A\(.*\)\Z/s)) {
                    # we're relying on the apiprefixregex having a capturing group.
                    $apr = "(" . $apr . ")";
                }
                $str =~ s/(\S*?)\[\`?($apr[a-zA-Z0-9_]+)\`?\]\($apr[a-zA-Z0-9_]+\)(\S*)\s*/\n.BR "" "$1" "$2" "$5"\n/gm;
                # handle cases like "[x](x), [y](y), [z](z)" being separated.
                while($str =~ s/(\.BR[^\n]*)\n\n\.BR/$1\n.BR/gm) {}
            }

            # links
            $str =~ s/\[(.*?)]\((https?\:\/\/.*?)\)/\n.URL "$2" "$1"\n/g;

            # <code></code> is also popular.  :/
            $str =~ s/\s*(\S*?)\`([^\n]*?)\`(\S*)\s*/\n.BR "" "$1" "$2" "$3"\n/gms;

            # bold+italic (this looks bad, just make it bold).
            $str =~ s/\s*(\S*?)\*\*\*([^\n]*?)\*\*\*(\S*)\s*/\n.BR "" "$1" "$2" "$3"\n/gms;

            # bold
            $str =~ s/\s*(\S*?)\*\*([^\n]*?)\*\*(\S*)\s*/\n.BR "" "$1" "$2" "$3"\n/gms;

            # italic
            $str =~ s/\s*(\S*?)\*([^\n]*?)\*(\S*)\s*/\n.IR "" "$1" "$2" "$3"\n/gms;
        }

        # cleanup unnecessary quotes
        $str =~ s/(\.[IB]R?)(.*?) ""\n/$1$2\n/gm;
        $str =~ s/(\.[IB]R?) "" ""(.*?)\n/$1$2\n/gm;
        $str =~ s/"(\S+)"/$1/gm;
        # cleanup unnecessary whitespace
        $str =~ s/ +\n/\n/gm;

        if (defined $code) {
            $code =~ s/\A\n+//gms;
            $code =~ s/\n+\Z//gms;
            $code =~ s/\\/\\(rs/gms;
            if ($dewikify_manpage_code_indent) {
                $str .= "\n.IP\n"
            } else {
                $str .= "\n.PP\n"
            }
            $str .= ".EX\n$code\n.EE\n.PP\n";
        }
    } elsif ($dewikify_mode eq 'LaTeX') {
        if ($wikitype eq 'mediawiki') {
            # Dump obvious wikilinks.
            if (defined $apiprefixregex) {
                $str =~ s/\s*\[\[($apiprefixregex[a-zA-Z0-9_]+)\]\]/$1/gms;
            }

            # links
            $str =~ s/\[(https?\:\/\/.*?)\s+(.*?)\]/\\href{$1}{$2}/g;

            # <code></code> is also popular.  :/
            $str =~ s/\s*\<code>(.*?)<\/code>/ \\texttt{$1}/gms;

            # bold+italic
            $str =~ s/\s*'''''(.*?)'''''/ \\textbf{\\textit{$1}}/gms;

            # bold
            $str =~ s/\s*'''(.*?)'''/ \\textbf{$1}/gms;

            # italic
            $str =~ s/\s*''(.*?)''/ \\textit{$1}/gms;

            # bullets
            $str =~ s/^\*\s+/  \\item /gm;
        } elsif ($wikitype eq 'md') {
            # Dump obvious wikilinks.
            if (defined $apiprefixregex) {
                $str =~ s/\[(\`?$apiprefixregex[a-zA-Z0-9_]+\`?)\]\($apiprefixregex[a-zA-Z0-9_]+\)/$1/gms;
            }

            # links
            $str =~ s/\[(.*?)]\((https?\:\/\/.*?)\)/\\href{$2}{$1}/g;

            # <code></code> is also popular.  :/
            $str =~ s/\s*\`(.*?)\`/ \\texttt{$1}/gms;

            # bold+italic
            $str =~ s/\s*\*\*\*(.*?)\*\*\*/ \\textbf{\\textit{$1}}/gms;

            # bold
            $str =~ s/\s*\*\*(.*?)\*\*/ \\textbf{$1}/gms;

            # italic
            $str =~ s/\s*\*(.*?)\*/ \\textit{$1}/gms;

            # bullets
            $str =~ s/^\-\s+/  \\item /gm;
        }

        # Wrap bullet lists in itemize blocks...
        $str =~ s/^(\s*\\item .*?)(\n\n|\Z)/\n\\begin{itemize}\n$1$2\n\\end{itemize}\n\n/gms;

        $str = escLaTeX($str);

        if (defined $code) {
            $code =~ s/\A\n+//gms;
            $code =~ s/\n+\Z//gms;

            if (($codelang eq '') || ($codelang eq 'output')) {
                $str .= "\\begin{verbatim}\n$code\n\\end{verbatim}\n";
            } else {
                if ($codelang eq 'c') {
                    $codelang = 'C';
                } elsif ($codelang eq 'c++') {
                    $codelang = 'C++';
                } else {
                    die("Unexpected codelang '$codelang'");
                }
                $str .= "\n\\lstset{language=$codelang}\n";
                $str .= "\\begin{lstlisting}\n$code\n\\end{lstlisting}\n";
            }
        }
    } else {
        die("Unexpected dewikify_mode");
    }

    #print("\n\nDEWIKIFY CHUNK DONE:\n\n$str\n\n\n");

    return $str;
}

sub dewikify {
    my $wikitype = shift;
    my $str = shift;
    return '' if not defined $str;

    #print("DEWIKIFY WHOLE:\n\n$str\n\n\n");

    $str =~ s/\A[\s\n]*\= .*? \=\s*?\n+//ms;
    $str =~ s/\A[\s\n]*\=\= .*? \=\=\s*?\n+//ms;

    my $retval = '';
    if ($wikitype eq 'mediawiki') {
        while ($str =~ s/\A(.*?)<syntaxhighlight lang='?(.*?)'?>(.*?)<\/syntaxhighlight\>//ms) {
            $retval .= dewikify_chunk($wikitype, $1, $2, $3);
        }
    } elsif ($wikitype eq 'md') {
        while ($str =~ s/\A(.*?)\n?```(.*?)\n(.*?)\n```\n//ms) {
            $retval .= dewikify_chunk($wikitype, $1, $2, $3);
        }
    }
    $retval .= dewikify_chunk($wikitype, $str, undef, undef);

    #print("DEWIKIFY WHOLE DONE:\n\n$retval\n\n\n");

    return $retval;
}

sub filecopy {
    my $src = shift;
    my $dst = shift;
    my $endline = shift;
    $endline = "\n" if not defined $endline;

    open(COPYIN, '<', $src) or die("Failed to open '$src' for reading: $!\n");
    open(COPYOUT, '>', $dst) or die("Failed to open '$dst' for writing: $!\n");
    while (<COPYIN>) {
        chomp;
        s/[ \t\r\n]*\Z//;
        print COPYOUT "$_$endline";
    }
    close(COPYOUT);
    close(COPYIN);
}

sub usage {
    die("USAGE: $0 <source code git clone path> <wiki git clone path> [--copy-to-headers|--copy-to-wiki|--copy-to-manpages] [--warn-about-missing] [--manpath=<man path>]\n\n");
}

usage() if not defined $srcpath;
usage() if not defined $wikipath;
#usage() if $copy_direction == 0;

if (not defined $manpath) {
    $manpath = "$srcpath/man";
}

my @standard_wiki_sections = (
    'Draft',
    '[Brief]',
    'Deprecated',
    'Header File',
    'Syntax',
    'Function Parameters',
    'Macro Parameters',
    'Fields',
    'Values',
    'Return Value',
    'Remarks',
    'Thread Safety',
    'Version',
    'Code Examples',
    'See Also'
);

# Sections that only ever exist in the wiki and shouldn't be deleted when
#  not found in the headers.
my %only_wiki_sections = (  # The ones don't mean anything, I just need to check for key existence.
    'Draft', 1,
    'Code Examples', 1,
    'Header File', 1
);


my %headers = ();       # $headers{"SDL_audio.h"} -> reference to an array of all lines of text in SDL_audio.h.
my %headersyms = ();   # $headersyms{"SDL_OpenAudio"} -> string of header documentation for SDL_OpenAudio, with comment '*' bits stripped from the start. Newlines embedded!
my %headerdecls = ();
my %headersymslocation = ();   # $headersymslocation{"SDL_OpenAudio"} -> name of header holding SDL_OpenAudio define ("SDL_audio.h" in this case).
my %headersymschunk = ();   # $headersymschunk{"SDL_OpenAudio"} -> offset in array in %headers that should be replaced for this symbol.
my %headersymshasdoxygen = ();   # $headersymshasdoxygen{"SDL_OpenAudio"} -> 1 if there was no existing doxygen for this function.
my %headersymstype = ();   # $headersymstype{"SDL_OpenAudio"} -> 1 (function), 2 (macro), 3 (struct), 4 (enum), 5 (other typedef)
my %headersymscategory = ();   # $headersymscategory{"SDL_OpenAudio"} -> 'Audio' ... this is set with a `/* WIKI CATEGEORY: Audio */` comment in the headers that sets it on all symbols until a new comment changes it. So usually, once at the top of the header file.
my %headercategorydocs = ();   # $headercategorydocs{"Audio"} -> (fake) symbol for this category's documentation. Undefined if not documented.
my %headersymsparaminfo = (); # $headersymsparaminfo{"SDL_OpenAudio"} -> reference to array of parameters, pushed by name, then C type string, repeating. Undef'd if void params, or not a function.
my %headersymsrettype = (); # $headersymsrettype{"SDL_OpenAudio"} -> string of C datatype of return value. Undef'd if not a function.
my %wikitypes = ();  # contains string of wiki page extension, like $wikitypes{"SDL_OpenAudio"} == 'mediawiki'
my %wikisyms = ();  # contains references to hash of strings, each string being the full contents of a section of a wiki page, like $wikisyms{"SDL_OpenAudio"}{"Remarks"}.
my %wikisectionorder = ();   # contains references to array, each array item being a key to a wikipage section in the correct order, like $wikisectionorder{"SDL_OpenAudio"}[2] == 'Remarks'
my %quickreffuncorder = ();   # contains references to array, each array item being a key to a category with functions in the order they appear in the headers, like $quickreffuncorder{"Audio"}[0] == 'SDL_GetNumAudioDrivers'

my %referenceonly = ();  # $referenceonly{"Y"} -> symbol name that this symbol is bound to. This makes wiki pages that say "See X" where "X" is a typedef and "Y" is a define attached to it. These pages are generated in the wiki only and do not bridge to the headers or manpages.

my @coverage_gap = ();  # array of strings that weren't part of documentation, or blank, or basic preprocessor logic. Lets you see what this script is missing!

sub add_coverage_gap {
    if ($copy_direction == -3) {  # --report-coverage-gaps
        my $text = shift;
        my $dent = shift;
        my $lineno = shift;
        return if $text =~ /\A\s*\Z/;  # skip blank lines
        return if $text =~ /\A\s*\#\s*(if|el|endif|include)/; # skip preprocessor floof.
        push @coverage_gap, "$dent:$lineno: $text";
    }
}

sub print_undocumented_section {
    my $fh = shift;
    my $typestr = shift;
    my $typeval = shift;

    print $fh "## $typestr defined in the headers, but not in the wiki\n\n";
    my $header_only_sym = 0;
    foreach (sort keys %headersyms) {
        my $sym = $_;
        if ((not defined $wikisyms{$sym}) && ($headersymstype{$sym} == $typeval)) {
            print $fh "- [$sym]($sym)\n";
            $header_only_sym = 1;
        }
    }
    if (!$header_only_sym) {
        print $fh "(none)\n";
    }
    print $fh "\n";

    if (0) {  # !!! FIXME: this lists things that _shouldn't_ be in the headers, like MigrationGuide, etc, but also we don't know if they're functions, macros, etc at this point (can we parse that from the wiki page, though?)
    print $fh "## $typestr defined in the wiki, but not in the headers\n\n";

    my $wiki_only_sym = 0;
    foreach (sort keys %wikisyms) {
        my $sym = $_;
        if ((not defined $headersyms{$sym}) && ($headersymstype{$sym} == $typeval)) {
            print $fh "- [$sym]($sym)\n";
            $wiki_only_sym = 1;
        }
    }
    if (!$wiki_only_sym) {
        print $fh "(none)\n";
    }
    print $fh "\n";
    }
}

sub strip_fn_declaration_metadata {
    my $decl = shift;
    $decl =~ s/SDL_(PRINTF|SCANF)_FORMAT_STRING\s*//;  # don't want this metadata as part of the documentation.
    $decl =~ s/SDL_ALLOC_SIZE2?\(.*?\)\s*//;  # don't want this metadata as part of the documentation.
    $decl =~ s/SDL_MALLOC\s*//;  # don't want this metadata as part of the documentation.
    $decl =~ s/SDL_(IN|OUT|INOUT)_.*?CAP\s*\(.*?\)\s*//g;  # don't want this metadata as part of the documentation.
    $decl =~ s/\)(\s*SDL_[a-zA-Z_]+(\(.*?\)|))*;/);/; # don't want this metadata as part of the documentation.
    return $decl;
}

sub sanitize_c_typename {
    my $str = shift;
    $str =~ s/\A\s+//;
    $str =~ s/\s+\Z//;
    $str =~ s/const\s*(\*+)/const $1/g;  # one space between `const` and pointer stars: `char const* const *` becomes `char const * const *`.
    $str =~ s/\*\s+\*/**/g;  # drop spaces between pointers: `void * *` becomes `void **`.
    $str =~ s/\s*(\*+)\Z/ $1/;  # one space between pointer stars and what it points to: `void**` becomes `void **`.
    return $str;
}

my %big_ascii = (
    'A' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{255A}\x{2550}\x{255D}" ],
    'B' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'C' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    'D' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'E' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{255D}\x{20}\x{20}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    'F' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{255D}\x{20}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{20}\x{20}\x{20}" ],
    'G' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'H' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{255A}\x{2550}\x{255D}" ],
    'I' => [ "\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{255D}" ],
    'J' => [ "\x{20}\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{20}\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{20}\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'K' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{255A}\x{2550}\x{255D}" ],
    'L' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    'M' => [ "\x{2588}\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2554}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{255A}\x{2588}\x{2588}\x{2554}\x{255D}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{255A}\x{2550}\x{255D}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{20}\x{20}\x{20}\x{255A}\x{2550}\x{255D}" ],
    'N' => [ "\x{2588}\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2554}\x{2588}\x{2588}\x{2557}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{255A}\x{2588}\x{2588}\x{2557}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    'O' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'P' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{20}\x{20}\x{20}" ],
    'Q' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{2584}\x{2584}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2580}\x{2580}\x{2550}\x{255D}\x{20}" ],
    'R' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{255A}\x{2550}\x{255D}" ],
    'S' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'T' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{255D}", "\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{20}" ],
    'U' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'V' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2557}\x{20}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}", "\x{20}\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}\x{20}" ],
    'W' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{20}\x{2588}\x{2557}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}\x{2588}\x{2588}\x{2588}\x{2557}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2554}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{255D}\x{255A}\x{2550}\x{2550}\x{255D}\x{20}" ],
    'X' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2588}\x{2588}\x{2557}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}", "\x{20}\x{2588}\x{2588}\x{2554}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{255D}\x{20}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{255A}\x{2550}\x{255D}" ],
    'Y' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2588}\x{2588}\x{2557}\x{20}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}", "\x{20}\x{20}\x{255A}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{20}" ],
    'Z' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{20}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}", "\x{20}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}\x{20}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    ' ' => [ "\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}" ],
    '.' => [ "\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}", "\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{255D}" ],
    ',' => [ "\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}", "\x{2584}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{255D}" ],
    '/' => [ "\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{20}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}", "\x{20}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}\x{20}", "\x{2588}\x{2588}\x{2554}\x{255D}\x{20}\x{20}\x{20}", "\x{255A}\x{2550}\x{255D}\x{20}\x{20}\x{20}\x{20}" ],
    '!' => [ "\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{255D}", "\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{255D}" ],
    '_' => [ "\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}\x{20}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    '0' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{2588}\x{2588}\x{2554}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    '1' => [ "\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2588}\x{2588}\x{2551}", "\x{20}\x{2588}\x{2588}\x{2551}", "\x{20}\x{2588}\x{2588}\x{2551}", "\x{20}\x{255A}\x{2550}\x{255D}" ],
    '2' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    '3' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    '4' => [ "\x{2588}\x{2588}\x{2557}\x{20}\x{20}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2551}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2551}", "\x{20}\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}", "\x{20}\x{20}\x{20}\x{20}\x{20}\x{255A}\x{2550}\x{255D}" ],
    '5' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2551}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2551}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}" ],
    '6' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}", "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    '7' => [ "\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2551}", "\x{20}\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2554}\x{255D}\x{20}", "\x{20}\x{20}\x{20}\x{2588}\x{2588}\x{2551}\x{20}\x{20}", "\x{20}\x{20}\x{20}\x{255A}\x{2550}\x{255D}\x{20}\x{20}" ],
    '8' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
    '9' => [ "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2557}\x{20}", "\x{2588}\x{2588}\x{2554}\x{2550}\x{2550}\x{2588}\x{2588}\x{2557}", "\x{255A}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2551}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2588}\x{2588}\x{2551}", "\x{20}\x{2588}\x{2588}\x{2588}\x{2588}\x{2588}\x{2554}\x{255D}", "\x{20}\x{255A}\x{2550}\x{2550}\x{2550}\x{2550}\x{255D}\x{20}" ],
);

sub print_big_ascii_string {
    my $fh = shift;
    my $str = shift;
    my $comment = shift;
    my $lowascii = shift;
    $comment = '' if not defined $comment;
    $lowascii = 0 if not defined $lowascii;

    my @chars = split //, $str;
    my $charcount = scalar(@chars);

    binmode($fh, ":utf8");

    my $maxrows = $lowascii ? 5 : 6;

    for(my $rownum = 0; $rownum < $maxrows; $rownum++){
        print $fh $comment;
        my $charidx = 0;
        foreach my $ch (@chars) {
            my $rowsref = $big_ascii{uc($ch)};
            die("Don't have a big ascii entry for '$ch'!\n") if not defined $rowsref;
            my $row = @$rowsref[$rownum];

            if ($lowascii) {
                my @x = split //, $row;
                foreach (@x) {
                    my $v = ($_ eq "\x{2588}") ? 'X' : ' ';
                    print $fh $v;
                }
            } else {
                print $fh $row;
            }

            $charidx++;

            if ($charidx < $charcount) {
                print $fh " ";
            }
        }
        print $fh "\n";
    }
}

sub generate_quickref {
    my $briefsref = shift;
    my $path = shift;
    my $lowascii = shift;

    # !!! FIXME: this gitrev and majorver/etc stuff is copy/pasted a few times now.
    if (!$gitrev) {
        $gitrev = `cd "$srcpath" ; git rev-list HEAD~..`;
        chomp($gitrev);
    }

    # !!! FIXME
    open(FH, '<', "$srcpath/$versionfname") or die("Can't open '$srcpath/$versionfname': $!\n");
    my $majorver = 0;
    my $minorver = 0;
    my $microver = 0;
    while (<FH>) {
        chomp;
        if (/$versionmajorregex/) {
            $majorver = int($1);
        } elsif (/$versionminorregex/) {
            $minorver = int($1);
        } elsif (/$versionmicroregex/) {
            $microver = int($1);
        }
    }
    close(FH);
    my $fullversion = "$majorver.$minorver.$microver";

    my $tmppath = "$path.tmp";
    open(my $fh, '>', $tmppath) or die("Can't open '$tmppath': $!\n");

    if (not @quickrefcategoryorder) {
        @quickrefcategoryorder = sort keys %headercategorydocs;
    }

    #my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
    #my $datestr = sprintf("%04d-%02d-%02d %02d:%02d:%02d GMT", $year+1900, $mon+1, $mday, $hour, $min, $sec);

    print $fh "<!-- DO NOT EDIT THIS PAGE ON THE WIKI. IT WILL BE OVERWRITTEN BY WIKIHEADERS AND CHANGES WILL BE LOST! -->\n\n";

    # Just something to test big_ascii output.
    #print_big_ascii_string($fh, "ABCDEFGHIJ", '', $lowascii);
    #print_big_ascii_string($fh, "KLMNOPQRST", '', $lowascii);
    #print_big_ascii_string($fh, "UVWXYZ0123", '', $lowascii);
    #print_big_ascii_string($fh, "456789JT3A", '', $lowascii);
    #print_big_ascii_string($fh, "hello, _a.b/c_!!", '', $lowascii);

    # Dan Bechard's work was on an SDL2 cheatsheet:
    # https://blog.theprogrammingjunkie.com/post/sdl2-cheatsheet/

    if ($lowascii) {
        print $fh "# QuickReferenceNoUnicode\n\n";
        print $fh "If you want to paste this into a text editor that can handle\n";
        print $fh "fancy Unicode section headers, try using\n";
        print $fh "[QuickReference](QuickReference) instead.\n\n";
    } else {
        print $fh "# QuickReference\n\n";
        print $fh "If you want to paste this into a text editor that can't handle\n";
        print $fh "the fancy Unicode section headers, try using\n";
        print $fh "[QuickReferenceNoUnicode](QuickReferenceNoUnicode) instead.\n\n";
    }

    print $fh "```c\n";
    print $fh "// $quickreftitle\n" if defined $quickreftitle;
    print $fh "//\n";
    print $fh "// $quickrefurl\n//\n" if defined $quickrefurl;
    print $fh "// $quickrefdesc\n" if defined $quickrefdesc;
    #print $fh "// When this document was written: $datestr\n";
    print $fh "// Based on $projectshortname version $fullversion\n";
    #print $fh "// git revision $gitrev\n";
    print $fh "//\n";
    print $fh "// This can be useful in an IDE with search and syntax highlighting.\n";
    print $fh "//\n";
    print $fh "// Original idea for this document came from Dan Bechard (thanks!)\n";
    print $fh "// ASCII art generated by: https://patorjk.com/software/taag/#p=display&f=ANSI%20Shadow (with modified 'S' for readability)\n\n";

    foreach (@quickrefcategoryorder) {
        my $cat = $_;
        my $maxlen = 0;
        my @csigs = ();
        my $funcorderref = $quickreffuncorder{$cat};
        next if not defined $funcorderref;

        foreach (@$funcorderref) {
            my $sym = $_;
            my $csig = '';

            if ($headersymstype{$sym} == 1) {  # function
                $csig = "${headersymsrettype{$sym}} $sym";
                my $fnsigparams = $headersymsparaminfo{$sym};
                if (not defined($fnsigparams)) {
                    $csig .= '(void);';
                } else {
                    my $sep = '(';
                    for (my $i = 0; $i < scalar(@$fnsigparams); $i += 2) {
                        my $paramname = @$fnsigparams[$i];
                        my $paramtype = @$fnsigparams[$i+1];
                        my $spc = ($paramtype =~ /\*\Z/) ? '' : ' ';
                        $csig .= "$sep$paramtype$spc$paramname";
                        $sep = ', ';
                    }
                    $csig .= ");";
                }
            } elsif ($headersymstype{$sym} == 2) {  # macro
                next if defined $quickrefmacroregex && not $sym =~ /$quickrefmacroregex/;

                $csig = (split /\n/, $headerdecls{$sym})[0];  # get the first line from a multiline string.
                if (not $csig =~ s/\A(\#define [a-zA-Z0-9_]*\(.*?\))(\s+.*)?\Z/$1/) {
                    $csig =~ s/\A(\#define [a-zA-Z0-9_]*)(\s+.*)?\Z/$1/;
                }
                chomp($csig);
            }

            my $len = length($csig);
            $maxlen = $len if $len > $maxlen;

            push @csigs, $sym;
            push @csigs, $csig;
        }

        $maxlen += 2;

        next if (not @csigs);

        print $fh "\n";
        print_big_ascii_string($fh, $cat, '// ', $lowascii);
        print $fh "\n";

        while (@csigs) {
            my $sym = shift @csigs;
            my $csig = shift @csigs;
            my $brief = $$briefsref{$sym};
            if (defined $brief) {
                $brief = "$brief";
                chomp($brief);
                my $thiswikitype = defined $wikitypes{$sym} ? $wikitypes{$sym} : 'md';  # default to MarkDown for new stuff.
                $brief = dewikify($thiswikitype, $brief);
                my $spaces = ' ' x ($maxlen - length($csig));
                $brief = "$spaces// $brief";
            } else {
                $brief = '';
            }
            print $fh "$csig$brief\n";
        }
    }

    print $fh "```\n\n";

    close($fh);

#    # Don't overwrite the file if nothing has changed besides the timestamp
#    #  and git revision.
#    my $matches = 1;
#    if ( not -f $path ) {
#        $matches = 0;  # always write if the file hasn't been created yet.
#    } else {
#        open(my $fh_a, '<', $tmppath) or die("Can't open '$tmppath': $!\n");
#        open(my $fh_b, '<', $path) or die("Can't open '$path': $!\n");
#        while (1) {
#            my $a = <$fh_a>;
#            my $b = <$fh_b>;
#            $matches = 0, last if ((not defined $a) != (not defined $b));
#            last if ((not defined $a) || (not defined $b));
#            if ($a ne $b) {
#                next if ($a =~ /\A\/\/ When this document was written:/);
#                next if ($a =~ /\A\/\/ git revision /);
#                $matches = 0;
#                last;
#            }
#        }
#
#        close($fh_a);
#        close($fh_b);
#    }
#
#    if ($matches) {
#        unlink($tmppath);  # it's the same file except maybe the date/gitrev. Don't overwrite it.
#    } else {
#        rename($tmppath, $path) or die("Can't rename '$tmppath' to '$path': $!\n");
#    }
    rename($tmppath, $path) or die("Can't rename '$tmppath' to '$path': $!\n");
}


my $incpath = "$srcpath";
$incpath .= "/$incsubdir" if $incsubdir ne '';

my $wikireadmepath = "$wikipath/$wikireadmesubdir";
my $readmepath = undef;
if (defined $readmesubdir) {
    $readmepath = "$srcpath/$readmesubdir";
}

opendir(DH, $incpath) or die("Can't opendir '$incpath': $!\n");
while (my $d = readdir(DH)) {
    my $dent = $d;
    next if not $dent =~ /$selectheaderregex/;  # just selected headers.
    open(FH, '<', "$incpath/$dent") or die("Can't open '$incpath/$dent': $!\n");

    # You can optionally set a wiki category with Perl code in .wikiheaders-options that gets eval()'d per-header,
    # and also if you put `/* WIKI CATEGORY: blah */` on a line by itself, it'll change the category for any symbols
    # below it in the same file. If no category is set, one won't be added for the symbol (beyond the standard CategoryFunction, etc)
    my $current_wiki_category = undef;
    if (defined $headercategoryeval) {
        $_ = $dent;
        $current_wiki_category = eval($headercategoryeval);
        if (($current_wiki_category eq '') || ($current_wiki_category eq '-')) {
            $current_wiki_category = undef;
        }
        #print("CATEGORY FOR '$dent' IS " . (defined($current_wiki_category) ? "'$current_wiki_category'" : '(undef)') . "\n");
    }

    my @contents = ();
    my @function_order = ();
    my $ignoring_lines = 0;
    my $header_comment = -1;
    my $saw_category_doxygen = -1;
    my $lineno = 0;

    while (<FH>) {
        chomp;
        $lineno++;
        my $symtype = 0;  # nothing, yet.
        my $decl;
        my @templines;
        my $str;
        my $has_doxygen = 1;

        # Since a lot of macros are just preprocessor logic spam and not all macros are worth documenting anyhow, we only pay attention to them when they have a Doxygen comment attached.
        # Functions and other things are a different story, though!

        if ($header_comment == -1) {
            $header_comment = /\A\/\*\s*\Z/ ? 1 : 0;
        } elsif (($header_comment == 1) && (/\A\*\/\s*\Z/)) {
            $header_comment = 0;
        }

        if ($ignoring_lines && /\A\s*\#\s*endif\s*\Z/) {
            $ignoring_lines = 0;
            push @contents, $_;
            next;
        } elsif ($ignoring_lines) {
            push @contents, $_;
            next;
        } elsif (/\A\s*\#\s*ifndef\s+SDL_WIKI_DOCUMENTATION_SECTION\s*\Z/) {
            $ignoring_lines = 1;
            push @contents, $_;
            next;
        } elsif (/\A\s*\/\*\s*WIKI CATEGORY:\s*(.*?)\s*\*\/\s*\Z/) {
            $current_wiki_category = (($1 eq '') || ($1 eq '-')) ? undef : $1;
            #print("CATEGORY FOR '$dent' CHANGED TO " . (defined($current_wiki_category) ? "'$current_wiki_category'" : '(undef)') . "\n");
            push @contents, $_;
            next;
        } elsif (/\A\s*extern\s+(SDL_DEPRECATED\s+|)(SDLMAIN_|SDL_)?DECLSPEC/) {  # a function declaration without a doxygen comment?
            $symtype = 1;   # function declaration
            @templines = ();
            $decl = $_;
            $str = '';
            $has_doxygen = 0;
        } elsif (/\A\s*SDL_FORCE_INLINE/) {  # a (forced-inline) function declaration without a doxygen comment?
            $symtype = 1;   # function declaration
            @templines = ();
            $decl = $_;
            $str = '';
            $has_doxygen = 0;
        } elsif (not /\A\/\*\*\s*\Z/) {  # not doxygen comment start?
            push @contents, $_;
            add_coverage_gap($_, $dent, $lineno) if ($header_comment == 0);
            next;
        } else {   # Start of a doxygen comment, parse it out.
            my $is_category_doxygen = 0;

            @templines = ( $_ );
            while (<FH>) {
                chomp;
                $lineno++;
                push @templines, $_;
                last if /\A\s*\*\/\Z/;
                if (s/\A\s*\*\s*\`\`\`/```/) {  # this is a hack, but a lot of other code relies on the whitespace being trimmed, but we can't trim it in code blocks...
                    $str .= "$_\n";
                    while (<FH>) {
                        chomp;
                        $lineno++;
                        push @templines, $_;
                        s/\A\s*\*\s?//;
                        if (s/\A\s*\`\`\`/```/) {
                            $str .= "$_\n";
                            last;
                        } else {
                            $str .= "$_\n";
                        }
                    }
                } else {
                    s/\A\s*\*\s*//;   # Strip off the " * " at the start of the comment line.

                    # To add documentation to Category Pages, the rule is it has to
                    # be the first Doxygen comment in the header, and it must start with `# CategoryX`
                    # (otherwise we'll treat it as documentation for whatever's below it). `X` is
                    # the category name, which doesn't _necessarily_ have to match
                    # $current_wiki_category, but it probably should.
                    #
                    # For compatibility with Doxygen, if there's a `\file` here instead of
                    # `# CategoryName`, we'll accept it and use the $current_wiki_category if set.
                    if ($saw_category_doxygen == -1) {
                        $saw_category_doxygen = defined($current_wiki_category) && /\A\\file\s+/;
                        if ($saw_category_doxygen) {
                            $_ = "# Category$current_wiki_category";
                        } else {
                            $saw_category_doxygen = /\A\# Category/;
                        }
                        $is_category_doxygen = $saw_category_doxygen;
                    }

                    $str .= "$_\n";
                }
            }

            if ($is_category_doxygen) {
                $str =~ s/\s*\Z//;
                $decl = '';
                $symtype = -1;  # not a symbol at all.
            } else {
                $decl = <FH>;
                $lineno++ if defined $decl;
                $decl = '' if not defined $decl;
                chomp($decl);
                if ($decl =~ /\A\s*extern\s+(SDL_DEPRECATED\s+|)(SDLMAIN_|SDL_)?DECLSPEC/) {
                    $symtype = 1;   # function declaration
                } elsif ($decl =~ /\A\s*SDL_FORCE_INLINE/) {
                    $symtype = 1;   # (forced-inline) function declaration
                } elsif ($decl =~ /\A\s*\#\s*define\s+/) {
                    $symtype = 2;   # macro
                } elsif ($decl =~ /\A\s*(typedef\s+|)(struct|union)\s*([a-zA-Z0-9_]*?)\s*(\n|\{|\Z)/) {
                    $symtype = 3;   # struct or union
                } elsif ($decl =~ /\A\s*(typedef\s+|)enum\s*([a-zA-Z0-9_]*?)\s*(\n|\{|\Z)/) {
                    $symtype = 4;   # enum
                } elsif ($decl =~ /\A\s*typedef\s+.*\Z/) {
                    $symtype = 5;   # other typedef
                } else {
                    #print "Found doxygen but no function sig:\n$str\n\n";
                    foreach (@templines) {
                        push @contents, $_;
                        add_coverage_gap($_, $dent, $lineno);
                    }
                    push @contents, $decl;
                    add_coverage_gap($decl, $dent, $lineno);
                    next;
                }
            }
        }

        my @paraminfo = ();
        my $rettype = undef;
        my @decllines = ( $decl );
        my $sym = '';

        if ($symtype == -1) {  # category documentation with no symbol attached.
            @decllines = ();
            if ($str =~ /^#\s*Category(.*?)\s*$/m) {
                $sym = "[category documentation] $1";  # make a fake, unique symbol that's not valid C.
            } else {
                die("Unexpected category documentation line '$str' in '$incpath/$dent' ...?");
            }
            $headercategorydocs{$current_wiki_category} = $sym;
        } elsif ($symtype == 1) {  # a function
            my $is_forced_inline = ($decl =~ /\A\s*SDL_FORCE_INLINE/);

            if ($is_forced_inline) {
                if (not $decl =~ /\)\s*(\{.*|)\s*\Z/) {
                    while (<FH>) {
                        chomp;
                        $lineno++;
                        push @decllines, $_;
                        s/\A\s+//;
                        s/\s+\Z//;
                        $decl .= " $_";
                        last if /\)\s*(\{.*|)\s*\Z/;
                    }
                }
                $decl =~ s/\s*\)\s*(\{.*|)\s*\Z/);/;
            } else {
                if (not $decl =~ /;/) {
                    while (<FH>) {
                        chomp;
                        $lineno++;
                        push @decllines, $_;
                        s/\A\s+//;
                        s/\s+\Z//;
                        $decl .= " $_";
                        last if /;/;
                    }
                }
                $decl =~ s/\s+\);\Z/);/;
                $decl =~ s/\s+;\Z/;/;
            }

            $decl =~ s/\s+\Z//;

            $decl = strip_fn_declaration_metadata($decl);

            my $paramsstr = undef;

            if (!$is_forced_inline && $decl =~ /\A\s*extern\s+(SDL_DEPRECATED\s+|)(SDLMAIN_|SDL_)?DECLSPEC\w*\s+(const\s+|)(unsigned\s+|)(.*?)([\*\s]+)(\*?)\s*SDLCALL\s+(.*?)\s*\((.*?)\);/) {
                $sym = $8;
                $rettype = "$3$4$5$6";
                $paramsstr = $9;
             } elsif ($is_forced_inline && $decl =~ /\A\s*SDL_FORCE_INLINE\s+(SDL_DEPRECATED\s+|)(const\s+|)(unsigned\s+|)(.*?)([\*\s]+)(.*?)\s*\((.*?)\);/) {
                $sym = $6;
                $rettype = "$2$3$4$5";
                $paramsstr = $7;
             } else {
                #print "Found doxygen but no function sig:\n$str\n\n";
                foreach (@templines) {
                    push @contents, $_;
                }
                foreach (@decllines) {
                    push @contents, $_;
                }
                next;
            }

            $rettype = sanitize_c_typename($rettype);

            if ($paramsstr =~ /\(/) {
                die("\n\n$0 FAILURE!\n" .
                    "There's a '(' in the parameters for function '$sym' '$incpath/$dent'.\n" .
                    "This usually means there's a parameter that's a function pointer type.\n" .
                    "This causes problems for wikiheaders.pl and is less readable, too.\n" .
                    "Please put that function pointer into a typedef,\n" .
                    "and use the new type in this function's signature instead!\n\n");
            }

            my @params = split(/,/, $paramsstr);
            my $dotdotdot = 0;
            foreach (@params) {
                my $p = $_;
                $p =~ s/\A\s+//;
                $p =~ s/\s+\Z//;
                if (($p eq 'void') || ($p eq '')) {
                    die("Void parameter in a function with multiple params?! ('$sym' in '$incpath/$dent')") if (scalar(@params) != 1);
                } elsif ($p eq '...') {
                    die("Mutiple '...' params?! ('$sym' in '$incpath/$dent')") if ($dotdotdot);
                    $dotdotdot = 1;
                    push @paraminfo, '...';
                    push @paraminfo, '...';
                } elsif ($p =~ /\A(.*)\s+([a-zA-Z0-9_\*\[\]]+)\Z/) {
                    die("Parameter after '...' param?! ('$sym' in '$incpath/$dent')") if ($dotdotdot);
                    my $t = $1;
                    my $n = $2;
                    if ($n =~ s/\A(\*+)//) {
                        $t .= $1;  # move any `*` that stuck to the name over.
                    }
                    if ($n =~ s/\[\]\Z//) {
                        $t = "$t*";  # move any `[]` that stuck to the name over, as a pointer.
                    }
                    $t = sanitize_c_typename($t);
                    #print("$t\n");
                    #print("$n\n");
                    push @paraminfo, $n;
                    push @paraminfo, $t;
                } else {
                    die("Unexpected parameter '$p' in function '$sym' in '$incpath/$dent'!");
                }
            }

            if (!$is_forced_inline) {  # don't do with forced-inline because we don't want the implementation inserted in the wiki.
                my $shrink_length = 0;

                $decl = '';  # rebuild this with the line breaks, since it looks better for syntax highlighting.
                foreach (@decllines) {
                    if ($decl eq '') {
                        my $temp;

                        $decl = $_;
                        $temp = $decl;
                        $temp =~ s/\Aextern\s+(SDL_DEPRECATED\s+|)(SDLMAIN_|SDL_)?DECLSPEC\w*\s+(.*?)\s+(\*?)SDLCALL\s+/$3$4 /;
                        $shrink_length = length($decl) - length($temp);
                        $decl = $temp;
                    } else {
                        my $trimmed = $_;
                        $trimmed =~ s/\A\s{$shrink_length}//;  # shrink to match the removed "extern SDL_DECLSPEC SDLCALL "
                        $decl .= $trimmed;
                    }
                    $decl .= "\n";
                }
            }

            $decl = strip_fn_declaration_metadata($decl);

            # !!! FIXME: code duplication with typedef processing, below.
            # We assume any `#define`s directly after the function are related to it: probably bitflags for an integer typedef.
            # We'll also allow some other basic preprocessor lines.
            # Blank lines are allowed, anything else, even comments, are not.
            my $blank_lines = 0;
            my $lastpos = tell(FH);
            my $lastlineno = $lineno;
            my $additional_decl = '';
            my $saw_define = 0;
            while (<FH>) {
                chomp;

                $lineno++;

                if (/\A\s*\Z/) {
                    $blank_lines++;
                } elsif (/\A\s*\#\s*(define|if|else|elif|endif)(\s+|\Z)/) {
                    if (/\A\s*\#\s*define\s+([a-zA-Z0-9_]*)/) {
                        $referenceonly{$1} = $sym;
                        $saw_define = 1;
                    } elsif (!$saw_define) {
                        # if the first non-blank thing isn't a #define, assume we're done.
                        seek(FH, $lastpos, 0);  # re-read eaten lines again next time.
                        $lineno = $lastlineno;
                        last;
                    }

                    # update strings now that we know everything pending is to be applied to this declaration. Add pending blank lines and the new text.

                    # At Sam's request, don't list property defines with functions. (See #9440)
                    my $is_property = /\A\s*\#\s*define\s+SDL_PROP_/;
                    if (!$is_property) {
                        if ($blank_lines > 0) {
                            while ($blank_lines > 0) {
                                $additional_decl .= "\n";
                                push @decllines, '';
                                $blank_lines--;
                            }
                        }
                        $additional_decl .= "\n$_";
                        push @decllines, $_;
                        $lastpos = tell(FH);
                    }
                } else {
                    seek(FH, $lastpos, 0);  # re-read eaten lines again next time.
                    $lineno = $lastlineno;
                    last;
                }
            }
            $decl .= $additional_decl;
        } elsif ($symtype == 2) {  # a macro
            if ($decl =~ /\A\s*\#\s*define\s+(.*?)(\(.*?\)|)\s+/) {
                $sym = $1;
            } else {
                #print "Found doxygen but no macro:\n$str\n\n";
                foreach (@templines) {
                    push @contents, $_;
                }
                foreach (@decllines) {
                    push @contents, $_;
                }
                next;
            }

            while ($decl =~ /\\\Z/) {
                my $l = <FH>;
                last if not $l;
                $lineno++;
                chomp($l);
                push @decllines, $l;
                #$l =~ s/\A\s+//;
                $l =~ s/\s+\Z//;
                $decl .= "\n$l";
            }
        } elsif (($symtype == 3) || ($symtype == 4)) {  # struct or union or enum
            my $has_definition = 0;
            if ($decl =~ /\A\s*(typedef\s+|)(struct|union|enum)\s*([a-zA-Z0-9_]*?)\s*(\n|\{|\;|\Z)/) {
                my $ctype = $2;
                my $origsym = $3;
                my $ending = $4;
                $sym = $origsym;
                if ($sym =~ s/\A(.*?)(\s+)(.*?)\Z/$1/) {
                    die("Failed to parse '$origsym' correctly!") if ($sym ne $1);  # Thought this was "typedef struct MySym MySym;" ... it was not.  :(  This is a hack!
                }
                if ($sym eq '') {
                    die("\n\n$0 FAILURE!\n" .
                        "There's a 'typedef $ctype' in $incpath/$dent without a name at the top.\n" .
                        "Instead of `typedef $ctype {} x;`, this should be `typedef $ctype x {} x;`.\n" .
                        "This causes problems for wikiheaders.pl and scripting language bindings.\n" .
                        "Please fix it!\n\n");
                }
                $has_definition = ($ending ne ';');
            } else {
                #print "Found doxygen but no datatype:\n$str\n\n";
                foreach (@templines) {
                    push @contents, $_;
                }
                foreach (@decllines) {
                    push @contents, $_;
                }
                next;
            }

            # This block attempts to find the whole struct/union/enum definition by counting matching brackets. Kind of yucky.
            # It also "parses" enums enough to find out the elements of it.
            if ($has_definition) {
                my $started = 0;
                my $brackets = 0;
                my $pending = $decl;
                my $skipping_comment = 0;

                $decl = '';
                while (!$started || ($brackets != 0)) {
                    foreach my $seg (split(/([{}])/, $pending)) {   # (this will pick up brackets in comments! Be careful!)
                        $decl .= $seg;
                        if ($seg eq '{') {
                            $started = 1;
                            $brackets++;
                        } elsif ($seg eq '}') {
                            die("Something is wrong with header $incpath/$dent while parsing $sym; is a bracket missing?\n") if ($brackets <= 0);
                            $brackets--;
                        }
                    }

                    if ($skipping_comment) {
                        if ($pending =~ s/\A.*?\*\///) {
                            $skipping_comment = 0;
                        }
                    }

                    if (!$skipping_comment && $started && ($symtype == 4)) {  # Pick out elements of an enum.
                        my $stripped = "$pending";
                        $stripped =~ s/\/\*.*?\*\///g;  # dump /* comments */ that exist fully on one line.
                        if ($stripped =~ /\/\*/) {  # uhoh, a /* comment */ that crosses newlines.
                            $skipping_comment = 1;
                        } elsif ($stripped =~ /\A\s*([a-zA-Z0-9_]+)(.*)\Z/) {  #\s*(\=\s*.*?|)\s*,?(.*?)\Z/) {
                            if ($1 ne 'typedef') {  # make sure we didn't just eat the first line by accident.  :/
                                #print("ENUM [$1] $incpath/$dent:$lineno\n");
                                $referenceonly{$1} = $sym;
                            }
                        }
                    }

                    if (!$started || ($brackets != 0)) {
                        $pending = <FH>;
                        die("EOF/error reading $incpath/$dent while parsing $sym\n") if not $pending;
                        $lineno++;
                        chomp($pending);
                        push @decllines, $pending;
                        $decl .= "\n";
                    }
                }
                # this currently assumes the struct/union/enum ends on the line with the final bracket. I'm not writing a C parser here, fix the header!
            }
        } elsif ($symtype == 5) {  # other typedef
            if ($decl =~ /\A\s*typedef\s+(.*)\Z/) {
                my $tdstr = $1;

                if (not $decl =~ /;/) {
                    while (<FH>) {
                        chomp;
                        $lineno++;
                        push @decllines, $_;
                        s/\A\s+//;
                        s/\s+\Z//;
                        $decl .= " $_";
                        last if /;/;
                    }
                }
                $decl =~ s/\s+(\))?;\Z/$1;/;

                $tdstr =~ s/;\s*\Z//;

                #my $datatype;
                if ($tdstr =~ /\A(.*?)\s*\((.*?)\s*\*\s*(.*?)\)\s*\((.*?)(\))?/) {  # a function pointer type
                    $sym = $3;
                    #$datatype = "$1 ($2 *$sym)($4)";
                } elsif ($tdstr =~ /\A(.*[\s\*]+)(.*?)\s*\Z/) {
                    $sym = $2;
                    #$datatype = $1;
                } else {
                    die("Failed to parse typedef '$tdstr' in $incpath/$dent!\n");  # I'm hitting a C grammar nail with a regexp hammer here, y'all.
                }

                $sym =~ s/\A\s+//;
                $sym =~ s/\s+\Z//;
                #$datatype =~ s/\A\s+//;
                #$datatype =~ s/\s+\Z//;
            } else {
                #print "Found doxygen but no datatype:\n$str\n\n";
                foreach (@templines) {
                    push @contents, $_;
                }
                foreach (@decllines) {
                    push @contents, $_;
                }
                next;
            }

            # We assume any `#define`s directly after the typedef are related to it: probably bitflags for an integer typedef.
            # We'll also allow some other basic preprocessor lines.
            # Blank lines are allowed, anything else, even comments, are not.
            my $blank_lines = 0;
            my $lastpos = tell(FH);
            my $lastlineno = $lineno;
            my $additional_decl = '';
            my $saw_define = 0;
            while (<FH>) {
                chomp;

                $lineno++;

                if (/\A\s*\Z/) {
                    $blank_lines++;
                } elsif (/\A\s*\#\s*(define|if|else|elif|endif)(\s+|\Z)/) {
                    if (/\A\s*\#\s*define\s+([a-zA-Z0-9_]*)/) {
                        $referenceonly{$1} = $sym;
                        $saw_define = 1;
                    } elsif (!$saw_define) {
                        # if the first non-blank thing isn't a #define, assume we're done.
                        seek(FH, $lastpos, 0);  # re-read eaten lines again next time.
                        $lineno = $lastlineno;
                        last;
                    }
                    # update strings now that we know everything pending is to be applied to this declaration. Add pending blank lines and the new text.
                    if ($blank_lines > 0) {
                        while ($blank_lines > 0) {
                            $additional_decl .= "\n";
                            push @decllines, '';
                            $blank_lines--;
                        }
                    }
                    $additional_decl .= "\n$_";
                    push @decllines, $_;
                    $lastpos = tell(FH);
                } else {
                    seek(FH, $lastpos, 0);  # re-read eaten lines again next time.
                    $lineno = $lastlineno;
                    last;
                }
            }
            $decl .= $additional_decl;
        } else {
            die("Unexpected symtype $symtype");
        }

        #print("DECL: [$decl]\n");

        #print("$sym:\n$str\n\n");

        # There might be multiple declarations of a function due to #ifdefs,
        #  and only one of them will have documentation. If we hit an
        #  undocumented one before, delete the placeholder line we left for
        #  it so it doesn't accumulate a new blank line on each run.
        my $skipsym = 0;
        if (defined $headersymshasdoxygen{$sym}) {
            if ($headersymshasdoxygen{$sym} == 0) {  # An undocumented declaration already exists, nuke its placeholder line.
                delete $contents[$headersymschunk{$sym}];  # delete DOES NOT RENUMBER existing elements!
            } else {  # documented function already existed?
                $skipsym = 1;  # don't add this copy to the list of functions.
                if ($has_doxygen) {
                    print STDERR "WARNING: Symbol '$sym' appears to be documented in multiple locations. Only keeping the first one we saw!\n";
                }
                push @contents, join("\n", @decllines) if (scalar(@decllines) > 0);  # just put the existing declation in as-is.
            }
        }

        if (!$skipsym) {
            $headersymscategory{$sym} = $current_wiki_category if defined $current_wiki_category;
            $headersyms{$sym} = $str;
            $headerdecls{$sym} = $decl;
            $headersymslocation{$sym} = $dent;
            $headersymschunk{$sym} = scalar(@contents);
            $headersymshasdoxygen{$sym} = $has_doxygen;
            $headersymstype{$sym} = $symtype;
            $headersymsparaminfo{$sym} = \@paraminfo if (scalar(@paraminfo) > 0);
            $headersymsrettype{$sym} = $rettype if (defined($rettype));
            push @function_order, $sym if ($symtype == 1) || ($symtype == 2);
            push @contents, join("\n", @templines);
            push @contents, join("\n", @decllines) if (scalar(@decllines) > 0);
        }

    }
    close(FH);

    $headers{$dent} = \@contents;
    $quickreffuncorder{$current_wiki_category} = \@function_order if defined $current_wiki_category;
}
closedir(DH);


opendir(DH, $wikipath) or die("Can't opendir '$wikipath': $!\n");
while (my $d = readdir(DH)) {
    my $dent = $d;
    my $type = '';
    if ($dent =~ /\.(md|mediawiki)\Z/) {
        $type = $1;
    } else {
        next;  # only dealing with wiki pages.
    }

    my $sym = $dent;
    $sym =~ s/\..*\Z//;

    # (There are other pages to ignore, but these are known ones to not bother parsing.)
    # Ignore FrontPage.
    next if $sym eq 'FrontPage';

    open(FH, '<', "$wikipath/$dent") or die("Can't open '$wikipath/$dent': $!\n");

    if ($sym =~ /\ACategory(.*?)\Z/) {  # Special case for Category pages.
        # Find the end of the category documentation in the existing file and append everything else to the new file.
        my $cat = $1;
        my $docstr = '';
        my $notdocstr = '';
        my $docs = 1;
        while (<FH>) {
            chomp;
            if ($docs) {
                $docs = 0 if /\A\-\-\-\-\Z/;  # Hit a footer? We're done.
                $docs = 0 if /\A<!\-\-/;  # Hit an HTML comment? We're done.
            }
            if ($docs) {
                $docstr .= "$_\n";
            } else {
                $notdocstr .= "$_\n";
            }
        }
        close(FH);

        $docstr =~ s/\s*\Z//;

        $sym = "[category documentation] $cat";  # make a fake, unique symbol that's not valid C.
        $wikitypes{$sym} = $type;
        my %sections = ();
        $sections{'Remarks'} = $docstr;
        $sections{'[footer]'} = $notdocstr;
        $wikisyms{$sym} = \%sections;
        my @section_order = ( 'Remarks', '[footer]' );
        $wikisectionorder{$sym} = \@section_order;
        next;
    }

    my $current_section = '[start]';
    my @section_order = ( $current_section );
    my %sections = ();
    $sections{$current_section} = '';

    my $firstline = 1;

    while (<FH>) {
        chomp;
        my $orig = $_;
        s/\A\s*//;
        s/\s*\Z//;

        if ($type eq 'mediawiki') {
            if (defined($wikipreamble) && $firstline && /\A\=\=\=\=\=\= (.*?) \=\=\=\=\=\=\Z/ && ($1 eq $wikipreamble)) {
                $firstline = 0;  # skip this.
                next;
            } elsif (/\A\= (.*?) \=\Z/) {
                $firstline = 0;
                $current_section = ($1 eq $sym) ? '[Brief]' : $1;
                die("Doubly-defined section '$current_section' in '$dent'!\n") if defined $sections{$current_section};
                push @section_order, $current_section;
                $sections{$current_section} = '';
            } elsif (/\A\=\= (.*?) \=\=\Z/) {
                $firstline = 0;
                $current_section = ($1 eq $sym) ? '[Brief]' : $1;
                die("Doubly-defined section '$current_section' in '$dent'!\n") if defined $sections{$current_section};
                push @section_order, $current_section;
                $sections{$current_section} = '';
                next;
            } elsif (/\A\-\-\-\-\Z/) {
                $firstline = 0;
                $current_section = '[footer]';
                die("Doubly-defined section '$current_section' in '$dent'!\n") if defined $sections{$current_section};
                push @section_order, $current_section;
                $sections{$current_section} = '';
                next;
            }
        } elsif ($type eq 'md') {
            if (defined($wikipreamble) && $firstline && /\A\#\#\#\#\#\# (.*?)\Z/ && ($1 eq $wikipreamble)) {
                $firstline = 0;  # skip this.
                next;
            } elsif (/\A\#+ (.*?)\Z/) {
                $firstline = 0;
                $current_section = ($1 eq $sym) ? '[Brief]' : $1;
                die("Doubly-defined section '$current_section' in '$dent'!\n") if defined $sections{$current_section};
                push @section_order, $current_section;
                $sections{$current_section} = '';
                next;
            } elsif (/\A\-\-\-\-\Z/) {
                $firstline = 0;
                $current_section = '[footer]';
                die("Doubly-defined section '$current_section' in '$dent'!\n") if defined $sections{$current_section};
                push @section_order, $current_section;
                $sections{$current_section} = '';
                next;
            }
        } else {
            die("Unexpected wiki file type. Fixme!");
        }

        if ($firstline) {
            $firstline = ($_ ne '');
        }
        if (!$firstline) {
            $sections{$current_section} .= "$orig\n";
        }
    }
    close(FH);

    foreach (keys %sections) {
        $sections{$_} =~ s/\A\n+//;
        $sections{$_} =~ s/\n+\Z//;
        $sections{$_} .= "\n";
    }

    # older section name we used, migrate over from it.
    if (defined $sections{'Related Functions'}) {
        if (not defined $sections{'See Also'}) {
            $sections{'See Also'} = $sections{'Related Functions'};
        }
        delete $sections{'Related Functions'};
    }

    if (0) {
        foreach (@section_order) {
            print("$sym SECTION '$_':\n");
            print($sections{$_});
            print("\n\n");
        }
    }

    $wikitypes{$sym} = $type;
    $wikisyms{$sym} = \%sections;
    $wikisectionorder{$sym} = \@section_order;
}
closedir(DH);

delete $wikisyms{"Undocumented"};

{
    my $path = "$wikipath/Undocumented.md";
    open(my $fh, '>', $path) or die("Can't open '$path': $!\n");

    print $fh "# Undocumented\n\n";
    print_undocumented_section($fh, 'Functions', 1);
    #print_undocumented_section($fh, 'Macros', 2);

    close($fh);
}

if ($warn_about_missing) {
    foreach (keys %wikisyms) {
        my $sym = $_;
        if (not defined $headersyms{$sym}) {
            print STDERR "WARNING: $sym defined in the wiki but not the headers!\n";
        }
    }

    foreach (keys %headersyms) {
        my $sym = $_;
        if (not defined $wikisyms{$sym}) {
            print STDERR "WARNING: $sym defined in the headers but not the wiki!\n";
        }
    }
}

if ($copy_direction == 1) {  # --copy-to-headers
    my %changed_headers = ();

    $dewikify_mode = 'md';
    $wordwrap_mode = 'md';   # the headers use Markdown format.

    foreach (keys %headersyms) {
        my $sym = $_;
        next if not defined $wikisyms{$sym};  # don't have a page for that function, skip it.
        my $symtype = $headersymstype{$sym};
        my $wikitype = $wikitypes{$sym};
        my $sectionsref = $wikisyms{$sym};
        my $remarks = $sectionsref->{'Remarks'};
        my $returns = $sectionsref->{'Return Value'};
        my $threadsafety = $sectionsref->{'Thread Safety'};
        my $version = $sectionsref->{'Version'};
        my $related = $sectionsref->{'See Also'};
        my $deprecated = $sectionsref->{'Deprecated'};
        my $brief = $sectionsref->{'[Brief]'};
        my $addblank = 0;
        my $str = '';

        my $params = undef;
        my $paramstr = undef;

        if ($symtype == -1) {  # category documentation block.
            # nothing to be done here.
        } elsif (($symtype == 1) || (($symtype == 5))) {  # we'll assume a typedef (5) with a \param is a function pointer typedef.
            $params = $sectionsref->{'Function Parameters'};
            $paramstr = '\param';
        } elsif ($symtype == 2) {
            $params = $sectionsref->{'Macro Parameters'};
            $paramstr = '\param';
        } elsif ($symtype == 3) {
            $params = $sectionsref->{'Fields'};
            $paramstr = '\field';
        } elsif ($symtype == 4) {
            $params = $sectionsref->{'Values'};
            $paramstr = '\value';
        } else {
            die("Unexpected symtype $symtype");
        }

        $headersymshasdoxygen{$sym} = 1;  # Added/changed doxygen for this header.

        $brief = dewikify($wikitype, $brief);
        $brief =~ s/\A(.*?\.) /$1\n/;  # \brief should only be one sentence, delimited by a period+space. Split if necessary.
        my @briefsplit = split /\n/, $brief;
        $brief = shift @briefsplit;

        if (defined $remarks) {
            $remarks = join("\n", @briefsplit) . dewikify($wikitype, $remarks);
        }

        if (defined $brief) {
            $str .= "\n" if $addblank; $addblank = 1;
            $str .= wordwrap($brief) . "\n";
        }

        if (defined $remarks) {
            $str .= "\n" if $addblank; $addblank = 1;
            $str .= wordwrap($remarks) . "\n";
        }

        if (defined $deprecated) {
            # !!! FIXME: lots of code duplication in all of these.
            $str .= "\n" if $addblank; $addblank = 1;
            my $v = dewikify($wikitype, $deprecated);
            my $whitespacelen = length("\\deprecated") + 1;
            my $whitespace = ' ' x $whitespacelen;
            $v = wordwrap($v, -$whitespacelen);
            my @desclines = split /\n/, $v;
            my $firstline = shift @desclines;
            $str .= "\\deprecated $firstline\n";
            foreach (@desclines) {
                $str .= "${whitespace}$_\n";
            }
        }

        if (defined $params) {
            $str .= "\n" if $addblank; $addblank = (defined $returns) ? 0 : 1;
            my @lines = split /\n/, dewikify($wikitype, $params);
            if ($wikitype eq 'mediawiki') {
                die("Unexpected data parsing MediaWiki table") if (shift @lines ne '{|');  # Dump the '{|' start
                while (scalar(@lines) >= 3) {
                    my $c_datatype = shift @lines;
                    my $name = shift @lines;
                    my $desc = shift @lines;
                    my $terminator;  # the '|-' or '|}' line.

                    if (($desc eq '|-') or ($desc eq '|}') or (not $desc =~ /\A\|/)) {  # we seem to be out of cells, which means there was no datatype column on this one.
                        $terminator = $desc;
                        $desc = $name;
                        $name = $c_datatype;
                        $c_datatype = '';
                    } else {
                        $terminator = shift @lines;
                    }

                    last if ($terminator ne '|-') and ($terminator ne '|}');  # we seem to have run out of table.
                    $name =~ s/\A\|\s*//;
                    $name =~ s/\A\*\*(.*?)\*\*/$1/;
                    $name =~ s/\A\'\'\'(.*?)\'\'\'/$1/;
                    $desc =~ s/\A\|\s*//;
                    #print STDERR "SYM: $sym   CDATATYPE: $c_datatype  NAME: $name   DESC: $desc TERM: $terminator\n";
                    my $whitespacelen = length($name) + 8;
                    my $whitespace = ' ' x $whitespacelen;
                    $desc = wordwrap($desc, -$whitespacelen);
                    my @desclines = split /\n/, $desc;
                    my $firstline = shift @desclines;
                    $str .= "$paramstr $name $firstline\n";
                    foreach (@desclines) {
                        $str .= "${whitespace}$_\n";
                    }
                }
            } elsif ($wikitype eq 'md') {
                my $l;
                $l = shift @lines;
                die("Unexpected data parsing Markdown table") if (not $l =~ /\A(\s*\|)?\s*\|\s*\|\s*\|\s*\Z/);
                $l = shift @lines;
                die("Unexpected data parsing Markdown table") if (not $l =~ /\A\s*(\|\s*\-*\s*)?\|\s*\-*\s*\|\s*\-*\s*\|\s*\Z/);
                while (scalar(@lines) >= 1) {
                    $l = shift @lines;
                    my $name;
                    my $desc;
                    if ($l =~ /\A\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*\Z/) {
                        # c datatype is $1, but we don't care about it here.
                        $name = $2;
                        $desc = $3;
                    } elsif ($l =~ /\A\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*\Z/) {
                        $name = $1;
                        $desc = $2;
                    } else {
                        last;  # we seem to have run out of table.
                    }

                    $name =~ s/\A\*\*(.*?)\*\*/$1/;
                    $name =~ s/\A\'\'\'(.*?)\'\'\'/$1/;
                    #print STDERR "SYM: $sym   NAME: $name   DESC: $desc\n";
                    my $whitespacelen = length($name) + 8;
                    my $whitespace = ' ' x $whitespacelen;
                    $desc = wordwrap($desc, -$whitespacelen);
                    my @desclines = split /\n/, $desc;
                    my $firstline = shift @desclines;
                    $str .= "$paramstr $name $firstline\n";
                    foreach (@desclines) {
                        $str .= "${whitespace}$_\n";
                    }
                }
            } else {
                die("write me");
            }
        }

        if (defined $returns) {
            $str .= "\n" if $addblank; $addblank = 1;
            my $r = dewikify($wikitype, $returns);
            $r =~ s/\A\(.*?\)\s*//;  # Chop datatype in parentheses off the front.
            my $retstr = "\\returns";
            if ($r =~ s/\AReturn(s?)\s+//) {
                $retstr = "\\return$1";
            }

            my $whitespacelen = length($retstr) + 1;
            my $whitespace = ' ' x $whitespacelen;
            $r = wordwrap($r, -$whitespacelen);
            my @desclines = split /\n/, $r;
            my $firstline = shift @desclines;
            $str .= "$retstr $firstline\n";
            foreach (@desclines) {
                $str .= "${whitespace}$_\n";
            }
        }

        if (defined $threadsafety) {
            # !!! FIXME: lots of code duplication in all of these.
            $str .= "\n" if $addblank; $addblank = 1;
            my $v = dewikify($wikitype, $threadsafety);
            my $whitespacelen = length("\\threadsafety") + 1;
            my $whitespace = ' ' x $whitespacelen;
            $v = wordwrap($v, -$whitespacelen);
            my @desclines = split /\n/, $v;
            my $firstline = shift @desclines;
            $str .= "\\threadsafety $firstline\n";
            foreach (@desclines) {
                $str .= "${whitespace}$_\n";
            }
        }

        if (defined $version) {
            # !!! FIXME: lots of code duplication in all of these.
            $str .= "\n" if $addblank; $addblank = 1;
            my $v = dewikify($wikitype, $version);
            my $whitespacelen = length("\\since") + 1;
            my $whitespace = ' ' x $whitespacelen;
            $v = wordwrap($v, -$whitespacelen);
            my @desclines = split /\n/, $v;
            my $firstline = shift @desclines;
            $str .= "\\since $firstline\n";
            foreach (@desclines) {
                $str .= "${whitespace}$_\n";
            }
        }

        if (defined $related) {
            # !!! FIXME: lots of code duplication in all of these.
            $str .= "\n" if $addblank; $addblank = 1;
            my $v = dewikify($wikitype, $related);
            my @desclines = split /\n/, $v;
            foreach (@desclines) {
                s/\(\)\Z//;  # Convert "SDL_Func()" to "SDL_Func"
                s/\[\[(.*?)\]\]/$1/;  # in case some wikilinks remain.
                s/\[(.*?)\]\(.*?\)/$1/;  # in case some wikilinks remain.
                s/\A\/*//;
                s/\A\s*[\:\*\-]\s*//;
                s/\A\s+//;
                s/\s+\Z//;
                $str .= "\\sa $_\n";
            }
        }

        my $header = $headersymslocation{$sym};
        my $contentsref = $headers{$header};
        my $chunk = $headersymschunk{$sym};

        my @lines = split /\n/, $str;

        my $addnewline = (($chunk > 0) && ($$contentsref[$chunk-1] ne '')) ? "\n" : '';

        my $output = "$addnewline/**\n";
        foreach (@lines) {
            chomp;
            s/\s*\Z//;
            if ($_ eq '') {
                $output .= " *\n";
            } else {
                $output .= " * $_\n";
            }
        }
        $output .= " */";

        #print("$sym:\n[$output]\n\n");

        $$contentsref[$chunk] = $output;
        #$$contentsref[$chunk+1] = $headerdecls{$sym};

        $changed_headers{$header} = 1;
    }

    foreach (keys %changed_headers) {
        my $header = $_;

        # this is kinda inefficient, but oh well.
        my @removelines = ();
        foreach (keys %headersymslocation) {
            my $sym = $_;
            next if $headersymshasdoxygen{$sym};
            next if $headersymslocation{$sym} ne $header;
            # the index of the blank line we put before the function declaration in case we needed to replace it with new content from the wiki.
            push @removelines, $headersymschunk{$sym};
        }

        my $contentsref = $headers{$header};
        foreach (@removelines) {
            delete $$contentsref[$_];  # delete DOES NOT RENUMBER existing elements!
        }

        my $path = "$incpath/$header.tmp";
        open(FH, '>', $path) or die("Can't open '$path': $!\n");
        foreach (@$contentsref) {
            print FH "$_\n" if defined $_;
        }
        close(FH);
        rename($path, "$incpath/$header") or die("Can't rename '$path' to '$incpath/$header': $!\n");
    }

    if (defined $readmepath) {
        if ( -d $wikireadmepath ) {
            mkdir($readmepath);  # just in case
            opendir(DH, $wikireadmepath) or die("Can't opendir '$wikireadmepath': $!\n");
            while (readdir(DH)) {
                my $dent = $_;
                if ($dent =~ /\A(.*?)\.md\Z/) {  # we only bridge Markdown files here.
                    next if $1 eq 'FrontPage';
                    filecopy("$wikireadmepath/$dent", "$readmepath/README-$dent", "\n");
                }
            }
            closedir(DH);
        }
    }

} elsif ($copy_direction == -1) { # --copy-to-wiki

    my %briefs = ();  # $briefs{'SDL_OpenAudio'} -> the \brief string for the function.

    if (defined $changeformat) {
        $dewikify_mode = $changeformat;
        $wordwrap_mode = $changeformat;
    }

    foreach (keys %headersyms) {
        my $sym = $_;
        next if not $headersymshasdoxygen{$sym};
        next if $sym =~ /\A\[category documentation\]/;   # not real symbols, we handle this elsewhere.
        my $symtype = $headersymstype{$sym};
        my $origwikitype = defined $wikitypes{$sym} ? $wikitypes{$sym} : 'md';  # default to MarkDown for new stuff.
        my $wikitype = (defined $changeformat) ? $changeformat : $origwikitype;
        die("Unexpected wikitype '$wikitype'") if (($wikitype ne 'mediawiki') and ($wikitype ne 'md') and ($wikitype ne 'manpage'));

        #print("$sym\n"); next;

        $wordwrap_mode = $wikitype;

        my $raw = $headersyms{$sym};  # raw doxygen text with comment characters stripped from start/end and start of each line.
        next if not defined $raw;
        $raw =~ s/\A\s*\\brief\s+//;  # Technically we don't need \brief (please turn on JAVADOC_AUTOBRIEF if you use Doxygen), so just in case one is present, strip it.

        my @doxygenlines = split /\n/, $raw;
        my $brief = '';
        while (@doxygenlines) {
            last if $doxygenlines[0] =~ /\A\\/;  # some sort of doxygen command, assume we're past the general remarks.
            last if $doxygenlines[0] =~ /\A\s*\Z/;  # blank line? End of paragraph, done.
            my $l = shift @doxygenlines;
            chomp($l);
            $l =~ s/\A\s*//;
            $l =~ s/\s*\Z//;
            $brief .= "$l ";
        }

        $brief =~ s/\s+\Z//;
        $brief =~ s/\A(.*?\.) /$1\n\n/;  # \brief should only be one sentence, delimited by a period+space. Split if necessary.
        my @briefsplit = split /\n/, $brief;

        next if not defined $briefsplit[0];  # No brief text? Probably a bogus Doxygen comment, skip it.

        $brief = wikify($wikitype, shift @briefsplit) . "\n";
        @doxygenlines = (@briefsplit, @doxygenlines);

        my $remarks = '';
        while (@doxygenlines) {
            last if $doxygenlines[0] =~ /\A\\/;  # some sort of doxygen command, assume we're past the general remarks.
            my $l = shift @doxygenlines;
            $remarks .= "$l\n";
        }

        #print("REMARKS:\n\n $remarks\n\n");

        $remarks = wordwrap(wikify($wikitype, $remarks));
        $remarks =~ s/\A\s*//;
        $remarks =~ s/\s*\Z//;

        my $decl = $headerdecls{$sym};

        my $syntax = '';
        if ($wikitype eq 'mediawiki') {
            $syntax = "<syntaxhighlight lang='c'>\n$decl</syntaxhighlight>\n";
        } elsif ($wikitype eq 'md') {
            $decl =~ s/\n+\Z//;
            $syntax = "```c\n$decl\n```\n";
        } else { die("Expected wikitype '$wikitype'"); }

        my %sections = ();
        $sections{'[Brief]'} = $brief;  # include this section even if blank so we get a title line.
        $sections{'Remarks'} = "$remarks\n" if $remarks ne '';
        $sections{'Syntax'} = $syntax;

        $briefs{$sym} = $brief;

        my %params = ();  # have to parse these and build up the wiki tables after, since Markdown needs to know the length of the largest string.  :/
        my @paramsorder = ();
        my $fnsigparams = $headersymsparaminfo{$sym};
        my $has_returns = 0;
        my $has_threadsafety = 0;

        while (@doxygenlines) {
            my $l = shift @doxygenlines;
            # We allow param/field/value interchangeably, even if it doesn't make sense. The next --copy-to-headers will correct it anyhow.
            if ($l =~ /\A\\(param|field|value)\s+(.*?)\s+(.*)\Z/) {
                my $arg = $2;
                my $desc = $3;
                while (@doxygenlines) {
                    my $subline = $doxygenlines[0];
                    $subline =~ s/\A\s*//;
                    last if $subline =~ /\A\\/;  # some sort of doxygen command, assume we're past this thing.
                    shift @doxygenlines;  # dump this line from the array; we're using it.
                    if ($subline eq '') {  # empty line, make sure it keeps the newline char.
                        $desc .= "\n";
                    } else {
                        $desc .= " $subline";
                    }
                }

                $desc =~ s/[\s\n]+\Z//ms;

                if (0) {  # !!! FIXME: disabled because it's not currently suitable for general use, but for manually inspecting the output, it can be useful.
                    if (($desc =~ /\A[A-Z]/) && (not $desc =~ /\ASDL_/)) {
                        print STDERR "WARNING: $sym\'s '\\param $arg' text starts with a capital letter: '$desc'. Fixing.\n";
                        $desc = lcfirst($desc);
                    }
                }

                if (not $desc =~ /[\.\!]\Z/) {
                    print STDERR "WARNING: $sym\'s '\\param $arg' text doesn't end with punctuation: '$desc'. Fixing.\n";
                    $desc .= '.';
                }

                # Validate this param.
                if (defined($params{$arg})) {
                    print STDERR "WARNING: Symbol '$sym' has multiple '\\param $arg' declarations! Only keeping the first one!\n";
                } elsif (defined $fnsigparams) {
                    my $found = 0;
                    for (my $i = 0; $i < scalar(@$fnsigparams); $i += 2) {
                        $found = 1, last if (@$fnsigparams[$i] eq $arg);
                    }
                    if (!$found) {
                        print STDERR "WARNING: Symbol '$sym' has a '\\param $arg' for a param that doesn't exist. It will be removed!\n";
                    }
                }

                # We need to know the length of the longest string to make Markdown tables, so we just store these off until everything is parsed.
                $params{$arg} = $desc;
                push @paramsorder, $arg;
            } elsif ($l =~ /\A\\r(eturns?)\s+(.*)\Z/) {
                $has_returns = 1;
                # !!! FIXME: complain if this isn't a function or macro.
                my $retstr = "R$1";  # "Return" or "Returns"
                my $desc = $2;

                while (@doxygenlines) {
                    my $subline = $doxygenlines[0];
                    $subline =~ s/\A\s*//;
                    last if $subline =~ /\A\\/;  # some sort of doxygen command, assume we're past this thing.
                    shift @doxygenlines;  # dump this line from the array; we're using it.
                    if ($subline eq '') {  # empty line, make sure it keeps the newline char.
                        $desc .= "\n";
                    } else {
                        $desc .= " $subline";
                    }
                }
                $desc =~ s/[\s\n]+\Z//ms;

                if (0) {  # !!! FIXME: disabled because it's not currently suitable for general use, but for manually inspecting the output, it can be useful.
                    if (($desc =~ /\A[A-Z]/) && (not $desc =~ /\ASDL_/)) {
                        print STDERR "WARNING: $sym\'s '\\returns' text starts with a capital letter: '$desc'. Fixing.\n";
                        $desc = lcfirst($desc);
                    }
                }

                if (not $desc =~ /[\.\!]\Z/) {
                    print STDERR "WARNING: $sym\'s '\\returns' text doesn't end with punctuation: '$desc'. Fixing.\n";
                    $desc .= '.';
                }

                # Make sure the \returns info is valid.
                my $rettype = $headersymsrettype{$sym};
                die("Don't have a rettype for '$sym' for some reason!") if (($symtype == 1) && (not defined($rettype)));
                if (defined($sections{'Return Value'})) {
                    print STDERR "WARNING: Symbol '$sym' has multiple '\\return' declarations! Only keeping the first one!\n";
                } elsif (($symtype != 1) && ($symtype != 2) && ($symtype != 5)) {  # !!! FIXME: if 5, make sure it's a function pointer typedef!
                    print STDERR "WARNING: Symbol '$sym' has a '\\return' declaration but isn't a function or macro! Removing it!\n";
                } elsif (($symtype == 1) && ($headersymsrettype{$sym} eq 'void')) {
                    print STDERR "WARNING: Function '$sym' has a '\\returns' declaration but function returns void! Removing it!\n";
                } else {
                    my $rettypestr = defined($rettype) ? ('(' . wikify($wikitype, $rettype) . ') ') : '';
                    $sections{'Return Value'} = wordwrap("$rettypestr$retstr ". wikify($wikitype, $desc)) . "\n";
                }
            } elsif ($l =~ /\A\\deprecated\s+(.*)\Z/) {
                my $desc = $1;
                while (@doxygenlines) {
                    my $subline = $doxygenlines[0];
                    $subline =~ s/\A\s*//;
                    last if $subline =~ /\A\\/;  # some sort of doxygen command, assume we're past this thing.
                    shift @doxygenlines;  # dump this line from the array; we're using it.
                    if ($subline eq '') {  # empty line, make sure it keeps the newline char.
                        $desc .= "\n";
                    } else {
                        $desc .= " $subline";
                    }
                }
                $desc =~ s/[\s\n]+\Z//ms;
                $sections{'Deprecated'} = wordwrap(wikify($wikitype, $desc)) . "\n";
            } elsif ($l =~ /\A\\since\s+(.*)\Z/) {
                my $desc = $1;
                while (@doxygenlines) {
                    my $subline = $doxygenlines[0];
                    $subline =~ s/\A\s*//;
                    last if $subline =~ /\A\\/;  # some sort of doxygen command, assume we're past this thing.
                    shift @doxygenlines;  # dump this line from the array; we're using it.
                    if ($subline eq '') {  # empty line, make sure it keeps the newline char.
                        $desc .= "\n";
                    } else {
                        $desc .= " $subline";
                    }
                }
                $desc =~ s/[\s\n]+\Z//ms;
                $sections{'Version'} = wordwrap(wikify($wikitype, $desc)) . "\n";
            } elsif ($l =~ /\A\\threadsafety\s+(.*)\Z/) {
                my $desc = $1;
                while (@doxygenlines) {
                    my $subline = $doxygenlines[0];
                    $subline =~ s/\A\s*//;
                    last if $subline =~ /\A\\/;  # some sort of doxygen command, assume we're past this thing.
                    shift @doxygenlines;  # dump this line from the array; we're using it.
                    if ($subline eq '') {  # empty line, make sure it keeps the newline char.
                        $desc .= "\n";
                    } else {
                        $desc .= " $subline";
                    }
                }
                $desc =~ s/[\s\n]+\Z//ms;
                $sections{'Thread Safety'} = wordwrap(wikify($wikitype, $desc)) . "\n";
                $has_threadsafety = 1;
            } elsif ($l =~ /\A\\sa\s+(.*)\Z/) {
                my $sa = $1;
                $sa =~ s/\(\)\Z//;  # Convert "SDL_Func()" to "SDL_Func"
                $sections{'See Also'} = '' if not defined $sections{'See Also'};
                if ($wikitype eq 'mediawiki') {
                    $sections{'See Also'} .= ":[[$sa]]\n";
                } elsif ($wikitype eq 'md') {
                    $sections{'See Also'} .= "- [$sa]($sa)\n";
                } else { die("Expected wikitype '$wikitype'"); }
            }
        }

        if (($symtype == 1) && ($headersymsrettype{$sym} ne 'void') && !$has_returns) {
            print STDERR "WARNING: Function '$sym' has a non-void return type but no '\\returns' declaration\n";
        }

        # !!! FIXME: uncomment this when we're trying to clean this up in the headers.
        #if (($symtype == 1) && !$has_threadsafety) {
        #    print STDERR "WARNING: Function '$sym' doesn't have a '\\threadsafety' declaration\n";
        #}

        # Make sure %params is in the same order as the actual function signature and add C datatypes...
        my $params_has_c_datatype = 0;
        my @final_params = ();
        if (($symtype == 1) && (defined($headersymsparaminfo{$sym}))) {  # is a function and we have param info for it...
            my $fnsigparams = $headersymsparaminfo{$sym};
            for (my $i = 0; $i < scalar(@$fnsigparams); $i += 2) {
                my $paramname = @$fnsigparams[$i];
                my $paramdesc = $params{$paramname};
                if (defined($paramdesc)) {
                    push @final_params, $paramname;             # name
                    push @final_params, @$fnsigparams[$i+1];    # C datatype
                    push @final_params, $paramdesc;             # description
                    $params_has_c_datatype = 1 if (defined(@$fnsigparams[$i+1]));
                } else {
                    print STDERR "WARNING: Symbol '$sym' is missing a '\\param $paramname' declaration!\n";
                }
            }
        } else {
            foreach (@paramsorder) {
                my $paramname = $_;
                my $paramdesc = $params{$paramname};
                if (defined($paramdesc)) {
                    push @final_params, $_;
                    push @final_params, undef;
                    push @final_params, $paramdesc;
                }
            }
        }

        my $hfiletext = $wikiheaderfiletext;
        $hfiletext =~ s/\%fname\%/$headersymslocation{$sym}/g;
        $sections{'Header File'} = "$hfiletext\n";

        # Make sure this ends with a double-newline.
        $sections{'See Also'} .= "\n" if defined $sections{'See Also'};

        if (0) {  # !!! FIXME: this was a useful hack, but this needs to be generalized if we're going to do this always.
            # Plug in a \since section if one wasn't listed.
            if (not defined $sections{'Version'}) {
                my $symtypename;
                if ($symtype == 1) {
                    $symtypename = 'function';
                } elsif ($symtype == 2) {
                    $symtypename = 'macro';
                } elsif ($symtype == 3) {
                    $symtypename = 'struct';
                } elsif ($symtype == 4) {
                    $symtypename = 'enum';
                } elsif ($symtype == 5) {
                    $symtypename = 'datatype';
                } else {
                    die("Unexpected symbol type $symtype!");
                }
                my $str = "This $symtypename is available since SDL 3.0.0.";
                $sections{'Version'} = wordwrap(wikify($wikitype, $str)) . "\n";
            }
        }

        # We can build the wiki table now that we have all the data.
        if (scalar(@final_params) > 0) {
            my $str = '';
            if ($wikitype eq 'mediawiki') {
                while (scalar(@final_params) > 0) {
                    my $arg = shift @final_params;
                    my $c_datatype = shift @final_params;
                    my $desc = wikify($wikitype, shift @final_params);
                    $c_datatype = '' if not defined $c_datatype;
                    $str .= ($str eq '') ? "{|\n" : "|-\n";
                    $str .= "|$c_datatype\n" if $params_has_c_datatype;
                    $str .= "|'''$arg'''\n";
                    $str .= "|$desc\n";
                }
                $str .= "|}\n";
            } elsif ($wikitype eq 'md') {
                my $longest_arg = 0;
                my $longest_c_datatype = 0;
                my $longest_desc = 0;
                my $which = 0;
                foreach (@final_params) {
                    if ($which == 0) {
                        my $len = length($_);
                        $longest_arg = $len if ($len > $longest_arg);
                        $which = 1;
                    } elsif ($which == 1) {
                        if (defined($_)) {
                            my $len = length(wikify($wikitype, $_));
                            $longest_c_datatype = $len if ($len > $longest_c_datatype);
                        }
                        $which = 2;
                    } else {
                        my $len = length(wikify($wikitype, $_));
                        $longest_desc = $len if ($len > $longest_desc);
                        $which = 0;
                    }
                }

                # Markdown tables are sort of obnoxious.
                my $c_datatype_cell;
                $c_datatype_cell = ($longest_c_datatype > 0) ? ('| ' . (' ' x ($longest_c_datatype)) . ' ') : '';
                $str .= $c_datatype_cell . '| ' . (' ' x ($longest_arg+4)) . ' | ' . (' ' x $longest_desc) . " |\n";
                $c_datatype_cell = ($longest_c_datatype > 0) ? ('| ' . ('-' x ($longest_c_datatype)) . ' ') : '';
                $str .= $c_datatype_cell . '| ' . ('-' x ($longest_arg+4)) . ' | ' . ('-' x $longest_desc) . " |\n";

                while (@final_params) {
                    my $arg = shift @final_params;
                    my $c_datatype = shift @final_params;
                    $c_datatype_cell = '';
                    if ($params_has_c_datatype) {
                        $c_datatype = defined($c_datatype) ? wikify($wikitype, $c_datatype) : '';
                        $c_datatype_cell = ($longest_c_datatype > 0) ? ("| $c_datatype " . (' ' x ($longest_c_datatype - length($c_datatype)))) : '';
                    }
                    my $desc = wikify($wikitype, shift @final_params);
                    $str .= $c_datatype_cell . "| **$arg** " . (' ' x ($longest_arg - length($arg))) . "| $desc" . (' ' x ($longest_desc - length($desc))) . " |\n";
                }
            } else {
                die("Unexpected wikitype!");  # should have checked this elsewhere.
            }
            $sections{'Function Parameters'} = $str;
        }

        my $path = "$wikipath/$sym.${wikitype}.tmp";
        open(FH, '>', $path) or die("Can't open '$path': $!\n");

        my $sectionsref = $wikisyms{$sym};

        foreach (@standard_wiki_sections) {
            # drop sections we either replaced or removed from the original wiki's contents.
            if (not defined $only_wiki_sections{$_}) {
                delete($$sectionsref{$_});
            }
        }

        my $wikisectionorderref = $wikisectionorder{$sym};

        # Make sure there's a footer in the wiki that puts this function in CategoryAPI...
        if (not $$sectionsref{'[footer]'}) {
            $$sectionsref{'[footer]'} = '';
            push @$wikisectionorderref, '[footer]';
        }

        # If changing format, convert things that otherwise are passed through unmolested.
        if (defined $changeformat) {
            if (($dewikify_mode eq 'md') and ($origwikitype eq 'mediawiki')) {
                $$sectionsref{'[footer]'} =~ s/\[\[(Category[a-zA-Z0-9_]+)\]\]/[$1]($1)/g;
            } elsif (($dewikify_mode eq 'mediawiki') and ($origwikitype eq 'md')) {
                $$sectionsref{'[footer]'} =~ s/\[(Category[a-zA-Z0-9_]+)\]\(.*?\)/[[$1]]/g;
            }

            foreach (keys %only_wiki_sections) {
                my $sect = $_;
                if (defined $$sectionsref{$sect}) {
                    $$sectionsref{$sect} = wikify($wikitype, dewikify($origwikitype, $$sectionsref{$sect}));
                }
            }
        }

        if ($symtype != -1) {  # Don't do these in category documentation block
            my $footer = $$sectionsref{'[footer]'};

            my $symtypename;
            if ($symtype == 1) {
                $symtypename = 'Function';
            } elsif ($symtype == 2) {
                $symtypename = 'Macro';
            } elsif ($symtype == 3) {
                $symtypename = 'Struct';
            } elsif ($symtype == 4) {
                $symtypename = 'Enum';
            } elsif ($symtype == 5) {
                $symtypename = 'Datatype';
            } else {
                die("Unexpected symbol type $symtype!");
            }

            my $symcategory = $headersymscategory{$sym};
            if ($wikitype eq 'mediawiki') {
                $footer =~ s/\[\[CategoryAPI\]\],?\s*//g;
                $footer =~ s/\[\[CategoryAPI${symtypename}\]\],?\s*//g;
                $footer =~ s/\[\[Category${symcategory}\]\],?\s*//g if defined $symcategory;
                $footer = "[[CategoryAPI]], [[CategoryAPI$symtypename]]" . (defined $symcategory ? ", [[Category$symcategory]]" : '') . (($footer eq '') ? "\n" : ", $footer");
            } elsif ($wikitype eq 'md') {
                $footer =~ s/\[CategoryAPI\]\(CategoryAPI\),?\s*//g;
                $footer =~ s/\[CategoryAPI${symtypename}\]\(CategoryAPI${symtypename}\),?\s*//g;
                $footer =~ s/\[Category${symcategory}\]\(Category${symcategory}\),?\s*//g if defined $symcategory;
                $footer = "[CategoryAPI](CategoryAPI), [CategoryAPI$symtypename](CategoryAPI$symtypename)" . (defined $symcategory ? ", [Category$symcategory](Category$symcategory)" : '') . (($footer eq '') ? '' : ', ') . $footer;
            } else { die("Unexpected wikitype '$wikitype'"); }
            $$sectionsref{'[footer]'} = $footer;

            if (defined $wikipreamble) {
                my $wikified_preamble = wikify($wikitype, $wikipreamble);
                if ($wikitype eq 'mediawiki') {
                    print FH "====== $wikified_preamble ======\n";
                } elsif ($wikitype eq 'md') {
                    print FH "###### $wikified_preamble\n";
                } else { die("Unexpected wikitype '$wikitype'"); }
            }
        }

        my $prevsectstr = '';
        my @ordered_sections = (@standard_wiki_sections, defined $wikisectionorderref ? @$wikisectionorderref : ());  # this copies the arrays into one.
        foreach (@ordered_sections) {
            my $sect = $_;
            next if $sect eq '[start]';
            next if (not defined $sections{$sect} and not defined $$sectionsref{$sect});
            my $section = defined $sections{$sect} ? $sections{$sect} : $$sectionsref{$sect};

            if ($sect eq '[footer]') {
                # Make sure previous section ends with two newlines.
                if (substr($prevsectstr, -1) ne "\n") {
                    print FH "\n\n";
                } elsif (substr($prevsectstr, -2) ne "\n\n") {
                    print FH "\n";
                }
                print FH "----\n";   # It's the same in Markdown and MediaWiki.
            } elsif ($sect eq '[Brief]') {
                if ($wikitype eq 'mediawiki') {
                    print FH  "= $sym =\n\n";
                } elsif ($wikitype eq 'md') {
                    print FH "# $sym\n\n";
                } else { die("Unexpected wikitype '$wikitype'"); }
            } else {
                my $sectname = $sect;
                if ($sectname eq 'Function Parameters') {  # We use this same table for different things depending on what we're documenting, so rename it now.
                    if (($symtype == 1) || ($symtype == 5)) {  # function (or typedef, in case it's a function pointer type).
                    } elsif ($symtype == 2) {  # macro
                        $sectname = 'Macro Parameters';
                    } elsif ($symtype == 3) {  # struct/union
                        $sectname = 'Fields';
                    } elsif ($symtype == 4) {  # enum
                        $sectname = 'Values';
                    } else {
                        die("Unexpected symtype $symtype");
                    }
                }

                if ($symtype != -1) {  # Not for category documentation block
                    if ($wikitype eq 'mediawiki') {
                        print FH  "\n== $sectname ==\n\n";
                    } elsif ($wikitype eq 'md') {
                        print FH "\n## $sectname\n\n";
                    } else { die("Unexpected wikitype '$wikitype'"); }
                }
            }

            my $sectstr = defined $sections{$sect} ? $sections{$sect} : $$sectionsref{$sect};
            print FH $sectstr;

            $prevsectstr = $sectstr;

            # make sure these don't show up twice.
            delete($sections{$sect});
            delete($$sectionsref{$sect});
        }

        print FH "\n\n";
        close(FH);

        if (defined $changeformat and ($origwikitype ne $wikitype)) {
            system("cd '$wikipath' ; git mv '$_.${origwikitype}' '$_.${wikitype}'");
            unlink("$wikipath/$_.${origwikitype}");
        }

        rename($path, "$wikipath/$_.${wikitype}") or die("Can't rename '$path' to '$wikipath/$_.${wikitype}': $!\n");
    }

    # Write out simple redirector pages if they don't already exist.
    foreach (keys %referenceonly) {
        my $sym = $_;
        my $refersto = $referenceonly{$sym};
        my $path = "$wikipath/$sym.md";  # we only do Markdown for these.
        next if (-f $path);  # don't overwrite if it already exists. Delete the file if you need a rebuild!
        open(FH, '>', $path) or die("Can't open '$path': $!\n");

        if (defined $wikipreamble) {
            my $wikified_preamble = wikify('md', $wikipreamble);
            print FH "###### $wikified_preamble\n";
        }

        my $category = 'CategoryAPIMacro';
        if ($headersymstype{$refersto} == 4) {
            $category = 'CategoryAPIEnumerators';  # NOT CategoryAPIEnum!
        }

        print FH "# $sym\n\nPlease refer to [$refersto]($refersto) for details.\n\n";
        print FH "----\n";
        print FH "[CategoryAPI](CategoryAPI), [$category]($category)\n\n";

        close(FH);
    }

    # Write out Category pages...
    foreach (keys %headercategorydocs) {
        my $cat = $_;
        my $sym = $headercategorydocs{$cat};  # fake symbol
        my $raw = $headersyms{$sym};  # raw doxygen text with comment characters stripped from start/end and start of each line.
        my $wikitype = defined($wikitypes{$sym}) ? $wikitypes{$sym} : 'md';
        my $path = "$wikipath/Category$cat.$wikitype";

        $raw = wordwrap(wikify($wikitype, $raw));

        my $tmppath = "$path.tmp";
        open(FH, '>', $tmppath) or die("Can't open '$tmppath': $!\n");
        print FH "$raw\n\n";

        if (! -f $path) {  # Doesn't exist at all? Write out a template file.
            # If writing from scratch, it's always a Markdown file.
            die("Unexpected wikitype '$wikitype'!") if $wikitype ne 'md';
            print FH <<__EOF__

<!-- END CATEGORY DOCUMENTATION -->

## Functions

<!-- DO NOT HAND-EDIT CATEGORY LISTS, THEY ARE AUTOGENERATED AND WILL BE OVERWRITTEN, BASED ON TAGS IN INDIVIDUAL PAGE FOOTERS. EDIT THOSE INSTEAD. -->
<!-- BEGIN CATEGORY LIST: Category$cat, CategoryAPIFunction -->
<!-- END CATEGORY LIST -->

## Datatypes

<!-- DO NOT HAND-EDIT CATEGORY LISTS, THEY ARE AUTOGENERATED AND WILL BE OVERWRITTEN, BASED ON TAGS IN INDIVIDUAL PAGE FOOTERS. EDIT THOSE INSTEAD. -->
<!-- BEGIN CATEGORY LIST: Category$cat, CategoryAPIDatatype -->
<!-- END CATEGORY LIST -->

## Structs

<!-- DO NOT HAND-EDIT CATEGORY LISTS, THEY ARE AUTOGENERATED AND WILL BE OVERWRITTEN, BASED ON TAGS IN INDIVIDUAL PAGE FOOTERS. EDIT THOSE INSTEAD. -->
<!-- BEGIN CATEGORY LIST: Category$cat, CategoryAPIStruct -->
<!-- END CATEGORY LIST -->

## Enums

<!-- DO NOT HAND-EDIT CATEGORY LISTS, THEY ARE AUTOGENERATED AND WILL BE OVERWRITTEN, BASED ON TAGS IN INDIVIDUAL PAGE FOOTERS. EDIT THOSE INSTEAD. -->
<!-- BEGIN CATEGORY LIST: Category$cat, CategoryAPIEnum -->
<!-- END CATEGORY LIST -->

## Macros

<!-- DO NOT HAND-EDIT CATEGORY LISTS, THEY ARE AUTOGENERATED AND WILL BE OVERWRITTEN, BASED ON TAGS IN INDIVIDUAL PAGE FOOTERS. EDIT THOSE INSTEAD. -->
<!-- BEGIN CATEGORY LIST: Category$cat, CategoryAPIMacro -->
<!-- END CATEGORY LIST -->

----
[CategoryAPICategory](CategoryAPICategory)

__EOF__
;
        } else {
            my $endstr = $wikisyms{$sym}->{'[footer]'};
            if (defined($endstr)) {
                print FH $endstr;
            }
        }

        close(FH);
        rename($tmppath, $path) or die("Can't rename '$tmppath' to '$path': $!\n");
    }

    # Write out READMEs...
    if (defined $readmepath) {
        if ( -d $readmepath ) {
            mkdir($wikireadmepath);  # just in case
            opendir(DH, $readmepath) or die("Can't opendir '$readmepath': $!\n");
            while (my $d = readdir(DH)) {
                my $dent = $d;
                if ($dent =~ /\AREADME\-(.*?\.md)\Z/) {  # we only bridge Markdown files here.
                    my $wikifname = $1;
                    next if $wikifname eq 'FrontPage.md';
                    filecopy("$readmepath/$dent", "$wikireadmepath/$wikifname", "\n");
                }
            }
            closedir(DH);

            my @pages = ();
            opendir(DH, $wikireadmepath) or die("Can't opendir '$wikireadmepath': $!\n");
            while (my $d = readdir(DH)) {
                my $dent = $d;
                if ($dent =~ /\A(.*?)\.(mediawiki|md)\Z/) {
                    my $wikiname = $1;
                    next if $wikiname eq 'FrontPage';
                    push @pages, $wikiname;
                }
            }
            closedir(DH);

            open(FH, '>', "$wikireadmepath/FrontPage.md") or die("Can't open '$wikireadmepath/FrontPage.md': $!\n");
            print FH "# All READMEs available here\n\n";
            foreach (sort @pages) {
                my $wikiname = $_;
                print FH "- [$wikiname]($wikiname)\n";
            }
            close(FH);
        }
    }

    # Write out quick reference pages...
    if ($quickrefenabled) {
        generate_quickref(\%briefs, "$wikipath/QuickReference.md", 0);
        generate_quickref(\%briefs, "$wikipath/QuickReferenceNoUnicode.md", 1);
    }
} elsif ($copy_direction == -2) { # --copy-to-manpages
    # This only takes from the wiki data, since it has sections we omit from the headers, like code examples.

    File::Path::make_path("$manpath/man3");

    $dewikify_mode = 'manpage';
    $wordwrap_mode = 'manpage';

    my $introtxt = '';
    if (0) {
    open(FH, '<', "$srcpath/LICENSE.txt") or die("Can't open '$srcpath/LICENSE.txt': $!\n");
    while (<FH>) {
        chomp;
        $introtxt .= ".\\\" $_\n";
    }
    close(FH);
    }

    if (!$gitrev) {
        $gitrev = `cd "$srcpath" ; git rev-list HEAD~..`;
        chomp($gitrev);
    }

    # !!! FIXME
    open(FH, '<', "$srcpath/$versionfname") or die("Can't open '$srcpath/$versionfname': $!\n");
    my $majorver = 0;
    my $minorver = 0;
    my $microver = 0;
    while (<FH>) {
        chomp;
        if (/$versionmajorregex/) {
            $majorver = int($1);
        } elsif (/$versionminorregex/) {
            $minorver = int($1);
        } elsif (/$versionmicroregex/) {
            $microver = int($1);
        }
    }
    close(FH);
    my $fullversion = "$majorver.$minorver.$microver";

    foreach (keys %headersyms) {
        my $sym = $_;
        next if not defined $wikisyms{$sym};  # don't have a page for that function, skip it.
        next if $sym =~ /\A\[category documentation\]/;   # not real symbols
        next if (defined $manpagesymbolfilterregex) && ($sym =~ /$manpagesymbolfilterregex/);
        my $symtype = $headersymstype{$sym};
        my $wikitype = $wikitypes{$sym};
        my $sectionsref = $wikisyms{$sym};
        my $remarks = $sectionsref->{'Remarks'};
        my $returns = $sectionsref->{'Return Value'};
        my $version = $sectionsref->{'Version'};
        my $threadsafety = $sectionsref->{'Thread Safety'};
        my $related = $sectionsref->{'See Also'};
        my $examples = $sectionsref->{'Code Examples'};
        my $deprecated = $sectionsref->{'Deprecated'};
        my $headerfile = $manpageheaderfiletext;

        my $params = undef;

        if ($symtype == -1) {  # category documentation block.
            # nothing to be done here.
        } elsif (($symtype == 1) || (($symtype == 5))) {  # we'll assume a typedef (5) with a \param is a function pointer typedef.
            $params = $sectionsref->{'Function Parameters'};
        } elsif ($symtype == 2) {
            $params = $sectionsref->{'Macro Parameters'};
        } elsif ($symtype == 3) {
            $params = $sectionsref->{'Fields'};
        } elsif ($symtype == 4) {
            $params = $sectionsref->{'Values'};
        } else {
            die("Unexpected symtype $symtype");
        }

        $headerfile =~ s/\%fname\%/$headersymslocation{$sym}/g;
        $headerfile .= "\n";

        my $mansection;
        my $mansectionname;
        if (($symtype == 1) || ($symtype == 2)) {  # functions or macros
            $mansection = '3';
            $mansectionname = 'FUNCTIONS';
        } elsif (($symtype >= 3) && ($symtype <= 5)) {  # struct/union/enum/typedef
            $mansection = '3type';
            $mansectionname = 'DATATYPES';
        } else {
            die("Unexpected symtype $symtype");
        }

        my $brief = $sectionsref->{'[Brief]'};
        my $decl = $headerdecls{$sym};
        my $str = '';

        # the "$brief" makes sure this is a copy of the string, which is doing some weird reference thing otherwise.
        $brief = defined $brief ? "$brief" : '';
        $brief =~ s/\A[\s\n]*\= .*? \=\s*?\n+//ms;
        $brief =~ s/\A[\s\n]*\=\= .*? \=\=\s*?\n+//ms;
        $brief =~ s/\A(.*?\.) /$1\n/;  # \brief should only be one sentence, delimited by a period+space. Split if necessary.
        my @briefsplit = split /\n/, $brief;
        $brief = shift @briefsplit;
        $brief = dewikify($wikitype, $brief);

        if (defined $remarks) {
            $remarks = dewikify($wikitype, join("\n", @briefsplit) . $remarks);
        }

        $str .= $introtxt;

        $str .= ".\\\" This manpage content is licensed under Creative Commons\n";
        $str .= ".\\\"  Attribution 4.0 International (CC BY 4.0)\n";
        $str .= ".\\\"   https://creativecommons.org/licenses/by/4.0/\n";
        $str .= ".\\\" This manpage was generated from ${projectshortname}'s wiki page for $sym:\n";
        $str .= ".\\\"   $wikiurl/$sym\n";
        $str .= ".\\\" Generated with SDL/build-scripts/wikiheaders.pl\n";
        $str .= ".\\\"  revision $gitrev\n" if $gitrev ne '';
        $str .= ".\\\" Please report issues in this manpage's content at:\n";
        $str .= ".\\\"   $bugreporturl\n";
        $str .= ".\\\" Please report issues in the generation of this manpage from the wiki at:\n";
        $str .= ".\\\"   https://github.com/libsdl-org/SDL/issues/new?title=Misgenerated%20manpage%20for%20$sym\n";
        $str .= ".\\\" $projectshortname can be found at $projecturl\n";

        # Define a .URL macro. The "www.tmac" thing decides if we're using GNU roff (which has a .URL macro already), and if so, overrides the macro we just created.
        # This wizadry is from https://web.archive.org/web/20060102165607/http://people.debian.org/~branden/talks/wtfm/wtfm.pdf
        $str .= ".de URL\n";
        $str .= '\\$2 \(laURL: \\$1 \(ra\\$3' . "\n";
        $str .= "..\n";
        $str .= '.if \n[.g] .mso www.tmac' . "\n";

        $str .= ".TH $sym $mansection \"$projectshortname $fullversion\" \"$projectfullname\" \"$projectshortname$majorver $mansectionname\"\n";
        $str .= ".SH NAME\n";

        $str .= "$sym";
        $str .= " \\- $brief" if (defined $brief);
        $str .= "\n";

        if (defined $deprecated) {
            $str .= ".SH DEPRECATED\n";
            $str .= dewikify($wikitype, $deprecated) . "\n";
        }

        my $incfile = $mainincludefname;
        if (defined $headerfile) {
            if($headerfile =~ /Defined in (.*)/) {
                $incfile = $1;
            }
        }

        $str .= ".SH SYNOPSIS\n";
        $str .= ".nf\n";
        $str .= ".B #include <$incfile>\n";
        $str .= ".PP\n";

        my @decllines = split /\n/, $decl;
        foreach (@decllines) {
            $_ =~ s/\\/\\(rs/g;  # fix multiline macro defs
            $_ =~ s/"/\\(dq/g;
            $str .= ".BI \"$_\n";
        }
        $str .= ".fi\n";

        if (defined $remarks) {
            $str .= ".SH DESCRIPTION\n";
            $str .= $remarks . "\n";
        }

        if (defined $params) {
            if (($symtype == 1) || ($symtype == 5)) {
                $str .= ".SH FUNCTION PARAMETERS\n";
            } elsif ($symtype == 2) {  # macro
                $str .= ".SH MACRO PARAMETERS\n";
            } elsif ($symtype == 3) {  # struct/union
                $str .= ".SH FIELDS\n";
            } elsif ($symtype == 4) {  # enum
                $str .= ".SH VALUES\n";
            } else {
                die("Unexpected symtype $symtype");
            }

            my @lines = split /\n/, $params;
            if ($wikitype eq 'mediawiki') {
                die("Unexpected data parsing MediaWiki table") if (shift @lines ne '{|');  # Dump the '{|' start
                while (scalar(@lines) >= 3) {
                    my $c_datatype = shift @lines;
                    my $name = shift @lines;
                    my $desc = shift @lines;
                    my $terminator;  # the '|-' or '|}' line.

                    if (($desc eq '|-') or ($desc eq '|}') or (not $desc =~ /\A\|/)) {  # we seem to be out of cells, which means there was no datatype column on this one.
                        $terminator = $desc;
                        $desc = $name;
                        $name = $c_datatype;
                        $c_datatype = '';
                    } else {
                        $terminator = shift @lines;
                    }

                    last if ($terminator ne '|-') and ($terminator ne '|}');  # we seem to have run out of table.
                    $name =~ s/\A\|\s*//;
                    $name =~ s/\A\*\*(.*?)\*\*/$1/;
                    $name =~ s/\A\'\'\'(.*?)\'\'\'/$1/;
                    $desc =~ s/\A\|\s*//;
                    $desc = dewikify($wikitype, $desc);
                    #print STDERR "SYM: $sym   CDATATYPE: $c_datatype  NAME: $name   DESC: $desc TERM: $terminator\n";

                    $str .= ".TP\n";
                    $str .= ".I $name\n";
                    $str .= "$desc\n";
                }
            } elsif ($wikitype eq 'md') {
                my $l;
                $l = shift @lines;
                die("Unexpected data parsing Markdown table") if (not $l =~ /\A(\s*\|)?\s*\|\s*\|\s*\|\s*\Z/);
                $l = shift @lines;
                die("Unexpected data parsing Markdown table") if (not $l =~ /\A\s*(\|\s*\-*\s*)?\|\s*\-*\s*\|\s*\-*\s*\|\s*\Z/);
                while (scalar(@lines) >= 1) {
                    $l = shift @lines;
                    my $name;
                    my $desc;
                    if ($l =~ /\A\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*\Z/) {
                        # c datatype is $1, but we don't care about it here.
                        $name = $2;
                        $desc = $3;
                    } elsif ($l =~ /\A\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*\Z/) {
                        $name = $1;
                        $desc = $2;
                    } else {
                        last;  # we seem to have run out of table.
                    }

                    $name =~ s/\A\*\*(.*?)\*\*/$1/;
                    $name =~ s/\A\'\'\'(.*?)\'\'\'/$1/;
                    $desc = dewikify($wikitype, $desc);

                    $str .= ".TP\n";
                    $str .= ".I $name\n";
                    $str .= "$desc\n";
                }
            } else {
                die("write me");
            }
        }

        if (defined $returns) {
            # Chop datatype in parentheses off the front.
            if(!($returns =~ s/\A\([^\[]*\[[^\]]*\]\([^\)]*\)[^\)]*\) //ms)) {
                $returns =~ s/\A\([^\)]*\) //ms;
            }
            $returns = dewikify($wikitype, $returns);
            $str .= ".SH RETURN VALUE\n";
            $str .= "$returns\n";
        }

        if (defined $examples) {
            $str .= ".SH CODE EXAMPLES\n";
            $dewikify_manpage_code_indent = 0;
            $str .= dewikify($wikitype, $examples) . "\n";
            $dewikify_manpage_code_indent = 1;
        }

        if (defined $threadsafety) {
            $str .= ".SH THREAD SAFETY\n";
            $str .= dewikify($wikitype, $threadsafety) . "\n";
        }

        if (defined $version) {
            $str .= ".SH AVAILABILITY\n";
            $str .= dewikify($wikitype, $version) . "\n";
        }

        if (defined $related) {
            $str .= ".SH SEE ALSO\n";
            # !!! FIXME: lots of code duplication in all of these.
            my $v = dewikify($wikitype, $related);
            my @desclines = split /\n/, $v;
            my $nextstr = '';
            foreach (@desclines) {
                s/\(\)\Z//;  # Convert "SDL_Func()" to "SDL_Func"
                s/\[\[(.*?)\]\]/$1/;  # in case some wikilinks remain.
                s/\[(.*?)\]\(.*?\)/$1/;  # in case some wikilinks remain.
                s/\A\*\s*\Z//;
                s/\A\/*//;
                s/\A\.BR\s+//;  # dewikify added this, but we want to handle it.
                s/\A\.I\s+//;  # dewikify added this, but we want to handle it.
                s/\A\.PP\s*//;  # dewikify added this, but we want to handle it.
                s/\\\(bu//;  # dewikify added this, but we want to handle it.
                s/\A\s*[\:\*\-]\s*//;
                s/\A\s+//;
                s/\s+\Z//;
                next if $_ eq '';
                my $seealso_symtype = $headersymstype{$_};
                my $seealso_mansection = '3';
                if (defined($seealso_symtype) && ($seealso_symtype >= 3) && ($seealso_symtype <= 5)) {  # struct/union/enum/typedef
                    $seealso_mansection = '3type';
                }
                $str .= "$nextstr.BR $_ ($seealso_mansection)";
                $nextstr = ",\n";
            }
            $str .= "\n";
        }

        if (0) {
        $str .= ".SH COPYRIGHT\n";
        $str .= "This manpage is licensed under\n";
        $str .= ".UR https://creativecommons.org/licenses/by/4.0/\n";
        $str .= "Creative Commons Attribution 4.0 International (CC BY 4.0)\n";
        $str .= ".UE\n";
        $str .= ".PP\n";
        $str .= "This manpage was generated from\n";
        $str .= ".UR $wikiurl/$sym\n";
        $str .= "${projectshortname}'s wiki\n";
        $str .= ".UE\n";
        $str .= "using SDL/build-scripts/wikiheaders.pl";
        $str .= " revision $gitrev" if $gitrev ne '';
        $str .= ".\n";
        $str .= "Please report issues in this manpage at\n";
        $str .= ".UR $bugreporturl\n";
        $str .= "our bugtracker!\n";
        $str .= ".UE\n";
        }

        my $path = "$manpath/man3/$_.$mansection";
        my $tmppath = "$path.tmp";
        open(FH, '>', $tmppath) or die("Can't open '$tmppath': $!\n");
        print FH $str;
        close(FH);
        rename($tmppath, $path) or die("Can't rename '$tmppath' to '$path': $!\n");
    }

} elsif ($copy_direction == -4) { # --copy-to-latex
    # This only takes from the wiki data, since it has sections we omit from the headers, like code examples.

    print STDERR "\n(The --copy-to-latex code is known to not be ready for serious use; send patches, not bug reports, please.)\n\n";

    $dewikify_mode = 'LaTeX';
    $wordwrap_mode = 'LaTeX';

    # !!! FIXME: code duplication with --copy-to-manpages section.

    my $introtxt = '';
    if (0) {
    open(FH, '<', "$srcpath/LICENSE.txt") or die("Can't open '$srcpath/LICENSE.txt': $!\n");
    while (<FH>) {
        chomp;
        $introtxt .= ".\\\" $_\n";
    }
    close(FH);
    }

    if (!$gitrev) {
        $gitrev = `cd "$srcpath" ; git rev-list HEAD~..`;
        chomp($gitrev);
    }

    # !!! FIXME
    open(FH, '<', "$srcpath/$versionfname") or die("Can't open '$srcpath/$versionfname': $!\n");
    my $majorver = 0;
    my $minorver = 0;
    my $microver = 0;
    while (<FH>) {
        chomp;
        if (/$versionmajorregex/) {
            $majorver = int($1);
        } elsif (/$versionminorregex/) {
            $minorver = int($1);
        } elsif (/$versionmicroregex/) {
            $microver = int($1);
        }
    }
    close(FH);
    my $fullversion = "$majorver.$minorver.$microver";

    my $latex_fname = "$srcpath/$projectshortname.tex";
    my $latex_tmpfname = "$latex_fname.tmp";
    open(TEXFH, '>', "$latex_tmpfname") or die("Can't open '$latex_tmpfname' for writing: $!\n");

    print TEXFH <<__EOF__
\\documentclass{book}

\\usepackage{listings}
\\usepackage{color}
\\usepackage{hyperref}

\\definecolor{dkgreen}{rgb}{0,0.6,0}
\\definecolor{gray}{rgb}{0.5,0.5,0.5}
\\definecolor{mauve}{rgb}{0.58,0,0.82}

\\setcounter{secnumdepth}{0}

\\lstset{frame=tb,
  language=C,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\\small\\ttfamily},
  numbers=none,
  numberstyle=\\tiny\\color{gray},
  keywordstyle=\\color{blue},
  commentstyle=\\color{dkgreen},
  stringstyle=\\color{mauve},
  breaklines=true,
  breakatwhitespace=true,
  tabsize=3
}

\\begin{document}
\\frontmatter

\\title{$projectfullname $majorver.$minorver.$microver Reference Manual}
\\author{The $projectshortname Developers}
\\maketitle

\\mainmatter

__EOF__
;

    # !!! FIXME: Maybe put this in the book intro?  print TEXFH $introtxt;

    # Sort symbols by symbol type, then alphabetically.
    my @headersymskeys = sort {
        my $symtypea = $headersymstype{$a};
        my $symtypeb = $headersymstype{$b};
        $symtypea = 3 if ($symtypea > 3);
        $symtypeb = 3 if ($symtypeb > 3);
        my $rc = $symtypea <=> $symtypeb;
        if ($rc == 0) {
            $rc = lc($a) cmp lc($b);
        }
        return $rc;
    } keys %headersyms;

    my $current_symtype = 0;
    my $current_chapter = '';

    foreach (@headersymskeys) {
        my $sym = $_;
        next if not defined $wikisyms{$sym};  # don't have a page for that function, skip it.
        next if $sym =~ /\A\[category documentation\]/;   # not real symbols.
        my $symtype = $headersymstype{$sym};
        my $wikitype = $wikitypes{$sym};
        my $sectionsref = $wikisyms{$sym};
        my $remarks = $sectionsref->{'Remarks'};
        my $params = $sectionsref->{'Function Parameters'};
        my $returns = $sectionsref->{'Return Value'};
        my $version = $sectionsref->{'Version'};
        my $threadsafety = $sectionsref->{'Thread Safety'};
        my $related = $sectionsref->{'See Also'};
        my $examples = $sectionsref->{'Code Examples'};
        my $deprecated = $sectionsref->{'Deprecated'};
        my $headerfile = $manpageheaderfiletext;
        $headerfile =~ s/\%fname\%/$headersymslocation{$sym}/g;
        $headerfile .= "\n";

        my $brief = $sectionsref->{'[Brief]'};
        my $decl = $headerdecls{$sym};
        my $str = '';

        if ($current_symtype != $symtype) {
            my $newchapter = '';
            if ($symtype == 1) {
                $newchapter = 'Functions';
            } elsif ($symtype == 2) {
                $newchapter = 'Macros';
            } else {
                $newchapter = 'Datatypes';
            }

            if ($current_chapter ne $newchapter) {
                $str .= "\n\n\\chapter{$projectshortname $newchapter}\n\n\\clearpage\n\n";
                $current_chapter = $newchapter;
            }
            $current_symtype = $symtype;
        }

        $brief = "$brief";
        $brief =~ s/\A[\s\n]*\= .*? \=\s*?\n+//ms;
        $brief =~ s/\A[\s\n]*\=\= .*? \=\=\s*?\n+//ms;
        $brief =~ s/\A(.*?\.) /$1\n/;  # \brief should only be one sentence, delimited by a period+space. Split if necessary.
        my @briefsplit = split /\n/, $brief;
        $brief = shift @briefsplit;
        $brief = dewikify($wikitype, $brief);

        if (defined $remarks) {
            $remarks = dewikify($wikitype, join("\n", @briefsplit) . $remarks);
        }

        my $escapedsym = escLaTeX($sym);
        $str .= "\\hypertarget{$sym}{%\n\\section{$escapedsym}\\label{$sym}}\n\n";
        $str .= $brief if (defined $brief);
        $str .= "\n\n";

        if (defined $deprecated) {
            $str .= "\\subsection{Deprecated}\n\n";
            $str .= dewikify($wikitype, $deprecated) . "\n";
        }

        if (defined $headerfile) {
            $str .= "\\subsection{Header File}\n\n";
            $str .= dewikify($wikitype, $headerfile) . "\n";
        }

        $str .= "\\subsection{Syntax}\n\n";
        $str .= "\\begin{lstlisting}\n$decl\n\\end{lstlisting}\n";

        if (defined $params) {
            if (($symtype == 1) || ($symtype == 5)) {
                $str .= "\\subsection{Function Parameters}\n\n";
            } elsif ($symtype == 2) {  # macro
                $str .= "\\subsection{Macro Parameters}\n\n";
            } elsif ($symtype == 3) {  # struct/union
                $str .= "\\subsection{Fields}\n\n";
            } elsif ($symtype == 4) {  # enum
                $str .= "\\subsection{Values}\n\n";
            } else {
                die("Unexpected symtype $symtype");
            }

            $str .= "\\begin{center}\n";
            $str .= "    \\begin{tabular}{ | l | p{0.75\\textwidth} |}\n";
            $str .= "    \\hline\n";

            # !!! FIXME: this table parsing has gotten complicated and is pasted three times in this file; move it to a subroutine!
            my @lines = split /\n/, $params;
            if ($wikitype eq 'mediawiki') {
                die("Unexpected data parsing MediaWiki table") if (shift @lines ne '{|');  # Dump the '{|' start
                while (scalar(@lines) >= 3) {
                    my $name = shift @lines;
                    my $desc = shift @lines;
                    my $terminator = shift @lines;  # the '|-' or '|}' line.
                    last if ($terminator ne '|-') and ($terminator ne '|}');  # we seem to have run out of table.
                    $name =~ s/\A\|\s*//;
                    $name =~ s/\A\*\*(.*?)\*\*/$1/;
                    $name =~ s/\A\'\'\'(.*?)\'\'\'/$1/;
                    $name = escLaTeX($name);
                    $desc =~ s/\A\|\s*//;
                    $desc = dewikify($wikitype, $desc);
                    #print STDERR "FN: $sym   NAME: $name   DESC: $desc TERM: $terminator\n";
                    $str .= "    \\textbf{$name} & $desc \\\\ \\hline\n";
                }
            } elsif ($wikitype eq 'md') {
                my $l;
                $l = shift @lines;
                die("Unexpected data parsing Markdown table") if (not $l =~ /\A(\s*\|)?\s*\|\s*\|\s*\|\s*\Z/);
                $l = shift @lines;
                die("Unexpected data parsing Markdown table") if (not $l =~ /\A\s*(\|\s*\-*\s*)?\|\s*\-*\s*\|\s*\-*\s*\|\s*\Z/);
                while (scalar(@lines) >= 1) {
                    $l = shift @lines;
                    my $name;
                    my $desc;
                    if ($l =~ /\A\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*\Z/) {
                        # c datatype is $1, but we don't care about it here.
                        $name = $2;
                        $desc = $3;
                    } elsif ($l =~ /\A\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*\Z/) {
                        $name = $1;
                        $desc = $2;
                    } else {
                        last;  # we seem to have run out of table.
                    }

                    $name =~ s/\A\*\*(.*?)\*\*/$1/;
                    $name =~ s/\A\'\'\'(.*?)\'\'\'/$1/;
                    $name = escLaTeX($name);
                    $desc = dewikify($wikitype, $desc);
                    $str .= "    \\textbf{$name} & $desc \\\\ \\hline\n";
                }
            } else {
                die("write me");
            }

            $str .= "    \\end{tabular}\n";
            $str .= "\\end{center}\n";
        }

        if (defined $returns) {
            $returns = dewikify($wikitype, $returns);
            $returns =~ s/\A\(.*?\)\s*//;  # Chop datatype in parentheses off the front.
            $str .= "\\subsection{Return Value}\n\n";
            $str .= "$returns\n";
        }

        if (defined $remarks) {
            $str .= "\\subsection{Remarks}\n\n";
            $str .= $remarks . "\n";
        }

        if (defined $examples) {
            $str .= "\\subsection{Code Examples}\n\n";
            $dewikify_manpage_code_indent = 0;
            $str .= dewikify($wikitype, $examples) . "\n";
            $dewikify_manpage_code_indent = 1;
        }

        if (defined $threadsafety) {
            $str .= "\\subsection{Thread Safety}\n\n";
            $str .= dewikify($wikitype, $threadsafety) . "\n";
        }

        if (defined $version) {
            $str .= "\\subsection{Version}\n\n";
            $str .= dewikify($wikitype, $version) . "\n";
        }

        if (defined $related) {
            $str .= "\\subsection{See Also}\n\n";
            $str .= "\\begin{itemize}\n";
            # !!! FIXME: lots of code duplication in all of these.
            my $v = dewikify($wikitype, $related);
            my @desclines = split /\n/, $v;
            my $nextstr = '';
            foreach (@desclines) {
                s/\(\)\Z//;  # Convert "SDL_Func()" to "SDL_Func"
                s/\[\[(.*?)\]\]/$1/;  # in case some wikilinks remain.
                s/\[(.*?)\]\(.*?\)/$1/;  # in case some wikilinks remain.
                s/\A\*\s*\Z//;
                s/\A\s*\\item\s*//;
                s/\A\/*//;
                s/\A\s*[\:\*\-]\s*//;
                s/\A\s+//;
                s/\s+\Z//;
                next if $_ eq '';
                next if $_ eq '\begin{itemize}';
                next if $_ eq '\end{itemize}';
                $str .= "    \\item $_\n";
            }
            $str .= "\\end{itemize}\n";
            $str .= "\n";
        }

        # !!! FIXME: Maybe put copyright in the book intro?
        if (0) {
        $str .= ".SH COPYRIGHT\n";
        $str .= "This manpage is licensed under\n";
        $str .= ".UR https://creativecommons.org/licenses/by/4.0/\n";
        $str .= "Creative Commons Attribution 4.0 International (CC BY 4.0)\n";
        $str .= ".UE\n";
        $str .= ".PP\n";
        $str .= "This manpage was generated from\n";
        $str .= ".UR $wikiurl/$sym\n";
        $str .= "${projectshortname}'s wiki\n";
        $str .= ".UE\n";
        $str .= "using SDL/build-scripts/wikiheaders.pl";
        $str .= " revision $gitrev" if $gitrev ne '';
        $str .= ".\n";
        $str .= "Please report issues in this manpage at\n";
        $str .= ".UR $bugreporturl\n";
        $str .= "our bugtracker!\n";
        $str .= ".UE\n";
        }

        $str .= "\\clearpage\n\n";

        print TEXFH $str;
    }

    print TEXFH "\\end{document}\n\n";
    close(TEXFH);
    rename($latex_tmpfname, $latex_fname) or die("Can't rename '$latex_tmpfname' to '$latex_fname': $!\n");

} elsif ($copy_direction == -3) { # --report-coverage-gaps
    foreach (@coverage_gap) {
        print("$_\n");
    }
}

# end of wikiheaders.pl ...