summaryrefslogtreecommitdiff
path: root/xC.c
blob: 85d2e74e9f20a5ae3fe459ac6db6c4252d272e93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
/*
 * xC.c: a terminal-based IRC client
 *
 * Copyright (c) 2015 - 2024, Přemysl Eric Janouch <p@janouch.name>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

// A table of all attributes we use for output
#define ATTR_TABLE(XX)                                                  \
	XX( PROMPT,      prompt,      Terminal attrs for the prompt       ) \
	XX( DATE_CHANGE, date_change, Terminal attrs for date change      ) \
	XX( READ_MARKER, read_marker, Terminal attrs for the read marker  ) \
	XX( WARNING,     warning,     Terminal attrs for warnings         ) \
	XX( ERROR,       error,       Terminal attrs for errors           ) \
	XX( EXTERNAL,    external,    Terminal attrs for external lines   ) \
	XX( TIMESTAMP,   timestamp,   Terminal attrs for timestamps       ) \
	XX( HIGHLIGHT,   highlight,   Terminal attrs for highlights       ) \
	XX( ACTION,      action,      Terminal attrs for user actions     ) \
	XX( USERHOST,    userhost,    Terminal attrs for user@host        ) \
	XX( JOIN,        join,        Terminal attrs for joins            ) \
	XX( PART,        part,        Terminal attrs for parts            )

enum
{
	ATTR_RESET,
#define XX(x, y, z) ATTR_ ## x,
	ATTR_TABLE (XX)
#undef XX
	ATTR_COUNT
};

// User data for logger functions to enable formatted logging
#define print_fatal_data    ((void *) ATTR_ERROR)
#define print_error_data    ((void *) ATTR_ERROR)
#define print_warning_data  ((void *) ATTR_WARNING)

#include "config.h"
#define PROGRAM_NAME "xC"

// fmemopen
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700

#include "common.c"
#include "xD-replies.c"
#include "xC-proto.c"

#include <math.h>
#include <langinfo.h>
#include <locale.h>
#include <pwd.h>
#include <sys/utsname.h>
#include <wchar.h>

#include <termios.h>
#include <sys/ioctl.h>

#include <curses.h>
#include <term.h>

// Literally cancer
#undef lines
#undef columns

#include <ffi.h>

#ifdef HAVE_LUA
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#endif // HAVE_LUA

// --- Terminal information ----------------------------------------------------

static struct
{
	bool initialized;                   ///< Terminal is available
	bool stdout_is_tty;                 ///< `stdout' is a terminal
	bool stderr_is_tty;                 ///< `stderr' is a terminal

	struct termios termios;             ///< Terminal attributes
	char *color_set_fg[256];            ///< Codes to set the foreground colour
	char *color_set_bg[256];            ///< Codes to set the background colour

	int lines;                          ///< Number of lines
	int columns;                        ///< Number of columns
}
g_terminal;

static void
update_screen_size (void)
{
#ifdef TIOCGWINSZ
	if (!g_terminal.stdout_is_tty)
		return;

	struct winsize size;
	if (!ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &size))
	{
		char *row = getenv ("LINES");
		char *col = getenv ("COLUMNS");
		unsigned long tmp;
		g_terminal.lines =
			(row && xstrtoul (&tmp, row, 10)) ? tmp : size.ws_row;
		g_terminal.columns =
			(col && xstrtoul (&tmp, col, 10)) ? tmp : size.ws_col;
	}
#endif // TIOCGWINSZ
}

static bool
init_terminal (void)
{
	int tty_fd = -1;
	if ((g_terminal.stderr_is_tty = isatty (STDERR_FILENO)))
		tty_fd = STDERR_FILENO;
	if ((g_terminal.stdout_is_tty = isatty (STDOUT_FILENO)))
		tty_fd = STDOUT_FILENO;

	int err;
	if (tty_fd == -1 || setupterm (NULL, tty_fd, &err) == ERR)
		return false;

	// Make sure all terminal features used by us are supported
	if (!set_a_foreground || !set_a_background
	 || !enter_bold_mode || !exit_attribute_mode
	 || tcgetattr (tty_fd, &g_terminal.termios))
	{
		del_curterm (cur_term);
		return false;
	}

	// Make sure newlines are output correctly
	g_terminal.termios.c_oflag |= ONLCR;
	(void) tcsetattr (tty_fd, TCSADRAIN, &g_terminal.termios);

	g_terminal.lines   = tigetnum ("lines");
	g_terminal.columns = tigetnum ("cols");
	update_screen_size ();

	int max = MIN (256, max_colors);
	for (int i = 0; i < max; i++)
	{
		g_terminal.color_set_fg[i] = xstrdup (tparm (set_a_foreground,
			i, 0, 0, 0, 0, 0, 0, 0, 0));
		g_terminal.color_set_bg[i] = xstrdup (tparm (set_a_background,
			i, 0, 0, 0, 0, 0, 0, 0, 0));
	}
	return g_terminal.initialized = true;
}

static void
free_terminal (void)
{
	if (!g_terminal.initialized)
		return;

	for (int i = 0; i < 256; i++)
	{
		free (g_terminal.color_set_fg[i]);
		free (g_terminal.color_set_bg[i]);
	}
	del_curterm (cur_term);
}

// --- User interface ----------------------------------------------------------

// I'm not sure which one of these backends is worse: whether it's GNU Readline
// or BSD Editline.  They both have their own annoying problems.  We use lots
// of hacks to get the results we want and need.
//
// The abstraction is a necessary evil.  It's still not 100%, though.

/// Some arbitrary limit for the history
#define HISTORY_LIMIT 10000

/// Characters that separate words
#define WORD_BREAKING_CHARS " \f\n\r\t\v"

struct input
{
	struct input_vtable *vtable;        ///< Virtual methods
	void (*add_functions) (void *);     ///< Define functions for binding
	void *user_data;                    ///< User data for callbacks
};

typedef void *input_buffer_t;           ///< Pointer alias for input buffers

/// Named function that can be bound to a sequence of characters
typedef bool (*input_fn) (int count, int key, void *user_data);

// A little bit better than tons of forwarder functions in our case
#define CALL(self, name)        ((self)->vtable->name ((self)))
#define CALL_(self, name, ...)  ((self)->vtable->name ((self), __VA_ARGS__))

struct input_vtable
{
	/// Start the interface under the given program name
	void (*start) (void *input, const char *program_name);
	/// Stop the interface
	void (*stop) (void *input);
	/// Prepare or unprepare terminal for our needs
	void (*prepare) (void *input, bool enabled);
	/// Destroy the object
	void (*destroy) (void *input);

	/// Hide the prompt if shown
	void (*hide) (void *input);
	/// Show the prompt if hidden
	void (*show) (void *input);
	/// Retrieve current prompt string
	const char *(*get_prompt) (void *input);
	/// Change the prompt string; takes ownership
	void (*set_prompt) (void *input, char *prompt);
	/// Ring the terminal bell
	void (*ding) (void *input);

	/// Create a new input buffer
	input_buffer_t (*buffer_new) (void *input);
	/// Destroy an input buffer
	void (*buffer_destroy) (void *input, input_buffer_t);
	/// Switch to a different input buffer
	void (*buffer_switch) (void *input, input_buffer_t);
	/// Return all history lines in the locale encoding
	struct strv (*buffer_get_history) (void *input, input_buffer_t);
	/// Add a history line in the locale encoding
	void (*buffer_add_history) (void *input, input_buffer_t, const char *);

	/// Register a function that can be bound to character sequences
	void (*register_fn) (void *input,
		const char *name, const char *help, input_fn fn, void *user_data);
	/// Bind an arbitrary sequence of characters to the given named function
	void (*bind) (void *input, const char *seq, const char *fn);
	/// Bind Ctrl+key to the given named function
	void (*bind_control) (void *input, char key, const char *fn);
	/// Bind Alt+key to the given named function
	void (*bind_meta) (void *input, char key, const char *fn);

	/// Get the current line input and position within
	char *(*get_line) (void *input, int *position);
	/// Clear the current line input
	void (*clear_line) (void *input);
	/// Insert text at current position
	bool (*insert) (void *input, const char *text);

	/// Handle terminal resize
	void (*on_tty_resized) (void *input);
	/// Handle terminal input
	void (*on_tty_readable) (void *input);
};

#define INPUT_VTABLE(XX)                                                       \
	XX (start) XX (stop) XX (prepare) XX (destroy)                             \
	XX (hide) XX (show) XX (get_prompt) XX (set_prompt) XX (ding)              \
	XX (buffer_new) XX (buffer_destroy) XX (buffer_switch)                     \
	XX (buffer_get_history) XX (buffer_add_history)                            \
	XX (register_fn) XX (bind) XX (bind_control) XX (bind_meta)                \
	XX (get_line) XX (clear_line) XX (insert)                                  \
	XX (on_tty_resized) XX (on_tty_readable)

// ~~~ GNU Readline ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#ifdef HAVE_READLINE

#include <readline/readline.h>
#include <readline/history.h>

#define INPUT_START_IGNORE  RL_PROMPT_START_IGNORE
#define INPUT_END_IGNORE    RL_PROMPT_END_IGNORE

struct input_rl_fn
{
	ffi_closure closure;                ///< Closure

	LIST_HEADER (struct input_rl_fn)
	input_fn callback;                  ///< Real callback
	void *user_data;                    ///< Real callback user data
};

struct input_rl_buffer
{
	HISTORY_STATE *history;             ///< Saved history state
	char *saved_line;                   ///< Saved line content
	int saved_point;                    ///< Saved cursor position
	int saved_mark;                     ///< Saved mark
};

struct input_rl
{
	struct input super;                 ///< Parent class

	bool active;                        ///< Interface has been started
	char *prompt;                       ///< The prompt we use
	int prompt_shown;                   ///< Whether the prompt is shown now

	char *saved_line;                   ///< Saved line content
	int saved_point;                    ///< Saved cursor position
	int saved_mark;                     ///< Saved mark

	struct input_rl_fn *fns;            ///< Named functions
	struct input_rl_buffer *current;    ///< Current input buffer
};

static void
input_rl_ding (void *input)
{
	(void) input;
	rl_ding ();
}

static const char *
input_rl_get_prompt (void *input)
{
	struct input_rl *self = input;
	return self->prompt;
}

static void
input_rl_set_prompt (void *input, char *prompt)
{
	struct input_rl *self = input;
	cstr_set (&self->prompt, prompt);

	if (!self->active || self->prompt_shown <= 0)
		return;

	// First reset the prompt to work around a bug in readline
	rl_set_prompt ("");
	rl_redisplay ();

	rl_set_prompt (self->prompt);
	rl_redisplay ();
}

static void
input_rl_clear_line (void *input)
{
	(void) input;
	rl_replace_line ("", false);
	rl_redisplay ();
}

static void
input_rl__erase (struct input_rl *self)
{
	rl_set_prompt ("");
	input_rl_clear_line (self);
}

static bool
input_rl_insert (void *input, const char *s)
{
	struct input_rl *self = input;
	rl_insert_text (s);
	if (self->prompt_shown > 0)
		rl_redisplay ();

	// GNU Readline, contrary to Editline, doesn't care about validity
	return true;
}

static char *
input_rl_get_line (void *input, int *position)
{
	(void) input;
	if (position) *position = rl_point;
	return rl_copy_text (0, rl_end);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_rl_bind (void *input, const char *seq, const char *function_name)
{
	(void) input;
	rl_bind_keyseq (seq, rl_named_function (function_name));
}

static void
input_rl_bind_meta (void *input, char key, const char *function_name)
{
	// This one seems to actually work
	char keyseq[] = { '\\', 'e', key, 0 };
	input_rl_bind (input, keyseq, function_name);
#if 0
	// While this one only fucks up UTF-8
	// Tested with urxvt and xterm, on Debian Jessie/Arch, default settings
	// \M-<key> behaves exactly the same
	rl_bind_key (META (key), rl_named_function (function_name));
#endif
}

static void
input_rl_bind_control (void *input, char key, const char *function_name)
{
	char keyseq[] = { '\\', 'C', '-', key, 0 };
	input_rl_bind (input, keyseq, function_name);
}

static void
input_rl__forward (ffi_cif *cif, void *ret, void **args, void *user_data)
{
	(void) cif;

	struct input_rl_fn *data = user_data;
	if (!data->callback
		(*(int *) args[0], UNMETA (*(int *) args[1]), data->user_data))
		rl_ding ();
	*(int *) ret = 0;
}

static void
input_rl_register_fn (void *input,
	const char *name, const char *help, input_fn callback, void *user_data)
{
	struct input_rl *self = input;
	(void) help;

	void *bound_fn = NULL;
	struct input_rl_fn *data = ffi_closure_alloc (sizeof *data, &bound_fn);
	hard_assert (data);

	static ffi_cif cif;
	static ffi_type *args[2] = { &ffi_type_sint, &ffi_type_sint };
	hard_assert (ffi_prep_cif
		(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_sint, args) == FFI_OK);

	data->prev = data->next = NULL;
	data->callback = callback;
	data->user_data = user_data;
	hard_assert (ffi_prep_closure_loc (&data->closure,
		&cif, input_rl__forward, data, bound_fn) == FFI_OK);

	rl_add_defun (name, (rl_command_func_t *) bound_fn, -1);
	LIST_PREPEND (self->fns, data);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int app_readline_init (void);
static void on_readline_input (char *line);
static char **app_readline_completion (const char *text, int start, int end);

static void
input_rl_start (void *input, const char *program_name)
{
	struct input_rl *self = input;
	using_history ();
	// This can cause memory leaks, or maybe even a segfault.  Funny, eh?
	stifle_history (HISTORY_LIMIT);

	const char *slash = strrchr (program_name, '/');
	rl_readline_name = slash ? ++slash : program_name;
	rl_startup_hook = app_readline_init;
	rl_catch_sigwinch = false;
	rl_change_environment = false;

	rl_basic_word_break_characters = WORD_BREAKING_CHARS;
	rl_completer_word_break_characters = NULL;
	rl_attempted_completion_function = app_readline_completion;

	// We shouldn't produce any duplicates that the library would help us
	// autofilter, and we don't generally want alphabetic ordering at all
	rl_sort_completion_matches = false;

	hard_assert (self->prompt != NULL);
	// The inputrc is read before any callbacks are called, so we need to
	// register all functions that our user may want to map up front
	self->super.add_functions (self->super.user_data);
	rl_callback_handler_install (self->prompt, on_readline_input);

	self->prompt_shown = 1;
	self->active = true;
}

static void
input_rl_stop (void *input)
{
	struct input_rl *self = input;
	if (self->prompt_shown > 0)
		input_rl__erase (self);

	// This is okay as long as we're not called from within readline
	rl_callback_handler_remove ();
	self->active = false;
	self->prompt_shown = false;
}

static void
input_rl_prepare (void *input, bool enabled)
{
	(void) input;
	if (enabled)
		rl_prep_terminal (true);
	else
		rl_deprep_terminal ();
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// The following part shows you why it's not a good idea to use
// GNU Readline for this kind of software.  Or for anything else, really.

static void
input_rl__save_buffer (struct input_rl *self, struct input_rl_buffer *buffer)
{
	(void) self;

	buffer->history = history_get_history_state ();
	buffer->saved_line = rl_copy_text (0, rl_end);
	buffer->saved_point = rl_point;
	buffer->saved_mark = rl_mark;

	rl_replace_line ("", true);
	if (self->prompt_shown > 0)
		rl_redisplay ();
}

static void
input_rl__restore_buffer (struct input_rl *self, struct input_rl_buffer *buffer)
{
	if (buffer->history)
	{
		// history_get_history_state() just allocates a new HISTORY_STATE
		// and fills it with its current internal data.  We don't need that
		// shell anymore after reviving it.
		history_set_history_state (buffer->history);
		free (buffer->history);
		buffer->history = NULL;
	}
	else
	{
		// This should get us a clean history while keeping the flags.
		// Note that we've either saved the previous history entries, or we've
		// cleared them altogether, so there should be nothing to leak.
		HISTORY_STATE *state = history_get_history_state ();
		state->offset = state->length = state->size = 0;
		state->entries = NULL;
		history_set_history_state (state);
		free (state);
	}

	if (buffer->saved_line)
	{
		rl_replace_line (buffer->saved_line, true);
		rl_point = buffer->saved_point;
		rl_mark = buffer->saved_mark;
		cstr_set (&buffer->saved_line, NULL);

		if (self->prompt_shown > 0)
			rl_redisplay ();
	}
}

static void
input_rl_buffer_switch (void *input, input_buffer_t input_buffer)
{
	struct input_rl *self = input;
	struct input_rl_buffer *buffer = input_buffer;

	// There could possibly be occurences of the current undo list in some
	// history entry.  We either need to free the undo list, or move it
	// somewhere else to load back later, as the buffer we're switching to
	// has its own history state.
	rl_free_undo_list ();

	// Save this buffer's history so that it's independent for each buffer
	if (self->current)
		input_rl__save_buffer (self, self->current);
	else
		// Just throw it away; there should always be an active buffer however
#if RL_READLINE_VERSION >= 0x0603
		rl_clear_history ();
#else // RL_READLINE_VERSION < 0x0603
		// At least something... this may leak undo entries
		clear_history ();
#endif // RL_READLINE_VERSION < 0x0603

	input_rl__restore_buffer (self, buffer);
	self->current = buffer;
}

static struct strv
input_rl_buffer_get_history (void *input, input_buffer_t input_buffer)
{
	(void) input;
	struct input_rl_buffer *buffer = input_buffer;
	HIST_ENTRY **p =
		buffer->history ? buffer->history->entries : history_list();
	struct strv v = strv_make ();
	while (p && *p)
		strv_append (&v, (*p++)->line);
	return v;
}

static void
input_rl_buffer_add_history (void *input, input_buffer_t input_buffer,
	const char *line)
{
	(void) input;
	struct input_rl_buffer *buffer = input_buffer;

	// For inactive buffers, we'd have to either alloc_history_entry(),
	// construe a timestamp, and manually insert it into saved HISTORY_STATEs,
	// or temporarily switch histories.
	if (!buffer->history)
	{
		bool at_end = where_history () == history_length;
		add_history (line);
		if (at_end)
			next_history ();
	}
}

static void
input_rl__buffer_destroy_wo_history (struct input_rl_buffer *self)
{
	free (self->history);
	free (self->saved_line);
	free (self);
}

static void
input_rl_buffer_destroy (void *input, input_buffer_t input_buffer)
{
	(void) input;
	struct input_rl_buffer *buffer = input_buffer;

	// rl_clear_history, being the only way I know of to get rid of the complete
	// history including attached data, is a pretty recent addition.  *sigh*
#if RL_READLINE_VERSION >= 0x0603
	if (buffer->history)
	{
		// See input_rl_buffer_switch() for why we need to do this BS
		rl_free_undo_list ();

		// This is probably the only way we can free the history fully
		HISTORY_STATE *state = history_get_history_state ();

		history_set_history_state (buffer->history);
		rl_clear_history ();
		// rl_clear_history just removes history entries,
		// we have to reclaim memory for their actual container ourselves
		free (buffer->history->entries);
		free (buffer->history);
		buffer->history = NULL;

		history_set_history_state (state);
		free (state);
	}
#endif // RL_READLINE_VERSION

	input_rl__buffer_destroy_wo_history (buffer);
}

static input_buffer_t
input_rl_buffer_new (void *input)
{
	(void) input;
	struct input_rl_buffer *self = xcalloc (1, sizeof *self);
	return self;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Since {save,restore}_buffer() store history, we can't use them here like we
// do with libedit, because then buffer_destroy() can free memory that's still
// being used by readline.  This situation is bound to happen on quit.

static void
input_rl__save (struct input_rl *self)
{
	hard_assert (!self->saved_line);

	self->saved_point = rl_point;
	self->saved_mark = rl_mark;
	self->saved_line = rl_copy_text (0, rl_end);
}

static void
input_rl__restore (struct input_rl *self)
{
	hard_assert (self->saved_line);

	rl_set_prompt (self->prompt);
	rl_replace_line (self->saved_line, false);
	rl_point = self->saved_point;
	rl_mark = self->saved_mark;
	cstr_set (&self->saved_line, NULL);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_rl_hide (void *input)
{
	struct input_rl *self = input;
	if (!self->active || self->prompt_shown-- < 1)
		return;

	input_rl__save (self);
	input_rl__erase (self);
}

static void
input_rl_show (void *input)
{
	struct input_rl *self = input;
	if (!self->active || ++self->prompt_shown < 1)
		return;

	input_rl__restore (self);
	rl_redisplay ();
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_rl_on_tty_resized (void *input)
{
	(void) input;
	// This fucks up big time on terminals with automatic wrapping such as
	// rxvt-unicode or newer VTE when the current line overflows, however we
	// can't do much about that
	rl_resize_terminal ();
}

static void
input_rl_on_tty_readable (void *input)
{
	(void) input;
	rl_callback_read_char ();
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_rl_destroy (void *input)
{
	struct input_rl *self = input;
	free (self->saved_line);
	LIST_FOR_EACH (struct input_rl_fn, iter, self->fns)
		ffi_closure_free (iter);
	free (self->prompt);
	free (self);
}

#define XX(a) .a = input_rl_ ## a,
static struct input_vtable input_rl_vtable = { INPUT_VTABLE (XX) };
#undef XX

static struct input *
input_rl_new (void)
{
	struct input_rl *self = xcalloc (1, sizeof *self);
	self->super.vtable = &input_rl_vtable;
	return &self->super;
}

#define input_new input_rl_new
#endif // HAVE_READLINE

// ~~~ BSD Editline ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#ifdef HAVE_EDITLINE

#include <histedit.h>

#define INPUT_START_IGNORE  '\x01'
#define INPUT_END_IGNORE    '\x01'

struct input_el_fn
{
	ffi_closure closure;                ///< Closure

	LIST_HEADER (struct input_el_fn)
	input_fn callback;                  ///< Real callback
	void *user_data;                    ///< Real callback user data

	wchar_t *name;                      ///< Function name
	wchar_t *help;                      ///< Function help
};

struct input_el_buffer
{
	HistoryW *history;                  ///< The history object
	wchar_t *saved_line;                ///< Saved line content
	int saved_len;                      ///< Length of the saved line
	int saved_point;                    ///< Saved cursor position
};

struct input_el
{
	struct input super;                 ///< Parent class
	EditLine *editline;                 ///< The EditLine object

	bool active;                        ///< Are we a thing?
	char *prompt;                       ///< The prompt we use
	int prompt_shown;                   ///< Whether the prompt is shown now

	struct input_el_fn *fns;            ///< Named functions
	struct input_el_buffer *current;    ///< Current input buffer
};

static void app_editline_init (struct input_el *self);

static void
input_el__redisplay (void *input)
{
	// See rl_redisplay(), however NetBSD editline's map.c v1.54 breaks VREPRINT
	// so we bind redisplay somewhere else in app_editline_init()
	struct input_el *self = input;
	wchar_t x[] = { L'q' & 31, 0 };
	el_wpush (self->editline, x);

	// We have to do this or it gets stuck and nothing is done
	int dummy_count = 0;
	(void) el_wgets (self->editline, &dummy_count);
}

static char *
input_el__make_prompt (EditLine *editline)
{
	struct input_el *self = NULL;
	el_get (editline, EL_CLIENTDATA, &self);
	if (!self->prompt)
		return "";
	return self->prompt;
}

static char *
input_el__make_empty_prompt (EditLine *editline)
{
	(void) editline;
	return "";
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_el_ding (void *input)
{
	// XXX: this isn't probably very portable;
	//   we could use "bell" from terminfo but that creates a dependency
	(void) input;
	write (STDOUT_FILENO, "\a", 1);
}

static const char *
input_el_get_prompt (void *input)
{
	struct input_el *self = input;
	return self->prompt;
}

static void
input_el_set_prompt (void *input, char *prompt)
{
	struct input_el *self = input;
	cstr_set (&self->prompt, prompt);

	if (self->prompt_shown > 0)
		input_el__redisplay (self);
}

static void
input_el_clear_line (void *input)
{
	struct input_el *self = input;
	const LineInfoW *info = el_wline (self->editline);
	int len = info->lastchar - info->buffer;
	int point = info->cursor - info->buffer;
	el_cursor (self->editline, len - point);
	el_wdeletestr (self->editline, len);
	input_el__redisplay (self);
}

static void
input_el__erase (struct input_el *self)
{
	el_set (self->editline, EL_PROMPT, input_el__make_empty_prompt);
	input_el_clear_line (self);
}

static bool
input_el_insert (void *input, const char *s)
{
	struct input_el *self = input;
	bool success = !*s || !el_insertstr (self->editline, s);
	if (self->prompt_shown > 0)
		input_el__redisplay (self);
	return success;
}

static char *
input_el_get_line (void *input, int *position)
{
	struct input_el *self = input;
	const LineInfo *info = el_line (self->editline);
	int point = info->cursor - info->buffer;
	if (position) *position = point;
	return xstrndup (info->buffer, info->lastchar - info->buffer);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_el_bind (void *input, const char *seq, const char *function_name)
{
	struct input_el *self = input;
	el_set (self->editline, EL_BIND, seq, function_name, NULL);
}

static void
input_el_bind_meta (void *input, char key, const char *function_name)
{
	char keyseq[] = { 'M', '-', key, 0 };
	input_el_bind (input, keyseq, function_name);
}

static void
input_el_bind_control (void *input, char key, const char *function_name)
{
	char keyseq[] = { '^', key, 0 };
	input_el_bind (input, keyseq, function_name);
}

static void
input_el__forward (ffi_cif *cif, void *ret, void **args, void *user_data)
{
	(void) cif;

	struct input_el_fn *data = user_data;
	*(unsigned char *) ret = data->callback
		(1, *(int *) args[1], data->user_data) ? CC_NORM : CC_ERROR;
}

static wchar_t *
ascii_to_wide (const char *ascii)
{
	size_t len = strlen (ascii) + 1;
	wchar_t *wide = xcalloc (sizeof *wide, len);
	while (len--)
		hard_assert ((wide[len] = (unsigned char) ascii[len]) < 0x80);
	return wide;
}

static void
input_el_register_fn (void *input,
	const char *name, const char *help, input_fn callback, void *user_data)
{
	void *bound_fn = NULL;
	struct input_el_fn *data = ffi_closure_alloc (sizeof *data, &bound_fn);
	hard_assert (data);

	static ffi_cif cif;
	static ffi_type *args[2] = { &ffi_type_pointer, &ffi_type_sint };
	hard_assert (ffi_prep_cif
		(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_uchar, args) == FFI_OK);

	data->user_data = user_data;
	data->callback = callback;
	data->name = ascii_to_wide (name);
	data->help = ascii_to_wide (help);
	hard_assert (ffi_prep_closure_loc (&data->closure,
		&cif, input_el__forward, data, bound_fn) == FFI_OK);

	struct input_el *self = input;
	el_wset (self->editline, EL_ADDFN, data->name, data->help, bound_fn);
	LIST_PREPEND (self->fns, data);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_el_start (void *input, const char *program_name)
{
	struct input_el *self = input;
	self->editline = el_init (program_name, stdin, stdout, stderr);
	el_set (self->editline, EL_CLIENTDATA, self);
	el_set (self->editline, EL_PROMPT_ESC,
		input_el__make_prompt, INPUT_START_IGNORE);
	el_set (self->editline, EL_SIGNAL, false);
	el_set (self->editline, EL_UNBUFFERED, true);
	el_set (self->editline, EL_EDITOR, "emacs");

	app_editline_init (self);

	self->prompt_shown = 1;
	self->active = true;
}

static void
input_el_stop (void *input)
{
	struct input_el *self = input;
	if (self->prompt_shown > 0)
		input_el__erase (self);

	el_end (self->editline);
	self->editline = NULL;
	self->active = false;
	self->prompt_shown = false;
}

static void
input_el_prepare (void *input, bool enabled)
{
	struct input_el *self = input;
	el_set (self->editline, EL_PREP_TERM, enabled);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_el__save_buffer (struct input_el *self, struct input_el_buffer *buffer)
{
	const LineInfoW *info = el_wline (self->editline);
	int len = info->lastchar - info->buffer;
	int point = info->cursor - info->buffer;

	wchar_t *line = calloc (sizeof *info->buffer, len + 1);
	memcpy (line, info->buffer, sizeof *info->buffer * len);
	el_cursor (self->editline, len - point);
	el_wdeletestr (self->editline, len);

	buffer->saved_line = line;
	buffer->saved_point = point;
	buffer->saved_len = len;
}

static void
input_el__save (struct input_el *self)
{
	if (self->current)
		input_el__save_buffer (self, self->current);
}

static void
input_el__restore_buffer (struct input_el *self, struct input_el_buffer *buffer)
{
	if (buffer->saved_line)
	{
		el_winsertstr (self->editline, buffer->saved_line);
		el_cursor (self->editline,
			-(buffer->saved_len - buffer->saved_point));
		free (buffer->saved_line);
		buffer->saved_line = NULL;
	}
}

static void
input_el__restore (struct input_el *self)
{
	if (self->current)
		input_el__restore_buffer (self, self->current);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Editline keeping its own history position (look for "eventno" there).
// This is the only sane way of resetting it.
static void
input_el__start_over (struct input_el *self)
{
	wchar_t x[] = { L'c' & 31, 0 };
	el_wpush (self->editline, x);

	int dummy_count = 0;
	(void) el_wgets (self->editline, &dummy_count);
}

static void
input_el_buffer_switch (void *input, input_buffer_t input_buffer)
{
	struct input_el *self = input;
	struct input_el_buffer *buffer = input_buffer;
	if (!self->active)
		return;

	if (self->current)
		input_el__save_buffer (self, self->current);

	self->current = buffer;
	el_wset (self->editline, EL_HIST, history, buffer->history);
	// We only know how to reset the history position to be at the end.
	input_el__start_over (self);
	input_el__restore_buffer (self, buffer);
}

static struct strv
input_el_buffer_get_history (void *input, input_buffer_t input_buffer)
{
	(void) input;
	struct input_el_buffer *buffer = input_buffer;
	struct strv v = strv_make ();
	HistEventW ev;
	if (history_w (buffer->history, &ev, H_LAST) < 0)
		return v;

	do
	{
		size_t len = wcstombs (NULL, ev.str, 0);
		if (len++ == (size_t) -1)
			continue;

		char *mb = xmalloc (len);
		mb[wcstombs (mb, ev.str, len)] = 0;
		strv_append_owned (&v, mb);
	}
	while (history_w (buffer->history, &ev, H_PREV) >= 0);
	return v;
}

static void
input_el_buffer_add_history (void *input, input_buffer_t input_buffer,
	const char *line)
{
	(void) input;
	struct input_el_buffer *buffer = input_buffer;

	// When currently iterating history, this makes editline's internal
	// history pointer wrongly point to a newer entry.
	size_t len = mbstowcs (NULL, line, 0);
	if (len++ != (size_t) -1)
	{
		wchar_t *wc = xcalloc (len, sizeof *wc);
		wc[mbstowcs (wc, line, len)] = 0;
		HistEventW ev;
		(void) history_w (buffer->history, &ev, H_ENTER, wc);
		free (wc);
	}
}

static void
input_el_buffer_destroy (void *input, input_buffer_t input_buffer)
{
	struct input_el *self = input;
	struct input_el_buffer *buffer = input_buffer;
	if (self->active && self->current == buffer)
	{
		el_wset (self->editline, EL_HIST, history, NULL);
		self->current = NULL;
	}

	history_wend (buffer->history);
	free (buffer->saved_line);
	free (buffer);
}

static input_buffer_t
input_el_buffer_new (void *input)
{
	(void) input;
	struct input_el_buffer *self = xcalloc (1, sizeof *self);
	self->history = history_winit ();

	HistEventW ev;
	history_w (self->history, &ev, H_SETSIZE, HISTORY_LIMIT);
	return self;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_el_hide (void *input)
{
	struct input_el *self = input;
	if (!self->active || self->prompt_shown-- < 1)
		return;

	input_el__save (self);
	input_el__erase (self);
}

static void
input_el_show (void *input)
{
	struct input_el *self = input;
	if (!self->active || ++self->prompt_shown < 1)
		return;

	input_el__restore (self);
	el_set (self->editline,
		EL_PROMPT_ESC, input_el__make_prompt, INPUT_START_IGNORE);
	input_el__redisplay (self);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_el_on_tty_resized (void *input)
{
	struct input_el *self = input;
	el_resize (self->editline);
}

static void
input_el_on_tty_readable (void *input)
{
	// We bind the return key to process it how we need to
	struct input_el *self = input;

	// el_gets() with EL_UNBUFFERED doesn't work with UTF-8,
	// we must use the wide-character interface
	int count = 0;
	const wchar_t *buf = el_wgets (self->editline, &count);
	if (!buf || count-- <= 0)
		return;

	if (count == 0 && buf[0] == ('D' - 0x40) /* hardcoded VEOF in el_wgets() */)
	{
		el_deletestr (self->editline, 1);
		input_el__redisplay (self);
		input_el_ding (self);
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
input_el_destroy (void *input)
{
	struct input_el *self = input;
	LIST_FOR_EACH (struct input_el_fn, iter, self->fns)
	{
		free (iter->name);
		free (iter->help);
		ffi_closure_free (iter);
	}
	free (self->prompt);
	free (self);
}

#define XX(a) .a = input_el_ ## a,
static struct input_vtable input_el_vtable = { INPUT_VTABLE (XX) };
#undef XX

static struct input *
input_el_new (void)
{
	struct input_el *self = xcalloc (1, sizeof *self);
	self->super.vtable = &input_el_vtable;
	return &self->super;
}

#define input_new input_el_new
#endif // HAVE_EDITLINE

// --- Application data --------------------------------------------------------

// All text stored in our data structures is encoded in UTF-8.  Or at least
// should be--our only ways of retrieving strings are: via the command line
// (converted from locale, no room for errors), via the configuration file
// (restrictive ASCII grammar for bare words and an internal check for strings),
// and via plugins (meticulously validated).
//
// The only exception is IRC identifiers.

// ~~~ Scripting support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// We need a few reference countable objects with support for both strong
// and weak references (mainly used for scripted plugins).
//
// Beware that if you don't own the object, you will most probably want
// to keep the weak reference link so that you can get rid of it later.
// Also note that you have to make sure the user_data don't leak resources.
//
// Having a callback is more versatile than just nulling out a pointer.

/// Callback just before a reference counted object is destroyed
typedef void (*destroy_cb_fn) (void *object, void *user_data);

struct weak_ref_link
{
	LIST_HEADER (struct weak_ref_link)

	destroy_cb_fn on_destroy;           ///< Called when object is destroyed
	void *user_data;                    ///< User data
};

static struct weak_ref_link *
weak_ref (struct weak_ref_link **list, destroy_cb_fn cb, void *user_data)
{
	struct weak_ref_link *link = xcalloc (1, sizeof *link);
	link->on_destroy = cb;
	link->user_data = user_data;
	LIST_PREPEND (*list, link);
	return link;
}

static void
weak_unref (struct weak_ref_link **list, struct weak_ref_link **link)
{
	if (*link)
		LIST_UNLINK (*list, *link);
	free (*link);
	*link = NULL;
}

#define REF_COUNTABLE_HEADER                                                   \
	size_t ref_count;                   /**< Reference count                */ \
	struct weak_ref_link *weak_refs;    /**< To remove any weak references  */

#define REF_COUNTABLE_METHODS(name)                                            \
	static struct name *                                                       \
	name ## _ref (struct name *self)                                           \
	{                                                                          \
		self->ref_count++;                                                     \
		return self;                                                           \
	}                                                                          \
																			   \
	static void                                                                \
	name ## _unref (struct name *self)                                         \
	{                                                                          \
		if (--self->ref_count)                                                 \
			return;                                                            \
		LIST_FOR_EACH (struct weak_ref_link, iter, self->weak_refs)            \
		{                                                                      \
			iter->on_destroy (self, iter->user_data);                          \
			free (iter);                                                       \
		}                                                                      \
		name ## _destroy (self);                                               \
	}                                                                          \
																			   \
	static struct weak_ref_link *                                              \
	name ## _weak_ref (struct name *self, destroy_cb_fn cb, void *user_data)   \
	{ return weak_ref (&self->weak_refs, cb, user_data); }                     \
																			   \
	static void                                                                \
	name ## _weak_unref (struct name *self, struct weak_ref_link **link)       \
	{ weak_unref (&self->weak_refs, link); }

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Simple introspection framework to simplify exporting stuff to Lua, since
// there is a lot of it.  While not fully automated, at least we have control
// over which fields are exported.

enum ispect_type
{
	ISPECT_BOOL, ISPECT_INT, ISPECT_UINT, ISPECT_SIZE, ISPECT_STRING,

	ISPECT_STR,                         ///< "struct str"
	ISPECT_STR_MAP,                     ///< "struct str_map"
	ISPECT_REF                          ///< Weakly referenced object
};

struct ispect_field
{
	const char *name;                   ///< Name of the field
	size_t offset;                      ///< Offset in the structure
	enum ispect_type type;              ///< Type of the field

	enum ispect_type subtype;           ///< STR_MAP subtype
	struct ispect_field *fields;        ///< REF target fields
	bool is_list;                       ///< REF target is a list
};

#define ISPECT(object, field, type)                                            \
	{ #field, offsetof (struct object, field), ISPECT_##type, 0, NULL, false },
#define ISPECT_REF(object, field, is_list, ref_type)                           \
	{ #field, offsetof (struct object, field), ISPECT_REF, 0,                  \
	  g_##ref_type##_ispect, is_list },
#define ISPECT_MAP(object, field, subtype)                                     \
	{ #field, offsetof (struct object, field), ISPECT_STR_MAP,                 \
	  ISPECT_##subtype, NULL, false },
#define ISPECT_MAP_REF(object, field, is_list, ref_type)                       \
	{ #field, offsetof (struct object, field), ISPECT_STR_MAP,                 \
	  ISPECT_REF, g_##ref_type##_ispect, is_list },

// ~~~ Chat ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

struct user_channel
{
	LIST_HEADER (struct user_channel)

	struct channel *channel;            ///< Reference to channel
};

static struct user_channel *
user_channel_new (struct channel *channel)
{
	struct user_channel *self = xcalloc (1, sizeof *self);
	self->channel = channel;
	return self;
}

static void
user_channel_destroy (struct user_channel *self)
{
	// The "channel" reference is weak and this object should get
	// destroyed whenever the user stops being in the channel.
	free (self);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// We keep references to user information in channels and buffers,
// and weak references in the name lookup table.

struct user
{
	REF_COUNTABLE_HEADER

	char *nickname;                     ///< Literal nickname
	bool away;                          ///< User is away

	struct user_channel *channels;      ///< Channels the user is on (with us)
};

static struct ispect_field g_user_ispect[] =
{
	ISPECT( user, nickname, STRING )
	ISPECT( user, away,     BOOL   )
	{}
};

static struct user *
user_new (char *nickname)
{
	struct user *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;
	self->nickname = nickname;
	return self;
}

static void
user_destroy (struct user *self)
{
	free (self->nickname);
	LIST_FOR_EACH (struct user_channel, iter, self->channels)
		user_channel_destroy (iter);
	free (self);
}

REF_COUNTABLE_METHODS (user)

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct channel_user
{
	LIST_HEADER (struct channel_user)

	struct user *user;                  ///< Reference to user
	char *prefixes;                     ///< Ordered @+... characters
};

static struct channel_user *
channel_user_new (struct user *user, const char *prefixes)
{
	struct channel_user *self = xcalloc (1, sizeof *self);
	self->user = user;
	self->prefixes = xstrdup (prefixes);
	return self;
}

static void
channel_user_destroy (struct channel_user *self)
{
	user_unref (self->user);
	free (self->prefixes);
	free (self);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// We keep references to channels in their buffers,
// and weak references in their users and the name lookup table.

struct channel
{
	REF_COUNTABLE_HEADER

	struct server *s;                   ///< Server

	char *name;                         ///< Channel name
	char *topic;                        ///< Channel topic

	// XXX: write something like an ordered set of characters object?
	struct str no_param_modes;          ///< No parameter channel modes
	struct str_map param_modes;         ///< Parametrized channel modes

	struct channel_user *users;         ///< Channel users
	struct strv names_buf;              ///< Buffer for RPL_NAMREPLY
	size_t users_len;                   ///< User count

	bool left_manually;                 ///< Don't rejoin on reconnect
	bool show_names_after_who;          ///< RPL_ENDOFWHO delays RPL_ENDOFNAMES
};

static struct ispect_field g_channel_ispect[] =
{
	ISPECT( channel, name,           STRING  )
	ISPECT( channel, topic,          STRING  )
	ISPECT( channel, no_param_modes, STR     )
	ISPECT_MAP( channel, param_modes, STRING )
	ISPECT( channel, users_len,      SIZE    )
	ISPECT( channel, left_manually,  BOOL    )
	{}
};

static struct channel *
channel_new (struct server *s, char *name)
{
	struct channel *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;
	self->s = s;
	self->name = name;
	self->no_param_modes = str_make ();
	self->param_modes = str_map_make (free);
	self->names_buf = strv_make ();
	return self;
}

static void
channel_destroy (struct channel *self)
{
	free (self->name);
	free (self->topic);
	str_free (&self->no_param_modes);
	str_map_free (&self->param_modes);
	// Owner has to make sure we have no users by now
	hard_assert (!self->users && !self->users_len);
	strv_free (&self->names_buf);
	free (self);
}

REF_COUNTABLE_METHODS (channel)

// ~~~ Attribute utilities ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

enum
{
	TEXT_BOLD        = 1 << 0,
	TEXT_ITALIC      = 1 << 1,
	TEXT_UNDERLINE   = 1 << 2,
	TEXT_INVERSE     = 1 << 3,
	TEXT_BLINK       = 1 << 4,
	TEXT_CROSSED_OUT = 1 << 5,
	TEXT_MONOSPACE   = 1 << 6
};

// Similar to code in liberty-tui.c.
struct attrs
{
	short fg;                           ///< Foreground (256-colour cube or -1)
	short bg;                           ///< Background (256-colour cube or -1)
	unsigned attrs;                     ///< TEXT_* mask
};

/// Decode attributes in the value using a subset of the git config format,
/// ignoring all errors since it doesn't affect functionality
static struct attrs
attrs_decode (const char *value)
{
	struct strv v = strv_make ();
	cstr_split (value, " ", true, &v);

	int colors = 0;
	struct attrs attrs = { -1, -1, 0 };
	for (char **it = v.vector; *it; it++)
	{
		char *end = NULL;
		long n = strtol (*it, &end, 10);
		if (*it != end && !*end && n >= SHRT_MIN && n <= SHRT_MAX)
		{
			if (colors == 0) attrs.fg = n;
			if (colors == 1) attrs.bg = n;
			colors++;
		}
		else if (!strcmp (*it, "bold"))    attrs.attrs |= TEXT_BOLD;
		else if (!strcmp (*it, "italic"))  attrs.attrs |= TEXT_ITALIC;
		else if (!strcmp (*it, "ul"))      attrs.attrs |= TEXT_UNDERLINE;
		else if (!strcmp (*it, "reverse")) attrs.attrs |= TEXT_INVERSE;
		else if (!strcmp (*it, "blink"))   attrs.attrs |= TEXT_BLINK;
		else if (!strcmp (*it, "strike"))  attrs.attrs |= TEXT_CROSSED_OUT;
	}
	strv_free (&v);
	return attrs;
}

// ~~~ Buffers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

enum formatter_item_type
{
	FORMATTER_ITEM_END,                 ///< Sentinel value for arrays
	FORMATTER_ITEM_TEXT,                ///< Text
	FORMATTER_ITEM_ATTR,                ///< Formatting attributes
	FORMATTER_ITEM_FG_COLOR,            ///< Foreground colour
	FORMATTER_ITEM_BG_COLOR,            ///< Background colour
	FORMATTER_ITEM_SIMPLE,              ///< Toggle IRC formatting
	FORMATTER_ITEM_IGNORE_ATTR          ///< Un/set attribute ignoration
};

struct formatter_item
{
	enum formatter_item_type type : 16; ///< Type of this item
	int attribute                 : 16; ///< Attribute ID or a TEXT_* mask
	int color;                          ///< Colour ([256 << 16] | 16)
	char *text;                         ///< String
};

static void
formatter_item_free (struct formatter_item *self)
{
	free (self->text);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct formatter
{
	struct app_context *ctx;            ///< Application context
	struct server *s;                   ///< Server

	bool clean;                         ///< Assume ATTR_RESET
	struct formatter_item *items;       ///< Items
	size_t items_len;                   ///< Items used
	size_t items_alloc;                 ///< Items allocated
};

static struct formatter
formatter_make (struct app_context *ctx, struct server *s)
{
	struct formatter self = { .ctx = ctx, .s = s, .clean = true };
	self.items = xcalloc (sizeof *self.items, (self.items_alloc = 16));
	return self;
}

static void
formatter_free (struct formatter *self)
{
	for (size_t i = 0; i < self->items_len; i++)
		formatter_item_free (&self->items[i]);
	free (self->items);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

enum buffer_line_flags
{
	BUFFER_LINE_SKIP_FILE   = 1 << 0,   ///< Don't log this to file
	BUFFER_LINE_UNIMPORTANT = 1 << 1,   ///< Joins, parts, similar spam
	BUFFER_LINE_HIGHLIGHT   = 1 << 2,   ///< The user was highlighted by this
};

// NOTE: This sequence must match up with xC-proto, only one lower.
enum buffer_line_rendition
{
	BUFFER_LINE_BARE,                   ///< Unadorned
	BUFFER_LINE_INDENT,                 ///< Just indent the line
	BUFFER_LINE_STATUS,                 ///< Status message
	BUFFER_LINE_ERROR,                  ///< Error message
	BUFFER_LINE_JOIN,                   ///< Join arrow
	BUFFER_LINE_PART,                   ///< Part arrow
	BUFFER_LINE_ACTION,                 ///< Highlighted asterisk
};

struct buffer_line
{
	LIST_HEADER (struct buffer_line)

	unsigned flags;                     ///< Functional flags
	enum buffer_line_rendition r;       ///< What the line should look like
	time_t when;                        ///< Time of the event
	struct formatter_item items[];      ///< Line data
};

/// Create a new buffer line stealing all data from the provided formatter
struct buffer_line *
buffer_line_new (struct formatter *f)
{
	// We make space for one more item that gets initialized to all zeros,
	// meaning FORMATTER_ITEM_END (because it's the first value in the enum)
	size_t items_size = f->items_len * sizeof *f->items;
	struct buffer_line *self =
		xcalloc (1, sizeof *self + items_size + sizeof *self->items);
	memcpy (self->items, f->items, items_size);

	// We've stolen pointers from the formatter, let's destroy it altogether
	free (f->items);
	memset (f, 0, sizeof *f);
	return self;
}

static void
buffer_line_destroy (struct buffer_line *self)
{
	for (struct formatter_item *iter = self->items; iter->type; iter++)
		formatter_item_free (iter);
	free (self);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

enum buffer_type
{
	BUFFER_GLOBAL,                      ///< Global information
	BUFFER_SERVER,                      ///< Server-related messages
	BUFFER_CHANNEL,                     ///< Channels
	BUFFER_PM                           ///< Private messages (query)
};

struct buffer
{
	LIST_HEADER (struct buffer)
	REF_COUNTABLE_HEADER

	enum buffer_type type;              ///< Type of the buffer
	char *name;                         ///< The name of the buffer

	struct input *input;                ///< API for "input_data"
	input_buffer_t input_data;          ///< User interface data

	// Buffer contents:

	struct buffer_line *lines;          ///< All lines in this buffer
	struct buffer_line *lines_tail;     ///< The tail of buffer lines
	unsigned lines_count;               ///< How many lines we have

	unsigned new_messages_count;        ///< # messages since last left
	unsigned new_unimportant_count;     ///< How much of that is unimportant
	bool highlighted;                   ///< We've been highlighted
	bool hide_unimportant;              ///< Hide unimportant messages

	FILE *log_file;                     ///< Log file

	// Origin information:

	struct server *server;              ///< Reference to server
	struct channel *channel;            ///< Reference to channel
	struct user *user;                  ///< Reference to user
};

static struct ispect_field g_server_ispect[];
static struct ispect_field g_buffer_ispect[] =
{
	ISPECT( buffer, name,                  STRING )
	ISPECT( buffer, new_messages_count,    UINT   )
	ISPECT( buffer, new_unimportant_count, UINT   )
	ISPECT( buffer, highlighted,           BOOL   )
	ISPECT( buffer, hide_unimportant,      BOOL   )
	ISPECT_REF( buffer, server,  false, server    )
	ISPECT_REF( buffer, channel, false, channel   )
	ISPECT_REF( buffer, user,    false, user      )
	{}
};

static struct buffer *
buffer_new (struct input *input, enum buffer_type type, char *name)
{
	struct buffer *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;
	self->input = input;
	self->input_data = CALL (input, buffer_new);
	self->type = type;
	self->name = name;
	return self;
}

static void
buffer_destroy (struct buffer *self)
{
	free (self->name);
	if (self->input_data)
	{
#ifdef HAVE_READLINE
		// FIXME: can't really free "history" contents from here, as we cannot
		//   be sure that the user interface pointer is valid and usable
		input_rl__buffer_destroy_wo_history (self->input_data);
#else // ! HAVE_READLINE
		CALL_ (self->input, buffer_destroy, self->input_data);
#endif // ! HAVE_READLINE
	}
	LIST_FOR_EACH (struct buffer_line, iter, self->lines)
		buffer_line_destroy (iter);
	if (self->log_file)
		(void) fclose (self->log_file);
	if (self->user)
		user_unref (self->user);
	if (self->channel)
		channel_unref (self->channel);
	free (self);
}

REF_COUNTABLE_METHODS (buffer)
#define buffer_ref do_not_use_dangerous

// ~~~ Relay ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

struct client
{
	LIST_HEADER (struct client)
	struct app_context *ctx;            ///< Application context

	// TODO: Convert this all to TLS, and only TLS, with required client cert.
	//   That means replacing plumbing functions with the /other/ set from xD.

	int socket_fd;                      ///< The TCP socket
	struct str read_buffer;             ///< Unprocessed input
	struct str write_buffer;            ///< Output yet to be sent out

	uint32_t event_seq;                 ///< Outgoing message counter
	bool initialized;                   ///< Initial sync took place

	struct poller_fd socket_event;      ///< The socket can be read/written to
};

static struct client *
client_new (void)
{
	struct client *self = xcalloc (1, sizeof *self);
	self->socket_fd = -1;
	self->read_buffer = str_make ();
	self->write_buffer = str_make ();
	return self;
}

static void
client_destroy (struct client *self)
{
	if (!soft_assert (self->socket_fd == -1))
		xclose (self->socket_fd);

	str_free (&self->read_buffer);
	str_free (&self->write_buffer);
	free (self);
}

static void client_kill (struct client *c);

// ~~~ Server ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// The only real purpose of this is to abstract away TLS
struct transport
{
	/// Initialize the transport
	bool (*init) (struct server *s, const char *hostname, struct error **e);
	/// Destroy the user data pointer
	void (*cleanup) (struct server *s);

	/// The underlying socket may have become readable, update `read_buffer'
	enum socket_io_result (*try_read) (struct server *s);
	/// The underlying socket may have become writeable, flush `write_buffer'
	enum socket_io_result (*try_write) (struct server *s);
	/// Return event mask to use in the poller
	int (*get_poll_events) (struct server *s);

	/// Called just before closing the connection from our side
	void (*in_before_shutdown) (struct server *s);
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

enum server_state
{
	IRC_DISCONNECTED,                   ///< Not connected
	IRC_CONNECTING,                     ///< Connecting to the server
	IRC_CONNECTED,                      ///< Trying to register
	IRC_REGISTERED,                     ///< We can chat now
	IRC_CLOSING,                        ///< Flushing output before shutdown
	IRC_HALF_CLOSED                     ///< Connection shutdown from our side
};

/// Convert an IRC identifier character to lower-case
typedef int (*irc_tolower_fn) (int);

/// Key conversion function for hashmap lookups
typedef size_t (*irc_strxfrm_fn) (char *, const char *, size_t);

struct server
{
	REF_COUNTABLE_HEADER
	struct app_context *ctx;            ///< Application context

	char *name;                         ///< Server identifier
	struct buffer *buffer;              ///< The buffer for this server
	struct config_item *config;         ///< Configuration root

	// Connection:

	enum server_state state;            ///< Connection state
	struct connector *connector;        ///< Connection establisher
	struct socks_connector *socks_conn; ///< SOCKS connection establisher
	unsigned reconnect_attempt;         ///< Number of reconnect attempt
	bool manual_disconnect;             ///< Don't reconnect after disconnect

	int socket;                         ///< Socket FD of the server
	struct str read_buffer;             ///< Input yet to be processed
	struct str write_buffer;            ///< Outut yet to be be sent out
	struct poller_fd socket_event;      ///< We can read from the socket

	struct transport *transport;        ///< Transport method
	void *transport_data;               ///< Transport data

	// Events:

	struct poller_timer ping_tmr;       ///< We should send a ping
	struct poller_timer timeout_tmr;    ///< Connection seems to be dead
	struct poller_timer reconnect_tmr;  ///< We should reconnect now
	struct poller_timer autojoin_tmr;   ///< Re/join channels as appropriate

	// IRC:

	// TODO: an output queue to prevent excess floods (this will be needed
	//   especially for away status polling)

	bool rehashing;                     ///< Rehashing IRC identifiers

	struct str_map irc_users;           ///< IRC user data
	struct str_map irc_channels;        ///< IRC channel data
	struct str_map irc_buffer_map;      ///< Maps IRC identifiers to buffers

	struct user *irc_user;              ///< Our own user
	int nick_counter;                   ///< Iterates "nicks" when registering
	struct str irc_user_modes;          ///< Our current user modes
	char *irc_user_host;                ///< Our current user@host
	bool autoaway_active;               ///< Autoaway is currently active

	struct strv outstanding_joins;      ///< JOINs we expect a response to

	struct strv cap_ls_buf;             ///< Buffer for IRCv3.2 CAP LS
	bool cap_echo_message;              ///< Whether the server echoes messages
	bool cap_away_notify;               ///< Whether we get AWAY notifications
	bool cap_sasl;                      ///< Whether SASL is available

	// Server-specific information (from RPL_ISUPPORT):

	irc_tolower_fn irc_tolower;         ///< Server tolower()
	irc_strxfrm_fn irc_strxfrm;         ///< Server strxfrm()

	char *irc_chantypes;                ///< Channel types (name prefixes)
	char *irc_idchan_prefixes;          ///< Prefixes for "safe channels"
	char *irc_statusmsg;                ///< Prefixes for channel targets

	char irc_extban_prefix;             ///< EXTBAN prefix or \0
	char *irc_extban_types;             ///< EXTBAN types

	char *irc_chanmodes_list;           ///< Channel modes for lists
	char *irc_chanmodes_param_always;   ///< Channel modes with mandatory param
	char *irc_chanmodes_param_when_set; ///< Channel modes with param when set
	char *irc_chanmodes_param_never;    ///< Channel modes without param

	char *irc_chanuser_prefixes;        ///< Channel user prefixes
	char *irc_chanuser_modes;           ///< Channel user modes

	unsigned irc_max_modes;             ///< Max parametrized modes per command
};

static struct ispect_field g_server_ispect[] =
{
	ISPECT( server, name,              STRING )
	ISPECT( server, state,             INT    )
	ISPECT( server, reconnect_attempt, UINT   )
	ISPECT( server, manual_disconnect, BOOL   )
	ISPECT( server, irc_user_host,     STRING )
	ISPECT( server, autoaway_active,   BOOL   )
	ISPECT( server, cap_echo_message,  BOOL   )
	ISPECT_REF( server, buffer, false, buffer )

	// TODO: either rename the underlying field or fix the plugins
	{ "user",      offsetof (struct server, irc_user),
	  ISPECT_REF, 0, g_user_ispect, false },
	{ "user_mode", offsetof (struct server, irc_user_modes),
	  ISPECT_STR, 0, NULL, false },

	{}
};

static void on_irc_timeout (void *user_data);
static void on_irc_ping_timeout (void *user_data);
static void on_irc_autojoin_timeout (void *user_data);
static void irc_initiate_connect (struct server *s);

static void
server_init_specifics (struct server *self)
{
	// Defaults as per the RPL_ISUPPORT drafts, or RFC 1459

	self->irc_tolower                   = irc_tolower;
	self->irc_strxfrm                   = irc_strxfrm;

	self->irc_chantypes                 = xstrdup ("#&");
	self->irc_idchan_prefixes           = xstrdup ("");
	self->irc_statusmsg                 = xstrdup ("");

	self->irc_extban_prefix             = 0;
	self->irc_extban_types              = xstrdup ("");

	self->irc_chanmodes_list            = xstrdup ("b");
	self->irc_chanmodes_param_always    = xstrdup ("k");
	self->irc_chanmodes_param_when_set  = xstrdup ("l");
	self->irc_chanmodes_param_never     = xstrdup ("imnpst");

	self->irc_chanuser_prefixes         = xstrdup ("@+");
	self->irc_chanuser_modes            = xstrdup ("ov");

	self->irc_max_modes                 = 3;
}

static void
server_free_specifics (struct server *self)
{
	free (self->irc_chantypes);
	free (self->irc_idchan_prefixes);
	free (self->irc_statusmsg);

	free (self->irc_extban_types);

	free (self->irc_chanmodes_list);
	free (self->irc_chanmodes_param_always);
	free (self->irc_chanmodes_param_when_set);
	free (self->irc_chanmodes_param_never);

	free (self->irc_chanuser_prefixes);
	free (self->irc_chanuser_modes);
}

static struct server *
server_new (struct poller *poller)
{
	struct server *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;

	self->socket = -1;
	self->read_buffer = str_make ();
	self->write_buffer = str_make ();
	self->state = IRC_DISCONNECTED;

	self->timeout_tmr = poller_timer_make (poller);
	self->timeout_tmr.dispatcher = on_irc_timeout;
	self->timeout_tmr.user_data = self;

	self->ping_tmr = poller_timer_make (poller);
	self->ping_tmr.dispatcher = on_irc_ping_timeout;
	self->ping_tmr.user_data = self;

	self->reconnect_tmr = poller_timer_make (poller);
	self->reconnect_tmr.dispatcher = (poller_timer_fn) irc_initiate_connect;
	self->reconnect_tmr.user_data = self;

	self->autojoin_tmr = poller_timer_make (poller);
	self->autojoin_tmr.dispatcher = on_irc_autojoin_timeout;
	self->autojoin_tmr.user_data = self;

	self->irc_users = str_map_make (NULL);
	self->irc_users.key_xfrm = irc_strxfrm;
	self->irc_channels = str_map_make (NULL);
	self->irc_channels.key_xfrm = irc_strxfrm;
	self->irc_buffer_map = str_map_make (NULL);
	self->irc_buffer_map.key_xfrm = irc_strxfrm;

	self->irc_user_modes = str_make ();

	self->outstanding_joins = strv_make ();
	self->cap_ls_buf = strv_make ();
	server_init_specifics (self);
	return self;
}

static void
server_destroy (struct server *self)
{
	free (self->name);

	if (self->connector)
	{
		connector_free (self->connector);
		free (self->connector);
	}
	if (self->socks_conn)
	{
		socks_connector_free (self->socks_conn);
		free (self->socks_conn);
	}

	if (self->transport
	 && self->transport->cleanup)
		self->transport->cleanup (self);

	if (self->socket != -1)
	{
		poller_fd_reset (&self->socket_event);
		xclose (self->socket);
	}
	str_free (&self->read_buffer);
	str_free (&self->write_buffer);

	poller_timer_reset (&self->ping_tmr);
	poller_timer_reset (&self->timeout_tmr);
	poller_timer_reset (&self->reconnect_tmr);
	poller_timer_reset (&self->autojoin_tmr);

	str_map_free (&self->irc_users);
	str_map_free (&self->irc_channels);
	str_map_free (&self->irc_buffer_map);

	if (self->irc_user)
		user_unref (self->irc_user);
	str_free (&self->irc_user_modes);
	free (self->irc_user_host);

	strv_free (&self->outstanding_joins);
	strv_free (&self->cap_ls_buf);
	server_free_specifics (self);
	free (self);
}

REF_COUNTABLE_METHODS (server)
#define server_ref do_not_use_dangerous

// ~~~ Scripting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

struct plugin
{
	LIST_HEADER (struct plugin)

	char *name;                         ///< Name of the plugin
	struct plugin_vtable *vtable;       ///< Methods
};

struct plugin_vtable
{
	/// Collect garbage
	void (*gc) (struct plugin *self);
	/// Unregister and free the plugin including all relevant resources
	void (*free) (struct plugin *self);
};

static void
plugin_destroy (struct plugin *self)
{
	self->vtable->free (self);
	free (self->name);
	free (self);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// This is a bit ugly since insertion is O(n) and the need to get rid of the
// specific type because of list macros, however I don't currently posses any
// strictly better, ordered data structure

struct hook
{
	LIST_HEADER (struct hook)
	int priority;                       ///< The lesser the sooner
};

static struct hook *
hook_insert (struct hook *list, struct hook *item)
{
	// Corner cases: list is empty or we precede everything
	if (!list || item->priority < list->priority)
	{
		LIST_PREPEND (list, item);
		return list;
	}

	// Otherwise fast-forward to the last entry that precedes us
	struct hook *before = list;
	while (before->next && before->next->priority < item->priority)
		before = before->next;

	// And link ourselves in between it and its successor
	if ((item->next = before->next))
		item->next->prev = item;
	before->next = item;
	item->prev = before;
	return list;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct input_hook
{
	struct hook super;                  ///< Common hook fields

	/// Takes over the ownership of "input", returns either NULL if input
	/// was thrown away, or a possibly modified version of it
	char *(*filter) (struct input_hook *self,
		struct buffer *buffer, char *input);
};

struct irc_hook
{
	struct hook super;                  ///< Common hook fields

	/// Takes over the ownership of "message", returns either NULL if message
	/// was thrown away, or a possibly modified version of it
	char *(*filter) (struct irc_hook *self,
		struct server *server, char *message);
};

struct prompt_hook
{
	struct hook super;                  ///< Common hook fields

	/// Returns what the prompt should look like right now based on other state
	char *(*make) (struct prompt_hook *self);
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct completion_word
{
	size_t start;                       ///< Offset to start of word
	size_t end;                         ///< Offset to end of word
};

struct completion
{
	char *line;                         ///< The line which is being completed

	struct completion_word *words;      ///< Word locations
	size_t words_len;                   ///< Number of words
	size_t words_alloc;                 ///< Number of words allocated

	size_t location;                    ///< Which word is being completed
};

struct completion_hook
{
	struct hook super;                  ///< Common hook fields

	/// Tries to add possible completions of "word" to "output"
	void (*complete) (struct completion_hook *self,
		struct completion *data, const char *word, struct strv *output);
};

// ~~~ Main context ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

struct app_context
{
	/// Default terminal attributes
	struct attrs theme_defaults[ATTR_COUNT];

	// Configuration:

	struct config config;               ///< Program configuration
	struct attrs theme[ATTR_COUNT];     ///< Terminal attributes
	bool isolate_buffers;               ///< Isolate global/server buffers
	bool beep_on_highlight;             ///< Beep on highlight
	bool logging;                       ///< Logging to file enabled
	bool show_all_prefixes;             ///< Show all prefixes before nicks
	bool word_wrapping;                 ///< Enable simple word wrapping

	struct str_map servers;             ///< Our servers

	// Relay:

	int relay_fd;                       ///< Listening socket FD
	struct client *clients;             ///< Our relay clients

	/// A single message buffer to prepare all outcoming messages within
	struct relay_event_message relay_message;

	// Events:

	struct poller_fd tty_event;         ///< Terminal input event
	struct poller_fd signal_event;      ///< Signal FD event
	struct poller_fd relay_event;       ///< New relay connection available

	struct poller_timer flush_timer;    ///< Flush all open files (e.g. logs)
	struct poller_timer date_chg_tmr;   ///< Print a date change
	struct poller_timer autoaway_tmr;   ///< Autoaway timer

	struct poller poller;               ///< Manages polled descriptors
	bool quitting;                      ///< User requested quitting
	bool polling;                       ///< The event loop is running

	// Buffers:

	struct buffer *buffers;             ///< All our buffers in order
	struct buffer *buffers_tail;        ///< The tail of our buffers

	struct buffer *global_buffer;       ///< The global buffer
	struct buffer *current_buffer;      ///< The current buffer
	struct buffer *last_buffer;         ///< Last used buffer

	struct str_map buffers_by_name;     ///< Buffers by name

	unsigned backlog_limit;             ///< Limit for buffer lines
	time_t last_displayed_msg_time;     ///< Time of last displayed message

	// Terminal:

	iconv_t term_to_utf8;               ///< Terminal encoding to UTF-8
	iconv_t term_from_utf8;             ///< UTF-8 to terminal encoding

	struct input *input;                ///< User interface

	struct poller_idle prompt_event;    ///< Deferred prompt refresh
	struct poller_idle input_event;     ///< Pending input event
	struct strv pending_input;          ///< Pending input lines

	int *nick_palette;                  ///< A 256-colour palette for nicknames
	size_t nick_palette_len;            ///< Number of entries in nick_palette

	bool awaiting_formatting_escape;    ///< Awaiting an IRC formatting escape
	bool in_bracketed_paste;            ///< User is pasting some content
	struct str input_buffer;            ///< Buffered pasted content

	bool running_pager;                 ///< Running a pager for buffer history
	bool running_editor;                ///< Running editor for the input
	char *editor_filename;              ///< The file being edited by user
	int terminal_suspended;             ///< Terminal suspension level

	// Plugins:

	struct plugin *plugins;             ///< Loaded plugins
	struct hook *input_hooks;           ///< Input hooks
	struct hook *irc_hooks;             ///< IRC hooks
	struct hook *prompt_hooks;          ///< Prompt hooks
	struct hook *completion_hooks;      ///< Autocomplete hooks
}
*g_ctx;

static struct ispect_field g_ctx_ispect[] =
{
	ISPECT_MAP_REF( app_context, servers,    false, server )
	ISPECT_REF( app_context, buffers,        true,  buffer )
	ISPECT_REF( app_context, global_buffer,  false, buffer )
	ISPECT_REF( app_context, current_buffer, false, buffer )
	{}
};

static int *
filter_color_cube_for_acceptable_nick_colors (size_t *len)
{
	// This is a pure function and we don't use threads, static storage is fine
	static int table[6 * 6 * 6];
	size_t len_counter = 0;
	for (int x = 0; x < (int) N_ELEMENTS (table); x++)
	{
		int r =  x / 36;
		int g = (x / 6) % 6;
		int b = (x % 6);

		// The first step is 95/255, the rest are 40/255,
		// as an approximation we can double the first step
		double linear_R = pow ((r + !!r) / 6., 2.2);
		double linear_G = pow ((g + !!g) / 6., 2.2);
		double linear_B = pow ((b + !!b) / 6., 2.2);

		// Use the relative luminance of colours within the cube to filter
		// colours that look okay-ish on terminals with both black and white
		// backgrounds (use the test-nick-colors script to calibrate)
		double Y = 0.2126 * linear_R + 0.7152 * linear_G + 0.0722 * linear_B;
		if (Y >= .25 && Y <= .4)
			table[len_counter++] = 16 + x;
	}
	*len = len_counter;
	return table;
}

static bool
app_iconv_open (iconv_t *target, const char *to, const char *from)
{
	if (ICONV_ACCEPTS_TRANSLIT)
	{
		char *to_real = xstrdup_printf ("%s//TRANSLIT", to);
		*target = iconv_open (to_real, from);
		free (to_real);
	}
	else
		*target = iconv_open (to, from);
	return *target != (iconv_t) -1;
}

static void
app_context_init (struct app_context *self)
{
	memset (self, 0, sizeof *self);

	self->config = config_make ();
	poller_init (&self->poller);

	self->relay_fd = -1;

	self->servers = str_map_make ((str_map_free_fn) server_unref);
	self->servers.key_xfrm = tolower_ascii_strxfrm;

	self->buffers_by_name = str_map_make (NULL);
	self->buffers_by_name.key_xfrm = tolower_ascii_strxfrm;

	// So that we don't lose the logo shortly after startup
	self->backlog_limit = 1000;
	self->last_displayed_msg_time = time (NULL);

	char *native = nl_langinfo (CODESET);
	if (!app_iconv_open (&self->term_from_utf8, native, "UTF-8")
	 || !app_iconv_open (&self->term_to_utf8, "UTF-8", native))
		exit_fatal ("creating the UTF-8 conversion object failed: %s",
			strerror (errno));

	self->input = input_new ();
	self->input->user_data = self;
	self->pending_input = strv_make ();
	self->input_buffer = str_make ();

	self->nick_palette =
		filter_color_cube_for_acceptable_nick_colors (&self->nick_palette_len);
}

static void
app_context_relay_stop (struct app_context *self)
{
	if (self->relay_fd != -1)
	{
		poller_fd_reset (&self->relay_event);
		xclose (self->relay_fd);
		self->relay_fd = -1;
	}
}

static void
app_context_free (struct app_context *self)
{
	// Plugins can try to use of the other fields when destroyed
	LIST_FOR_EACH (struct plugin, iter, self->plugins)
		plugin_destroy (iter);

	config_free (&self->config);

	LIST_FOR_EACH (struct buffer, iter, self->buffers)
	{
#ifdef HAVE_READLINE
		// We can use the user interface here; see buffer_destroy()
		CALL_ (self->input, buffer_destroy, iter->input_data);
		iter->input_data = NULL;
#endif // HAVE_READLINE
		buffer_unref (iter);
	}
	str_map_free (&self->buffers_by_name);

	app_context_relay_stop (self);
	LIST_FOR_EACH (struct client, c, self->clients)
		client_kill (c);
	relay_event_message_free (&self->relay_message);

	str_map_free (&self->servers);
	poller_free (&self->poller);

	iconv_close (self->term_from_utf8);
	iconv_close (self->term_to_utf8);

	CALL (self->input, destroy);
	strv_free (&self->pending_input);
	str_free (&self->input_buffer);

	free (self->editor_filename);
}

static void
refresh_prompt (struct app_context *ctx)
{
	// XXX: the need for this conditional could probably be resolved
	//   by some clever reordering
	if (ctx->prompt_event.poller)
		poller_idle_set (&ctx->prompt_event);
}

// --- Configuration -----------------------------------------------------------

static void
on_config_debug_mode_change (struct config_item *item)
{
	g_debug_mode = item->value.boolean;
}

static void
on_config_show_all_prefixes_change (struct config_item *item)
{
	struct app_context *ctx = item->user_data;
	ctx->show_all_prefixes = item->value.boolean;
	refresh_prompt (ctx);
}

static void on_config_relay_bind_change (struct config_item *item);
static void on_config_backlog_limit_change (struct config_item *item);
static void on_config_theme_change (struct config_item *item);
static void on_config_logging_change (struct config_item *item);

#define TRIVIAL_BOOLEAN_ON_CHANGE(name)                                        \
	static void                                                                \
	on_config_ ## name ## _change (struct config_item *item)                   \
	{                                                                          \
		struct app_context *ctx = item->user_data;                             \
		ctx->name = item->value.boolean;                                       \
	}

TRIVIAL_BOOLEAN_ON_CHANGE (isolate_buffers)
TRIVIAL_BOOLEAN_ON_CHANGE (beep_on_highlight)
TRIVIAL_BOOLEAN_ON_CHANGE (word_wrapping)

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool
config_validate_nonjunk_string
	(const struct config_item *item, struct error **e)
{
	if (item->type == CONFIG_ITEM_NULL)
		return true;

	hard_assert (config_item_type_is_string (item->type));
	for (size_t i = 0; i < item->value.string.len; i++)
	{
		// Not even a tabulator
		unsigned char c = item->value.string.str[i];
		if (iscntrl_ascii (c))
		{
			error_set (e, "control characters are not allowed");
			return false;
		}
	}
	return true;
}

static bool
config_validate_addresses
	(const struct config_item *item, struct error **e)
{
	if (item->type == CONFIG_ITEM_NULL)
		return true;
	if (!config_validate_nonjunk_string (item, e))
		return false;

	// Comma-separated list of "host[:port]" pairs
	regex_t re;
	int err = regcomp (&re, "^([^/:,]+(:[^/:,]+)?)?"
		"(,([^/:,]+(:[^/:,]+)?)?)*$", REG_EXTENDED | REG_NOSUB);
	hard_assert (!err);

	bool result = !regexec (&re, item->value.string.str, 0, NULL, 0);
	if (!result)
		error_set (e, "invalid address list string");

	regfree (&re);
	return result;
}

static bool
config_validate_nonnegative
	(const struct config_item *item, struct error **e)
{
	if (item->type == CONFIG_ITEM_NULL)
		return true;

	hard_assert (item->type == CONFIG_ITEM_INTEGER);
	if (item->value.integer >= 0)
		return true;

	error_set (e, "must be non-negative");
	return false;
}

static const struct config_schema g_config_server[] =
{
	{ .name      = "nicks",
	  .comment   = "IRC nickname",
	  .type      = CONFIG_ITEM_STRING_ARRAY,
	  .validate  = config_validate_nonjunk_string },
	{ .name      = "username",
	  .comment   = "IRC user name",
	  .type      = CONFIG_ITEM_STRING,
	  .validate  = config_validate_nonjunk_string },
	{ .name      = "realname",
	  .comment   = "IRC real name/e-mail",
	  .type      = CONFIG_ITEM_STRING,
	  .validate  = config_validate_nonjunk_string },

	{ .name      = "addresses",
	  .comment   = "Addresses of the IRC network (e.g. \"irc.net:6667\")",
	  .type      = CONFIG_ITEM_STRING_ARRAY,
	  .validate  = config_validate_addresses },
	{ .name      = "password",
	  .comment   = "Password to connect to the server, if any",
	  .type      = CONFIG_ITEM_STRING,
	  .validate  = config_validate_nonjunk_string },
	// XXX: if we add support for new capabilities, the value stays unchanged
	{ .name      = "capabilities",
	  .comment   = "Capabilities to use if supported by server",
	  .type      = CONFIG_ITEM_STRING_ARRAY,
	  .validate  = config_validate_nonjunk_string,
	  .default_  = "\"multi-prefix,invite-notify,server-time,echo-message,"
		"message-tags,away-notify,cap-notify,chghost\"" },

	{ .name      = "tls",
	  .comment   = "Whether to use TLS",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off" },
	{ .name      = "tls_cert",
	  .comment   = "Client TLS certificate (PEM)",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "tls_verify",
	  .comment   = "Whether to verify certificates",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on" },
	{ .name      = "tls_ca_file",
	  .comment   = "OpenSSL CA bundle file",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "tls_ca_path",
	  .comment   = "OpenSSL CA bundle path",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "tls_ciphers",
	  .comment   = "OpenSSL cipher preference list",
	  .type      = CONFIG_ITEM_STRING,
	  .default_  = "\"DEFAULT:!MEDIUM:!LOW\"" },

	{ .name      = "autoconnect",
	  .comment   = "Connect automatically on startup",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on" },
	{ .name      = "autojoin",
	  .comment   = "Channels to join on start (e.g. \"#abc,#def key,#ghi\")",
	  .type      = CONFIG_ITEM_STRING_ARRAY,
	  .validate  = config_validate_nonjunk_string },
	{ .name      = "command",
	  .comment   = "Command to execute after a successful connect",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "command_delay",
	  .comment   = "Delay between executing \"command\" and joining channels",
	  .type      = CONFIG_ITEM_INTEGER,
	  .validate  = config_validate_nonnegative,
	  .default_  = "0" },
	{ .name      = "reconnect",
	  .comment   = "Whether to reconnect on error",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on" },
	{ .name      = "reconnect_delay",
	  .comment   = "Time between reconnecting",
	  .type      = CONFIG_ITEM_INTEGER,
	  .validate  = config_validate_nonnegative,
	  .default_  = "5" },

	{ .name      = "socks_host",
	  .comment   = "Address of a SOCKS 4a/5 proxy",
	  .type      = CONFIG_ITEM_STRING,
	  .validate  = config_validate_nonjunk_string },
	{ .name      = "socks_port",
	  .comment   = "SOCKS port number",
	  .type      = CONFIG_ITEM_INTEGER,
	  .validate  = config_validate_nonnegative,
	  .default_  = "1080" },
	{ .name      = "socks_username",
	  .comment   = "SOCKS auth. username",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "socks_password",
	  .comment   = "SOCKS auth. password",
	  .type      = CONFIG_ITEM_STRING },
	{}
};

static const struct config_schema g_config_general[] =
{
	{ .name      = "autosave",
	  .comment   = "Save configuration automatically after each change",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on" },
	{ .name      = "debug_mode",
	  .comment   = "Produce some debugging output",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off",
	  .on_change = on_config_debug_mode_change },
	{ .name      = "logging",
	  .comment   = "Log buffer contents to file",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off",
	  .on_change = on_config_logging_change },
	{ .name      = "plugin_autoload",
	  .comment   = "Plugins to automatically load on start",
	  .type      = CONFIG_ITEM_STRING_ARRAY,
	  .validate  = config_validate_nonjunk_string },
	{ .name      = "relay_bind",
	  .comment   = "Address to bind to for a user interface relay point",
	  .type      = CONFIG_ITEM_STRING,
	  .validate  = config_validate_nonjunk_string,
	  .on_change = on_config_relay_bind_change },

	// Buffer history:
	{ .name      = "backlog_limit",
	  .comment   = "Maximum number of lines stored in the backlog",
	  .type      = CONFIG_ITEM_INTEGER,
	  .validate  = config_validate_nonnegative,
	  .default_  = "1000",
	  .on_change = on_config_backlog_limit_change },
	{ .name      = "pager",
	  .comment   = "Shell command to page buffer history (args: name [path])",
	  .type      = CONFIG_ITEM_STRING,
	  .default_  = "`name=$(echo \"$1\" | sed 's/[%?:.]/\\\\&/g'); "
		"prompt='?f%F:'$name'. ?db- page %db?L of %D. .(?eEND:?PB%PB\\%..)'; "
		"LESSSECURE=1 less +Gb -Ps\"$prompt\" \"${2:--R}\"`" },
	{ .name      = "pager_strip_formatting",
	  .comment   = "Strip terminal formatting from pager input",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off" },

	// Output adjustments:
	{ .name      = "beep_on_highlight",
	  .comment   = "Ring the bell when highlighted or on a new invisible PM",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on",
	  .on_change = on_config_beep_on_highlight_change },
	{ .name      = "date_change_line",
	  .comment   = "Input to strftime(3) for the date change line",
	  .type      = CONFIG_ITEM_STRING,
	  .default_  = "\"%F\"" },
	{ .name      = "isolate_buffers",
	  .comment   = "Don't leak messages from the server and global buffers",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off",
	  .on_change = on_config_isolate_buffers_change },
	{ .name      = "read_marker_char",
	  .comment   = "The character to use for the read marker line",
	  .type      = CONFIG_ITEM_STRING,
	  .default_  = "\"-\"",
	  .validate  = config_validate_nonjunk_string },
	{ .name      = "show_all_prefixes",
	  .comment   = "Show all prefixes in front of nicknames",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off",
	  .on_change = on_config_show_all_prefixes_change },
	{ .name      = "word_wrapping",
	  .comment   = "Enable simple word wrapping in buffers",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on",
	  .on_change = on_config_word_wrapping_change },

	// User input:
	{ .name      = "editor",
	  .comment   = "VIM: \"vim +%Bgo %F\", Emacs: \"emacs -nw +%L:%C %F\", "
		"nano/micro/kakoune: \"nano/micro/kak +%L:%C %F\"",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "process_pasted_text",
	  .comment   = "Normalize newlines and quote the command prefix in pastes",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on" },

	// Pan-server configuration:
	{ .name      = "autoaway_message",
	  .comment   = "Automated away message",
	  .type      = CONFIG_ITEM_STRING,
	  .default_  = "\"I'm not here right now\"" },
	{ .name      = "autoaway_delay",
	  .comment   = "Delay from the last keypress in seconds",
	  .type      = CONFIG_ITEM_INTEGER,
	  .validate  = config_validate_nonnegative,
	  .default_  = "1800" },
	{ .name      = "reconnect_delay_growing",
	  .comment   = "Growth factor for the reconnect delay",
	  .type      = CONFIG_ITEM_INTEGER,
	  .validate  = config_validate_nonnegative,
	  .default_  = "2" },
	{ .name      = "reconnect_delay_max",
	  .comment   = "Maximum reconnect delay in seconds",
	  .type      = CONFIG_ITEM_INTEGER,
	  .validate  = config_validate_nonnegative,
	  .default_  = "600" },
	{}
};

static const struct config_schema g_config_theme[] =
{
#define XX(x, y, z) { .name = #y, .comment = #z, .type = CONFIG_ITEM_STRING, \
	.on_change = on_config_theme_change },
	ATTR_TABLE (XX)
#undef XX
	{}
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
load_config_general (struct config_item *subtree, void *user_data)
{
	config_schema_apply_to_object (g_config_general, subtree, user_data);
}

static void
load_config_theme (struct config_item *subtree, void *user_data)
{
	config_schema_apply_to_object (g_config_theme, subtree, user_data);
}

static void
register_config_modules (struct app_context *ctx)
{
	struct config *config = &ctx->config;
	// The servers are loaded later when we can create buffers for them
	config_register_module (config, "servers", NULL, NULL);
	config_register_module (config, "aliases", NULL, NULL);
	config_register_module (config, "plugins", NULL, NULL);
	config_register_module (config, "general", load_config_general, ctx);
	config_register_module (config, "theme",   load_config_theme,   ctx);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static const char *
get_config_string (struct config_item *root, const char *key)
{
	struct config_item *item = config_item_get (root, key, NULL);
	hard_assert (item);
	if (item->type == CONFIG_ITEM_NULL)
		return NULL;
	hard_assert (config_item_type_is_string (item->type));
	return item->value.string.str;
}

static bool
set_config_string
	(struct config_item *root, const char *key, const char *value)
{
	struct config_item *item = config_item_get (root, key, NULL);
	hard_assert (item);

	struct config_item *new_ = config_item_string_from_cstr (value);
	struct error *e = NULL;
	if (config_item_set_from (item, new_, &e))
		return true;

	config_item_destroy (new_);
	print_error ("couldn't set `%s' in configuration: %s", key, e->message);
	error_free (e);
	return false;
}

static int64_t
get_config_integer (struct config_item *root, const char *key)
{
	struct config_item *item = config_item_get (root, key, NULL);
	hard_assert (item && item->type == CONFIG_ITEM_INTEGER);
	return item->value.integer;
}

static bool
get_config_boolean (struct config_item *root, const char *key)
{
	struct config_item *item = config_item_get (root, key, NULL);
	hard_assert (item && item->type == CONFIG_ITEM_BOOLEAN);
	return item->value.boolean;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static struct str_map *
get_servers_config (struct app_context *ctx)
{
	return &config_item_get (ctx->config.root, "servers", NULL)->value.object;
}

static struct str_map *
get_aliases_config (struct app_context *ctx)
{
	return &config_item_get (ctx->config.root, "aliases", NULL)->value.object;
}

static struct str_map *
get_plugins_config (struct app_context *ctx)
{
	return &config_item_get (ctx->config.root, "plugins", NULL)->value.object;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
serialize_configuration (struct config_item *root, struct str *output)
{
	str_append (output,
		"# " PROGRAM_NAME " " PROGRAM_VERSION " configuration file\n"
		"#\n"
		"# Relative paths are searched for in ${XDG_CONFIG_HOME:-~/.config}\n"
		"# /" PROGRAM_NAME " as well as in $XDG_CONFIG_DIRS/" PROGRAM_NAME "\n"
		"#\n"
		"# Everything is in UTF-8.  Any custom comments will be overwritten.\n"
		"\n");

	config_item_write (root, true, output);
}

// --- Relay output ------------------------------------------------------------

static void
client_kill (struct client *c)
{
	struct app_context *ctx = c->ctx;
	poller_fd_reset (&c->socket_event);
	xclose (c->socket_fd);
	c->socket_fd = -1;

	LIST_UNLINK (ctx->clients, c);
	client_destroy (c);
}

static void
client_update_poller (struct client *c, const struct pollfd *pfd)
{
	int new_events = POLLIN;
	if (c->write_buffer.len)
		new_events |= POLLOUT;

	hard_assert (new_events != 0);
	if (!pfd || pfd->events != new_events)
		poller_fd_set (&c->socket_event, new_events);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
relay_send (struct client *c)
{
	struct relay_event_message *m = &c->ctx->relay_message;
	m->event_seq = c->event_seq++;

	// TODO: Also don't try sending anything if half-closed.
	if (!c->initialized || c->socket_fd == -1)
		return;

	// liberty has msg_{reader,writer} already, but they use 8-byte lengths.
	size_t frame_len_pos = c->write_buffer.len, frame_len = 0;
	str_pack_u32 (&c->write_buffer, 0);
	if (!relay_event_message_serialize (m, &c->write_buffer)
	 || (frame_len = c->write_buffer.len - frame_len_pos - 4) > UINT32_MAX)
	{
		print_error ("serialization failed, killing client");
		client_kill (c);
		return;
	}

	uint32_t len = htonl (frame_len);
	memcpy (c->write_buffer.str + frame_len_pos, &len, sizeof len);
	client_update_poller (c, NULL);
}

static void
relay_broadcast_except (struct app_context *ctx, struct client *exception)
{
	LIST_FOR_EACH (struct client, c, ctx->clients)
		if (c != exception)
			relay_send (c);
}

#define relay_broadcast(ctx) relay_broadcast_except ((ctx), NULL)

static struct relay_event_message *
relay_prepare (struct app_context *ctx)
{
	struct relay_event_message *m = &ctx->relay_message;
	relay_event_message_free (m);
	memset (m, 0, sizeof *m);
	return m;
}

static void
relay_prepare_ping (struct app_context *ctx)
{
	relay_prepare (ctx)->data.event = RELAY_EVENT_PING;
}

static union relay_item_data *
relay_translate_formatter (struct app_context *ctx, union relay_item_data *p,
	const struct formatter_item *i)
{
	// XXX: See attr_printer_decode_color(), this is a footgun.
	int16_t c16  = i->color;
	int16_t c256 = i->color >> 16;

	unsigned attrs = i->attribute;
	switch (i->type)
	{
	case FORMATTER_ITEM_TEXT:
		p->text.text = str_from_cstr (i->text);
		(p++)->kind = RELAY_ITEM_TEXT;
		break;
	case FORMATTER_ITEM_FG_COLOR:
		p->fg_color.color = c256 <= 0 ? c16 : c256;
		(p++)->kind = RELAY_ITEM_FG_COLOR;
		break;
	case FORMATTER_ITEM_BG_COLOR:
		p->bg_color.color = c256 <= 0 ? c16 : c256;
		(p++)->kind = RELAY_ITEM_BG_COLOR;
		break;
	case FORMATTER_ITEM_ATTR:
		(p++)->kind = RELAY_ITEM_RESET;
		if ((c256 = ctx->theme[i->attribute].fg) >= 0)
		{
			p->fg_color.color = c256;
			(p++)->kind = RELAY_ITEM_FG_COLOR;
		}
		if ((c256 = ctx->theme[i->attribute].bg) >= 0)
		{
			p->bg_color.color = c256;
			(p++)->kind = RELAY_ITEM_BG_COLOR;
		}

		attrs = ctx->theme[i->attribute].attrs;
		// Fall-through
	case FORMATTER_ITEM_SIMPLE:
		if (attrs & TEXT_BOLD)
			(p++)->kind = RELAY_ITEM_FLIP_BOLD;
		if (attrs & TEXT_ITALIC)
			(p++)->kind = RELAY_ITEM_FLIP_ITALIC;
		if (attrs & TEXT_UNDERLINE)
			(p++)->kind = RELAY_ITEM_FLIP_UNDERLINE;
		if (attrs & TEXT_INVERSE)
			(p++)->kind = RELAY_ITEM_FLIP_INVERSE;
		if (attrs & TEXT_CROSSED_OUT)
			(p++)->kind = RELAY_ITEM_FLIP_CROSSED_OUT;
		if (attrs & TEXT_MONOSPACE)
			(p++)->kind = RELAY_ITEM_FLIP_MONOSPACE;
		break;
	default:
		break;
	}
	return p;
}

static union relay_item_data *
relay_items (struct app_context *ctx, const struct formatter_item *items,
	uint32_t *len)
{
	size_t items_len = 0;
	for (size_t i = 0; items[i].type; i++)
		items_len++;

	// Beware of the upper bound, currently dominated by FORMATTER_ITEM_ATTR.
	union relay_item_data *a = xcalloc (items_len * 9, sizeof *a), *p = a;
	for (const struct formatter_item *i = items; items_len--; i++)
		p = relay_translate_formatter (ctx, p, i);

	*len = p - a;
	return a;
}

static void
relay_prepare_buffer_line (struct app_context *ctx, struct buffer *buffer,
	struct buffer_line *line, bool leak_to_active)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_line *e = &m->data.buffer_line;
	e->event = RELAY_EVENT_BUFFER_LINE;
	e->buffer_name = str_from_cstr (buffer->name);
	e->is_unimportant = !!(line->flags & BUFFER_LINE_UNIMPORTANT);
	e->is_highlight = !!(line->flags & BUFFER_LINE_HIGHLIGHT);
	e->rendition = 1 + line->r;
	e->when = line->when * 1000;
	e->leak_to_active = leak_to_active;
	e->items = relay_items (ctx, line->items, &e->items_len);
}

// TODO: Consider pushing this whole block of code much further down.
static void formatter_add (struct formatter *self, const char *format, ...);
static char *irc_to_utf8 (const char *text);

static void
relay_prepare_channel_buffer_update (struct app_context *ctx,
	struct buffer *buffer, struct relay_buffer_context_channel *e)
{
	struct channel *channel = buffer->channel;
	struct formatter f = formatter_make (ctx, buffer->server);
	if (channel->topic)
		formatter_add (&f, "#m", channel->topic);
	e->topic = relay_items (ctx, f.items, &e->topic_len);
	formatter_free (&f);

	// As in make_prompt(), conceal the last known channel modes.
	// XXX: This should use irc_channel_is_joined().
	if (!channel->users_len)
		return;

	struct str modes = str_make ();
	str_append_str (&modes, &channel->no_param_modes);

	struct str params = str_make ();
	struct str_map_iter iter = str_map_iter_make (&channel->param_modes);
	const char *param;
	while ((param = str_map_iter_next (&iter)))
	{
		str_append_c (&modes, iter.link->key[0]);
		str_append_c (&params, ' ');
		str_append (&params, param);
	}

	str_append_str (&modes, &params);
	str_free (&params);

	char *modes_utf8 = irc_to_utf8 (modes.str);
	str_free (&modes);
	e->modes = str_from_cstr (modes_utf8);
	free (modes_utf8);
}

static void
relay_prepare_buffer_update (struct app_context *ctx, struct buffer *buffer)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_update *e = &m->data.buffer_update;
	e->event = RELAY_EVENT_BUFFER_UPDATE;
	e->buffer_name = str_from_cstr (buffer->name);
	e->hide_unimportant = buffer->hide_unimportant;

	struct str *server_name = NULL;
	switch (buffer->type)
	{
	case BUFFER_GLOBAL:
		e->context.kind = RELAY_BUFFER_KIND_GLOBAL;
		break;
	case BUFFER_SERVER:
		e->context.kind = RELAY_BUFFER_KIND_SERVER;
		server_name = &e->context.server.server_name;
		break;
	case BUFFER_CHANNEL:
		e->context.kind = RELAY_BUFFER_KIND_CHANNEL;
		server_name = &e->context.channel.server_name;
		relay_prepare_channel_buffer_update (ctx, buffer, &e->context.channel);
		break;
	case BUFFER_PM:
		e->context.kind = RELAY_BUFFER_KIND_PRIVATE_MESSAGE;
		server_name = &e->context.private_message.server_name;
		break;
	}
	if (server_name)
		*server_name = str_from_cstr (buffer->server->name);
}

static void
relay_prepare_buffer_stats (struct app_context *ctx, struct buffer *buffer)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_stats *e = &m->data.buffer_stats;
	e->event = RELAY_EVENT_BUFFER_STATS;
	e->buffer_name = str_from_cstr (buffer->name);
	e->new_messages = MIN (UINT32_MAX,
		buffer->new_messages_count - buffer->new_unimportant_count);
	e->new_unimportant_messages = MIN (UINT32_MAX,
		buffer->new_unimportant_count);
	e->highlighted = buffer->highlighted;
}

static void
relay_prepare_buffer_rename (struct app_context *ctx, struct buffer *buffer,
	const char *new_name)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_rename *e = &m->data.buffer_rename;
	e->event = RELAY_EVENT_BUFFER_RENAME;
	e->buffer_name = str_from_cstr (buffer->name);
	e->new = str_from_cstr (new_name);
}

static void
relay_prepare_buffer_remove (struct app_context *ctx, struct buffer *buffer)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_remove *e = &m->data.buffer_remove;
	e->event = RELAY_EVENT_BUFFER_REMOVE;
	e->buffer_name = str_from_cstr (buffer->name);
}

static void
relay_prepare_buffer_activate (struct app_context *ctx, struct buffer *buffer)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_activate *e = &m->data.buffer_activate;
	e->event = RELAY_EVENT_BUFFER_ACTIVATE;
	e->buffer_name = str_from_cstr (buffer->name);
}

static void
relay_prepare_buffer_input (struct app_context *ctx, struct buffer *buffer,
	const char *input)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_input *e = &m->data.buffer_input;
	e->event = RELAY_EVENT_BUFFER_INPUT;
	e->buffer_name = str_from_cstr (buffer->name);
	e->text = str_from_cstr (input);
}

static void
relay_prepare_buffer_clear (struct app_context *ctx,
	struct buffer *buffer)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_buffer_clear *e = &m->data.buffer_clear;
	e->event = RELAY_EVENT_BUFFER_CLEAR;
	e->buffer_name = str_from_cstr (buffer->name);
}

enum relay_server_state
relay_server_state_for_server (struct server *s)
{
	switch (s->state)
	{
	case IRC_DISCONNECTED: return RELAY_SERVER_STATE_DISCONNECTED;
	case IRC_CONNECTING:   return RELAY_SERVER_STATE_CONNECTING;
	case IRC_CONNECTED:    return RELAY_SERVER_STATE_CONNECTED;
	case IRC_REGISTERED:   return RELAY_SERVER_STATE_REGISTERED;
	case IRC_CLOSING:
	case IRC_HALF_CLOSED:  return RELAY_SERVER_STATE_DISCONNECTING;
	}
	return 0;
}

static void
relay_prepare_server_update (struct app_context *ctx, struct server *s)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_server_update *e = &m->data.server_update;
	e->event = RELAY_EVENT_SERVER_UPDATE;
	e->server_name = str_from_cstr (s->name);
	e->data.state = relay_server_state_for_server (s);
	if (s->state == IRC_REGISTERED)
	{
		char *user_utf8 = irc_to_utf8 (s->irc_user->nickname);
		e->data.registered.user = str_from_cstr (user_utf8);
		free (user_utf8);

		char *user_modes_utf8 = irc_to_utf8 (s->irc_user_modes.str);
		e->data.registered.user_modes = str_from_cstr (user_modes_utf8);
		free (user_modes_utf8);
	}
}

static void
relay_prepare_server_rename (struct app_context *ctx, struct server *s,
	const char *new_name)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_server_rename *e = &m->data.server_rename;
	e->event = RELAY_EVENT_SERVER_RENAME;
	e->server_name = str_from_cstr (s->name);
	e->new = str_from_cstr (new_name);
}

static void
relay_prepare_server_remove (struct app_context *ctx, struct server *s)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_server_remove *e = &m->data.server_remove;
	e->event = RELAY_EVENT_SERVER_REMOVE;
	e->server_name = str_from_cstr (s->name);
}

static void
relay_prepare_error (struct app_context *ctx, uint32_t seq, const char *message)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_error *e = &m->data.error;
	e->event = RELAY_EVENT_ERROR;
	e->command_seq = seq;
	e->error = str_from_cstr (message);
}

static struct relay_event_data_response *
relay_prepare_response (struct app_context *ctx, uint32_t seq)
{
	struct relay_event_message *m = relay_prepare (ctx);
	struct relay_event_data_response *e = &m->data.response;
	e->event = RELAY_EVENT_RESPONSE;
	e->command_seq = seq;
	return e;
}

// --- Terminal output ---------------------------------------------------------

/// Default colour pair
#define COLOR_DEFAULT -1

/// Bright versions of the basic colour set
#define COLOR_BRIGHT(x) (COLOR_ ## x + 8)

/// Builds a colour pair for 256-colour terminals with a 16-colour backup value
#define COLOR_256(name, c256) \
	(((COLOR_ ## name) & 0xFFFF) | (((c256) & 0xFFFF) << 16))

typedef int (*terminal_printer_fn) (int);

static int
putchar_stderr (int c)
{
	return fputc (c, stderr);
}

static terminal_printer_fn
get_attribute_printer (FILE *stream)
{
	if (stream == stdout && g_terminal.stdout_is_tty)
		return putchar;
	if (stream == stderr && g_terminal.stderr_is_tty)
		return putchar_stderr;
	return NULL;
}

// ~~~ Attribute printer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// A little tool that tries to make the most of the terminal's capabilities
// to set up text attributes.  It mostly targets just terminal emulators as that
// is what people are using these days.  At least no stupid ncurses limits us
// with colour pairs.

struct attr_printer
{
	struct attrs *attrs;                ///< Named attributes
	FILE *stream;                       ///< Output stream
	bool dirty;                         ///< Attributes are set
};

#define ATTR_PRINTER_INIT(attrs, stream) { attrs, stream, true }

static void
attr_printer_filtered_puts (FILE *stream, const char *attr)
{
	for (; *attr; attr++)
	{
		// sgr/set_attributes and sgr0/exit_attribute_mode like to enable or
		// disable the ACS with SO/SI (e.g. for TERM=screen), however `less -R`
		// does not skip over these characters and it screws up word wrapping
		if (*attr == 14 /* SO */ || *attr == 15 /* SI */)
			continue;

		// Trivially skip delay sequences intended to be processed by tputs()
		const char *end = NULL;
		if (attr[0] == '$' && attr[1] == '<' && (end = strchr (attr, '>')))
			attr = end;
		else
			fputc (*attr, stream);
	}
}

static void
attr_printer_tputs (struct attr_printer *self, const char *attr)
{
	terminal_printer_fn printer = get_attribute_printer (self->stream);
	if (printer)
		tputs (attr, 1, printer);
	else
		// We shouldn't really do this but we need it to output formatting
		// to the pager--it should be SGR-only
		attr_printer_filtered_puts (self->stream, attr);
}

static void
attr_printer_reset (struct attr_printer *self)
{
	if (self->dirty)
		attr_printer_tputs (self, exit_attribute_mode);

	self->dirty = false;
}

// NOTE: commonly terminals have:
//   8 colours (worst, bright fg often with BOLD, bg sometimes with BLINK)
//   16 colours (okayish, we have the full basic range guaranteed)
//   88 colours (the same plus a 4^3 RGB cube and a few shades of grey)
//   256 colours (best, like above but with a larger cube and more grey)

/// Interpolate from the 256-colour palette to the 88-colour one
static int
attr_printer_256_to_88 (int color)
{
	// These colours are the same everywhere
	if (color < 16)
		return color;

	// 24 -> 8 extra shades of grey
	if (color >= 232)
		return 80 + (color - 232) / 3;

	// 6 * 6 * 6 cube -> 4 * 4 * 4 cube
	int x[6] = { 0, 1, 1, 2, 2, 3 };
	int index = color - 16;
	return 16 +
		( x[ index / 36      ] << 8
		| x[(index /  6) % 6 ] << 4
		| x[(index %  6)     ] );
}

static int
attr_printer_decode_color (int color, bool *is_bright)
{
	int16_t c16  = color;        hard_assert (c16  < 16);
	int16_t c256 = color >> 16;  hard_assert (c256 < 256);

	*is_bright = false;
	switch (max_colors)
	{
	case 8:
		if (c16 >= 8)
		{
			c16 -= 8;
			*is_bright = true;
		}
		// Fall-through
	case 16:
		return c16;

	case 88:
		return c256 <= 0 ? c16 : attr_printer_256_to_88 (c256);
	case 256:
		return c256 <= 0 ? c16 : c256;

	default:
		// Unsupported palette
		return -1;
	}
}

static void
attr_printer_apply (struct attr_printer *self,
	int text_attrs, int wanted_fg, int wanted_bg)
{
	bool fg_is_bright;
	int fg = attr_printer_decode_color (wanted_fg, &fg_is_bright);
	bool bg_is_bright;
	int bg = attr_printer_decode_color (wanted_bg, &bg_is_bright);

	bool have_inverse = !!(text_attrs & TEXT_INVERSE);
	if (have_inverse)
	{
		bool tmp = fg_is_bright;
		fg_is_bright = bg_is_bright;
		bg_is_bright = tmp;
	}

	// In 8 colour mode, some terminals don't support bright backgrounds.
	// However, we can make use of the fact that the brightness change caused
	// by the bold attribute is retained when inverting the colours.
	// This has the downside of making the text bold when it's not supposed
	// to be, and we still can't make both colours bright, so it's more of
	// an interesting hack rather than anything else.
	if (!fg_is_bright && bg_is_bright && have_inverse)
		text_attrs |= TEXT_BOLD;
	else if (!fg_is_bright && bg_is_bright
		&& !have_inverse && fg >= 0 && bg >= 0)
	{
		// As long as none of the colours is the default, we can swap them
		int tmp = fg; fg = bg; bg = tmp;
		text_attrs |= TEXT_BOLD | TEXT_INVERSE;
	}
	else
	{
		// This often works, however...
		if (fg_is_bright) text_attrs |= TEXT_BOLD;
		// this turns out to be annoying if implemented "correctly"
		if (bg_is_bright) text_attrs |= TEXT_BLINK;
	}

	attr_printer_reset (self);

	// TEXT_MONOSPACE is unimplemented, for obvious reasons
	if (text_attrs)
		attr_printer_tputs (self, tparm (set_attributes,
			0,   // standout
			text_attrs & TEXT_UNDERLINE,
			text_attrs & TEXT_INVERSE,
			text_attrs & TEXT_BLINK,
			0,   // dim
			text_attrs & TEXT_BOLD,
			0,   // blank
			0,   // protect
			0)); // acs
	if ((text_attrs & TEXT_ITALIC) && enter_italics_mode)
		attr_printer_tputs (self, enter_italics_mode);

	char *smxx = NULL;
	if ((text_attrs & TEXT_CROSSED_OUT)
	 && (smxx = tigetstr ("smxx")) && smxx != (char *) -1)
		attr_printer_tputs (self, smxx);

	if (fg >= 0)
		attr_printer_tputs (self, g_terminal.color_set_fg[fg]);
	if (bg >= 0)
		attr_printer_tputs (self, g_terminal.color_set_bg[bg]);

	self->dirty = true;
}

static void
attr_printer_apply_named (struct attr_printer *self, int attribute)
{
	attr_printer_reset (self);
	if (attribute == ATTR_RESET)
		return;

	// See the COLOR_256 macro or attr_printer_decode_color().
	struct attrs *a = &self->attrs[attribute];
	attr_printer_apply (self, a->attrs,
		a->fg < 16 ? a->fg : (a->fg << 16 | (-1 & 0xFFFF)),
		a->bg < 16 ? a->bg : (a->bg << 16 | (-1 & 0xFFFF)));
	self->dirty = true;
}

// ~~~ Logging redirect ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

static void
vprint_attributed (struct app_context *ctx,
	FILE *stream, intptr_t attribute, const char *fmt, va_list ap)
{
	terminal_printer_fn printer = get_attribute_printer (stream);
	if (!attribute)
		printer = NULL;

	struct attr_printer state = ATTR_PRINTER_INIT (ctx->theme, stream);
	if (printer)
		attr_printer_apply_named (&state, attribute);

	vfprintf (stream, fmt, ap);

	if (printer)
		attr_printer_reset (&state);
}

static void
print_attributed (struct app_context *ctx,
	FILE *stream, intptr_t attribute, const char *fmt, ...)
{
	va_list ap;
	va_start (ap, fmt);
	vprint_attributed (ctx, stream, attribute, fmt, ap);
	va_end (ap);
}

static void
log_message_attributed (void *user_data, const char *quote, const char *fmt,
	va_list ap)
{
	FILE *stream = stderr;
	struct app_context *ctx = g_ctx;

	CALL (ctx->input, hide);

	print_attributed (ctx, stream, (intptr_t) user_data, "%s", quote);
	vprint_attributed (ctx, stream, (intptr_t) user_data, fmt, ap);
	fputs ("\n", stream);

	CALL (ctx->input, show);
}

// ~~~ Theme ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

static ssize_t
attr_by_name (const char *name)
{
	static const char *table[ATTR_COUNT] =
	{
		NULL,
#define XX(x, y, z) [ATTR_ ## x] = #y,
		ATTR_TABLE (XX)
#undef XX
	};

	for (size_t i = 1; i < N_ELEMENTS (table); i++)
		if (!strcmp (name, table[i]))
			return i;
	return -1;
}

static void
on_config_theme_change (struct config_item *item)
{
	struct app_context *ctx = item->user_data;
	ssize_t id = attr_by_name (item->schema->name);
	if (id != -1)
	{
		// TODO: There should be a validator.
		ctx->theme[id] = item->type == CONFIG_ITEM_NULL
			? ctx->theme_defaults[id]
			: attrs_decode (item->value.string.str);
	}
}

static void
init_colors (struct app_context *ctx)
{
	bool have_ti = init_terminal ();

#define INIT_ATTR(id, ...) ctx->theme[ATTR_ ## id] = \
	ctx->theme_defaults[ATTR_ ## id] = (struct attrs) { __VA_ARGS__ }

	INIT_ATTR (PROMPT,      -1, -1, TEXT_BOLD);
	INIT_ATTR (RESET,       -1, -1, 0);
	INIT_ATTR (DATE_CHANGE, -1, -1, TEXT_BOLD);
	INIT_ATTR (READ_MARKER, COLOR_MAGENTA, -1, 0);
	INIT_ATTR (WARNING,     COLOR_YELLOW,  -1, 0);
	INIT_ATTR (ERROR,       COLOR_RED,     -1, 0);

	INIT_ATTR (EXTERNAL,    COLOR_WHITE,   -1, 0);
	INIT_ATTR (TIMESTAMP,   COLOR_WHITE,   -1, 0);
	INIT_ATTR (HIGHLIGHT,   COLOR_BRIGHT (YELLOW), COLOR_MAGENTA, TEXT_BOLD);
	INIT_ATTR (ACTION,      COLOR_RED,     -1, 0);
	INIT_ATTR (USERHOST,    COLOR_CYAN,    -1, 0);
	INIT_ATTR (JOIN,        COLOR_GREEN,   -1, 0);
	INIT_ATTR (PART,        COLOR_RED,     -1, 0);

#undef INIT_ATTR

	// This prevents formatters from obtaining an attribute printer function
	if (!have_ti)
	{
		g_terminal.stdout_is_tty = false;
		g_terminal.stderr_is_tty = false;
	}

	g_log_message_real = log_message_attributed;
}

// --- Helpers -----------------------------------------------------------------

static int
irc_server_strcmp (struct server *s, const char *a, const char *b)
{
	int x;
	while (*a || *b)
		if ((x = s->irc_tolower (*a++) - s->irc_tolower (*b++)))
			return x;
	return 0;
}

static int
irc_server_strncmp (struct server *s, const char *a, const char *b, size_t n)
{
	int x;
	while (n-- && (*a || *b))
		if ((x = s->irc_tolower (*a++) - s->irc_tolower (*b++)))
			return x;
	return 0;
}

static char *
irc_cut_nickname (const char *prefix)
{
	return cstr_cut_until (prefix, "!@");
}

static const char *
irc_find_userhost (const char *prefix)
{
	const char *p = strchr (prefix, '!');
	return p ? p + 1 : NULL;
}

static bool
irc_is_this_us (struct server *s, const char *prefix)
{
	// This shouldn't be called before successfully registering.
	// Better safe than sorry, though.
	if (!s->irc_user)
		return false;

	char *nick = irc_cut_nickname (prefix);
	bool result = !irc_server_strcmp (s, nick, s->irc_user->nickname);
	free (nick);
	return result;
}

static bool
irc_is_channel (struct server *s, const char *ident)
{
	return *ident
		&& (!!strchr (s->irc_chantypes,       *ident) ||
			!!strchr (s->irc_idchan_prefixes, *ident));
}

// Message targets can be prefixed by a character filtering their targets
static const char *
irc_skip_statusmsg (struct server *s, const char *target)
{
	return target + (*target && strchr (s->irc_statusmsg, *target));
}

static bool
irc_is_extban (struct server *s, const char *target)
{
	// Some servers have a prefix, and some support negation
	if (s->irc_extban_prefix && *target++ != s->irc_extban_prefix)
		return false;
	if (*target == '~')
		target++;

	// XXX: we don't know if it's supposed to have an argument, or not
	return *target && strchr (s->irc_extban_types, *target++)
		&& strchr (":\0", *target);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// As of 2020, everything should be in UTF-8.  And if it's not, we'll decode it
// as ISO Latin 1.  This function should not be called on the whole message.
static char *
irc_to_utf8 (const char *text)
{
	if (!text)
		return NULL;

	// XXX: the validation may be unnecessarily harsh, could do with a lenient
	//   first pass, then replace any errors with the replacement character
	size_t len = strlen (text) + 1;
	if (utf8_validate (text, len))
		return xstrdup (text);

	// Windows 1252 redefines several silly C1 control characters as glyphs
	static const char c1[32][4] =
	{
		"\xe2\x82\xac", "\xc2\x81",     "\xe2\x80\x9a", "\xc6\x92",
		"\xe2\x80\x9e", "\xe2\x80\xa6", "\xe2\x80\xa0", "\xe2\x80\xa1",
		"\xcb\x86",     "\xe2\x80\xb0", "\xc5\xa0",     "\xe2\x80\xb9",
		"\xc5\x92",     "\xc2\x8d",     "\xc5\xbd",     "\xc2\x8f",
		"\xc2\x90",     "\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c",
		"\xe2\x80\x9d", "\xe2\x80\xa2", "\xe2\x80\x93", "\xe2\x80\x94",
		"\xcb\x9c",     "\xe2\x84\xa2", "\xc5\xa1",     "\xe2\x80\xba",
		"\xc5\x93",     "\xc2\x9d",     "\xc5\xbe",     "\xc5\xb8",
	};

	struct str s = str_make ();
	for (const char *p = text; *p; p++)
	{
		int c = *(unsigned char *) p;
		if (c < 0x80)
			str_append_c (&s, c);
		else if (c < 0xA0)
			str_append (&s, c1[c & 0x1f]);
		else
			str_append_data (&s,
				(char[]) {0xc0 | (c >> 6), 0x80 | (c & 0x3f)}, 2);
	}
	return str_steal (&s);
}

// --- Output formatter --------------------------------------------------------

// This complicated piece of code makes attributed text formatting simple.
// We use a printf-inspired syntax to push attributes and text to the object,
// then flush it either to a terminal, or a log file with formatting stripped.
//
// Format strings use a #-quoted notation, to differentiate from printf:
//   #s inserts a string (expected to be in UTF-8)
//   #d inserts a signed integer
//   #l inserts a locale-encoded string
//
//   #S inserts a string from the server in an unknown encoding
//   #m inserts an IRC-formatted string (auto-resets at boundaries)
//   #n cuts the nickname from a string and automatically colours it
//   #N is like #n but also appends userhost, if present
//
//   #a inserts named attributes (auto-resets)
//   #r resets terminal attributes
//   #c sets foreground colour
//   #C sets background colour
//
// Modifiers:
//    & free() the string argument after using it

static void
formatter_add_item (struct formatter *self, struct formatter_item template_)
{
	// Auto-resetting tends to create unnecessary items,
	// which also end up being relayed to frontends, so filter them out.
	bool reset =
		template_.type == FORMATTER_ITEM_ATTR &&
		template_.attribute == ATTR_RESET;
	if (self->clean && reset)
		return;

	self->clean = reset ||
		(self->clean && template_.type == FORMATTER_ITEM_TEXT);

	if (template_.text)
		template_.text = xstrdup (template_.text);

	if (self->items_len == self->items_alloc)
		self->items = xreallocarray
			(self->items, sizeof *self->items, (self->items_alloc <<= 1));
	self->items[self->items_len++] = template_;
}

#define FORMATTER_ADD_ITEM(self, type_, ...) formatter_add_item ((self), \
	(struct formatter_item) { .type = FORMATTER_ITEM_ ## type_, __VA_ARGS__ })

#define FORMATTER_ADD_RESET(self) \
	FORMATTER_ADD_ITEM ((self), ATTR, .attribute = ATTR_RESET)
#define FORMATTER_ADD_TEXT(self, text_) \
	FORMATTER_ADD_ITEM ((self), TEXT, .text = (text_))

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

enum
{
	MIRC_WHITE,  MIRC_BLACK,    MIRC_BLUE,   MIRC_GREEN,
	MIRC_L_RED,  MIRC_RED,      MIRC_PURPLE, MIRC_ORANGE,
	MIRC_YELLOW, MIRC_L_GREEN,  MIRC_CYAN,   MIRC_L_CYAN,
	MIRC_L_BLUE, MIRC_L_PURPLE, MIRC_GRAY,   MIRC_L_GRAY,
};

// We use estimates from the 16 colour terminal palette, or the 256 colour cube,
// which is not always available.  The mIRC orange colour is only in the cube.

static const int g_mirc_to_terminal[] =
{
	[MIRC_WHITE]    = COLOR_256 (BRIGHT (WHITE),  231),
	[MIRC_BLACK]    = COLOR_256         (BLACK,    16),
	[MIRC_BLUE]     = COLOR_256         (BLUE,     19),
	[MIRC_GREEN]    = COLOR_256         (GREEN,    34),
	[MIRC_L_RED]    = COLOR_256 (BRIGHT (RED),    196),
	[MIRC_RED]      = COLOR_256         (RED,     124),
	[MIRC_PURPLE]   = COLOR_256         (MAGENTA, 127),
	[MIRC_ORANGE]   = COLOR_256 (BRIGHT (YELLOW), 214),
	[MIRC_YELLOW]   = COLOR_256 (BRIGHT (YELLOW), 226),
	[MIRC_L_GREEN]  = COLOR_256 (BRIGHT (GREEN),   46),
	[MIRC_CYAN]     = COLOR_256         (CYAN,     37),
	[MIRC_L_CYAN]   = COLOR_256 (BRIGHT (CYAN),    51),
	[MIRC_L_BLUE]   = COLOR_256 (BRIGHT (BLUE),    21),
	[MIRC_L_PURPLE] = COLOR_256 (BRIGHT (MAGENTA),201),
	[MIRC_GRAY]     = COLOR_256 (BRIGHT (BLACK),  244),
	[MIRC_L_GRAY]   = COLOR_256         (WHITE,   252),
};

// https://modern.ircdocs.horse/formatting.html
// http://anti.teamidiot.de/static/nei/*/extended_mirc_color_proposal.html
static const int16_t g_extra_to_256[100 - 16] =
{
	 52,  94, 100,  58,  22,  29,  23,  24,  17,  54,  53,  89,
	 88, 130, 142,  64,  28,  35,  30,  25,  18,  91,  90, 125,
	124, 166, 184, 106,  34,  49,  37,  33,  19, 129, 127, 161,
	196, 208, 226, 154,  46,  86 , 51,  75,  21, 171, 201, 198,
	203, 215, 227, 191,  83, 122,  87, 111,  63, 177, 207, 205,
	217, 223, 229, 193, 157, 158, 159, 153, 147, 183, 219, 212,
	 16, 233, 235, 237, 239, 241, 244, 247, 250, 254, 231,  -1
};

static const char *
irc_parse_mirc_color (const char *s, uint8_t *fg, uint8_t *bg)
{
	if (!isdigit_ascii (*s))
	{
		*fg = *bg = 99;
		return s;
	}

	*fg = *s++ - '0';
	if (isdigit_ascii (*s))
		*fg = *fg * 10 + (*s++ - '0');

	if (*s != ',' || !isdigit_ascii (s[1]))
		return s;
	s++;

	*bg = *s++ - '0';
	if (isdigit_ascii (*s))
		*bg = *bg * 10 + (*s++ - '0');
	return s;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct irc_char_attrs
{
	uint8_t fg, bg;                     ///< {Fore,back}ground colour or 99
	uint8_t attributes;                 ///< TEXT_* flags, except TEXT_BLINK
	uint8_t starts_at_boundary;         ///< Possible to split here?
};

static void
irc_serialize_char_attrs (const struct irc_char_attrs *attrs, struct str *out)
{
	soft_assert (attrs->fg < 100 && attrs->bg < 100);

	if (attrs->fg != 99 || attrs->bg != 99)
	{
		str_append_printf (out, "\x03%u", attrs->fg);
		if (attrs->bg != 99)
			str_append_printf (out, ",%02u", attrs->bg);
	}
	if (attrs->attributes & TEXT_BOLD)        str_append_c (out, '\x02');
	if (attrs->attributes & TEXT_ITALIC)      str_append_c (out, '\x1d');
	if (attrs->attributes & TEXT_UNDERLINE)   str_append_c (out, '\x1f');
	if (attrs->attributes & TEXT_INVERSE)     str_append_c (out, '\x16');
	if (attrs->attributes & TEXT_CROSSED_OUT) str_append_c (out, '\x1e');
	if (attrs->attributes & TEXT_MONOSPACE)   str_append_c (out, '\x11');
}

static int
irc_parse_attribute (char c)
{
	switch (c)
	{
	case '\x02' /* ^B */: return TEXT_BOLD;
	case '\x11' /* ^Q */: return TEXT_MONOSPACE;
	case '\x16' /* ^V */: return TEXT_INVERSE;
	case '\x1d' /* ^] */: return TEXT_ITALIC;
	case '\x1e' /* ^^ */: return TEXT_CROSSED_OUT;
	case '\x1f' /* ^_ */: return TEXT_UNDERLINE;
	case '\x0f' /* ^O */: return -1;
	}
	return 0;
}

// The text needs to be NUL-terminated, and a valid UTF-8 string
static struct irc_char_attrs *
irc_analyze_text (const char *text, size_t len)
{
	struct irc_char_attrs *attrs = xcalloc (len, sizeof *attrs),
		blank = { .fg = 99, .bg = 99, .starts_at_boundary = true },
		next = blank, cur = next;

	for (size_t i = 0; i != len; cur = next)
	{
		const char *start = text;
		hard_assert (utf8_decode (&text, len - i) >= 0);

		int attribute = irc_parse_attribute (*start);
		if (*start == '\x03')
			text = irc_parse_mirc_color (text, &next.fg, &next.bg);
		else if (attribute > 0)
			next.attributes ^= attribute;
		else if (attribute < 0)
			next = blank;

		while (start++ != text)
		{
			attrs[i++] = cur;
			cur.starts_at_boundary = false;
		}
	}
	return attrs;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static const char *
formatter_parse_mirc_color (struct formatter *self, const char *s)
{
	uint8_t fg = 255, bg = 255;
	s = irc_parse_mirc_color (s, &fg, &bg);

	if (fg < 16)
		FORMATTER_ADD_ITEM (self, FG_COLOR, .color = g_mirc_to_terminal[fg]);
	else if (fg < 100)
		FORMATTER_ADD_ITEM (self, FG_COLOR,
			.color = COLOR_256 (DEFAULT, g_extra_to_256[fg - 16]));

	if (bg < 16)
		FORMATTER_ADD_ITEM (self, BG_COLOR, .color = g_mirc_to_terminal[bg]);
	else if (bg < 100)
		FORMATTER_ADD_ITEM (self, BG_COLOR,
			.color = COLOR_256 (DEFAULT, g_extra_to_256[bg - 16]));

	return s;
}

static void
formatter_parse_message (struct formatter *self, const char *s)
{
	FORMATTER_ADD_RESET (self);

	struct str buf = str_make ();
	unsigned char c;
	while ((c = *s++))
	{
		if (buf.len && c < 0x20)
		{
			FORMATTER_ADD_TEXT (self, buf.str);
			str_reset (&buf);
		}

		int attribute = irc_parse_attribute (c);
		if (c == '\x03')
			s = formatter_parse_mirc_color (self, s);
		else if (attribute > 0)
			FORMATTER_ADD_ITEM (self, SIMPLE, .attribute = attribute);
		else if (attribute < 0)
			FORMATTER_ADD_RESET (self);
		else
			str_append_c (&buf, c);
	}

	if (buf.len)
		FORMATTER_ADD_TEXT (self, buf.str);

	str_free (&buf);
	FORMATTER_ADD_RESET (self);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
formatter_parse_nick (struct formatter *self, const char *s)
{
	// For outgoing messages; maybe we should add a special #t for them
	// which would also make us not cut off the userhost part, ever
	if (irc_is_channel (self->s, irc_skip_statusmsg (self->s, s)))
	{
		char *tmp = irc_to_utf8 (s);
		FORMATTER_ADD_TEXT (self, tmp);
		free (tmp);
		return;
	}

	char *nick = irc_cut_nickname (s);
	int color = siphash_wrapper (nick, strlen (nick)) % 7;

	// Never use the black colour, could become transparent on black terminals;
	// white is similarly excluded from the range
	if (color == COLOR_BLACK)
		color = (uint16_t) -1;

	// Use a colour from the 256-colour cube if available
	color |= self->ctx->nick_palette[siphash_wrapper (nick,
		strlen (nick)) % self->ctx->nick_palette_len] << 16;

	// We always use the default colour for ourselves
	if (self->s && irc_is_this_us (self->s, nick))
		color = -1;

	FORMATTER_ADD_ITEM (self, FG_COLOR, .color = color);

	char *x = irc_to_utf8 (nick);
	free (nick);
	FORMATTER_ADD_TEXT (self, x);
	free (x);

	// Need to reset the colour afterwards
	FORMATTER_ADD_ITEM (self, FG_COLOR, .color = -1);
}

static void
formatter_parse_nick_full (struct formatter *self, const char *s)
{
	formatter_parse_nick (self, s);

	const char *userhost;
	if (!(userhost = irc_find_userhost (s)))
		return;

	FORMATTER_ADD_TEXT (self, " (");
	FORMATTER_ADD_ITEM (self, ATTR, .attribute = ATTR_USERHOST);

	char *x = irc_to_utf8 (userhost);
	FORMATTER_ADD_TEXT (self, x);
	free (x);

	FORMATTER_ADD_RESET (self);
	FORMATTER_ADD_TEXT (self, ")");
}

static const char *
formatter_parse_field (struct formatter *self,
	const char *field, struct str *buf, va_list *ap)
{
	bool free_string = false;
	char *s = NULL;
	char *tmp = NULL;
	int c;

restart:
	switch ((c = *field++))
	{
		// We can push boring text content to the caller's buffer
		// and let it flush the buffer only when it's actually needed
	case 'd':
		tmp = xstrdup_printf ("%d", va_arg (*ap, int));
		str_append (buf, tmp);
		free (tmp);
		break;
	case 's':
		str_append (buf, (s = va_arg (*ap, char *)));
		break;
	case 'l':
		if (!(tmp = iconv_xstrdup (self->ctx->term_to_utf8,
			(s = va_arg (*ap, char *)), -1, NULL)))
			print_error ("character conversion failed for: %s", "output");
		else
			str_append (buf, tmp);
		free (tmp);
		break;

	case 'S':
		tmp = irc_to_utf8 ((s = va_arg (*ap, char *)));
		str_append (buf, tmp);
		free (tmp);
		break;
	case 'm':
		tmp = irc_to_utf8 ((s = va_arg (*ap, char *)));
		formatter_parse_message (self, tmp);
		free (tmp);
		break;
	case 'n':
		formatter_parse_nick (self, (s = va_arg (*ap, char *)));
		break;
	case 'N':
		formatter_parse_nick_full (self, (s = va_arg (*ap, char *)));
		break;

	case 'a':
		FORMATTER_ADD_ITEM (self, ATTR, .attribute = va_arg (*ap, int));
		break;
	case 'c':
		FORMATTER_ADD_ITEM (self, FG_COLOR, .color = va_arg (*ap, int));
		break;
	case 'C':
		FORMATTER_ADD_ITEM (self, BG_COLOR, .color = va_arg (*ap, int));
		break;
	case 'r':
		FORMATTER_ADD_RESET (self);
		break;

	default:
		if (c == '&' && !free_string)
			free_string = true;
		else if (c)
			hard_assert (!"unexpected format specifier");
		else
			hard_assert (!"unexpected end of format string");
		goto restart;
	}

	if (free_string)
		free (s);
	return field;
}

// I was unable to take a pointer of a bare "va_list" when it was passed in
// as a function argument, so it has to be a pointer from the beginning
static void
formatter_addv (struct formatter *self, const char *format, va_list *ap)
{
	struct str buf = str_make ();
	while (*format)
	{
		if (*format != '#' || *++format == '#')
		{
			str_append_c (&buf, *format++);
			continue;
		}
		if (buf.len)
		{
			FORMATTER_ADD_TEXT (self, buf.str);
			str_reset (&buf);
		}

		format = formatter_parse_field (self, format, &buf, ap);
	}

	if (buf.len)
		FORMATTER_ADD_TEXT (self, buf.str);

	str_free (&buf);
}

static void
formatter_add (struct formatter *self, const char *format, ...)
{
	va_list ap;
	va_start (ap, format);
	formatter_addv (self, format, &ap);
	va_end (ap);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct line_char_attrs
{
	short named;                        ///< Named attribute or -1
	short text;                         ///< Text attributes
	int fg;                             ///< Foreground colour (-1 for default)
	int bg;                             ///< Background colour (-1 for default)
};

// We can get rid of the linked list and do this in one allocation (use strlen()
// for the upper bound)--since we only prepend and/or replace characters, add
// a member to specify the prepended character and how many times to repeat it.
// Tabs may nullify the wide character but it's not necessary.
//
// This would be slighly more optimal but it would also set the algorithm in
// stone and complicate flushing.

struct line_char
{
	LIST_HEADER (struct line_char)

	wchar_t wide;                       ///< The character as a wchar_t
	int width;                          ///< Width of the character in cells
	struct line_char_attrs attrs;       ///< Attributes
};

static struct line_char *
line_char_new (wchar_t wc)
{
	struct line_char *self = xcalloc (1, sizeof *self);
	self->width = wcwidth ((self->wide = wc));

	// Typically various control characters
	if (self->width < 0)
		self->width = 0;

	self->attrs.bg = self->attrs.fg = -1;
	self->attrs.named = ATTR_RESET;
	return self;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct line_wrap_mark
{
	struct line_char *start;            ///< First character
	int used;                           ///< Display cells used
};

static void
line_wrap_mark_push (struct line_wrap_mark *mark, struct line_char *c)
{
	if (!mark->start)
		mark->start = c;
	mark->used += c->width;
}

struct line_wrap_state
{
	struct line_char *result;           ///< Head of result
	struct line_char *result_tail;      ///< Tail of result

	int line_used;                      ///< Line length before marks
	int line_max;                       ///< Maximum line length
	struct line_wrap_mark chunk;        ///< All buffered text
	struct line_wrap_mark overflow;     ///< Overflowing text
};

static void
line_wrap_flush_split (struct line_wrap_state *s, struct line_wrap_mark *before)
{
	struct line_char *nl = line_char_new (L'\n');
	LIST_INSERT_WITH_TAIL (s->result, s->result_tail, nl, before->start);
	s->line_used = before->used;
}

static void
line_wrap_flush (struct line_wrap_state *s, bool force_split)
{
	if (!s->overflow.start)
		s->line_used += s->chunk.used;
	else if (force_split || s->chunk.used > s->line_max)
	{
#ifdef WRAP_UNNECESSARILY
		// When the line wraps at the end of the screen and a background colour
		// is set, the terminal paints the entire new line with that colour.
		// Explicitly inserting a newline with the default attributes fixes it.
		line_wrap_flush_split (s, &s->overflow);
#else
		// Splitting here breaks link searching mechanisms in some terminals,
		// though, so we make a trade-off and let the chunk wrap naturally.
		// Fuck terminals, really.
		s->line_used = s->overflow.used;
#endif
	}
	else
		// Print the chunk in its entirety on a new line
		line_wrap_flush_split (s, &s->chunk);

	memset (&s->chunk,    0, sizeof s->chunk);
	memset (&s->overflow, 0, sizeof s->overflow);
}

static void
line_wrap_nl (struct line_wrap_state *s)
{
	line_wrap_flush (s, true);
	struct line_char *nl = line_char_new (L'\n');
	LIST_APPEND_WITH_TAIL (s->result, s->result_tail, nl);
	s->line_used = 0;
}

static void
line_wrap_tab (struct line_wrap_state *s, struct line_char *c)
{
	line_wrap_flush (s, true);
	if (s->line_used >= s->line_max)
		line_wrap_nl (s);

	// Compute the number of characters needed to get to the next tab stop
	int tab_width = ((s->line_used + 8) & ~7) - s->line_used;
	// On overflow just fill the rest of the line with spaces
	if (s->line_used + tab_width > s->line_max)
		tab_width = s->line_max - s->line_used;

	s->line_used += tab_width;
	while (tab_width--)
	{
		struct line_char *space = line_char_new (L' ');
		space->attrs = c->attrs;
		LIST_APPEND_WITH_TAIL (s->result, s->result_tail, space);
	}
}

static void
line_wrap_push_char (struct line_wrap_state *s, struct line_char *c)
{
	// Note that when processing whitespace here, any non-WS chunk has already
	// been flushed, and thus it matters little if we flush with force split
	if (wcschr (L"\r\f\v", c->wide))
		/* Skip problematic characters */;
	else if (c->wide == L'\n')
		line_wrap_nl (s);
	else if (c->wide == L'\t')
		line_wrap_tab (s, c);
	else
		goto use_as_is;
	free (c);
	return;

use_as_is:
	if (s->overflow.start
	 || s->line_used + s->chunk.used + c->width > s->line_max)
	{
		if (s->overflow.used + c->width > s->line_max)
		{
#ifdef WRAP_UNNECESSARILY
			// If the overflow overflows, restart on a new line
			line_wrap_nl (s);
#else
			// See line_wrap_flush(), we would end up on a new line anyway
			line_wrap_flush (s, true);
			s->line_used = 0;
#endif
		}
		else
			line_wrap_mark_push (&s->overflow, c);
	}
	line_wrap_mark_push (&s->chunk, c);
	LIST_APPEND_WITH_TAIL (s->result, s->result_tail, c);
}

/// Basic word wrapping that respects wcwidth(3) and expands tabs.
/// Besides making text easier to read, it also fixes the problem with
/// formatting spilling over the entire new line on line wrap.
static struct line_char *
line_wrap (struct line_char *line, int max_width)
{
	struct line_wrap_state s = { .line_max = max_width };
	bool last_was_word_char = false;
	LIST_FOR_EACH (struct line_char, c, line)
	{
		// Act on the right boundary of (\s*\S+) chunks
		bool this_is_word_char = !wcschr (L" \t\r\n\f\v", c->wide);
		if (last_was_word_char && !this_is_word_char)
			line_wrap_flush (&s, false);
		last_was_word_char = this_is_word_char;

		LIST_UNLINK (line, c);
		line_wrap_push_char (&s, c);
	}

	// Make sure to process the last word and return the modified list
	line_wrap_flush (&s, false);
	return s.result;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct exploder
{
	struct app_context *ctx;            ///< Application context
	struct line_char *result;           ///< Result
	struct line_char *result_tail;      ///< Tail of result
	struct line_char_attrs attrs;       ///< Current attributes
};

static bool
explode_formatter_attr (struct exploder *self, struct formatter_item *item)
{
	switch (item->type)
	{
	case FORMATTER_ITEM_ATTR:
		self->attrs.named = item->attribute;
		self->attrs.text = 0;
		self->attrs.fg = -1;
		self->attrs.bg = -1;
		return true;
	case FORMATTER_ITEM_SIMPLE:
		self->attrs.named = -1;
		self->attrs.text ^= item->attribute;
		return true;
	case FORMATTER_ITEM_FG_COLOR:
		self->attrs.named = -1;
		self->attrs.fg = item->color;
		return true;
	case FORMATTER_ITEM_BG_COLOR:
		self->attrs.named = -1;
		self->attrs.bg = item->color;
		return true;
	default:
		return false;
	}
}

static void
explode_text (struct exploder *self, const char *text)
{
	// Throw away any potentially harmful control characters first
	struct str filtered = str_make ();
	for (const char *p = text; *p; p++)
		if (!strchr ("\a\b\x0e\x0f\x1b" /* BEL BS SO SI ESC */, *p))
			str_append_c (&filtered, *p);

	size_t term_len = 0, processed = 0, len;
	char *term = iconv_xstrdup (self->ctx->term_from_utf8,
		filtered.str, filtered.len + 1, &term_len);
	str_free (&filtered);

	mbstate_t ps;
	memset (&ps, 0, sizeof ps);

	wchar_t wch;
	while ((len = mbrtowc (&wch, term + processed, term_len - processed, &ps)))
	{
		hard_assert (len != (size_t) -2 && len != (size_t) -1);
		hard_assert ((processed += len) <= term_len);

		struct line_char *c = line_char_new (wch);
		c->attrs = self->attrs;
		LIST_APPEND_WITH_TAIL (self->result, self->result_tail, c);
	}
	free (term);
}

static struct line_char *
formatter_to_chars (struct formatter *formatter)
{
	struct exploder self = { .ctx = formatter->ctx };
	self.attrs.fg = self.attrs.bg = self.attrs.named = -1;

	int attribute_ignore = 0;
	for (size_t i = 0; i < formatter->items_len; i++)
	{
		struct formatter_item *iter = &formatter->items[i];
		if      (iter->type == FORMATTER_ITEM_TEXT)
			explode_text (&self, iter->text);
		else if (iter->type == FORMATTER_ITEM_IGNORE_ATTR)
			attribute_ignore += iter->attribute;
		else if (attribute_ignore <= 0
			&& !explode_formatter_attr (&self, iter))
				hard_assert (!"unhandled formatter item type");
	}
	return self.result;
}

enum
{
	FLUSH_OPT_RAW    = (1 << 0),        ///< Print raw attributes
	FLUSH_OPT_NOWRAP = (1 << 1)         ///< Do not wrap
};

/// The input is a bunch of wide characters--respect shift state encodings
static void
formatter_putc (struct line_char *c, FILE *stream)
{
	static mbstate_t mb;
	char buf[MB_LEN_MAX] = {};
	size_t len = wcrtomb (buf, c ? c->wide : L'\0', &mb);
	if (len != (size_t) -1 && len)
		fwrite (buf, len - !c, 1, stream);
	free (c);
}

static void
formatter_flush (struct formatter *self, FILE *stream, int flush_opts)
{
	struct line_char *line = formatter_to_chars (self);

	bool is_tty = !!get_attribute_printer (stream);
	if (!is_tty && !(flush_opts & FLUSH_OPT_RAW))
	{
		LIST_FOR_EACH (struct line_char, c, line)
			formatter_putc (c, stream);
		formatter_putc (NULL, stream);
		return;
	}

	if (self->ctx->word_wrapping && !(flush_opts & FLUSH_OPT_NOWRAP))
		line = line_wrap (line, g_terminal.columns);

	struct attr_printer state = ATTR_PRINTER_INIT (self->ctx->theme, stream);
	struct line_char_attrs attrs = {};  // Won't compare equal to anything
	LIST_FOR_EACH (struct line_char, c, line)
	{
		if (attrs.fg    != c->attrs.fg
		 || attrs.bg    != c->attrs.bg
		 || attrs.named != c->attrs.named
		 || attrs.text  != c->attrs.text)
		{
			formatter_putc (NULL, stream);

			attrs = c->attrs;
			if (attrs.named == -1)
				attr_printer_apply (&state, attrs.text, attrs.fg, attrs.bg);
			else
				attr_printer_apply_named (&state, attrs.named);
		}

		formatter_putc (c, stream);
	}
	formatter_putc (NULL, stream);
	attr_printer_reset (&state);
}

// --- Buffers -----------------------------------------------------------------

static void
buffer_pop_excess_lines (struct app_context *ctx, struct buffer *self)
{
	int to_delete = (int) self->lines_count - (int) ctx->backlog_limit;
	while (to_delete-- > 0 && self->lines)
	{
		struct buffer_line *excess = self->lines;
		LIST_UNLINK_WITH_TAIL (self->lines, self->lines_tail, excess);
		buffer_line_destroy (excess);
		self->lines_count--;
	}
}

static void
on_config_backlog_limit_change (struct config_item *item)
{
	struct app_context *ctx = item->user_data;
	ctx->backlog_limit = MIN (item->value.integer, INT_MAX);

	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
		buffer_pop_excess_lines (ctx, iter);
}

static void
buffer_update_time (struct app_context *ctx, time_t now, FILE *stream,
	int flush_opts)
{
	struct tm last, current;
	if (!localtime_r (&ctx->last_displayed_msg_time, &last)
	 || !localtime_r (&now, &current))
	{
		// Strange but nonfatal
		print_error ("%s: %s", "localtime_r", strerror (errno));
		return;
	}

	ctx->last_displayed_msg_time = now;
	if (last.tm_year == current.tm_year
	 && last.tm_mon  == current.tm_mon
	 && last.tm_mday == current.tm_mday)
		return;

	char buf[64] = "";
	const char *format =
		get_config_string (ctx->config.root, "general.date_change_line");
	if (!strftime (buf, sizeof buf, format, &current))
	{
		print_error ("%s: %s", "strftime", strerror (errno));
		return;
	}

	struct formatter f = formatter_make (ctx, NULL);
	formatter_add (&f, "#a#s\n", ATTR_DATE_CHANGE, buf);
	formatter_flush (&f, stream, flush_opts);
	// Flush the trailing formatting reset item
	fflush (stream);
	formatter_free (&f);
}

static void
buffer_line_flush (struct buffer_line *line, struct formatter *f, FILE *output,
	int flush_opts)
{
	switch (line->r)
	{
	case BUFFER_LINE_BARE:                               break;
	case BUFFER_LINE_INDENT:  formatter_add (f, "    "); break;
	case BUFFER_LINE_STATUS:  formatter_add (f, " -  "); break;
	case BUFFER_LINE_ERROR:   formatter_add (f, "#a=!=#r ", ATTR_ERROR);  break;
	case BUFFER_LINE_JOIN:    formatter_add (f, "#a-->#r ", ATTR_JOIN);   break;
	case BUFFER_LINE_PART:    formatter_add (f, "#a<--#r ", ATTR_PART);   break;
	case BUFFER_LINE_ACTION:  formatter_add (f, " #a*#r  ", ATTR_ACTION); break;
	}

	for (struct formatter_item *iter = line->items; iter->type; iter++)
		formatter_add_item (f, *iter);

	formatter_add (f, "\n");
	formatter_flush (f, output, flush_opts);
	formatter_free (f);
}

static void
buffer_line_write_time (struct formatter *f, struct buffer_line *line,
	FILE *stream, int flush_opts)
{
	// Normal timestamps don't include the date, make sure the user won't be
	// confused as to when an event has happened
	buffer_update_time (f->ctx, line->when, stream, flush_opts);

	struct tm current;
	char buf[9];
	if (!localtime_r (&line->when, &current))
		print_error ("%s: %s", "localtime_r", strerror (errno));
	else if (!strftime (buf, sizeof buf, "%T", &current))
		print_error ("%s: %s", "strftime", "buffer too small");
	else
		formatter_add (f, "#a#s#r ", ATTR_TIMESTAMP, buf);
}

#define buffer_line_will_show_up(buffer, line) \
	(!(buffer)->hide_unimportant || !((line)->flags & BUFFER_LINE_UNIMPORTANT))

static void
buffer_line_display (struct app_context *ctx,
	struct buffer *buffer, struct buffer_line *line, bool is_external)
{
	if (!buffer_line_will_show_up (buffer, line))
		return;

	CALL (ctx->input, hide);

	struct formatter f = formatter_make (ctx, NULL);
	buffer_line_write_time (&f, line, stdout, 0);

	// Ignore all formatting for messages coming from other buffers, that is
	// either from the global or server buffer.  Instead print them in grey.
	if (is_external)
	{
		formatter_add (&f, "#a", ATTR_EXTERNAL);
		FORMATTER_ADD_ITEM (&f, IGNORE_ATTR, .attribute = 1);
	}
	buffer_line_flush (line, &f, stdout, 0);
	// Flush the trailing formatting reset item
	fflush (stdout);

	CALL (ctx->input, show);
}

static void
buffer_line_write_to_backlog (struct app_context *ctx,
	struct buffer_line *line, FILE *log_file, int flush_opts)
{
	struct formatter f = formatter_make (ctx, NULL);
	buffer_line_write_time (&f, line, log_file, flush_opts);
	buffer_line_flush (line, &f, log_file, flush_opts);
}

static void
buffer_line_write_to_log (struct app_context *ctx,
	struct buffer_line *line, FILE *log_file)
{
	if (line->flags & BUFFER_LINE_SKIP_FILE)
		return;

	struct formatter f = formatter_make (ctx, NULL);
	struct tm current;
	char buf[20];
	if (!gmtime_r (&line->when, &current))
		print_error ("%s: %s", "gmtime_r", strerror (errno));
	else if (!strftime (buf, sizeof buf, "%F %T", &current))
		print_error ("%s: %s", "strftime", "buffer too small");
	else
		formatter_add (&f, "#s ", buf);

	// The target is not a terminal, thus it won't wrap in spite of the 0
	buffer_line_flush (line, &f, log_file, 0);
}

static void
log_formatter (struct app_context *ctx, struct buffer *buffer,
	unsigned flags, enum buffer_line_rendition r, struct formatter *f)
{
	if (!buffer)
		buffer = ctx->global_buffer;

	struct buffer_line *line = buffer_line_new (f);
	line->flags = flags;
	line->r = r;
	// TODO: allow providing custom time (IRCv3.2 server-time)
	line->when = time (NULL);

	buffer_pop_excess_lines (ctx, buffer);
	LIST_APPEND_WITH_TAIL (buffer->lines, buffer->lines_tail, line);
	buffer->lines_count++;

	if (buffer->log_file)
		buffer_line_write_to_log (ctx, line, buffer->log_file);

	bool unseen_pm = buffer->type == BUFFER_PM
		&& buffer != ctx->current_buffer
		&& !(flags & BUFFER_LINE_UNIMPORTANT);
	bool important = (flags & BUFFER_LINE_HIGHLIGHT) || unseen_pm;
	if (ctx->beep_on_highlight && important)
		// XXX: this may disturb any other foreground process
		CALL (ctx->input, ding);

	bool can_leak = false;
	if ((buffer == ctx->global_buffer)
	 || (ctx->current_buffer->type == BUFFER_GLOBAL
		&& buffer->type == BUFFER_SERVER)
	 || (ctx->current_buffer->type != BUFFER_GLOBAL
		&& buffer == ctx->current_buffer->server->buffer))
		can_leak = !ctx->isolate_buffers;

	bool leak_to_active = buffer != ctx->current_buffer && can_leak;
	relay_prepare_buffer_line (ctx, buffer, line, leak_to_active);
	relay_broadcast (ctx);

	bool visible = (buffer == ctx->current_buffer || leak_to_active)
		&& ctx->terminal_suspended <= 0;

	// Advance the unread marker but don't create a new one
	if (!visible || buffer->new_messages_count)
	{
		buffer->new_messages_count++;
		if ((flags & BUFFER_LINE_UNIMPORTANT) || leak_to_active)
			buffer->new_unimportant_count++;
	}

	if (visible)
		buffer_line_display (ctx, buffer, line, leak_to_active);
	else
	{
		buffer->highlighted |= important;
		refresh_prompt (ctx);
	}
}

static void
log_full (struct app_context *ctx, struct server *s, struct buffer *buffer,
	unsigned flags, enum buffer_line_rendition r, const char *format, ...)
{
	va_list ap;
	va_start (ap, format);

	struct formatter f = formatter_make (ctx, s);
	formatter_addv (&f, format, &ap);
	log_formatter (ctx, buffer, flags, r, &f);

	va_end (ap);
}

#define log_global(ctx, flags, r, ...)                                         \
	log_full ((ctx), NULL, (ctx)->global_buffer, (flags), (r), __VA_ARGS__)
#define log_server(s, buffer, flags, r, ...)                                   \
	log_full ((s)->ctx, (s), (buffer), (flags), (r), __VA_ARGS__)

#define log_global_status(ctx, ...)                                            \
	log_global ((ctx), 0, BUFFER_LINE_STATUS, __VA_ARGS__)
#define log_global_error(ctx, ...)                                             \
	log_global ((ctx), 0, BUFFER_LINE_ERROR,  __VA_ARGS__)
#define log_global_indent(ctx, ...)                                            \
	log_global ((ctx), 0, BUFFER_LINE_INDENT, __VA_ARGS__)

#define log_server_status(s, buffer, ...)                                      \
	log_server ((s), (buffer), 0, BUFFER_LINE_STATUS, __VA_ARGS__)
#define log_server_error(s, buffer, ...)                                       \
	log_server ((s), (buffer), 0, BUFFER_LINE_ERROR,  __VA_ARGS__)

#define log_global_debug(ctx, ...)                                             \
	BLOCK_START                                                                \
		if (g_debug_mode)                                                      \
			log_global ((ctx), 0, 0, "(*) " __VA_ARGS__);                      \
	BLOCK_END

#define log_server_debug(s, ...)                                               \
	BLOCK_START                                                                \
		if (g_debug_mode)                                                      \
			log_server ((s), (s)->buffer, 0, 0, "(*) " __VA_ARGS__);           \
	BLOCK_END

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Lines that are used in more than one place

#define log_nick_self(s, buffer, new_)                                         \
	log_server ((s), (buffer), BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_STATUS,    \
		"You are now known as #n", (new_))
#define log_nick(s, buffer, old, new_)                                         \
	log_server ((s), (buffer), BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_STATUS,    \
		"#n is now known as #n", (old), (new_))

#define log_chghost_self(s, buffer, new_)                                      \
	log_server ((s), (buffer), BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_STATUS,    \
		"You are now #N", (new_))
#define log_chghost(s, buffer, old, new_)                                      \
	log_server ((s), (buffer), BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_STATUS,    \
		"#N is now #N", (old), (new_))

#define log_outcoming_notice(s, buffer, who, text)                             \
	log_server_status ((s), (buffer), "#s(#n): #m", "Notice", (who), (text))
#define log_outcoming_privmsg(s, buffer, prefixes, who, text)                  \
	log_server ((s), (buffer), 0, 0, "<#s#n> #m", (prefixes), (who), (text))
#define log_outcoming_action(s, buffer, who, text)                             \
	log_server ((s), (buffer), 0, BUFFER_LINE_ACTION, "#n #m", (who), (text))

#define log_outcoming_orphan_notice(s, target, text)                           \
	log_server_status ((s), (s)->buffer, "Notice -> #n: #m", (target), (text))
#define log_outcoming_orphan_privmsg(s, target, text)                          \
	log_server ((s), (s)->buffer, 0, BUFFER_LINE_STATUS,                       \
		"MSG(#n): #m", (target), (text))
#define log_outcoming_orphan_action(s, target, text)                           \
	log_server ((s), (s)->buffer, 0, BUFFER_LINE_ACTION,                       \
		"MSG(#n): #m", (target), (text))

#define log_ctcp_query(s, target, tag)                                         \
	log_server_status ((s), (s)->buffer, "CTCP query to #S: #S", target, tag)
#define log_ctcp_reply(s, target, reply /* freed! */)                          \
	log_server_status ((s), (s)->buffer, "CTCP reply to #S: #&S", target, reply)

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
make_log_filename (const char *filename, struct str *output)
{
	for (const char *p = filename; *p; p++)
		// XXX: anything more to replace?
		if (strchr ("/\\ ", *p))
			str_append_c (output, '_');
		else
			str_append_c (output, tolower_ascii (*p));
}

static char *
buffer_get_log_path (struct buffer *buffer)
{
	struct str path = str_make ();
	get_xdg_home_dir (&path, "XDG_DATA_HOME", ".local/share");
	str_append_printf (&path, "/%s/%s", PROGRAM_NAME, "logs");

	(void) mkdir_with_parents (path.str, NULL);

	str_append_c (&path, '/');
	// FIXME: This mixes up character encodings.
	make_log_filename (buffer->name, &path);
	str_append (&path, ".log");
	return str_steal (&path);
}

static void
buffer_open_log_file (struct app_context *ctx, struct buffer *buffer)
{
	if (!ctx->logging || buffer->log_file)
		return;

	// TODO: should we try to reopen files wrt. case mapping?
	//  - Need to read the whole directory and look for matches:
	//    irc_server_strcmp(buffer->s, d_name, make_log_filename())
	//    remember to strip the ".log" suffix from d_name, case-sensitively.
	//  - The tolower_ascii() in make_log_filename() is a perfect overlap,
	//    it may stay as-is.
	//  - buffer_get_log_path() will need to return a FILE *,
	//    or an error that includes the below message.
	char *path = buffer_get_log_path (buffer);
	if (!(buffer->log_file = fopen (path, "ab")))
		log_global_error (ctx, "Couldn't open log file `#l': #l",
			path, strerror (errno));
	else
		set_cloexec (fileno (buffer->log_file));
	free (path);
}

static void
buffer_close_log_file (struct buffer *buffer)
{
	if (buffer->log_file)
		(void) fclose (buffer->log_file);
	buffer->log_file = NULL;
}

static void
on_config_logging_change (struct config_item *item)
{
	struct app_context *ctx = item->user_data;
	ctx->logging = item->value.boolean;

	for (struct buffer *buffer = ctx->buffers; buffer; buffer = buffer->next)
		if (ctx->logging)
			buffer_open_log_file (ctx, buffer);
		else
			buffer_close_log_file (buffer);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static struct buffer *
buffer_by_name (struct app_context *ctx, const char *name)
{
	return str_map_find (&ctx->buffers_by_name, name);
}

static void
buffer_add (struct app_context *ctx, struct buffer *buffer)
{
	hard_assert (!buffer_by_name (ctx, buffer->name));

	relay_prepare_buffer_update (ctx, buffer);
	relay_broadcast (ctx);

	str_map_set (&ctx->buffers_by_name, buffer->name, buffer);
	LIST_APPEND_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);

	buffer_open_log_file (ctx, buffer);

	// Normally this doesn't cause changes in the prompt but a prompt hook
	// could decide to show some information for all buffers nonetheless
	refresh_prompt (ctx);
}

static void
buffer_remove (struct app_context *ctx, struct buffer *buffer)
{
	hard_assert (buffer != ctx->current_buffer);
	hard_assert (buffer != ctx->global_buffer);

	relay_prepare_buffer_remove (ctx, buffer);
	relay_broadcast (ctx);

	CALL_ (ctx->input, buffer_destroy, buffer->input_data);
	buffer->input_data = NULL;

	// And make sure to unlink the buffer from "irc_buffer_map"
	struct server *s = buffer->server;
	if (buffer->channel)
		str_map_set (&s->irc_buffer_map, buffer->channel->name, NULL);
	if (buffer->user)
		str_map_set (&s->irc_buffer_map, buffer->user->nickname, NULL);

	if (buffer == ctx->last_buffer)
		ctx->last_buffer = NULL;
	if (buffer->type == BUFFER_SERVER)
		buffer->server->buffer = NULL;

	str_map_set (&ctx->buffers_by_name, buffer->name, NULL);
	LIST_UNLINK_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);
	buffer_unref (buffer);

	refresh_prompt (ctx);
}

static void
buffer_print_read_marker (struct app_context *ctx, FILE *stream, int flush_opts)
{
	struct formatter f = formatter_make (ctx, NULL);
	const int timestamp_width = 8;  // hardcoded to %T right now, simple
	const char *marker_char =
		get_config_string (ctx->config.root, "general.read_marker_char");

	// We could turn this off on FLUSH_OPT_NOWRAP, however our default pager
	// wraps lines for us even if we don't do it ourselves, and thus there's
	// no need to worry about inconsistency.
	if (*marker_char)
	{
		struct str s = str_make ();
		for (int i = 0; i < timestamp_width; i++)
			str_append (&s, marker_char);
		formatter_add (&f, "#a#s#r", ATTR_TIMESTAMP, s.str);
		str_reset (&s);
		for (int i = timestamp_width; i < g_terminal.columns; i++)
			str_append (&s, marker_char);
		formatter_add (&f, "#a#s#r\n", ATTR_READ_MARKER, s.str);
		str_free (&s);
	}
	else
		formatter_add (&f, "#a-- -- -- ---\n", ATTR_READ_MARKER);

	formatter_flush (&f, stream, flush_opts);
	// Flush the trailing formatting reset item
	fflush (stream);
	formatter_free (&f);
}

static void
buffer_print_backlog (struct app_context *ctx, struct buffer *buffer)
{
	// Buffers can be activated, or their lines modified, as automatic actions.
	if (ctx->terminal_suspended)
		return;

	// The prompt can take considerable time to redraw
	CALL (ctx->input, hide);

	// Simulate curses-like fullscreen buffers if the terminal allows it
	if (g_terminal.initialized && clear_screen)
	{
		terminal_printer_fn printer = get_attribute_printer (stdout);
		tputs (clear_screen, 1, printer);
		if (cursor_to_ll)
			tputs (cursor_to_ll, 1, printer);
		else if (row_address)
			tputs (tparm (row_address, g_terminal.lines - 1,
				0, 0, 0, 0, 0, 0, 0, 0), 1, printer);
		else if (cursor_address)
			tputs (tparm (cursor_address, g_terminal.lines - 1,
				0, 0, 0, 0, 0, 0, 0, 0), 1, printer);
		fflush (stdout);

		// We should update "last_displayed_msg_time" here just to be sure
		// that the first date marker, if necessary, is shown, but in practice
		// the value should always be from today when this function is called
	}
	else
	{
		char *buffer_name_localized =
			iconv_xstrdup (ctx->term_from_utf8, buffer->name, -1, NULL);
		print_status ("%s", buffer_name_localized);
		free (buffer_name_localized);
	}

	// That is, minus the readline prompt (taking at least one line)
	int display_limit = MAX (10, g_terminal.lines - 1);
	int to_display = 0;

	struct buffer_line *line;
	for (line = buffer->lines_tail; line; line = line->prev)
	{
		to_display++;
		if (buffer_line_will_show_up (buffer, line))
			display_limit--;
		if (!line->prev || display_limit <= 0)
			break;
	}

	// Once we've found where we want to start with the backlog, print it
	int until_marker = to_display - (int) buffer->new_messages_count;
	for (; line; line = line->next)
	{
		if (until_marker-- == 0
		 && buffer->new_messages_count != buffer->lines_count)
			buffer_print_read_marker (ctx, stdout, 0);
		buffer_line_display (ctx, buffer, line, 0);
	}

	// So that it is obvious if the last line in the buffer is not from today
	buffer_update_time (ctx, time (NULL), stdout, 0);

	refresh_prompt (ctx);
	CALL (ctx->input, show);
}

static void
buffer_activate (struct app_context *ctx, struct buffer *buffer)
{
	if (ctx->current_buffer == buffer)
		return;

	relay_prepare_buffer_activate (ctx, buffer);
	relay_broadcast (ctx);

	// This is the only place where the unread messages marker
	// and highlight indicator are reset
	if (ctx->current_buffer)
	{
		ctx->current_buffer->new_messages_count = 0;
		ctx->current_buffer->new_unimportant_count = 0;
		ctx->current_buffer->highlighted = false;
	}

	buffer_print_backlog (ctx, buffer);
	CALL_ (ctx->input, buffer_switch, buffer->input_data);

	// Now at last we can switch the pointers
	ctx->last_buffer = ctx->current_buffer;
	ctx->current_buffer = buffer;

	refresh_prompt (ctx);
}

static void
buffer_merge (struct app_context *ctx,
	struct buffer *buffer, struct buffer *merged)
{
	// XXX: anything better to do?  This situation is arguably rare and I'm
	//   not entirely sure what action to take.
	log_full (ctx, NULL, buffer, 0, BUFFER_LINE_STATUS,
		"Buffer #s was merged into this buffer", merged->name);

	// Find all lines from "merged" newer than the newest line in "buffer"
	struct buffer_line *start = merged->lines;
	if (buffer->lines_tail)
		while (start && start->when < buffer->lines_tail->when)
			start = start->next;
	if (!start)
		return;

	// Count how many of them we have
	size_t n = 0;
	for (struct buffer_line *iter = start; iter; iter = iter->next)
		n++;
	struct buffer_line *tail = merged->lines_tail;

	// Cut them from the original buffer
	if (start == merged->lines)
		merged->lines = NULL;
	else if (start->prev)
		start->prev->next = NULL;
	merged->lines_tail = start->prev;
	merged->lines_count -= n;

	// Append them to current lines in the buffer
	buffer->lines_tail->next = start;
	start->prev = buffer->lines_tail;
	buffer->lines_tail = tail;
	buffer->lines_count += n;

	// And since there is no log_*() call, send them to relays manually
	buffer->highlighted |= merged->highlighted;
	LIST_FOR_EACH (struct buffer_line, line, start)
	{
		if (buffer->new_messages_count)
		{
			buffer->new_messages_count++;
			if (line->flags & BUFFER_LINE_UNIMPORTANT)
				buffer->new_unimportant_count++;
		}

		relay_prepare_buffer_line (ctx, buffer, line, false);
		relay_broadcast (ctx);
	}

	log_full (ctx, NULL, buffer, BUFFER_LINE_SKIP_FILE, BUFFER_LINE_STATUS,
		"End of merged content");
}

static void
buffer_rename (struct app_context *ctx,
	struct buffer *buffer, const char *new_name)
{
	struct buffer *collision = str_map_find (&ctx->buffers_by_name, new_name);
	if (collision == buffer)
		return;

	hard_assert (!collision);

	relay_prepare_buffer_rename (ctx, buffer, new_name);
	relay_broadcast (ctx);

	str_map_set (&ctx->buffers_by_name, buffer->name, NULL);
	str_map_set (&ctx->buffers_by_name, new_name, buffer);

	cstr_set (&buffer->name, xstrdup (new_name));

	buffer_close_log_file (buffer);
	buffer_open_log_file (ctx, buffer);

	// We might have renamed the current buffer
	refresh_prompt (ctx);
}

static void
buffer_clear (struct app_context *ctx, struct buffer *buffer)
{
	relay_prepare_buffer_clear (ctx, buffer);
	relay_broadcast (ctx);

	LIST_FOR_EACH (struct buffer_line, iter, buffer->lines)
		buffer_line_destroy (iter);

	buffer->lines = buffer->lines_tail = NULL;
	buffer->lines_count = 0;
}

static void
buffer_toggle_unimportant (struct app_context *ctx, struct buffer *buffer)
{
	buffer->hide_unimportant ^= true;

	relay_prepare_buffer_update (ctx, buffer);
	relay_broadcast (ctx);

	if (buffer == ctx->current_buffer)
		buffer_print_backlog (ctx, buffer);
}

static struct buffer *
buffer_at_index (struct app_context *ctx, int n)
{
	int i = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
		if (++i == n)
			return iter;
	return NULL;
}

static struct buffer *
buffer_next (struct app_context *ctx, int count)
{
	struct buffer *new_buffer = ctx->current_buffer;
	while (count-- > 0)
		if (!(new_buffer = new_buffer->next))
			new_buffer = ctx->buffers;
	return new_buffer;
}

static struct buffer *
buffer_previous (struct app_context *ctx, int count)
{
	struct buffer *new_buffer = ctx->current_buffer;
	while (count-- > 0)
		if (!(new_buffer = new_buffer->prev))
			new_buffer = ctx->buffers_tail;
	return new_buffer;
}

static bool
buffer_goto (struct app_context *ctx, int n)
{
	struct buffer *buffer = buffer_at_index (ctx, n);
	if (!buffer)
		return false;

	buffer_activate (ctx, buffer);
	return true;
}

static int
buffer_count (struct app_context *ctx)
{
	int total = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
		total++;
	return total;
}

static void
buffer_move (struct app_context *ctx, struct buffer *buffer, int n)
{
	hard_assert (n >= 1 && n <= buffer_count (ctx));
	LIST_UNLINK_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);

	struct buffer *following = ctx->buffers;
	while (--n && following)
		following = following->next;

	LIST_INSERT_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer, following);
	refresh_prompt (ctx);
}

static int
buffer_get_index (struct app_context *ctx, struct buffer *buffer)
{
	int index = 1;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
	{
		if (iter == buffer)
			return index;
		index++;
	}
	return -1;
}

static void
buffer_remove_safe (struct app_context *ctx, struct buffer *buffer)
{
	if (buffer == ctx->current_buffer)
		buffer_activate (ctx, ctx->last_buffer
			? ctx->last_buffer
			: buffer_next (ctx, 1));
	buffer_remove (ctx, buffer);
}

static void
init_global_buffer (struct app_context *ctx)
{
	struct buffer *global = ctx->global_buffer =
		buffer_new (ctx->input, BUFFER_GLOBAL, xstrdup (PROGRAM_NAME));

	buffer_add (ctx, global);
	buffer_activate (ctx, global);
}

// --- Users, channels ---------------------------------------------------------

static char *
irc_make_buffer_name (struct server *s, const char *target)
{
	if (!target)
		return xstrdup (s->name);

	char *target_utf8 = irc_to_utf8 (target);
	char *name = xstrdup_printf ("%s.%s", s->name, target_utf8);
	free (target_utf8);

	struct buffer *conflict = buffer_by_name (s->ctx, name);
	if (!conflict)
		return name;

	hard_assert (conflict->server == s);

	// Fix up any conflicts.  Note that while parentheses aren't allowed
	// in IRC nicknames, they may occur in channel names.
	int i = 0;
	char *unique = xstrdup_printf ("%s(%d)", name, ++i);
	while (buffer_by_name (s->ctx, unique))
		cstr_set (&unique, xstrdup_printf ("%s(%d)", name, ++i));
	free (name);
	return unique;
}

static void
irc_user_on_destroy (void *object, void *user_data)
{
	struct user *user = object;
	struct server *s = user_data;
	if (!s->rehashing)
		str_map_set (&s->irc_users, user->nickname, NULL);
}

static struct user *
irc_make_user (struct server *s, char *nickname)
{
	hard_assert (!str_map_find (&s->irc_users, nickname));

	struct user *user = user_new (nickname);
	(void) user_weak_ref (user, irc_user_on_destroy, s);
	str_map_set (&s->irc_users, user->nickname, user);
	return user;
}

struct user *
irc_get_or_make_user (struct server *s, const char *nickname)
{
	struct user *user = str_map_find (&s->irc_users, nickname);
	if (user)
		return user_ref (user);
	return irc_make_user (s, xstrdup (nickname));
}

static struct buffer *
irc_get_or_make_user_buffer (struct server *s, const char *nickname)
{
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, nickname);
	if (buffer)
		return buffer;

	struct user *user = irc_get_or_make_user (s, nickname);

	// Open a new buffer for the user
	buffer = buffer_new (s->ctx->input,
		BUFFER_PM, irc_make_buffer_name (s, nickname));
	buffer->server = s;
	buffer->user = user;
	str_map_set (&s->irc_buffer_map, user->nickname, buffer);

	buffer_add (s->ctx, buffer);
	return buffer;
}

static void
irc_get_channel_user_prefix (struct server *s,
	struct channel_user *channel_user, struct str *output)
{
	if (s->ctx->show_all_prefixes)
		str_append (output, channel_user->prefixes);
	else if (channel_user->prefixes[0])
		str_append_c (output, channel_user->prefixes[0]);
}

static bool
irc_channel_is_joined (struct channel *channel)
{
	// TODO: find a better way of checking if we're on a channel
	return !!channel->users_len;
}

// Note that this eats the user reference
static void
irc_channel_link_user (struct channel *channel, struct user *user,
	const char *prefixes)
{
	struct user_channel *user_channel = user_channel_new (channel);
	LIST_PREPEND (user->channels, user_channel);

	struct channel_user *channel_user = channel_user_new (user, prefixes);
	LIST_PREPEND (channel->users, channel_user);
	channel->users_len++;
}

static void
irc_channel_unlink_user
	(struct channel *channel, struct channel_user *channel_user)
{
	// First destroy the user's weak references to the channel
	struct user *user = channel_user->user;
	LIST_FOR_EACH (struct user_channel, iter, user->channels)
		if (iter->channel == channel)
		{
			LIST_UNLINK (user->channels, iter);
			user_channel_destroy (iter);
		}

	// TODO: poll the away status for users we don't share a channel with.
	//   It might or might not be worth to auto-set this on with RPL_AWAY.
	if (!user->channels && user != channel->s->irc_user)
		user->away = false;

	// Then just unlink the user from the channel
	LIST_UNLINK (channel->users, channel_user);
	channel_user_destroy (channel_user);
	channel->users_len--;
}

static void
irc_channel_on_destroy (void *object, void *user_data)
{
	struct channel *channel = object;
	struct server *s = user_data;
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
		irc_channel_unlink_user (channel, iter);
	if (!s->rehashing)
		str_map_set (&s->irc_channels, channel->name, NULL);
}

static struct channel *
irc_make_channel (struct server *s, char *name)
{
	hard_assert (!str_map_find (&s->irc_channels, name));

	struct channel *channel = channel_new (s, name);
	(void) channel_weak_ref (channel, irc_channel_on_destroy, s);
	str_map_set (&s->irc_channels, channel->name, channel);
	return channel;
}

static void
irc_channel_broadcast_buffer_update (const struct channel *channel)
{
	struct server *s = channel->s;
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel->name);
	if (buffer)
	{
		relay_prepare_buffer_update (s->ctx, buffer);
		relay_broadcast (s->ctx);
	}
}

static void
irc_channel_set_topic (struct channel *channel, const char *topic)
{
	cstr_set (&channel->topic, xstrdup (topic));
	irc_channel_broadcast_buffer_update (channel);
}

static struct channel_user *
irc_channel_get_user (struct channel *channel, struct user *user)
{
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
		if (iter->user == user)
			return iter;
	return NULL;
}

static void
irc_remove_user_from_channel (struct user *user, struct channel *channel)
{
	struct channel_user *channel_user = irc_channel_get_user (channel, user);
	if (channel_user)
		irc_channel_unlink_user (channel, channel_user);
}

static void
irc_left_channel (struct channel *channel)
{
	strv_reset (&channel->names_buf);
	channel->show_names_after_who = false;

	LIST_FOR_EACH (struct channel_user, iter, channel->users)
		irc_channel_unlink_user (channel, iter);

	// Send empty channel modes.
	irc_channel_broadcast_buffer_update (channel);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
remove_conflicting_buffer (struct server *s, struct buffer *buffer)
{
	log_server_status (s, s->buffer,
		"Removed buffer #s because of casemapping conflict", buffer->name);
	if (s->ctx->current_buffer == buffer)
		buffer_activate (s->ctx, s->buffer);
	buffer_remove (s->ctx, buffer);
}

static void
irc_try_readd_user (struct server *s,
	struct user *user, struct buffer *buffer)
{
	if (str_map_find (&s->irc_users, user->nickname))
	{
		// Remove user from all channels and destroy any PM buffer
		user_ref (user);
		LIST_FOR_EACH (struct user_channel, iter, user->channels)
			irc_remove_user_from_channel (user, iter->channel);
		if (buffer)
			remove_conflicting_buffer (s, buffer);
		user_unref (user);
	}
	else
	{
		str_map_set (&s->irc_users, user->nickname, user);
		str_map_set (&s->irc_buffer_map, user->nickname, buffer);
	}
}

static void
irc_try_readd_channel (struct channel *channel, struct buffer *buffer)
{
	struct server *s = channel->s;
	if (str_map_find (&s->irc_channels, channel->name))
	{
		// Remove all users from channel and destroy any channel buffer
		channel_ref (channel);
		LIST_FOR_EACH (struct channel_user, iter, channel->users)
			irc_channel_unlink_user (channel, iter);
		if (buffer)
			remove_conflicting_buffer (s, buffer);
		channel_unref (channel);
	}
	else
	{
		str_map_set (&s->irc_channels, channel->name, channel);
		str_map_set (&s->irc_buffer_map, channel->name, buffer);
	}
}

static void
irc_rehash_and_fix_conflicts (struct server *s)
{
	// Save the old maps and initialize new ones
	struct str_map old_users      = s->irc_users;
	struct str_map old_channels   = s->irc_channels;
	struct str_map old_buffer_map = s->irc_buffer_map;

	s->irc_users      = str_map_make (NULL);
	s->irc_channels   = str_map_make (NULL);
	s->irc_buffer_map = str_map_make (NULL);

	s->irc_users     .key_xfrm = s->irc_strxfrm;
	s->irc_channels  .key_xfrm = s->irc_strxfrm;
	s->irc_buffer_map.key_xfrm = s->irc_strxfrm;

	// Prevent channels and users from unsetting themselves
	// from server maps upon removing the last reference to them
	s->rehashing = true;

	// XXX: to be perfectly sure, we should also check
	//   whether any users collide with channels and vice versa

	// Our own user always takes priority, add him first
	if (s->irc_user)
		irc_try_readd_user (s, s->irc_user,
			str_map_find (&old_buffer_map, s->irc_user->nickname));

	struct str_map_iter iter;
	struct user *user;
	struct channel *channel;

	iter = str_map_iter_make (&old_users);
	while ((user = str_map_iter_next (&iter)))
		irc_try_readd_user (s, user,
			str_map_find (&old_buffer_map, user->nickname));

	iter = str_map_iter_make (&old_channels);
	while ((channel = str_map_iter_next (&iter)))
		irc_try_readd_channel (channel,
			str_map_find (&old_buffer_map, channel->name));

	// Hopefully we've either moved or destroyed all the old content
	s->rehashing = false;

	str_map_free (&old_users);
	str_map_free (&old_channels);
	str_map_free (&old_buffer_map);
}

static void
irc_set_casemapping (struct server *s,
	irc_tolower_fn tolower, irc_strxfrm_fn strxfrm)
{
	if (tolower == s->irc_tolower
	 && strxfrm == s->irc_strxfrm)
		return;

	s->irc_tolower = tolower;
	s->irc_strxfrm = strxfrm;

	// Ideally we would never have to do this but I can't think of a workaround
	irc_rehash_and_fix_conflicts (s);
}

// --- Core functionality ------------------------------------------------------

static bool
irc_is_connected (struct server *s)
{
	return s->state != IRC_DISCONNECTED && s->state != IRC_CONNECTING;
}

static void
irc_update_poller (struct server *s, const struct pollfd *pfd)
{
	int new_events = s->transport->get_poll_events (s);
	hard_assert (new_events != 0);

	if (!pfd || pfd->events != new_events)
		poller_fd_set (&s->socket_event, new_events);
}

static void
irc_cancel_timers (struct server *s)
{
	poller_timer_reset (&s->timeout_tmr);
	poller_timer_reset (&s->ping_tmr);
	poller_timer_reset (&s->reconnect_tmr);
	poller_timer_reset (&s->autojoin_tmr);
}

static void
irc_reset_connection_timeouts (struct server *s)
{
	poller_timer_set (&s->timeout_tmr, 3 * 60 * 1000);
	poller_timer_set (&s->ping_tmr, (3 * 60 + 30) * 1000);
	poller_timer_reset (&s->reconnect_tmr);
}

static int64_t
irc_get_reconnect_delay (struct server *s)
{
	int64_t delay = get_config_integer (s->config, "reconnect_delay");
	int64_t delay_factor = get_config_integer
		(s->ctx->config.root, "general.reconnect_delay_growing");
	for (unsigned i = 0; i < s->reconnect_attempt; i++)
	{
		if (delay_factor && delay > INT64_MAX / delay_factor)
			break;
		delay *= delay_factor;
	}

	int64_t delay_max =
		get_config_integer (s->ctx->config.root, "general.reconnect_delay_max");
	return MIN (delay, delay_max);
}

static void
irc_queue_reconnect (struct server *s)
{
	// As long as the user wants us to, that is
	if (!get_config_boolean (s->config, "reconnect"))
		return;

	// XXX: maybe add a state for when a connect is queued?
	hard_assert (s->state == IRC_DISCONNECTED);

	int64_t delay = irc_get_reconnect_delay (s);
	s->reconnect_attempt++;

	log_server_status (s, s->buffer,
		"Trying to reconnect in #&s seconds...",
		xstrdup_printf ("%" PRId64, delay));
	poller_timer_set (&s->reconnect_tmr, delay * 1000);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void irc_process_sent_message
	(const struct irc_message *msg, struct server *s);
static void irc_send (struct server *s,
	const char *format, ...) ATTRIBUTE_PRINTF (2, 3);

static void
irc_send (struct server *s, const char *format, ...)
{
	if (!soft_assert (irc_is_connected (s)))
	{
		log_server_debug (s, "sending a message to a dead server connection");
		return;
	}

	if (s->state == IRC_CLOSING
	 || s->state == IRC_HALF_CLOSED)
		return;

	va_list ap;
	va_start (ap, format);
	struct str str = str_make ();
	str_append_vprintf (&str, format, ap);
	va_end (ap);

	log_server_debug (s, "#a<< \"#S\"#r", ATTR_PART, str.str);

	struct irc_message msg;
	irc_parse_message (&msg, str.str);
	irc_process_sent_message (&msg, s);
	irc_free_message (&msg);

	str_append_str (&s->write_buffer, &str);
	str_free (&str);
	str_append (&s->write_buffer, "\r\n");
	irc_update_poller (s, NULL);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
irc_set_state (struct server *s, enum server_state state)
{
	s->state = state;

	relay_prepare_server_update (s->ctx, s);
	relay_broadcast (s->ctx);

	refresh_prompt (s->ctx);
}

static void
irc_real_shutdown (struct server *s)
{
	hard_assert (irc_is_connected (s) && s->state != IRC_HALF_CLOSED);

	if (s->transport
	 && s->transport->in_before_shutdown)
		s->transport->in_before_shutdown (s);

	while (shutdown (s->socket, SHUT_WR) == -1)
		// XXX: we get ENOTCONN with OpenSSL (not plain) when a localhost
		// server is aborted, why?  strace says read 0, write 31, shutdown -1.
		if (!soft_assert (errno == EINTR))
			break;

	irc_set_state (s, IRC_HALF_CLOSED);
}

static void
irc_shutdown (struct server *s)
{
	if (s->state == IRC_CLOSING
	 || s->state == IRC_HALF_CLOSED)
		return;

	// TODO: set a timer to cut the connection if we don't receive an EOF
	irc_set_state (s, IRC_CLOSING);

	// Either there's still some data in the write buffer and we wait
	// until they're sent, or we send an EOF to the server right away
	if (!s->write_buffer.len)
		irc_real_shutdown (s);
}

static void
irc_destroy_connector (struct server *s)
{
	if (s->connector)
		connector_free (s->connector);
	free (s->connector);
	s->connector = NULL;

	if (s->socks_conn)
		socks_connector_free (s->socks_conn);
	free (s->socks_conn);
	s->socks_conn = NULL;

	// Not connecting anymore
	irc_set_state (s, IRC_DISCONNECTED);
}

static void
try_finish_quit (struct app_context *ctx)
{
	if (!ctx->quitting)
		return;

	bool disconnected_all = true;
	struct str_map_iter iter = str_map_iter_make (&ctx->servers);
	struct server *s;
	while ((s = str_map_iter_next (&iter)))
		if (irc_is_connected (s))
			disconnected_all = false;

	if (disconnected_all)
		ctx->polling = false;
}

static void
irc_destroy_transport (struct server *s)
{
	if (s->transport
	 && s->transport->cleanup)
		s->transport->cleanup (s);
	s->transport = NULL;

	poller_fd_reset (&s->socket_event);
	xclose (s->socket);
	s->socket = -1;
	irc_set_state (s, IRC_DISCONNECTED);

	str_reset (&s->read_buffer);
	str_reset (&s->write_buffer);
}

static void
irc_destroy_state (struct server *s)
{
	struct str_map_iter iter = str_map_iter_make (&s->irc_channels);
	struct channel *channel;
	while ((channel = str_map_iter_next (&iter)))
		irc_left_channel (channel);

	if (s->irc_user)
	{
		user_unref (s->irc_user);
		s->irc_user = NULL;
	}

	str_reset (&s->irc_user_modes);
	cstr_set (&s->irc_user_host, NULL);

	strv_reset (&s->outstanding_joins);
	strv_reset (&s->cap_ls_buf);
	s->cap_away_notify = false;
	s->cap_echo_message = false;
	s->cap_sasl = false;

	// Need to call this before server_init_specifics()
	irc_set_casemapping (s, irc_tolower, irc_strxfrm);

	server_free_specifics (s);
	server_init_specifics (s);
}

static void
irc_disconnect (struct server *s)
{
	hard_assert (irc_is_connected (s));

	struct str_map_iter iter = str_map_iter_make (&s->irc_buffer_map);
	struct buffer *buffer;
	while ((buffer = str_map_iter_next (&iter)))
		log_server (s, buffer, BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_STATUS,
			"Disconnected from server");

	irc_cancel_timers (s);
	irc_destroy_transport (s);
	irc_destroy_state (s);

	// Take any relevant actions
	if (s->ctx->quitting)
		try_finish_quit (s->ctx);
	else if (s->manual_disconnect)
		s->manual_disconnect = false;
	else
	{
		s->reconnect_attempt = 0;
		irc_queue_reconnect (s);
	}
}

static void
irc_initiate_disconnect (struct server *s, const char *reason)
{
	hard_assert (irc_is_connected (s));

	// It can take a very long time for sending QUIT to take effect
	if (s->manual_disconnect)
	{
		log_server_error (s, s->buffer, "#s: #s", "Disconnected from server",
			"connection torn down early per user request");
		irc_disconnect (s);
		return;
	}

	if (reason)
		irc_send (s, "QUIT :%s", reason);
	else
		// TODO: make the default QUIT message customizable
		//   -> global/per server/both?
		//   -> implement it with an output hook in a plugin?
		irc_send (s, "QUIT :%s", PROGRAM_NAME " " PROGRAM_VERSION);

	s->manual_disconnect = true;
	irc_shutdown (s);
}

static void
request_quit (struct app_context *ctx, const char *message)
{
	if (!ctx->quitting)
	{
		log_global_status (ctx, "Shutting down");
		ctx->quitting = true;

		// Disable the user interface
		CALL (ctx->input, hide);
	}

	struct str_map_iter iter = str_map_iter_make (&ctx->servers);
	struct server *s;
	while ((s = str_map_iter_next (&iter)))
	{
		// There may be a timer set to reconnect to the server
		poller_timer_reset (&s->reconnect_tmr);

		if (irc_is_connected (s))
			irc_initiate_disconnect (s, message);
		else if (s->state == IRC_CONNECTING)
			irc_destroy_connector (s);
	}

	try_finish_quit (ctx);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
on_irc_ping_timeout (void *user_data)
{
	struct server *s = user_data;
	log_server_error (s, s->buffer,
		"#s: #s", "Disconnected from server", "timeout");
	irc_disconnect (s);
}

static void
on_irc_timeout (void *user_data)
{
	// Provoke a response from the server
	struct server *s = user_data;
	irc_send (s, "PING :%" PRIi64, (int64_t) time (NULL));
}

static void
on_irc_autojoin_timeout (void *user_data)
{
	struct server *s = user_data;

	// Since we may not have information from RPL_ISUPPORT yet,
	// it's our safest bet to send the channels one at a time

	struct str_map joins_sent = str_map_make (NULL);

	// We don't know the casemapping yet either, however ASCII should do
	joins_sent.key_xfrm = tolower_ascii_strxfrm;

	// First join autojoin channels in their given order
	const char *autojoin = get_config_string (s->config, "autojoin");
	if (autojoin)
	{
		struct strv v = strv_make ();
		cstr_split (autojoin, ",", true, &v);
		for (size_t i = 0; i < v.len; i++)
		{
			irc_send (s, "JOIN %s", v.vector[i]);
			str_map_set (&joins_sent, v.vector[i], (void *) 1);
		}
		strv_free (&v);
	}

	// Then also rejoin any channels from the last disconnect
	struct str_map_iter iter = str_map_iter_make (&s->irc_channels);
	struct channel *channel;
	while ((channel = str_map_iter_next (&iter)))
	{
		struct str target = str_make ();
		str_append (&target, channel->name);

		const char *key;
		if ((key = str_map_find (&channel->param_modes, "k")))
			str_append_printf (&target, " %s", key);

		// When a channel is both autojoined and rejoined, both keys are tried
		if (!channel->left_manually
		 && !str_map_find (&joins_sent, target.str))
			irc_send (s, "JOIN %s", target.str);
		str_free (&target);
	}

	str_map_free (&joins_sent);
}

// --- Server I/O --------------------------------------------------------------

static char *
irc_process_hooks (struct server *s, char *input)
{
	log_server_debug (s, "#a>> \"#S\"#r", ATTR_JOIN, input);
	uint64_t hash = siphash_wrapper (input, strlen (input));
	LIST_FOR_EACH (struct hook, iter, s->ctx->irc_hooks)
	{
		struct irc_hook *hook = (struct irc_hook *) iter;
		if (!(input = hook->filter (hook, s, input)))
		{
			log_server_debug (s, "#a>= #s#r", ATTR_JOIN, "thrown away by hook");
			return NULL;
		}

		// The old input may get freed, so we compare against a hash of it
		uint64_t new_hash = siphash_wrapper (input, strlen (input));
		if (new_hash != hash)
			log_server_debug (s, "#a>= \"#S\"#r", ATTR_JOIN, input);
		hash = new_hash;
	}
	return input;
}

static void irc_process_message
	(const struct irc_message *msg, struct server *s);

static void
irc_process_buffer_custom (struct server *s, struct str *buf)
{
	const char *start = buf->str, *end = start + buf->len;
	for (const char *p = start; p + 1 < end; p++)
	{
		// Split the input on newlines
		if (p[0] != '\r' || p[1] != '\n')
			continue;

		char *processed = irc_process_hooks (s, xstrndup (start, p - start));
		start = p + 2;
		if (!processed)
			continue;

		struct irc_message msg;
		irc_parse_message (&msg, processed);
		irc_process_message (&msg, s);
		irc_free_message (&msg);

		free (processed);
	}
	str_remove_slice (buf, 0, start - buf->str);
}

static enum socket_io_result
irc_try_read (struct server *s)
{
	enum socket_io_result result = s->transport->try_read (s);
	if (s->read_buffer.len >= (1 << 20))
	{
		// XXX: this is stupid; if anything, count it in dependence of time;
		//   we could make transport_tls_try_read() limit the immediate amount
		//   of data read like socket_io_try_read() does and remove this check
		log_server_error (s, s->buffer,
			"The IRC server seems to spew out data frantically");
		return SOCKET_IO_ERROR;
	}
	if (s->read_buffer.len)
		irc_process_buffer_custom (s, &s->read_buffer);
	return result;
}

static enum socket_io_result
irc_try_write (struct server *s)
{
	enum socket_io_result result = s->transport->try_write (s);
	if (result == SOCKET_IO_OK)
	{
		// If we're flushing the write buffer and our job is complete, we send
		// an EOF to the server, changing the state to IRC_HALF_CLOSED
		if (s->state == IRC_CLOSING && !s->write_buffer.len)
			irc_real_shutdown (s);
	}
	return result;
}

static bool
irc_try_read_write (struct server *s)
{
	enum socket_io_result read_result;
	enum socket_io_result write_result;
	if ((read_result  = irc_try_read  (s)) == SOCKET_IO_ERROR
	 || (write_result = irc_try_write (s)) == SOCKET_IO_ERROR)
	{
		log_server_error (s, s->buffer, "Server connection failed");
		return false;
	}

	// FIXME: this may probably fire multiple times when we're flushing,
	//   we should probably store a flag next to the state
	if (read_result  == SOCKET_IO_EOF
	 || write_result == SOCKET_IO_EOF)
		log_server_error (s, s->buffer, "Server closed the connection");

	// If the write needs to read and we receive an EOF, we can't flush
	if (write_result == SOCKET_IO_EOF)
		return false;

	if (read_result  == SOCKET_IO_EOF)
	{
		// Eventually initiate shutdown to flush the write buffer
		irc_shutdown (s);

		// If there's nothing to write, we can disconnect now
		if (s->state == IRC_HALF_CLOSED)
			return false;
	}
	return true;
}

static void
on_irc_ready (const struct pollfd *pfd, struct server *s)
{
	if (irc_try_read_write (s))
	{
		// XXX: shouldn't we rather wait for PONG messages?
		irc_reset_connection_timeouts (s);
		irc_update_poller (s, pfd);
	}
	else
		// We don't want to keep the socket anymore
		irc_disconnect (s);
}

// --- Plain transport ---------------------------------------------------------

static enum socket_io_result
transport_plain_try_read (struct server *s)
{
	enum socket_io_result result =
		socket_io_try_read (s->socket, &s->read_buffer);
	if (result == SOCKET_IO_ERROR)
		print_debug ("%s: %s", __func__, strerror (errno));
	return result;
}

static enum socket_io_result
transport_plain_try_write (struct server *s)
{
	enum socket_io_result result =
		socket_io_try_write (s->socket, &s->write_buffer);
	if (result == SOCKET_IO_ERROR)
		print_debug ("%s: %s", __func__, strerror (errno));
	return result;
}

static int
transport_plain_get_poll_events (struct server *s)
{
	int events = POLLIN;
	if (s->write_buffer.len)
		events |= POLLOUT;
	return events;
}

static struct transport g_transport_plain =
{
	.try_read         = transport_plain_try_read,
	.try_write        = transport_plain_try_write,
	.get_poll_events  = transport_plain_get_poll_events,
};

// --- TLS transport -----------------------------------------------------------

struct transport_tls_data
{
	SSL_CTX *ssl_ctx;                   ///< SSL context
	SSL *ssl;                           ///< SSL connection
	bool ssl_rx_want_tx;                ///< SSL_read() wants to write
	bool ssl_tx_want_rx;                ///< SSL_write() wants to read
};

/// The index in SSL_CTX user data for a reference to the server
static int g_transport_tls_data_index = -1;

static int
transport_tls_verify_callback (int preverify_ok, X509_STORE_CTX *ctx)
{
	SSL *ssl = X509_STORE_CTX_get_ex_data
		(ctx, SSL_get_ex_data_X509_STORE_CTX_idx ());
	struct server *s = SSL_CTX_get_ex_data
		(SSL_get_SSL_CTX (ssl), g_transport_tls_data_index);

	X509 *cert = X509_STORE_CTX_get_current_cert (ctx);
	char *subject = X509_NAME_oneline (X509_get_subject_name (cert), NULL, 0);
	char *issuer  = X509_NAME_oneline (X509_get_issuer_name  (cert), NULL, 0);

	log_server_status (s, s->buffer, "Certificate subject: #s", subject);
	log_server_status (s, s->buffer, "Certificate issuer: #s", issuer);

	if (!preverify_ok)
	{
		log_server_error (s, s->buffer,
			"Certificate verification failed: #s",
			X509_verify_cert_error_string (X509_STORE_CTX_get_error (ctx)));
	}

	free (subject);
	free (issuer);
	return preverify_ok;
}

static bool
transport_tls_init_ca_set (SSL_CTX *ssl_ctx, const char *file, const char *path,
	struct error **e)
{
	ERR_clear_error ();

	if (file || path)
	{
		if (SSL_CTX_load_verify_locations (ssl_ctx, file, path))
			return true;

		return error_set (e, "%s: %s",
			"Failed to set locations for the CA certificate bundle",
			xerr_describe_error ());
	}

	if (!SSL_CTX_set_default_verify_paths (ssl_ctx))
		return error_set (e, "%s: %s",
			"Couldn't load the default CA certificate bundle",
			xerr_describe_error ());
	return true;
}

static bool
transport_tls_init_ca (struct server *s, SSL_CTX *ssl_ctx, struct error **e)
{
	const char *ca_file = get_config_string (s->config, "tls_ca_file");
	const char *ca_path = get_config_string (s->config, "tls_ca_path");

	char *full_ca_file = ca_file
		? resolve_filename (ca_file, resolve_relative_config_filename) : NULL;
	char *full_ca_path = ca_path
		? resolve_filename (ca_path, resolve_relative_config_filename) : NULL;

	bool ok = false;
	if      (ca_file && !full_ca_file)
		error_set (e, "Couldn't find the CA bundle file");
	else if (ca_path && !full_ca_path)
		error_set (e, "Couldn't find the CA bundle path");
	else
		ok = transport_tls_init_ca_set (ssl_ctx, full_ca_file, full_ca_path, e);

	free (full_ca_file);
	free (full_ca_path);
	return ok;
}

static bool
transport_tls_init_ctx (struct server *s, SSL_CTX *ssl_ctx, struct error **e)
{
	bool verify = get_config_boolean (s->config, "tls_verify");
	SSL_CTX_set_verify (ssl_ctx, verify ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
		transport_tls_verify_callback);

	if (g_transport_tls_data_index == -1)
		g_transport_tls_data_index =
			SSL_CTX_get_ex_new_index (0, "server", NULL, NULL, NULL);
	SSL_CTX_set_ex_data (ssl_ctx, g_transport_tls_data_index, s);

	const char *ciphers = get_config_string (s->config, "tls_ciphers");
	if (ciphers && !SSL_CTX_set_cipher_list (ssl_ctx, ciphers))
		log_server_error (s, s->buffer,
			"Failed to select any cipher from the cipher list");
	SSL_CTX_set_mode (ssl_ctx,
		SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);

	// Disable deprecated protocols (see RFC 7568)
	SSL_CTX_set_options (ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

	// This seems to consume considerable amounts of memory while not giving
	// that much in return; in addition to that, I'm not sure about security
	// (see RFC 7525, section 3.3)
#ifdef SSL_OP_NO_COMPRESSION
	SSL_CTX_set_options (ssl_ctx, SSL_OP_NO_COMPRESSION);
#endif // SSL_OP_NO_COMPRESSION
#ifdef LOMEM
	SSL_CTX_set_mode (ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
#endif // LOMEM

	struct error *error = NULL;
	if (!transport_tls_init_ca (s, ssl_ctx, &error))
	{
		if (verify)
		{
			error_propagate (e, error);
			return false;
		}

		// Just inform the user if we're not actually verifying
		log_server_error (s, s->buffer, "#s", error->message);
		error_free (error);
	}
	return true;
}

static bool
transport_tls_init_cert (struct server *s, SSL *ssl, struct error **e)
{
	const char *tls_cert = get_config_string (s->config, "tls_cert");
	if (!tls_cert)
		return true;

	ERR_clear_error ();

	bool result = false;
	char *path = resolve_filename (tls_cert, resolve_relative_config_filename);
	if (!path)
		error_set (e, "%s: %s", "Cannot open file", tls_cert);
	// XXX: perhaps we should read the file ourselves for better messages
	else if (!SSL_use_certificate_file (ssl, path, SSL_FILETYPE_PEM)
		|| !SSL_use_PrivateKey_file (ssl, path, SSL_FILETYPE_PEM))
		error_set (e, "%s: %s", "Setting the TLS client certificate failed",
			xerr_describe_error ());
	else
		result = true;
	free (path);
	return result;
}

static bool
transport_tls_init (struct server *s, const char *hostname, struct error **e)
{
	ERR_clear_error ();

	struct error *error = NULL;
	SSL_CTX *ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
	if (!ssl_ctx)
		goto error_ssl_1;
	if (!transport_tls_init_ctx (s, ssl_ctx, &error))
		goto error_ssl_2;

	SSL *ssl = SSL_new (ssl_ctx);
	if (!ssl)
		goto error_ssl_2;

	if (!transport_tls_init_cert (s, ssl, &error))
	{
		// XXX: is this a reason to abort the connection?
		log_server_error (s, s->buffer, "#s", error->message);
		error_free (error);
		error = NULL;
	}

	SSL_set_connect_state (ssl);
	if (!SSL_set_fd (ssl, s->socket))
		goto error_ssl_3;

	// Enable SNI, FWIW; literal IP addresses aren't allowed
	struct in6_addr dummy;
	if (!inet_pton (AF_INET,  hostname, &dummy)
	 && !inet_pton (AF_INET6, hostname, &dummy))
		SSL_set_tlsext_host_name (ssl, hostname);

	struct transport_tls_data *data = xcalloc (1, sizeof *data);
	data->ssl_ctx = ssl_ctx;
	data->ssl = ssl;

	// Forces a handshake even if neither side wants to transmit data
	data->ssl_rx_want_tx = true;

	s->transport_data = data;
	return true;

error_ssl_3:
	SSL_free (ssl);
error_ssl_2:
	SSL_CTX_free (ssl_ctx);
error_ssl_1:
	if (!error)
		error_set (&error, "%s: %s", "Could not initialize TLS",
			xerr_describe_error ());

	error_propagate (e, error);
	return false;
}

static void
transport_tls_cleanup (struct server *s)
{
	struct transport_tls_data *data = s->transport_data;
	if (data->ssl)
		SSL_free (data->ssl);
	if (data->ssl_ctx)
		SSL_CTX_free (data->ssl_ctx);
	free (data);
}

static enum socket_io_result
transport_tls_try_read (struct server *s)
{
	struct transport_tls_data *data = s->transport_data;
	if (data->ssl_tx_want_rx)
		return SOCKET_IO_OK;

	struct str *buf = &s->read_buffer;
	data->ssl_rx_want_tx = false;
	while (true)
	{
		ERR_clear_error ();
		str_reserve (buf, 512);
		int n_read = SSL_read (data->ssl, buf->str + buf->len,
			buf->alloc - buf->len - 1 /* null byte */);

		const char *error_info = NULL;
		switch (xssl_get_error (data->ssl, n_read, &error_info))
		{
		case SSL_ERROR_NONE:
			buf->str[buf->len += n_read] = '\0';
			continue;
		case SSL_ERROR_ZERO_RETURN:
			return SOCKET_IO_EOF;
		case SSL_ERROR_WANT_READ:
			return SOCKET_IO_OK;
		case SSL_ERROR_WANT_WRITE:
			data->ssl_rx_want_tx = true;
			return SOCKET_IO_OK;
		case XSSL_ERROR_TRY_AGAIN:
			continue;
		default:
			LOG_FUNC_FAILURE ("SSL_read", error_info);
			return SOCKET_IO_ERROR;
		}
	}
}

static enum socket_io_result
transport_tls_try_write (struct server *s)
{
	struct transport_tls_data *data = s->transport_data;
	if (data->ssl_rx_want_tx)
		return SOCKET_IO_OK;

	struct str *buf = &s->write_buffer;
	data->ssl_tx_want_rx = false;
	while (buf->len)
	{
		ERR_clear_error ();
		int n_written = SSL_write (data->ssl, buf->str, buf->len);

		const char *error_info = NULL;
		switch (xssl_get_error (data->ssl, n_written, &error_info))
		{
		case SSL_ERROR_NONE:
			str_remove_slice (buf, 0, n_written);
			continue;
		case SSL_ERROR_ZERO_RETURN:
			return SOCKET_IO_EOF;
		case SSL_ERROR_WANT_WRITE:
			return SOCKET_IO_OK;
		case SSL_ERROR_WANT_READ:
			data->ssl_tx_want_rx = true;
			return SOCKET_IO_OK;
		case XSSL_ERROR_TRY_AGAIN:
			continue;
		default:
			LOG_FUNC_FAILURE ("SSL_write", error_info);
			return SOCKET_IO_ERROR;
		}
	}
	return SOCKET_IO_OK;
}

static int
transport_tls_get_poll_events (struct server *s)
{
	struct transport_tls_data *data = s->transport_data;

	int events = POLLIN;
	if (s->write_buffer.len || data->ssl_rx_want_tx)
		events |= POLLOUT;

	// While we're waiting for an opposite event, we ignore the original
	if (data->ssl_rx_want_tx)  events &= ~POLLIN;
	if (data->ssl_tx_want_rx)  events &= ~POLLOUT;
	return events;
}

static void
transport_tls_in_before_shutdown (struct server *s)
{
	struct transport_tls_data *data = s->transport_data;
	(void) SSL_shutdown (data->ssl);
}

static struct transport g_transport_tls =
{
	.init               = transport_tls_init,
	.cleanup            = transport_tls_cleanup,
	.try_read           = transport_tls_try_read,
	.try_write          = transport_tls_try_write,
	.get_poll_events    = transport_tls_get_poll_events,
	.in_before_shutdown = transport_tls_in_before_shutdown,
};

// --- Connection establishment ------------------------------------------------

static bool
irc_autofill_user_info (struct server *s, struct error **e)
{
	const char *nicks    = get_config_string (s->config, "nicks");
	const char *username = get_config_string (s->config, "username");
	const char *realname = get_config_string (s->config, "realname");

	if (nicks && *nicks && username && *username && realname)
		return true;

	// Read POSIX user info and fill the configuration if needed
	errno = 0;
	struct passwd *pwd = getpwuid (geteuid ());
	if (!pwd)
	{
		return error_set (e,
			"cannot retrieve user information: %s", strerror (errno));
	}

	// FIXME: set_config_strings() writes errors on its own
	if (!nicks    || !*nicks)
		set_config_string (s->config, "nicks",    pwd->pw_name);
	if (!username || !*username)
		set_config_string (s->config, "username", pwd->pw_name);

	// Not all systems have the GECOS field but the vast majority does
	if (!realname)
	{
		char *gecos = pwd->pw_gecos;

		// The first comma, if any, ends the user's real name
		char *comma = strchr (gecos, ',');
		if (comma)
			*comma = '\0';

		set_config_string (s->config, "realname", gecos);
	}

	return true;
}

static char *
irc_fetch_next_nickname (struct server *s)
{
	struct strv v = strv_make ();
	cstr_split (get_config_string (s->config, "nicks"), ",", true, &v);

	char *result = NULL;
	if (s->nick_counter >= 0 && (size_t) s->nick_counter < v.len)
		result = xstrdup (v.vector[s->nick_counter++]);
	if ((size_t) s->nick_counter >= v.len)
		// Exhausted all nicknames
		s->nick_counter = -1;

	strv_free (&v);
	return result;
}

static void
irc_register (struct server *s)
{
	// Fill in user information automatically if needed
	irc_autofill_user_info (s, NULL);

	const char *username = get_config_string (s->config, "username");
	const char *realname = get_config_string (s->config, "realname");
	hard_assert (username && realname);

	// Start IRCv3 capability negotiation, with up to 3.2 features;
	// at worst the server will ignore this or send a harmless error message
	irc_send (s, "CAP LS 302");

	const char *password = get_config_string (s->config, "password");
	if (password)
		irc_send (s, "PASS :%s", password);

	s->nick_counter = 0;

	char *nickname = irc_fetch_next_nickname (s);
	if (nickname)
		irc_send (s, "NICK :%s", nickname);
	else
		log_server_error (s, s->buffer, "No nicks present in configuration");
	free (nickname);

	// IRC servers may ignore the last argument if it's empty
	irc_send (s, "USER %s 8 * :%s", username, *realname ? realname : " ");
}

static void
irc_finish_connection (struct server *s, int socket, const char *hostname)
{
	struct app_context *ctx = s->ctx;

	// Most of our output comes from the user one full command at a time and we
	// use output buffering, so it makes a lot of sense to avoid these delays
	int yes = 1;
	soft_assert (setsockopt (socket, IPPROTO_TCP, TCP_NODELAY,
		&yes, sizeof yes) != -1);

	set_blocking (socket, false);
	s->socket = socket;
	s->transport = get_config_boolean (s->config, "tls")
		? &g_transport_tls
		: &g_transport_plain;

	struct error *e = NULL;
	if (s->transport->init && !s->transport->init (s, hostname, &e))
	{
		log_server_error (s, s->buffer, "Connection failed: #s", e->message);
		error_free (e);

		xclose (s->socket);
		s->socket = -1;

		s->transport = NULL;
		return;
	}

	log_server_status (s, s->buffer, "Connection established");
	irc_set_state (s, IRC_CONNECTED);

	s->socket_event = poller_fd_make (&ctx->poller, s->socket);
	s->socket_event.dispatcher = (poller_fd_fn) on_irc_ready;
	s->socket_event.user_data = s;

	irc_update_poller (s, NULL);
	irc_reset_connection_timeouts (s);
	irc_register (s);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
irc_on_connector_connecting (void *user_data, const char *address)
{
	struct server *s = user_data;
	log_server_status (s, s->buffer, "Connecting to #s...", address);
}

static void
irc_on_connector_error (void *user_data, const char *error)
{
	struct server *s = user_data;
	log_server_error (s, s->buffer, "Connection failed: #s", error);
}

static void
irc_on_connector_failure (void *user_data)
{
	struct server *s = user_data;
	irc_destroy_connector (s);
	irc_queue_reconnect (s);
}

static void
irc_on_connector_connected (void *user_data, int socket, const char *hostname)
{
	struct server *s = user_data;
	char *hostname_copy = xstrdup (hostname);
	irc_destroy_connector (s);
	irc_finish_connection (s, socket, hostname_copy);
	free (hostname_copy);
}

static void
irc_setup_connector (struct server *s, const struct strv *addresses)
{
	struct connector *connector = xmalloc (sizeof *connector);
	connector_init (connector, &s->ctx->poller);
	s->connector = connector;

	connector->user_data     = s;
	connector->on_connecting = irc_on_connector_connecting;
	connector->on_error      = irc_on_connector_error;
	connector->on_connected  = irc_on_connector_connected;
	connector->on_failure    = irc_on_connector_failure;

	for (size_t i = 0; i < addresses->len; i++)
	{
		const char *port = "6667",
			*host = tokenize_host_port (addresses->vector[i], &port);
		connector_add_target (connector, host, port);
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// TODO: see if we can further merge code for the two connectors, for example
//   by making SOCKS 4A and 5 mere plugins for the connector, or by using
//   a virtual interface common to them both (seems more likely)

static void
irc_on_socks_connecting (void *user_data,
	const char *address, const char *via, const char *version)
{
	struct server *s = user_data;
	log_server_status (s, s->buffer,
		"Connecting to #s via #s (#s)...", address, via, version);
}

static bool
irc_setup_connector_socks (struct server *s, const struct strv *addresses,
	struct error **e)
{
	const char *socks_host = get_config_string (s->config, "socks_host");
	int64_t socks_port_int = get_config_integer (s->config, "socks_port");

	if (!socks_host)
		return false;

	struct socks_connector *connector = xmalloc (sizeof *connector);
	socks_connector_init (connector, &s->ctx->poller);
	s->socks_conn = connector;

	connector->user_data     = s;
	connector->on_connecting = irc_on_socks_connecting;
	connector->on_error      = irc_on_connector_error;
	connector->on_connected  = irc_on_connector_connected;
	connector->on_failure    = irc_on_connector_failure;

	for (size_t i = 0; i < addresses->len; i++)
	{
		const char *port = "6667",
			*host = tokenize_host_port (addresses->vector[i], &port);
		if (!socks_connector_add_target (connector, host, port, e))
			return false;
	}

	char *service = xstrdup_printf ("%" PRIi64, socks_port_int);
	socks_connector_run (connector, socks_host, service,
		get_config_string (s->config, "socks_username"),
		get_config_string (s->config, "socks_password"));
	free (service);

	// The SOCKS connector can have already failed; we mustn't return true then
	if (!s->socks_conn)
		return error_set (e, "SOCKS connection failed");
	return true;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
irc_initiate_connect (struct server *s)
{
	hard_assert (s->state == IRC_DISCONNECTED);

	const char *addresses = get_config_string (s->config, "addresses");
	if (!addresses || !addresses[strspn (addresses, ",")])
	{
		// No sense in trying to reconnect
		log_server_error (s, s->buffer,
			"No addresses specified in configuration");
		return;
	}

	struct strv servers = strv_make ();
	cstr_split (addresses, ",", true, &servers);

	struct error *e = NULL;
	if (!irc_setup_connector_socks (s, &servers, &e) && !e)
		irc_setup_connector (s, &servers);

	strv_free (&servers);

	if (e)
	{
		irc_destroy_connector (s);

		log_server_error (s, s->buffer, "#s", e->message);
		error_free (e);
		irc_queue_reconnect (s);
	}
	else if (s->state != IRC_CONNECTED)
		irc_set_state (s, IRC_CONNECTING);
}

// --- Input prompt ------------------------------------------------------------

static void
make_unseen_prefix (struct app_context *ctx, struct str *active_buffers)
{
	size_t buffer_no = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
	{
		buffer_no++;
		if (!(iter->new_messages_count - iter->new_unimportant_count)
		 || iter == ctx->current_buffer)
			continue;

		if (active_buffers->len)
			str_append_c (active_buffers, ',');
		if (iter->highlighted)
			str_append_c (active_buffers, '!');
		str_append_printf (active_buffers, "%zu", buffer_no);
	}
}

static void
make_chanmode_postfix (struct channel *channel, struct str *modes)
{
	if (channel->no_param_modes.len)
		str_append (modes, channel->no_param_modes.str);

	struct str_map_iter iter = str_map_iter_make (&channel->param_modes);
	const char *param;
	while ((param = str_map_iter_next (&iter)))
		str_append_c (modes, iter.link->key[0]);
}

static void
make_server_postfix_registered (struct buffer *buffer, struct str *output)
{
	struct server *s = buffer->server;
	if (buffer->type == BUFFER_CHANNEL)
	{
		struct channel_user *channel_user =
			irc_channel_get_user (buffer->channel, s->irc_user);
		if (channel_user)
			irc_get_channel_user_prefix (s, channel_user, output);
	}
	str_append (output, s->irc_user->nickname);
	if (s->irc_user_modes.len)
		str_append_printf (output, "(%s)", s->irc_user_modes.str);
}

static void
make_server_postfix (struct buffer *buffer, struct str *output)
{
	struct server *s = buffer->server;
	str_append_c (output, ' ');
	if (!irc_is_connected (s))
		str_append (output, "(disconnected)");
	else if (s->state != IRC_REGISTERED)
		str_append (output, "(unregistered)");
	else
		make_server_postfix_registered (buffer, output);
}

static void
make_prompt (struct app_context *ctx, struct str *output)
{
	LIST_FOR_EACH (struct hook, iter, ctx->prompt_hooks)
	{
		struct prompt_hook *hook = (struct prompt_hook *) iter;
		char *made = hook->make (hook);
		if (made)
		{
			str_append (output, made);
			free (made);
			return;
		}
	}

	struct buffer *buffer = ctx->current_buffer;
	if (!buffer)
		return;

	str_append_c (output, '[');

	struct str active_buffers = str_make ();
	make_unseen_prefix (ctx, &active_buffers);
	if (active_buffers.len)
		str_append_printf (output, "(%s) ", active_buffers.str);
	str_free (&active_buffers);

	str_append_printf (output, "%d:%s",
		buffer_get_index (ctx, buffer), buffer->name);
	// We remember old modes, don't show them while we're not on the channel
	if (buffer->type == BUFFER_CHANNEL
	 && irc_channel_is_joined (buffer->channel))
	{
		struct str modes = str_make ();
		make_chanmode_postfix (buffer->channel, &modes);
		if (modes.len)
			str_append_printf (output, "(+%s)", modes.str);
		str_free (&modes);

		str_append_printf (output, "{%zu}", buffer->channel->users_len);
	}
	if (buffer->hide_unimportant)
		str_append (output, "<H>");

	if (buffer != ctx->global_buffer)
		make_server_postfix (buffer, output);

	str_append_c (output, ']');
	str_append_c (output, ' ');
}

static void
input_maybe_set_prompt (struct input *self, char *new_prompt)
{
	// Fix libedit's expectations to see a non-control character following
	// the end mark (see prompt.c and literal.c) by cleaning this up
	for (char *p = new_prompt; *p; )
		if (p[0] == INPUT_END_IGNORE && p[1] == INPUT_START_IGNORE)
			memmove (p, p + 2, strlen (p + 2) + 1);
		else
			p++;

	// Redisplay can be an expensive operation
	const char *prompt = CALL (self, get_prompt);
	if (prompt && !strcmp (new_prompt, prompt))
		free (new_prompt);
	else
		CALL_ (self, set_prompt, new_prompt);
}

static void
on_refresh_prompt (struct app_context *ctx)
{
	poller_idle_reset (&ctx->prompt_event);
	bool have_attributes = !!get_attribute_printer (stdout);

	struct str prompt = str_make ();
	make_prompt (ctx, &prompt);

	// libedit has a weird bug where it misapplies ignores when they're not
	// followed by anything else, so let's try to move a trailing space,
	// which will at least fix the default prompt.
	const char *attributed_suffix = "";
#ifdef HAVE_EDITLINE
	if (have_attributes && prompt.len && prompt.str[prompt.len - 1] == ' ')
	{
		prompt.str[--prompt.len] = 0;
		attributed_suffix = " ";
	}

	// Also enable a uniform interface for prompt hooks by assuming it uses
	// GNU Readline escapes: turn this into libedit's almost-flip-flop
	for (size_t i = 0; i < prompt.len; i++)
		if (prompt.str[i] == '\x01' || prompt.str[i] == '\x02')
			prompt.str[i] = INPUT_START_IGNORE /* == INPUT_END_IGNORE */;
#endif // HAVE_EDITLINE

	char *localized = iconv_xstrdup (ctx->term_from_utf8, prompt.str, -1, NULL);
	str_free (&prompt);

	// XXX: to be completely correct, we should use tputs, but we cannot
	if (have_attributes)
	{
		char buf[16384] = "";
		FILE *memfp = fmemopen (buf, sizeof buf - 1, "wb");
		struct attr_printer state = { ctx->theme, memfp, false };

		fputc (INPUT_START_IGNORE, memfp);
		attr_printer_apply_named (&state, ATTR_PROMPT);
		fputc (INPUT_END_IGNORE, memfp);

		fputs (localized, memfp);
		free (localized);

		fputc (INPUT_START_IGNORE, memfp);
		attr_printer_reset (&state);
		fputc (INPUT_END_IGNORE, memfp);

		fputs (attributed_suffix, memfp);

		fclose (memfp);
		input_maybe_set_prompt (ctx->input, xstrdup (buf));
	}
	else
		input_maybe_set_prompt (ctx->input, localized);
}

// --- Helpers -----------------------------------------------------------------

static struct buffer *
irc_get_buffer_for_message (struct server *s,
	const struct irc_message *msg, const char *target)
{
	// TODO: display such messages differently
	target = irc_skip_statusmsg (s, target);

	struct buffer *buffer = str_map_find (&s->irc_buffer_map, target);
	if (irc_is_channel (s, target))
	{
		struct channel *channel = str_map_find (&s->irc_channels, target);
		hard_assert (channel || !buffer);

		// This is weird
		if (!channel)
			return NULL;
	}
	else if (!buffer)
	{
		// Outgoing messages needn't have a prefix, no buffer associated
		if (!msg->prefix)
			return NULL;

		// Don't make user buffers for servers (they can send NOTICEs)
		if (!irc_find_userhost (msg->prefix))
			return s->buffer;

		char *nickname = irc_cut_nickname (msg->prefix);
		if (irc_is_this_us (s, target))
			buffer = irc_get_or_make_user_buffer (s, nickname);
		free (nickname);

		// With the IRCv3.2 echo-message capability, we can receive messages
		// as they are delivered to the target; in that case we return NULL
		// and the caller should check the origin
	}
	return buffer;
}

static bool
irc_is_highlight (struct server *s, const char *message)
{
	// This may be called by notices before even successfully registering
	if (!s->irc_user)
		return false;

	// Strip formatting from the message so that it doesn't interfere
	// with nickname detection (colour sequences in particular)
	struct formatter f = formatter_make (s->ctx, NULL);
	formatter_parse_message (&f, message);

	struct str stripped = str_make ();
	for (size_t i = 0; i < f.items_len; i++)
	{
		if (f.items[i].type == FORMATTER_ITEM_TEXT)
			str_append (&stripped, f.items[i].text);
	}
	formatter_free (&f);

	// Well, this is rather crude but it should make most users happy.
	// We could do this in proper Unicode but that's two more conversions per
	// message when both the nickname and the message are likely valid UTF-8.
	char *copy = str_steal (&stripped);
	cstr_transform (copy, s->irc_tolower);

	char *nick = xstrdup (s->irc_user->nickname);
	cstr_transform (nick, s->irc_tolower);

	// Special characters allowed in nicknames by RFC 2812: []\`_^{|} and -
	// Also excluded from the ASCII: common user channel prefixes: +%@&~
	// XXX: why did I exclude those?  It won't match when IRC newbies use them.
	const char *delimiters = ",.;:!?()<>/=#$* \t\r\n\v\f\"'";

	bool result = false;
	char *save = NULL;
	for (char *token = strtok_r (copy, delimiters, &save);
		token; token = strtok_r (NULL, delimiters, &save))
		if (!strcmp (token, nick))
		{
			result = true;
			break;
		}

	free (copy);
	free (nick);
	return result;
}

static char *
irc_get_privmsg_prefix (struct server *s, struct user *user, const char *target)
{
	struct str prefix = str_make ();
	if (user && irc_is_channel (s, (target = irc_skip_statusmsg (s, target))))
	{
		struct channel *channel;
		struct channel_user *channel_user;
		if ((channel = str_map_find (&s->irc_channels, target))
		 && (channel_user = irc_channel_get_user (channel, user)))
			irc_get_channel_user_prefix (s, channel_user, &prefix);
	}
	return str_steal (&prefix);
}

// --- Mode processor ----------------------------------------------------------

struct mode_processor
{
	char **params;                      ///< Mode string parameters
	bool adding;                        ///< Currently adding modes
	char mode_char;                     ///< Currently processed mode char

	// User data:

	struct server *s;                   ///< Server
	struct channel *channel;            ///< The channel being modified
	unsigned changes;                   ///< Count of all changes
	unsigned usermode_changes;          ///< Count of all usermode changes
};

/// Process a single mode character
typedef bool (*mode_processor_apply_fn) (struct mode_processor *);

static const char *
mode_processor_next_param (struct mode_processor *self)
{
	if (!*self->params)
		return NULL;
	return *self->params++;
}

static void
mode_processor_run (struct mode_processor *self,
	char **params, mode_processor_apply_fn apply_cb)
{
	self->params = params;

	const char *mode_string;
	while ((mode_string = mode_processor_next_param (self)))
	{
		self->adding = true;
		while ((self->mode_char = *mode_string++))
		{
			if      (self->mode_char == '+') self->adding = true;
			else if (self->mode_char == '-') self->adding = false;
			else if (!apply_cb (self))
				break;
		}
	}
}

static int
mode_char_cmp (const void *a, const void *b)
{
	return *(const char *) a - *(const char *) b;
}

/// Add/remove the current mode character to/from the given ordered list
static void
mode_processor_toggle (struct mode_processor *self, struct str *modes)
{
	const char *pos = strchr (modes->str, self->mode_char);
	if (self->adding == !!pos)
		return;

	if (self->adding)
	{
		str_append_c (modes, self->mode_char);
		qsort (modes->str, modes->len, 1, mode_char_cmp);
	}
	else
		str_remove_slice (modes, pos - modes->str, 1);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
mode_processor_do_user (struct mode_processor *self)
{
	const char *nickname;
	struct user *user;
	struct channel_user *channel_user;
	if (!(nickname = mode_processor_next_param (self))
	 || !(user = str_map_find (&self->s->irc_users, nickname))
	 || !(channel_user = irc_channel_get_user (self->channel, user)))
		return;

	// Translate mode character to user prefix character
	const char *all_prefixes = self->s->irc_chanuser_prefixes;
	const char *all_modes    = self->s->irc_chanuser_modes;

	const char *mode = strchr (all_modes, self->mode_char);
	hard_assert (mode && (size_t) (mode - all_modes) < strlen (all_prefixes));
	char prefix = all_prefixes[mode - all_modes];

	char **prefixes = &channel_user->prefixes;
	char *pos = strchr (*prefixes, prefix);
	if (self->adding == !!pos)
		return;

	if (self->adding)
	{
		// Add the new mode prefix while retaining the right order
		struct str buf = str_make ();
		for (const char *p = all_prefixes; *p; p++)
			if (*p == prefix || strchr (*prefixes, *p))
				str_append_c (&buf, *p);
		cstr_set (prefixes, str_steal (&buf));
	}
	else
		memmove (pos, pos + 1, strlen (pos));
}

static void
mode_processor_do_param_always (struct mode_processor *self)
{
	const char *param = NULL;
	if (!(param = mode_processor_next_param (self)))
		return;

	char key[2] = { self->mode_char, 0 };
	str_map_set (&self->channel->param_modes, key,
		self->adding ? xstrdup (param) : NULL);
}

static void
mode_processor_do_param_when_set (struct mode_processor *self)
{
	const char *param = NULL;
	if (self->adding && !(param = mode_processor_next_param (self)))
		return;

	char key[2] = { self->mode_char, 0 };
	str_map_set (&self->channel->param_modes, key,
		self->adding ? xstrdup (param) : NULL);
}

static bool
mode_processor_apply_channel (struct mode_processor *self)
{
	self->changes++;
	if      (strchr (self->s->irc_chanuser_modes,           self->mode_char))
	{
		self->usermode_changes++;
		mode_processor_do_user (self);
	}
	else if (strchr (self->s->irc_chanmodes_list,           self->mode_char))
		// Nothing to do here, just skip the next argument if there's any
		(void) mode_processor_next_param (self);
	else if (strchr (self->s->irc_chanmodes_param_always,   self->mode_char))
		mode_processor_do_param_always (self);
	else if (strchr (self->s->irc_chanmodes_param_when_set, self->mode_char))
		mode_processor_do_param_when_set (self);
	else if (strchr (self->s->irc_chanmodes_param_never,    self->mode_char))
		mode_processor_toggle (self, &self->channel->no_param_modes);
	else
		// It's not safe to continue, results could be undesired
		return false;
	return true;
}

/// Returns whether the change has only affected channel user modes
static bool
irc_handle_mode_channel (struct channel *channel, char **params)
{
	struct mode_processor p = { .s = channel->s, .channel = channel };
	mode_processor_run (&p, params, mode_processor_apply_channel);
	if (p.changes == p.usermode_changes)
		return true;

	irc_channel_broadcast_buffer_update (channel);
	return false;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool
mode_processor_apply_user (struct mode_processor *self)
{
	mode_processor_toggle (self, &self->s->irc_user_modes);
	return true;
}

static void
irc_handle_mode_user (struct server *s, char **params)
{
	struct mode_processor p = { .s = s };
	mode_processor_run (&p, params, mode_processor_apply_user);

	relay_prepare_server_update (s->ctx, s);
	relay_broadcast (s->ctx);
}

// --- Output processing -------------------------------------------------------

// Both user and plugins can send whatever the heck they want to,
// we need to parse it back so that it's evident what's happening

static void
irc_handle_sent_cap (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 1)
		return;

	const char *subcommand = msg->params.vector[0];
	const char *args = (msg->params.len > 1) ? msg->params.vector[1] : "";
	if (!strcasecmp_ascii (subcommand, "REQ"))
		log_server_status (s, s->buffer,
			"#s: #S", "Capabilities requested", args);
}

static void
irc_handle_sent_join (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 1)
		return;

	if (strcmp (msg->params.vector[0], "0"))
		cstr_split (msg->params.vector[0], ",", true, &s->outstanding_joins);
}

static void
irc_handle_sent_notice_text (struct server *s,
	const struct irc_message *msg, struct str *text)
{
	const char *target = msg->params.vector[0];
	struct buffer *buffer = irc_get_buffer_for_message (s, msg, target);
	if (buffer && soft_assert (s->irc_user))
		log_outcoming_notice (s, buffer, s->irc_user->nickname, text->str);
	else
		log_outcoming_orphan_notice (s, target, text->str);
}

static void
irc_handle_sent_notice (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2 || s->cap_echo_message)
		return;

	// This ignores empty messages which we should not normally send
	struct ctcp_chunk *chunks = ctcp_parse (msg->params.vector[1]);
	LIST_FOR_EACH (struct ctcp_chunk, iter, chunks)
	{
		if (iter->is_extended)
			log_ctcp_reply (s, msg->params.vector[0],
				xstrdup_printf ("%s %s", iter->tag.str, iter->text.str));
		else
			irc_handle_sent_notice_text (s, msg, &iter->text);
	}
	ctcp_destroy (chunks);
}

static void
irc_handle_sent_privmsg_text (struct server *s,
	const struct irc_message *msg, struct str *text, bool is_action)
{
	const char *target = msg->params.vector[0];
	struct buffer *buffer = irc_get_buffer_for_message (s, msg, target);
	if (buffer && soft_assert (s->irc_user))
	{
		char *prefixes = irc_get_privmsg_prefix (s, s->irc_user, target);
		if (is_action)
			log_outcoming_action (s, buffer, s->irc_user->nickname, text->str);
		else
			log_outcoming_privmsg (s, buffer,
				prefixes, s->irc_user->nickname, text->str);
		free (prefixes);
	}
	else if (is_action)
		log_outcoming_orphan_action (s, target, text->str);
	else
		log_outcoming_orphan_privmsg (s, target, text->str);
}

static void
irc_handle_sent_privmsg (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2 || s->cap_echo_message)
		return;

	// This ignores empty messages which we should not normally send
	// and the server is likely going to reject with an error reply anyway
	struct ctcp_chunk *chunks = ctcp_parse (msg->params.vector[1]);
	LIST_FOR_EACH (struct ctcp_chunk, iter, chunks)
	{
		if (!iter->is_extended)
			irc_handle_sent_privmsg_text (s, msg, &iter->text, false);
		else if (!strcmp (iter->tag.str, "ACTION"))
			irc_handle_sent_privmsg_text (s, msg, &iter->text, true);
		else
			log_ctcp_query (s, msg->params.vector[0], iter->tag.str);
	}
	ctcp_destroy (chunks);
}

static struct irc_handler
{
	const char *name;
	void (*handler) (struct server *s, const struct irc_message *msg);
}
g_irc_sent_handlers[] =
{
	// This list needs to stay sorted
	{ "CAP",     irc_handle_sent_cap     },
	{ "JOIN",    irc_handle_sent_join    },
	{ "NOTICE",  irc_handle_sent_notice  },
	{ "PRIVMSG", irc_handle_sent_privmsg },
};

static int
irc_handler_cmp_by_name (const void *a, const void *b)
{
	const struct irc_handler *first  = a;
	const struct irc_handler *second = b;
	return strcasecmp_ascii (first->name, second->name);
}

static void
irc_process_sent_message (const struct irc_message *msg, struct server *s)
{
	// The server is free to reject even a matching prefix
	// XXX: even though no prefix should normally be present, this is racy
	if (msg->prefix && !irc_is_this_us (s, msg->prefix))
		return;

	struct irc_handler key = { .name = msg->command };
	struct irc_handler *handler = bsearch (&key, g_irc_sent_handlers,
		N_ELEMENTS (g_irc_sent_handlers), sizeof key, irc_handler_cmp_by_name);
	if (handler)
		handler->handler (s, msg);
}

// --- Input handling ----------------------------------------------------------

static void
irc_handle_authenticate (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 1)
		return;

	// Empty challenge -> empty response for e.g. SASL EXTERNAL,
	// abort anything else as it doesn't make much sense to let the user do it
	if (!strcmp (msg->params.vector[0], "+"))
		irc_send (s, "AUTHENTICATE +");
	else
		irc_send (s, "AUTHENTICATE *");
}

static void
irc_handle_away (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix)
		return;

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&s->irc_users, nickname);
	free (nickname);

	// Let's allow the server to make us away
	if (user)
		user->away = !!msg->params.len;
}

static void
irc_process_cap_ls (struct server *s)
{
	log_server_status (s, s->buffer,
		"#s: #&S", "Capabilities supported", strv_join (&s->cap_ls_buf, " "));

	struct strv chosen = strv_make ();
	struct strv use    = strv_make ();

	cstr_split (get_config_string (s->config, "capabilities"), ",", true, &use);

	// Filter server capabilities for ones we can make use of
	for (size_t i = 0; i < s->cap_ls_buf.len; i++)
	{
		const char *cap = s->cap_ls_buf.vector[i];
		size_t cap_name_len = strcspn (cap, "=");
		for (size_t k = 0; k < use.len; k++)
			if (!strncasecmp_ascii (use.vector[k], cap, cap_name_len))
				strv_append_owned (&chosen, xstrndup (cap, cap_name_len));
	}
	strv_reset (&s->cap_ls_buf);

	char *chosen_str = strv_join (&chosen, " ");
	strv_free (&chosen);
	strv_free (&use);

	// XXX: with IRCv3.2, this may end up being too long for one message,
	// and we need to be careful with CAP END.  One probably has to count
	// the number of sent CAP REQ vs the number of received CAP ACK/NAK.
	if (s->state == IRC_CONNECTED)
		irc_send (s, "CAP REQ :%s", chosen_str);

	free (chosen_str);
}

static void
irc_toggle_cap (struct server *s, const char *cap, bool active)
{
	if (!strcasecmp_ascii (cap, "echo-message")) s->cap_echo_message = active;
	if (!strcasecmp_ascii (cap, "away-notify"))  s->cap_away_notify  = active;
	if (!strcasecmp_ascii (cap, "sasl"))         s->cap_sasl         = active;
}

static void
irc_try_finish_cap_negotiation (struct server *s)
{
	// It does not make sense to do this post-registration, although it would
	// not hurt either, as the server must ignore it in that case
	if (s->state == IRC_CONNECTED)
		irc_send (s, "CAP END");
}

static void
irc_handle_cap (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	struct strv v = strv_make ();
	const char *args = "";
	if (msg->params.len > 2)
		cstr_split ((args = msg->params.vector[2]), " ", true, &v);

	const char *subcommand = msg->params.vector[1];
	if (!strcasecmp_ascii (subcommand, "ACK"))
	{
		log_server_status (s, s->buffer,
			"#s: #S", "Capabilities acknowledged", args);
		for (size_t i = 0; i < v.len; i++)
		{
			const char *cap = v.vector[i];
			bool active = true;
			if (*cap == '-')
			{
				active = false;
				cap++;
			}
			irc_toggle_cap (s, cap, active);
		}
		if (s->cap_sasl && s->transport == &g_transport_tls)
			irc_send (s, "AUTHENTICATE EXTERNAL");
		else
			irc_try_finish_cap_negotiation (s);
	}
	else if (!strcasecmp_ascii (subcommand, "NAK"))
	{
		log_server_error (s, s->buffer,
			"#s: #S", "Capabilities not acknowledged", args);
		irc_try_finish_cap_negotiation (s);
	}
	else if (!strcasecmp_ascii (subcommand, "DEL"))
	{
		log_server_error (s, s->buffer,
			"#s: #S", "Capabilities deleted", args);
		for (size_t i = 0; i < v.len; i++)
			irc_toggle_cap (s, v.vector[i], false);
	}
	else if (!strcasecmp_ascii (subcommand, "LS"))
	{

		if (msg->params.len > 3 && !strcmp (args, "*"))
			cstr_split (msg->params.vector[3], " ", true, &s->cap_ls_buf);
		else
		{
			strv_append_vector (&s->cap_ls_buf, v.vector);
			irc_process_cap_ls (s);
		}
	}

	strv_free (&v);
}

static void
irc_handle_chghost (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&s->irc_users, nickname);
	free (nickname);
	if (!user)
		return;

	char *new_prefix = xstrdup_printf ("%s!%s@%s", user->nickname,
		msg->params.vector[0], msg->params.vector[1]);

	if (irc_is_this_us (s, msg->prefix))
	{
		cstr_set (&s->irc_user_host, xstrdup_printf ("%s@%s",
			msg->params.vector[0], msg->params.vector[1]));

		log_chghost_self (s, s->buffer, new_prefix);

		// Log a message in all open buffers on this server
		struct str_map_iter iter = str_map_iter_make (&s->irc_buffer_map);
		struct buffer *buffer;
		while ((buffer = str_map_iter_next (&iter)))
			log_chghost_self (s, buffer, new_prefix);
	}
	else
	{
		// Log a message in any PM buffer
		struct buffer *buffer =
			str_map_find (&s->irc_buffer_map, user->nickname);
		if (buffer)
			log_chghost (s, buffer, msg->prefix, new_prefix);

		// Log a message in all channels the user is in
		LIST_FOR_EACH (struct user_channel, iter, user->channels)
		{
			buffer = str_map_find (&s->irc_buffer_map, iter->channel->name);
			hard_assert (buffer != NULL);
			log_chghost (s, buffer, msg->prefix, new_prefix);
		}
	}

	free (new_prefix);
}

static void
irc_handle_error (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 1)
		return;

	log_server_error (s, s->buffer, "#m", msg->params.vector[0]);
}

static void
irc_handle_invite (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	const char *target       = msg->params.vector[0];
	const char *channel_name = msg->params.vector[1];

	struct buffer *buffer;
	if (!(buffer = str_map_find (&s->irc_buffer_map, channel_name)))
		buffer = s->buffer;

	// IRCv3.2 invite-notify extension allows the target to be someone else
	if (irc_is_this_us (s, target))
		log_server_status (s, buffer,
			"#n has invited you to #S", msg->prefix, channel_name);
	else
		log_server_status (s, buffer,
			"#n has invited #n to #S", msg->prefix, target, channel_name);
}

static bool
irc_satisfy_join (struct server *s, const char *target)
{
	// This queue could use some garbage collection,
	// but it's unlikely to pose problems.
	for (size_t i = 0; i < s->outstanding_joins.len; i++)
		if (!irc_server_strcmp (s, target, s->outstanding_joins.vector[i]))
		{
			strv_remove (&s->outstanding_joins, i);
			return true;
		}
	return false;
}

static void
irc_handle_join (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	// TODO: RFC 2812 doesn't guarantee that the argument isn't a target list.
	const char *channel_name = msg->params.vector[0];
	if (!irc_is_channel (s, channel_name))
		return;

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	// We've joined a new channel
	if (!channel)
	{
		// This is weird, ignoring
		if (!irc_is_this_us (s, msg->prefix))
			return;

		buffer = buffer_new (s->ctx->input,
			BUFFER_CHANNEL, irc_make_buffer_name (s, channel_name));
		buffer->server = s;
		buffer->channel = channel =
			irc_make_channel (s, xstrdup (channel_name));
		str_map_set (&s->irc_buffer_map, channel->name, buffer);

		buffer_add (s->ctx, buffer);

		char *input = CALL_ (s->ctx->input, get_line, NULL);
		if (irc_satisfy_join (s, channel_name) && !*input)
			buffer_activate (s->ctx, buffer);
		else
			buffer->highlighted = true;
		free (input);
	}

	if (irc_is_this_us (s, msg->prefix))
	{
		// Reset the field so that we rejoin the channel after reconnecting
		channel->left_manually = false;

		// Request the channel mode as we don't get it automatically
		str_reset (&channel->no_param_modes);
		str_map_clear (&channel->param_modes);
		irc_send (s, "MODE %s", channel_name);

		if ((channel->show_names_after_who = s->cap_away_notify))
			irc_send (s, "WHO %s", channel_name);
	}

	// Add the user to the channel
	char *nickname = irc_cut_nickname (msg->prefix);
	irc_channel_link_user (channel, irc_get_or_make_user (s, nickname), "");
	free (nickname);

	// Finally log the message
	if (buffer)
	{
		log_server (s, buffer, BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_JOIN,
			"#N #a#s#r #S", msg->prefix, ATTR_JOIN, "has joined", channel_name);
	}
}

static void
irc_handle_kick (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	const char *channel_name = msg->params.vector[0];
	const char *target = msg->params.vector[1];
	if (!irc_is_channel (s, channel_name)
	 || irc_is_channel (s, target))
		return;

	const char *message = NULL;
	if (msg->params.len > 2)
		message = msg->params.vector[2];

	struct user *user = str_map_find (&s->irc_users, target);
	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	// It would be weird for this to be false
	if (user && channel)
	{
		if (irc_is_this_us (s, target))
			irc_left_channel (channel);
		else
			irc_remove_user_from_channel (user, channel);
	}

	if (buffer)
	{
		struct formatter f = formatter_make (s->ctx, s);
		formatter_add (&f, "#N #a#s#r #n",
			msg->prefix, ATTR_PART, "has kicked", target);
		if (message)
			formatter_add (&f, " (#m)", message);
		log_formatter (s->ctx, buffer, 0, BUFFER_LINE_PART, &f);
	}
}

static void
irc_handle_kill (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	const char *target  = msg->params.vector[0];
	const char *comment = msg->params.vector[1];

	if (irc_is_this_us (s, target))
		log_server_status (s, s->buffer,
			"You've been killed by #n (#m)", msg->prefix, comment);
}

static void
irc_handle_mode (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	const char *context = msg->params.vector[0];

	// Join the modes back to a single string
	struct strv copy = strv_make ();
	strv_append_vector (&copy, msg->params.vector + 1);
	char *modes = strv_join (&copy, " ");
	strv_free (&copy);

	if (irc_is_channel (s, context))
	{
		struct channel *channel = str_map_find (&s->irc_channels, context);
		struct buffer *buffer = str_map_find (&s->irc_buffer_map, context);
		hard_assert (channel || !buffer);

		int flags = 0;
		if (channel
		 && irc_handle_mode_channel (channel, msg->params.vector + 1))
			// This is 90% automode spam, let's not let it steal attention,
			// maybe this behaviour should be configurable though
			flags = BUFFER_LINE_UNIMPORTANT;

		if (buffer)
		{
			log_server (s, buffer, flags, BUFFER_LINE_STATUS,
				"Mode #S [#S] by #n", context, modes, msg->prefix);
		}
	}
	else if (irc_is_this_us (s, context))
	{
		irc_handle_mode_user (s, msg->params.vector + 1);
		log_server_status (s, s->buffer,
			"User mode [#S] by #n", modes, msg->prefix);
	}

	free (modes);
}

static void
irc_handle_nick (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	const char *new_nickname = msg->params.vector[0];

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&s->irc_users, nickname);
	free (nickname);
	if (!user)
		return;

	bool lexicographically_different =
		!!irc_server_strcmp (s, user->nickname, new_nickname);

	// What the fuck, someone renamed themselves to ourselves
	// TODO: probably log a message and force a reconnect
	if (lexicographically_different
	 && !irc_server_strcmp (s, new_nickname, s->irc_user->nickname))
		return;

	// Log a message in any PM buffer (we may even have one for ourselves)
	struct buffer *pm_buffer =
		str_map_find (&s->irc_buffer_map, user->nickname);
	if (pm_buffer)
	{
		if (irc_is_this_us (s, msg->prefix))
			log_nick_self (s, pm_buffer, new_nickname);
		else
			log_nick (s, pm_buffer, msg->prefix, new_nickname);
	}

	// The new nickname may collide with a user referenced by a PM buffer,
	// or in case of data inconsistency with the server, channels.
	// In the latter case we need the colliding user to leave all of them.
	struct user *user_collision = NULL;
	if (lexicographically_different
	 && (user_collision = str_map_find (&s->irc_users, new_nickname)))
		LIST_FOR_EACH (struct user_channel, iter, user_collision->channels)
			irc_remove_user_from_channel (user_collision, iter->channel);

	struct buffer *buffer_collision = NULL;
	if (lexicographically_different
	 && (buffer_collision = str_map_find (&s->irc_buffer_map, new_nickname)))
	{
		hard_assert (buffer_collision->type == BUFFER_PM);
		hard_assert (buffer_collision->user == user_collision);

		user_unref (buffer_collision->user);
		buffer_collision->user = user_ref (user);
	}

	if (pm_buffer && buffer_collision)
	{
		// There's not much else we can do other than somehow try to merge
		// one buffer into the other.  In our case, the original buffer wins.
		buffer_merge (s->ctx, buffer_collision, pm_buffer);
		if (s->ctx->current_buffer == pm_buffer)
			buffer_activate (s->ctx, buffer_collision);
		buffer_remove (s->ctx, pm_buffer);
		pm_buffer = buffer_collision;
	}

	// The colliding user should be completely gone by now
	if (lexicographically_different)
		hard_assert (!str_map_find (&s->irc_users, new_nickname));

	// Now we can rename everything to reflect the new nickname
	if (pm_buffer)
	{
		str_map_set (&s->irc_buffer_map, user->nickname, NULL);
		str_map_set (&s->irc_buffer_map, new_nickname, pm_buffer);

		char *x = irc_make_buffer_name (s, new_nickname);
		buffer_rename (s->ctx, pm_buffer, x);
		free (x);
	}

	str_map_set (&s->irc_users, user->nickname, NULL);
	str_map_set (&s->irc_users, new_nickname, user);

	cstr_set (&user->nickname, xstrdup (new_nickname));

	// Finally broadcast the event to relay clients and secondary buffers
	if (irc_is_this_us (s, new_nickname))
	{
		relay_prepare_server_update (s->ctx, s);
		relay_broadcast (s->ctx);

		log_nick_self (s, s->buffer, new_nickname);

		// Log a message in all open buffers on this server
		struct str_map_iter iter = str_map_iter_make (&s->irc_buffer_map);
		struct buffer *buffer;
		while ((buffer = str_map_iter_next (&iter)))
		{
			// We've already done that
			if (buffer != pm_buffer)
				log_nick_self (s, buffer, new_nickname);
		}
	}
	else
	{
		// Log a message in all channels the user is in
		LIST_FOR_EACH (struct user_channel, iter, user->channels)
		{
			struct buffer *buffer =
				str_map_find (&s->irc_buffer_map, iter->channel->name);
			hard_assert (buffer != NULL);
			log_nick (s, buffer, msg->prefix, new_nickname);
		}
	}
}

static void
irc_handle_ctcp_reply (struct server *s,
	const struct irc_message *msg, struct ctcp_chunk *chunk)
{
	const char *target = msg->params.vector[0];
	if (irc_is_this_us (s, msg->prefix))
		log_ctcp_reply (s, target,
			xstrdup_printf ("%s %s", chunk->tag.str, chunk->text.str));
	else
		log_server_status (s, s->buffer, "CTCP reply from #n: #S #S",
			msg->prefix, chunk->tag.str, chunk->text.str);
}

static void
irc_handle_notice_text (struct server *s,
	const struct irc_message *msg, struct str *text)
{
	const char *target = msg->params.vector[0];
	struct buffer *buffer = irc_get_buffer_for_message (s, msg, target);
	if (!buffer)
	{
		if (irc_is_this_us (s, msg->prefix))
			log_outcoming_orphan_notice (s, target, text->str);
		return;
	}

	char *nick = irc_cut_nickname (msg->prefix);
	// IRCv3.2 echo-message could otherwise cause us to highlight ourselves
	if (!irc_is_this_us (s, msg->prefix) && irc_is_highlight (s, text->str))
		log_server (s, buffer, BUFFER_LINE_HIGHLIGHT, BUFFER_LINE_STATUS,
			"#a#s(#S)#r: #m", ATTR_HIGHLIGHT, "Notice", nick, text->str);
	else
		log_outcoming_notice (s, buffer, msg->prefix, text->str);
	free (nick);
}

static void
irc_handle_notice (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	// This ignores empty messages which we should never receive anyway
	struct ctcp_chunk *chunks = ctcp_parse (msg->params.vector[1]);
	LIST_FOR_EACH (struct ctcp_chunk, iter, chunks)
		if (!iter->is_extended)
			irc_handle_notice_text (s, msg, &iter->text);
		else
			irc_handle_ctcp_reply (s, msg, iter);
	ctcp_destroy (chunks);
}

static void
irc_handle_part (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	const char *channel_name = msg->params.vector[0];
	if (!irc_is_channel (s, channel_name))
		return;

	const char *message = NULL;
	if (msg->params.len > 1)
		message = msg->params.vector[1];

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&s->irc_users, nickname);
	free (nickname);

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	// It would be weird for this to be false
	if (user && channel)
	{
		if (irc_is_this_us (s, msg->prefix))
			irc_left_channel (channel);
		else
			irc_remove_user_from_channel (user, channel);
	}

	if (buffer)
	{
		struct formatter f = formatter_make (s->ctx, s);
		formatter_add (&f, "#N #a#s#r #S",
			msg->prefix, ATTR_PART, "has left", channel_name);
		if (message)
			formatter_add (&f, " (#m)", message);
		log_formatter (s->ctx, buffer,
			BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_PART, &f);
	}
}

static void
irc_handle_ping (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len)
		irc_send (s, "PONG :%s", msg->params.vector[0]);
	else
		irc_send (s, "PONG");
}

static char *
ctime_now (char buf[26])
{
	struct tm tm_;
	time_t now = time (NULL);
	if (!asctime_r (localtime_r (&now, &tm_), buf))
		return NULL;

	// Annoying thing
	*strchr (buf, '\n') = '\0';
	return buf;
}

static void irc_send_ctcp_reply (struct server *s, const char *recipient,
	const char *format, ...) ATTRIBUTE_PRINTF (3, 4);

static void
irc_send_ctcp_reply (struct server *s,
	const char *recipient, const char *format, ...)
{
	struct str m = str_make ();

	va_list ap;
	va_start (ap, format);
	str_append_vprintf (&m, format, ap);
	va_end (ap);

	irc_send (s, "NOTICE %s :\x01%s\x01", recipient, m.str);
	str_free (&m);
}

static void
irc_handle_ctcp_request (struct server *s,
	const struct irc_message *msg, struct ctcp_chunk *chunk)
{
	const char *target = msg->params.vector[0];
	if (irc_is_this_us (s, msg->prefix))
	{
		if (s->cap_echo_message)
			log_ctcp_query (s, target, chunk->tag.str);
		if (!irc_is_this_us (s, target))
			return;
	}

	struct formatter f = formatter_make (s->ctx, s);
	formatter_add (&f, "CTCP requested by #n", msg->prefix);
	if (irc_is_channel (s, irc_skip_statusmsg (s, target)))
		formatter_add (&f, " (to #S)", target);
	formatter_add (&f, ": #S", chunk->tag.str);
	log_formatter (s->ctx, s->buffer, 0, BUFFER_LINE_STATUS, &f);

	char *nickname = irc_cut_nickname (msg->prefix);

	if (!strcmp (chunk->tag.str, "CLIENTINFO"))
		irc_send_ctcp_reply (s, nickname, "CLIENTINFO %s %s %s %s",
			"PING", "VERSION", "TIME", "CLIENTINFO");
	else if (!strcmp (chunk->tag.str, "PING"))
		irc_send_ctcp_reply (s, nickname, "PING %s", chunk->text.str);
	else if (!strcmp (chunk->tag.str, "VERSION"))
	{
		struct utsname info;
		if (uname (&info))
			LOG_LIBC_FAILURE ("uname");
		else
			irc_send_ctcp_reply (s, nickname, "VERSION %s %s on %s %s",
				PROGRAM_NAME, PROGRAM_VERSION, info.sysname, info.machine);
	}
	else if (!strcmp (chunk->tag.str, "TIME"))
	{
		char buf[26];
		if (!ctime_now (buf))
			LOG_LIBC_FAILURE ("asctime_r");
		else
			irc_send_ctcp_reply (s, nickname, "TIME %s", buf);
	}

	free (nickname);
}

static void
irc_handle_privmsg_text (struct server *s,
	const struct irc_message *msg, struct str *text, bool is_action)
{
	const char *target = msg->params.vector[0];
	struct buffer *buffer = irc_get_buffer_for_message (s, msg, target);
	if (!buffer)
	{
		if (irc_is_this_us (s, msg->prefix))
			log_outcoming_orphan_privmsg (s, target, text->str);
		return;
	}

	char *nickname = irc_cut_nickname (msg->prefix);
	char *prefixes = irc_get_privmsg_prefix
		(s, str_map_find (&s->irc_users, nickname), target);

	// Make autocomplete offer recent speakers first on partial matches
	// (note that freshly joined users also move to the front)
	struct user *user;
	struct channel_user *channel_user;
	if (!irc_is_this_us (s, msg->prefix) && buffer->channel
	 && (user = str_map_find (&s->irc_users, nickname))
	 && (channel_user = irc_channel_get_user (buffer->channel, user)))
	{
		LIST_UNLINK (buffer->channel->users, channel_user);
		LIST_PREPEND (buffer->channel->users, channel_user);
	}

	// IRCv3.2 echo-message could otherwise cause us to highlight ourselves
	if (irc_is_this_us (s, msg->prefix) || !irc_is_highlight (s, text->str))
	{
		if (is_action)
			log_outcoming_action (s, buffer, nickname, text->str);
		else
			log_outcoming_privmsg (s, buffer, prefixes, nickname, text->str);
	}
	else if (is_action)
		log_server (s, buffer, BUFFER_LINE_HIGHLIGHT, BUFFER_LINE_ACTION,
			"#a#S#r #m", ATTR_HIGHLIGHT, nickname, text->str);
	else
		log_server (s, buffer, BUFFER_LINE_HIGHLIGHT, 0,
			"#a<#S#S>#r #m", ATTR_HIGHLIGHT, prefixes, nickname, text->str);

	free (nickname);
	free (prefixes);
}

static void
irc_handle_privmsg (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	// This ignores empty messages which we should never receive anyway
	struct ctcp_chunk *chunks = ctcp_parse (msg->params.vector[1]);
	LIST_FOR_EACH (struct ctcp_chunk, iter, chunks)
		if (!iter->is_extended)
			irc_handle_privmsg_text (s, msg, &iter->text, false);
		else if (!strcmp (iter->tag.str, "ACTION"))
			irc_handle_privmsg_text (s, msg, &iter->text, true);
		else
			irc_handle_ctcp_request (s, msg, iter);
	ctcp_destroy (chunks);
}

static void
log_quit (struct server *s,
	struct buffer *buffer, const char *prefix, const char *reason)
{
	struct formatter f = formatter_make (s->ctx, s);
	formatter_add (&f, "#N #a#s#r", prefix, ATTR_PART, "has quit");
	if (reason)
		formatter_add (&f, " (#m)", reason);
	log_formatter (s->ctx, buffer,
		BUFFER_LINE_UNIMPORTANT, BUFFER_LINE_PART, &f);
}

static void
irc_handle_quit (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix)
		return;

	// What the fuck, the server never sends this back
	if (irc_is_this_us (s, msg->prefix))
		return;

	char *nickname = irc_cut_nickname (msg->prefix);
	struct user *user = str_map_find (&s->irc_users, nickname);
	free (nickname);
	if (!user)
		return;

	const char *message = NULL;
	if (msg->params.len > 0)
		message = msg->params.vector[0];

	// Log a message in any PM buffer
	struct buffer *buffer =
		str_map_find (&s->irc_buffer_map, user->nickname);
	if (buffer)
	{
		log_quit (s, buffer, msg->prefix, message);

		// TODO: set some kind of a flag in the buffer and when the user
		//   reappears on a channel (JOIN), log a "is back online" message.
		//   Also set this flag when we receive a "no such nick" numeric
		//   and reset it when we send something to the buffer.
	}

	// Log a message in all channels the user is in
	LIST_FOR_EACH (struct user_channel, iter, user->channels)
	{
		if ((buffer = str_map_find (&s->irc_buffer_map, iter->channel->name)))
			log_quit (s, buffer, msg->prefix, message);

		// This destroys "iter" which doesn't matter to us
		irc_remove_user_from_channel (user, iter->channel);
	}
}

static void
irc_handle_tagmsg (struct server *s, const struct irc_message *msg)
{
	// TODO: here we can process "typing" tags, once we find this useful
	(void) s;
	(void) msg;
}

static void
irc_handle_topic (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 2)
		return;

	const char *channel_name = msg->params.vector[0];
	const char *topic = msg->params.vector[1];
	if (!irc_is_channel (s, channel_name))
		return;

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	// It would be weird for this to be false
	if (channel)
		irc_channel_set_topic (channel, topic);

	if (buffer)
	{
		log_server (s, buffer, 0, BUFFER_LINE_STATUS, "#n #s \"#m\"",
			msg->prefix, "has changed the topic to", topic);
	}
}

static void
irc_handle_wallops (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	const char *message = msg->params.vector[0];
	log_server (s, s->buffer, 0, 0, "<#n> #m", msg->prefix, message);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static struct irc_handler g_irc_handlers[] =
{
	// This list needs to stay sorted
	{ "AUTHENTICATE", irc_handle_authenticate },
	{ "AWAY",         irc_handle_away         },
	{ "CAP",          irc_handle_cap          },
	{ "CHGHOST",      irc_handle_chghost      },
	{ "ERROR",        irc_handle_error        },
	{ "INVITE",       irc_handle_invite       },
	{ "JOIN",         irc_handle_join         },
	{ "KICK",         irc_handle_kick         },
	{ "KILL",         irc_handle_kill         },
	{ "MODE",         irc_handle_mode         },
	{ "NICK",         irc_handle_nick         },
	{ "NOTICE",       irc_handle_notice       },
	{ "PART",         irc_handle_part         },
	{ "PING",         irc_handle_ping         },
	{ "PRIVMSG",      irc_handle_privmsg      },
	{ "QUIT",         irc_handle_quit         },
	{ "TAGMSG",       irc_handle_tagmsg       },
	{ "TOPIC",        irc_handle_topic        },
	{ "WALLOPS",      irc_handle_wallops      },
};

static bool
irc_try_parse_word_for_userhost (struct server *s, const char *word)
{
	regex_t re;
	int err = regcomp (&re, "^[^!@]+!([^!@]+@[^!@]+)$", REG_EXTENDED);
	if (!soft_assert (!err))
		return false;

	regmatch_t matches[2];
	bool result = false;
	if (!regexec (&re, word, 2, matches, 0))
	{
		cstr_set (&s->irc_user_host, xstrndup (word + matches[1].rm_so,
			matches[1].rm_eo - matches[1].rm_so));
		result = true;
	}
	regfree (&re);
	return result;
}

static void
irc_try_parse_welcome_for_userhost (struct server *s, const char *m)
{
	struct strv v = strv_make ();
	cstr_split (m, " ", true, &v);
	for (size_t i = 0; i < v.len; i++)
		if (irc_try_parse_word_for_userhost (s, v.vector[i]))
			break;
	strv_free (&v);
}

static void process_input
	(struct app_context *, struct buffer *, const char *);
static bool process_input_line
	(struct app_context *, struct buffer *, const char *, int);
static void on_autoaway_timer (struct app_context *ctx);

static void
irc_on_registered (struct server *s, const char *nickname)
{
	s->irc_user = irc_get_or_make_user (s, nickname);
	str_reset (&s->irc_user_modes);
	cstr_set (&s->irc_user_host, NULL);

	irc_set_state (s, IRC_REGISTERED);

	// XXX: we can also use WHOIS if it's not supported (optional by RFC 2812)
	// TODO: maybe rather always use RPL_ISUPPORT NICKLEN & USERLEN & HOSTLEN
	//   since we don't seem to follow any subsequent changes in userhost;
	//   unrealircd sends RPL_HOSTHIDDEN (396), which has an optional user part,
	//   and there is also CAP CHGHOST which /may/ send it to ourselves
	irc_send (s, "USERHOST %s", s->irc_user->nickname);

	// A little hack that reinstates auto-away status when we get disconnected
	if (s->autoaway_active)
		on_autoaway_timer (s->ctx);

	const char *command = get_config_string (s->config, "command");
	if (command)
	{
		log_server_debug (s, "Executing \"#s\"", command);
		(void) process_input (s->ctx, s->buffer, command);
	}

	int64_t command_delay = get_config_integer (s->config, "command_delay");
	log_server_debug (s, "Autojoining channels in #&s seconds...",
		xstrdup_printf ("%" PRId64, command_delay));
	poller_timer_set (&s->autojoin_tmr, command_delay * 1000);
}

static void
irc_handle_rpl_userhost (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	const char *response = msg->params.vector[1];
	struct strv v = strv_make ();
	cstr_split (response, " ", true, &v);

	for (size_t i = 0; i < v.len; i++)
	{
		char *nick = v.vector[i];
		char *equals = strchr (nick, '=');

		if (!equals || equals == nick)
			continue;

		// User is an IRC operator
		if (equals[-1] == '*')
			equals[-1] = '\0';
		else
			equals[ 0] = '\0';

		// TODO: make use of this (away status polling?)
		char away_status = equals[1];
		if (!strchr ("+-", away_status))
			continue;

		char *userhost = equals + 2;
		if (irc_is_this_us (s, nick))
			cstr_set (&s->irc_user_host, xstrdup (userhost));
	}
	strv_free (&v);
}

static void
irc_handle_rpl_umodeis (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	str_reset (&s->irc_user_modes);
	irc_handle_mode_user (s, msg->params.vector + 1);

	// XXX: do we want to log a message?
}

static void
irc_handle_rpl_namreply (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 4)
		return;

	const char *channel_name = msg->params.vector[2];
	const char *nicks        = msg->params.vector[3];

	// Just push the nicknames to a string vector to process later
	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	if (channel)
		cstr_split (nicks, " ", true, &channel->names_buf);
	else
		log_server_status (s, s->buffer, "Users on #S: #S",
			channel_name, nicks);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct channel_user_sort_entry
{
	struct server *s;                   ///< Server (because of the qsort API)
	struct channel_user *channel_user;  ///< Channel user
};

static int
channel_user_sort_entry_cmp (const void *entry_a, const void *entry_b)
{
	const struct channel_user_sort_entry *a = entry_a;
	const struct channel_user_sort_entry *b = entry_b;
	struct server *s = a->s;

	// First order by the most significant channel user prefix
	const char *prio_a = strchr (s->irc_chanuser_prefixes,
		a->channel_user->prefixes[0]);
	const char *prio_b = strchr (s->irc_chanuser_prefixes,
		b->channel_user->prefixes[0]);

	// Put unrecognized prefixes at the end of the list
	if (prio_a || prio_b)
	{
		if (!prio_a) return  1;
		if (!prio_b) return -1;

		if (prio_a != prio_b)
			return prio_a - prio_b;
	}

	return irc_server_strcmp (s,
		a->channel_user->user->nickname,
		b->channel_user->user->nickname);
}

static void
irc_sort_channel_users (struct channel *channel)
{
	size_t n_users = channel->users_len;
	struct channel_user_sort_entry entries[n_users], *p = entries;
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
	{
		p->s = channel->s;
		p->channel_user = iter;
		p++;
	}

	qsort (entries, n_users, sizeof *entries, channel_user_sort_entry_cmp);

	channel->users = NULL;
	while (p-- != entries)
		LIST_PREPEND (channel->users, p->channel_user);
}

static char *
make_channel_users_list (struct channel *channel)
{
	size_t n_users = channel->users_len;
	struct channel_user_sort_entry entries[n_users], *p = entries;
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
	{
		p->s = channel->s;
		p->channel_user = iter;
		p++;
	}

	qsort (entries, n_users, sizeof *entries, channel_user_sort_entry_cmp);

	// Make names of users that are away italicised, constructing a formatter
	// and adding a new attribute seems like unnecessary work
	struct str list = str_make ();
	for (size_t i = 0; i < n_users; i++)
	{
		struct channel_user *channel_user = entries[i].channel_user;
		if (channel_user->user->away) str_append_c (&list, '\x1d');
		irc_get_channel_user_prefix (channel->s, channel_user, &list);
		str_append (&list, channel_user->user->nickname);
		if (channel_user->user->away) str_append_c (&list, '\x1d');
		str_append_c (&list, ' ');
	}
	if (list.len)
		list.str[--list.len] = '\0';
	return str_steal (&list);
}

static void
irc_sync_channel_user (struct channel *channel, const char *nickname,
	const char *prefixes)
{
	struct user *user = irc_get_or_make_user (channel->s, nickname);
	struct channel_user *channel_user =
		irc_channel_get_user (channel, user);
	if (!channel_user)
	{
		irc_channel_link_user (channel, user, prefixes);
		return;
	}

	user_unref (user);

	// If our idea of the user's modes disagrees with what the server's
	// sent us (the most powerful modes differ), use the latter one
	if (channel_user->prefixes[0] != prefixes[0])
		cstr_set (&channel_user->prefixes, xstrdup (prefixes));
}

static void
irc_process_names_finish (struct channel *channel)
{
	struct server *s = channel->s;
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel->name);
	if (buffer)
	{
		log_server_status (channel->s, buffer, "Users on #S: #&m",
			channel->name, make_channel_users_list (channel));
	}
}

static void
irc_process_names (struct channel *channel)
{
	struct str_map present = str_map_make (NULL);
	present.key_xfrm = channel->s->irc_strxfrm;

	// Either that, or there is no other inhabitant, and sorting does nothing
	bool we_have_just_joined = channel->users_len == 1;

	struct strv *updates = &channel->names_buf;
	for (size_t i = 0; i < updates->len; i++)
	{
		const char *item = updates->vector[i];
		size_t n_prefixes = strspn (item, channel->s->irc_chanuser_prefixes);
		const char *nickname = item + n_prefixes;

		// Store the nickname in a hashset
		str_map_set (&present, nickname, (void *) 1);

		char *prefixes = xstrndup (item, n_prefixes);
		irc_sync_channel_user (channel, nickname, prefixes);
		free (prefixes);
	}

	// Get rid of channel users missing from "updates"
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
		if (!str_map_find (&present, iter->user->nickname))
			irc_channel_unlink_user (channel, iter);

	str_map_free (&present);
	strv_reset (&channel->names_buf);

	if (we_have_just_joined)
		irc_sort_channel_users (channel);
	if (!channel->show_names_after_who)
		irc_process_names_finish (channel);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
irc_handle_rpl_endofnames (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	const char *channel_name = msg->params.vector[1];
	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	if (!strcmp (channel_name, "*"))
	{
		struct str_map_iter iter = str_map_iter_make (&s->irc_channels);
		struct channel *channel;
		while ((channel = str_map_iter_next (&iter)))
			irc_process_names (channel);
	}
	else if (channel)
		irc_process_names (channel);
}

static bool
irc_handle_rpl_whoreply (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 7)
		return false;

	// Sequence: channel, user, host, server, nick, chars
	const char *channel_name = msg->params.vector[1];
	const char *nickname     = msg->params.vector[5];
	const char *chars        = msg->params.vector[6];

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct user *user = str_map_find (&s->irc_users, nickname);

	// This makes sense to set only with the away-notify capability so far.
	if (!channel || !channel->show_names_after_who)
		return false;

	// We track ourselves by other means and we can't track PM-only users yet.
	if (user && user != s->irc_user && user->channels)
		user->away = *chars == 'G';
	return true;
}

static bool
irc_handle_rpl_endofwho (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return false;

	const char *target = msg->params.vector[1];

	struct channel *channel = str_map_find (&s->irc_channels, target);
	if (!channel || !channel->show_names_after_who)
		return false;

	irc_process_names_finish (channel);
	channel->show_names_after_who = false;
	return true;
}

static void
irc_handle_rpl_topic (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 3)
		return;

	const char *channel_name = msg->params.vector[1];
	const char *topic        = msg->params.vector[2];

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	if (channel)
		irc_channel_set_topic (channel, topic);

	if (buffer)
		log_server_status (s, buffer, "The topic is: #m", topic);
}

static void
irc_handle_rpl_channelmodeis (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	const char *channel_name = msg->params.vector[1];

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	if (channel)
	{
		str_reset (&channel->no_param_modes);
		str_map_clear (&channel->param_modes);

		irc_handle_mode_channel (channel, msg->params.vector + 1);
	}

	// XXX: do we want to log a message?
}

static char *
make_time_string (time_t time)
{
	char buf[32];
	struct tm tm;
	strftime (buf, sizeof buf, "%a %b %d %Y %T", localtime_r (&time, &tm));
	return xstrdup (buf);
}

static void
irc_handle_rpl_creationtime (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 3)
		return;

	const char *channel_name  = msg->params.vector[1];
	const char *creation_time = msg->params.vector[2];

	unsigned long created;
	if (!xstrtoul (&created, creation_time, 10))
		return;

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	if (buffer)
	{
		log_server_status (s, buffer, "Channel created on #&s",
			make_time_string (created));
	}
}

static void
irc_handle_rpl_topicwhotime (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 4)
		return;

	const char *channel_name = msg->params.vector[1];
	const char *who          = msg->params.vector[2];
	const char *change_time  = msg->params.vector[3];

	unsigned long changed;
	if (!xstrtoul (&changed, change_time, 10))
		return;

	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel_name);
	hard_assert (channel || !buffer);

	if (buffer)
	{
		log_server_status (s, buffer, "Topic set by #N on #&s",
			who, make_time_string (changed));
	}
}

static void
irc_handle_rpl_inviting (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 3)
		return;

	const char *nickname     = msg->params.vector[1];
	const char *channel_name = msg->params.vector[2];

	struct buffer *buffer;
	if (!(buffer = str_map_find (&s->irc_buffer_map, channel_name)))
		buffer = s->buffer;

	log_server_status (s, buffer,
		"You have invited #n to #S", nickname, channel_name);
}

static void
irc_handle_err_nicknameinuse (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	log_server_error (s, s->buffer,
		"Nickname is already in use: #S", msg->params.vector[1]);

	// Only do this while we haven't successfully registered yet
	if (s->state != IRC_CONNECTED)
		return;

	char *nickname = irc_fetch_next_nickname (s);
	if (nickname)
	{
		log_server_status (s, s->buffer, "Retrying with #s...", nickname);
		irc_send (s, "NICK :%s", nickname);
		free (nickname);
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
irc_handle_isupport_prefix (struct server *s, char *value)
{
	char *modes = value;
	char *prefixes = strchr (value, ')');
	size_t n_prefixes = prefixes - modes;
	if (*modes++ != '(' || !prefixes++ || strlen (value) != 2 * n_prefixes--)
		return;

	cstr_set (&s->irc_chanuser_modes,    xstrndup (modes,    n_prefixes));
	cstr_set (&s->irc_chanuser_prefixes, xstrndup (prefixes, n_prefixes));
}

static void
irc_handle_isupport_casemapping (struct server *s, char *value)
{
	if      (!strcmp (value, "ascii"))
		irc_set_casemapping (s, tolower_ascii,      tolower_ascii_strxfrm);
	else if (!strcmp (value, "rfc1459"))
		irc_set_casemapping (s, irc_tolower,        irc_strxfrm);
	else if (!strcmp (value, "rfc1459-strict"))
		irc_set_casemapping (s, irc_tolower_strict, irc_strxfrm_strict);
}

static void
irc_handle_isupport_chantypes (struct server *s, char *value)
{
	cstr_set (&s->irc_chantypes, xstrdup (value));
}

static void
irc_handle_isupport_idchan (struct server *s, char *value)
{
	struct str prefixes = str_make ();
	struct strv v = strv_make ();
	cstr_split (value, ",", true, &v);
	for (size_t i = 0; i < v.len; i++)
	{
		// Not using or validating the numeric part
		const char *pair = v.vector[i];
		const char *colon = strchr (pair, ':');
		if (colon)
			str_append_data (&prefixes, pair, colon - pair);
	}
	strv_free (&v);
	cstr_set (&s->irc_idchan_prefixes, str_steal (&prefixes));
}

static void
irc_handle_isupport_statusmsg (struct server *s, char *value)
{
	cstr_set (&s->irc_statusmsg, xstrdup (value));
}

static void
irc_handle_isupport_extban (struct server *s, char *value)
{
	s->irc_extban_prefix = 0;
	if (*value && *value != ',')
		s->irc_extban_prefix = *value++;

	cstr_set (&s->irc_extban_types, xstrdup (*value == ',' ? ++value : ""));
}

static void
irc_handle_isupport_chanmodes (struct server *s, char *value)
{
	struct strv v = strv_make ();
	cstr_split (value, ",", true, &v);
	if (v.len >= 4)
	{
		cstr_set (&s->irc_chanmodes_list,           xstrdup (v.vector[0]));
		cstr_set (&s->irc_chanmodes_param_always,   xstrdup (v.vector[1]));
		cstr_set (&s->irc_chanmodes_param_when_set, xstrdup (v.vector[2]));
		cstr_set (&s->irc_chanmodes_param_never,    xstrdup (v.vector[3]));
	}
	strv_free (&v);
}

static void
irc_handle_isupport_modes (struct server *s, char *value)
{
	unsigned long modes;
	if (!*value)
		s->irc_max_modes = UINT_MAX;
	else if (xstrtoul (&modes, value, 10) && modes && modes <= UINT_MAX)
		s->irc_max_modes = modes;
}

static void
unescape_isupport_value (const char *value, struct str *output)
{
	const char *alphabet = "0123456789abcdef", *a, *b;
	for (const char *p = value; *p; p++)
	{
		if (p[0] == '\\'
		 && p[1] == 'x'
		 && p[2] && (a = strchr (alphabet, tolower_ascii (p[2])))
		 && p[3] && (b = strchr (alphabet, tolower_ascii (p[3]))))
		{
			str_append_c (output, (a - alphabet) << 4 | (b - alphabet));
			p += 3;
		}
		else
			str_append_c (output, *p);
	}
}

static void
dispatch_isupport (struct server *s, const char *name, char *value)
{
#define MATCH(from, to) if (!strcmp (name, (from))) { (to) (s, value); return; }

	// TODO: also make use of TARGMAX to split client commands as necessary

	MATCH ("PREFIX",      irc_handle_isupport_prefix);
	MATCH ("CASEMAPPING", irc_handle_isupport_casemapping);
	MATCH ("CHANTYPES",   irc_handle_isupport_chantypes);
	MATCH ("IDCHAN",      irc_handle_isupport_idchan);
	MATCH ("STATUSMSG",   irc_handle_isupport_statusmsg);
	MATCH ("EXTBAN",      irc_handle_isupport_extban);
	MATCH ("CHANMODES",   irc_handle_isupport_chanmodes);
	MATCH ("MODES",       irc_handle_isupport_modes);

#undef MATCH
}

static void
irc_handle_rpl_isupport (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	for (size_t i = 1; i < msg->params.len - 1; i++)
	{
		// TODO: if the parameter starts with "-", it resets to default
		char *param = msg->params.vector[i];
		char *value = param + strcspn (param, "=");
		if (*value) *value++ = '\0';

		struct str value_unescaped = str_make ();
		unescape_isupport_value (value, &value_unescaped);
		dispatch_isupport (s, param, value_unescaped.str);
		str_free (&value_unescaped);
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
irc_adjust_motd (char **motd)
{
	// Heuristic, force MOTD to be monospace in graphical frontends.
	if (!strchr (*motd, '\x11'))
	{
		struct str s = str_make ();
		str_append_c (&s, '\x11');
		for (const char *p = *motd; *p; p++)
		{
			str_append_c (&s, *p);
			if (*p == '\x0f')
				str_append_c (&s, '\x11');
		}
		cstr_set (motd, str_steal (&s));
	}
}

static void
irc_process_numeric (struct server *s,
	const struct irc_message *msg, unsigned long numeric)
{
	// Numerics typically have human-readable information

	// Get rid of the first parameter, if there's any at all,
	// as it contains our nickname and is of no practical use to the user
	struct strv copy = strv_make ();
	strv_append_vector (&copy, msg->params.vector + !!msg->params.len);

	struct buffer *buffer = s->buffer;
	int flags = 0;
	switch (numeric)
	{
	case IRC_RPL_WELCOME:
		irc_on_registered (s, msg->params.vector[0]);

		// We still issue a USERHOST anyway as this is in general unreliable
		if (msg->params.len == 2)
			irc_try_parse_welcome_for_userhost (s, msg->params.vector[1]);
		break;
	case IRC_RPL_MOTDSTART:
	case IRC_RPL_MOTD:
		if (copy.len)
			irc_adjust_motd (&copy.vector[0]);
		break;

	case IRC_RPL_ISUPPORT:
		irc_handle_rpl_isupport      (s, msg);                break;
	case IRC_RPL_USERHOST:
		irc_handle_rpl_userhost      (s, msg);                break;
	case IRC_RPL_UMODEIS:
		irc_handle_rpl_umodeis       (s, msg); buffer = NULL; break;
	case IRC_RPL_NAMREPLY:
		irc_handle_rpl_namreply      (s, msg); buffer = NULL; break;
	case IRC_RPL_ENDOFNAMES:
		irc_handle_rpl_endofnames    (s, msg); buffer = NULL; break;
	case IRC_RPL_TOPIC:
		irc_handle_rpl_topic         (s, msg); buffer = NULL; break;
	case IRC_RPL_CHANNELMODEIS:
		irc_handle_rpl_channelmodeis (s, msg); buffer = NULL; break;
	case IRC_RPL_CREATIONTIME:
		irc_handle_rpl_creationtime  (s, msg); buffer = NULL; break;
	case IRC_RPL_TOPICWHOTIME:
		irc_handle_rpl_topicwhotime  (s, msg); buffer = NULL; break;
	case IRC_RPL_INVITING:
		irc_handle_rpl_inviting      (s, msg); buffer = NULL; break;

	case IRC_ERR_NICKNAMEINUSE:
		irc_handle_err_nicknameinuse (s, msg); buffer = NULL; break;

		// Auto-away spams server buffers with activity
	case IRC_RPL_NOWAWAY:
		flags |= BUFFER_LINE_UNIMPORTANT;
		if (s->irc_user) s->irc_user->away = true;
		break;
	case IRC_RPL_UNAWAY:
		flags |= BUFFER_LINE_UNIMPORTANT;
		if (s->irc_user) s->irc_user->away = false;
		break;

	case IRC_RPL_WHOREPLY:
		if (irc_handle_rpl_whoreply (s, msg))  buffer = NULL;
		break;
	case IRC_RPL_ENDOFWHO:
		if (irc_handle_rpl_endofwho (s, msg))  buffer = NULL;
		break;

	case IRC_ERR_NICKLOCKED:
	case IRC_RPL_SASLSUCCESS:
	case IRC_ERR_SASLFAIL:
	case IRC_ERR_SASLTOOLONG:
	case IRC_ERR_SASLABORTED:
	case IRC_ERR_SASLALREADY:
		irc_try_finish_cap_negotiation (s);
		break;

	case IRC_RPL_LIST:

	case IRC_ERR_UNKNOWNCOMMAND:
	case IRC_ERR_NEEDMOREPARAMS:
		// Just preventing these commands from getting printed in a more
		// specific buffer as that would be unwanted
		break;

	default:
		// If the second parameter is something we have a buffer for
		// (a channel, a PM buffer), log it in that buffer.  This is very basic.
		// TODO: whitelist/blacklist a lot more replies in here.
		// TODO: we should either strip the first parameter from the resulting
		//   buffer line, or at least put it in brackets
		if (msg->params.len < 2)
			break;

		struct buffer *x;
		if ((x = str_map_find (&s->irc_buffer_map, msg->params.vector[1])))
			buffer = x;

		// A JOIN request should be split at commas,
		// then for each element produce either a JOIN response, or a numeric.
		(void) irc_satisfy_join (s, msg->params.vector[1]);
	}

	if (buffer)
	{
		// Join the parameter vector back and send it to the server buffer
		log_server (s, buffer, flags, BUFFER_LINE_STATUS,
			"#&m", strv_join (&copy, " "));
	}

	strv_free (&copy);
}

static void
irc_sanitize_cut_off_utf8 (char **line)
{
	// A variation on utf8_validate(), we need to detect the -2 return
	const char *p = *line, *end = strchr (p, 0);
	int32_t codepoint;
	while ((codepoint = utf8_decode (&p, end - p)) >= 0
		&& utf8_validate_cp (codepoint))
		;
	if (codepoint != -2)
		return;

	struct str fixed_up = str_make ();
	str_append_data (&fixed_up, *line, p - *line);
	str_append (&fixed_up, "\xEF\xBF\xBD" /* U+FFFD */);
	cstr_set (line, str_steal (&fixed_up));
}

static void
irc_process_message (const struct irc_message *msg, struct server *s)
{
	if (msg->params.len)
		irc_sanitize_cut_off_utf8 (&msg->params.vector[msg->params.len - 1]);

	// TODO: make use of IRCv3.2 server-time (with fallback to unixtime_msec())
	//   -> change all calls to log_{server,nick,chghost,outcoming,ctcp}*()
	//   to take an extra numeric argument specifying time
	struct irc_handler key = { .name = msg->command };
	struct irc_handler *handler = bsearch (&key, g_irc_handlers,
		N_ELEMENTS (g_irc_handlers), sizeof key, irc_handler_cmp_by_name);
	if (handler)
		handler->handler (s, msg);

	unsigned long numeric;
	if (xstrtoul (&numeric, msg->command, 10))
		irc_process_numeric (s, msg, numeric);

	// Better always make sure everything is in sync rather than care about
	// each case explicitly whether anything might have changed
	refresh_prompt (s->ctx);
}

// --- Message autosplitting magic ---------------------------------------------

// This is a rather basic algorithm; something like ICU with proper
// locale specification would be needed to make it work better.

static size_t
wrap_text_for_single_line (const char *text, struct irc_char_attrs *attrs,
	size_t text_len, size_t target_len, struct str *output)
{
	size_t eaten = 0;

	// First try going word by word
	const char *word_start;
	const char *word_end = text + strcspn (text, " ");
	size_t word_len = word_end - text;
	while (target_len && word_len <= target_len)
	{
		if (word_len)
		{
			str_append_data (output, text, word_len);

			text += word_len;
			eaten += word_len;
			target_len -= word_len;
		}

		// Find the next word's end
		word_start = text + strspn (text, " ");
		word_end = word_start + strcspn (word_start, " ");
		word_len = word_end - text;
	}

	if (eaten)
		// Discard whitespace between words if split
		return eaten + (word_start - text);

	// And if that doesn't help, cut the longest valid block of characters
	for (size_t i = 1; i <= text_len && i <= target_len; i++)
		if (i == text_len || attrs[i].starts_at_boundary)
			eaten = i;

	str_append_data (output, text, eaten);
	return eaten;
}

// In practice, this should never fail at all, although it's not guaranteed
static bool
wrap_message (const char *message,
	int line_max, struct strv *output, struct error **e)
{
	size_t message_left = strlen (message), i = 0;
	struct irc_char_attrs *attrs = irc_analyze_text (message, message_left);
	struct str m = str_make ();
	if (line_max <= 0)
		goto error;

	while (m.len + message_left > (size_t) line_max)
	{
		size_t eaten = wrap_text_for_single_line
			(message + i, attrs + i, message_left, line_max - m.len, &m);
		if (!eaten)
			goto error;

		strv_append_owned (output, str_steal (&m));
		m = str_make ();

		i += eaten;
		if (!(message_left -= eaten))
			break;

		irc_serialize_char_attrs (attrs + i, &m);
		if (m.len >= (size_t) line_max)
		{
			print_debug ("formatting continuation too long");
			str_reset (&m);
		}
	}
	if (message_left)
		strv_append_owned (output,
			xstrdup_printf ("%s%s", m.str, message + i));

	free (attrs);
	str_free (&m);
	return true;

error:
	free (attrs);
	str_free (&m);
	return error_set (e,
		"Message splitting was unsuccessful as there was "
		"too little room for UTF-8 characters");
}

/// Automatically splits messages that arrive at other clients with our prefix
/// so that they don't arrive cut off by the server
static bool
irc_autosplit_message (struct server *s, const char *message,
	int fixed_part, struct strv *output, struct error **e)
{
	// :<nick>!<user>@<host> <fixed-part><message>
	int space_in_one_message = 0;
	if (s->irc_user && s->irc_user_host)
		space_in_one_message = 510
			- 1 - (int) strlen (s->irc_user->nickname)
			- 1 - (int) strlen (s->irc_user_host)
			- 1 - fixed_part;

	// Multiline messages can be triggered through hooks and plugins.
	struct strv lines = strv_make ();
	cstr_split (message, "\r\n", false, &lines);
	bool success = true;
	for (size_t i = 0; i < lines.len; i++)
	{
		// We don't always have the full info for message splitting.
		if (!space_in_one_message)
			strv_append (output, lines.vector[i]);
		else if (!(success =
			wrap_message (lines.vector[i], space_in_one_message, output, e)))
			break;
	}
	strv_free (&lines);
	return success;
}

static void
send_autosplit_message (struct server *s,
	const char *command, const char *target, const char *message,
	const char *prefix, const char *suffix)
{
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, target);

	// "COMMAND target * :prefix*suffix"
	int fixed_part = strlen (command) + 1 + strlen (target) + 1 + 1
		+ strlen (prefix) + strlen (suffix);

	struct strv lines = strv_make ();
	struct error *e = NULL;
	if (!irc_autosplit_message (s, message, fixed_part, &lines, &e))
	{
		log_server_error (s, buffer ? buffer : s->buffer, "#s", e->message);
		error_free (e);
	}
	else
	{
		for (size_t i = 0; i < lines.len; i++)
			irc_send (s, "%s %s :%s%s%s", command, target,
				prefix, lines.vector[i], suffix);
	}
	strv_free (&lines);
}

#define SEND_AUTOSPLIT_ACTION(s, target, message)                              \
	send_autosplit_message ((s), "PRIVMSG", (target), (message),               \
		"\x01" "ACTION ", "\x01")

#define SEND_AUTOSPLIT_PRIVMSG(s, target, message)                             \
	send_autosplit_message ((s), "PRIVMSG", (target), (message), "", "")

#define SEND_AUTOSPLIT_NOTICE(s, target, message)                              \
	send_autosplit_message ((s), "NOTICE", (target), (message), "", "")

// --- Configuration dumper ----------------------------------------------------

struct config_dump_data
{
	struct strv path;                   ///< Levels
	struct strv *output;                ///< Where to place new entries
};

static void config_dump_item
	(struct config_item *item, struct config_dump_data *data);

static void
config_dump_children
	(struct config_item *object, struct config_dump_data *data)
{
	hard_assert (object->type == CONFIG_ITEM_OBJECT);

	struct str_map_iter iter = str_map_iter_make (&object->value.object);
	struct config_item *child;
	while ((child = str_map_iter_next (&iter)))
	{
		strv_append_owned (&data->path, iter.link->key);
		config_dump_item (child, data);
		strv_steal (&data->path, data->path.len - 1);
	}
}

static void
config_dump_item (struct config_item *item, struct config_dump_data *data)
{
	// Empty objects will show as such
	if (item->type == CONFIG_ITEM_OBJECT
	 && item->value.object.len)
	{
		config_dump_children (item, data);
		return;
	}

	// Currently there's no reason for us to dump unknown items
	const struct config_schema *schema = item->schema;
	if (!schema)
		return;

	struct str line = str_make ();
	if (data->path.len)
		str_append (&line, data->path.vector[0]);
	for (size_t i = 1; i < data->path.len; i++)
		str_append_printf (&line, ".%s", data->path.vector[i]);

	struct str value = str_make ();
	config_item_write (item, false, &value);

	// Don't bother writing out null values everywhere
	bool has_default = schema && schema->default_;
	if (item->type != CONFIG_ITEM_NULL || has_default)
	{
		str_append (&line, " = ");
		str_append_str (&line, &value);
	}

	if (!schema)
		str_append (&line, " (unrecognized)");
	else if (has_default && strcmp (schema->default_, value.str))
		str_append_printf (&line, " (default: %s)", schema->default_);
	else if (!has_default && item->type != CONFIG_ITEM_NULL)
		str_append_printf (&line, " (default: %s)", "null");

	str_free (&value);
	strv_append_owned (data->output, str_steal (&line));
}

static void
config_dump (struct config_item *root, struct strv *output)
{
	struct config_dump_data data;
	data.path = strv_make ();
	data.output = output;

	config_dump_item (root, &data);

	hard_assert (!data.path.len);
	strv_free (&data.path);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
strv_sort_cb (const void *a, const void *b)
{
	return strcmp (*(const char **) a, *(const char **) b);
}

static void
strv_sort (struct strv *self)
{
	qsort (self->vector, self->len, sizeof *self->vector, strv_sort_cb);
}

static void
dump_matching_options
	(struct config_item *root, const char *mask, struct strv *output)
{
	config_dump (root, output);
	strv_sort (output);

	// Filter out results by wildcard matching
	for (size_t i = 0; i < output->len; i++)
	{
		// Yeah, I know
		char *key = cstr_cut_until (output->vector[i], " ");
		if (fnmatch (mask, key, 0))
			strv_remove (output, i--);
		free (key);
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
save_configuration (struct app_context *ctx)
{
	struct str data = str_make ();
	serialize_configuration (ctx->config.root, &data);

	struct error *e = NULL;
	char *filename = write_configuration_file (NULL, &data, &e);
	str_free (&data);

	if (!filename)
	{
		log_global_error (ctx,
			"#s: #s", "Saving configuration failed", e->message);
		error_free (e);
	}
	else
		log_global_status (ctx, "Configuration written to `#s'", filename);
	free (filename);
}

// --- Server management -------------------------------------------------------

static bool
validate_server_name (const char *name)
{
	for (const unsigned char *p = (const unsigned char *) name; *p; p++)
		if (iscntrl_ascii (*p) || *p == '.')
			return false;
	return true;
}

static const char *
check_server_name_for_addition (struct app_context *ctx, const char *name)
{
	if (!strcasecmp_ascii (name, ctx->global_buffer->name))
		return "name collides with the global buffer";
	if (str_map_find (&ctx->servers, name))
		return "server already exists";
	if (!validate_server_name (name))
		return "invalid server name";
	return NULL;
}

static struct server *
server_add (struct app_context *ctx,
	const char *name, struct config_item *subtree)
{
	hard_assert (!str_map_find (&ctx->servers, name));

	struct server *s = server_new (&ctx->poller);
	s->ctx = ctx;
	s->name = xstrdup (name);
	str_map_set (&ctx->servers, s->name, s);
	s->config = subtree;

	relay_prepare_server_update (ctx, s);
	relay_broadcast (ctx);

	// Add a buffer and activate it
	struct buffer *buffer = s->buffer = buffer_new (ctx->input,
		BUFFER_SERVER, irc_make_buffer_name (s, NULL));
	buffer->server = s;

	buffer_add (ctx, buffer);
	buffer_activate (ctx, buffer);

	config_schema_apply_to_object (g_config_server, subtree, s);
	config_schema_call_changed (subtree);

	if (get_config_boolean (s->config, "autoconnect"))
		// Connect to the server ASAP
		poller_timer_set (&s->reconnect_tmr, 0);
	return s;
}

static void
server_add_new (struct app_context *ctx, const char *name)
{
	// Note that there may already be something in the configuration under
	// that key that we've ignored earlier, and there may also be
	// a case-insensitive conflict.  Those things may only happen as a result
	// of manual edits to the configuration, though, and they're not really
	// going to break anything.  They only cause surprises when loading.
	struct str_map *servers = get_servers_config (ctx);
	struct config_item *subtree = config_item_object ();
	str_map_set (servers, name, subtree);

	struct server *s = server_add (ctx, name, subtree);
	struct error *e = NULL;
	if (!irc_autofill_user_info (s, &e))
	{
		log_server_error (s, s->buffer,
			"#s: #s", "Failed to fill in user details", e->message);
		error_free (e);
	}
}

static void
server_remove (struct app_context *ctx, struct server *s)
{
	hard_assert (!irc_is_connected (s));

	if (s->buffer)
		buffer_remove_safe (ctx, s->buffer);

	relay_prepare_server_remove (ctx, s);
	relay_broadcast (ctx);

	struct str_map_unset_iter iter =
		str_map_unset_iter_make (&s->irc_buffer_map);
	struct buffer *buffer;
	while ((buffer = str_map_unset_iter_next (&iter)))
		buffer_remove_safe (ctx, buffer);
	str_map_unset_iter_free (&iter);

	hard_assert (!s->buffer);
	hard_assert (!s->irc_buffer_map.len);
	hard_assert (!s->irc_channels.len);
	soft_assert (!s->irc_users.len);

	str_map_set (get_servers_config (ctx), s->name, NULL);
	s->config = NULL;

	// This actually destroys the server as it's owned by the map
	str_map_set (&ctx->servers, s->name, NULL);
}

static void
server_rename (struct app_context *ctx, struct server *s, const char *new_name)
{
	hard_assert (!str_map_find (&ctx->servers, new_name));

	relay_prepare_server_rename (ctx, s, new_name);
	relay_broadcast (ctx);

	str_map_set (&ctx->servers, new_name,
		str_map_steal (&ctx->servers, s->name));

	struct str_map *servers = get_servers_config (ctx);
	str_map_set (servers, new_name, str_map_steal (servers, s->name));

	cstr_set (&s->name, xstrdup (new_name));
	buffer_rename (ctx, s->buffer, new_name);

	struct str_map_iter iter = str_map_iter_make (&s->irc_buffer_map);
	struct buffer *buffer;
	while ((buffer = str_map_iter_next (&iter)))
	{
		char *x = NULL;
		switch (buffer->type)
		{
		case BUFFER_PM:
			x = irc_make_buffer_name (s, buffer->user->nickname);
			break;
		case BUFFER_CHANNEL:
			x = irc_make_buffer_name (s, buffer->channel->name);
			break;
		default:
			hard_assert (!"unexpected type of server-related buffer");
		}
		buffer_rename (ctx, buffer, x);
		free (x);
	}
}

// --- Plugins -----------------------------------------------------------------

/// Returns the basename of the plugin's name without any extensions,
/// or NULL if the name isn't suitable (starts with a dot)
static char *
plugin_config_name (struct plugin *self)
{
	const char *begin = self->name;
	for (const char *p = begin; *p; )
		if (*p++ == '/')
			begin = p;

	size_t len = strcspn (begin, ".");
	if (!len)
		return NULL;

	// XXX: we might also allow arbitrary strings as object keys (except dots)
	char *copy = xstrndup (begin, len);
	for (char *p = copy; *p; p++)
		if (!config_tokenizer_is_word_char (*p))
			*p = '_';
	return copy;
}

// --- Lua ---------------------------------------------------------------------

// Each plugin has its own Lua state object, so that a/ they don't disturb each
// other and b/ unloading a plugin releases all resources.
//
// References to internal objects (buffers, servers) are all weak.

#ifdef HAVE_LUA

struct lua_plugin
{
	struct plugin super;                ///< The structure we're deriving
	struct app_context *ctx;            ///< Application context
	lua_State *L;                       ///< Lua state for the main thread

	struct lua_schema_item *schemas;    ///< Registered schema items
};

static void
lua_plugin_gc (struct plugin *self_)
{
	struct lua_plugin *self = (struct lua_plugin *) self_;
	lua_gc (self->L, LUA_GCCOLLECT, 0 /* Lua 5.3 required, 5.4 varargs */);
}

static void
lua_plugin_free (struct plugin *self_)
{
	struct lua_plugin *self = (struct lua_plugin *) self_;
	lua_close (self->L);
}

struct plugin_vtable lua_plugin_vtable =
{
	.gc   = lua_plugin_gc,
	.free = lua_plugin_free,
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// The registry can be used as a cache for weakly referenced objects

static bool
lua_cache_get (lua_State *L, void *object)
{
	lua_rawgetp (L, LUA_REGISTRYINDEX, object);
	if (lua_isnil (L, -1))
	{
		lua_pop (L, 1);
		return false;
	}
	return true;
}

static void
lua_cache_store (lua_State *L, void *object, int index)
{
	lua_pushvalue (L, index);
	lua_rawsetp (L, LUA_REGISTRYINDEX, object);
}

static void
lua_cache_invalidate (lua_State *L, void *object)
{
	lua_pushnil (L);
	lua_rawsetp (L, LUA_REGISTRYINDEX, object);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/// Append a traceback to all errors so that we can later extract it
static int
lua_plugin_error_handler (lua_State *L)
{
	luaL_traceback (L, L, luaL_checkstring (L, 1), 1);
	return 1;
}

static bool
lua_plugin_process_error (struct lua_plugin *self, const char *message,
	struct error **e)
{
	struct strv v = strv_make ();
	cstr_split (message, "\n", true, &v);

	if (v.len < 2)
		error_set (e, "%s", message);
	else
	{
		error_set (e, "%s", v.vector[0]);
		log_global_debug (self->ctx, "Lua: plugin \"#s\": #s",
			self->super.name, v.vector[1]);
		for (size_t i = 2; i < v.len; i++)
			log_global_debug (self->ctx, " #s", v.vector[i]);
	}

	strv_free (&v);
	return false;
}

/// Call a Lua function and process errors using our special error handler
static bool
lua_plugin_call (struct lua_plugin *self,
	int n_params, int n_results, struct error **e)
{
	// XXX: this may eventually be called from a thread, then this is wrong
	lua_State *L = self->L;

	// We need to pop the error handler at the end
	lua_pushcfunction (L, lua_plugin_error_handler);
	int error_handler_idx = -n_params - 2;
	lua_insert (L, error_handler_idx);

	if (!lua_pcall (L, n_params, n_results, error_handler_idx))
	{
		lua_remove (L, -n_results - 1);
		return true;
	}

	(void) lua_plugin_process_error (self, lua_tostring (L, -1), e);
	lua_pop (L, 2);
	return false;
}

/// Convenience function; replaces the "original" string or produces an error
static bool
lua_plugin_handle_string_filter_result (struct lua_plugin *self,
	char **original, bool utf8, struct error **e)
{
	lua_State *L = self->L;
	if (lua_isnil (L, -1))
	{
		cstr_set (original, NULL);
		return true;
	}
	if (!lua_isstring (L, -1))
		return error_set (e, "must return either a string or nil");

	size_t len;
	const char *processed = lua_tolstring (L, -1, &len);
	if (utf8 && !utf8_validate (processed, len))
		return error_set (e, "must return valid UTF-8");

	// Only replace the string if it's different
	if (strcmp (processed, *original))
		cstr_set (original, xstrdup (processed));
	return true;
}

static const char *
lua_plugin_check_utf8 (lua_State *L, int arg)
{
	size_t len;
	const char *s = luaL_checklstring (L, arg, &len);
	luaL_argcheck (L, utf8_validate (s, len), arg, "must be valid UTF-8");
	return s;
}

static void
lua_plugin_log_error
	(struct lua_plugin *self, const char *where, struct error *error)
{
	log_global_error (self->ctx, "Lua: plugin \"#s\": #s: #s",
		self->super.name, where, error->message);
	error_free (error);
}

/// Pop "n" values from the stack into a table, using their indexes as keys
static void
lua_plugin_pack (lua_State *L, int n)
{
	lua_createtable (L, n, 0);
	lua_insert (L, -n - 1);
	for (int i = n; i; i--)
		lua_rawseti (L, -i - 1, i);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
lua_plugin_kv (lua_State *L, const char *key, const char *value)
{
	lua_pushstring (L, value);
	lua_setfield (L, -2, key);
}

static void
lua_plugin_push_message (lua_State *L, const struct irc_message *msg)
{
	lua_createtable (L, 0, 4);

	lua_createtable (L, msg->tags.len, 0);
	struct str_map_iter iter = str_map_iter_make (&msg->tags);
	const char *value;
	while ((value = str_map_iter_next (&iter)))
		lua_plugin_kv (L, iter.link->key, value);
	lua_setfield (L, -2, "tags");

	// TODO: parse the prefix further?
	if (msg->prefix)   lua_plugin_kv (L, "prefix",  msg->prefix);
	if (msg->command)  lua_plugin_kv (L, "command", msg->command);

	lua_createtable (L, msg->params.len, 0);
	for (size_t i = 0; i < msg->params.len; i++)
	{
		lua_pushstring (L, msg->params.vector[i]);
		lua_rawseti (L, -2, i + 1);
	}
	lua_setfield (L, -2, "params");
}

static int
lua_plugin_parse (lua_State *L)
{
	struct irc_message msg;
	irc_parse_message (&msg, luaL_checkstring (L, 1));
	lua_plugin_push_message (L, &msg);
	irc_free_message (&msg);
	return 1;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Lua code can use weakly referenced wrappers for internal objects.

typedef struct weak_ref_link *
	(*lua_weak_ref_fn) (void *object, destroy_cb_fn cb, void *user_data);
typedef void (*lua_weak_unref_fn) (void *object, struct weak_ref_link **link);

struct lua_weak_info
{
	const char *name;                   ///< Metatable name
	struct ispect_field *ispect;        ///< Introspection data

	lua_weak_ref_fn ref;                ///< Weak link invalidator
	lua_weak_unref_fn unref;            ///< Weak link generator
};

struct lua_weak
{
	struct lua_plugin *plugin;          ///< The plugin we belong to
	struct lua_weak_info *info;         ///< Introspection data
	void *object;                       ///< The object
	struct weak_ref_link *weak_ref;     ///< A weak reference link
};

static void
lua_weak_invalidate (void *object, void *user_data)
{
	struct lua_weak *wrapper = user_data;
	wrapper->object = NULL;
	wrapper->weak_ref = NULL;
	// This can in theory call the GC, order isn't arbitrary here
	lua_cache_invalidate (wrapper->plugin->L, object);
}

static void
lua_weak_push (lua_State *L, struct lua_plugin *plugin, void *object,
	struct lua_weak_info *info)
{
	if (!object)
	{
		lua_pushnil (L);
		return;
	}
	if (lua_cache_get (L, object))
		return;

	struct lua_weak *wrapper = lua_newuserdata (L, sizeof *wrapper);
	luaL_setmetatable (L, info->name);
	wrapper->plugin = plugin;
	wrapper->info = info;
	wrapper->object = object;
	wrapper->weak_ref = NULL;
	if (info->ref)
		wrapper->weak_ref = info->ref (object, lua_weak_invalidate, wrapper);
	lua_cache_store (L, object, -1);
}

static int
lua_weak_gc (lua_State *L, const struct lua_weak_info *info)
{
	struct lua_weak *wrapper = luaL_checkudata (L, 1, info->name);
	if (wrapper->object)
	{
		lua_cache_invalidate (L, wrapper->object);
		if (info->unref)
			info->unref (wrapper->object, &wrapper->weak_ref);
		wrapper->object = NULL;
	}
	return 0;
}

static struct lua_weak *
lua_weak_deref (lua_State *L, const struct lua_weak_info *info)
{
	struct lua_weak *weak = luaL_checkudata (L, 1, info->name);
	luaL_argcheck (L, weak->object, 1, "dead reference used");
	return weak;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#define LUA_WEAK_DECLARE(id, metatable_id)                                     \
	static struct lua_weak_info lua_ ## id ## _info =                          \
	{                                                                          \
		.name   = metatable_id,                                                \
		.ispect = g_ ## id ## _ispect,                                         \
		.ref    = (lua_weak_ref_fn)   id ## _weak_ref,                         \
		.unref  = (lua_weak_unref_fn) id ## _weak_unref,                       \
	};

#define XLUA_USER_METATABLE    "user"     ///< Identifier for Lua metatable
#define XLUA_CHANNEL_METATABLE "channel"  ///< Identifier for Lua metatable
#define XLUA_BUFFER_METATABLE  "buffer"   ///< Identifier for Lua metatable
#define XLUA_SERVER_METATABLE  "server"   ///< Identifier for Lua metatable

LUA_WEAK_DECLARE (user,    XLUA_USER_METATABLE)
LUA_WEAK_DECLARE (channel, XLUA_CHANNEL_METATABLE)
LUA_WEAK_DECLARE (buffer,  XLUA_BUFFER_METATABLE)
LUA_WEAK_DECLARE (server,  XLUA_SERVER_METATABLE)

// The global context is kind of fake and doesn't have any ref-counting,
// however it's still very much an object
static struct lua_weak_info lua_ctx_info =
{
	.name = PROGRAM_NAME,
	.ispect = g_ctx_ispect,
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_user_gc (lua_State *L)
{
	return lua_weak_gc (L, &lua_user_info);
}

static int
lua_user_get_channels (lua_State *L)
{
	struct lua_weak *wrapper = lua_weak_deref (L, &lua_user_info);
	struct user *user = wrapper->object;

	int i = 1;
	lua_newtable (L);
	LIST_FOR_EACH (struct user_channel, iter, user->channels)
	{
		lua_weak_push (L, wrapper->plugin, iter->channel, &lua_channel_info);
		lua_rawseti (L, -2, i++);
	}
	return 1;
}

static luaL_Reg lua_user_table[] =
{
	{ "__gc",         lua_user_gc           },
	{ "get_channels", lua_user_get_channels },
	{ NULL,           NULL                  }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_channel_gc (lua_State *L)
{
	return lua_weak_gc (L, &lua_channel_info);
}

static int
lua_channel_get_users (lua_State *L)
{
	struct lua_weak *wrapper = lua_weak_deref (L, &lua_channel_info);
	struct channel *channel = wrapper->object;

	int i = 1;
	lua_newtable (L);
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
	{
		lua_createtable (L, 0, 2);
		lua_weak_push (L, wrapper->plugin, iter->user, &lua_user_info);
		lua_setfield (L, -2, "user");
		lua_plugin_kv (L, "prefixes", iter->prefixes);

		lua_rawseti (L, -2, i++);
	}
	return 1;
}

static luaL_Reg lua_channel_table[] =
{
	{ "__gc",      lua_channel_gc        },
	{ "get_users", lua_channel_get_users },
	{ NULL,        NULL                  }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_buffer_gc (lua_State *L)
{
	return lua_weak_gc (L, &lua_buffer_info);
}

static int
lua_buffer_log (lua_State *L)
{
	struct lua_weak *wrapper = lua_weak_deref (L, &lua_buffer_info);
	struct buffer *buffer = wrapper->object;
	const char *message = lua_plugin_check_utf8 (L, 2);
	log_full (wrapper->plugin->ctx, buffer->server, buffer,
		0, BUFFER_LINE_STATUS, "#s", message);
	return 0;
}

static int
lua_buffer_execute (lua_State *L)
{
	struct lua_weak *wrapper = lua_weak_deref (L, &lua_buffer_info);
	struct buffer *buffer = wrapper->object;
	const char *line = lua_plugin_check_utf8 (L, 2);
	(void) process_input_line (wrapper->plugin->ctx, buffer, line, 0);
	return 0;
}

static luaL_Reg lua_buffer_table[] =
{
	{ "__gc",        lua_buffer_gc          },
	{ "log",         lua_buffer_log         },
	{ "execute",     lua_buffer_execute     },
	{ NULL,          NULL                   }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_server_gc (lua_State *L)
{
	return lua_weak_gc (L, &lua_server_info);
}

static const char *
lua_server_state_to_string (enum server_state state)
{
	switch (state)
	{
	case IRC_DISCONNECTED: return "disconnected";
	case IRC_CONNECTING:   return "connecting";
	case IRC_CONNECTED:    return "connected";
	case IRC_REGISTERED:   return "registered";
	case IRC_CLOSING:      return "closing";
	case IRC_HALF_CLOSED:  return "half-closed";
	}
	return "?";
}

static int
lua_server_get_state (lua_State *L)
{
	struct lua_weak *wrapper = lua_weak_deref (L, &lua_server_info);
	struct server *server = wrapper->object;
	lua_pushstring (L, lua_server_state_to_string (server->state));
	return 1;
}

static int
lua_server_send (lua_State *L)
{
	struct lua_weak *wrapper = lua_weak_deref (L, &lua_server_info);
	struct server *server = wrapper->object;
	irc_send (server, "%s", luaL_checkstring (L, 2));
	return 0;
}

static luaL_Reg lua_server_table[] =
{
	{ "__gc",       lua_server_gc         },
	{ "get_state",  lua_server_get_state  },
	{ "send",       lua_server_send       },
	{ NULL,         NULL                  }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#define XLUA_HOOK_METATABLE "hook"      ///< Identifier for the Lua metatable

enum lua_hook_type
{
	XLUA_HOOK_DEFUNCT,                  ///< No longer functional
	XLUA_HOOK_INPUT,                    ///< Input hook
	XLUA_HOOK_IRC,                      ///< IRC hook
	XLUA_HOOK_PROMPT,                   ///< Prompt hook
	XLUA_HOOK_COMPLETION,               ///< Autocomplete
};

struct lua_hook
{
	struct lua_plugin *plugin;          ///< The plugin we belong to
	enum lua_hook_type type;            ///< Type of the hook
	int ref_callback;                   ///< Reference to the callback
	union
	{
		struct hook hook;               ///< Hook base structure
		struct input_hook input_hook;   ///< Input hook
		struct irc_hook irc_hook;       ///< IRC hook
		struct prompt_hook prompt_hook; ///< IRC hook
		struct completion_hook c_hook;  ///< Autocomplete hook
	}
	data;                               ///< Hook data
};

static int
lua_hook_unhook (lua_State *L)
{
	struct lua_hook *hook = luaL_checkudata (L, 1, XLUA_HOOK_METATABLE);
	switch (hook->type)
	{
	case XLUA_HOOK_INPUT:
		LIST_UNLINK (hook->plugin->ctx->input_hooks,      &hook->data.hook);
		break;
	case XLUA_HOOK_IRC:
		LIST_UNLINK (hook->plugin->ctx->irc_hooks,        &hook->data.hook);
		break;
	case XLUA_HOOK_PROMPT:
		LIST_UNLINK (hook->plugin->ctx->prompt_hooks,     &hook->data.hook);
		refresh_prompt (hook->plugin->ctx);
		break;
	case XLUA_HOOK_COMPLETION:
		LIST_UNLINK (hook->plugin->ctx->completion_hooks, &hook->data.hook);
		break;
	default:
		hard_assert (!"invalid hook type");
	case XLUA_HOOK_DEFUNCT:
		break;
	}

	luaL_unref (L, LUA_REGISTRYINDEX, hook->ref_callback);
	hook->ref_callback = LUA_REFNIL;

	// The hook no longer has to stay alive
	hook->type = XLUA_HOOK_DEFUNCT;
	lua_cache_invalidate (L, hook);
	return 0;
}

// The hook dies either when the plugin requests it or at plugin unload
static luaL_Reg lua_hook_table[] =
{
	{ "unhook", lua_hook_unhook },
	{ "__gc",   lua_hook_unhook },
	{ NULL,     NULL            }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static char *
lua_input_hook_filter (struct input_hook *self, struct buffer *buffer,
	char *input)
{
	struct lua_hook *hook =
		CONTAINER_OF (self, struct lua_hook, data.input_hook);
	struct lua_plugin *plugin = hook->plugin;
	lua_State *L = plugin->L;

	lua_rawgeti (L, LUA_REGISTRYINDEX, hook->ref_callback);
	lua_rawgetp (L, LUA_REGISTRYINDEX, hook);             // 1: hook
	lua_weak_push (L, plugin, buffer, &lua_buffer_info);  // 2: buffer
	lua_pushstring (L, input);                            // 3: input

	struct error *e = NULL;
	if (lua_plugin_call (plugin, 3, 1, &e))
	{
		lua_plugin_handle_string_filter_result (plugin, &input, true, &e);
		lua_pop (L, 1);
	}
	if (e)
		lua_plugin_log_error (plugin, "input hook", e);
	return input;
}

static char *
lua_irc_hook_filter (struct irc_hook *self, struct server *s, char *message)
{
	struct lua_hook *hook =
		CONTAINER_OF (self, struct lua_hook, data.irc_hook);
	struct lua_plugin *plugin = hook->plugin;
	lua_State *L = plugin->L;

	lua_rawgeti (L, LUA_REGISTRYINDEX, hook->ref_callback);
	lua_rawgetp (L, LUA_REGISTRYINDEX, hook);        // 1: hook
	lua_weak_push (L, plugin, s, &lua_server_info);  // 2: server
	lua_pushstring (L, message);                     // 3: message

	struct error *e = NULL;
	if (lua_plugin_call (plugin, 3, 1, &e))
	{
		lua_plugin_handle_string_filter_result (plugin, &message, false, &e);
		lua_pop (L, 1);
	}
	if (e)
		lua_plugin_log_error (plugin, "IRC hook", e);
	return message;
}

static char *
lua_prompt_hook_make (struct prompt_hook *self)
{
	struct lua_hook *hook =
		CONTAINER_OF (self, struct lua_hook, data.prompt_hook);
	struct lua_plugin *plugin = hook->plugin;
	lua_State *L = plugin->L;

	lua_rawgeti (L, LUA_REGISTRYINDEX, hook->ref_callback);
	lua_rawgetp (L, LUA_REGISTRYINDEX, hook);  // 1: hook

	struct error *e = NULL;
	char *prompt = xstrdup ("");
	if (lua_plugin_call (plugin, 1, 1, &e))
	{
		lua_plugin_handle_string_filter_result (plugin, &prompt, true, &e);
		lua_pop (L, 1);
	}
	if (e)
		lua_plugin_log_error (plugin, "prompt hook", e);
	return prompt;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
lua_plugin_push_completion (lua_State *L, struct completion *data)
{
	lua_createtable (L, 0, 3);

	lua_pushstring (L, data->line);
	lua_setfield (L, -2, "line");

	lua_createtable (L, data->words_len, 0);
	for (size_t i = 0; i < data->words_len; i++)
	{
		lua_pushlstring (L, data->line + data->words[i].start,
			data->words[i].end - data->words[i].start);
		lua_rawseti (L, -2, i + 1);
	}
	lua_setfield (L, -2, "words");

	lua_pushinteger (L, data->location);
	lua_setfield (L, -2, "location");
}

static bool
lua_completion_hook_process_value (lua_State *L, struct strv *output,
	struct error **e)
{
	if (lua_type (L, -1) != LUA_TSTRING)
	{
		return error_set (e,
			"%s: %s", "invalid type", lua_typename (L, lua_type (L, -1)));
	}

	size_t len;
	const char *value = lua_tolstring (L, -1, &len);
	if (!utf8_validate (value, len))
		return error_set (e, "must be valid UTF-8");

	strv_append (output, value);
	return true;
}

static bool
lua_completion_hook_process (lua_State *L, struct strv *output,
	struct error **e)
{
	if (lua_isnil (L, -1))
		return true;
	if (!lua_istable (L, -1))
		return error_set (e, "must return either a table or nil");

	bool success = true;
	for (lua_Integer i = 1; success && lua_rawgeti (L, -1, i); i++)
		if ((success = lua_completion_hook_process_value (L, output, e)))
			lua_pop (L, 1);
	lua_pop (L, 1);
	return success;
}

static void
lua_completion_hook_complete (struct completion_hook *self,
	struct completion *data, const char *word, struct strv *output)
{
	struct lua_hook *hook =
		CONTAINER_OF (self, struct lua_hook, data.c_hook);
	struct lua_plugin *plugin = hook->plugin;
	lua_State *L = plugin->L;

	lua_rawgeti (L, LUA_REGISTRYINDEX, hook->ref_callback);
	lua_rawgetp (L, LUA_REGISTRYINDEX, hook);  // 1: hook
	lua_plugin_push_completion (L, data);      // 2: data

	lua_weak_push (L, plugin, plugin->ctx->current_buffer, &lua_buffer_info);
	lua_setfield (L, -2, "buffer");

	lua_pushstring (L, word);                  // 3: word

	struct error *e = NULL;
	if (lua_plugin_call (plugin, 3, 1, &e))
	{
		lua_completion_hook_process (L, output, &e);
		lua_pop (L, 1);
	}
	if (e)
		lua_plugin_log_error (plugin, "autocomplete hook", e);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static struct lua_hook *
lua_plugin_push_hook (lua_State *L, struct lua_plugin *plugin,
	int callback_index, enum lua_hook_type type, int priority)
{
	luaL_checktype (L, callback_index, LUA_TFUNCTION);

	struct lua_hook *hook = lua_newuserdata (L, sizeof *hook);
	luaL_setmetatable (L, XLUA_HOOK_METATABLE);
	memset (hook, 0, sizeof *hook);
	hook->data.hook.priority = priority;
	hook->type = type;
	hook->plugin = plugin;

	lua_pushvalue (L, callback_index);
	hook->ref_callback = luaL_ref (L, LUA_REGISTRYINDEX);

	// Make sure the hook doesn't get garbage collected and return it
	lua_cache_store (L, hook, -1);
	return hook;
}

static int
lua_plugin_hook_input (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	struct lua_hook *hook = lua_plugin_push_hook
		(L, plugin, 1, XLUA_HOOK_INPUT, luaL_optinteger (L, 2, 0));
	hook->data.input_hook.filter = lua_input_hook_filter;
	plugin->ctx->input_hooks =
		hook_insert (plugin->ctx->input_hooks, &hook->data.hook);
	return 1;
}

static int
lua_plugin_hook_irc (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	struct lua_hook *hook = lua_plugin_push_hook
		(L, plugin, 1, XLUA_HOOK_IRC, luaL_optinteger (L, 2, 0));
	hook->data.irc_hook.filter = lua_irc_hook_filter;
	plugin->ctx->irc_hooks =
		hook_insert (plugin->ctx->irc_hooks, &hook->data.hook);
	return 1;
}

static int
lua_plugin_hook_prompt (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	struct lua_hook *hook = lua_plugin_push_hook
		(L, plugin, 1, XLUA_HOOK_PROMPT, luaL_optinteger (L, 2, 0));
	hook->data.prompt_hook.make = lua_prompt_hook_make;
	plugin->ctx->prompt_hooks =
		hook_insert (plugin->ctx->prompt_hooks, &hook->data.hook);
	refresh_prompt (plugin->ctx);
	return 1;
}

static int
lua_plugin_hook_completion (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	struct lua_hook *hook = lua_plugin_push_hook
		(L, plugin, 1, XLUA_HOOK_COMPLETION, luaL_optinteger (L, 2, 0));
	hook->data.c_hook.complete = lua_completion_hook_complete;
	plugin->ctx->completion_hooks =
		hook_insert (plugin->ctx->completion_hooks, &hook->data.hook);
	return 1;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

#define XLUA_SCHEMA_METATABLE "schema"  ///< Identifier for the Lua metatable

struct lua_schema_item
{
	LIST_HEADER (struct lua_schema_item)

	struct lua_plugin *plugin;          ///< The plugin we belong to
	struct config_item *item;           ///< The item managed by the schema
	struct config_schema schema;        ///< Schema itself

	int ref_validate;                   ///< Reference to "validate" callback
	int ref_on_change;                  ///< Reference to "on_change" callback
};

static void
lua_schema_item_discard (struct lua_schema_item *self)
{
	if (self->item)
	{
		self->item->schema = NULL;
		self->item->user_data = NULL;
		self->item = NULL;
		LIST_UNLINK (self->plugin->schemas, self);
	}

	// Now that we've disconnected from the item, allow garbage collection
	lua_cache_invalidate (self->plugin->L, self);
}

static int
lua_schema_item_gc (lua_State *L)
{
	struct lua_schema_item *self =
		luaL_checkudata (L, 1, XLUA_SCHEMA_METATABLE);
	lua_schema_item_discard (self);

	free ((char *) self->schema.name);
	free ((char *) self->schema.comment);
	free ((char *) self->schema.default_);

	luaL_unref (L, LUA_REGISTRYINDEX, self->ref_validate);
	luaL_unref (L, LUA_REGISTRYINDEX, self->ref_on_change);
	return 0;
}

static luaL_Reg lua_schema_table[] =
{
	{ "__gc", lua_schema_item_gc },
	{ NULL,   NULL               }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/// Unfortunately this has the same problem as JSON libraries in that Lua
/// cannot store null values in containers (it has no distinct "undefined" type)
static void
lua_plugin_push_config_item (lua_State *L, const struct config_item *item)
{
	switch (item->type)
	{
	case CONFIG_ITEM_NULL:
		lua_pushnil (L);
		break;
	case CONFIG_ITEM_OBJECT:
	{
		lua_createtable (L, 0, item->value.object.len);

		struct str_map_iter iter = str_map_iter_make (&item->value.object);
		struct config_item *child;
		while ((child = str_map_iter_next (&iter)))
		{
			lua_plugin_push_config_item (L, child);
			lua_setfield (L, -2, iter.link->key);
		}
		break;
	}
	case CONFIG_ITEM_BOOLEAN:
		lua_pushboolean (L, item->value.boolean);
		break;
	case CONFIG_ITEM_INTEGER:
		lua_pushinteger (L, item->value.integer);
		break;
	case CONFIG_ITEM_STRING:
	case CONFIG_ITEM_STRING_ARRAY:
		lua_pushlstring (L, item->value.string.str, item->value.string.len);
		break;
	}
}

static bool
lua_schema_item_validate (const struct config_item *item, struct error **e)
{
	struct lua_schema_item *self = item->user_data;
	if (self->ref_validate == LUA_REFNIL)
		return true;

	lua_State *L = self->plugin->L;
	lua_rawgeti (L, LUA_REGISTRYINDEX, self->ref_validate);
	lua_plugin_push_config_item (L, item);

	// The callback can make use of error("...", 0) to produce nice messages
	return lua_plugin_call (self->plugin, 1, 0, e);
}

static void
lua_schema_item_on_change (struct config_item *item)
{
	struct lua_schema_item *self = item->user_data;
	if (self->ref_on_change == LUA_REFNIL)
		return;

	lua_State *L = self->plugin->L;
	lua_rawgeti (L, LUA_REGISTRYINDEX, self->ref_on_change);
	lua_plugin_push_config_item (L, item);

	struct error *e = NULL;
	if (!lua_plugin_call (self->plugin, 1, 0, &e))
		lua_plugin_log_error (self->plugin, "schema on_change", e);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_plugin_decode_config_item_type (const char *type)
{
	if (!strcmp (type, "null"))         return CONFIG_ITEM_NULL;
	if (!strcmp (type, "object"))       return CONFIG_ITEM_OBJECT;
	if (!strcmp (type, "boolean"))      return CONFIG_ITEM_BOOLEAN;
	if (!strcmp (type, "integer"))      return CONFIG_ITEM_INTEGER;
	if (!strcmp (type, "string"))       return CONFIG_ITEM_STRING;
	if (!strcmp (type, "string_array")) return CONFIG_ITEM_STRING_ARRAY;
	return -1;
}

static bool
lua_plugin_check_field (lua_State *L, int idx, const char *name,
	int expected, bool optional)
{
	int found = lua_getfield (L, idx, name);
	if (found == expected)
		return true;
	if (optional && found == LUA_TNIL)
		return false;

	const char *message = optional
		? "invalid field \"%s\" (found: %s, expected: %s or nil)"
		: "invalid or missing field \"%s\" (found: %s, expected: %s)";
	return luaL_error (L, message, name,
		lua_typename (L, found), lua_typename (L, expected));
}

static int
lua_plugin_add_config_schema (lua_State *L, struct lua_plugin *plugin,
	struct config_item *subtree, const char *name)
{
	struct config_item *item = str_map_find (&subtree->value.object, name);
	// This should only ever happen because of a conflict with another plugin;
	// this is the price we pay for simplicity
	if (item && item->schema)
	{
		struct lua_schema_item *owner = item->user_data;
		return luaL_error (L, "conflicting schema item: %s (owned by: %s)",
			name, owner->plugin->super.name);
	}

	// Create and initialize a full userdata wrapper for the schema item
	struct lua_schema_item *self = lua_newuserdata (L, sizeof *self);
	luaL_setmetatable (L, XLUA_SCHEMA_METATABLE);
	memset (self, 0, sizeof *self);

	self->plugin = plugin;
	self->ref_on_change = LUA_REFNIL;
	self->ref_validate = LUA_REFNIL;

	struct config_schema *schema = &self->schema;
	schema->name      = xstrdup (name);
	schema->comment   = NULL;
	schema->default_  = NULL;
	schema->type      = CONFIG_ITEM_NULL;
	schema->on_change = lua_schema_item_on_change;
	schema->validate  = lua_schema_item_validate;

	// Try to update the defaults with values provided by the plugin
	int values = lua_absindex (L, -2);
	(void) lua_plugin_check_field (L, values, "type", LUA_TSTRING, false);
	int item_type = schema->type =
		lua_plugin_decode_config_item_type (lua_tostring (L, -1));
	if (item_type == -1)
		return luaL_error (L, "invalid type of schema item");

	if (lua_plugin_check_field (L, values, "comment",   LUA_TSTRING, true))
		schema->comment = xstrdup (lua_tostring (L, -1));
	if (lua_plugin_check_field (L, values, "default",   LUA_TSTRING, true))
		schema->default_ = xstrdup (lua_tostring (L, -1));

	lua_pop (L, 3);

	(void) lua_plugin_check_field (L, values, "on_change", LUA_TFUNCTION, true);
	self->ref_on_change = luaL_ref (L, LUA_REGISTRYINDEX);
	(void) lua_plugin_check_field (L, values, "validate",  LUA_TFUNCTION, true);
	self->ref_validate = luaL_ref (L, LUA_REGISTRYINDEX);

	// Try to install the created schema item into our configuration
	struct error *warning = NULL, *e = NULL;
	item = config_schema_initialize_item
		(&self->schema, subtree, self, &warning, &e);

	if (warning)
	{
		log_global_error (plugin->ctx, "Lua: plugin \"#s\": #s",
			plugin->super.name, warning->message);
		error_free (warning);
	}
	if (e)
	{
		const char *error = lua_pushstring (L, e->message);
		error_free (e);
		return luaL_error (L, "%s", error);
	}

	self->item = item;
	LIST_PREPEND (plugin->schemas, self);

	// On the stack there should be the schema table and the resulting object;
	// we need to make sure Lua doesn't GC the second and get rid of them both
	lua_cache_store (L, self, -1);
	lua_pop (L, 2);
	return 0;
}

static int
lua_plugin_setup_config (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	luaL_checktype (L, 1, LUA_TTABLE);

	struct app_context *ctx = plugin->ctx;
	char *config_name = plugin_config_name (&plugin->super);
	if (!config_name)
		return luaL_error (L, "unsuitable plugin name");

	struct str_map *plugins = get_plugins_config (ctx);
	struct config_item *subtree = str_map_find (plugins, config_name);
	if (!subtree || subtree->type != CONFIG_ITEM_OBJECT)
		str_map_set (plugins, config_name, (subtree = config_item_object ()));
	free (config_name);

	LIST_FOR_EACH (struct lua_schema_item, iter, plugin->schemas)
		lua_schema_item_discard (iter);

	// Load all schema items and apply them to the plugin's subtree
	lua_pushnil (L);
	while (lua_next (L, 1))
	{
		if (lua_type (L, -2) != LUA_TSTRING
		 || lua_type (L, -1) != LUA_TTABLE)
			return luaL_error (L, "%s: %s -> %s", "invalid types",
				lua_typename (L, lua_type (L, -2)),
				lua_typename (L, lua_type (L, -1)));
		lua_plugin_add_config_schema (L, plugin, subtree, lua_tostring (L, -2));
	}

	// Let the plugin read out configuration via on_change callbacks
	config_schema_call_changed (subtree);
	return 0;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/// Identifier for the Lua metatable
#define XLUA_CONNECTION_METATABLE "connection"

struct lua_connection
{
	struct lua_plugin *plugin;          ///< The plugin we belong to
	struct poller_fd socket_event;      ///< Socket is ready
	int socket_fd;                      ///< Underlying connected socket

	bool got_eof;                       ///< Half-closed by remote host
	bool closing;                       ///< We're closing the connection

	struct str read_buffer;             ///< Read buffer
	struct str write_buffer;            ///< Write buffer
};

static void
lua_connection_update_poller (struct lua_connection *self)
{
	poller_fd_set (&self->socket_event,
		self->write_buffer.len ? (POLLIN | POLLOUT) : POLLIN);
}

static int
lua_connection_send (lua_State *L)
{
	struct lua_connection *self =
		luaL_checkudata (L, 1, XLUA_CONNECTION_METATABLE);
	if (self->socket_fd == -1)
		return luaL_error (L, "connection has been closed");

	size_t len;
	const char *s = luaL_checklstring (L, 2, &len);
	str_append_data (&self->write_buffer, s, len);
	lua_connection_update_poller (self);
	return 0;
}

static void
lua_connection_discard (struct lua_connection *self)
{
	if (self->socket_fd != -1)
	{
		poller_fd_reset (&self->socket_event);
		xclose (self->socket_fd);
		self->socket_fd = -1;

		str_free (&self->read_buffer);
		str_free (&self->write_buffer);
	}

	// Connection is dead, we don't need to hold onto any resources anymore
	lua_cache_invalidate (self->plugin->L, self);
}

static int
lua_connection_close (lua_State *L)
{
	struct lua_connection *self =
		luaL_checkudata (L, 1, XLUA_CONNECTION_METATABLE);
	if (self->socket_fd != -1)
	{
		self->closing = true;
		// NOTE: this seems to do nothing on Linux
		(void) shutdown (self->socket_fd, SHUT_RD);

		// Right now we want to wait until all data is flushed to the socket
		// and can't call close() here immediately -- a rewrite to use async
		// would enable the user to await on either :send() or :flush();
		// a successful send() doesn't necessarily mean anything though
		if (!self->write_buffer.len)
			lua_connection_discard (self);
	}
	return 0;
}

static int
lua_connection_gc (lua_State *L)
{
	lua_connection_discard (luaL_checkudata (L, 1, XLUA_CONNECTION_METATABLE));
	return 0;
}

static luaL_Reg lua_connection_table[] =
{
	{ "send",  lua_connection_send  },
	{ "close", lua_connection_close },
	{ "__gc",  lua_connection_gc    },
	{ NULL,    NULL                 }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_connection_check_fn (lua_State *L)
{
	lua_plugin_check_field (L, 1, luaL_checkstring (L, 2), LUA_TFUNCTION, true);
	return 1;
}

// We need to run it in a protected environment because of lua_getfield()
static bool
lua_connection_cb_lookup (struct lua_connection *self, const char *name,
	struct error **e)
{
	lua_State *L = self->plugin->L;
	lua_pushcfunction (L, lua_connection_check_fn);
	hard_assert (lua_cache_get (L, self));
	lua_pushstring (L, name);
	return lua_plugin_call (self->plugin, 2, 1, e);
}

// Ideally lua_connection_cb_lookup() would return a ternary value
static bool
lua_connection_eat_nil (struct lua_connection *self)
{
	if (lua_toboolean (self->plugin->L, -1))
		return false;
	lua_pop (self->plugin->L, 1);
	return true;
}

static bool
lua_connection_invoke_on_data (struct lua_connection *self, struct error **e)
{
	if (!lua_connection_cb_lookup (self, "on_data", e))
		return false;
	if (lua_connection_eat_nil (self))
		return true;

	lua_pushlstring (self->plugin->L,
		self->read_buffer.str, self->read_buffer.len);
	return lua_plugin_call (self->plugin, 1, 0, e);
}

static bool
lua_connection_invoke_on_eof (struct lua_connection *self, struct error **e)
{
	if (!lua_connection_cb_lookup (self, "on_eof", e))
		return false;
	if (lua_connection_eat_nil (self))
		return true;
	return lua_plugin_call (self->plugin, 0, 0, e);
}

static bool
lua_connection_invoke_on_error (struct lua_connection *self,
	const char *error, struct error **e)
{
	// XXX: not sure if ignoring errors after :close() is always desired;
	//   code might want to make sure that data are transferred successfully
	if (!self->closing
	 && lua_connection_cb_lookup (self, "on_error", e)
	 && !lua_connection_eat_nil (self))
	{
		lua_pushstring (self->plugin->L, error);
		lua_plugin_call (self->plugin, 1, 0, e);
	}
	return false;
}

static bool
lua_connection_try_read (struct lua_connection *self, struct error **e)
{
	// Avoid the read call when it's obviously not going to return any data
	// and would only cause unwanted invocation of callbacks
	if (self->closing || self->got_eof)
		return true;

	enum socket_io_result read_result =
		socket_io_try_read (self->socket_fd, &self->read_buffer);
	const char *error = strerror (errno);

	// Dispatch any data that we got before an EOF or any error
	if (self->read_buffer.len)
	{
		if (!lua_connection_invoke_on_data (self, e))
			return false;
		str_reset (&self->read_buffer);
	}

	if (read_result == SOCKET_IO_EOF)
	{
		if (!lua_connection_invoke_on_eof (self, e))
			return false;
		self->got_eof = true;
	}
	if (read_result == SOCKET_IO_ERROR)
		return lua_connection_invoke_on_error (self, error, e);
	return true;
}

static bool
lua_connection_try_write (struct lua_connection *self, struct error **e)
{
	enum socket_io_result write_result =
		socket_io_try_write (self->socket_fd, &self->write_buffer);
	const char *error = strerror (errno);

	if (write_result == SOCKET_IO_ERROR)
		return lua_connection_invoke_on_error (self, error, e);
	return !self->closing || self->write_buffer.len;
}

static void
lua_connection_on_ready (const struct pollfd *pfd, struct lua_connection *self)
{
	(void) pfd;

	// Hold a reference so that it doesn't get collected on close()
	hard_assert (lua_cache_get (self->plugin->L, self));

	struct error *e = NULL;
	bool keep = lua_connection_try_read (self, &e)
		&& lua_connection_try_write (self, &e);
	if (e)
		lua_plugin_log_error (self->plugin, "network I/O", e);
	if (keep)
		lua_connection_update_poller (self);
	else
		lua_connection_discard (self);

	lua_pop (self->plugin->L, 1);
}

static struct lua_connection *
lua_plugin_push_connection (struct lua_plugin *plugin, int socket_fd)
{
	lua_State *L = plugin->L;

	struct lua_connection *self = lua_newuserdata (L, sizeof *self);
	luaL_setmetatable (L, XLUA_CONNECTION_METATABLE);
	memset (self, 0, sizeof *self);
	self->plugin = plugin;

	set_blocking (socket_fd, false);
	self->socket_event = poller_fd_make
		(&plugin->ctx->poller, (self->socket_fd = socket_fd));
	self->socket_event.dispatcher = (poller_fd_fn) lua_connection_on_ready;
	self->socket_event.user_data = self;
	poller_fd_set (&self->socket_event, POLLIN);

	self->read_buffer = str_make ();
	self->write_buffer = str_make ();

	// Make sure the connection doesn't get garbage collected and return it
	lua_cache_store (L, self, -1);
	return self;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// The script can create as many wait channels as wanted.  They only actually
// do anything once they get yielded to the main lua_resume() call.

/// Identifier for the Lua metatable
#define XLUA_WCHANNEL_METATABLE "wchannel"

struct lua_wait_channel
{
	LIST_HEADER (struct lua_wait_channel)

	struct lua_task *task;              ///< The task we're active in

	/// Check if the event is ready and eventually push values to the thread;
	/// the channel then may release any resources
	bool (*check) (struct lua_wait_channel *self);

	/// Release all resources held by the subclass
	void (*cleanup) (struct lua_wait_channel *self);
};

static int
lua_wchannel_gc (lua_State *L)
{
	struct lua_wait_channel *self =
		luaL_checkudata (L, 1, XLUA_WCHANNEL_METATABLE);
	if (self->cleanup)
		self->cleanup (self);
	return 0;
}

static luaL_Reg lua_wchannel_table[] =
{
	{ "__gc", lua_wchannel_gc },
	{ NULL,   NULL            }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// A task encapsulates a thread so that wait channels yielded from its main
// function get waited upon by the event loop

#define XLUA_TASK_METATABLE  "task"     ///< Identifier for the Lua metatable

struct lua_task
{
	LIST_HEADER (struct lua_task)

	struct lua_plugin *plugin;          ///< The plugin we belong to
	lua_State *thread;                  ///< Lua thread
	struct lua_wait_channel *active;    ///< Channels we're waiting on
	struct poller_idle idle;            ///< Idle job
};

static void
lua_task_unregister_channels (struct lua_task *self)
{
	LIST_FOR_EACH (struct lua_wait_channel, iter, self->active)
	{
		iter->task = NULL;
		LIST_UNLINK (self->active, iter);
		lua_cache_invalidate (self->plugin->L, iter);
	}
}

static void
lua_task_cancel_internal (struct lua_task *self)
{
	if (self->thread)
	{
		lua_cache_invalidate (self->plugin->L, self->thread);
		self->thread = NULL;
	}
	lua_task_unregister_channels (self);
	poller_idle_reset (&self->idle);

	// The task no longer has to stay alive
	lua_cache_invalidate (self->plugin->L, self);
}

static int
lua_task_cancel (lua_State *L)
{
	struct lua_task *self = luaL_checkudata (L, 1, XLUA_TASK_METATABLE);
	// We could also yield and make lua_task_resume() check "self->thread",
	// however the main issue here is that the script should just return
	luaL_argcheck (L, L != self->thread, 1,
		"cannot cancel task from within itself");
	lua_task_cancel_internal (self);
	return 0;
}

#define lua_task_wakeup(self) poller_idle_set (&(self)->idle)

static bool
lua_task_schedule (struct lua_task *self, int n, struct error **e)
{
	lua_State *L = self->thread;
	for (int i = -1; -i <= n; i--)
	{
		struct lua_wait_channel *channel =
			luaL_testudata (L, i, XLUA_WCHANNEL_METATABLE);
		if (!channel)
			return error_set (e, "bad argument #%d to yield: %s", -i + n + 1,
				"tasks can only yield wait channels");
		if (channel->task)
			return error_set (e, "bad argument #%d to yield: %s", -i + n + 1,
				"wait channels can only be active in one task at most");
	}
	for (int i = -1; -i <= n; i--)
	{
		// Quietly ignore duplicate channels
		struct lua_wait_channel *channel = lua_touserdata (L, i);
		if (channel->task)
			continue;

		// By going in reverse the list ends up in the right order
		channel->task = self;
		LIST_PREPEND (self->active, channel);
		lua_cache_store (self->plugin->L, channel, i);
	}
	lua_pop (L, n);

	// There doesn't have to be a single channel
	// We can also be waiting on a channel that is already ready
	lua_task_wakeup (self);
	return true;
}

static void
lua_task_resume (struct lua_task *self, int index)
{
	lua_State *L = self->thread;
	bool waiting_on_multiple = self->active && self->active->next;

	// Since we've ended the wait, we don't need to hold on to them anymore
	lua_task_unregister_channels (self);

	// On the first run we also have the main function on the stack,
	// before any initial arguments
	int n = lua_gettop (L) - (lua_status (L) == LUA_OK);

	// Pack the values in a table and prepend the index of the channel, so that
	// the caller doesn't need to care about the number of return values
	if (waiting_on_multiple)
	{
		lua_plugin_pack (L, n);
		lua_pushinteger (L, index);
		lua_insert (L, -2);
		n = 2;
	}

#if LUA_VERSION_NUM >= 504
	int nresults = 0;
	int res = lua_resume (L, NULL, n, &nresults);
#else
	int res = lua_resume (L, NULL, n);
	int nresults = lua_gettop (L);
#endif

	struct error *error = NULL;
	if (res == LUA_YIELD)
	{
		// AFAIK we don't get any good error context information from here
		if (lua_task_schedule (self, nresults, &error))
			return;
	}
	// For simplicity ignore any results from successful returns
	else if (res != LUA_OK)
	{
		luaL_traceback (L, L, lua_tostring (L, -1), 0 /* or 1? */);
		lua_plugin_process_error (self->plugin, lua_tostring (L, -1), &error);
		lua_pop (L, 2);
	}
	if (error)
		lua_plugin_log_error (self->plugin, "task", error);
	lua_task_cancel_internal (self);
}

static void
lua_task_check (struct lua_task *self)
{
	poller_idle_reset (&self->idle);

	lua_Integer i = 0;
	LIST_FOR_EACH (struct lua_wait_channel, iter, self->active)
	{
		i++;
		if (iter->check (iter))
		{
			lua_task_resume (self, i);
			return;
		}
	}
	if (!self->active)
		lua_task_resume (self, i);
}

// The task dies either when it finishes, it is cancelled, or at plugin unload
static luaL_Reg lua_task_table[] =
{
	{ "cancel", lua_task_cancel },
	{ "__gc",   lua_task_cancel },
	{ NULL,     NULL            }
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct lua_wait_timer
{
	struct lua_wait_channel super;      ///< The structure we're deriving
	struct poller_timer timer;          ///< Timer event
	bool expired;                       ///< Whether the timer has expired
};

static bool
lua_wait_timer_check (struct lua_wait_channel *wchannel)
{
	struct lua_wait_timer *self =
		CONTAINER_OF (wchannel, struct lua_wait_timer, super);
	return self->super.task && self->expired;
}

static void
lua_wait_timer_cleanup (struct lua_wait_channel *wchannel)
{
	struct lua_wait_timer *self =
		CONTAINER_OF (wchannel, struct lua_wait_timer, super);
	poller_timer_reset (&self->timer);
}

static void
lua_wait_timer_dispatch (struct lua_wait_timer *self)
{
	self->expired = true;
	if (self->super.task)
		lua_task_wakeup (self->super.task);
}

static int
lua_plugin_push_wait_timer (struct lua_plugin *plugin, lua_State *L,
	lua_Integer timeout)
{
	struct lua_wait_timer *self = lua_newuserdata (L, sizeof *self);
	luaL_setmetatable (L, XLUA_WCHANNEL_METATABLE);
	memset (self, 0, sizeof *self);

	self->super.check = lua_wait_timer_check;
	self->super.cleanup = lua_wait_timer_cleanup;

	self->timer = poller_timer_make (&plugin->ctx->poller);
	self->timer.dispatcher = (poller_timer_fn) lua_wait_timer_dispatch;
	self->timer.user_data = self;

	if (timeout)
		poller_timer_set (&self->timer, timeout);
	else
		self->expired = true;
	return 1;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

struct lua_wait_dial
{
	struct lua_wait_channel super;      ///< The structure we're deriving

	struct lua_plugin *plugin;          ///< The plugin we belong to
	struct connector connector;         ///< Connector object
	bool active;                        ///< Whether the connector is alive

	struct lua_connection *connection;  ///< Established connection
	char *hostname;                     ///< Target hostname
	char *last_error;                   ///< Connecting error, if any
};

static bool
lua_wait_dial_check (struct lua_wait_channel *wchannel)
{
	struct lua_wait_dial *self =
		CONTAINER_OF (wchannel, struct lua_wait_dial, super);

	lua_State *L = self->super.task->thread;
	if (self->connection)
	{
		// FIXME: this way the connection may leak -- we pass the value to the
		//   task manager on the stack and forget about it but still leave the
		//   connection in the cache.  That is because right now, when Lua code
		//   sets up callbacks in the connection object and returns, it might
		//   get otherwise GC'd since nothing else keeps referencing it.
		//   By rewriting lua_connection using async, tasks and wait channels
		//   would hold a reference, allowing us to remove it from the cache.
		lua_cache_get (L, self->connection);
		lua_pushstring (L, self->hostname);
		self->connection = NULL;
	}
	else if (self->last_error)
	{
		lua_pushnil (L);
		lua_pushnil (L);
		lua_pushstring (L, self->last_error);
	}
	else
		return false;
	return true;
}

static void
lua_wait_dial_cancel (struct lua_wait_dial *self)
{
	if (self->active)
	{
		connector_free (&self->connector);
		self->active = false;
	}
}

static void
lua_wait_dial_cleanup (struct lua_wait_channel *wchannel)
{
	struct lua_wait_dial *self =
		CONTAINER_OF (wchannel, struct lua_wait_dial, super);

	lua_wait_dial_cancel (self);
	if (self->connection)
		lua_connection_discard (self->connection);

	free (self->hostname);
	free (self->last_error);
}

static void
lua_wait_dial_on_connected (void *user_data, int socket, const char *hostname)
{
	struct lua_wait_dial *self = user_data;
	if (self->super.task)
		lua_task_wakeup (self->super.task);

	self->connection = lua_plugin_push_connection (self->plugin, socket);
	// TODO: use the hostname for SNI once TLS is implemented
	self->hostname = xstrdup (hostname);
	lua_wait_dial_cancel (self);
}

static void
lua_wait_dial_on_failure (void *user_data)
{
	struct lua_wait_dial *self = user_data;
	if (self->super.task)
		lua_task_wakeup (self->super.task);
	lua_wait_dial_cancel (self);
}

static void
lua_wait_dial_on_error (void *user_data, const char *error)
{
	struct lua_wait_dial *self = user_data;
	cstr_set (&self->last_error, xstrdup (error));
}

static int
lua_plugin_push_wait_dial (struct lua_plugin *plugin, lua_State *L,
	const char *host, const char *service)
{
	struct lua_wait_dial *self = lua_newuserdata (L, sizeof *self);
	luaL_setmetatable (L, XLUA_WCHANNEL_METATABLE);
	memset (self, 0, sizeof *self);

	self->super.check = lua_wait_dial_check;
	self->super.cleanup = lua_wait_dial_cleanup;

	struct connector *connector = &self->connector;
	connector_init (connector, &plugin->ctx->poller);
	connector_add_target (connector, host, service);

	connector->on_connected  = lua_wait_dial_on_connected;
	connector->on_connecting = NULL;
	connector->on_error      = lua_wait_dial_on_error;
	connector->on_failure    = lua_wait_dial_on_failure;
	connector->user_data     = self;

	self->plugin = plugin;
	self->active = true;
	return 1;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_async_go (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	luaL_checktype (L, 1, LUA_TFUNCTION);

	lua_State *thread = lua_newthread (L);
	lua_cache_store (L, thread, -1);
	lua_pop (L, 1);

	// Move the main function w/ arguments to the thread
	lua_xmove (L, thread, lua_gettop (L));

	struct lua_task *task = lua_newuserdata (L, sizeof *task);
	luaL_setmetatable (L, XLUA_TASK_METATABLE);
	memset (task, 0, sizeof *task);
	task->plugin = plugin;
	task->thread = thread;

	task->idle = poller_idle_make (&plugin->ctx->poller);
	task->idle.dispatcher = (poller_idle_fn) lua_task_check;
	task->idle.user_data = task;
	poller_idle_set (&task->idle);

	// Make sure the task doesn't get garbage collected and return it
	lua_cache_store (L, task, -1);
	return 1;
}

static int
lua_async_timer_ms (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	lua_Integer timeout = luaL_checkinteger (L, 1);
	if (timeout < 0)
		luaL_argerror (L, 1, "timeout mustn't be negative");
	return lua_plugin_push_wait_timer (plugin, L, timeout);
}

static int
lua_async_dial (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	return lua_plugin_push_wait_dial (plugin, L,
		luaL_checkstring (L, 1), luaL_checkstring (L, 2));
}

static luaL_Reg lua_async_library[] =
{
	{ "go",       lua_async_go       },
	{ "timer_ms", lua_async_timer_ms },
	{ "dial",     lua_async_dial     },
	{ NULL,       NULL               },
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
lua_plugin_get_screen_size (lua_State *L)
{
	lua_pushinteger (L, g_terminal.lines);
	lua_pushinteger (L, g_terminal.columns);
	return 2;
}

static int
lua_plugin_measure (lua_State *L)
{
	struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1));
	const char *line = lua_plugin_check_utf8 (L, 1);

	size_t term_len = 0, processed = 0, width = 0, len;
	char *term = iconv_xstrdup (plugin->ctx->term_from_utf8,
		(char *) line, strlen (line) + 1, &term_len);

	mbstate_t ps;
	memset (&ps, 0, sizeof ps);

	wchar_t wch;
	while ((len = mbrtowc (&wch, term + processed, term_len - processed, &ps)))
	{
		hard_assert (len != (size_t) -2 && len != (size_t) -1);
		hard_assert ((processed += len) <= term_len);

		int wch_width = wcwidth (wch);
		width += MAX (0, wch_width);
	}
	free (term);
	lua_pushinteger (L, width);
	return 1;
}

static int
lua_ctx_gc (lua_State *L)
{
	return lua_weak_gc (L, &lua_ctx_info);
}

static luaL_Reg lua_plugin_library[] =
{
	// These are pseudo-global functions:

	{ "measure",         lua_plugin_measure         },
	{ "parse",           lua_plugin_parse           },
	{ "hook_input",      lua_plugin_hook_input      },
	{ "hook_irc",        lua_plugin_hook_irc        },
	{ "hook_prompt",     lua_plugin_hook_prompt     },
	{ "hook_completion", lua_plugin_hook_completion },
	{ "setup_config",    lua_plugin_setup_config    },

	// And these are methods:

	// Note that this only returns the height when used through an accessor.
	{ "get_screen_size", lua_plugin_get_screen_size },
	{ "__gc",            lua_ctx_gc                 },
	{ NULL,              NULL                       },
};

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void *
lua_plugin_alloc (void *ud, void *ptr, size_t o_size, size_t n_size)
{
	(void) ud;
	(void) o_size;

	if (n_size)
		return realloc (ptr, n_size);

	free (ptr);
	return NULL;
}

static int
lua_plugin_panic (lua_State *L)
{
	// XXX: we might be able to do something better
	print_fatal ("Lua panicked: %s", lua_tostring (L, -1));
	lua_close (L);
	exit (EXIT_FAILURE);
	return 0;
}

static void
lua_plugin_push_ref (lua_State *L, struct lua_plugin *self, void *object,
	struct ispect_field *field)
{
	// We create a mapping on object type registration
	hard_assert (lua_rawgetp (L, LUA_REGISTRYINDEX, field->fields));
	struct lua_weak_info *info = lua_touserdata (L, -1);
	lua_pop (L, 1);

	if (!field->is_list)
	{
		lua_weak_push (L, self, object, info);
		return;
	}

	// As a rule in this codebase, these fields are right at the top of structs
	struct list_header { LIST_HEADER (void) };

	int i = 1;
	lua_newtable (L);
	LIST_FOR_EACH (struct list_header, iter, object)
	{
		lua_weak_push (L, self, iter, info);
		lua_rawseti (L, -2, i++);
	}
}

static void lua_plugin_push_map_field (lua_State *L, struct lua_plugin *self,
	const char *key, void *p, struct ispect_field *field);

static void
lua_plugin_push_struct (lua_State *L, struct lua_plugin *self,
	enum ispect_type type, void *value, struct ispect_field *field)
{
	if (type == ISPECT_STR)
	{
		const struct str *s = value;
		lua_pushlstring (L, s->str, s->len);
		return;
	}
	if (type == ISPECT_STR_MAP)
	{
		struct str_map_iter iter = str_map_iter_make (value);

		void *value;
		lua_newtable (L);
		while ((value = str_map_iter_next (&iter)))
			lua_plugin_push_map_field (L, self, iter.link->key, value, field);
		return;
	}
	hard_assert (!"unhandled introspection object type");
}

static void
lua_plugin_push_map_field (lua_State *L, struct lua_plugin *self,
	const char *key, void *p, struct ispect_field *field)
{
	// That would mean maps in maps ad infinitum
	hard_assert (field->subtype != ISPECT_STR_MAP);

	intptr_t n = (intptr_t) p;
	switch (field->subtype)
	{
	// Here the types are generally casted to a void pointer
	case ISPECT_BOOL:   lua_pushboolean (L, (bool     ) n); break;
	case ISPECT_INT:    lua_pushinteger (L, (int      ) n); break;
	case ISPECT_UINT:   lua_pushinteger (L, (unsigned ) n); break;
	case ISPECT_SIZE:   lua_pushinteger (L, (size_t   ) n); break;
	case ISPECT_STRING: lua_pushstring  (L,             p); break;
	case ISPECT_REF: lua_plugin_push_ref (L, self, p, field); break;
	default: lua_plugin_push_struct (L, self, field->subtype, p, field);
	}
	lua_setfield (L, -2, key);
}

static bool
lua_plugin_property_get_ispect (lua_State *L, const char *property_name)
{
	struct lua_weak_info *info = lua_touserdata (L, lua_upvalueindex (1));
	if (!info || !info->ispect)
		return false;

	struct lua_weak *weak = luaL_checkudata (L, 1, info->name);
	// TODO: I think we can do better than this, maybe binary search at least?
	struct ispect_field *field;
	for (field = info->ispect; field->name; field++)
		if (!strcmp (property_name, field->name))
			break;
	if (!field->name)
		return false;

	struct lua_plugin *self = weak->plugin;
	void *p = (uint8_t *) weak->object + field->offset;
	switch (field->type)
	{
	// Here the types are really what's under the pointer
	case ISPECT_BOOL:   lua_pushboolean (L, *(bool     *) p); break;
	case ISPECT_INT:    lua_pushinteger (L, *(int      *) p); break;
	case ISPECT_UINT:   lua_pushinteger (L, *(unsigned *) p); break;
	case ISPECT_SIZE:   lua_pushinteger (L, *(size_t   *) p); break;
	case ISPECT_STRING: lua_pushstring  (L, *(char    **) p); break;
	case ISPECT_REF: lua_plugin_push_ref (L, self, *(void **) p, field); break;
	default: lua_plugin_push_struct (L, self, field->type, p, field);
	}
	return true;
}

static int
lua_plugin_property_get (lua_State *L)
{
	luaL_checktype (L, 1, LUA_TUSERDATA);
	const char *property_name = luaL_checkstring (L, 2);

	// Either it's directly present in the metatable
	if (luaL_getmetafield (L, 1, property_name))
		return 1;

	// Or we try to find and eventually call a getter method
	char *getter_name = xstrdup_printf ("get_%s", property_name);
	bool found = luaL_getmetafield (L, 1, getter_name);
	free (getter_name);

	if (found)
	{
		lua_pushvalue (L, 1);
		lua_call (L, 1, 1);
		return 1;
	}

	// Maybe we can find it via introspection
	if (lua_plugin_property_get_ispect (L, property_name))
		return 1;

	// Or we look for a property set by the user (__gc cannot be overriden)
	if (lua_getuservalue (L, 1) != LUA_TTABLE)
		lua_pushnil (L);
	else
		lua_getfield (L, -1, property_name);
	return 1;
}

static int
lua_plugin_property_set (lua_State *L)
{
	luaL_checktype (L, 1, LUA_TUSERDATA);
	const char *property_name = luaL_checkstring (L, 2);
	luaL_checkany (L, 3);

	// We use the associated value to store user-defined properties
	int type = lua_getuservalue (L, 1);
	if (type == LUA_TNIL)
	{
		lua_pop (L, 1);
		lua_newtable (L);
		lua_pushvalue (L, -1);
		lua_setuservalue (L, 1);
	}
	else if (type != LUA_TTABLE)
		return luaL_error (L, "associated value is not a table");

	// Beware that we do not check for conflicts here;
	// if Lua code writes a conflicting field, it is effectively ignored
	lua_pushvalue (L, 3);
	lua_setfield (L, -2, property_name);
	return 0;
}

static void
lua_plugin_add_accessors (lua_State *L, struct lua_weak_info *info)
{
	// Emulate properties for convenience
	lua_pushlightuserdata (L, info);
	lua_pushcclosure (L, lua_plugin_property_get, 1);
	lua_setfield (L, -2, "__index");
	lua_pushcfunction (L, lua_plugin_property_set);
	lua_setfield (L, -2, "__newindex");
}

static void
lua_plugin_reg_meta (lua_State *L, const char *name, luaL_Reg *fns)
{
	luaL_newmetatable (L, name);
	luaL_setfuncs (L, fns, 0);
	lua_plugin_add_accessors (L, NULL);
	lua_pop (L, 1);
}

static void
lua_plugin_reg_weak (lua_State *L, struct lua_weak_info *info, luaL_Reg *fns)
{
	// Create a mapping from the object type (info->ispect) back to metadata
	// so that we can figure out what to create from ISPECT_REF fields
	lua_pushlightuserdata (L, info);
	lua_rawsetp (L, LUA_REGISTRYINDEX, info->ispect);

	luaL_newmetatable (L, info->name);
	luaL_setfuncs (L, fns, 0);
	lua_plugin_add_accessors (L, info);
	lua_pop (L, 1);
}

static struct plugin *
lua_plugin_load (struct app_context *ctx, const char *filename,
	struct error **e)
{
	lua_State *L = lua_newstate (lua_plugin_alloc, NULL);
	if (!L)
	{
		error_set (e, "Lua initialization failed");
		return NULL;
	}

	lua_atpanic (L, lua_plugin_panic);
	luaL_openlibs (L);

	struct lua_plugin *plugin = xcalloc (1, sizeof *plugin);
	plugin->super.name = xstrdup (filename);
	plugin->super.vtable = &lua_plugin_vtable;
	plugin->ctx = ctx;
	plugin->L = L;

	luaL_checkversion (L);

	// Register the xC library as a singleton with "plugin" as an upvalue
	// (mostly historical, but rather convenient)
	luaL_newmetatable (L, lua_ctx_info.name);
	lua_pushlightuserdata (L, plugin);
	luaL_setfuncs (L, lua_plugin_library, 1);
	lua_plugin_add_accessors (L, &lua_ctx_info);

	// Add the asynchronous library underneath
	lua_newtable (L);
	lua_pushlightuserdata (L, plugin);
	luaL_setfuncs (L, lua_async_library, 1);
	lua_setfield (L, -2, "async");
	lua_pop (L, 1);

	lua_weak_push (L, plugin, ctx, &lua_ctx_info);
	lua_setglobal (L, lua_ctx_info.name);

	// Create metatables for our objects
	lua_plugin_reg_meta (L, XLUA_HOOK_METATABLE,       lua_hook_table);
	lua_plugin_reg_weak (L, &lua_user_info,            lua_user_table);
	lua_plugin_reg_weak (L, &lua_channel_info,         lua_channel_table);
	lua_plugin_reg_weak (L, &lua_buffer_info,          lua_buffer_table);
	lua_plugin_reg_weak (L, &lua_server_info,          lua_server_table);
	lua_plugin_reg_meta (L, XLUA_SCHEMA_METATABLE,     lua_schema_table);
	lua_plugin_reg_meta (L, XLUA_CONNECTION_METATABLE, lua_connection_table);

	lua_plugin_reg_meta (L, XLUA_TASK_METATABLE,       lua_task_table);
	lua_plugin_reg_meta (L, XLUA_WCHANNEL_METATABLE,   lua_wchannel_table);

	struct error *error = NULL;
	if (luaL_loadfile (L, filename))
		error_set (e, "%s: %s", "Lua", lua_tostring (L, -1));
	else if (!lua_plugin_call (plugin, 0, 0, &error))
	{
		error_set (e, "%s: %s", "Lua", error->message);
		error_free (error);
	}
	else
		return &plugin->super;

	plugin_destroy (&plugin->super);
	return NULL;
}

#endif // HAVE_LUA

// --- Plugins -----------------------------------------------------------------

typedef struct plugin *(*plugin_load_fn)
	(struct app_context *ctx, const char *filename, struct error **e);

// We can potentially add support for other scripting languages if so desired,
// however this possibility is just a byproduct of abstraction
static plugin_load_fn g_plugin_loaders[] =
{
#ifdef HAVE_LUA
	lua_plugin_load,
#endif // HAVE_LUA
};

static struct plugin *
plugin_load_from_filename (struct app_context *ctx, const char *filename,
	struct error **e)
{
	struct plugin *plugin = NULL;
	struct error *error = NULL;
	for (size_t i = 0; i < N_ELEMENTS (g_plugin_loaders); i++)
		if ((plugin = g_plugin_loaders[i](ctx, filename, &error)) || error)
			break;

	if (error)
		error_propagate (e, error);
	else if (!plugin)
	{
		error_set (e, "no plugin handler for \"%s\"", filename);
		return NULL;
	}
	return plugin;
}

static struct plugin *
plugin_find (struct app_context *ctx, const char *name)
{
	LIST_FOR_EACH (struct plugin, iter, ctx->plugins)
		if (!strcmp (name, iter->name))
			return iter;
	return NULL;
}

static char *
plugin_resolve_relative_filename (const char *filename)
{
	struct strv paths = strv_make ();
	get_xdg_data_dirs (&paths);
	strv_append (&paths, PROJECT_DATADIR);
	char *result = resolve_relative_filename_generic
		(&paths, PROGRAM_NAME "/plugins/", filename);
	strv_free (&paths);
	return result;
}

static struct plugin *
plugin_load_by_name (struct app_context *ctx, const char *name,
	struct error **e)
{
	struct plugin *plugin = plugin_find (ctx, name);
	if (plugin)
	{
		error_set (e, "plugin already loaded");
		return NULL;
	}

	// As a side effect, a plugin can be loaded multiple times by giving
	// various relative or non-relative paths to the function; this is not
	// supposed to be fool-proof though, that requires other mechanisms
	char *filename = resolve_filename (name, plugin_resolve_relative_filename);
	if (!filename)
	{
		error_set (e, "file not found");
		return NULL;
	}

	plugin = plugin_load_from_filename (ctx, filename, e);
	free (filename);
	return plugin;
}

static void
plugin_load (struct app_context *ctx, const char *name)
{
	struct error *e = NULL;
	struct plugin *plugin = plugin_load_by_name (ctx, name, &e);
	if (plugin)
	{
		// FIXME: this way the real name isn't available to the plugin on load,
		//   which has effect on e.g. plugin_config_name()
		cstr_set (&plugin->name, xstrdup (name));

		log_global_status (ctx, "Plugin \"#s\" loaded", name);
		LIST_PREPEND (ctx->plugins, plugin);
	}
	else
	{
		log_global_error (ctx, "Can't load plugin \"#s\": #s",
			name, e->message);
		error_free (e);
	}
}

static void
plugin_unload (struct app_context *ctx, const char *name)
{
	struct plugin *plugin = plugin_find (ctx, name);
	if (!plugin)
		log_global_error (ctx, "Can't unload plugin \"#s\": #s",
			name, "plugin not loaded");
	else
	{
		log_global_status (ctx, "Plugin \"#s\" unloaded", name);
		LIST_UNLINK (ctx->plugins, plugin);
		plugin_destroy (plugin);
	}
}

static void
load_plugins (struct app_context *ctx)
{
	const char *plugins =
		get_config_string (ctx->config.root, "general.plugin_autoload");
	if (plugins)
	{
		struct strv v = strv_make ();
		cstr_split (plugins, ",", true, &v);
		for (size_t i = 0; i < v.len; i++)
			plugin_load (ctx, v.vector[i]);
		strv_free (&v);
	}
}

// --- User input handling -----------------------------------------------------

// HANDLER_NEEDS_REG is primarily for message sending commands,
// as they may want to log buffer lines and use our current nickname

enum handler_flags
{
	HANDLER_SERVER        = (1 << 0),   ///< Server context required
	HANDLER_NEEDS_REG     = (1 << 1),   ///< Server registration required
	HANDLER_CHANNEL_FIRST = (1 << 2),   ///< Channel required, first argument
	HANDLER_CHANNEL_LAST  = (1 << 3)    ///< Channel required, last argument
};

struct handler_args
{
	struct app_context *ctx;            ///< Application context
	struct buffer *buffer;              ///< Current buffer
	struct server *s;                   ///< Related server
	const char *channel_name;           ///< Related channel name
	char *arguments;                    ///< Command arguments
};

/// Cuts the longest non-whitespace portion of text and advances the pointer
static char *
cut_word (char **s)
{
	char *start = *s;
	size_t word_len = strcspn (*s, WORD_BREAKING_CHARS);
	char *end = start + word_len;
	*s = end + strspn (end, WORD_BREAKING_CHARS);
	*end = '\0';
	return start;
}

/// Validates a word to be cut from a string
typedef bool (*word_validator_fn) (void *, char *);

static char *
maybe_cut_word (char **s, word_validator_fn validator, void *user_data)
{
	char *start = *s;
	size_t word_len = strcspn (*s, WORD_BREAKING_CHARS);

	char *word = xstrndup (start, word_len);
	bool ok = validator (user_data, word);
	free (word);

	if (!ok)
		return NULL;

	char *end = start + word_len;
	*s = end + strspn (end, WORD_BREAKING_CHARS);
	*end = '\0';
	return start;
}

static char *
maybe_cut_word_from_end (char **s, word_validator_fn validator, void *user_data)
{
	// Find the start and end of the last word
	// Contrary to maybe_cut_word(), we ignore all whitespace at the end
	char *start = *s, *end = start + strlen (start);
	while (end  > start &&  strchr (WORD_BREAKING_CHARS, end [-1]))
		end--;
	char *word = end;
	while (word > start && !strchr (WORD_BREAKING_CHARS, word[-1]))
		word--;

	// There's just one word at maximum, starting at the beginning
	if (word == start)
		return maybe_cut_word (s, validator, user_data);

	char *tmp = xstrndup (word, word - start);
	bool ok = validator (user_data, tmp);
	free (tmp);

	if (!ok)
		return NULL;

	// It doesn't start at the beginning, cut it off and return it
	word[-1] = *end = '\0';
	return word;
}

static bool
validate_channel_name (void *user_data, char *word)
{
	return irc_is_channel (user_data, word);
}

static char *
try_get_channel (struct handler_args *a,
	char *(*cutter) (char **, word_validator_fn, void *))
{
	char *channel_name = cutter (&a->arguments, validate_channel_name, a->s);
	if (channel_name)
		return channel_name;
	if (a->buffer->type == BUFFER_CHANNEL)
		return a->buffer->channel->name;
	return NULL;
}

static bool
try_handle_buffer_goto (struct app_context *ctx, const char *word)
{
	unsigned long n;
	if (!xstrtoul (&n, word, 10))
		return false;

	if (n > INT_MAX || !buffer_goto (ctx, n))
		log_global_error (ctx, "#s: #s", "No such buffer", word);
	return true;
}

static struct buffer *
try_decode_buffer (struct app_context *ctx, const char *word)
{
	unsigned long n;
	struct buffer *buffer = NULL;
	if (xstrtoul (&n, word, 10) && n <= INT_MAX)
		buffer = buffer_at_index (ctx, n);
	if (buffer || (buffer = buffer_by_name (ctx, word)))
		return buffer;

	// Basic case insensitive partial matching -- at most one buffer can match
	int n_matches = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
	{
		char *string  = xstrdup (iter->name);
		char *pattern = xstrdup_printf ("*%s*", word);
		for (char *p = string;  *p; p++) *p = tolower_ascii (*p);
		for (char *p = pattern; *p; p++) *p = tolower_ascii (*p);
		if (!fnmatch (pattern, string, 0))
		{
			n_matches++;
			buffer = iter;
		}
		free (string);
		free (pattern);
	}
	return n_matches == 1 ? buffer : NULL;
}

static void
show_buffers_list (struct app_context *ctx)
{
	log_global_indent (ctx, "");
	log_global_indent (ctx, "Buffers list:");

	int i = 1;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
	{
		struct str s = str_make ();
		int new = iter->new_messages_count - iter->new_unimportant_count;
		if (new && iter != ctx->current_buffer)
			str_append_printf (&s, " (%d%s)", new, &"!"[!iter->highlighted]);
		log_global_indent (ctx,
			"  [#d] #s#&s", i++, iter->name, str_steal (&s));
	}
}

static void
part_channel (struct server *s, const char *channel_name, const char *reason)
{
	if (*reason)
		irc_send (s, "PART %s :%s", channel_name, reason);
	else
		irc_send (s, "PART %s", channel_name);

	struct channel *channel;
	if ((channel = str_map_find (&s->irc_channels, channel_name)))
		channel->left_manually = true;
}

static bool
handle_buffer_goto (struct app_context *ctx, struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	const char *which = cut_word (&a->arguments);
	struct buffer *buffer = try_decode_buffer (ctx, which);
	if (buffer)
		buffer_activate (ctx, buffer);
	else
		log_global_error (ctx, "#s: #s", "No such buffer", which);
	return true;
}

static void
handle_buffer_close (struct app_context *ctx, struct handler_args *a)
{
	struct buffer *buffer = NULL;
	const char *which = NULL;
	if (!*a->arguments)
		buffer = a->buffer;
	else
		buffer = try_decode_buffer (ctx, (which = cut_word (&a->arguments)));

	if (!buffer)
		log_global_error (ctx, "#s: #s", "No such buffer", which);
	else if (buffer == ctx->global_buffer)
		log_global_error (ctx, "Can't close the global buffer");
	else if (buffer->type == BUFFER_SERVER)
		log_global_error (ctx, "Can't close a server buffer");
	else
	{
		// The user would be unable to recreate the buffer otherwise
		if (buffer->type == BUFFER_CHANNEL
		 && irc_channel_is_joined (buffer->channel))
			part_channel (buffer->server, buffer->channel->name, "");
		buffer_remove_safe (ctx, buffer);
	}
}

static bool
handle_buffer_move (struct app_context *ctx, struct handler_args *a)
{
	unsigned long request;
	if (!xstrtoul (&request, a->arguments, 10))
		return false;

	if (request == 0 || request > (unsigned long) buffer_count (ctx))
	{
		log_global_error (ctx, "#s: #s",
			"Can't move buffer", "requested position is out of range");
		return true;
	}
	buffer_move (ctx, a->buffer, request);
	return true;
}

static bool
handle_command_buffer (struct handler_args *a)
{
	struct app_context *ctx = a->ctx;
	char *action = cut_word (&a->arguments);
	if (try_handle_buffer_goto (ctx, action))
		return true;

	bool result = true;
	if (!*action || !strcasecmp_ascii (action, "list"))
		show_buffers_list (ctx);
	else if (!strcasecmp_ascii (action, "clear"))
	{
		buffer_clear (ctx, a->buffer);
		if (a->buffer == ctx->current_buffer)
			buffer_print_backlog (ctx, a->buffer);
	}
	else if (!strcasecmp_ascii (action, "move"))
		result = handle_buffer_move (ctx, a);
	else if (!strcasecmp_ascii (action, "goto"))
		result = handle_buffer_goto (ctx, a);
	else if (!strcasecmp_ascii (action, "close"))
		handle_buffer_close (ctx, a);
	else
		result = false;
	return result;
}

static bool
handle_command_set_add
	(struct strv *items, const struct strv *values, struct error **e)
{
	for (size_t i = 0; i < values->len; i++)
	{
		const char *value = values->vector[i];
		if (strv_find (items, values->vector[i]) != -1)
			return error_set (e, "already present in the array: %s", value);
		strv_append (items, value);
	}
	return true;
}

static bool
handle_command_set_remove
	(struct strv *items, const struct strv *values, struct error **e)
{
	for (size_t i = 0; i < values->len; i++)
	{
		const char *value = values->vector[i];
		ssize_t i = strv_find (items, value);
		if (i == -1)
			return error_set (e, "not present in the array: %s", value);
		strv_remove (items, i);
	}
	return true;
}

static bool
handle_command_set_modify
	(struct config_item *item, const char *value, bool add, struct error **e)
{
	struct strv items = strv_make ();
	if (item->type != CONFIG_ITEM_NULL)
		cstr_split (item->value.string.str, ",", false, &items);
	if (items.len == 1 && !*items.vector[0])
		strv_reset (&items);

	struct strv values = strv_make ();
	cstr_split (value, ",", false, &values);
	bool result = add
		? handle_command_set_add (&items, &values, e)
		: handle_command_set_remove (&items, &values, e);

	if (result)
	{
		char *changed = strv_join (&items, ",");
		struct str tmp = { .str = changed, .len = strlen (changed) };
		result = config_item_set_from (item,
			config_item_string_array (&tmp), e);
		free (changed);
	}

	strv_free (&items);
	strv_free (&values);
	return result;
}

static bool
handle_command_set_assign_item (struct app_context *ctx,
	char *key, struct config_item *new_, bool add, bool remove)
{
	struct config_item *item =
		config_item_get (ctx->config.root, key, NULL);
	hard_assert (item);

	struct error *e = NULL;
	if (!item->schema)
		error_set (&e, "option not recognized");
	else if (!add && !remove)
		config_item_set_from (item, config_item_clone (new_), &e);
	else if (item->schema->type != CONFIG_ITEM_STRING_ARRAY)
		error_set (&e, "not a string array");
	else
		handle_command_set_modify (item, new_->value.string.str, add, &e);

	if (e)
	{
		log_global_error (ctx,
			"Failed to set option \"#s\": #s", key, e->message);
		error_free (e);
		return false;
	}

	struct strv tmp = strv_make ();
	dump_matching_options (ctx->config.root, key, &tmp);
	log_global_status (ctx, "Option changed: #s", tmp.vector[0]);
	strv_free (&tmp);
	return true;
}

static bool
handle_command_set_assign
	(struct app_context *ctx, struct strv *all, char *arguments)
{
	hard_assert (all->len > 0);

	char *op = cut_word (&arguments);
	bool add = false;
	bool remove = false;

	if      (!strcmp (op, "+="))  add = true;
	else if (!strcmp (op, "-="))  remove = true;
	else if  (strcmp (op, "="))   return false;

	if (!*arguments)
		return false;

	struct error *e = NULL;
	struct config_item *new_ =
		config_item_parse (arguments, strlen (arguments), true, &e);
	if (e)
	{
		log_global_error (ctx, "Invalid value: #s", e->message);
		error_free (e);
		return true;
	}

	if ((add | remove) && !config_item_type_is_string (new_->type))
	{
		log_global_error (ctx, "+= / -= operators need a string argument");
		config_item_destroy (new_);
		return true;
	}

	bool changed = false;
	for (size_t i = 0; i < all->len; i++)
	{
		char *key = cstr_cut_until (all->vector[i], " ");
		if (handle_command_set_assign_item (ctx, key, new_, add, remove))
			changed = true;
		free (key);
	}
	config_item_destroy (new_);

	if (changed && get_config_boolean (ctx->config.root, "general.autosave"))
		save_configuration (ctx);
	return true;
}

static bool
handle_command_set (struct handler_args *a)
{
	struct app_context *ctx = a->ctx;
	char *option = "*";
	if (*a->arguments)
		option = cut_word (&a->arguments);

	struct strv all = strv_make ();
	dump_matching_options (ctx->config.root, option, &all);

	bool result = true;
	if (!all.len)
		log_global_error (ctx, "No matches: #s", option);
	else if (!*a->arguments)
	{
		log_global_indent (ctx, "");
		for (size_t i = 0; i < all.len; i++)
			log_global_indent (ctx, "#s", all.vector[i]);
	}
	else
		result = handle_command_set_assign (ctx, &all, a->arguments);

	strv_free (&all);
	return result;
}

static bool
handle_command_save (struct handler_args *a)
{
	if (*a->arguments)
		return false;

	save_configuration (a->ctx);
	return true;
}

static void
show_plugin_list (struct app_context *ctx)
{
	log_global_indent (ctx, "");
	log_global_indent (ctx, "Plugins:");
	LIST_FOR_EACH (struct plugin, iter, ctx->plugins)
		log_global_indent (ctx, "  #s", iter->name);
}

static bool
handle_command_plugin (struct handler_args *a)
{
	char *action = cut_word (&a->arguments);
	if (!*action || !strcasecmp_ascii (action, "list"))
		show_plugin_list (a->ctx);
	else if (!strcasecmp_ascii (action, "load"))
	{
		if (!*a->arguments)
			return false;

		plugin_load (a->ctx, cut_word (&a->arguments));
	}
	else if (!strcasecmp_ascii (action, "unload"))
	{
		if (!*a->arguments)
			return false;

		plugin_unload (a->ctx, cut_word (&a->arguments));
	}
	else
		return false;
	return true;
}

static bool
handle_command_relay (struct handler_args *a)
{
	if (*a->arguments)
		return false;

	int len = 0;
	LIST_FOR_EACH (struct client, c, a->ctx->clients)
		len++;

	if (a->ctx->relay_fd == -1)
		log_global_status (a->ctx, "The relay is not enabled");
	else
		log_global_status (a->ctx, "The relay has #d clients", len);
	return true;
}

static bool
show_aliases_list (struct app_context *ctx)
{
	log_global_indent (ctx, "");
	log_global_indent (ctx, "Aliases:");

	struct str_map *aliases = get_aliases_config (ctx);
	if (!aliases->len)
	{
		log_global_indent (ctx, "  (none)");
		return true;
	}

	struct str_map_iter iter = str_map_iter_make (aliases);
	struct config_item *alias;
	while ((alias = str_map_iter_next (&iter)))
	{
		struct str definition = str_make ();
		if (config_item_type_is_string (alias->type))
			config_item_write_string (&definition, &alias->value.string);
		else
			str_append (&definition, "alias definition is not a string");
		log_global_indent (ctx, "  /#s: #s", iter.link->key, definition.str);
		str_free (&definition);
	}
	return true;
}

static bool
handle_command_alias (struct handler_args *a)
{
	if (!*a->arguments)
		return show_aliases_list (a->ctx);

	char *name = cut_word (&a->arguments);
	if (!*a->arguments)
		return false;
	if (*name == '/')
		name++;

	struct config_item *alias = config_item_string_from_cstr (a->arguments);

	struct str definition = str_make ();
	config_item_write_string (&definition, &alias->value.string);
	str_map_set (get_aliases_config (a->ctx), name, alias);
	log_global_status (a->ctx, "Created alias /#s: #s", name, definition.str);
	str_free (&definition);
	return true;
}

static bool
handle_command_unalias (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	struct str_map *aliases = get_aliases_config (a->ctx);
	while (*a->arguments)
	{
		char *name = cut_word (&a->arguments);
		if (!str_map_find (aliases, name))
			log_global_error (a->ctx, "No such alias: #s", name);
		else
		{
			str_map_set (aliases, name, NULL);
			log_global_status (a->ctx, "Alias removed: #s", name);
		}
	}
	return true;
}

static bool
handle_command_msg (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (!*a->arguments)
		log_server_error (a->s, a->s->buffer, "No text to send");
	else
		SEND_AUTOSPLIT_PRIVMSG (a->s, target, a->arguments);
	return true;
}

static bool
handle_command_query (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (irc_is_channel (a->s, irc_skip_statusmsg (a->s, target)))
		log_server_error (a->s, a->s->buffer, "Cannot query a channel");
	else if (!*a->arguments)
		buffer_activate (a->ctx, irc_get_or_make_user_buffer (a->s, target));
	else
	{
		buffer_activate (a->ctx, irc_get_or_make_user_buffer (a->s, target));
		SEND_AUTOSPLIT_PRIVMSG (a->s, target, a->arguments);
	}
	return true;
}

static bool
handle_command_notice (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (!*a->arguments)
		log_server_error (a->s, a->s->buffer, "No text to send");
	else
		SEND_AUTOSPLIT_NOTICE (a->s, target, a->arguments);
	return true;
}

static bool
handle_command_squery (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (!*a->arguments)
		log_server_error (a->s, a->s->buffer, "No text to send");
	else
		irc_send (a->s, "SQUERY %s :%s", target, a->arguments);
	return true;
}

static bool
handle_command_ctcp (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (!*a->arguments)
		return false;

	char *tag = cut_word (&a->arguments);
	cstr_transform (tag, toupper_ascii);

	if (*a->arguments)
		irc_send (a->s, "PRIVMSG %s :\x01%s %s\x01", target, tag, a->arguments);
	else
		irc_send (a->s, "PRIVMSG %s :\x01%s\x01", target, tag);
	return true;
}

static bool
handle_command_me (struct handler_args *a)
{
	if (a->buffer->type == BUFFER_CHANNEL)
		SEND_AUTOSPLIT_ACTION (a->s,
			a->buffer->channel->name, a->arguments);
	else if (a->buffer->type == BUFFER_PM)
		SEND_AUTOSPLIT_ACTION (a->s,
			a->buffer->user->nickname, a->arguments);
	else
		log_server_error (a->s, a->s->buffer,
			"Can't do this from a server buffer (#s)",
			"send CTCP actions");
	return true;
}

static bool
handle_command_quit (struct handler_args *a)
{
	request_quit (a->ctx, *a->arguments ? a->arguments : NULL);
	return true;
}

static bool
handle_command_join (struct handler_args *a)
{
	// XXX: send the last known channel key?
	if (irc_is_channel (a->s, a->arguments))
		// XXX: we may want to split the list of channels
		irc_send (a->s, "JOIN %s", a->arguments);
	else if (a->buffer->type != BUFFER_CHANNEL)
		log_server_error (a->s, a->buffer, "#s: #s", "Can't join",
			"no channel name given and this buffer is not a channel");
	else if (irc_channel_is_joined (a->buffer->channel))
		log_server_error (a->s, a->buffer, "#s: #s", "Can't join",
			"you already are on the channel");
	else if (*a->arguments)
		irc_send (a->s, "JOIN %s :%s", a->buffer->channel->name, a->arguments);
	else
		irc_send (a->s, "JOIN %s", a->buffer->channel->name);
	return true;
}

static bool
handle_command_part (struct handler_args *a)
{
	if (irc_is_channel (a->s, a->arguments))
	{
		struct strv v = strv_make ();
		cstr_split (cut_word (&a->arguments), ",", true, &v);
		for (size_t i = 0; i < v.len; i++)
			part_channel (a->s, v.vector[i], a->arguments);
		strv_free (&v);
	}
	else if (a->buffer->type != BUFFER_CHANNEL)
		log_server_error (a->s, a->buffer, "#s: #s", "Can't part",
			"no channel name given and this buffer is not a channel");
	else if (!irc_channel_is_joined (a->buffer->channel))
		log_server_error (a->s, a->buffer, "#s: #s", "Can't part",
			"you're not on the channel");
	else
		part_channel (a->s, a->buffer->channel->name, a->arguments);
	return true;
}

static void
cycle_channel (struct server *s, const char *channel_name, const char *reason)
{
	// If a channel key is set, we must specify it when rejoining
	const char *key = NULL;
	struct channel *channel;
	if ((channel = str_map_find (&s->irc_channels, channel_name)))
		key = str_map_find (&channel->param_modes, "k");

	if (*reason)
		irc_send (s, "PART %s :%s", channel_name, reason);
	else
		irc_send (s, "PART %s", channel_name);

	if (key)
		irc_send (s, "JOIN %s :%s", channel_name, key);
	else
		irc_send (s, "JOIN %s", channel_name);
}

static bool
handle_command_cycle (struct handler_args *a)
{
	if (irc_is_channel (a->s, a->arguments))
	{
		struct strv v = strv_make ();
		cstr_split (cut_word (&a->arguments), ",", true, &v);
		for (size_t i = 0; i < v.len; i++)
			cycle_channel (a->s, v.vector[i], a->arguments);
		strv_free (&v);
	}
	else if (a->buffer->type != BUFFER_CHANNEL)
		log_server_error (a->s, a->buffer, "#s: #s", "Can't cycle",
			"no channel name given and this buffer is not a channel");
	else if (!irc_channel_is_joined (a->buffer->channel))
		log_server_error (a->s, a->buffer, "#s: #s", "Can't cycle",
			"you're not on the channel");
	else
		cycle_channel (a->s, a->buffer->channel->name, a->arguments);
	return true;
}

static bool
handle_command_mode (struct handler_args *a)
{
	// Channel names prefixed by "+" collide with mode strings,
	// so we just disallow specifying these channels
	char *target = NULL;
	if (strchr ("+-\0", *a->arguments))
	{
		if (a->buffer->type == BUFFER_CHANNEL)
			target = a->buffer->channel->name;
		if (a->buffer->type == BUFFER_PM)
			target = a->buffer->user->nickname;
		if (a->buffer->type == BUFFER_SERVER)
			target = a->s->irc_user->nickname;
	}
	else
		// If there a->arguments and they don't begin with a mode string,
		// they're either a user name or a channel name
		target = cut_word (&a->arguments);

	if (!target)
		log_server_error (a->s, a->buffer, "#s: #s", "Can't change mode",
			"no target given and this buffer is neither a PM nor a channel");
	else if (*a->arguments)
		// XXX: split channel mode params as necessary using irc_max_modes?
		irc_send (a->s, "MODE %s %s", target, a->arguments);
	else
		irc_send (a->s, "MODE %s", target);
	return true;
}

static bool
handle_command_topic (struct handler_args *a)
{
	if (*a->arguments)
		// FIXME: there's no way to start the topic with whitespace
		// FIXME: there's no way to unset the topic;
		//   we could adopt the Tcl style of "-switches" with "--" sentinels,
		//   or we could accept "strings" in the config format
		irc_send (a->s, "TOPIC %s :%s", a->channel_name, a->arguments);
	else
		irc_send (a->s, "TOPIC %s", a->channel_name);
	return true;
}

static bool
handle_command_kick (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (*a->arguments)
		irc_send (a->s, "KICK %s %s :%s",
			a->channel_name, target, a->arguments);
	else
		irc_send (a->s, "KICK %s %s", a->channel_name, target);
	return true;
}

static bool
handle_command_kickban (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (strpbrk (target, "!@*?"))
		return false;

	// XXX: how about other masks?
	irc_send (a->s, "MODE %s +b %s!*@*", a->channel_name, target);
	if (*a->arguments)
		irc_send (a->s, "KICK %s %s :%s",
			a->channel_name, target, a->arguments);
	else
		irc_send (a->s, "KICK %s %s", a->channel_name, target);
	return true;
}

static void
mass_channel_mode (struct server *s, const char *channel_name,
	bool adding, char mode_char, struct strv *v)
{
	size_t n;
	for (size_t i = 0; i < v->len; i += n)
	{
		struct str modes  = str_make ();
		struct str params = str_make ();

		n = MIN (v->len - i, s->irc_max_modes);
		str_append_printf (&modes, "MODE %s %c", channel_name, "-+"[adding]);
		for (size_t k = 0; k < n; k++)
		{
			str_append_c (&modes, mode_char);
			str_append_printf (&params, " %s", v->vector[i + k]);
		}

		irc_send (s, "%s%s", modes.str, params.str);

		str_free (&modes);
		str_free (&params);
	}
}

static void
mass_channel_mode_mask_list
	(struct handler_args *a, bool adding, char mode_char)
{
	struct strv v = strv_make ();
	cstr_split (a->arguments, " ", true, &v);

	// XXX: this may be a bit too trivial; we could also map nicknames
	//   to information from WHO polling or userhost-in-names
	for (size_t i = 0; i < v.len; i++)
	{
		char *target = v.vector[i];
		if (strpbrk (target, "!@*?") || irc_is_extban (a->s, target))
			continue;

		v.vector[i] = xstrdup_printf ("%s!*@*", target);
		free (target);
	}

	mass_channel_mode (a->s, a->channel_name, adding, mode_char, &v);
	strv_free (&v);
}

static bool
handle_command_ban (struct handler_args *a)
{
	if (*a->arguments)
		mass_channel_mode_mask_list (a, true, 'b');
	else
		irc_send (a->s, "MODE %s +b", a->channel_name);
	return true;
}

static bool
handle_command_unban (struct handler_args *a)
{
	if (*a->arguments)
		mass_channel_mode_mask_list (a, false, 'b');
	else
		return false;
	return true;
}

static bool
handle_command_invite (struct handler_args *a)
{
	struct strv v = strv_make ();
	cstr_split (a->arguments, " ", true, &v);

	bool result = !!v.len;
	for (size_t i = 0; i < v.len; i++)
		irc_send (a->s, "INVITE %s %s", v.vector[i], a->channel_name);

	strv_free (&v);
	return result;
}

static struct server *
resolve_server (struct app_context *ctx, struct handler_args *a,
	const char *command_name)
{
	struct server *s = NULL;
	if (*a->arguments)
	{
		char *server_name = cut_word (&a->arguments);
		if (!(s = str_map_find (&ctx->servers, server_name)))
			log_global_error (ctx, "/#s: #s: #s",
				command_name, "no such server", server_name);
	}
	else if (a->buffer->type == BUFFER_GLOBAL)
		log_global_error (ctx, "/#s: #s",
			command_name, "no server name given and this buffer is global");
	else
		s = a->buffer->server;
	return s;
}

static bool
handle_command_connect (struct handler_args *a)
{
	struct server *s = NULL;
	if (!(s = resolve_server (a->ctx, a, "connect")))
		return true;

	if (irc_is_connected (s))
	{
		log_server_error (s, s->buffer, "Already connected");
		return true;
	}
	if (s->state == IRC_CONNECTING)
		irc_destroy_connector (s);

	irc_cancel_timers (s);

	s->reconnect_attempt = 0;
	irc_initiate_connect (s);
	return true;
}

static bool
handle_command_disconnect (struct handler_args *a)
{
	struct server *s = NULL;
	if (!(s = resolve_server (a->ctx, a, "disconnect")))
		return true;

	if (s->state == IRC_CONNECTING)
	{
		log_server_status (s, s->buffer, "Connecting aborted");
		irc_destroy_connector (s);
	}
	else if (poller_timer_is_active (&s->reconnect_tmr))
	{
		log_server_status (s, s->buffer, "Connecting aborted");
		poller_timer_reset (&s->reconnect_tmr);
	}
	else if (!irc_is_connected (s))
		log_server_error (s, s->buffer, "Not connected");
	else
		irc_initiate_disconnect (s, *a->arguments ? a->arguments : NULL);
	return true;
}

static bool
show_servers_list (struct app_context *ctx)
{
	log_global_indent (ctx, "");
	log_global_indent (ctx, "Servers list:");

	struct str_map_iter iter = str_map_iter_make (&ctx->servers);
	struct server *s;
	while ((s = str_map_iter_next (&iter)))
		log_global_indent (ctx, "  #s", s->name);
	return true;
}

static bool
handle_server_add (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	struct app_context *ctx = a->ctx;
	char *name = cut_word (&a->arguments);
	const char *err;
	if ((err = check_server_name_for_addition (ctx, name)))
		log_global_error (ctx, "Cannot create server `#s': #s", name, err);
	else
	{
		server_add_new (ctx, name);
		log_global_status (ctx, "Server added: #s", name);
	}
	return true;
}

static bool
handle_server_remove (struct handler_args *a)
{
	struct app_context *ctx = a->ctx;
	struct server *s = NULL;
	if (!(s = resolve_server (ctx, a, "server")))
		return true;

	if (irc_is_connected (s))
		log_server_error (s, s->buffer, "Can't remove a connected server");
	else
	{
		char *name = xstrdup (s->name);
		server_remove (ctx, s);
		log_global_status (ctx, "Server removed: #s", name);
		free (name);
	}
	return true;
}

static bool
handle_server_rename (struct handler_args *a)
{
	struct app_context *ctx = a->ctx;
	if (!*a->arguments)
		return false;
	char *old_name = cut_word (&a->arguments);
	if (!*a->arguments)
		return false;
	char *new_name = cut_word (&a->arguments);

	struct server *s;
	const char *err;
	if (!(s = str_map_find (&ctx->servers, old_name)))
		log_global_error (ctx, "/#s: #s: #s",
			"server", "no such server", old_name);
	else if ((err = check_server_name_for_addition (ctx, new_name)))
		log_global_error (ctx,
			"Cannot rename server to `#s': #s", new_name, err);
	else
	{
		server_rename (ctx, s, new_name);
		log_global_status (ctx, "Server renamed: #s to #s", old_name, new_name);
	}
	return true;
}

static bool
handle_command_server (struct handler_args *a)
{
	if (!*a->arguments)
		return show_servers_list (a->ctx);

	char *action = cut_word (&a->arguments);
	if (!strcasecmp_ascii (action, "list"))
		return show_servers_list (a->ctx);
	if (!strcasecmp_ascii (action, "add"))
		return handle_server_add (a);
	if (!strcasecmp_ascii (action, "remove"))
		return handle_server_remove (a);
	if (!strcasecmp_ascii (action, "rename"))
		return handle_server_rename (a);
	return false;
}

static bool
handle_command_names (struct handler_args *a)
{
	char *channel_name = try_get_channel (a, maybe_cut_word);
	if (channel_name)
		irc_send (a->s, "NAMES %s", channel_name);
	else
		irc_send (a->s, "NAMES");
	return true;
}

static bool
handle_command_whois (struct handler_args *a)
{
	if (*a->arguments)
		irc_send (a->s, "WHOIS %s", a->arguments);
	else if (a->buffer->type == BUFFER_PM)
		irc_send (a->s, "WHOIS %s", a->buffer->user->nickname);
	else if (a->buffer->type == BUFFER_SERVER)
		irc_send (a->s, "WHOIS %s", a->s->irc_user->nickname);
	else
		log_server_error (a->s, a->buffer, "#s: #s", "Can't request info",
			"no target given and this buffer is neither a PM nor a server");
	return true;
}

static bool
handle_command_whowas (struct handler_args *a)
{
	if (*a->arguments)
		irc_send (a->s, "WHOWAS %s", a->arguments);
	else if (a->buffer->type == BUFFER_PM)
		irc_send (a->s, "WHOWAS %s", a->buffer->user->nickname);
	else
		log_server_error (a->s, a->buffer, "#s: #s", "Can't request info",
			"no target given and this buffer is not a PM");
	return true;
}

static bool
handle_command_kill (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (*a->arguments)
		irc_send (a->s, "KILL %s :%s", target, a->arguments);
	else
		irc_send (a->s, "KILL %s", target);
	return true;
}

static bool
handle_command_away (struct handler_args *a)
{
	if (*a->arguments)
		irc_send (a->s, "AWAY :%s", a->arguments);
	else
		irc_send (a->s, "AWAY");
	return true;
}

static bool
handle_command_nick (struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	irc_send (a->s, "NICK %s", cut_word (&a->arguments));
	return true;
}

static bool
handle_command_quote (struct handler_args *a)
{
	irc_send (a->s, "%s", a->arguments);
	return true;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool
handle_command_channel_mode
	(struct handler_args *a, bool adding, char mode_char)
{
	const char *targets = a->arguments;
	if (!*targets)
	{
		if (adding)
			return false;

		targets = a->s->irc_user->nickname;
	}

	struct strv v = strv_make ();
	cstr_split (targets, " ", true, &v);
	mass_channel_mode (a->s, a->channel_name, adding, mode_char, &v);
	strv_free (&v);
	return true;
}

#define CHANMODE_HANDLER(name, adding, mode_char)                              \
	static bool                                                                \
	handle_command_ ## name (struct handler_args *a)                           \
	{                                                                          \
		return handle_command_channel_mode (a, (adding), (mode_char));         \
	}

CHANMODE_HANDLER (op,      true,  'o')  CHANMODE_HANDLER (deop,    false, 'o')
CHANMODE_HANDLER (voice,   true,  'v')  CHANMODE_HANDLER (devoice, false, 'v')

#define TRIVIAL_HANDLER(name, command)                                         \
	static bool                                                                \
	handle_command_ ## name (struct handler_args *a)                           \
	{                                                                          \
		if (*a->arguments)                                                     \
			irc_send (a->s, command " %s", a->arguments);                      \
		else                                                                   \
			irc_send (a->s, command);                                          \
		return true;                                                           \
	}

TRIVIAL_HANDLER (list,  "LIST")
TRIVIAL_HANDLER (who,   "WHO")
TRIVIAL_HANDLER (motd,  "MOTD")
TRIVIAL_HANDLER (oper,  "OPER")
TRIVIAL_HANDLER (stats, "STATS")

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool handle_command_help (struct handler_args *);

static struct command_handler
{
	const char *name;
	const char *description;
	const char *usage;
	bool (*handler) (struct handler_args *a);
	enum handler_flags flags;
}
g_command_handlers[] =
{
	{ "help",       "Show help",
	  "[<command> | <option>]",
	  handle_command_help,       0 },
	{ "quit",       "Quit the program",
	  "[<message>]",
	  handle_command_quit,       0 },
	{ "buffer",     "Manage buffers",
	  "<N> | list | clear | move <N> | goto <N or name> | close [<N or name>]",
	  handle_command_buffer,     0 },
	{ "set",        "Manage configuration",
	  "[<option>]",
	  handle_command_set,        0 },
	{ "save",       "Save configuration",
	  NULL,
	  handle_command_save,       0 },
	{ "plugin",     "Manage plugins",
	  "list | load <name> | unload <name>",
	  handle_command_plugin,     0 },
	{ "relay",      "Show relay information",
	  NULL,
	  handle_command_relay,      0 },

	{ "alias",      "List or set aliases",
	  "[<name> <definition>]",
	  handle_command_alias,      0 },
	{ "unalias",    "Unset aliases",
	  "<name>...",
	  handle_command_unalias,    0 },

	{ "msg",        "Send message to a nick or channel",
	  "<target> <message>",
	  handle_command_msg,        HANDLER_SERVER | HANDLER_NEEDS_REG },
	{ "query",      "Send a private message to a nick",
	  "<nick> <message>",
	  handle_command_query,      HANDLER_SERVER | HANDLER_NEEDS_REG },
	{ "notice",     "Send notice to a nick or channel",
	  "<target> <message>",
	  handle_command_notice,     HANDLER_SERVER | HANDLER_NEEDS_REG },
	{ "squery",     "Send a message to a service",
	  "<service> <message>",
	  handle_command_squery,     HANDLER_SERVER | HANDLER_NEEDS_REG },
	{ "ctcp",       "Send a CTCP query",
	  "<target> <tag>",
	  handle_command_ctcp,       HANDLER_SERVER | HANDLER_NEEDS_REG },
	{ "me",         "Send a CTCP action",
	  "<message>",
	  handle_command_me,         HANDLER_SERVER | HANDLER_NEEDS_REG },

	{ "join",       "Join channels",
	  "[<channel>[,<channel>...]] [<key>[,<key>...]]",
	  handle_command_join,       HANDLER_SERVER },
	{ "part",       "Leave channels",
	  "[<channel>[,<channel>...]] [<reason>]",
	  handle_command_part,       HANDLER_SERVER },
	{ "cycle",      "Rejoin channels",
	  "[<channel>[,<channel>...]] [<reason>]",
	  handle_command_cycle,      HANDLER_SERVER },

	{ "op",         "Give channel operator status",
	  "<nick>...",
	  handle_command_op,         HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "deop",       "Remove channel operator status",
	  "[<nick>...]",
	  handle_command_deop,       HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "voice",      "Give voice",
	  "<nick>...",
	  handle_command_voice,      HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "devoice",    "Remove voice",
	  "[<nick>...]",
	  handle_command_devoice,    HANDLER_SERVER | HANDLER_CHANNEL_FIRST },

	{ "mode",       "Change mode",
	  "[<channel>] [<mode>...]",
	  handle_command_mode,       HANDLER_SERVER },
	{ "topic",      "Change topic",
	  "[<channel>] [<topic>]",
	  handle_command_topic,      HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "kick",       "Kick user from channel",
	  "[<channel>] <user> [<reason>]",
	  handle_command_kick,       HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "kickban",    "Kick and ban user from channel",
	  "[<channel>] <user> [<reason>]",
	  handle_command_kickban,    HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "ban",        "Ban user from channel",
	  "[<channel>] [<mask>...]",
	  handle_command_ban,        HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "unban",      "Unban user from channel",
	  "[<channel>] <mask>...",
	  handle_command_unban,      HANDLER_SERVER | HANDLER_CHANNEL_FIRST },
	{ "invite",     "Invite user to channel",
	  "<user>... [<channel>]",
	  handle_command_invite,     HANDLER_SERVER | HANDLER_CHANNEL_LAST },

	{ "server",     "Manage servers",
	  "list | add <name> | remove <name> | rename <old> <new>",
	  handle_command_server,     0 },
	{ "connect",    "Connect to the server",
	  "[<server>]",
	  handle_command_connect,    0 },
	{ "disconnect", "Disconnect from the server",
	  "[<server> [<reason>]]",
	  handle_command_disconnect, 0 },

	{ "list",       "List channels and their topic",
	  "[<channel>[,<channel>...]] [<target>]",
	  handle_command_list,       HANDLER_SERVER },
	{ "names",      "List users on channel",
	  "[<channel>[,<channel>...]]",
	  handle_command_names,      HANDLER_SERVER },
	{ "who",        "List users",
	  "[<mask> [o]]",
	  handle_command_who,        HANDLER_SERVER },
	{ "whois",      "Get user information",
	  "[<target>] <mask>",
	  handle_command_whois,      HANDLER_SERVER },
	{ "whowas",     "Get user information",
	  "<user> [<count> [<target>]]",
	  handle_command_whowas,     HANDLER_SERVER },

	{ "motd",       "Get the Message of The Day",
	  "[<target>]",
	  handle_command_motd,       HANDLER_SERVER },
	{ "oper",       "Authenticate as an IRC operator",
	  "<name> <password>",
	  handle_command_oper,       HANDLER_SERVER },
	{ "kill",       "Kick another user from the server",
	  "<user> <comment>",
	  handle_command_kill,       HANDLER_SERVER },
	{ "stats",      "Query server statistics",
	  "[<query> [<target>]]",
	  handle_command_stats,      HANDLER_SERVER },
	{ "away",       "Set away status",
	  "[<text>]",
	  handle_command_away,       HANDLER_SERVER },
	{ "nick",       "Change current nick",
	  "<nickname>",
	  handle_command_nick,       HANDLER_SERVER },
	{ "quote",      "Send a raw command to the server",
	  "<command>",
	  handle_command_quote,      HANDLER_SERVER },
};

static bool
try_handle_command_help_option (struct app_context *ctx, const char *name)
{
	struct config_item *item =
		config_item_get (ctx->config.root, name, NULL);
	if (!item)
		return false;

	const struct config_schema *schema = item->schema;
	if (!schema)
	{
		log_global_error (ctx, "#s: #s", "Option not recognized", name);
		return true;
	}

	log_global_indent (ctx, "");
	log_global_indent (ctx, "Option \"#s\":", name);
	log_global_indent (ctx, "  Description: #s",
		schema->comment ? schema->comment : "(none)");
	log_global_indent (ctx, "  Type: #s", config_item_type_name (schema->type));
	log_global_indent (ctx, "  Default: #s",
		schema->default_ ? schema->default_ : "null");

	struct str tmp = str_make ();
	config_item_write (item, false, &tmp);
	log_global_indent (ctx, "  Current value: #s", tmp.str);
	str_free (&tmp);
	return true;
}

static bool
show_command_list (struct app_context *ctx)
{
	log_global_indent (ctx, "");
	log_global_indent (ctx, "Commands:");

	int longest = 0;
	for (size_t i = 0; i < N_ELEMENTS (g_command_handlers); i++)
	{
		int len = strlen (g_command_handlers[i].name);
		longest = MAX (longest, len);
	}
	for (size_t i = 0; i < N_ELEMENTS (g_command_handlers); i++)
	{
		struct command_handler *handler = &g_command_handlers[i];
		log_global_indent (ctx, "  #&s", xstrdup_printf
			("%-*s  %s", longest, handler->name, handler->description));
	}
	return true;
}

static bool
show_command_help (struct app_context *ctx, struct command_handler *handler)
{
	log_global_indent (ctx, "");
	log_global_indent (ctx, "/#s: #s", handler->name, handler->description);
	log_global_indent (ctx, "  Arguments: #s",
		handler->usage ? handler->usage : "(none)");
	return true;
}

static bool
handle_command_help (struct handler_args *a)
{
	struct app_context *ctx = a->ctx;
	if (!*a->arguments)
		return show_command_list (ctx);

	const char *word = cut_word (&a->arguments);

	const char *command = word + (*word == '/');
	for (size_t i = 0; i < N_ELEMENTS (g_command_handlers); i++)
	{
		struct command_handler *handler = &g_command_handlers[i];
		if (!strcasecmp_ascii (command, handler->name))
			return show_command_help (ctx, handler);
	}

	if (try_handle_command_help_option (ctx, word))
		return true;

	if (str_map_find (get_aliases_config (ctx), command))
		log_global_status (ctx, "/#s is an alias", command);
	else
		log_global_error (ctx, "#s: #s", "No such command or option", word);
	return true;
}

static void
init_user_command_map (struct str_map *map)
{
	*map = str_map_make (NULL);
	map->key_xfrm = tolower_ascii_strxfrm;

	for (size_t i = 0; i < N_ELEMENTS (g_command_handlers); i++)
	{
		struct command_handler *handler = &g_command_handlers[i];
		str_map_set (map, handler->name, handler);
	}
}

static bool
process_user_command (struct app_context *ctx, struct buffer *buffer,
	const char *command_name, char *input)
{
	static bool initialized = false;
	static struct str_map map;
	if (!initialized)
	{
		init_user_command_map (&map);
		initialized = true;
	}

	if (try_handle_buffer_goto (ctx, command_name))
		return true;

	struct handler_args args =
	{
		.ctx = ctx,
		.buffer = buffer,
		.arguments = input,
	};

	struct command_handler *handler;
	if (!(handler = str_map_find (&map, command_name)))
		return false;
	hard_assert (handler->flags == 0 || (handler->flags & HANDLER_SERVER));

	if ((handler->flags & HANDLER_SERVER)
		&& args.buffer->type == BUFFER_GLOBAL)
		log_global_error (ctx, "/#s: #s",
			command_name, "can't do this from a global buffer");
	else if ((handler->flags & HANDLER_SERVER)
		&& !irc_is_connected ((args.s = args.buffer->server)))
		log_server_error (args.s, args.s->buffer, "Not connected");
	else if ((handler->flags & HANDLER_NEEDS_REG)
		&& args.s->state != IRC_REGISTERED)
		log_server_error (args.s, args.s->buffer, "Not registered");
	else if (((handler->flags & HANDLER_CHANNEL_FIRST)
			&& !(args.channel_name =
				try_get_channel (&args, maybe_cut_word)))
		|| ((handler->flags & HANDLER_CHANNEL_LAST)
			&& !(args.channel_name =
				try_get_channel (&args, maybe_cut_word_from_end))))
		log_server_error (args.s, args.buffer, "/#s: #s", command_name,
			"no channel name given and this buffer is not a channel");
	else if (!handler->handler (&args))
		log_global_error (ctx,
			"#s: /#s #s", "Usage", handler->name, handler->usage);
	return true;
}

static const char *
expand_alias_escape (const char *p, const char *arguments, struct str *output)
{
	struct strv words = strv_make ();
	cstr_split (arguments, " ", true, &words);

	// TODO: eventually also add support for argument ranges
	//  - Can use ${0}, ${0:}, ${:0}, ${1:-1} with strtol, dispose of $1 syntax
	//    (default aliases don't use numeric arguments).
	//  - Start numbering from zero, since we'd have to figure out what to do
	//    in case we encounter a zero if we keep the current approach.
	//  - Ignore the sequence altogether if no closing '}' can be found,
	//    or if the internal format doesn't fit the above syntax.
	if (*p >= '1' && *p <= '9')
	{
		size_t offset = *p - '1';
		if (offset < words.len)
			str_append (output, words.vector[offset]);
	}
	else if (*p == '*')
		str_append (output, arguments);
	else if (strchr ("$;", *p))
		str_append_c (output, *p);
	else
		str_append_printf (output, "$%c", *p);

	strv_free (&words);
	return ++p;
}

static void
expand_alias_definition (const char *definition, const char *arguments,
	struct strv *commands)
{
	struct str expanded = str_make ();
	bool escape = false;
	for (const char *p = definition; *p; p++)
	{
		if (escape)
		{
			p = expand_alias_escape (p, arguments, &expanded) - 1;
			escape = false;
		}
		else if (*p == ';')
		{
			strv_append_owned (commands, str_steal (&expanded));
			expanded = str_make ();
		}
		else if (*p == '$' && p[1])
			escape = true;
		else
			str_append_c (&expanded, *p);
	}
	strv_append_owned (commands, str_steal (&expanded));
}

static bool
expand_alias (struct app_context *ctx,
	const char *alias_name, char *input, struct strv *commands)
{
	struct config_item *entry =
		str_map_find (get_aliases_config (ctx), alias_name);
	if (!entry)
		return false;

	if (!config_item_type_is_string (entry->type))
	{
		log_global_error (ctx, "Error executing `/#s': #s",
			alias_name, "alias definition is not a string");
		return false;
	}

	expand_alias_definition (entry->value.string.str, input, commands);
	return true;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
send_message_to_target (struct server *s,
	const char *target, char *message, struct buffer *buffer)
{
	if (!irc_is_connected (s))
		log_server_error (s, buffer, "Not connected");
	else
		SEND_AUTOSPLIT_PRIVMSG (s, target, message);
}

static void
send_message_to_buffer (struct app_context *ctx, struct buffer *buffer,
	char *message)
{
	hard_assert (buffer != NULL);

	switch (buffer->type)
	{
	case BUFFER_CHANNEL:
		send_message_to_target (buffer->server,
			buffer->channel->name, message, buffer);
		break;
	case BUFFER_PM:
		send_message_to_target (buffer->server,
			buffer->user->nickname, message, buffer);
		break;
	default:
		log_full (ctx, NULL, buffer, 0, BUFFER_LINE_ERROR,
			"This buffer is not a channel");
	}
}

static bool
process_alias (struct app_context *ctx, struct buffer *buffer,
	struct strv *commands, int level)
{
	for (size_t i = 0; i < commands->len; i++)
		log_global_debug (ctx, "Alias expanded to: ###d: \"#s\"",
			(int) i, commands->vector[i]);
	for (size_t i = 0; i < commands->len; i++)
		if (!process_input_line (ctx, buffer, commands->vector[i], ++level))
			return false;
	return true;
}

static bool
process_input_line_posthook (struct app_context *ctx, struct buffer *buffer,
	char *input, int alias_level)
{
	if (*input != '/' || *++input == '/')
	{
		send_message_to_buffer (ctx, buffer, input);
		return true;
	}

	char *name = cut_word (&input);
	if (process_user_command (ctx, buffer, name, input))
		return true;

	struct strv commands = strv_make ();
	bool result = false;
	if (!expand_alias (ctx, name, input, &commands))
		log_global_error (ctx, "#s: /#s", "No such command or alias", name);
	else if (alias_level != 0)
		log_global_error (ctx, "#s: /#s", "Aliases can't nest", name);
	else
		result = process_alias (ctx, buffer, &commands, alias_level);

	strv_free (&commands);
	return result;
}

static char *
process_input_hooks (struct app_context *ctx, struct buffer *buffer,
	char *input)
{
	uint64_t hash = siphash_wrapper (input, strlen (input));
	LIST_FOR_EACH (struct hook, iter, ctx->input_hooks)
	{
		struct input_hook *hook = (struct input_hook *) iter;
		if (!(input = hook->filter (hook, buffer, input)))
		{
			log_global_debug (ctx, "Input thrown away by hook");
			return NULL;
		}

		uint64_t new_hash = siphash_wrapper (input, strlen (input));
		if (new_hash != hash)
			log_global_debug (ctx, "Input transformed to \"#s\"#r", input);
		hash = new_hash;
	}
	return input;
}

static bool
process_input_line (struct app_context *ctx, struct buffer *buffer,
	const char *input, int alias_level)
{
	// Note that this also gets called on expanded aliases,
	// which might or might not be desirable (we can forward "alias_level")
	char *processed = process_input_hooks (ctx, buffer, xstrdup (input));
	bool result = !processed
		|| process_input_line_posthook (ctx, buffer, processed, alias_level);
	free (processed);
	return result;
}

static void
process_input (struct app_context *ctx, struct buffer *buffer,
	const char *input)
{
	struct strv lines = strv_make ();
	cstr_split (input, "\r\n", false, &lines);
	for (size_t i = 0; i < lines.len; i++)
		(void) process_input_line (ctx, buffer, lines.vector[i], 0);
	strv_free (&lines);
}

// --- Word completion ---------------------------------------------------------

// The amount of crap that goes into this is truly insane.
// It's mostly because of Editline's total ignorance of this task.

static void
completion_free (struct completion *self)
{
	free (self->line);
	free (self->words);
}

static void
completion_add_word (struct completion *self, size_t start, size_t end)
{
	if (!self->words)
		self->words = xcalloc ((self->words_alloc = 4), sizeof *self->words);
	if (self->words_len == self->words_alloc)
		self->words = xreallocarray (self->words,
			(self->words_alloc <<= 1), sizeof *self->words);
	self->words[self->words_len++] = (struct completion_word) { start, end };
}

static struct completion
completion_make (const char *line, size_t len)
{
	struct completion self = { .line = xstrndup (line, len) };

	// The first and the last word may be empty
	const char *s = self.line;
	while (true)
	{
		const char *start = s;
		size_t word_len = strcspn (s, WORD_BREAKING_CHARS);
		const char *end = start + word_len;
		s = end + strspn (end, WORD_BREAKING_CHARS);

		completion_add_word (&self, start - self.line, end - self.line);
		if (s == end)
			break;
	}
	return self;
}

static void
completion_locate (struct completion *self, size_t offset)
{
	size_t i = 0;
	for (; i < self->words_len; i++)
		if (self->words[i].start > offset)
			break;
	self->location = i - 1;
}

static char *
completion_word (struct completion *self, int word)
{
	hard_assert (word >= 0 && word < (int) self->words_len);
	return xstrndup (self->line + self->words[word].start,
		self->words[word].end - self->words[word].start);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// XXX: this isn't completely right because Unicode, but let's keep it simple.
//   At worst it will stop before a combining mark, or fail to compare
//   non-ASCII identifiers case-insensitively.

static size_t
utf8_common_prefix (const char **vector, size_t len)
{
	size_t prefix = 0;
	if (!vector || !len)
		return 0;

	struct utf8_iter a[len];
	for (size_t i = 0; i < len; i++)
		a[i] = utf8_iter_make (vector[i]);

	size_t ch_len;
	int32_t ch;
	while ((ch = utf8_iter_next (&a[0], &ch_len)) >= 0)
	{
		for (size_t i = 1; i < len; i++)
		{
			int32_t other = utf8_iter_next (&a[i], NULL);
			if (ch == other)
				continue;
			// Not bothering with lowercasing non-ASCII
			if (ch >= 0x80 || other >= 0x80
			 || tolower_ascii (ch) != tolower_ascii (other))
				return prefix;
		}
		prefix += ch_len;
	}
	return prefix;
}

static void
complete_command (struct app_context *ctx, struct completion *data,
	const char *word, struct strv *output)
{
	(void) data;

	const char *prefix = "";
	if (*word == '/')
	{
		word++;
		prefix = "/";
	}

	size_t word_len = strlen (word);
	for (size_t i = 0; i < N_ELEMENTS (g_command_handlers); i++)
	{
		struct command_handler *handler = &g_command_handlers[i];
		if (!strncasecmp_ascii (word, handler->name, word_len))
			strv_append_owned (output,
				xstrdup_printf ("%s%s", prefix, handler->name));
	}

	struct str_map_iter iter = str_map_iter_make (get_aliases_config (ctx));
	struct config_item *alias;
	while ((alias = str_map_iter_next (&iter)))
	{
		if (!strncasecmp_ascii (word, iter.link->key, word_len))
			strv_append_owned (output,
				xstrdup_printf ("%s%s", prefix, iter.link->key));
	}
}

static void
complete_option (struct app_context *ctx, struct completion *data,
	const char *word, struct strv *output)
{
	(void) data;

	struct strv options = strv_make ();
	config_dump (ctx->config.root, &options);
	strv_sort (&options);

	// Wildcard expansion is an interesting side-effect
	char *mask = xstrdup_printf ("%s*", word);
	for (size_t i = 0; i < options.len; i++)
	{
		char *key = cstr_cut_until (options.vector[i], " ");
		if (!fnmatch (mask, key, 0))
			strv_append_owned (output, key);
		else
			free (key);
	}
	free (mask);
	strv_free (&options);
}

static void
complete_set_value (struct config_item *item, const char *word,
	struct strv *output)
{
	struct str serialized = str_make ();
	config_item_write (item, false, &serialized);
	if (!strncmp (serialized.str, word, strlen (word)))
		strv_append_owned (output, str_steal (&serialized));
	else
		str_free (&serialized);
}

static void
complete_set_value_array (struct config_item *item, const char *word,
	struct strv *output)
{
	if (!item->schema || item->schema->type != CONFIG_ITEM_STRING_ARRAY)
		return;

	struct strv items = strv_make ();
	cstr_split (item->value.string.str, ",", false, &items);
	for (size_t i = 0; i < items.len; i++)
	{
		struct str wrapped = str_from_cstr (items.vector[i]);
		struct str serialized = str_make ();
		config_item_write_string (&serialized, &wrapped);
		str_free (&wrapped);

		if (!strncmp (serialized.str, word, strlen (word)))
			strv_append_owned (output, str_steal (&serialized));
		else
			str_free (&serialized);
	}
	strv_free (&items);
}

static void
complete_set (struct app_context *ctx, struct completion *data,
	const char *word, struct strv *output)
{
	if (data->location == 1)
	{
		complete_option (ctx, data, word, output);
		return;
	}
	if (data->location != 3)
		return;

	char *key = completion_word (data, 1);
	struct config_item *item = config_item_get (ctx->config.root, key, NULL);
	if (item)
	{
		char *op = completion_word (data, 2);
		if (!strcmp (op, "-=")) complete_set_value_array (item, word, output);
		if (!strcmp (op,  "=")) complete_set_value       (item, word, output);
		free (op);
	}
	free (key);
}

static void
complete_topic (struct buffer *buffer, struct completion *data,
	const char *word, struct strv *output)
{
	(void) data;

	// TODO: make it work in other server-related buffers, too, i.e. when we're
	//   completing the third word and the second word is a known channel name
	if (buffer->type != BUFFER_CHANNEL)
		return;

	const char *topic = buffer->channel->topic;
	if (topic && !strncasecmp_ascii (word, topic, strlen (word)))
	{
		// We must prepend the channel name if the topic itself starts
		// with something that could be regarded as a channel name
		strv_append_owned (output, irc_is_channel (buffer->server, topic)
			? xstrdup_printf ("%s %s", buffer->channel->name, topic)
			: xstrdup (topic));
	}
}

static void
complete_nicknames (struct buffer *buffer, struct completion *data,
	const char *word, struct strv *output)
{
	size_t word_len = strlen (word);
	if (buffer->type == BUFFER_SERVER)
	{
		struct user *self_user = buffer->server->irc_user;
		if (self_user && !irc_server_strncmp (buffer->server,
				word, self_user->nickname, word_len))
			strv_append (output, self_user->nickname);
	}
	if (buffer->type != BUFFER_CHANNEL)
		return;

	LIST_FOR_EACH (struct channel_user, iter, buffer->channel->users)
	{
		const char *nickname = iter->user->nickname;
		if (irc_server_strncmp (buffer->server, word, nickname, word_len))
			continue;
		strv_append_owned (output, data->location == 0
			? xstrdup_printf ("%s:", nickname)
			: xstrdup (nickname));
	}
}

static struct strv
complete_word (struct app_context *ctx, struct buffer *buffer,
	struct completion *data, const char *word)
{
	char *initial = completion_word (data, 0);

	// Start with a placeholder for the longest common prefix
	struct strv words = strv_make ();
	strv_append_owned (&words, NULL);

	if      (data->location == 0 && *initial == '/')
		complete_command   (ctx, data, word, &words);
	else if (data->location >= 1 && !strcmp (initial, "/set"))
		complete_set       (ctx, data, word, &words);
	else if (data->location == 1 && !strcmp (initial, "/help"))
	{
		complete_command   (ctx, data, word, &words);
		complete_option    (ctx, data, word, &words);
	}
	else if (data->location == 1 && !strcmp (initial, "/topic"))
	{
		complete_topic     (buffer, data, word, &words);
		complete_nicknames (buffer, data, word, &words);
	}
	else
		complete_nicknames (buffer, data, word, &words);

	cstr_set (&initial, NULL);
	LIST_FOR_EACH (struct hook, iter, ctx->completion_hooks)
	{
		struct completion_hook *hook = (struct completion_hook *) iter;
		hook->complete (hook, data, word, &words);
	}

	if (words.len <= 2)
	{
		// When nothing matches, this copies the sentinel value
		words.vector[0] = words.vector[1];
		words.vector[1] = NULL;
		words.len--;
	}
	else
	{
		size_t prefix = utf8_common_prefix
			((const char **) words.vector + 1, words.len - 1);
		if (!prefix)
			words.vector[0] = xstrdup (word);
		else
			words.vector[0] = xstrndup (words.vector[1], prefix);
	}
	return words;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/// A special wrapper for iconv_xstrdup() that also fixes indexes into the
/// original string to point to the right location in the output.
/// Thanks, Readline!  Without you I would have never needed to deal with this.
static char *
locale_to_utf8 (struct app_context *ctx, const char *locale,
	int *indexes[], size_t n_indexes)
{
	mbstate_t state;
	memset (&state, 0, sizeof state);

	size_t remaining = strlen (locale) + 1;
	const char *p = locale;

	// Reset the shift state, FWIW
	// TODO: Don't use this iconv handle directly at all, elsewhere in xC.
	//   And ideally use U+FFFD with EILSEQ.
	(void) iconv (ctx->term_to_utf8, NULL, NULL, NULL, NULL);

	bool fixed[n_indexes];
	memset (fixed, 0, sizeof fixed);

	struct str utf8 = str_make ();
	while (true)
	{
		size_t len = mbrlen (p, remaining, &state);

		// Incomplete multibyte character or illegal sequence (probably)
		if (len == (size_t) -2
		 || len == (size_t) -1)
		{
			str_free (&utf8);
			return NULL;
		}

		// Convert indexes into the multibyte string to UTF-8
		for (size_t i = 0; i < n_indexes; i++)
			if (!fixed[i] && *indexes[i] <= p - locale)
			{
				*indexes[i] = utf8.len;
				fixed[i] = true;
			}

		// End of string
		if (!len)
			break;

		// EINVAL (incomplete sequence) should never happen and
		// EILSEQ neither because we've already checked for that with mbrlen().
		// E2BIG is what iconv_xstrdup solves.  This must succeed.
		size_t ch_len;
		char *ch = iconv_xstrdup (ctx->term_to_utf8, (char *) p, len, &ch_len);
		hard_assert (ch != NULL);
		str_append_data (&utf8, ch, ch_len);
		free (ch);

		p += len;
		remaining -= len;
	}
	return str_steal (&utf8);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static struct strv
make_completions (struct app_context *ctx, struct buffer *buffer,
	const char *line_utf8, size_t start, size_t end)
{
	struct completion comp = completion_make (line_utf8, strlen (line_utf8));
	completion_locate (&comp, start);
	char *word = xstrndup (line_utf8 + start, end - start);
	struct strv completions = complete_word (ctx, buffer, &comp, word);
	free (word);
	completion_free (&comp);
	return completions;
}

/// Takes a line in locale-specific encoding and position of a word to complete,
/// returns a vector of matches in locale-specific encoding.
static char **
make_input_completions
	(struct app_context *ctx, const char *line, int start, int end)
{
	int *fixes[] = { &start, &end };
	char *line_utf8 = locale_to_utf8 (ctx, line, fixes, N_ELEMENTS (fixes));
	if (!line_utf8)
		return NULL;

	hard_assert (start >= 0 && end >= 0 && start <= end);

	struct strv completions =
		make_completions (ctx, ctx->current_buffer, line_utf8, start, end);
	free (line_utf8);
	if (!completions.len)
	{
		strv_free (&completions);
		return NULL;
	}
	for (size_t i = 0; i < completions.len; i++)
	{
		char *converted = iconv_xstrdup
			(ctx->term_from_utf8, completions.vector[i], -1, NULL);
		if (!soft_assert (converted))
			converted = xstrdup ("?");
		cstr_set (&completions.vector[i], converted);
	}
	return completions.vector;
}

// --- Common code for user actions --------------------------------------------

static void
toggle_bracketed_paste (bool enable)
{
	fprintf (stdout, "\x1b[?2004%c", "lh"[enable]);
	fflush (stdout);
}

static void
suspend_terminal (struct app_context *ctx)
{
	// Terminal can get suspended by both the pager and SIGTSTP handling
	if (ctx->terminal_suspended++ > 0)
		return;

	toggle_bracketed_paste (false);
	CALL (ctx->input, hide);
	poller_fd_reset (&ctx->tty_event);

	CALL_ (ctx->input, prepare, false);
}

static void
resume_terminal (struct app_context *ctx)
{
	if (--ctx->terminal_suspended > 0)
		return;

	update_screen_size ();
	CALL_ (ctx->input, prepare, true);
	CALL (ctx->input, on_tty_resized);

	toggle_bracketed_paste (true);
	// In theory we could just print all unseen messages but this is safer
	buffer_print_backlog (ctx, ctx->current_buffer);
	// Now it's safe to process any user input
	poller_fd_set (&ctx->tty_event, POLLIN);
	CALL (ctx->input, show);
}

static pid_t
spawn_helper_child (struct app_context *ctx)
{
	suspend_terminal (ctx);
	pid_t child = fork ();
	switch (child)
	{
	case -1:
	{
		int saved_errno = errno;
		resume_terminal (ctx);
		errno = saved_errno;
		break;
	}
	case 0:
		// Put the child in a new foreground process group
		hard_assert (setpgid (0, 0) != -1);
		hard_assert (tcsetpgrp (STDOUT_FILENO, getpgid (0)) != -1);
		break;
	default:
		// Make sure of it in the parent as well before continuing
		(void) setpgid (child, child);
	}
	return child;
}

static void
redraw_screen (struct app_context *ctx)
{
	// If by some circumstance we had the wrong idea
	CALL (ctx->input, on_tty_resized);
	update_screen_size ();

	CALL (ctx->input, hide);
	buffer_print_backlog (ctx, ctx->current_buffer);
	CALL (ctx->input, show);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool
dump_input_to_file (struct app_context *ctx, char *template, struct error **e)
{
	mode_t mask = umask (S_IXUSR | S_IRWXG | S_IRWXO);
	int fd = mkstemp (template);
	(void) umask (mask);

	if (fd < 0)
		return error_set (e, "%s", strerror (errno));

	char *input = CALL_ (ctx->input, get_line, NULL);
	bool success = xwrite (fd, input, strlen (input), e);
	free (input);

	if (!success)
		(void) unlink (template);

	xclose (fd);
	return success;
}

static char *
try_dump_input_to_file (struct app_context *ctx)
{
	char *template = resolve_filename
		("input.XXXXXX", resolve_relative_runtime_template);

	struct error *e = NULL;
	if (dump_input_to_file (ctx, template, &e))
		return template;

	log_global_error (ctx, "#s: #s",
		"Failed to create a temporary file for editing", e->message);
	error_free (e);
	free (template);
	return NULL;
}

static struct strv
build_editor_command (struct app_context *ctx, const char *filename)
{
	struct strv argv = strv_make ();
	const char *editor = get_config_string (ctx->config.root, "general.editor");
	if (!editor)
	{
		const char *command;
		if (!(command = getenv ("VISUAL"))
		 && !(command = getenv ("EDITOR")))
			command = "vi";

		// Although most visual editors support a "+LINE" argument
		// (every editor mentioned in the default value of general.editor,
		// plus vi, mcedit, vis, ...), it isn't particularly useful by itself.
		// We need to be able to specify the column number.
		//
		// Seeing as less popular software may try to process this as a filename
		// and fail, do not bother with this "undocumented standard feature".
		strv_append (&argv, command);
		strv_append (&argv, filename);
		return argv;
	}

	int cursor = 0;
	char *input = CALL_ (ctx->input, get_line, &cursor);
	hard_assert (cursor >= 0);

	mbstate_t ps;
	memset (&ps, 0, sizeof ps);

	wchar_t wch;
	size_t len, processed = 0, line_one_based = 1, column = 0;
	while (processed < (size_t) cursor
		&& (len = mbrtowc (&wch, input + processed, cursor - processed, &ps))
		&& len != (size_t) -2 && len != (size_t) -1)
	{
		// Both VIM and Emacs use the caret notation with columns.
		// Consciously leaving tabs broken, they're too difficult to handle.
		int width = wcwidth (wch);
		if (width < 0)
			width = 2;

		processed += len;
		if (wch == '\n')
		{
			line_one_based++;
			column = 0;
		}
		else
			column += width;
	}
	free (input);

	// Trivially split the command on spaces and substitute our values
	struct str argument = str_make ();
	for (; *editor; editor++)
	{
		if (*editor == ' ')
		{
			if (argument.len)
			{
				strv_append_owned (&argv, str_steal (&argument));
				argument = str_make ();
			}
			continue;
		}
		if (*editor != '%' || !editor[1])
		{
			str_append_c (&argument, *editor);
			continue;
		}

		// None of them are zero-length, thus words don't get lost
		switch (*++editor)
		{
		case 'F':
			str_append (&argument, filename);
			continue;
		case 'L':
			str_append_printf (&argument, "%zu", line_one_based);
			continue;
		case 'C':
			str_append_printf (&argument, "%zu", column + 1);
			continue;
		case 'B':
			str_append_printf (&argument, "%d",  cursor + 1);
			continue;
		case '%':
		case ' ':
			str_append_c (&argument, *editor);
			continue;
		}

		const char *p = editor;
		if (soft_assert (utf8_decode (&p, strlen (p)) > 0))
		{
			log_global_error (ctx, "Unknown substitution variable: %#&s",
				xstrndup (editor, p - editor));
		}
	}
	if (argument.len)
		strv_append_owned (&argv, str_steal (&argument));
	else
		str_free (&argument);
	return argv;
}

static bool
on_edit_input (int count, int key, void *user_data)
{
	(void) count;
	(void) key;
	struct app_context *ctx = user_data;

	char *filename;
	if (!(filename = try_dump_input_to_file (ctx)))
		return false;

	struct strv argv = build_editor_command (ctx, filename);
	if (!argv.len)
		strv_append (&argv, "true");

	hard_assert (!ctx->running_editor);
	switch (spawn_helper_child (ctx))
	{
	case 0:
		execvp (argv.vector[0], argv.vector);
		print_error ("%s: %s",
			"Failed to launch editor", strerror (errno));
		_exit (EXIT_FAILURE);
	case -1:
		log_global_error (ctx, "#s: #l",
			"Failed to launch editor", strerror (errno));
		free (filename);
		break;
	default:
		ctx->running_editor = true;
		ctx->editor_filename = filename;
	}
	strv_free (&argv);
	return true;
}

static void
input_editor_process (struct app_context *ctx)
{
	struct str input = str_make ();
	struct error *e = NULL;
	if (!read_file (ctx->editor_filename, &input, &e))
	{
		log_global_error (ctx, "#s: #s", "Input editing failed", e->message);
		error_free (e);
	}
	else
		CALL (ctx->input, clear_line);

	if (!CALL_ (ctx->input, insert, input.str))
		log_global_error (ctx, "#s: #s", "Input editing failed",
			"could not re-insert the modified text");

	str_free (&input);
}

static void
input_editor_cleanup (struct app_context *ctx)
{
	if (unlink (ctx->editor_filename))
		log_global_error (ctx, "Could not unlink `#l': #l",
			ctx->editor_filename, strerror (errno));

	cstr_set (&ctx->editor_filename, NULL);
	ctx->running_editor = false;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
launch_pager (struct app_context *ctx,
	int fd, const char *name, const char *path)
{
	hard_assert (!ctx->running_pager);
	switch (spawn_helper_child (ctx))
	{
	case 0:
		dup2 (fd, STDIN_FILENO);
		char *localized_name =
			iconv_xstrdup (ctx->term_from_utf8, (char *) name, -1, NULL);
		execl ("/bin/sh", "/bin/sh", "-c",
			get_config_string (ctx->config.root, "general.pager"),
			PROGRAM_NAME, localized_name, path, NULL);
		print_error ("%s: %s", "Failed to launch pager", strerror (errno));
		_exit (EXIT_FAILURE);
	case -1:
		log_global_error (ctx, "#s: #l",
			"Failed to launch pager", strerror (errno));
		break;
	default:
		ctx->running_pager = true;
	}
}

static bool
display_backlog (struct app_context *ctx, int flush_opts)
{
	FILE *backlog = tmpfile ();
	if (!backlog)
	{
		log_global_error (ctx, "#s: #l",
			"Failed to create a temporary file", strerror (errno));
		return false;
	}

	if (!get_config_boolean (ctx->config.root,
		"general.pager_strip_formatting"))
		flush_opts |= FLUSH_OPT_RAW;

	struct buffer *buffer = ctx->current_buffer;
	int until_marker =
		(int) buffer->lines_count - (int) buffer->new_messages_count;
	for (struct buffer_line *line = buffer->lines; line; line = line->next)
	{
		if (until_marker-- == 0
		 && buffer->new_messages_count != buffer->lines_count)
			buffer_print_read_marker (ctx, backlog, flush_opts);
		if (buffer_line_will_show_up (buffer, line))
			buffer_line_write_to_backlog (ctx, line, backlog, flush_opts);
	}

	// So that it is obvious if the last line in the buffer is not from today
	buffer_update_time (ctx, time (NULL), backlog, flush_opts);

	rewind (backlog);
	set_cloexec (fileno (backlog));
	launch_pager (ctx, fileno (backlog), buffer->name, NULL);
	fclose (backlog);
	return true;
}

static bool
on_display_backlog (int count, int key, void *user_data)
{
	(void) count;
	(void) key;
	return display_backlog (user_data, 0);
}

static bool
on_display_backlog_nowrap (int count, int key, void *user_data)
{
	(void) count;
	(void) key;
	return display_backlog (user_data, FLUSH_OPT_NOWRAP);
}

static FILE *
open_log_path (struct app_context *ctx, struct buffer *buffer, const char *path)
{
	FILE *fp = fopen (path, "rb");
	if (!fp)
	{
		log_global_error (ctx,
			"Failed to open `#l': #l", path, strerror (errno));
		return NULL;
	}

	if (buffer->log_file)
		// The regular flush will log any error eventually
		(void) fflush (buffer->log_file);

	set_cloexec (fileno (fp));
	return fp;
}

static bool
on_display_full_log (int count, int key, void *user_data)
{
	(void) count;
	(void) key;
	struct app_context *ctx = user_data;

	struct buffer *buffer = ctx->current_buffer;
	char *path = buffer_get_log_path (buffer);
	FILE *full_log = open_log_path (ctx, buffer, path);
	if (!full_log)
	{
		free (path);
		return false;
	}

	launch_pager (ctx, fileno (full_log), buffer->name, path);
	fclose (full_log);
	free (path);
	return true;
}

static bool
on_toggle_unimportant (int count, int key, void *user_data)
{
	(void) count;
	(void) key;
	struct app_context *ctx = user_data;
	buffer_toggle_unimportant (ctx, ctx->current_buffer);
	return true;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool
on_goto_buffer (int count, int key, void *user_data)
{
	(void) count;
	struct app_context *ctx = user_data;

	int n = key - '0';
	if (n < 0 || n > 9)
		return false;

	// There's no buffer zero
	if (n == 0)
		n = 10;

	if (!ctx->last_buffer || buffer_get_index (ctx, ctx->current_buffer) != n)
		return buffer_goto (ctx, n);

	// Fast switching between two buffers
	buffer_activate (ctx, ctx->last_buffer);
	return true;
}

static bool
on_previous_buffer (int count, int key, void *user_data)
{
	(void) key;
	buffer_activate (user_data, buffer_previous (user_data, count));
	return true;
}

static bool
on_next_buffer (int count, int key, void *user_data)
{
	(void) key;
	buffer_activate (user_data, buffer_next (user_data, count));
	return true;
}

static bool
on_switch_buffer (int count, int key, void *user_data)
{
	(void) count;
	(void) key;
	struct app_context *ctx = user_data;

	if (!ctx->last_buffer)
		return false;
	buffer_activate (ctx, ctx->last_buffer);
	return true;
}

static bool
on_goto_highlight (int count, int key, void *user_data)
{
	(void) count;
	(void) key;

	struct app_context *ctx = user_data;
	struct buffer *iter = ctx->current_buffer;;
	do
	{
		if (!(iter = iter->next))
			iter = ctx->buffers;
		if (iter == ctx->current_buffer)
			return false;
	}
	while (!iter->highlighted);
	buffer_activate (ctx, iter);
	return true;
}

static bool
on_goto_activity (int count, int key, void *user_data)
{
	(void) count;
	(void) key;

	struct app_context *ctx = user_data;
	struct buffer *iter = ctx->current_buffer;
	do
	{
		if (!(iter = iter->next))
			iter = ctx->buffers;
		if (iter == ctx->current_buffer)
			return false;
	}
	while (iter->new_messages_count == iter->new_unimportant_count);
	buffer_activate (ctx, iter);
	return true;
}

static bool
on_move_buffer_left (int count, int key, void *user_data)
{
	(void) key;

	struct app_context *ctx = user_data;
	int total = buffer_count (ctx);
	int n = buffer_get_index (ctx, ctx->current_buffer) - count;
	buffer_move (ctx, ctx->current_buffer, n <= 0
		? (total + n % total)
		: ((n - 1) % total + 1));
	return true;
}

static bool
on_move_buffer_right (int count, int key, void *user_data)
{
	return on_move_buffer_left (-count, key, user_data);
}

static bool
on_redraw_screen (int count, int key, void *user_data)
{
	(void) count;
	(void) key;

	redraw_screen (user_data);
	return true;
}

static bool
on_insert_attribute (int count, int key, void *user_data)
{
	(void) count;
	(void) key;

	struct app_context *ctx = user_data;
	ctx->awaiting_formatting_escape = true;
	return true;
}

static bool
on_start_paste_mode (int count, int key, void *user_data)
{
	(void) count;
	(void) key;

	struct app_context *ctx = user_data;
	ctx->in_bracketed_paste = true;
	return true;
}

static void
input_add_functions (void *user_data)
{
	struct app_context *ctx = user_data;
#define XX(...) CALL_ (ctx->input, register_fn, __VA_ARGS__, ctx);
	XX ("previous-buffer",    "Previous buffer",   on_previous_buffer)
	XX ("next-buffer",        "Next buffer",       on_next_buffer)
	XX ("goto-buffer",        "Go to buffer",      on_goto_buffer)
	XX ("switch-buffer",      "Switch buffer",     on_switch_buffer)
	XX ("goto-highlight",     "Go to highlight",   on_goto_highlight)
	XX ("goto-activity",      "Go to activity",    on_goto_activity)
	XX ("move-buffer-left",   "Move buffer left",  on_move_buffer_left)
	XX ("move-buffer-right",  "Move buffer right", on_move_buffer_right)
	XX ("display-backlog",    "Show backlog",      on_display_backlog)
	XX ("display-backlog-nw", "Non-wrapped log",   on_display_backlog_nowrap)
	XX ("display-full-log",   "Show full log",     on_display_full_log)
	XX ("toggle-unimportant", "Toggle junk msgs",  on_toggle_unimportant)
	XX ("edit-input",         "Edit input",        on_edit_input)
	XX ("redraw-screen",      "Redraw screen",     on_redraw_screen)
	XX ("insert-attribute",   "IRC formatting",    on_insert_attribute)
	XX ("start-paste-mode",   "Bracketed paste",   on_start_paste_mode)
#undef XX
}

static void
bind_common_keys (struct app_context *ctx)
{
	struct input *self = ctx->input;
	CALL_ (self, bind_control, 'p', "previous-buffer");
	CALL_ (self, bind_control, 'n', "next-buffer");

	// Redefine M-0 through M-9 to switch buffers
	for (int i = 0; i <= 9; i++)
		CALL_ (self, bind_meta, '0' + i, "goto-buffer");

	CALL_ (self, bind_meta, '\t', "switch-buffer");
	CALL_ (self, bind_meta, '!', "goto-highlight");
	CALL_ (self, bind_meta, 'a', "goto-activity");
	CALL_ (self, bind_meta, 'm', "insert-attribute");
	CALL_ (self, bind_meta, 'h', "display-full-log");
	CALL_ (self, bind_meta, 'H', "toggle-unimportant");
	CALL_ (self, bind_meta, 'e', "edit-input");

	if (key_f5)     CALL_ (self, bind, key_f5, "previous-buffer");
	if (key_f6)     CALL_ (self, bind, key_f6, "next-buffer");
	if (key_ppage)  CALL_ (self, bind, key_ppage, "display-backlog");

	if (clear_screen)
		CALL_ (self, bind_control, 'l', "redraw-screen");

	CALL_ (self, bind, "\x1b[200~", "start-paste-mode");
}

// --- GNU Readline user actions -----------------------------------------------

#ifdef HAVE_READLINE

static int
on_readline_return (int count, int key)
{
	(void) count;
	(void) key;

	// Let readline pass the line to our input handler
	rl_done = 1;

	struct app_context *ctx = g_ctx;
	struct input_rl *self = (struct input_rl *) ctx->input;

	// Hide the line, don't redisplay it
	CALL (ctx->input, hide);
	input_rl__restore (self);
	return 0;
}

static void
on_readline_input (char *line)
{
	struct app_context *ctx = g_ctx;
	struct input_rl *self = (struct input_rl *) ctx->input;

	if (line)
	{
		if (*line)
			add_history (line);

		// readline always erases the input line after returning from here,
		// but we don't want that to happen if the command to be executed
		// would switch the buffer (we'd keep the already executed command in
		// the old buffer and delete any input restored from the new buffer)
		strv_append_owned (&ctx->pending_input, line);
		poller_idle_set (&ctx->input_event);
	}
	else
	{
		// Prevent readline from showing the prompt twice for w/e reason
		CALL (ctx->input, hide);
		input_rl__restore (self);

		CALL (ctx->input, ding);
	}

	if (self->active)
		// Readline automatically redisplays it
		self->prompt_shown = 1;
}

static char **
app_readline_completion (const char *text, int start, int end)
{
	// We will reconstruct that ourselves
	(void) text;

	// Don't iterate over filenames and stuff
	rl_attempted_completion_over = true;

	return make_input_completions (g_ctx, rl_line_buffer, start, end);
}

static void
app_readline_display_matches (char **matches, int len, int longest)
{
	struct app_context *ctx = g_ctx;
	CALL (ctx->input, hide);
	rl_display_match_list (matches, len, longest);
	CALL (ctx->input, show);
}

static int
app_readline_init (void)
{
	struct app_context *ctx = g_ctx;
	struct input *self = ctx->input;

	// XXX: maybe use rl_make_bare_keymap() and start from there;
	//   our dear user could potentionally rig things up in a way that might
	//   result in some funny unspecified behaviour

	// For vi mode, enabling "show-mode-in-prompt" is recommended as there is
	// no easy way to indicate mode changes otherwise.

	rl_add_defun ("send-line", on_readline_return, -1);
	bind_common_keys (ctx);

	// Move native history commands
	CALL_ (self, bind_meta, 'p', "previous-history");
	CALL_ (self, bind_meta, 'n', "next-history");

	// We need to hide the prompt and input first
	rl_bind_key (RETURN, rl_named_function ("send-line"));
	CALL_ (self, bind_control, 'j', "send-line");

	rl_completion_display_matches_hook = app_readline_display_matches;

	rl_variable_bind ("completion-ignore-case", "on");
	rl_variable_bind ("menu-complete-display-prefix", "on");
	rl_bind_key (TAB, rl_named_function ("menu-complete"));
	if (key_btab)
		CALL_ (self, bind, key_btab, "menu-complete-backward");
	return 0;
}

#endif // HAVE_READLINE

// --- BSD Editline user actions -----------------------------------------------

#ifdef HAVE_EDITLINE

static unsigned char
on_editline_complete (EditLine *editline, int key)
{
	(void) key;
	struct app_context *ctx = g_ctx;

	// First prepare what Readline would have normally done for us...
	const LineInfo *info_mb = el_line (editline);
	int len = info_mb->lastchar - info_mb->buffer;
	int point = info_mb->cursor - info_mb->buffer;
	char *copy = xstrndup (info_mb->buffer, len);

	// XXX: possibly incorrect wrt. shift state encodings
	int el_start = point, el_end = point;
	while (el_start && !strchr (WORD_BREAKING_CHARS, copy[el_start - 1]))
		el_start--;

	char **completions = make_input_completions (ctx, copy, el_start, el_end);

	// XXX: possibly incorrect wrt. shift state encodings
	copy[el_end] = '\0';
	int el_len = mbstowcs (NULL, copy + el_start, 0);
	free (copy);

	if (!completions)
		return CC_REFRESH_BEEP;

	// Remove the original word
	el_wdeletestr (editline, el_len);

	// Insert the best match instead
	el_insertstr (editline, completions[0]);

	// I'm not sure if Readline's menu-complete can at all be implemented
	// with Editline--we have no way of detecting what the last executed handler
	// was.  Employ the formatter's wrapping feature to spew all options.
	bool only_match = !completions[1];
	if (!only_match)
	{
		CALL (ctx->input, hide);
		redraw_screen (ctx);

		struct formatter f = formatter_make (ctx, NULL);
		for (char **p = completions; *++p; )
			formatter_add (&f, " #l", *p);
		formatter_add (&f, "\n");
		formatter_flush (&f, stdout, 0);
		formatter_free (&f);

		CALL (ctx->input, show);
	}

	for (char **p = completions; *p; p++)
		free (*p);
	free (completions);
	if (!only_match)
		return CC_REFRESH_BEEP;

	// If there actually is just one match, finish the word
	el_insertstr (editline, " ");
	return CC_REFRESH;
}

static unsigned char
on_editline_return (EditLine *editline, int key)
{
	(void) key;
	struct app_context *ctx = g_ctx;
	struct input_el *self = (struct input_el *) ctx->input;

	const LineInfoW *info = el_wline (editline);
	int len = info->lastchar - info->buffer;
	wchar_t *line = calloc (sizeof *info->buffer, len + 1);
	memcpy (line, info->buffer, sizeof *info->buffer * len);

	if (*line)
	{
		HistEventW ev;
		history_w (self->current->history, &ev, H_ENTER, line);
	}
	free (line);

	// on_pending_input() expects a multibyte string
	const LineInfo *info_mb = el_line (editline);
	strv_append_owned (&ctx->pending_input,
		xstrndup (info_mb->buffer, info_mb->lastchar - info_mb->buffer));
	poller_idle_set (&ctx->input_event);

	// We must invoke ch_reset(), which isn't done for us with EL_UNBUFFERED.
	input_el__start_over (self);
	return CC_REFRESH;
}

static void
app_editline_init (struct input_el *self)
{
	// el_set() leaks memory in 20150325 and other versions, we need wchar_t
	el_wset (self->editline, EL_ADDFN,
		L"send-line", L"Send line",     on_editline_return);
	el_wset (self->editline, EL_ADDFN,
		L"complete",  L"Complete word", on_editline_complete);

	struct input *input = &self->super;
	input->add_functions (input->user_data);
	bind_common_keys (g_ctx);

	// Move native history commands
	CALL_ (input, bind_meta, 'p', "ed-prev-history");
	CALL_ (input, bind_meta, 'n', "ed-next-history");

	// No, editline, it's not supposed to kill the entire line
	CALL_ (input, bind_control, 'w', "ed-delete-prev-word");
	// Just what are you doing?
	CALL_ (input, bind_control, 'u', "vi-kill-line-prev");

	// We need to hide the prompt and input first
	CALL_ (input, bind, "\r", "send-line");
	CALL_ (input, bind, "\n", "send-line");

	CALL_ (input, bind_control, 'i', "complete");

	// Source the user's defaults file
	el_source (self->editline, NULL);

	// See input_el__redisplay(), functionally important
	CALL_ (input, bind_control, 'q', "ed-redisplay");
	// This is what buffered el_wgets() does, functionally important
	CALL_ (input, bind_control, 'c', "ed-start-over");
}

#endif // HAVE_EDITLINE

// --- Configuration loading ---------------------------------------------------

static const char *g_first_time_help[] =
{
	"",
	"\x02Welcome to xC!",
	"",
	"To get a list of all commands, type \x02/help\x02.  To obtain",
	"more information on a command or option, simply add it as",
	"a parameter, e.g. \x02/help set\x02 or \x02/help general.logging\x02.",
	"",
	"To switch between buffers, press \x02"
		"F5/Ctrl-P\x02 or \x02" "F6/Ctrl-N\x02.",
	"",
	"Finally, adding a network is as simple as:",
	" - \x02/server add IRCnet\x02",
	" - \x02/set servers.IRCnet.addresses = \"open.ircnet.net\"\x02",
	" - \x02/connect IRCnet\x02",
	"",
	"That should be enough to get you started.  Have fun!",
	""
};

static void
show_first_time_help (struct app_context *ctx)
{
	for (size_t i = 0; i < N_ELEMENTS (g_first_time_help); i++)
		log_global_indent (ctx, "#m", g_first_time_help[i]);
}

const char *g_default_aliases[][2] =
{
	{ "c",     "/buffer clear" }, { "close", "/buffer close" },
	{ "j",     "/join $*"      }, { "p",     "/part $*"      },
	{ "k",     "/kick $*"      }, { "kb",    "/kickban $*"   },
	{ "m",     "/msg $*"       }, { "q",     "/query $*"     },
	{ "n",     "/names $*"     }, { "t",     "/topic $*"     },
	{ "w",     "/who $*"       }, { "wi",    "/whois $*"     },
	{ "ww",    "/whowas $*"    },
};

static void
load_default_aliases (struct app_context *ctx)
{
	struct str_map *aliases = get_aliases_config (ctx);
	for (size_t i = 0; i < N_ELEMENTS (g_default_aliases); i++)
	{
		const char **pair = g_default_aliases[i];
		str_map_set (aliases, pair[0], config_item_string_from_cstr (pair[1]));
	}
}

static void
load_configuration (struct app_context *ctx)
{
	// In theory, we could ensure that only one instance is running by locking
	// the configuration file and ensuring here that it exists.  This is
	// however brittle, as it may be unlinked without the application noticing.

	struct config_item *root = NULL;
	struct error *e = NULL;

	char *filename = resolve_filename
		(PROGRAM_NAME ".conf", resolve_relative_config_filename);
	if (filename)
		root = config_read_from_file (filename, &e);
	else
		log_global_error (ctx, "Configuration file not found");
	free (filename);

	if (e)
	{
		log_global_error (ctx, "Cannot load configuration: #s", e->message);
		log_global_error (ctx,
			"Please either fix the configuration file or remove it");
		error_free (e);
		exit (EXIT_FAILURE);
	}

	if (root)
	{
		config_load (&ctx->config, root);
		log_global_status (ctx, "Configuration loaded");
	}
	else
	{
		show_first_time_help (ctx);
		load_default_aliases (ctx);
	}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
load_servers (struct app_context *ctx)
{
	struct str_map_iter iter = str_map_iter_make (get_servers_config (ctx));

	struct config_item *subtree;
	while ((subtree = str_map_iter_next (&iter)))
	{
		const char *name = iter.link->key;
		const char *err;
		if (subtree->type != CONFIG_ITEM_OBJECT)
			log_global_error (ctx, "Error in configuration: "
				"ignoring server `#s' as it's not an object", name);
		else if ((err = check_server_name_for_addition (ctx, name)))
			log_global_error (ctx, "Cannot load server `#s': #s", name, err);
		else
			server_add (ctx, name, subtree);
	}
}

// --- Signals -----------------------------------------------------------------

static int g_signal_pipe[2];            ///< A pipe used to signal... signals

/// Program termination has been requested by a signal
static volatile sig_atomic_t g_termination_requested;
/// The window has changed in size
static volatile sig_atomic_t g_winch_received;

static void
postpone_signal_handling (char id)
{
	int original_errno = errno;
	if (write (g_signal_pipe[1], &id, 1) == -1)
		soft_assert (errno == EAGAIN);
	errno = original_errno;
}

static void
signal_superhandler (int signum)
{
	switch (signum)
	{
	case SIGWINCH:
		g_winch_received = true;
		postpone_signal_handling ('w');
		break;
	case SIGINT:
	case SIGTERM:
		g_termination_requested = true;
		postpone_signal_handling ('t');
		break;
	case SIGCHLD:
		postpone_signal_handling ('c');
		break;
	case SIGTSTP:
		postpone_signal_handling ('s');
		break;
	default:
		hard_assert (!"unhandled signal");
	}
}

static void
setup_signal_handlers (void)
{
	if (pipe (g_signal_pipe) == -1)
		exit_fatal ("%s: %s", "pipe", strerror (errno));

	set_cloexec (g_signal_pipe[0]);
	set_cloexec (g_signal_pipe[1]);

	// So that the pipe cannot overflow; it would make write() block within
	// the signal handler, which is something we really don't want to happen.
	// The same holds true for read().
	set_blocking (g_signal_pipe[0], false);
	set_blocking (g_signal_pipe[1], false);

	signal (SIGPIPE, SIG_IGN);

	// So that we can write to the terminal while we're running a pager.
	// This is also inherited by the child so that it doesn't stop
	// when it calls tcsetpgrp().
	signal (SIGTTOU, SIG_IGN);

	struct sigaction sa;
	sa.sa_flags = SA_RESTART;
	sa.sa_handler = signal_superhandler;
	sigemptyset (&sa.sa_mask);

	if (sigaction (SIGWINCH, &sa, NULL) == -1
	 || sigaction (SIGINT,   &sa, NULL) == -1
	 || sigaction (SIGTERM,  &sa, NULL) == -1
	 || sigaction (SIGTSTP,  &sa, NULL) == -1
	 || sigaction (SIGCHLD,  &sa, NULL) == -1)
		exit_fatal ("sigaction: %s", strerror (errno));
}

// --- I/O event handlers ------------------------------------------------------

static bool
try_reap_child (struct app_context *ctx)
{
	int status;
	pid_t zombie = waitpid (-1, &status, WNOHANG | WUNTRACED);

	if (zombie == -1)
	{
		if (errno == ECHILD)  return false;
		if (errno == EINTR)   return true;
		exit_fatal ("%s: %s", "waitpid", strerror (errno));
	}
	if (!zombie)
		return false;

	if (WIFSTOPPED (status))
	{
		// We could also send SIGCONT but what's the point
		log_global_debug (ctx,
			"A child has been stopped, killing its process group");
		kill (-zombie, SIGKILL);
		return true;
	}

	if (ctx->running_pager)
		ctx->running_pager = false;
	else if (!ctx->running_editor)
	{
		log_global_debug (ctx, "An unknown child has died");
		return true;
	}

	hard_assert (tcsetpgrp (STDOUT_FILENO, getpgid (0)) != -1);
	resume_terminal (ctx);

	if (WIFSIGNALED (status))
		log_global_error (ctx,
			"Child died from signal #d", WTERMSIG (status));
	else if (WIFEXITED (status) && WEXITSTATUS (status) != 0)
		log_global_error (ctx,
			"Child returned status #d", WEXITSTATUS (status));
	else if (ctx->running_editor)
		input_editor_process (ctx);

	if (ctx->running_editor)
		input_editor_cleanup (ctx);
	return true;
}

static void
on_signal_pipe_readable (const struct pollfd *fd, struct app_context *ctx)
{
	char id = 0;
	(void) read (fd->fd, &id, 1);

	// Stop ourselves cleanly, even if it makes little sense to do this
	if (id == 's')
	{
		suspend_terminal (ctx);
		kill (getpid (), SIGSTOP);
		g_winch_received = true;
		resume_terminal (ctx);
	}

	// Reap all dead children (since the signal pipe may overflow etc. we run
	// waitpid() in a loop to return all the zombies it knows about).
	while (try_reap_child (ctx))
		;

	if (g_termination_requested)
	{
		g_termination_requested = false;
		request_quit (ctx, NULL);
	}
	if (g_winch_received)
	{
		g_winch_received = false;
		redraw_screen (ctx);
	}
}

static void
process_formatting_escape (const struct pollfd *fd, struct app_context *ctx)
{
	// There's no other way with libedit, as both el_getc() in a function
	// handler and CC_ARGHACK would block execution
	struct str *buf = &ctx->input_buffer;
	str_reserve (buf, 1);
	if (read (fd->fd, buf->str + buf->len, 1) != 1)
		goto error;
	buf->str[++buf->len] = '\0';

	// XXX: I think this should be global and shared with Readline/libedit
	mbstate_t state;
	memset (&state, 0, sizeof state);

	size_t len = mbrlen (buf->str, buf->len, &state);

	// Illegal sequence
	if (len == (size_t) -1)
		goto error;

	// Incomplete multibyte character
	if (len == (size_t) -2)
		return;

	if (buf->len != 1)
		goto error;

	// Letters mostly taken from their caret escapes + HTML element names.
	// Additionally, 'm' stands for mono, 'x' for cross, 'r' for reset.
	switch (buf->str[0])
	{
	case 'b' ^ 96:
	case 'b': CALL_ (ctx->input, insert, "\x02"); break;
	case 'c': CALL_ (ctx->input, insert, "\x03"); break;
	case 'q':
	case 'm': CALL_ (ctx->input, insert, "\x11"); break;
	case 'v': CALL_ (ctx->input, insert, "\x16"); break;
	case 'i' ^ 96:
	case 'i':
	case ']': CALL_ (ctx->input, insert, "\x1d"); break;
	case 's' ^ 96:
	case 's':
	case 'x' ^ 96:
	case 'x':
	case '^': CALL_ (ctx->input, insert, "\x1e"); break;
	case 'u' ^ 96:
	case 'u':
	case '_': CALL_ (ctx->input, insert, "\x1f"); break;
	case 'r':
	case 'o': CALL_ (ctx->input, insert, "\x0f"); break;

	default:
		goto error;
	}
	goto done;

error:
	CALL (ctx->input, ding);
done:
	str_reset (buf);
	ctx->awaiting_formatting_escape = false;
}

#define BRACKETED_PASTE_LIMIT 102400    ///< How much text can be pasted

static bool
insert_paste (struct app_context *ctx, char *paste, size_t len)
{
	if (!get_config_boolean (ctx->config.root, "general.process_pasted_text"))
		return CALL_ (ctx->input, insert, paste);

	// Without ICRNL, which Editline keeps but Readline doesn't,
	// the terminal sends newlines as carriage returns (seen on urxvt)
	for (size_t i = 0; i < len; i++)
		if (paste[i] == '\r')
			paste[i] = '\n';

	int position = 0;
	char *input = CALL_ (ctx->input, get_line, &position);
	bool quote_first_slash = !position || strchr ("\r\n", input[position - 1]);
	free (input);

	// Executing commands by accident is much more common than pasting them
	// intentionally, although the latter may also have security consequences
	struct str processed = str_make ();
	str_reserve (&processed, len);
	for (size_t i = 0; i < len; i++)
	{
		if (paste[i] == '/'
			&& ((!i && quote_first_slash) || (i && paste[i - 1] == '\n')))
			str_append_c (&processed, paste[i]);
		str_append_c (&processed, paste[i]);
	}

	bool success = CALL_ (ctx->input, insert, processed.str);
	str_free (&processed);
	return success;
}

static void
process_bracketed_paste (const struct pollfd *fd, struct app_context *ctx)
{
	struct str *buf = &ctx->input_buffer;
	str_reserve (buf, 1);
	if (read (fd->fd, buf->str + buf->len, 1) != 1)
		goto error;
	buf->str[++buf->len] = '\0';

	static const char stop_mark[] = "\x1b[201~";
	static const size_t stop_mark_len = sizeof stop_mark - 1;
	if (buf->len < stop_mark_len)
		return;

	size_t text_len = buf->len - stop_mark_len;
	if (memcmp (buf->str + text_len, stop_mark, stop_mark_len))
		return;

	// Avoid endless flooding of the buffer
	if (text_len > BRACKETED_PASTE_LIMIT)
		log_global_error (ctx, "Paste trimmed to #d bytes",
			(int) (text_len = BRACKETED_PASTE_LIMIT));

	buf->str[text_len] = '\0';
	if (insert_paste (ctx, buf->str, text_len))
		goto done;

error:
	CALL (ctx->input, ding);
	log_global_error (ctx, "Paste failed");
done:
	str_reset (buf);
	ctx->in_bracketed_paste = false;
}

static void
reset_autoaway (struct app_context *ctx)
{
	// Stop the last one if it's been disabled altogether in the meantime
	poller_timer_reset (&ctx->autoaway_tmr);

	// Unset any automated statuses that are active right at this moment
	struct str_map_iter iter = str_map_iter_make (&ctx->servers);
	struct server *s;
	while ((s = str_map_iter_next (&iter)))
	{
		if (s->autoaway_active
		 && s->irc_user
		 && s->irc_user->away)
			irc_send (s, "AWAY");

		s->autoaway_active = false;
	}

	// And potentially start a new auto-away timer
	int64_t delay = get_config_integer
		(ctx->config.root, "general.autoaway_delay");
	if (delay)
		poller_timer_set (&ctx->autoaway_tmr, delay * 1000);
}

static void
on_autoaway_timer (struct app_context *ctx)
{
	// An empty message would unset any away status, so let's ignore that
	const char *message = get_config_string
		(ctx->config.root, "general.autoaway_message");
	if (!message || !*message)
		return;

	struct str_map_iter iter = str_map_iter_make (&ctx->servers);
	struct server *s;
	while ((s = str_map_iter_next (&iter)))
	{
		// If the user has already been marked as away,
		// don't override his current away status
		if (s->irc_user
		 && s->irc_user->away)
			continue;

		irc_send (s, "AWAY :%s", message);
		s->autoaway_active = true;
	}
}

static void
on_tty_readable (const struct pollfd *fd, struct app_context *ctx)
{
	if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
		print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);

	if (ctx->awaiting_formatting_escape)
		process_formatting_escape (fd, ctx);
	else if (ctx->in_bracketed_paste)
		process_bracketed_paste (fd, ctx);
	else if (!ctx->quitting)
		CALL (ctx->input, on_tty_readable);

	// User activity detected, stop current auto-away and start anew;
	// since they might have just changed the settings, do this last
	reset_autoaway (ctx);
}

static void
rearm_flush_timer (struct app_context *ctx)
{
	poller_timer_set (&ctx->flush_timer, 60 * 1000);
}

static void
on_flush_timer (struct app_context *ctx)
{
	// I guess we don't need to do anything more complicated
	fflush (NULL);

	// It would be a bit problematic to handle it properly, so do this at least
	LIST_FOR_EACH (struct buffer, buffer, ctx->buffers)
	{
		if (!buffer->log_file || !ferror (buffer->log_file))
			continue;

		// Might be a transient error such as running out of disk space,
		// keep notifying of the problem until it disappears
		clearerr (buffer->log_file);
		log_global (ctx, BUFFER_LINE_SKIP_FILE, BUFFER_LINE_ERROR,
			"Log write failure detected for #s", buffer->name);
	}

#ifdef LOMEM
	// Lua should normally be reasonable and collect garbage when needed,
	// though we can try to push it.  This is a reasonable place.
	LIST_FOR_EACH (struct plugin, iter, ctx->plugins)
		if (iter->vtable->gc)
			iter->vtable->gc (iter);
#endif // LOMEM

	rearm_flush_timer (ctx);
}

static void
rearm_date_change_timer (struct app_context *ctx)
{
	struct tm tm_;
	const time_t now = time (NULL);
	if (!soft_assert (localtime_r (&now, &tm_)))
		return;

	tm_.tm_sec = tm_.tm_min = tm_.tm_hour = 0;
	tm_.tm_mday++;
	tm_.tm_isdst = -1;

	const time_t midnight = mktime (&tm_);
	if (!soft_assert (midnight != (time_t) -1))
		return;
	poller_timer_set (&ctx->date_chg_tmr, (midnight - now) * 1000);
}

static void
on_date_change_timer (struct app_context *ctx)
{
	if (ctx->terminal_suspended <= 0)
	{
		CALL (ctx->input, hide);
		buffer_update_time (ctx, time (NULL), stdout, 0);
		CALL (ctx->input, show);
	}
	rearm_date_change_timer (ctx);
}

static void
on_pending_input (struct app_context *ctx)
{
	poller_idle_reset (&ctx->input_event);
	for (size_t i = 0; i < ctx->pending_input.len; i++)
	{
		char *input = iconv_xstrdup (ctx->term_to_utf8,
			ctx->pending_input.vector[i], -1, NULL);
		if (!input)
		{
			print_error ("character conversion failed for: %s", "user input");
			continue;
		}

		relay_prepare_buffer_input (ctx, ctx->current_buffer, input);
		relay_broadcast (ctx);

		process_input (ctx, ctx->current_buffer, input);
		free (input);
	}
	strv_reset (&ctx->pending_input);
}

static void
init_poller_events (struct app_context *ctx)
{
	ctx->signal_event = poller_fd_make (&ctx->poller, g_signal_pipe[0]);
	ctx->signal_event.dispatcher = (poller_fd_fn) on_signal_pipe_readable;
	ctx->signal_event.user_data = ctx;
	poller_fd_set (&ctx->signal_event, POLLIN);

	ctx->tty_event = poller_fd_make (&ctx->poller, STDIN_FILENO);
	ctx->tty_event.dispatcher = (poller_fd_fn) on_tty_readable;
	ctx->tty_event.user_data = ctx;
	poller_fd_set (&ctx->tty_event, POLLIN);

	ctx->flush_timer = poller_timer_make (&ctx->poller);
	ctx->flush_timer.dispatcher = (poller_timer_fn) on_flush_timer;
	ctx->flush_timer.user_data = ctx;
	rearm_flush_timer (ctx);

	ctx->date_chg_tmr = poller_timer_make (&ctx->poller);
	ctx->date_chg_tmr.dispatcher = (poller_timer_fn) on_date_change_timer;
	ctx->date_chg_tmr.user_data = ctx;
	rearm_date_change_timer (ctx);

	ctx->autoaway_tmr = poller_timer_make (&ctx->poller);
	ctx->autoaway_tmr.dispatcher = (poller_timer_fn) on_autoaway_timer;
	ctx->autoaway_tmr.user_data = ctx;

	ctx->prompt_event = poller_idle_make (&ctx->poller);
	ctx->prompt_event.dispatcher = (poller_idle_fn) on_refresh_prompt;
	ctx->prompt_event.user_data = ctx;

	ctx->input_event = poller_idle_make (&ctx->poller);
	ctx->input_event.dispatcher = (poller_idle_fn) on_pending_input;
	ctx->input_event.user_data = ctx;
}

// --- Relay processing --------------------------------------------------------

// XXX: This could be below completion code if reset_autoaway() was higher up.

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
client_resync_buffer_input (struct client *c, struct buffer *buffer)
{
	struct strv history =
		CALL_ (c->ctx->input, buffer_get_history, buffer->input_data);
	for (size_t i = 0; i < history.len; i++)
	{
		char *input = iconv_xstrdup (c->ctx->term_to_utf8,
			history.vector[i], -1, NULL);
		if (!input)
		{
			print_error ("character conversion failed for: %s",
				"user input history");
			continue;
		}

		relay_prepare_buffer_input (c->ctx, buffer, input);
		relay_send (c);
		free (input);
	}
	strv_free (&history);
}

static void
client_resync (struct client *c)
{
	struct str_map_iter iter = str_map_iter_make (&c->ctx->servers);
	struct server *s;
	while ((s = str_map_iter_next (&iter)))
	{
		relay_prepare_server_update (c->ctx, s);
		relay_send (c);
	}

	LIST_FOR_EACH (struct buffer, buffer, c->ctx->buffers)
	{
		relay_prepare_buffer_update (c->ctx, buffer);
		relay_send (c);
		relay_prepare_buffer_stats (c->ctx, buffer);
		relay_send (c);

		client_resync_buffer_input (c, buffer);

		LIST_FOR_EACH (struct buffer_line, line, buffer->lines)
		{
			relay_prepare_buffer_line (c->ctx, buffer, line, false);
			relay_send (c);
		}
	}

	relay_prepare_buffer_activate (c->ctx, c->ctx->current_buffer);
	relay_send (c);
}

static const char *
client_message_buffer_name (const struct relay_command_message *m)
{
	switch (m->data.command)
	{
	case RELAY_COMMAND_BUFFER_COMPLETE:
		return m->data.buffer_complete.buffer_name.str;
	case RELAY_COMMAND_BUFFER_ACTIVATE:
		return m->data.buffer_activate.buffer_name.str;
	case RELAY_COMMAND_BUFFER_INPUT:
		return m->data.buffer_input.buffer_name.str;
	case RELAY_COMMAND_BUFFER_TOGGLE_UNIMPORTANT:
		return m->data.buffer_toggle_unimportant.buffer_name.str;
	case RELAY_COMMAND_BUFFER_LOG:
		return m->data.buffer_log.buffer_name.str;
	default:
		return NULL;
	}
}

static void
client_process_buffer_complete (struct client *c, uint32_t seq,
	struct buffer *buffer, struct relay_command_data_buffer_complete *req)
{
	struct str *line = &req->text;
	uint32_t end = req->position;
	if (line->len < end || line->len != strlen (line->str))
	{
		relay_prepare_error (c->ctx, seq, "Invalid arguments");
		goto out;
	}

	uint32_t start = end;
	while (start && !strchr (WORD_BREAKING_CHARS, line->str[start - 1]))
		start--;

	struct strv completions =
		make_completions (c->ctx, buffer, line->str, start, end);
	if (completions.len > UINT32_MAX)
	{
		relay_prepare_error (c->ctx, seq, "Internal error");
		goto out_internal;
	}

	struct relay_event_data_response *e = relay_prepare_response (c->ctx, seq);
	e->data.command = RELAY_COMMAND_BUFFER_COMPLETE;
	struct relay_response_data_buffer_complete *resp =
		&e->data.buffer_complete;
	resp->start = start;
	resp->completions_len = completions.len;
	resp->completions = xcalloc (completions.len, sizeof *resp->completions);
	for (size_t i = 0; i < completions.len; i++)
		resp->completions[i] = str_from_cstr (completions.vector[i]);

out_internal:
	strv_free (&completions);
out:
	relay_send (c);
}

static void
client_process_buffer_input
	(struct client *c, struct buffer *buffer, const char *input)
{
	char *mb = iconv_xstrdup (c->ctx->term_from_utf8, (char *) input, -1, NULL);
	CALL_ (c->ctx->input, buffer_add_history, buffer->input_data, mb);
	free (mb);

	relay_prepare_buffer_input (c->ctx, buffer, input);
	relay_broadcast_except (c->ctx, c);

	process_input (c->ctx, buffer, input);
}

static void
client_process_buffer_log
	(struct client *c, uint32_t seq, struct buffer *buffer)
{
	// XXX: We log failures to the global buffer,
	//   so the client just receives nothing if there is no log file.
	struct str log = str_make ();
	char *path = buffer_get_log_path (buffer);
	FILE *fp = open_log_path (c->ctx, buffer, path);
	if (fp)
	{
		char buf[BUFSIZ];
		size_t len;
		while ((len = fread (buf, 1, sizeof buf, fp)))
			str_append_data (&log, buf, len);
		if (ferror (fp))
			log_global_error (c->ctx, "Failed to read `#l': #l",
				path, strerror (errno));
		fclose (fp);
	}
	free (path);

	struct relay_event_data_response *e = relay_prepare_response (c->ctx, seq);
	e->data.command = RELAY_COMMAND_BUFFER_LOG;
	// On overflow, it will later fail serialization (frame will be too long).
	e->data.buffer_log.log_len = MIN (UINT32_MAX, log.len);
	e->data.buffer_log.log = (uint8_t *) str_steal (&log);
	relay_send (c);
}

static bool
client_process_message (struct client *c,
	struct msg_unpacker *r, struct relay_command_message *m)
{
	if (!relay_command_message_deserialize (m, r)
	 || msg_unpacker_get_available (r))
	{
		log_global_error (c->ctx, "Deserialization failed, killing client");
		return false;
	}

	const char *buffer_name = client_message_buffer_name (m);
	struct buffer *buffer = NULL;
	if (buffer_name && !(buffer = buffer_by_name (c->ctx, buffer_name)))
	{
		relay_prepare_error (c->ctx, m->command_seq, "Unknown buffer");
		relay_send (c);
		return true;
	}

	switch (m->data.command)
	{
	case RELAY_COMMAND_HELLO:
		if (m->data.hello.version != RELAY_VERSION)
		{
			// TODO: This should send back an error message and shut down.
			log_global_error (c->ctx,
				"Protocol version mismatch, killing client");
			return false;
		}
		c->initialized = true;
		client_resync (c);
		break;
	case RELAY_COMMAND_PING:
		relay_prepare_response (c->ctx, m->command_seq)
			->data.command = RELAY_COMMAND_PING;
		relay_send (c);
		break;
	case RELAY_COMMAND_ACTIVE:
		reset_autoaway (c->ctx);
		break;
	case RELAY_COMMAND_BUFFER_COMPLETE:
		client_process_buffer_complete (c, m->command_seq, buffer,
			&m->data.buffer_complete);
		break;
	case RELAY_COMMAND_BUFFER_ACTIVATE:
		buffer_activate (c->ctx, buffer);
		break;
	case RELAY_COMMAND_BUFFER_INPUT:
		client_process_buffer_input (c, buffer, m->data.buffer_input.text.str);
		break;
	case RELAY_COMMAND_BUFFER_TOGGLE_UNIMPORTANT:
		buffer_toggle_unimportant (c->ctx, buffer);
		break;
	case RELAY_COMMAND_BUFFER_LOG:
		client_process_buffer_log (c, m->command_seq, buffer);
		break;
	default:
		log_global_debug (c->ctx, "Unhandled client command");
		relay_prepare_error (c->ctx, m->command_seq, "Unknown command");
		relay_send (c);
	}
	return true;
}

static bool
client_process_buffer (struct client *c)
{
	struct str *buf = &c->read_buffer;
	size_t offset = 0;
	while (true)
	{
		uint32_t frame_len = 0;
		struct msg_unpacker r =
			msg_unpacker_make (buf->str + offset, buf->len - offset);
		if (!msg_unpacker_u32 (&r, &frame_len))
			break;

		r.len = MIN (r.len, sizeof frame_len + frame_len);
		if (msg_unpacker_get_available (&r) < frame_len)
			break;

		struct relay_command_message m = {};
		bool ok = client_process_message (c, &r, &m);
		relay_command_message_free (&m);
		if (!ok)
			return false;

		offset += r.offset;
	}

	str_remove_slice (buf, 0, offset);
	return true;
}

// --- Relay plumbing ----------------------------------------------------------

static bool
client_try_read (struct client *c)
{
	struct str *buf = &c->read_buffer;
	ssize_t n_read;

	while ((n_read = read (c->socket_fd, buf->str + buf->len,
		buf->alloc - buf->len - 1 /* null byte */)) > 0)
	{
		buf->len += n_read;
		if (!client_process_buffer (c))
			break;
		str_reserve (buf, 512);
	}

	if (n_read < 0)
	{
		if (errno == EAGAIN || errno == EINTR)
			return true;

		log_global_debug (c->ctx,
			"#s: #s: #l", __func__, "read", strerror (errno));
	}

	client_kill (c);
	return false;
}

static bool
client_try_write (struct client *c)
{
	struct str *buf = &c->write_buffer;
	ssize_t n_written;

	while (buf->len)
	{
		n_written = write (c->socket_fd, buf->str, buf->len);
		if (n_written >= 0)
		{
			str_remove_slice (buf, 0, n_written);
			continue;
		}
		if (errno == EAGAIN || errno == EINTR)
			return true;

		log_global_debug (c->ctx,
			"#s: #s: #l", __func__, "write", strerror (errno));
		client_kill (c);
		return false;
	}
	return true;
}

static void
on_client_ready (const struct pollfd *pfd, void *user_data)
{
	struct client *c = user_data;
	if (client_try_read (c) && client_try_write (c))
		client_update_poller (c, pfd);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static bool
relay_try_fetch_client (struct app_context *ctx, int listen_fd)
{
	// XXX: `struct sockaddr_storage' is not the most portable thing
	struct sockaddr_storage peer;
	socklen_t peer_len = sizeof peer;

	int fd = accept (listen_fd, (struct sockaddr *) &peer, &peer_len);
	if (fd == -1)
	{
		if (errno == EAGAIN || errno == EWOULDBLOCK)
			return false;
		if (errno == EINTR)
			return true;

		if (accept_error_is_transient (errno))
		{
			log_global_debug (ctx, "#s: #l", "accept", strerror (errno));
			return true;
		}

		log_global_error (ctx, "#s: #l", "accept", strerror (errno));
		app_context_relay_stop (ctx);
		return false;
	}

	hard_assert (peer_len <= sizeof peer);
	set_blocking (fd, false);
	set_cloexec (fd);

	// We already buffer our output, so reduce latencies.
	int yes = 1;
	soft_assert (setsockopt (fd, IPPROTO_TCP, TCP_NODELAY,
		&yes, sizeof yes) != -1);

	struct client *c = client_new ();
	c->ctx = ctx;
	c->socket_fd = fd;
	LIST_PREPEND (ctx->clients, c);

	c->socket_event = poller_fd_make (&c->ctx->poller, c->socket_fd);
	c->socket_event.dispatcher = (poller_fd_fn) on_client_ready;
	c->socket_event.user_data = c;

	client_update_poller (c, NULL);
	return true;
}

static void
on_relay_client_available (const struct pollfd *pfd, void *user_data)
{
	struct app_context *ctx = user_data;
	while (relay_try_fetch_client (ctx, pfd->fd))
		;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static int
relay_listen (struct addrinfo *ai, struct error **e)
{
	int fd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol);
	if (fd == -1)
	{
		error_set (e, "socket: %s", strerror (errno));
		return -1;
	}

	set_cloexec (fd);

	int yes = 1;
	soft_assert (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
		&yes, sizeof yes) != -1);
	soft_assert (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
		&yes, sizeof yes) != -1);

	if (bind (fd, ai->ai_addr, ai->ai_addrlen))
		error_set (e, "bind: %s", strerror (errno));
	else if (listen (fd, 16 /* arbitrary number */))
		error_set (e, "listen: %s", strerror (errno));
	else
		return fd;

	xclose (fd);
	return -1;
}

static int
relay_listen_with_context (struct app_context *ctx, struct addrinfo *ai,
	struct error **e)
{
	char *address = gai_reconstruct_address (ai);
	log_global_debug (ctx, "binding to `#l'", address);

	struct error *error = NULL;
	int fd = relay_listen (ai, &error);
	if (fd == -1)
	{
		error_set (e, "binding to `%s' failed: %s", address, error->message);
		error_free (error);
	}
	free (address);
	return fd;
}

static bool
relay_start (struct app_context *ctx, char *address, struct error **e)
{
	const char *port = NULL, *host = tokenize_host_port (address, &port);
	if (!port || !*port)
		return error_set (e, "missing port");

	struct addrinfo hints = {}, *result = NULL;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	int err = getaddrinfo (*host ? host : NULL, port, &hints, &result);
	if (err)
	{
		return error_set (e, "failed to resolve `%s', port `%s': %s: %s",
			host, port, "getaddrinfo", gai_strerror (err));
	}

	// Just try the first one, disregarding IPv4/IPv6 ordering.
	// Use 0.0.0.0 or [::] to request either one specifically.
	int fd = relay_listen_with_context (ctx, result, e);
	freeaddrinfo (result);
	if (fd == -1)
		return false;

	set_blocking (fd, false);

	struct poller_fd *event = &ctx->relay_event;
	*event = poller_fd_make (&ctx->poller, fd);
	event->dispatcher = (poller_fd_fn) on_relay_client_available;
	event->user_data = ctx;

	ctx->relay_fd = fd;
	poller_fd_set (event, POLLIN);
	return true;
}

static void
on_config_relay_bind_change (struct config_item *item)
{
	struct app_context *ctx = item->user_data;
	char *value = item->value.string.str;
	app_context_relay_stop (ctx);
	if (!value)
		return;

	// XXX: This should perhaps be reencoded as the locale encoding.
	char *address = xstrdup (value);

	struct error *e = NULL;
	if (!relay_start (ctx, address, &e))
	{
		log_global_error (ctx, "#s: #l", item->schema->name, e->message);
		error_free (e);
	}
	free (address);
}

// --- Tests -------------------------------------------------------------------

// The application is quite monolithic and can only be partially unit-tested.
// Locale-, terminal- and filesystem-dependent tests are also somewhat tricky.

#ifdef TESTING

static const struct config_schema g_config_test[] =
{
	{ .name = "foo",    .type = CONFIG_ITEM_BOOLEAN, .default_ = "off" },
	{ .name = "bar",    .type = CONFIG_ITEM_INTEGER, .default_ = "1" },
	{ .name = "foobar", .type = CONFIG_ITEM_STRING,  .default_ = "\"x\\x01\"" },
	{}
};

static void
test_config (void)
{
	struct config_item *foo = config_item_object ();
	config_schema_apply_to_object (g_config_test, foo, NULL);
	struct config_item *root = config_item_object ();
	str_map_set (&root->value.object, "top", foo);

	struct strv v = strv_make ();
	dump_matching_options (root, "*foo*", &v);
	hard_assert (v.len == 2);
	hard_assert (!strcmp (v.vector[0], "top.foo = off"));
	hard_assert (!strcmp (v.vector[1], "top.foobar = \"x\\x01\""));
	strv_free (&v);

	config_item_destroy (root);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static void
test_aliases (void)
{
	struct strv v = strv_make ();
	expand_alias_definition ("/foo; /bar $* $$$;;;$1$2$3$4", "foo bar baz", &v);
	hard_assert (v.len == 4);
	hard_assert (!strcmp (v.vector[0], "/foo"));
	hard_assert (!strcmp (v.vector[1], " /bar foo bar baz $;"));
	hard_assert (!strcmp (v.vector[2], ""));
	hard_assert (!strcmp (v.vector[3], "foobarbaz"));
	strv_free (&v);
}

static void
test_wrapping (void)
{
	static const char *message = " foo bar foobar fóóbárbáz\002 a\0031 b";
	// XXX: formatting continuation order is implementation-dependent here
	//   (irc_serialize_char_attrs() makes a choice in serialization)
	static const char *split[] = { " foo", "bar", "foob", "ar",
		"fó", "ób", "árb", "áz\x02", "\002a\0031", "\0031\002b" };

	struct strv v = strv_make ();
	hard_assert (wrap_message (message, 4, &v, NULL));
	hard_assert (v.len == N_ELEMENTS (split));
	for (size_t i = 0; i < N_ELEMENTS (split); i++)
		hard_assert (!strcmp (v.vector[i], split[i]));
	strv_free (&v);
}

static void
test_utf8 (void)
{
	static const char *a[] = { "fřoo", "Fřooř", "fřOOŘ" };
	hard_assert (utf8_common_prefix (a, N_ELEMENTS (a)) == 5);

	char *cut_off = xstrdup ("ё\xD0");
	irc_sanitize_cut_off_utf8 (&cut_off);
	hard_assert (!strcmp (cut_off, "ё\xEF\xBF\xBD"));
	free (cut_off);
}

int
main (int argc, char *argv[])
{
	struct test test;
	test_init (&test, argc, argv);
	test_add_simple (&test, "/config",   NULL, test_config);
	test_add_simple (&test, "/aliases",  NULL, test_aliases);
	test_add_simple (&test, "/wrapping", NULL, test_wrapping);
	test_add_simple (&test, "/utf8",     NULL, test_utf8);
	return test_run (&test);
}

#define main main_shadowed
#endif // TESTING

// --- Main program ------------------------------------------------------------

static const char *g_logo[] =
{
	"",
	"\x02" PROGRAM_NAME "\x02  " PROGRAM_VERSION,
	"",
};

static void
show_logo (struct app_context *ctx)
{
	for (size_t i = 0; i < N_ELEMENTS (g_logo); i++)
		log_global_indent (ctx, "#m", g_logo[i]);
}

static void
format_input_and_die (struct app_context *ctx)
{
	// XXX: it might make sense to allow for redirection, using FLUSH_OPT_RAW
	struct str s = str_make ();
	int c = 0;
	while ((c = fgetc (stdin)) != EOF)
	{
		if (c != '\n')
		{
			str_append_c (&s, c);
			continue;
		}

		struct formatter f = formatter_make (ctx, NULL);
		formatter_add (&f, "#m\n", s.str);
		formatter_flush (&f, stdout, FLUSH_OPT_NOWRAP);
		formatter_free (&f);
		str_reset (&s);
	}

	struct formatter f = formatter_make (ctx, NULL);
	formatter_add (&f, "#m", s.str);
	formatter_flush (&f, stdout, FLUSH_OPT_NOWRAP);
	formatter_free (&f);
	str_free (&s);
	exit (EXIT_SUCCESS);
}

int
main (int argc, char *argv[])
{
	// We include a generated file from xD including this array we don't use;
	// let's just keep it there and silence the compiler warning instead
	(void) g_default_replies;

	static const struct opt opts[] =
	{
		{ 'h', "help", NULL, 0, "display this help and exit" },
		{ 'V', "version", NULL, 0, "output version information and exit" },
		// This is mostly intended for previewing formatted MOTD files
		{ 'f', "format", NULL, OPT_LONG_ONLY, "format IRC text from stdin" },
		{ 0, NULL, NULL, 0, NULL }
	};

	struct opt_handler oh =
		opt_handler_make (argc, argv, opts, NULL, "Terminal-based IRC client.");
	bool format_mode = false;

	int c;
	while ((c = opt_handler_get (&oh)) != -1)
	switch (c)
	{
	case 'h':
		opt_handler_usage (&oh, stdout);
		exit (EXIT_SUCCESS);
	case 'V':
		printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
		exit (EXIT_SUCCESS);
	case 'f':
		format_mode = true;
		break;
	default:
		print_error ("wrong options");
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}
	if (optind != argc)
	{
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}
	opt_handler_free (&oh);

	// We only need to convert to and from the terminal encoding
	setlocale (LC_CTYPE, "");

	struct app_context ctx;
	app_context_init (&ctx);
	g_ctx = &ctx;

	init_openssl ();

	// Bootstrap configuration, so that we can access schema items at all
	register_config_modules (&ctx);
	config_load (&ctx.config, config_item_object ());

	// The following part is a bit brittle because of interdependencies
	init_colors (&ctx);
	if (format_mode)
		format_input_and_die (&ctx);
	if (!cur_term)
		exit_fatal ("terminal initialization failed");

	init_global_buffer (&ctx);
	show_logo (&ctx);
	setup_signal_handlers ();
	init_poller_events (&ctx);
	load_configuration (&ctx);

	// At this moment we can safely call any "on_change" callbacks
	config_schema_call_changed (ctx.config.root);

	// Initialize input so that we can switch to new buffers
	on_refresh_prompt (&ctx);
	ctx.input->add_functions = input_add_functions;
	CALL_ (ctx.input, start, argv[0]);
	toggle_bracketed_paste (true);
	reset_autoaway (&ctx);

	// Finally, we juice the configuration for some servers to create
	load_plugins (&ctx);
	load_servers (&ctx);

	ctx.polling = true;
	while (ctx.polling)
		poller_run (&ctx.poller);

	CALL (ctx.input, stop);

	app_context_free (&ctx);
	toggle_bracketed_paste (false);
	free_terminal ();
	return EXIT_SUCCESS;
}