aboutsummaryrefslogtreecommitdiff
path: root/degesch.c
blob: b75a1f06bab76f3278d57d538fe9a9963c5a4971 (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
/*
 * degesch.c: the experimental IRC client
 *
 * Copyright (c) 2015, Přemysl Janouch <p.janouch@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * 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
// FIXME: awful naming, collides with ATTRIBUTE_*
#define ATTR_TABLE(XX)                                                         \
	XX( PROMPT,    "prompt",    "Terminal attributes for the prompt"     )     \
	XX( RESET,     "reset",     "String to reset terminal attributes"    )     \
	XX( WARNING,   "warning",   "Terminal attributes for warnings"       )     \
	XX( ERROR,     "error",     "Terminal attributes for errors"         )     \
	XX( EXTERNAL,  "external",  "Terminal attributes for external lines" )     \
	XX( TIMESTAMP, "timestamp", "Terminal attributes for timestamps"     )     \
	XX( HIGHLIGHT, "highlight", "Terminal attributes for highlights"     )     \
	XX( ACTION,    "action",    "Terminal attributes for user actions"   )     \
	XX( USERHOST,  "userhost",  "Terminal attributes for user@host"      )     \
	XX( JOIN,      "join",      "Terminal attributes for joins"          )     \
	XX( PART,      "part",      "Terminal attributes for parts"          )

enum
{
#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 "degesch"

#include "common.c"
#include "kike-replies.c"

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

#include <termios.h>
#ifndef TIOCGWINSZ
#include <sys/ioctl.h>
#endif  // ! TIOCGWINSZ

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

// Literally cancer
#undef lines
#undef columns

#ifdef HAVE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif // HAVE_READLINE

#ifdef HAVE_EDITLINE
#include <histedit.h>
#endif // HAVE_EDITLINE

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

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

// --- 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.

struct input_buffer
{
#ifdef HAVE_READLINE
	HISTORY_STATE *history;             ///< Saved history state
	char *saved_line;                   ///< Saved line content
	int saved_mark;                     ///< Saved mark
#elif defined HAVE_EDITLINE
	HistoryW *history;                  ///< The history object
	wchar_t *saved_line;                ///< Saved line content
	int saved_len;                      ///< Length of the saved line
#endif // HAVE_EDITLINE
	int saved_point;                    ///< Saved cursor position
};

static struct input_buffer *
input_buffer_new (void)
{
	struct input_buffer *self = xcalloc (1, sizeof *self);
#ifdef HAVE_EDITLINE
	self->history = history_winit ();

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

static void
input_buffer_destroy (struct input_buffer *self)
{
#ifdef HAVE_READLINE
	// Can't really free "history" contents from here
	free (self->history);
#elif defined HAVE_EDITLINE
	history_wend (self->history);
#endif // HAVE_EDITLINE
	free (self->saved_line);
	free (self);
}

struct input
{
	bool active;                        ///< Are we a thing?

#if defined HAVE_READLINE
	char *saved_line;                   ///< Saved line content
	int saved_point;                    ///< Saved cursor position
	int saved_mark;                     ///< Saved mark
#elif defined HAVE_EDITLINE
	EditLine *editline;                 ///< The EditLine object
	char *(*saved_prompt) (EditLine *); ///< Saved prompt function
	char saved_char;                    ///< Saved char for the prompt
#endif // HAVE_EDITLINE

	char *prompt;                       ///< The prompt we use
	int prompt_shown;                   ///< Whether the prompt is shown now

	struct input_buffer *current;       ///< Current input buffer
};

static void
input_init (struct input *self)
{
	memset (self, 0, sizeof *self);
}

static void
input_free (struct input *self)
{
#ifdef HAVE_READLINE
	free (self->saved_line);
#endif // HAVE_READLINE
	free (self->prompt);
}

// --- GNU Readline ------------------------------------------------------------

#ifdef HAVE_READLINE

#define INPUT_START_IGNORE  RL_PROMPT_START_IGNORE
#define INPUT_END_IGNORE    RL_PROMPT_END_IGNORE

#define input_ding(self) rl_ding ()

static void
input_on_terminal_resized (struct input *self)
{
	(void) self;

	// 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_on_readable (struct input *self)
{
	(void) self;
	rl_callback_read_char ();
}

static void
input_set_prompt (struct input *self, char *prompt)
{
	free (self->prompt);
	self->prompt = prompt;

	if (!self->active)
		return;

	// First reset the prompt to work around a bug in readline
	rl_set_prompt ("");
	if (self->prompt_shown)
		rl_redisplay ();

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

static void
input_erase (struct input *self)
{
	(void) self;

	rl_set_prompt ("");
	rl_replace_line ("", 0);
	rl_point = rl_mark = 0;
	rl_redisplay ();
}

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

static void
input_bind_meta (struct input *self, char key, const char *function_name)
{
	// This one seems to actually work
	char keyseq[] = { '\\', 'e', key, 0 };
	input_bind (self, 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_bind_control (struct input *self, char key, const char *function_name)
{
	char keyseq[] = { '\\', 'C', '-', key, 0 };
	input_bind (self, keyseq, function_name);
}

static void
input_insert_c (struct input *self, int c)
{
	char s[2] = { c, 0 };
	rl_insert_text (s);

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

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

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_start (struct input *self, const char *program_name)
{
	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_basic_word_break_characters = WORD_BREAKING_CHARS;
	rl_completer_word_break_characters = NULL;
	rl_attempted_completion_function = app_readline_completion;

	hard_assert (self->prompt != NULL);
	rl_callback_handler_install (self->prompt, on_readline_input);

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

static void
input_stop (struct input *self)
{
	if (self->prompt_shown > 0)
		input_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;
}

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

// 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_save_buffer (struct input *self, struct input_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;
}

static void
input_restore_buffer (struct input *self, struct input_buffer *buffer)
{
	// Restore the target buffer's history
	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;
		history_set_history_state (state);
		free (state);
	}

	// Try to restore the target buffer's readline state
	if (buffer->saved_line)
	{
		rl_replace_line (buffer->saved_line, 0);
		rl_point = buffer->saved_point;
		rl_mark = buffer->saved_mark;
		free (buffer->saved_line);
		buffer->saved_line = NULL;

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

static void
input_switch_buffer (struct input *self, struct input_buffer *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_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_restore_buffer (self, buffer);
	self->current = buffer;
}

static void
input_destroy_buffer (struct input *self, struct input_buffer *buffer)
{
	(void) self;

	// 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_switch_buffer() 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 ();
		free (buffer->history);
		buffer->history = NULL;

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

	input_buffer_destroy (buffer);
}

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

static void
input_save (struct input *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_restore (struct input *self)
{
	hard_assert (self->saved_line);

	rl_set_prompt (self->prompt);
	rl_replace_line (self->saved_line, 0);
	rl_point = self->saved_point;
	rl_mark = self->saved_mark;
	free (self->saved_line);
	self->saved_line = NULL;
}

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

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

	input_save (self);
	input_erase (self);
}

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

	input_restore (self);
	rl_redisplay ();
}

#endif // HAVE_READLINE

// --- BSD Editline ------------------------------------------------------------

#ifdef HAVE_EDITLINE

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

static void app_editline_init (struct input *self);

static void
input_ding (struct input *self)
{
	(void) self;

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

static void
input_on_terminal_resized (struct input *self)
{
	el_resize (self->editline);
}

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

static void
input_bind_meta (struct input *self, char key, const char *function_name)
{
	char keyseq[] = { 'M', '-', key, 0 };
	input_bind (self, keyseq, function_name);
}

static void
input_bind_control (struct input *self, char key, const char *function_name)
{
	char keyseq[] = { '^', key, 0 };
	input_bind (self, keyseq, function_name);
}

static void
input_redisplay (struct input *self)
{
	// See rl_redisplay()
	// The character is VREPRINT (usually C-r)
	// TODO: read it from terminal info
	// XXX: could we potentially break UTF-8 with this?
	char x[] = { ('R' - 'A' + 1), 0 };
	el_push (self->editline, x);

	// We have to do this or it gets stuck and nothing is done
	(void) el_gets (self->editline, NULL);
}

static void
input_set_prompt (struct input *self, char *prompt)
{
	free (self->prompt);
	self->prompt = prompt;

	if (self->prompt_shown)
		input_redisplay (self);
}

static char *
input_make_prompt (EditLine *editline)
{
	struct input *self;
	el_get (editline, EL_CLIENTDATA, &self);
	if (!self->prompt)
		return "";
	return self->prompt;
}

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

static void
input_erase (struct input *self)
{
	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);

	// XXX: this doesn't seem to save the escape character
	el_get (self->editline, EL_PROMPT, &self->saved_prompt, &self->saved_char);
	el_set (self->editline, EL_PROMPT, input_make_empty_prompt);
	input_redisplay (self);
}

static void
input_insert_c (struct input *self, int c)
{
	char s[2] = { c, 0 };
	el_insertstr (self->editline, s);

	if (self->prompt_shown)
		input_redisplay (self);
}

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

static void
input_start (struct input *self, const char *program_name)
{
	self->editline = el_init (program_name, stdin, stdout, stderr);
	el_set (self->editline, EL_CLIENTDATA, self);
	el_set (self->editline, EL_PROMPT_ESC,
		input_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_stop (struct input *self)
{
	if (self->prompt_shown > 0)
		input_erase (self);

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

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

static void
input_save_buffer (struct input *self, struct input_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_restore_buffer (struct input *self, struct input_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_switch_buffer (struct input *self, struct input_buffer *buffer)
{
	if (self->current)
		input_save_buffer (self, self->current);

	input_restore_buffer (self, buffer);
	el_wset (self->editline, EL_HIST, history, buffer->history);
	self->current = buffer;
}

static void
input_destroy_buffer (struct input *self, struct input_buffer *buffer)
{
	(void) self;
	input_buffer_destroy (buffer);
}

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

static void
input_save (struct input *self)
{
	if (self->current)
		input_save_buffer (self, self->current);
}

static void
input_restore (struct input *self)
{
	if (self->current)
		input_restore_buffer (self, self->current);
}

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

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

	input_save (self);
	input_erase (self);
}

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

	input_restore (self);
	// Would have used "saved_char" but it doesn't seem to work.
	// And it doesn't even when it does anyway (it seems to just strip it).
	el_set (self->editline,
		EL_PROMPT_ESC, input_make_prompt, INPUT_START_IGNORE);
	input_redisplay (self);
}

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

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

	// 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;

	// The character is VEOF (usually C-d)
	// TODO: read it from terminal info
	if (count == 0 && buf[0] == ('D' - 'A' + 1))
	{
		el_deletestr (self->editline, 1);
		input_redisplay (self);
		input_ding (self);
	}
}

#endif // HAVE_EDITLINE

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

// All text stored in our data structures is encoded in UTF-8.
// Or at least should be.  The exception is IRC identifiers.

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

// We need a few reference countable objects with support
// for both strong and weak references

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

#define REF_COUNTABLE_HEADER                                                   \
	size_t ref_count;                   /**< Reference count                */ \
	destroy_cb_fn on_destroy;           /**< To remove any weak references  */ \
	void *user_data;                    /**< User data for callbacks        */

#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;                                                            \
		if (self->on_destroy)                                                  \
			self->on_destroy (self, self->user_data);                          \
		name ## _destroy (self);                                               \
	}

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

struct user_channel
{
	LIST_HEADER (struct user_channel)

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

static struct user_channel *
user_channel_new (void)
{
	struct user_channel *self = xcalloc (1, sizeof *self);
	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

	// TODO: eventually a reference to the server

	char *nickname;                     ///< Literal nickname
	// TODO: write code to poll for the away status
	bool away;                          ///< User is away

	struct user_channel *channels;      ///< Channels the user is on
};

static struct user *
user_new (void)
{
	struct user *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;
	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
	struct str prefixes;                ///< Ordered @+... characters
};

static struct channel_user *
channel_user_new (void)
{
	struct channel_user *self = xcalloc (1, sizeof *self);
	str_init (&self->prefixes);
	return self;
}

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

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

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

// XXX: this doesn't really have to be reference countable

struct channel
{
	REF_COUNTABLE_HEADER

	// TODO: eventually a reference to the 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 str_vector names_buf;        ///< Buffer for RPL_NAMREPLY
};

static struct channel *
channel_new (void)
{
	struct channel *self = xcalloc (1, sizeof *self);
	self->ref_count = 1;
	str_init (&self->no_param_modes);
	str_map_init (&self->param_modes);
	self->param_modes.free = free;
	str_vector_init (&self->names_buf);
	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);
	str_vector_free (&self->names_buf);
	free (self);
}

REF_COUNTABLE_METHODS (channel)

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

enum buffer_line_flags
{
	BUFFER_LINE_HIGHLIGHT   = 1 << 0    ///< The user was highlighted by this
};

enum buffer_line_type
{
	BUFFER_LINE_PRIVMSG,                ///< PRIVMSG
	BUFFER_LINE_ACTION,                 ///< PRIVMSG ACTION
	BUFFER_LINE_NOTICE,                 ///< NOTICE
	BUFFER_LINE_JOIN,                   ///< JOIN
	BUFFER_LINE_PART,                   ///< PART
	BUFFER_LINE_KICK,                   ///< KICK
	BUFFER_LINE_NICK,                   ///< NICK
	BUFFER_LINE_TOPIC,                  ///< TOPIC
	BUFFER_LINE_QUIT,                   ///< QUIT
	BUFFER_LINE_STATUS,                 ///< Whatever status messages
	BUFFER_LINE_ERROR                   ///< Whatever error messages
};

struct buffer_line_args
{
	char *who;                          ///< Name of the origin or NULL (user)
	char *object;                       ///< Object of action
	char *text;                         ///< Text of message
	char *reason;                       ///< Reason for PART, KICK, QUIT
	char *prefixes;                     ///< Channel user prefixes
};

struct buffer_line
{
	LIST_HEADER (struct buffer_line)

	// We use the "type" and "flags" mostly just as formatting hints

	enum buffer_line_type type;         ///< Type of the event
	int flags;                          ///< Flags

	time_t when;                        ///< Time of the event
	struct buffer_line_args args;       ///< Arguments
};

struct buffer_line *
buffer_line_new (void)
{
	struct buffer_line *self = xcalloc (1, sizeof *self);
	return self;
}

static void
buffer_line_destroy (struct buffer_line *self)
{
	free (self->args.who);
	free (self->args.object);
	free (self->args.text);
	free (self->args.reason);
	free (self->args.prefixes);
	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)

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

	struct input_buffer *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 unseen_messages_count;     ///< # messages since last visited
	bool highlighted;                   ///< We've been highlighted

	// Origin information:

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

static struct buffer *
buffer_new (void)
{
	struct buffer *self = xcalloc (1, sizeof *self);
	self->input_data = input_buffer_new ();
	return self;
}

static void
buffer_destroy (struct buffer *self)
{
	free (self->name);
	if (self->input_data)
		input_buffer_destroy (self->input_data);
	LIST_FOR_EACH (struct buffer_line, iter, self->lines)
		buffer_line_destroy (iter);
	if (self->user)
		user_unref (self->user);
	if (self->channel)
		channel_unref (self->channel);
	free (self);
}

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

enum server_state
{
	IRC_DISCONNECTED,                   ///< Not connected
	IRC_CONNECTING,                     ///< Connecting to the server
	IRC_CONNECTED,                      ///< Trying to register
	IRC_REGISTERED                      ///< We can chat now
};

/// 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
{
	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
	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 poller_fd read_event;        ///< We can read from the socket

	SSL_CTX *ssl_ctx;                   ///< SSL context
	SSL *ssl;                           ///< SSL connection

	// 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

	// IRC:

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

	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
	struct str irc_user_mode;           ///< Our current user modes
	char *irc_user_host;                ///< Our current user@host

	bool cap_echo_message;              ///< Whether the server echos messages

	// 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_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 void on_irc_timeout (void *user_data);
static void on_irc_ping_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_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_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 void
server_init (struct server *self, struct poller *poller)
{
	memset (self, 0, sizeof *self);

	self->socket = -1;
	str_init (&self->read_buffer);
	self->state = IRC_DISCONNECTED;

	poller_timer_init (&self->timeout_tmr, poller);
	self->timeout_tmr.dispatcher = on_irc_timeout;
	self->timeout_tmr.user_data = self;

	poller_timer_init (&self->ping_tmr, poller);
	self->ping_tmr.dispatcher = on_irc_ping_timeout;
	self->ping_tmr.user_data = self;

	poller_timer_init (&self->reconnect_tmr, poller);
	self->reconnect_tmr.dispatcher = (poller_timer_fn) irc_initiate_connect;
	self->reconnect_tmr.user_data = self;

	str_map_init (&self->irc_users);
	self->irc_users.key_xfrm = irc_strxfrm;
	str_map_init (&self->irc_channels);
	self->irc_channels.key_xfrm = irc_strxfrm;
	str_map_init (&self->irc_buffer_map);
	self->irc_buffer_map.key_xfrm = irc_strxfrm;

	str_init (&self->irc_user_mode);

	server_free_specifics (self);
	server_init_specifics (self);
}

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

	if (self->connector)
	{
		connector_free (self->connector);
		free (self->connector);
	}
	if (self->socket != -1)
	{
		xclose (self->socket);
		poller_fd_reset (&self->read_event);
	}
	str_free (&self->read_buffer);

	if (self->ssl)
		SSL_free (self->ssl);
	if (self->ssl_ctx)
		SSL_CTX_free (self->ssl_ctx);

	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_mode);
	free (self->irc_user_host);

	server_free_specifics (self);
}

static void
server_destroy (void *self)
{
	server_free (self);
	free (self);
}

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

struct app_context
{
	// Configuration:

	struct config config;               ///< Program configuration
	char *attrs[ATTR_COUNT];            ///< Terminal attributes
	bool no_colors;                     ///< Colour output mode
	bool isolate_buffers;               ///< Isolate global/server buffers

	struct str_map servers;             ///< Our servers

	// Events:

	struct poller_fd tty_event;         ///< Terminal input event
	struct poller_fd signal_event;      ///< Signal FD event

	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

	// TODO: make buffer names fully unique like weechat does
	struct str_map buffers_by_name;     ///< Buffers by name

	// TODO: So that we always output proper date change messages
	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
	iconv_t latin1_to_utf8;             ///< ISO Latin 1 to UTF-8

	struct input input;                 ///< User interface

	bool awaiting_mirc_escape;          ///< Awaiting a mIRC attribute escape
	char char_buf[MB_LEN_MAX + 1];      ///< Buffered multibyte char
	size_t char_buf_len;                ///< How much of an MB char is buffered
}
*g_ctx;

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

	config_init (&self->config);
	poller_init (&self->poller);

	str_map_init (&self->servers);
	self->servers.free = server_destroy;
	self->servers.key_xfrm = tolower_ascii_strxfrm;

	str_map_init (&self->buffers_by_name);
	self->buffers_by_name.key_xfrm = tolower_ascii_strxfrm;

	self->last_displayed_msg_time = time (NULL);

	char *encoding = nl_langinfo (CODESET);
#ifdef __linux__
	encoding = xstrdup_printf ("%s//TRANSLIT", encoding);
#else // ! __linux__
	encoding = xstrdup (encoding);
#endif // ! __linux__

	if ((self->term_from_utf8 =
		iconv_open (encoding, "UTF-8")) == (iconv_t) -1
	 || (self->latin1_to_utf8 =
		iconv_open ("UTF-8", "ISO-8859-1")) == (iconv_t) -1
	 || (self->term_to_utf8 =
		iconv_open ("UTF-8", nl_langinfo (CODESET))) == (iconv_t) -1)
		exit_fatal ("creating the UTF-8 conversion object failed: %s",
			strerror (errno));

	free (encoding);

	input_init (&self->input);
}

static void
app_context_free (struct app_context *self)
{
	config_free (&self->config);
	for (size_t i = 0; i < ATTR_COUNT; i++)
		free (self->attrs[i]);

	// FIXME: this doesn't free the history state
	LIST_FOR_EACH (struct buffer, iter, self->buffers)
		buffer_destroy (iter);
	str_map_free (&self->buffers_by_name);

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

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

	input_free (&self->input);
}

static void refresh_prompt (struct app_context *ctx);
static char *irc_cut_nickname (const char *prefix);
static const char *irc_find_userhost (const char *prefix);

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

// TODO: eventually add "on_change" callbacks

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 (c < 32)
		{
			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 struct config_schema g_config_server[] =
{
	{ .name      = "nickname",
	  .comment   = "IRC nickname",
	  .type      = CONFIG_ITEM_STRING,
	  .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 },

	{ .name      = "ssl",
	  .comment   = "Whether to use SSL/TLS",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off" },
	{ .name      = "ssl_cert",
	  .comment   = "Client SSL certificate (PEM)",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "ssl_verify",
	  .comment   = "Whether to verify certificates",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "on" },
	{ .name      = "ssl_ca_file",
	  .comment   = "OpenSSL CA bundle file",
	  .type      = CONFIG_ITEM_STRING },
	{ .name      = "ssl_ca_path",
	  .comment   = "OpenSSL CA bundle path",
	  .type      = CONFIG_ITEM_STRING },

	{ .name      = "autojoin",
	  .comment   = "Channels to join on start",
	  .type      = CONFIG_ITEM_STRING_ARRAY,
	  .validate  = config_validate_nonjunk_string },
	{ .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 struct config_schema g_config_behaviour[] =
{
	{ .name      = "isolate_buffers",
	  .comment   = "Don't leak messages from the server and global buffers",
	  .type      = CONFIG_ITEM_BOOLEAN,
	  .default_  = "off" },
	{}
};

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

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

static void
load_config_server (struct config_item_ *subtree, void *user_data)
{
	(void) user_data;
	// This will eventually iterate over the object and create servers
	config_schema_apply_to_object (g_config_server, subtree);
}

static void
load_config_behaviour (struct config_item_ *subtree, void *user_data)
{
	(void) user_data;
	config_schema_apply_to_object (g_config_behaviour, subtree);
}

static void
load_config_attributes (struct config_item_ *subtree, void *user_data)
{
	(void) user_data;
	config_schema_apply_to_object (g_config_attributes, subtree);
}

static void
register_config_modules (struct app_context *ctx)
{
	struct config *config = &ctx->config;
	config_register_module (config,
		"server", load_config_server, ctx);
	config_register_module (config,
		"behaviour", load_config_behaviour, ctx);
	config_register_module (config,
		"attributes", load_config_attributes, 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 str s;
	str_init (&s);
	str_append (&s, value);
	struct config_item_ *new_ = config_item_string (&s);
	str_free (&s);

	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 char *
write_configuration_file (const struct str *data, struct error **e)
{
	struct str path;
	str_init (&path);
	get_xdg_home_dir (&path, "XDG_CONFIG_HOME", ".config");
	str_append (&path, "/" PROGRAM_NAME);

	if (!mkdir_with_parents (path.str, e))
		goto error;

	str_append (&path, "/" PROGRAM_NAME ".conf");
	FILE *fp = fopen (path.str, "w");
	if (!fp)
	{
		error_set (e, "could not open `%s' for writing: %s",
			path.str, strerror (errno));
		goto error;
	}

	errno = 0;
	fwrite (data->str, data->len, 1, fp);
	fclose (fp);

	if (errno)
	{
		error_set (e, "writing to `%s' failed: %s", path.str, strerror (errno));
		goto error;
	}
	return str_steal (&path);

error:
	str_free (&path);
	return NULL;
}

static void
serialize_configuration (struct app_context *ctx, 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 (ctx->config.root, true, output);
}

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

/// Default color pair
#define COLOR_DEFAULT -1

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

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

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

	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)
	{
		del_curterm (cur_term);
		return false;
	}

	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);
}

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

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;
}

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;

	if (printer)
		tputs (ctx->attrs[attribute], 1, printer);

	vfprintf (stream, fmt, ap);

	if (printer)
		tputs (ctx->attrs[ATTR_RESET], 1, printer);
}

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;

	input_hide (&ctx->input);

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

	input_show (&ctx->input);
}

static void
init_attribute (struct app_context *ctx, int id, const char *default_)
{
	static const char *table[ATTR_COUNT] =
	{
#define XX(x, y, z) [ATTR_ ## x] = "attributes." y,
		ATTR_TABLE (XX)
#undef XX
	};

	const char *user = get_config_string (ctx->config.root, table[id]);
	if (user)
		ctx->attrs[id] = xstrdup (user);
	else
		ctx->attrs[id] = xstrdup (default_);
}

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

#define INIT_ATTR(id, ti) init_attribute (ctx, ATTR_ ## id, have_ti ? (ti) : "")

	INIT_ATTR (PROMPT,    enter_bold_mode);
	INIT_ATTR (RESET,     exit_attribute_mode);
	INIT_ATTR (WARNING,   g_terminal.color_set_fg[COLOR_YELLOW]);
	INIT_ATTR (ERROR,     g_terminal.color_set_fg[COLOR_RED]);

	INIT_ATTR (EXTERNAL,  g_terminal.color_set_fg[COLOR_WHITE]);
	INIT_ATTR (TIMESTAMP, g_terminal.color_set_fg[COLOR_WHITE]);
	INIT_ATTR (ACTION,    g_terminal.color_set_fg[COLOR_RED]);
	INIT_ATTR (USERHOST,  g_terminal.color_set_fg[COLOR_CYAN]);
	INIT_ATTR (JOIN,      g_terminal.color_set_fg[COLOR_GREEN]);
	INIT_ATTR (PART,      g_terminal.color_set_fg[COLOR_RED]);

	char *highlight = xstrdup_printf ("%s%s%s",
		g_terminal.color_set_fg[COLOR_YELLOW],
		g_terminal.color_set_bg[COLOR_MAGENTA],
		enter_bold_mode);
	INIT_ATTR (HIGHLIGHT, highlight);
	free (highlight);

#undef INIT_ATTR

	if (ctx->no_colors)
	{
		g_terminal.stdout_is_tty = false;
		g_terminal.stderr_is_tty = false;
	}

	g_log_message_real = log_message_attributed;
}

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

// 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 color pairs.

enum
{
	ATTRIBUTE_BOLD      = 1 << 0,
	ATTRIBUTE_ITALIC    = 1 << 1,
	ATTRIBUTE_UNDERLINE = 1 << 2,
	ATTRIBUTE_INVERSE   = 1 << 3,
	ATTRIBUTE_BLINK     = 1 << 4
};

struct attribute_printer
{
	struct app_context *ctx;            ///< Application context
	terminal_printer_fn printer;        ///< Terminal printer
	bool dirty;                         ///< Attributes are set

	int want;                           ///< Desired attributes
	int want_foreground;                ///< Desired foreground color
	int want_background;                ///< Desired background color
};

static void
attribute_printer_reset (struct attribute_printer *self)
{
	if (self->dirty)
		tputs (self->ctx->attrs[ATTR_RESET], 1, self->printer);

	self->dirty = false;
}

static void
attribute_printer_init (struct attribute_printer *self,
	struct app_context *ctx, terminal_printer_fn printer)
{
	self->ctx = ctx;
	self->printer = printer;
	self->dirty = true;

	self->want = 0;
	self->want_foreground = -1;
	self->want_background = -1;
}

static void
attribute_printer_apply (struct attribute_printer *self, int attribute)
{
	attribute_printer_reset (self);
	if (attribute != ATTR_RESET)
	{
		tputs (self->ctx->attrs[attribute], 1, self->printer);
		self->dirty = true;
	}
}

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

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

	// 24 -> 8 extra shades of gray
	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
attribute_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;
		}
	case 16:
		return c16;

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

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

static void
attribute_printer_update (struct attribute_printer *self)
{
	bool fg_is_bright;
	int fg = attribute_printer_decode_color
		(self->want_foreground, &fg_is_bright);
	bool bg_is_bright;
	int bg = attribute_printer_decode_color
		(self->want_background, &bg_is_bright);

	// TODO: (INVERSE | BOLD) should be used for bright backgrounds
	//   when possible, i.e. when the foreground shouldn't be bright as well
	//   and when the BOLD attribute hasn't already been set
	int attributes = self->want;
	if (attributes & ATTRIBUTE_INVERSE)
	{
		bool tmp = fg_is_bright;
		fg_is_bright = bg_is_bright;
		bg_is_bright = tmp;
	}

	if (fg_is_bright) attributes |= ATTRIBUTE_BOLD;
	if (bg_is_bright) attributes |= ATTRIBUTE_BLINK;

	attribute_printer_reset (self);

	if (attributes)
		tputs (tparm (set_attributes,
			0, // standout
			attributes & ATTRIBUTE_UNDERLINE,
			attributes & ATTRIBUTE_INVERSE,
			attributes & ATTRIBUTE_BLINK,
			0, // dim
			attributes & ATTRIBUTE_BOLD,
			0, // blank
			0, // protect
			0) // acs
			, 1, self->printer);
	if (enter_italics_mode && (attributes & ATTRIBUTE_ITALIC))
		tputs (enter_italics_mode, 1, self->printer);

	if (fg >= 0)
		tputs (g_terminal.color_set_fg[fg], 1, self->printer);
	if (bg >= 0)
		tputs (g_terminal.color_set_bg[bg], 1, self->printer);

	self->dirty = true;
}

// --- 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
//   #d inserts a signed integer; also supports the #<N> and #0<N> notation
//   #m inserts a mIRC-formatted string (auto-resets at boundaries)
//
//   #a inserts named attributes (auto-resets)
//   #r resets terminal attributes
//   #c sets foreground color
//   #C sets background color

enum formatter_item_type
{
	FORMATTER_ITEM_TEXT,                ///< Text
	FORMATTER_ITEM_ATTR,                ///< Formatting attributes
	FORMATTER_ITEM_FG_COLOR,            ///< Foreground color
	FORMATTER_ITEM_BG_COLOR,            ///< Background color
	FORMATTER_ITEM_SIMPLE               ///< For mIRC formatting only so far
};

struct formatter_item
{
	LIST_HEADER (struct formatter_item)

	enum formatter_item_type type;      ///< Type of this item
	int color;                          ///< Color
	int attribute;                      ///< Attribute ID
	char *text;                         ///< Either text or an attribute string
};

static struct formatter_item *
formatter_item_new (void)
{
	struct formatter_item *self = xcalloc (1, sizeof *self);
	return self;
}

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

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

struct formatter
{
	struct app_context *ctx;            ///< Application context
	bool ignore_new_attributes;         ///< Whether to ignore new attributes

	struct formatter_item *items;       ///< Items
	struct formatter_item *items_tail;  ///< Tail of items
};

static void
formatter_init (struct formatter *self, struct app_context *ctx)
{
	memset (self, 0, sizeof *self);
	self->ctx = ctx;
}

static void
formatter_free (struct formatter *self)
{
	LIST_FOR_EACH (struct formatter_item, iter, self->items)
		formatter_item_destroy (iter);
}

static void
formatter_add_item (struct formatter *self, struct formatter_item template_)
{
	if (template_.type != FORMATTER_ITEM_TEXT && self->ignore_new_attributes)
		return;
	if (template_.text)
		template_.text = xstrdup (template_.text);

	struct formatter_item *item = formatter_item_new ();
	*item = template_;
	LIST_APPEND_WITH_TAIL (self->items, self->items_tail, item);
}

#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_))
#define FORMATTER_ADD_SIMPLE(self, attribute_) \
	FORMATTER_ADD_ITEM ((self), SIMPLE, .attribute = ATTRIBUTE_ ## attribute_)

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

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 color terminal palette, or the 256 color 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),
};

static const char *
formatter_parse_mirc_color (struct formatter *self, const char *s)
{
	if (!isdigit_ascii (*s))
		return s;

	int fg = *s++ - '0';
	if (isdigit_ascii (*s))
		fg = fg * 10 + (*s++ - '0');
	if (fg >= 0 && fg < 16)
		FORMATTER_ADD_ITEM (self, FG_COLOR, .color = g_mirc_to_terminal[fg]);

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

	int bg = *s++ - '0';
	if (isdigit_ascii (*s))
		bg = bg * 10 + (*s++ - '0');
	if (bg >= 0 && bg < 16)
		FORMATTER_ADD_ITEM (self, BG_COLOR, .color = g_mirc_to_terminal[bg]);

	return s;
}

static void
formatter_parse_mirc (struct formatter *self, const char *s)
{
	struct str buf;
	str_init (&buf);

	FORMATTER_ADD_RESET (self);

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

		switch (c)
		{
		case '\x02': FORMATTER_ADD_SIMPLE (self, BOLD);      break;
		case '\x1d': FORMATTER_ADD_SIMPLE (self, ITALIC);    break;
		case '\x1f': FORMATTER_ADD_SIMPLE (self, UNDERLINE); break;
		case '\x16': FORMATTER_ADD_SIMPLE (self, INVERSE);   break;

		case '\x03':
			s = formatter_parse_mirc_color (self, s);
			break;
		case '\x0f':
			FORMATTER_ADD_RESET (self);
			break;
		default:
			str_append_c (&buf, c);
		}
	}

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

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

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

static const char *
formatter_parse_field (struct formatter *self,
	const char *field, struct str *buf, va_list *ap)
{
	size_t width = 0;
	bool zero_padded = false;
	int c;

restart:
	switch ((c = *field++))
	{
		char *s;

		// We can push boring text content to the caller's buffer
		// and let it flush the buffer only when it's actually needed
	case 's':
		s = va_arg (*ap, char *);
		for (size_t len = strlen (s); len < width; len++)
			str_append_c (buf, ' ');
		str_append (buf, s);
		break;
	case 'd':
		s = xstrdup_printf ("%d", va_arg (*ap, int));
		for (size_t len = strlen (s); len < width; len++)
			str_append_c (buf, " 0"[zero_padded]);
		str_append (buf, s);
		free (s);
		break;
	case 'm':
		formatter_parse_mirc (self, 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 == '0' && !zero_padded)
			zero_padded = true;
		else if (isdigit_ascii (c))
			width = width * 10 + (c - '0');
		else if (c)
			hard_assert (!"unexpected format specifier");
		else
			hard_assert (!"unexpected end of format string");
		goto restart;
	}
	return field;
}

static void
formatter_add (struct formatter *self, const char *format, ...)
{
	struct str buf;
	str_init (&buf);

	va_list ap;
	va_start (ap, format);

	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);
	va_end (ap);
}

static void
formatter_flush (struct formatter *self, FILE *stream)
{
	terminal_printer_fn printer = get_attribute_printer (stream);
	if (!printer)
	{
		LIST_FOR_EACH (struct formatter_item, iter, self->items)
			if (iter->type == FORMATTER_ITEM_TEXT)
				fputs (iter->text, stream);
		return;
	}

	struct attribute_printer state;
	attribute_printer_init (&state, self->ctx, printer);
	attribute_printer_reset (&state);

	LIST_FOR_EACH (struct formatter_item, iter, self->items)
	{
		switch (iter->type)
		{
			char *term;
		case FORMATTER_ITEM_TEXT:
			term = iconv_xstrdup
				(self->ctx->term_from_utf8, iter->text, -1, NULL);
			fputs (term, stream);
			free (term);
			break;
		case FORMATTER_ITEM_ATTR:
			attribute_printer_apply (&state, iter->attribute);
			state.want = 0;
			state.want_foreground = -1;
			state.want_background = -1;
			break;
		case FORMATTER_ITEM_SIMPLE:
			state.want |= iter->attribute;
			attribute_printer_update (&state);
			break;
		case FORMATTER_ITEM_FG_COLOR:
			state.want_foreground = iter->color;
			attribute_printer_update (&state);
			break;
		case FORMATTER_ITEM_BG_COLOR:
			state.want_background = iter->color;
			attribute_printer_update (&state);
			break;
		}
	}
	attribute_printer_reset (&state);
}

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

static void
buffer_update_time (struct app_context *ctx, time_t now)
{
	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[32] = "";
	if (soft_assert (strftime (buf, sizeof buf, "%F", &current)))
		print_status ("%s", buf);
	// Else the buffer was too small, which is pretty weird
}

static void
buffer_line_display (struct app_context *ctx,
	struct buffer_line *line, bool is_external)
{
	// Normal timestamps don't include the date, this way the user won't be
	// confused as to when an event has happened
	buffer_update_time (ctx, line->when);

	struct buffer_line_args *a = &line->args;

	char *nick = NULL;
	const char *userhost = NULL;

	// TODO: always assign the default colour to ourselves
	// FIXME: never use the black colour, use the default instead
	int nick_color = -1;
	int object_color = -1;

	if (a->who)
	{
		nick = irc_cut_nickname (a->who);
		userhost = irc_find_userhost (a->who);
		nick_color = str_map_hash (nick, strlen (nick)) % 8;
	}
	if (a->object)
		object_color = str_map_hash (a->object, strlen (a->object)) % 8;

	struct formatter f;
	formatter_init (&f, ctx);

	struct tm current;
	if (!localtime_r (&line->when, &current))
		print_error ("%s: %s", "localtime_r", strerror (errno));
	else
		formatter_add (&f, "#a#02d:#02d:#02d#r ",
			ATTR_TIMESTAMP, current.tm_hour, current.tm_min, current.tm_sec);

	// 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);
		f.ignore_new_attributes = true;
	}

	switch (line->type)
	{
	case BUFFER_LINE_PRIVMSG:
		if (line->flags & BUFFER_LINE_HIGHLIGHT)
			formatter_add (&f, "#a<#s#s>#r #m",
				ATTR_HIGHLIGHT, a->prefixes ? a->prefixes : "", nick, a->text);
		else
			formatter_add (&f, "<#s#c#s#r> #m",
				a->prefixes ? a->prefixes : "", nick_color, nick, a->text);
		break;
	case BUFFER_LINE_ACTION:
		if (line->flags & BUFFER_LINE_HIGHLIGHT)
			formatter_add (&f, " #a*#r  ", ATTR_HIGHLIGHT);
		else
			formatter_add (&f, " #a*#r  ", ATTR_ACTION);
		formatter_add (&f, "#c#s#r #m", nick_color, nick, a->text);
		break;
	case BUFFER_LINE_NOTICE:
		formatter_add (&f, " -  ");
		if (line->flags & BUFFER_LINE_HIGHLIGHT)
			formatter_add (&f, "#a#s(#s)#r: #m",
				ATTR_HIGHLIGHT, "Notice", nick, a->text);
		else
			formatter_add (&f, "#s(#c#s#r): #m",
				"Notice", nick_color, nick, a->text);
		break;
	case BUFFER_LINE_JOIN:
		formatter_add (&f, "#a-->#r ", ATTR_JOIN);
		formatter_add (&f, "#c#s#r (#a#s#r) #a#s#r #s",
			nick_color, nick, ATTR_USERHOST, userhost,
			ATTR_JOIN, "has joined", a->object);
		break;
	case BUFFER_LINE_PART:
		formatter_add (&f, "#a<--#r ", ATTR_PART);
		formatter_add (&f, "#c#s#r (#a#s#r) #a#s#r #s",
			nick_color, nick, ATTR_USERHOST, userhost,
			ATTR_PART, "has left", a->object);
		if (a->reason)
			formatter_add (&f, " (#m)", a->reason);
		break;
	case BUFFER_LINE_KICK:
		formatter_add (&f, "#a<--#r ", ATTR_PART);
		formatter_add (&f, "#c#s#r (#a#s#r) #a#s#r #c#s#r",
			nick_color, nick, ATTR_USERHOST, userhost,
			ATTR_PART, "has kicked", object_color, a->object);
		if (a->reason)
			formatter_add (&f, " (#m)", a->reason);
		break;
	case BUFFER_LINE_NICK:
		formatter_add (&f, " -  ");
		if (a->who)
			formatter_add (&f, "#c#s#r #s #c#s#r",
				nick_color, nick,
				"is now known as", object_color, a->object);
		else
			formatter_add (&f, "#s #s",
				"You are now known as", a->object);
		break;
	case BUFFER_LINE_TOPIC:
		formatter_add (&f, " -  ");
		formatter_add (&f, "#c#s#r #s \"#m\"",
			nick_color, nick,
			"has changed the topic to", a->text);
		break;
	case BUFFER_LINE_QUIT:
		formatter_add (&f, "#a<--#r ", ATTR_PART);
		formatter_add (&f, "#c#s#r (#a#s#r) #a#s#r",
			nick_color, nick, ATTR_USERHOST, userhost,
			ATTR_PART, "has quit");
		if (a->reason)
			formatter_add (&f, " (#m)", a->reason);
		break;
	case BUFFER_LINE_STATUS:
		formatter_add (&f, " -  ");
		formatter_add (&f, "#s", a->text);
		break;
	case BUFFER_LINE_ERROR:
		formatter_add (&f, "#a=!=#r ", ATTR_ERROR);
		formatter_add (&f, "#s", a->text);
	}

	free (nick);

	input_hide (&ctx->input);

	// TODO: write the line to a log file; note that the global and server
	//   buffers musn't collide with filenames

	formatter_add (&f, "\n");
	formatter_flush (&f, stdout);
	formatter_free (&f);

	input_show (&ctx->input);
}

static void
buffer_send_internal (struct app_context *ctx, struct buffer *buffer,
	enum buffer_line_type type, int flags,
	struct buffer_line_args a)
{
	if (!buffer)
		buffer = ctx->global_buffer;

	struct buffer_line *line = buffer_line_new ();
	line->type = type;
	line->flags = flags;
	line->when = time (NULL);
	line->args = a;

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

	// TODO: beep if so configured and either the line is a highlight,
	//   or the buffer is an inactive PM buffer

	if (buffer == ctx->current_buffer)
	{
		buffer_line_display (ctx, line, false);
		return;
	}

	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 = true;

	if (!ctx->isolate_buffers && can_leak)
		buffer_line_display (ctx, line, true);
	else
	{
		buffer->unseen_messages_count++;
		if (flags & BUFFER_LINE_HIGHLIGHT)
			buffer->highlighted = true;

		refresh_prompt (ctx);
	}
}

#define buffer_send(ctx, buffer, type, flags, ...)                             \
	buffer_send_internal ((ctx), (buffer), (type), (flags),                    \
	(struct buffer_line_args) { __VA_ARGS__ })

#define buffer_send_status(ctx, buffer, ...)                                   \
	buffer_send (ctx, buffer, BUFFER_LINE_STATUS, 0,                           \
	.text = xstrdup_printf (__VA_ARGS__))
#define buffer_send_error(ctx, buffer, ...)                                    \
	buffer_send (ctx, buffer, BUFFER_LINE_ERROR, 0,                            \
	.text = xstrdup_printf (__VA_ARGS__))

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));

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

	// In theory this can't cause changes in the prompt
	refresh_prompt (ctx);
}

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

	// TODO: part from the channel if needed

	input_destroy_buffer (&ctx->input, 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);

	// It's not a good idea to remove these buffers, but it's even a worse
	// one to leave the pointers point to invalid memory
	if (buffer == ctx->global_buffer)
		ctx->global_buffer = NULL;
	if (buffer->type == BUFFER_SERVER)
		buffer->server->buffer = NULL;

	if (buffer == ctx->last_buffer)
		ctx->last_buffer = NULL;

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

	refresh_prompt (ctx);
}

static void
buffer_print_backlog (struct app_context *ctx, struct buffer *buffer)
{
	print_status ("%s", buffer->name);

	// That is, minus the buffer switch line and the readline prompt
	int to_display = MAX (10, g_terminal.lines - 2);
	struct buffer_line *line = buffer->lines_tail;
	while (line && line->prev && --to_display > 0)
		line = line->prev;

	// Once we've found where we want to start with the backlog, print it
	for (; line; line = line->next)
		buffer_line_display (ctx, line, false);
	buffer->unseen_messages_count = 0;
	buffer->highlighted = false;

	refresh_prompt (ctx);
}

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

	buffer_print_backlog (ctx, buffer);
	input_switch_buffer (&ctx->input, 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.
	buffer_send_status (ctx, buffer,
		"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++;

	// Append the merged part to current lines in the buffer
	buffer->lines_tail->next = start;
	start->prev = buffer->lines_tail;

	buffer->lines_tail = merged->lines_tail;
	buffer->lines_count += n;

	// And remove it from the original buffer
	if (start == merged->lines_tail)
		if (!(merged->lines_tail = start->prev))
			merged->lines = NULL;
	merged->lines_count -= n;

	// XXX: we don't want to log this entry to a file
	buffer_send_status (ctx, buffer, "End of merged content");
}

static void
buffer_rename (struct app_context *ctx,
	struct buffer *buffer, const char *new_name)
{
	hard_assert (buffer->type == BUFFER_PM);

	// FIXME: this will never find anything as we are being sent
	//   the full buffer name, including the server name;
	//   searching in "buffers_by_name" won't do it either,
	//   we seem to need more information to properly handle this
	struct buffer *collision =
		str_map_find (&buffer->server->irc_buffer_map, new_name);
	if (collision)
	{
		// TODO: use full weechat-style buffer names
		//   to prevent name collisions with the global buffer
		hard_assert (collision->type == BUFFER_PM);

		// When there's a collision, there's not much else we can do
		// other than somehow trying to merge them
		buffer_merge (ctx, collision, buffer);
		if (ctx->current_buffer == buffer)
			buffer_activate (ctx, collision);
		buffer_remove (ctx, buffer);
	}
	else
	{
		// Otherwise we just rename the buffer and that's it
		str_map_set (&ctx->buffers_by_name, buffer->name, NULL);
		str_map_set (&ctx->buffers_by_name, new_name, buffer);

		free (buffer->name);
		buffer->name = xstrdup (new_name);

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

static void
buffer_clear (struct buffer *buffer)
{
	LIST_FOR_EACH (struct buffer_line, iter, buffer->lines)
		buffer_line_destroy (iter);

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

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_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
init_buffers (struct app_context *ctx)
{
	struct buffer *global = ctx->global_buffer = buffer_new ();
	global->type = BUFFER_GLOBAL;
	global->name = xstrdup (PROGRAM_NAME);

	buffer_add (ctx, global);
}

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

static void
irc_user_on_destroy (void *object, void *user_data)
{
	struct user *user = object;
	struct server *s = user_data;
	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 ();
	user->on_destroy = irc_user_on_destroy;
	user->user_data = s;
	user->nickname = nickname;
	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 ();
	buffer->type = BUFFER_PM;
	buffer->name = xstrdup_printf ("%s.%s", s->name, nickname);
	buffer->server = s;
	buffer->user = user;
	str_map_set (&s->irc_buffer_map, user->nickname, buffer);

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

// 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 ();
	user_channel->channel = channel;
	LIST_PREPEND (user->channels, user_channel);

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

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);
		}

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

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);
	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 ();
	channel->on_destroy = irc_channel_on_destroy;
	channel->user_data = s;
	channel->name = name;
	channel->topic = NULL;
	str_map_set (&s->irc_channels, channel->name, channel);
	return 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)
{
	// TODO: shouldn't we decrease reference count on the channel?
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
		irc_channel_unlink_user (channel, iter);
}

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

// Most of the core IRC code comes from ZyklonB which is mostly blocking.
// While it's fairly easy to follow, it also stinks.  It needs to be rewritten
// to be as asynchronous as possible.  See kike.c for reference.

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

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);
}

static void
irc_reset_connection_timeouts (struct server *s)
{
	irc_cancel_timers (s);
	poller_timer_set (&s->timeout_tmr, 3 * 60 * 1000);
	poller_timer_set (&s->ping_tmr, (3 * 60 + 30) * 1000);
}

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;
	int64_t delay = get_config_integer (s->config, "reconnect_delay");

	// TODO: exponentional backoff
	// XXX: maybe add a state for when a connect is queued?
	hard_assert (s->state == IRC_DISCONNECTED);
	buffer_send_status (s->ctx, s->buffer,
		"Trying to reconnect in %ld seconds...", delay);
	poller_timer_set (&s->reconnect_tmr, delay * 1000);
}

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

static bool
irc_initialize_ssl_ctx (struct server *s, struct error **e)
{
	// XXX: maybe we should call SSL_CTX_set_options() for some workarounds

	bool verify = get_config_boolean (s->config, "ssl_verify");
	if (!verify)
		SSL_CTX_set_verify (s->ssl_ctx, SSL_VERIFY_NONE, NULL);

	const char *ca_file = get_config_string (s->config, "ssl_ca_file");
	const char *ca_path = get_config_string (s->config, "ssl_ca_path");

	struct error *error = NULL;
	if (ca_file || ca_path)
	{
		if (SSL_CTX_load_verify_locations (s->ssl_ctx, ca_file, ca_path))
			return true;

		error_set (&error, "%s: %s",
			"Failed to set locations for the CA certificate bundle",
			ERR_reason_error_string (ERR_get_error ()));
		goto ca_error;
	}

	if (!SSL_CTX_set_default_verify_paths (s->ssl_ctx))
	{
		error_set (&error, "%s: %s",
			"Couldn't load the default CA certificate bundle",
			ERR_reason_error_string (ERR_get_error ()));
		goto ca_error;
	}
	return true;

ca_error:
	if (verify)
	{
		error_propagate (e, error);
		return false;
	}

	// Only inform the user if we're not actually verifying
	buffer_send_error (s->ctx, s->buffer, "%s", error->message);
	error_free (error);
	return true;
}

static bool
irc_initialize_ssl (struct server *s, struct error **e)
{
	const char *error_info = NULL;
	s->ssl_ctx = SSL_CTX_new (SSLv23_client_method ());
	if (!s->ssl_ctx)
		goto error_ssl_1;
	if (!irc_initialize_ssl_ctx (s, e))
		goto error_ssl_2;

	s->ssl = SSL_new (s->ssl_ctx);
	if (!s->ssl)
		goto error_ssl_2;

	const char *ssl_cert = get_config_string (s->config, "ssl_cert");
	if (ssl_cert)
	{
		char *path = resolve_config_filename (ssl_cert);
		if (!path)
			buffer_send_error (s->ctx, NULL,
				"%s: %s", "Cannot open file", ssl_cert);
		// XXX: perhaps we should read the file ourselves for better messages
		else if (!SSL_use_certificate_file (s->ssl, path, SSL_FILETYPE_PEM)
			|| !SSL_use_PrivateKey_file (s->ssl, path, SSL_FILETYPE_PEM))
			buffer_send_error (s->ctx, NULL,
				"%s: %s", "Setting the SSL client certificate failed",
				ERR_error_string (ERR_get_error (), NULL));
		free (path);
	}

	SSL_set_connect_state (s->ssl);
	if (!SSL_set_fd (s->ssl, s->socket))
		goto error_ssl_3;
	// Avoid SSL_write() returning SSL_ERROR_WANT_READ
	SSL_set_mode (s->ssl, SSL_MODE_AUTO_RETRY);

	switch (xssl_get_error (s->ssl, SSL_connect (s->ssl), &error_info))
	{
	case SSL_ERROR_NONE:
		return true;
	case SSL_ERROR_ZERO_RETURN:
		error_info = "server closed the connection";
	default:
		break;
	}

error_ssl_3:
	SSL_free (s->ssl);
	s->ssl = NULL;
error_ssl_2:
	SSL_CTX_free (s->ssl_ctx);
	s->ssl_ctx = NULL;
error_ssl_1:
	// XXX: these error strings are really nasty; also there could be
	//   multiple errors on the OpenSSL stack.
	if (!error_info)
		error_info = ERR_error_string (ERR_get_error (), NULL);
	error_set (e, "%s: %s", "could not initialize SSL", error_info);
	return false;
}

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

// As of 2015, 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 (struct app_context *ctx, const char *text)
{
	if (!text)
		return NULL;
	size_t len = strlen (text) + 1;
	if (utf8_validate (text, len))
		return xstrdup (text);
	return iconv_xstrdup (ctx->latin1_to_utf8, (char *) text, len, NULL);
}

// This function is used to output debugging IRC traffic to the terminal.
// It's far from ideal, as any non-UTF-8 text degrades the entire line to
// ISO Latin 1.  But it should work good enough most of the time.
static char *
irc_to_term (struct app_context *ctx, const char *text)
{
	char *utf8 = irc_to_utf8 (ctx, text);
	char *term = iconv_xstrdup (ctx->term_from_utf8, utf8, -1, NULL);
	free (utf8);
	return term;
}

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

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)))
	{
		print_debug ("tried sending a message to a dead server connection");
		return;
	}

	va_list ap;
	va_start (ap, format);
	struct str str;
	str_init (&str);
	str_append_vprintf (&str, format, ap);
	va_end (ap);

	if (g_debug_mode)
	{
		input_hide (&s->ctx->input);

		char *server_name =
			iconv_xstrdup (s->ctx->term_from_utf8, s->name, -1, NULL);
		char *term = irc_to_term (s->ctx, str.str);
		fprintf (stderr, "[%s] <== \"%s\"\n", server_name, term);
		free (term);
		free (server_name);

		input_show (&s->ctx->input);
	}
	str_append (&str, "\r\n");

	if (s->ssl)
	{
		// TODO: call SSL_get_error() to detect if a clean shutdown has occured
		if (SSL_write (s->ssl, str.str, str.len) != (int) str.len)
			LOG_FUNC_FAILURE ("SSL_write",
				ERR_error_string (ERR_get_error (), NULL));
	}
	else if (write (s->socket, str.str, str.len) != (ssize_t) str.len)
		LOG_LIBC_FAILURE ("write");

	str_free (&str);
}

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

static void
irc_shutdown (struct server *s)
{
	// Generally non-critical
	if (s->ssl)
		soft_assert (SSL_shutdown (s->ssl) != -1);
	else
		soft_assert (shutdown (s->socket, SHUT_WR) == 0);

	// TODO: set a timer after which we cut the connection
}

static void
irc_destroy_connector (struct server *s)
{
	connector_free (s->connector);
	free (s->connector);
	s->connector = NULL;

	// Not connecting anymore
	s->state = IRC_DISCONNECTED;
}

static void
try_finish_quit (struct app_context *ctx)
{
	if (!ctx->quitting)
		return;

	struct str_map_iter iter;
	str_map_iter_init (&iter, &ctx->servers);

	bool disconnected_all = true;
	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
initiate_quit (struct app_context *ctx)
{
	buffer_send_status (ctx, NULL, "Shutting down");

	// Destroy the user interface
	input_stop (&ctx->input);

	struct str_map_iter iter;
	str_map_iter_init (&iter, &ctx->servers);

	// Initiate a connection close
	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))
		{
			// XXX: when we go async, we'll have to flush output buffers first
			irc_shutdown (s);
			s->manual_disconnect = true;
		}
		else if (s->state == IRC_CONNECTING)
			irc_destroy_connector (s);
	}

	ctx->quitting = true;
	try_finish_quit (ctx);
}

static void
on_irc_disconnected (struct server *s)
{
	hard_assert (irc_is_connected (s));

	// Get rid of the dead socket
	if (s->ssl)
	{
		SSL_free (s->ssl);
		s->ssl = NULL;
		SSL_CTX_free (s->ssl_ctx);
		s->ssl_ctx = NULL;
	}

	xclose (s->socket);
	s->socket = -1;
	s->state = IRC_DISCONNECTED;

	s->read_event.closed = true;
	poller_fd_reset (&s->read_event);

	// All of our timers have lost their meaning now
	irc_cancel_timers (s);

	// Reset state bound to the connection
	struct str_map_iter iter;
	str_map_iter_init (&iter, &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_mode);
	free (s->irc_user_host);
	s->irc_user_host = NULL;

	s->cap_echo_message = false;

	irc_tolower_fn old_tolower = s->irc_tolower;
	irc_strxfrm_fn old_strxfrm = s->irc_strxfrm;
	server_free_specifics (s);
	server_init_specifics (s);
	// TODO: compare with the original functions and merge users and their
	//   buffers as necessary; ideally we would never have to do this but
	//   I can't think of any good workaround
	s->irc_tolower = old_tolower;
	s->irc_strxfrm = old_strxfrm;

	// Take any relevant actions
	if (s->ctx->quitting)
		try_finish_quit (s->ctx);
	else if (s->manual_disconnect)
		s->manual_disconnect = false;
	else
		irc_queue_reconnect (s);

	refresh_prompt (s->ctx);
}

static void
irc_initiate_disconnect (struct server *s, const char *reason)
{
	hard_assert (irc_is_connected (s));

	s->manual_disconnect = true;
	if (reason)
		irc_send (s, "QUIT :%s", reason);
	else
		irc_send (s, "QUIT :%s", PROGRAM_NAME " " PROGRAM_VERSION);
}

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

static void
on_irc_ping_timeout (void *user_data)
{
	struct server *s = user_data;
	buffer_send_error (s->ctx, s->buffer, "Connection timeout");
	on_irc_disconnected (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));
}

// --- Processing server output ------------------------------------------------

static void irc_process_message
	(const struct irc_message *msg, const char *raw, void *user_data);

enum irc_read_result
{
	IRC_READ_OK,                        ///< Some data were read successfully
	IRC_READ_EOF,                       ///< The server has closed connection
	IRC_READ_AGAIN,                     ///< No more data at the moment
	IRC_READ_ERROR                      ///< General connection failure
};

static enum irc_read_result
irc_fill_read_buffer_ssl (struct server *s, struct str *buf)
{
	int n_read;
start:
	n_read = SSL_read (s->ssl, buf->str + buf->len,
		buf->alloc - buf->len - 1 /* null byte */);

	const char *error_info = NULL;
	switch (xssl_get_error (s->ssl, n_read, &error_info))
	{
	case SSL_ERROR_NONE:
		buf->str[buf->len += n_read] = '\0';
		return IRC_READ_OK;
	case SSL_ERROR_ZERO_RETURN:
		return IRC_READ_EOF;
	case SSL_ERROR_WANT_READ:
		return IRC_READ_AGAIN;
	case SSL_ERROR_WANT_WRITE:
	{
		// Let it finish the handshake as we don't poll for writability;
		// any errors are to be collected by SSL_read() in the next iteration
		struct pollfd pfd = { .fd = s->socket, .events = POLLOUT };
		soft_assert (poll (&pfd, 1, 0) > 0);
		goto start;
	}
	case XSSL_ERROR_TRY_AGAIN:
		goto start;
	default:
		LOG_FUNC_FAILURE ("SSL_read", error_info);
		return IRC_READ_ERROR;
	}
}

static enum irc_read_result
irc_fill_read_buffer (struct server *s, struct str *buf)
{
	ssize_t n_read;
start:
	n_read = recv (s->socket, buf->str + buf->len,
		buf->alloc - buf->len - 1 /* null byte */, 0);

	if (n_read > 0)
	{
		buf->str[buf->len += n_read] = '\0';
		return IRC_READ_OK;
	}
	if (n_read == 0)
		return IRC_READ_EOF;

	if (errno == EAGAIN)
		return IRC_READ_AGAIN;
	if (errno == EINTR)
		goto start;

	LOG_LIBC_FAILURE ("recv");
	return IRC_READ_ERROR;
}

static void
on_irc_readable (const struct pollfd *fd, struct server *s)
{
	if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
		print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);

	(void) set_blocking (s->socket, false);

	struct str *buf = &s->read_buffer;
	enum irc_read_result (*fill_buffer)(struct server *, struct str *)
		= s->ssl
		? irc_fill_read_buffer_ssl
		: irc_fill_read_buffer;
	bool disconnected = false;
	while (true)
	{
		str_ensure_space (buf, 512);
		switch (fill_buffer (s, buf))
		{
		case IRC_READ_AGAIN:
			goto end;
		case IRC_READ_ERROR:
			buffer_send_error (s->ctx, s->buffer,
				"Reading from the IRC server failed");
			disconnected = true;
			goto end;
		case IRC_READ_EOF:
			buffer_send_error (s->ctx, s->buffer,
				"The IRC server closed the connection");
			disconnected = true;
			goto end;
		case IRC_READ_OK:
			break;
		}

		if (buf->len >= (1 << 20))
		{
			buffer_send_error (s->ctx, s->buffer,
				"The IRC server seems to spew out data frantically");
			irc_shutdown (s);
			goto end;
		}
	}
end:
	(void) set_blocking (s->socket, true);
	irc_process_buffer (buf, irc_process_message, s);

	if (disconnected)
		on_irc_disconnected (s);
	else
		irc_reset_connection_timeouts (s);
}

// --- Connection establishment ------------------------------------------------

static bool
irc_autofill_user_info (struct server *s, struct error **e)
{
	const char *nickname = get_config_string (s->config, "nickname");
	const char *username = get_config_string (s->config, "username");
	const char *realname = get_config_string (s->config, "realname");

	if (nickname && username && realname)
		return true;

	// Read POSIX user info and fill the configuration if needed
	struct passwd *pwd = getpwuid (geteuid ());
	if (!pwd)
		FAIL ("cannot retrieve user information: %s", strerror (errno));

	// FIXME: set_config_strings() writes errors on its own
	if (!nickname)
		set_config_string (s->config, "nickname", pwd->pw_name);
	if (!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 void
irc_register (struct server *s)
{
	// Fill in user information automatically if needed
	irc_autofill_user_info (s, NULL);

	const char *nickname = get_config_string (s->config, "nickname");
	const char *username = get_config_string (s->config, "username");
	const char *realname = get_config_string (s->config, "realname");
	hard_assert (nickname && username && realname);

	// Start IRCv3.1 capability negotiation;
	// at worst the server will ignore this or send a harmless error message
	irc_send (s, "CAP LS");

	const char *password = get_config_string (s->config, "password");
	if (password)
		irc_send (s, "PASS :%s", password);

	irc_send (s, "NICK %s", 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)
{
	struct app_context *ctx = s->ctx;

	s->socket = socket;

	struct error *e = NULL;
	bool use_ssl = get_config_boolean (s->config, "ssl");
	if (use_ssl && !irc_initialize_ssl (s, &e))
	{
		buffer_send_error (ctx, s->buffer, "Connection failed: %s", e->message);
		error_free (e);

		xclose (s->socket);
		s->socket = -1;

		irc_queue_reconnect (s);
		return;
	}

	buffer_send_status (ctx, s->buffer, "Connection established");
	s->state = IRC_CONNECTED;

	poller_fd_init (&s->read_event, &ctx->poller, s->socket);
	s->read_event.dispatcher = (poller_fd_fn) on_irc_readable;
	s->read_event.user_data = s;

	poller_fd_set (&s->read_event, POLLIN);
	irc_reset_connection_timeouts (s);

	irc_register (s);
	refresh_prompt (s->ctx);
}

static void
irc_on_connector_connecting (void *user_data, const char *address)
{
	struct server *s = user_data;
	buffer_send_status (s->ctx, s->buffer, "Connecting to %s...", address);
}

static void
irc_on_connector_error (void *user_data, const char *error)
{
	struct server *s = user_data;
	buffer_send_error (s->ctx, 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)
{
	struct server *s = user_data;
	irc_destroy_connector (s);
	irc_finish_connection (s, socket);
}

static void
irc_split_host_port (char *s, char **host, char **port)
{
	char *colon = strchr (s, ':');
	if (colon)
	{
		*colon = '\0';
		*port = ++colon;
	}
	else
		*port = "6667";

	*host = s;
}

static bool
irc_setup_connector (struct server *s,
	const struct str_vector *addresses, struct error **e)
{
	struct connector *connector = xmalloc (sizeof *connector);
	connector_init (connector, &s->ctx->poller);

	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;

	s->state = IRC_CONNECTING;
	s->connector = connector;

	for (size_t i = 0; i < addresses->len; i++)
	{
		char *host, *port;
		irc_split_host_port (addresses->vector[i], &host, &port);

		if (!connector_add_target (connector, host, port, e))
		{
			irc_destroy_connector (s);
			return false;
		}
	}

	connector_step (connector);
	return true;
}

static bool
irc_initiate_connect_socks (struct server *s,
	const struct str_vector *addresses, struct error **e)
{
	struct app_context *ctx = s->ctx;

	const char *socks_host = get_config_string (s->config, "socks_host");
	int64_t socks_port_int = get_config_integer (s->config, "socks_port");

	const char *socks_username =
		get_config_string (s->config, "socks_username");
	const char *socks_password =
		get_config_string (s->config, "socks_password");

	if (!socks_host)
		return false;

	// FIXME: we only try the first address (still better than nothing)
	char *irc_host, *irc_port;
	irc_split_host_port (addresses->vector[0], &irc_host, &irc_port);

	char *socks_port = xstrdup_printf ("%" PRIi64, socks_port_int);

	char *address = format_host_port_pair (irc_host, irc_port);
	char *socks_address = format_host_port_pair (socks_host, socks_port);
	buffer_send_status (ctx, s->buffer,
		"Connecting to %s via %s...", address, socks_address);
	free (socks_address);
	free (address);

	// TODO: the SOCKS code needs a rewrite so that we don't block on it either;
	//   perhaps it could act as a special kind of connector
	struct error *error = NULL;
	bool result = true;
	int fd = socks_connect (socks_host, socks_port, irc_host, irc_port,
		socks_username, socks_password, &error);
	if (fd != -1)
		irc_finish_connection (s, fd);
	else
	{
		error_set (e, "%s: %s", "SOCKS connection failed", error->message);
		error_free (error);
		result = false;
	}

	free (socks_port);
	return result;
}

static void
irc_initiate_connect (struct server *s)
{
	hard_assert (s->state == IRC_DISCONNECTED);
	struct app_context *ctx = s->ctx;

	const char *addresses = get_config_string (s->config, "addresses");
	if (!addresses || !addresses[strspn (addresses, ",")])
	{
		// No sense in trying to reconnect
		buffer_send_error (ctx, s->buffer,
			"No addresses specified in configuration");
		return;
	}

	struct str_vector servers;
	str_vector_init (&servers);
	split_str_ignore_empty (addresses, ',', &servers);

	struct error *e = NULL;
	if (!irc_initiate_connect_socks (s, &servers, &e) && !e)
		irc_setup_connector (s, &servers, &e);

	str_vector_free (&servers);

	if (e)
	{
		buffer_send_error (s->ctx, s->buffer, "%s", e->message);
		error_free (e);
		irc_queue_reconnect (s);
	}
}

// --- Input prompt ------------------------------------------------------------

static char *
make_unseen_prefix (struct app_context *ctx)
{
	struct str active_buffers;
	str_init (&active_buffers);

	size_t i = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
	{
		i++;
		if (!iter->unseen_messages_count)
			continue;

		if (active_buffers.len)
			str_append_c (&active_buffers, ',');
		if (iter->highlighted)
			str_append_c (&active_buffers, '!');
		str_append_printf (&active_buffers, "%zu", i);
	}

	if (active_buffers.len)
		return str_steal (&active_buffers);

	str_free (&active_buffers);
	return NULL;
}

static char *
make_chanmode_postfix (struct channel *channel)
{
	struct str modes;
	str_init (&modes);
	if (channel->no_param_modes.len)
		str_append (&modes, channel->no_param_modes.str);

	struct str_map_iter iter;
	str_map_iter_init (&iter, &channel->param_modes);
	char *param;
	while ((param = str_map_iter_next (&iter)))
		str_append_c (&modes, iter.link->key[0]);

	if (modes.len)
		return str_steal (&modes);

	str_free (&modes);
	return NULL;
}

static void
make_prompt (struct app_context *ctx, struct str *output)
{
	struct buffer *buffer = ctx->current_buffer;
	if (!buffer)
		return;

	str_append_c (output, '[');

	char *unseen_prefix = make_unseen_prefix (ctx);
	if (unseen_prefix)
		str_append_printf (output, "(%s) ", unseen_prefix);
	free (unseen_prefix);

	str_append_printf (output, "%d:%s",
		buffer_get_index (ctx, buffer), buffer->name);
	if (buffer->type == BUFFER_CHANNEL)
	{
		char *modes = make_chanmode_postfix (buffer->channel);
		if (modes)
			str_append_printf (output, "(+%s)", modes);
		free (modes);
	}

	if (buffer != ctx->global_buffer)
	{
		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
		{
			if (buffer->type == BUFFER_CHANNEL)
			{
				struct channel_user *channel_user =
					irc_channel_get_user (buffer->channel, s->irc_user);
				if (channel_user)
					str_append (output, channel_user->prefixes.str);
			}
			str_append (output, s->irc_user->nickname);
			if (s->irc_user_mode.len)
				str_append_printf (output, "(%s)", s->irc_user_mode.str);
		}
	}

	str_append_c (output, ']');
}

static void
refresh_prompt (struct app_context *ctx)
{
	bool have_attributes = !!get_attribute_printer (stdout);

	struct str prompt;
	str_init (&prompt);
	make_prompt (ctx, &prompt);
	str_append_c (&prompt, ' ');

	if (have_attributes)
	{
		// XXX: to be completely correct, we should use tputs, but we cannot
		input_set_prompt (&ctx->input, xstrdup_printf ("%c%s%c%s%c%s%c",
			INPUT_START_IGNORE, ctx->attrs[ATTR_PROMPT],
			INPUT_END_IGNORE,
			prompt.str,
			INPUT_START_IGNORE, ctx->attrs[ATTR_RESET],
			INPUT_END_IGNORE));
	}
	else
		input_set_prompt (&ctx->input, xstrdup (prompt.str));
	str_free (&prompt);
}

// --- 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 xstrndup (prefix, strcspn (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));
}

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

static struct buffer *
irc_get_buffer_for_message (struct server *s,
	const struct irc_message *msg, const char *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) ||
			(channel && !buffer) || (!channel && !buffer));

		// This is weird
		if (!channel)
			return NULL;
	}
	else if (!buffer)
	{
		// 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);
		// With the IRCv3.2 echo-message capability, we can receive messages
		// as they are delivired to the target; in that case, check the origin
		else if (soft_assert (irc_is_this_us (s, nickname)))
			buffer = irc_get_or_make_user_buffer (s, target);
		free (nickname);
	}
	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;

	// Well, this is rather crude but it should make most users happy.
	// Ideally we could do this at least in proper Unicode.
	char *copy = xstrdup (message);
	for (char *p = copy; *p; p++)
		*p = irc_tolower (*p);

	char *nick = xstrdup (s->irc_user->nickname);
	for (char *p = nick; *p; p++)
		*p = irc_tolower (*p);

	// Special characters allowed in nicknames by RFC 2812: []\`_^{|} and -
	// Also excluded from the ASCII: common user channel prefixes: +%@&~
	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;
}

// --- 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
};

/// 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;

	const char *all_prefixes = self->s->irc_chanuser_prefixes;
	const char *all_modes    = self->s->irc_chanuser_modes;
	char prefix = all_prefixes[strchr (all_modes, self->mode_char) - all_modes];

	struct str *prefixes = &channel_user->prefixes;
	const char *pos = strchr (prefixes->str, prefix);
	if (self->adding == !!pos)
		return;

	if (self->adding)
	{
		// Add the new mode prefix while retaining the right order
		char *old_prefixes = str_steal (prefixes);
		str_init (prefixes);
		for (const char *p = all_prefixes; *p; p++)
			if (*p == prefix || strchr (old_prefixes, *p))
				str_append_c (prefixes, *p);
		free (old_prefixes);
	}
	else
		str_remove_slice (prefixes, pos - prefixes->str, 1);
}

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)
{
	if      (strchr (self->s->irc_chanuser_modes,           self->mode_char))
		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;
}

static void
irc_handle_mode_channel
	(struct server *s, struct channel *channel, char **params)
{
	struct mode_processor p = { .s = s, .channel = channel };
	mode_processor_run (&p, params, mode_processor_apply_channel);
}

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

static bool
mode_processor_apply_user (struct mode_processor *self)
{
	mode_processor_toggle (self, &self->s->irc_user_mode);
	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);
}

// --- Input handling ----------------------------------------------------------

static void
irc_handle_cap (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 2)
		return;

	struct str_vector v;
	str_vector_init (&v);

	if (msg->params.len > 2)
		split_str_ignore_empty (msg->params.vector[2], ' ', &v);

	const char *subcommand = msg->params.vector[1];
	if (!strcasecmp_ascii (subcommand, "ACK"))
	{
		for (size_t i = 0; i < v.len; i++)
		{
			const char *cap = v.vector[i];
			bool active = true;
			if (*cap == '-')
			{
				active = false;
				cap++;
			}
			if (!strcasecmp_ascii (cap, "echo-message"))
				s->cap_echo_message = active;
		}
		irc_send (s, "CAP END");
	}
	else if (!strcasecmp_ascii (subcommand, "NAK"))
		irc_send (s, "CAP END");
	else if (!strcasecmp_ascii (subcommand, "LS"))
	{
		struct str_vector chosen;
		str_vector_init (&chosen);

		// Filter server capabilities for ones we can make use of
		for (size_t i = 0; i < v.len; i++)
		{
			const char *cap = v.vector[i];
			if (!strcasecmp_ascii (cap, "multi-prefix")
			 || !strcasecmp_ascii (cap, "invite-notify")
			 || !strcasecmp_ascii (cap, "echo-message"))
				str_vector_add (&chosen, cap);
		}

		char *chosen_str = join_str_vector (&chosen, ' ');
		str_vector_free (&chosen);
		irc_send (s, "CAP REQ :%s", chosen_str);
		free (chosen_str);
	}

	str_vector_free (&v);
}

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;

	// FIXME: logging
	char *who = irc_cut_nickname (msg->prefix);
	char *who_utf8 = irc_to_utf8 (s->ctx, who);
	free (who);

	// IRCv3.2 invite-notify extension allows the target to be someone else
	if (irc_is_this_us (s, target))
		buffer_send_status (s->ctx, buffer,
			"%s has invited you to %s", who_utf8, channel_name);
	else
		buffer_send_status (s->ctx, buffer,
			"%s has invited %s to %s", who_utf8, target, channel_name);

	free (who_utf8);
}

static void
irc_handle_join (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;

	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) ||
		(channel && !buffer) || (!channel && !buffer));

	// We've joined a new channel
	if (!channel && irc_is_this_us (s, msg->prefix))
	{
		buffer = buffer_new ();
		buffer->type = BUFFER_CHANNEL;
		buffer->name = xstrdup_printf ("%s.%s", s->name, 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);
		buffer_activate (s->ctx, buffer);

		// Request the channel mode as we don't get it automatically
		irc_send (s, "MODE %s", channel_name);
	}

	// This is weird, ignoring
	if (!channel)
		return;

	// 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)
	{
		buffer_send (s->ctx, buffer, BUFFER_LINE_JOIN, 0,
			.who    = irc_to_utf8 (s->ctx, msg->prefix),
			.object = irc_to_utf8 (s->ctx, 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 = "";
	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) ||
		(channel && !buffer) || (!channel && !buffer));

	// It would be is 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)
	{
		buffer_send (s->ctx, buffer, BUFFER_LINE_KICK, 0,
			.who    = irc_to_utf8 (s->ctx, msg->prefix),
			.object = irc_to_utf8 (s->ctx, target),
			.reason = irc_to_utf8 (s->ctx, message));
	}
}

static void
irc_handle_mode (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix || msg->params.len < 1)
		return;

	char *who = irc_cut_nickname (msg->prefix);
	const char *context = msg->params.vector[0];

	// Join the modes back to a single string
	struct str_vector copy;
	str_vector_init (&copy);
	str_vector_add_vector (&copy, msg->params.vector + 1);
	char *reconstructed = join_str_vector (&copy, ' ');
	str_vector_free (&copy);
	char *modes = irc_to_utf8 (s->ctx, reconstructed);
	free (reconstructed);

	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) ||
			(channel && !buffer) || (!channel && !buffer));

		if (channel)
			irc_handle_mode_channel (s, channel, msg->params.vector + 1);

		// FIXME: logging
		if (buffer)
		{
			buffer_send_status (s->ctx, buffer,
				"Mode %s [%s] by %s", context, modes, who);
		}
	}
	else if (irc_is_this_us (s, context))
	{
		irc_handle_mode_user (s, msg->params.vector + 1);

		// FIXME: logging
		buffer_send_status (s->ctx, s->buffer,
			"User mode [%s] by %s", modes, who);
	}
	else
	{
		// XXX: this shouldn't happen, reconnect?
	}

	free (who);
	free (modes);

	// Our own modes might have changed
	refresh_prompt (s->ctx);
}

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_identical =
		!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_identical
	 && !irc_server_strcmp (s, new_nickname, s->irc_user->nickname))
		return;

	// Log a message in any PM buffer and rename it;
	// we may even have one for ourselves
	struct buffer *pm_buffer =
		str_map_find (&s->irc_buffer_map, user->nickname);
	if (pm_buffer)
	{
		if (!lexicographically_identical)
		{
			str_map_set (&s->irc_buffer_map, new_nickname, pm_buffer);
			str_map_set (&s->irc_buffer_map, user->nickname, NULL);
		}

		char *who = irc_is_this_us (s, msg->prefix)
			? irc_to_utf8 (s->ctx, msg->prefix)
			: NULL;
		buffer_send (s->ctx, pm_buffer, BUFFER_LINE_NICK, 0,
			.who    = who,
			.object = irc_to_utf8 (s->ctx, new_nickname));

		char *x = xstrdup_printf ("%s.%s", s->name, new_nickname);
		buffer_rename (s->ctx, pm_buffer, x);
		free (x);
	}

	if (irc_is_this_us (s, msg->prefix))
	{
		// Log a message in all open buffers on this server
		struct str_map_iter iter;
		str_map_iter_init (&iter, &s->irc_buffer_map);
		struct buffer *buffer;
		while ((buffer = str_map_iter_next (&iter)))
		{
			// We've already done that
			if (buffer == pm_buffer)
				continue;

			buffer_send (s->ctx, buffer, BUFFER_LINE_NICK, 0,
				.object = irc_to_utf8 (s->ctx, 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);
			buffer_send (s->ctx, buffer, BUFFER_LINE_NICK, 0,
				.who    = irc_to_utf8 (s->ctx, msg->prefix),
				.object = irc_to_utf8 (s->ctx, new_nickname));
		}
	}

	// Finally rename the user
	if (!lexicographically_identical)
	{
		str_map_set (&s->irc_users, new_nickname, user_ref (user));
		str_map_set (&s->irc_users, user->nickname, NULL);
	}

	free (user->nickname);
	user->nickname = xstrdup (new_nickname);

	// We might have renamed ourselves
	refresh_prompt (s->ctx);
}

static void
irc_handle_ctcp_reply (struct server *s,
	const struct irc_message *msg, struct ctcp_chunk *chunk)
{
	char *nickname      = irc_cut_nickname (msg->prefix);
	char *nickname_utf8 = irc_to_utf8 (s->ctx, nickname);
	char *tag_utf8      = irc_to_utf8 (s->ctx, chunk->tag.str);
	char *text_utf8     = irc_to_utf8 (s->ctx, chunk->text.str);

	buffer_send_status (s->ctx, s->buffer,
		"CTCP reply from %s: %s %s", nickname_utf8, tag_utf8, text_utf8);

	free (nickname);
	free (nickname_utf8);
	free (tag_utf8);
	free (text_utf8);
}

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)
	{
		int flags = irc_is_highlight (s, text->str)
			? BUFFER_LINE_HIGHLIGHT
			: 0;
		buffer_send (s->ctx, buffer, BUFFER_LINE_NOTICE, flags,
			.who  = irc_to_utf8 (s->ctx, msg->prefix),
			.text = irc_to_utf8 (s->ctx, text->str));
	}
}

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) ||
		(channel && !buffer) || (!channel && !buffer));

	// It would be is 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)
	{
		buffer_send (s->ctx, buffer, BUFFER_LINE_PART, 0,
			.who    = irc_to_utf8 (s->ctx, msg->prefix),
			.object = irc_to_utf8 (s->ctx, channel_name),
			.reason = irc_to_utf8 (s->ctx, message));
	}
}

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_init (&m);

	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);

	char *text_utf8      = irc_to_utf8 (s->ctx, m.str);
	char *recipient_utf8 = irc_to_utf8 (s->ctx, recipient);
	str_free (&m);

	buffer_send_status (s->ctx, s->buffer,
		"CTCP reply to %s: %s", recipient_utf8, text_utf8);
	free (text_utf8);
	free (recipient_utf8);
}

static void
irc_handle_ctcp_request (struct server *s,
	const struct irc_message *msg, struct ctcp_chunk *chunk)
{
	char *nickname      = irc_cut_nickname (msg->prefix);
	char *nickname_utf8 = irc_to_utf8 (s->ctx, nickname);
	char *tag_utf8      = irc_to_utf8 (s->ctx, chunk->tag.str);

	buffer_send_status (s->ctx, s->buffer,
		"CTCP requested by %s: %s", nickname_utf8, tag_utf8);

	const char *target = msg->params.vector[0];
	const char *recipient = nickname;
	if (irc_is_channel (s, target))
		recipient = target;

	if (!strcmp (chunk->tag.str, "CLIENTINFO"))
		irc_send_ctcp_reply (s, recipient, "CLIENTINFO %s %s %s %s",
			"PING", "VERSION", "TIME", "CLIENTINFO");
	else if (!strcmp (chunk->tag.str, "PING"))
		irc_send_ctcp_reply (s, recipient, "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, recipient, "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, recipient, "TIME %s", buf);
	}

	free (nickname);
	free (nickname_utf8);
	free (tag_utf8);
}

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);

	const char *prefixes = "";
	if (irc_is_channel (s, target))
	{
		char *nickname = irc_cut_nickname (msg->prefix);

		struct user *user;
		struct channel *channel;
		struct channel_user *channel_user;
		if ((user = str_map_find (&s->irc_users, nickname))
		 && (channel = str_map_find (&s->irc_channels, target))
		 && (channel_user = irc_channel_get_user (channel, user)))
			prefixes = channel_user->prefixes.str;

		free (nickname);
	}

	if (buffer)
	{
		// TODO: some more obvious indication of highlights
		int flags = irc_is_highlight (s, text->str)
			? BUFFER_LINE_HIGHLIGHT
			: 0;
		enum buffer_line_type type = is_action
			? BUFFER_LINE_ACTION
			: BUFFER_LINE_PRIVMSG;
		buffer_send (s->ctx, buffer, type, flags,
			.who  = irc_to_utf8 (s->ctx, msg->prefix),
			.text = irc_to_utf8 (s->ctx, text->str),
			.prefixes = xstrdup (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
irc_handle_quit (struct server *s, const struct irc_message *msg)
{
	if (!msg->prefix)
		return;

	// What the fuck
	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)
	{
		buffer_send (s->ctx, buffer, BUFFER_LINE_QUIT, 0,
			.who    = irc_to_utf8 (s->ctx, msg->prefix),
			.reason = irc_to_utf8 (s->ctx, 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)
	{
		buffer = str_map_find (&s->irc_buffer_map, iter->channel->name);
		if (buffer)
			buffer_send (s->ctx, buffer, BUFFER_LINE_QUIT, 0,
				.who    = irc_to_utf8 (s->ctx, msg->prefix),
				.reason = irc_to_utf8 (s->ctx, message));

		// This destroys "iter" which doesn't matter to us
		irc_remove_user_from_channel (user, iter->channel);
	}
}

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) ||
		(channel && !buffer) || (!channel && !buffer));

	// It would be is weird for this to be false
	if (channel)
	{
		free (channel->topic);
		channel->topic = xstrdup (topic);
	}

	if (buffer)
	{
		buffer_send (s->ctx, buffer, BUFFER_LINE_TOPIC, 0,
			.who  = irc_to_utf8 (s->ctx, msg->prefix),
			.text = irc_to_utf8 (s->ctx, topic));
	}
}

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

static struct irc_handler
{
	char *name;
	void (*handler) (struct server *s, const struct irc_message *msg);
}
g_irc_handlers[] =
{
	// This list needs to stay sorted
	{ "CAP",     irc_handle_cap     },
	{ "INVITE",  irc_handle_invite  },
	{ "JOIN",    irc_handle_join    },
	{ "KICK",    irc_handle_kick    },
	{ "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    },
	{ "TOPIC",   irc_handle_topic   },
};

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 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))
	{
		free (s->irc_user_host);
		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 str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (m, ' ', &v);
	for (size_t i = 0; i < v.len; i++)
		if (irc_try_parse_word_for_userhost (s, v.vector[i]))
			break;
	str_vector_free (&v);
}

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_mode);
	s->irc_user_host = NULL;

	s->state = IRC_REGISTERED;
	refresh_prompt (s->ctx);

	// XXX: we can also use WHOIS if it's not supported (optional by RFC 2812)
	irc_send (s, "USERHOST %s", s->irc_user->nickname);

	const char *autojoin = get_config_string (s->config, "autojoin");
	if (autojoin)
		irc_send (s, "JOIN :%s", autojoin);

	// TODO: rejoin all current channels (mark those we've left manually?)
}

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 str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (response, ' ', &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))
		{
			free (s->irc_user_host);
			s->irc_user_host = xstrdup (userhost);
		}
	}

	str_vector_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_mode);
	irc_handle_mode_user (s, msg->params.vector + 1);

	// XXX: do we want to log a message?
	refresh_prompt (s->ctx);
}

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 for later processing
	struct channel *channel = str_map_find (&s->irc_channels, channel_name);
	if (channel)
		split_str_ignore_empty (nicks, ' ', &channel->names_buf);
}

static void
irc_sync_channel_user (struct server *s, struct channel *channel,
	const char *nickname, const char *prefixes)
{
	struct user *user = irc_get_or_make_user (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.str[0] != prefixes[0])
	{
		str_reset (&channel_user->prefixes);
		str_append (&channel_user->prefixes, prefixes);
	}
}

static void
irc_process_names (struct server *s, struct channel *channel)
{
	struct str_map present;
	str_map_init (&present);
	present.key_xfrm = s->irc_strxfrm;

	struct str_vector *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, 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 (s, 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);
	str_vector_reset (&channel->names_buf);

	struct str_vector v;
	str_vector_init (&v);
	LIST_FOR_EACH (struct channel_user, iter, channel->users)
		str_vector_add_owned (&v,
			xstrdup_printf ("%s%s", iter->prefixes.str, iter->user->nickname));
	char *all_users = join_str_vector (&v, ' ');
	str_vector_free (&v);

	// XXX: only do this after joining the channel?
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, channel->name);
	if (buffer)
	{
		// FIXME: logging
		buffer_send_status (s->ctx, buffer, "Users on %s: %s",
			channel->name, all_users);
	}

	free (all_users);
}

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_init (&iter, &s->irc_channels);
		struct channel *channel;
		while ((channel = str_map_iter_next (&iter)))
			irc_process_names (s, channel);
	}
	else if (channel)
		irc_process_names (s, channel);
}

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) ||
		(channel && !buffer) || (!channel && !buffer));

	if (channel)
	{
		free (channel->topic);
		channel->topic = xstrdup (topic);
	}

	if (buffer)
	{
		// FIXME: logging
		buffer_send_status (s->ctx, buffer, "The topic is: %s", 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) ||
		(channel && !buffer) || (!channel && !buffer));

	if (channel)
	{
		str_reset (&channel->no_param_modes);
		str_map_clear (&channel->param_modes);

		irc_handle_mode_channel (s, channel, msg->params.vector + 1);
	}

	// XXX: do we want to log a message?
	refresh_prompt (s->ctx);
}

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) ||
		(channel && !buffer) || (!channel && !buffer));

	if (buffer)
	{
		char *x = make_time_string (created);
		buffer_send_status (s->ctx, buffer, "Channel created on %s", x);
		free (x);
	}
}

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) ||
		(channel && !buffer) || (!channel && !buffer));

	// Topic set by x (y@z) on ...
	if (buffer)
	{
		// FIXME: logging
		char *x = make_time_string (changed);
		buffer_send_status (s->ctx, buffer, "Topic set by %s on %s", who, x);
		free (x);
	}
}

static void
irc_handle_rpl_inviting (struct server *s, const struct irc_message *msg)
{
	if (msg->params.len < 3)
		return;

	const char *channel_name = msg->params.vector[1];
	const char *nickname     = msg->params.vector[2];

	struct buffer *buffer;;
	if (!(buffer = str_map_find (&s->irc_buffer_map, channel_name)))
		buffer = s->buffer;

	// FIXME: logging
	buffer_send_status (s->ctx, buffer,
		"You have invited %s to %s", nickname, channel_name);
}

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

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;

	free (s->irc_chanuser_modes);
	free (s->irc_chanuser_prefixes);

	s->irc_chanuser_modes    = xstrndup (modes,    n_prefixes);
	s->irc_chanuser_prefixes = xstrndup (prefixes, n_prefixes);
}

static void
irc_handle_isupport_casemapping (struct server *s, char *value)
{
	// TODO: reinitialize hashtables with the new tolower() and strxfrm(),
	//   note that collisions may arise on reconnecting

	if      (!strcmp (value, "ascii"))
	{
		s->irc_tolower = tolower_ascii;
		s->irc_strxfrm = tolower_ascii_strxfrm;
	}
	else if (!strcmp (value, "rfc1459"))
	{
		s->irc_tolower = irc_tolower;
		s->irc_strxfrm = irc_strxfrm;
	}
	else if (!strcmp (value, "rfc1459-strict"))
	{
		// TODO: implement
		s->irc_tolower = irc_tolower;
		s->irc_strxfrm = irc_strxfrm;
	}
}

static void
irc_handle_isupport_chantypes (struct server *s, char *value)
{
	free (s->irc_chantypes);
	s->irc_chantypes = xstrdup (value);
}

static void
irc_handle_isupport_idchan (struct server *s, char *value)
{
	struct str prefixes;
	str_init (&prefixes);

	struct str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (value, ',', &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);
	}
	str_vector_free (&v);

	free (s->irc_idchan_prefixes);
	s->irc_idchan_prefixes = str_steal (&prefixes);
}

static void
irc_handle_isupport_statusmsg (struct server *s, char *value)
{
	free (s->irc_statusmsg);
	s->irc_statusmsg = xstrdup (value);
}

static void
irc_handle_isupport_chanmodes (struct server *s, char *value)
{
	struct str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (value, ',', &v);
	if (v.len >= 4)
	{
		free (s->irc_chanmodes_list);
		s->irc_chanmodes_list           = xstrdup (v.vector[0]);
		free (s->irc_chanmodes_param_always);
		s->irc_chanmodes_param_always   = xstrdup (v.vector[1]);
		free (s->irc_chanmodes_param_when_set);
		s->irc_chanmodes_param_when_set = xstrdup (v.vector[2]);
		free (s->irc_chanmodes_param_never);
		s->irc_chanmodes_param_never    = xstrdup (v.vector[3]);
	}
	str_vector_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
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_init (&value_unescaped);
		unescape_isupport_value (value, &value_unescaped);

		if      (!strcmp (param, "PREFIX"))
			irc_handle_isupport_prefix      (s, value_unescaped.str);
		else if (!strcmp (param, "CASEMAPPING"))
			irc_handle_isupport_casemapping (s, value_unescaped.str);
		else if (!strcmp (param, "CHANTYPES"))
			irc_handle_isupport_chantypes   (s, value_unescaped.str);
		else if (!strcmp (param, "IDCHAN"))
			irc_handle_isupport_idchan      (s, value_unescaped.str);
		else if (!strcmp (param, "STATUSMSG"))
			irc_handle_isupport_statusmsg   (s, value_unescaped.str);
		else if (!strcmp (param, "CHANMODES"))
			irc_handle_isupport_chanmodes   (s, value_unescaped.str);
		else if (!strcmp (param, "MODES"))
			irc_handle_isupport_modes       (s, value_unescaped.str);

		// TODO: also parse TARGMAX and make use of it
		//   to split client commands as necessary

		str_free (&value_unescaped);
	}
}

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

static void
irc_process_numeric (struct server *s,
	const struct irc_message *msg, unsigned long numeric)
{
	// Numerics typically have human-readable information
	// TODO: try to output certain replies in more specific buffers

	// TODO: fail the connection if there's no first parameter

	// 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 str_vector copy;
	str_vector_init (&copy);
	str_vector_add_vector (&copy, msg->params.vector + !!msg->params.len);

	struct buffer *buffer = s->buffer;
	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_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:
		// TODO: if (state == IRC_CONNECTED), use a different nick;
		//   either use a number suffix, or accept commas in "nickname" config
		break;

	case IRC_RPL_LIST:
	case IRC_RPL_WHOREPLY:
	case IRC_RPL_ENDOFWHO:

	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
		// and we should whitelist/blacklist a lot more replies here.
		// TODO: if this happens, we should either strip the first parameter
		//   from the buffer line, or at least put it in brackets
		if (msg->params.len > 1)
		{
			struct buffer *x;
			if ((x = str_map_find (&s->irc_buffer_map, msg->params.vector[1])))
				buffer = x;
		}
	}

	if (buffer)
	{
		// Join the parameter vector back, recode it to our internal encoding
		// and send it to the server buffer
		char *reconstructed = join_str_vector (&copy, ' ');
		buffer_send (s->ctx, buffer, BUFFER_LINE_STATUS, 0,
			.text = irc_to_utf8 (s->ctx, reconstructed));
		free (reconstructed);
	}

	str_vector_free (&copy);
}

static void
irc_process_message (const struct irc_message *msg,
	const char *raw, void *user_data)
{
	struct server *s = user_data;

	if (g_debug_mode)
	{
		input_hide (&s->ctx->input);

		char *server_name =
			iconv_xstrdup (s->ctx->term_from_utf8, s->name, -1, NULL);
		char *term = irc_to_term (s->ctx, raw);
		fprintf (stderr, "[%s] ==> \"%s\"\n", server_name, term);
		free (term);
		free (server_name);

		input_show (&s->ctx->input);
	}

	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);
}

// --- Message autosplitting magic ---------------------------------------------

// This is the most basic acceptable 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, size_t text_len,
	size_t line_len, struct str *output)
{
	int 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 (line_len && word_len <= line_len)
	{
		if (word_len)
		{
			str_append_data (output, text, word_len);

			text += word_len;
			eaten += word_len;
			line_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
	while (true)
	{
		const char *next = utf8_next (text, text_len - eaten, NULL);
		hard_assert (next);

		size_t char_len = next - text;
		if (char_len > line_len)
			break;

		str_append_data (output, text, char_len);

		text += char_len;
		eaten += char_len;
		line_len -= char_len;
	}
	return eaten;
}

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

static bool
wrap_message (const char *message,
	int line_max, struct str_vector *output, struct error **e)
{
	if (line_max <= 0)
		goto error;

	for (size_t message_left = strlen (message); message_left; )
	{
		struct str m;
		str_init (&m);

		size_t eaten = wrap_text_for_single_line (message,
			MIN ((size_t) line_max, message_left), message_left, &m);
		if (!eaten)
		{
			str_free (&m);
			goto error;
		}

		str_vector_add_owned (output, str_steal (&m));
		message += eaten;
		message_left -= eaten;
	}
	return true;

error:
	// Well, that's just weird
	error_set (e,
		"Message splitting was unsuccessful as there was "
		"too little room for UTF-8 characters");
	return false;
}

/// 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 str_vector *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;

	// However we don't always have the full info for message splitting
	if (!space_in_one_message)
		str_vector_add (output, message);
	else if (!wrap_message (message, space_in_one_message, output, e))
		return false;
	return true;
}

struct send_autosplit_args;

typedef void (*send_autosplit_logger_fn) (struct server *s,
	struct send_autosplit_args *args, struct buffer *buffer, const char *line);

struct send_autosplit_args
{
	const char *command;                ///< E.g. PRIVMSG or NOTICE
	const char *target;                 ///< User or channel
	const char *message;                ///< A message to be autosplit
	send_autosplit_logger_fn logger;    ///< Logger for all resulting lines
	const char *prefix;                 ///< E.g. "\x01ACTION"
	const char *suffix;                 ///< E.g. "\x01"
};

static void
send_autosplit_message (struct server *s, struct send_autosplit_args a)
{
	struct buffer *buffer = str_map_find (&s->irc_buffer_map, a.target);
	int fixed_part = strlen (a.command) + 1 + strlen (a.target) + 1 + 1
		+ strlen (a.prefix) + strlen (a.suffix);

	// We might also want to preserve attributes across splits but
	// that would make this code a lot more complicated

	struct str_vector lines;
	str_vector_init (&lines);
	struct error *e = NULL;
	if (!irc_autosplit_message (s, a.message, fixed_part, &lines, &e))
	{
		buffer_send_error (s->ctx,
			buffer ? buffer : s->buffer, "%s", e->message);
		error_free (e);
		goto end;
	}

	for (size_t i = 0; i < lines.len; i++)
	{
		irc_send (s, "%s %s :%s%s%s", a.command, a.target,
			a.prefix, lines.vector[i], a.suffix);
		if (!s->cap_echo_message)
			a.logger (s, &a, buffer, lines.vector[i]);
	}
end:
	str_vector_free (&lines);
}

static void
log_outcoming_action (struct server *s,
	struct send_autosplit_args *a, struct buffer *buffer, const char *line)
{
	(void) a;

	if (buffer && soft_assert (s->irc_user))
		buffer_send (s->ctx, buffer, BUFFER_LINE_ACTION, 0,
			.who  = irc_to_utf8 (s->ctx, s->irc_user->nickname),
			.text = irc_to_utf8 (s->ctx, line));

	// This can only be sent from a user or channel buffer
}

#define SEND_AUTOSPLIT_ACTION(s, target, message)                              \
	send_autosplit_message ((s), (struct send_autosplit_args)                  \
		{ "PRIVMSG", (target), (message), log_outcoming_action,                \
		  "\x01" "ACTION ", "\x01" })

static void
log_outcoming_privmsg (struct server *s,
	struct send_autosplit_args *a, struct buffer *buffer, const char *line)
{
	const char *prefixes = "";
	if (irc_is_channel (s, a->target))
	{
		struct user *user;
		struct channel *channel;
		struct channel_user *channel_user;
		if ((user = s->irc_user)
		 && (channel = str_map_find (&s->irc_channels, a->target))
		 && (channel_user = irc_channel_get_user (channel, user)))
			prefixes = channel_user->prefixes.str;
	}

	if (buffer && soft_assert (s->irc_user))
		buffer_send (s->ctx, buffer, BUFFER_LINE_PRIVMSG, 0,
			.who  = irc_to_utf8 (s->ctx, s->irc_user->nickname),
			.text = irc_to_utf8 (s->ctx, line),
			.prefixes = xstrdup (prefixes));
	else
		// TODO: fix logging and encoding
		buffer_send (s->ctx, s->buffer, BUFFER_LINE_STATUS, 0,
			.text = xstrdup_printf ("MSG(%s): %s", a->target, line));
}

#define SEND_AUTOSPLIT_PRIVMSG(s, target, message)                             \
	send_autosplit_message ((s), (struct send_autosplit_args)                  \
		{ "PRIVMSG", (target), (message), log_outcoming_privmsg, "", "" })

static void
log_outcoming_notice (struct server *s,
	struct send_autosplit_args *a, struct buffer *buffer, const char *line)
{
	if (buffer && soft_assert (s->irc_user))
		buffer_send (s->ctx, buffer, BUFFER_LINE_NOTICE, 0,
			.who  = irc_to_utf8 (s->ctx, s->irc_user->nickname),
			.text = irc_to_utf8 (s->ctx, line));
	else
		// TODO: fix logging and encoding
		buffer_send (s->ctx, s->buffer, BUFFER_LINE_STATUS, 0,
			.text = xstrdup_printf ("Notice -> %s: %s", a->target, line));
}

#define SEND_AUTOSPLIT_NOTICE(s, target, message)                              \
	send_autosplit_message ((s), (struct send_autosplit_args)                  \
		{ "NOTICE", (target), (message), log_outcoming_notice, "", "" })

// --- Configuration dumper ----------------------------------------------------

struct config_dump_level
{
	struct config_dump_level *next;     ///< Next print level
	const char *name;                   ///< Name of the object
};

struct config_dump_data
{
	struct config_dump_level *head;     ///< The first level
	struct config_dump_level **tail;    ///< Where to place further levels
	struct str_vector *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 config_dump_level level;
	level.next = NULL;

	struct config_dump_level **prev_tail = data->tail;
	*data->tail = &level;
	data->tail = &level.next;

	struct str_map_iter iter;
	str_map_iter_init (&iter, &object->value.object);
	struct config_item_ *child;
	while ((child = str_map_iter_next (&iter)))
	{
		level.name = iter.link->key;
		config_dump_item (child, data);
	}

	data->tail = prev_tail;
	*data->tail = NULL;
}

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;
	}

	struct str line;
	str_init (&line);

	struct config_dump_level *iter = data->head;
	if (iter)
	{
		str_append (&line, iter->name);
		iter = iter->next;
	}
	for (; iter; iter = iter->next)
		str_append_printf (&line, ".%s", iter->name);

	// Don't bother writing out null values everywhere
	struct config_schema *schema = item->schema;
	bool has_default = schema && schema->default_;
	if (item->type != CONFIG_ITEM_NULL || has_default)
	{
		str_append (&line, " = ");

		struct str value;
		str_init (&value);
		config_item_write (item, false, &value);
		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);
	}

	str_vector_add_owned (data->output, str_steal (&line));
}

static void
config_dump (struct config_item_ *root, struct str_vector *output)
{
	struct config_dump_data data;
	data.head = NULL;
	data.tail = &data.head;
	data.output = output;

	config_dump_item (root, &data);
}

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

static int
str_vector_sort_cb (const void *a, const void *b)
{
	return strcmp (*(const char **) a, *(const char **) b);
}

static void
str_vector_sort (struct str_vector *self)
{
	qsort (self->vector, self->len, sizeof *self->vector, str_vector_sort_cb);
}

static void
dump_matching_options
	(struct app_context *ctx, const char *mask, struct str_vector *output)
{
	config_dump (ctx->config.root, output);
	str_vector_sort (output);

	// Filter out results by wildcard matching
	for (size_t i = 0; i < output->len; i++)
	{
		// Yeah, I know
		const char *line = output->vector[i];
		char *key = xstrndup (line, strcspn (line, " "));
		if (fnmatch (mask, key, 0))
			str_vector_remove (output, i--);
		free (key);
	}
}

// --- 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 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
	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))
		buffer_send_error (ctx, NULL, "%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);
	// TODO: partial matches
	return buffer;
}

static void
show_buffers_list (struct app_context *ctx)
{
	buffer_send_status (ctx, NULL, "%s", "");
	buffer_send_status (ctx, NULL, "Buffers list:");

	int i = 1;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
		buffer_send_status (ctx, NULL, "  [%d] %s", i++, iter->name);
}

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)
		buffer_send_error (ctx, NULL, "%s: %s", "No such buffer", which);
	else if (buffer == ctx->global_buffer)
		buffer_send_error (ctx, NULL, "Can't close the global buffer");
	else if (buffer->type == BUFFER_SERVER)
		buffer_send_error (ctx, NULL, "Can't close a server buffer");
	else
	{
		if (buffer == ctx->current_buffer)
			buffer_activate (ctx, buffer_next (ctx, 1));
		buffer_remove (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;

	unsigned long total = 0;
	LIST_FOR_EACH (struct buffer, iter, ctx->buffers)
		total++;

	if (request == 0 || request > total)
	{
		buffer_send_error (ctx, NULL, "%s: %s",
			"Can't move buffer", "requested position is out of range");
		return true;
	}

	struct buffer *buffer = a->buffer;
	LIST_UNLINK_WITH_TAIL (ctx->buffers, ctx->buffers_tail, buffer);

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

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

	refresh_prompt (ctx);
	return true;
}

static bool
handle_command_buffer (struct app_context *ctx, struct handler_args *a)
{
	char *action = cut_word (&a->arguments);
	if (try_handle_buffer_goto (ctx, action))
		return true;

	// XXX: also build a prefix map?
	// TODO: some subcommand to print N last lines from the buffer
	bool result = true;
	if (!strcasecmp_ascii (action, "list"))
		show_buffers_list (ctx);
	else if (!strcasecmp_ascii (action, "clear"))
	{
		buffer_clear (a->buffer);
		// XXX: clear screen?
		buffer_print_backlog (ctx, a->buffer);
	}
	else if (!strcasecmp_ascii (action, "move"))
		result = handle_buffer_move (ctx, a);
	else if (!strcasecmp_ascii (action, "close"))
		handle_buffer_close (ctx, a);
	else
		result = false;
	return true;
}

static bool
replace_string_array
	(struct config_item_ *item, struct str_vector *array, struct error **e)
{
	char *changed = join_str_vector (array, ',');
	struct str tmp = { .str = changed, .len = strlen (changed) };
	bool result = config_item_set_from (item,
		config_item_string_array (&tmp), e);
	free (changed);
	return result;
}

static bool
handle_command_set_add
	(struct config_item_ *item, const char *value, struct error **e)
{
	bool result = false;
	struct str_vector items;
	str_vector_init (&items);
	split_str (item->value.string.str, ',', &items);
	if (items.len == 1 && !*items.vector[0])
		str_vector_reset (&items);

	if (str_vector_find (&items, value) != -1)
		error_set (e, "already present in the array: %s", value);
	else
	{
		str_vector_add (&items, value);
		result = replace_string_array (item, &items, e);
	}

	str_vector_free (&items);
	return result;
}

static bool
handle_command_set_remove
	(struct config_item_ *item, const char *value, struct error **e)
{
	bool result = false;
	struct str_vector items;
	str_vector_init (&items);
	split_str (item->value.string.str, ',', &items);
	if (items.len == 1 && !*items.vector[0])
		str_vector_reset (&items);

	ssize_t i = str_vector_find (&items, value);
	if (i == -1)
		error_set (e, "not present in the array: %s", value);
	else
	{
		str_vector_remove (&items, i);
		result = replace_string_array (item, &items, e);
	}

	str_vector_free (&items);
	return result;
}

static void
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) && item->type != CONFIG_ITEM_STRING_ARRAY)
		// FIXME: it can also be null, which makes this message confusing
		error_set (&e, "not a string array");
	else if (add)
		handle_command_set_add (item, new_->value.string.str, &e);
	else if (remove)
		handle_command_set_remove (item, new_->value.string.str, &e);
	else
		config_item_set_from (item, config_item_clone (new_), &e);

	if (e)
	{
		buffer_send_error (ctx, NULL,
			"Failed to set option \"%s\": %s", key, e->message);
		error_free (e);
	}
	else
	{
		struct str_vector tmp;
		str_vector_init (&tmp);
		dump_matching_options (ctx, key, &tmp);
		buffer_send_status (ctx, NULL, "Option changed: %s", tmp.vector[0]);
		str_vector_free (&tmp);
	}
}

static bool
handle_command_set_assign
	(struct app_context *ctx, struct str_vector *all, char *arguments)
{
	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)
	{
		buffer_send_error (ctx, NULL, "Invalid value: %s", e->message);
		error_free (e);
		return true;
	}

	if ((add | remove) && !config_item_type_is_string (new_->type))
	{
		buffer_send_error (ctx, NULL,
			"+= / -= operators need a string argument");
		config_item_destroy (new_);
		return true;
	}
	for (size_t i = 0; i < all->len; i++)
	{
		char *key = xstrndup (all->vector[i], strcspn (all->vector[i], " "));
		handle_command_set_assign_item (ctx, key, new_, add, remove);
		free (key);
	}
	config_item_destroy (new_);
	return true;
}

static bool
handle_command_set (struct app_context *ctx, struct handler_args *a)
{
	char *option = "*";
	if (*a->arguments)
		option = cut_word (&a->arguments);

	struct str_vector all;
	str_vector_init (&all);
	dump_matching_options (ctx, option, &all);

	bool result = true;
	if (!all.len)
		buffer_send_error (ctx, NULL, "No matches: %s", option);
	else if (!*a->arguments)
	{
		buffer_send_status (ctx, NULL, "%s", "");
		for (size_t i = 0; i < all.len; i++)
			buffer_send_status (ctx, NULL, "%s", all.vector[i]);
	}
	else
		result = handle_command_set_assign (ctx, &all, a->arguments);

	str_vector_free (&all);
	return result;
}

static bool
handle_command_save (struct app_context *ctx, struct handler_args *a)
{
	if (*a->arguments)
		return false;

	struct str data;
	str_init (&data);
	serialize_configuration (ctx, &data);

	struct error *e = NULL;
	char *filename = write_configuration_file (&data, &e);
	str_free (&data);

	if (!filename)
	{
		buffer_send_error (ctx, NULL,
			"%s: %s", "Saving configuration failed", e->message);
		error_free (e);
	}
	else
		buffer_send_status (ctx, NULL,
			"Configuration written to `%s'", filename);
	free (filename);
	return true;
}

static bool
handle_command_msg (struct app_context *ctx, struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (!*a->arguments)
		buffer_send_error (ctx, a->s->buffer, "No text to send");
	else
		SEND_AUTOSPLIT_PRIVMSG (a->s, target, a->arguments);
	return true;
}

static bool
handle_command_query (struct app_context *ctx, struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (irc_is_channel (a->s, target))
		buffer_send_error (ctx, a->s->buffer, "Cannot query a channel");
	else if (!*a->arguments)
		buffer_send_error (ctx, a->s->buffer, "No text to send");
	else
	{
		buffer_activate (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 app_context *ctx, struct handler_args *a)
{
	if (!*a->arguments)
		return false;

	char *target = cut_word (&a->arguments);
	if (!*a->arguments)
		buffer_send_error (ctx, a->s->buffer, "No text to send");
	else
		SEND_AUTOSPLIT_NOTICE (a->s, target, a->arguments);
	return true;
}

static bool
handle_command_ctcp (struct app_context *ctx, 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);
	for (char *p = tag; *p; p++)
		*p = toupper_ascii (*p);

	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);

	buffer_send_status (ctx, a->s->buffer, "CTCP query to %s: %s", target, tag);
	return true;
}

static bool
handle_command_me (struct app_context *ctx, 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
		buffer_send_error (ctx, a->s->buffer,
			"Can't do this from a server buffer (%s)",
			"send CTCP actions");
	return true;
}

static bool
handle_command_quit (struct app_context *ctx, struct handler_args *a)
{
	struct str_map_iter iter;
	str_map_iter_init (&iter, &ctx->servers);

	struct server *s;
	while ((s = str_map_iter_next (&iter)))
	{
		if (irc_is_connected (s))
			irc_initiate_disconnect (s, *a->arguments ? a->arguments : NULL);
	}

	initiate_quit (ctx);
	return true;
}

static bool
handle_command_join (struct app_context *ctx, 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)
		buffer_send_error (ctx, a->buffer,
			"%s: %s", "Can't join",
			"no channel name given and this buffer is not a channel");
	// TODO: have a better way of checking if we're on the channel
	else if (a->buffer->channel->users)
		buffer_send_error (ctx, 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 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);
}

static bool
handle_command_part (struct app_context *ctx, struct handler_args *a)
{
	if (irc_is_channel (a->s, a->arguments))
	{
		struct str_vector v;
		str_vector_init (&v);
		split_str_ignore_empty (cut_word (&a->arguments), ' ', &v);
		for (size_t i = 0; i < v.len; i++)
			part_channel (a->s, v.vector[i], a->arguments);
		str_vector_free (&v);
	}
	else if (a->buffer->type != BUFFER_CHANNEL)
		buffer_send_error (ctx, a->buffer,
			"%s: %s", "Can't part",
			"no channel name given and this buffer is not a channel");
	// TODO: have a better way of checking if we're on the channel
	else if (!a->buffer->channel->users)
		buffer_send_error (ctx, 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 app_context *ctx, struct handler_args *a)
{
	if (irc_is_channel (a->s, a->arguments))
	{
		struct str_vector v;
		str_vector_init (&v);
		split_str_ignore_empty (cut_word (&a->arguments), ' ', &v);
		for (size_t i = 0; i < v.len; i++)
			cycle_channel (a->s, v.vector[i], a->arguments);
		str_vector_free (&v);
	}
	else if (a->buffer->type != BUFFER_CHANNEL)
		buffer_send_error (ctx, a->buffer,
			"%s: %s", "Can't cycle",
			"no channel name given and this buffer is not a channel");
	// TODO: have a better way of checking if we're on the channel
	else if (!a->buffer->channel->users)
		buffer_send_error (ctx, 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 app_context *ctx, 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)
		buffer_send_error (ctx, 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 app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	if (*a->arguments)
		// FIXME: there's no way to unset the topic
		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 app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	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 app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	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 str_vector *v)
{
	size_t n;
	for (size_t i = 0; i < v->len; i += n)
	{
		struct str modes;   str_init (&modes);
		struct str params;  str_init (&params);

		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 str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (a->arguments, ' ', &v);

	// XXX: this may be a bit too trivial; we could map also 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, "!@*?"))
			continue;

		v.vector[i] = xstrdup_printf ("%s!*@*", target);
		free (target);
	}

	mass_channel_mode (a->s, a->channel_name, adding, mode_char, &v);
	str_vector_free (&v);
}

static bool
handle_command_ban (struct app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	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 app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	if (*a->arguments)
		mass_channel_mode_mask_list (a, false, 'b');
	else
		return false;
	return true;
}

static bool
handle_command_invite (struct app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	struct str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (a->arguments, ' ', &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);

	str_vector_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)))
			buffer_send_error (ctx, NULL, "/%s: %s: %s",
				command_name, "no such server", server_name);
	}
	else if (a->buffer->type == BUFFER_GLOBAL)
		buffer_send_error (ctx, NULL, "/%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 app_context *ctx, struct handler_args *a)
{
	struct server *s = NULL;
	if (!(s = resolve_server (ctx, a, "connect")))
		return true;

	if (irc_is_connected (s))
	{
		buffer_send_error (ctx, s->buffer, "Already connected");
		return true;
	}
	if (s->state == IRC_CONNECTING)
		irc_destroy_connector (s);

	irc_cancel_timers (s);
	irc_initiate_connect (s);
	return true;
}

static bool
handle_command_disconnect (struct app_context *ctx, struct handler_args *a)
{
	struct server *s = NULL;
	if (!(s = resolve_server (ctx, a, "disconnect")))
		return true;

	if (s->state == IRC_CONNECTING)
	{
		buffer_send_status (ctx, s->buffer, "Connecting aborted");
		irc_destroy_connector (s);
	}
	else if (!irc_is_connected (s))
		buffer_send_error (ctx, s->buffer, "Not connected");
	else
		irc_initiate_disconnect (s, *a->arguments ? a->arguments : NULL);
	return true;
}

static bool
handle_command_names (struct app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	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 app_context *ctx, 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
		buffer_send_error (ctx, a->buffer,
			"%s: %s", "Can't request info",
			"no target given and this buffer is not a PM nor a server");
	return true;
}

static bool
handle_command_whowas (struct app_context *ctx, 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
		buffer_send_error (ctx, a->buffer,
			"%s: %s", "Can't request info",
			"no target given and this buffer is not a PM");
	return true;
}

static bool
handle_command_nick (struct app_context *ctx, struct handler_args *a)
{
	(void) ctx;

	if (!*a->arguments)
		return false;

	irc_send (a->s, "NICK %s", cut_word (&a->arguments));
	return true;
}

static bool
handle_command_quote (struct app_context *ctx, struct handler_args *a)
{
	(void) ctx;
	irc_send (a->s, "%s", a->arguments);
	return true;
}

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

static bool
handle_command_channel_mode
	(struct handler_args *a, bool adding, char mode_char)
{
	if (!*a->arguments)
		return false;

	struct str_vector v;
	str_vector_init (&v);
	split_str_ignore_empty (a->arguments, ' ', &v);
	mass_channel_mode (a->s, a->channel_name, adding, mode_char, &v);
	str_vector_free (&v);
	return true;
}

#define CHANMODE_HANDLER(name, adding, mode_char)                              \
	static bool                                                                \
	handle_command_ ## name (struct app_context *ctx, struct handler_args *a)  \
	{                                                                          \
		(void) ctx;                                                            \
		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 app_context *ctx, struct handler_args *a)  \
	{                                                                          \
		(void) ctx;                                                            \
		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 (stats, "STATS")
TRIVIAL_HANDLER (away,  "AWAY")

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

static bool handle_command_help (struct app_context *, struct handler_args *);

static struct command_handler
{
	const char *name;
	const char *description;
	const char *usage;
	bool (*handler) (struct app_context *ctx, 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> | close [<N> | <name>]",
	  handle_command_buffer,     0 },
	{ "set",        "Manage configuration",
	  "[<option>]",
	  handle_command_set,        0 },
	{ "save",       "Save configuration",
	  NULL,
	  handle_command_save,       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 },
	{ "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 },

	{ "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 },
	{ "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;

	struct config_schema *schema = item->schema;
	if (!schema)
	{
		buffer_send_error (ctx, NULL, "%s: %s", "Option not recognized", name);
		return true;
	}

	buffer_send_status (ctx, NULL, "%s", "");
	buffer_send_status (ctx, NULL,
		"Option \"%s\":", name);
	buffer_send_status (ctx, NULL,
		"  Description: %s", schema->comment);
	buffer_send_status (ctx, NULL,
		"  Type: %s", config_item_type_name (schema->type));
	buffer_send_status (ctx, NULL,
		"  Default: %s", schema->default_ ? schema->default_ : "null");

	struct str tmp;
	str_init (&tmp);
	config_item_write (item, false, &tmp);
	buffer_send_status (ctx, NULL,
		"  Current value: %s", tmp.str);
	str_free (&tmp);
	return true;
}

static bool
handle_command_help (struct app_context *ctx, struct handler_args *a)
{
	if (!*a->arguments)
	{
		buffer_send_status (ctx, NULL, "%s", "");
		buffer_send_status (ctx, NULL, "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];
			buffer_send_status (ctx, NULL,
				"  %-*s  %s", longest, handler->name, handler->description);
		}
		return true;
	}

	char *command = cut_word (&a->arguments);
	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))
			continue;

		buffer_send_status (ctx, NULL, "%s", "");
		buffer_send_status (ctx, NULL, "%s: %s",
			handler->name, handler->description);
		buffer_send_status (ctx, NULL, "  Arguments: %s",
			handler->usage ? handler->usage : "(none)");
		return true;
	}

	if (!try_handle_command_help_option (ctx, command))
		buffer_send_error (ctx, NULL,
			"%s: %s", "No such command or option", command);
	return true;
}

static int
command_handler_cmp_by_length (const void *a, const void *b)
{
	const struct command_handler *first  = a;
	const struct command_handler *second = b;
	return strlen (first->name) - strlen (second->name);
}

static void
init_partial_matching_user_command_map (struct str_map *partial)
{
	// Trivially create a partial matching map
	str_map_init (partial);
	partial->key_xfrm = tolower_ascii_strxfrm;

	// We process them from the longest to the shortest one,
	// so that common prefixes favor shorter entries
	struct command_handler *by_length[N_ELEMENTS (g_command_handlers)];
	for (size_t i = 0; i < N_ELEMENTS (by_length); i++)
		by_length[i] = &g_command_handlers[i];
	qsort (by_length, N_ELEMENTS (by_length), sizeof *by_length,
		command_handler_cmp_by_length);

	for (size_t i = N_ELEMENTS (by_length); i--; )
	{
		char *copy = xstrdup (by_length[i]->name);
		for (size_t part = strlen (copy); part; part--)
		{
			copy[part] = '\0';
			str_map_set (partial, copy, by_length[i]);
		}
		free (copy);
	}
}

static void
process_user_command (struct app_context *ctx, char *input)
{
	static bool initialized = false;
	static struct str_map partial;
	if (!initialized)
	{
		init_partial_matching_user_command_map (&partial);
		initialized = true;
	}

	char *command_name = cut_word (&input);
	if (try_handle_buffer_goto (ctx, command_name))
		return;

	struct handler_args args =
	{
		.buffer = ctx->current_buffer,
		.arguments = input,
	};

	struct command_handler *handler = str_map_find (&partial, command_name);
	if (!handler)
		buffer_send_error (ctx, NULL,
			"%s: %s", "No such command", command_name);
	else if ((handler->flags & HANDLER_SERVER)
		&& args.buffer->type == BUFFER_GLOBAL)
		buffer_send_error (ctx, NULL,
			"/%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)))
		buffer_send_error (ctx, args.s->buffer, "Not connected");
	else if ((handler->flags & HANDLER_NEEDS_REG)
		&& args.s->state != IRC_REGISTERED)
		buffer_send_error (ctx, 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))))
		buffer_send_error (ctx, args.buffer, "/%s: %s", command_name,
			"no channel name given and this buffer is not a channel");
	else if (!handler->handler (ctx, &args))
		buffer_send_error (ctx, NULL,
			"%s: /%s %s", "Usage", handler->name, handler->usage);
}

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

static void
send_message_to_target (struct server *s,
	const char *target, char *message, struct buffer *buffer)
{
	if (!irc_is_connected (s))
	{
		buffer_send_error (s->ctx, buffer, "Not connected");
		return;
	}

	SEND_AUTOSPLIT_PRIVMSG (s, target, message);
}

static void
send_message_to_current_buffer (struct app_context *ctx, char *message)
{
	struct buffer *buffer = ctx->current_buffer;
	hard_assert (buffer != NULL);

	switch (buffer->type)
	{
	case BUFFER_GLOBAL:
	case BUFFER_SERVER:
		buffer_send_error (ctx, buffer, "This buffer is not a channel");
		break;
	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;
	}
}

static void
process_input (struct app_context *ctx, char *user_input)
{
	char *input;
	size_t len;

	if (!(input = iconv_xstrdup (ctx->term_to_utf8, user_input, -1, &len)))
		print_error ("character conversion failed for `%s'", "user input");
	else if (input[0] != '/')
		send_message_to_current_buffer (ctx, input);
	else if (input[1] == '/')
		send_message_to_current_buffer (ctx, input + 1);
	else
		process_user_command (ctx, input + 1);

	free (input);
}

// --- 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.

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
};

static void
completion_init (struct completion *self)
{
	memset (self, 0, sizeof *self);
}

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 void
completion_parse (struct completion *self, const char *line, size_t len)
{
	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;
	}
}

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 bool
completion_matches (struct completion *self, int word, const char *pattern)
{
	hard_assert (word >= 0 && word < (int) self->words_len);
	char *text = xstrndup (self->line + self->words[word].start,
		self->words[word].end - self->words[word].start);
	bool result = !fnmatch (pattern, text, 0);
	free (text);
	return result;
}

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

// 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 || !vector[0])
		return 0;

	struct utf8_iter a[len];
	for (size_t i = 0; i < len; i++)
		utf8_iter_init (&a[i], vector[i]);

	size_t ch_len;
	int32_t ch;
	while ((ch = utf8_iter_next (&a[0], &ch_len)) != -1)
	{
		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 str_vector *output)
{
	(void) ctx;
	(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))
			str_vector_add_owned (output,
				xstrdup_printf ("%s%s", prefix, handler->name));
	}
}

static void
complete_option (struct app_context *ctx, struct completion *data,
	const char *word, struct str_vector *output)
{
	(void) data;

	struct str_vector options;
	str_vector_init (&options);

	config_dump (ctx->config.root, &options);
	str_vector_sort (&options);

	// Wildcard expansion is an interesting side-effect
	char *mask = xstrdup_printf ("%s*", word);
	for (size_t i = 0; i < options.len; i++)
	{
		const char *line = options.vector[i];
		char *key = xstrndup (line, strcspn (line, " "));
		if (!fnmatch (mask, key, 0))
			str_vector_add_owned (output, key);
		else
			free (key);
	}
	free (mask);
	str_vector_free (&options);
}

static void
complete_nicknames (struct app_context *ctx, struct completion *data,
	const char *word, struct str_vector *output)
{
	struct buffer *buffer = ctx->current_buffer;
	if (buffer->type != BUFFER_CHANNEL)
		return;

	size_t word_len = strlen (word);
	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;
		str_vector_add_owned (output, data->location == 0
			? xstrdup_printf ("%s:", nickname)
			: xstrdup (nickname));
	}
}

static char **
complete_word (struct app_context *ctx, struct completion *data,
	const char *word)
{
	// First figure out what exactly do we need to complete
	bool try_commands = false;
	bool try_options = false;
	bool try_nicknames = false;

	if (data->location == 0 && completion_matches (data, 0, "/*"))
		try_commands = true;
	else if (data->location == 1 && completion_matches (data, 0, "/set"))
		try_options = true;
	else if (data->location == 1 && completion_matches (data, 0, "/help"))
		try_commands = try_options = true;
	else
		try_nicknames = true;

	struct str_vector words;
	str_vector_init (&words);

	// Add placeholder
	str_vector_add_owned (&words, NULL);

	if (try_commands)   complete_command (ctx, data, word, &words);
	if (try_options)    complete_option (ctx, data, word, &words);
	if (try_nicknames)  complete_nicknames (ctx, data, word, &words);

	if (words.len == 1)
	{
		// Nothing matched
		str_vector_free (&words);
		return NULL;
	}

	if (words.len == 2)
	{
		words.vector[0] = words.vector[1];
		words.vector[1] = NULL;
	}
	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.vector;
}

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

/// 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)
{
	struct str utf8;  str_init (&utf8);
	mbstate_t state;  memset (&state, 0, sizeof state);

	size_t remaining = strlen (locale) + 1;
	const char *p = locale;

	// Reset the shift state, FWIW
	(void) iconv (ctx->term_to_utf8, NULL, NULL, NULL, NULL);

	bool fixed[n_indexes];
	memset (fixed, 0, sizeof fixed);

	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 void
utf8_vector_to_locale (struct app_context *ctx, char **vector)
{
	for (; *vector; vector++)
	{
		char *converted = iconv_xstrdup
			(ctx->term_from_utf8, *vector, -1, NULL);
		if (!soft_assert (converted))
			converted = xstrdup ("");

		free (*vector);
		*vector = converted;
	}
}

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

/// 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_completions (struct app_context *ctx, 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 completion c;
	completion_init (&c);
	completion_parse (&c, line, strlen (line));
	completion_locate (&c, start);
	char *word = xstrndup (line + start, end - start);
	char **completions = complete_word (ctx, &c, word);
	free (word);
	completion_free (&c);

	if (completions)
		utf8_vector_to_locale (ctx, completions);

	free (line_utf8);
	return completions;
}

// --- Common code for user actions --------------------------------------------

static bool
redraw_screen (struct app_context *ctx)
{
	if (!soft_assert (clear_screen != NULL))
		return false;

	input_hide (&ctx->input);

	terminal_printer_fn printer = get_attribute_printer (stdout);
	tputs (clear_screen, 1, printer);
	fflush (stdout);
	buffer_print_backlog (ctx, ctx->current_buffer);

	input_show (&ctx->input);
	return true;
}

static bool
jump_to_buffer (struct app_context *ctx, int n)
{
	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)
		// Fast switching between two buffers
		buffer_activate (ctx, ctx->last_buffer);
	else if (!buffer_goto (ctx, n))
		return false;
	return true;
}

static void
await_mirc_escape (struct app_context *ctx)
{
	ctx->awaiting_mirc_escape = true;
	ctx->char_buf_len = 0;
}

static void
bind_common_keys (struct app_context *ctx)
{
	struct input *self = &ctx->input;
	input_bind_control (self, 'p', "previous-buffer");
	input_bind_control (self, 'n', "next-buffer");

	// Redefine M-0 through M-9 to switch buffers
	for (int i = 0; i <= 9; i++)
		input_bind_meta (self, '0' + i, "goto-buffer");

	input_bind_meta (self, 'm', "insert-attribute");

	if (key_f5)
		input_bind (self, key_f5, "previous-buffer");
	if (key_f6)
		input_bind (self, key_f6, "next-buffer");

	if (clear_screen)
		input_bind_control (self, 'l', "redraw-screen");
}

// --- GNU Readline user actions -----------------------------------------------

#ifdef HAVE_READLINE

static int
on_readline_goto_buffer (int count, int key)
{
	(void) count;

	struct app_context *ctx = g_ctx;
	if (!jump_to_buffer (ctx, UNMETA (key) - '0'))
		input_ding (&ctx->input);
	return 0;
}

static int
on_readline_previous_buffer (int count, int key)
{
	(void) key;

	struct app_context *ctx = g_ctx;
	buffer_activate (ctx, buffer_previous (ctx, count));
	return 0;
}

static int
on_readline_next_buffer (int count, int key)
{
	(void) key;

	struct app_context *ctx = g_ctx;
	buffer_activate (ctx, buffer_next (ctx, count));
	return 0;
}

static int
on_readline_redraw_screen (int count, int key)
{
	(void) count;
	(void) key;

	struct app_context *ctx = g_ctx;
	if (!redraw_screen (ctx))
		input_ding (&ctx->input);
	return 0;
}

static int
on_readline_insert_attribute (int count, int key)
{
	(void) count;
	(void) key;

	struct app_context *ctx = g_ctx;
	await_mirc_escape (ctx);
	return 0;
}

static int
on_readline_return (int count, int key)
{
	(void) count;
	(void) key;

	struct app_context *ctx = g_ctx;

	// Let readline pass the line to our input handler
	rl_done = 1;

	// Hide the line, don't redisplay it
	input_hide (&ctx->input);
	input_restore (&ctx->input);
	return 0;
}

static void
on_readline_input (char *line)
{
	struct app_context *ctx = g_ctx;

	if (line)
	{
		if (*line)
			add_history (line);

		// The text is deleted _afterwards_
		rl_delete_text (0, rl_end);
		process_input (ctx, line);
		free (line);
	}
	else
	{
		input_hide (&ctx->input);
		input_restore (&ctx->input);
		input_ding (&ctx->input);
	}

	if (ctx->input.active)
		// Readline automatically redisplays it
		ctx->input.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_completions (g_ctx, rl_line_buffer, start, end);
}

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

	rl_add_defun ("previous-buffer",  on_readline_previous_buffer,  -1);
	rl_add_defun ("next-buffer",      on_readline_next_buffer,      -1);
	rl_add_defun ("goto-buffer",      on_readline_goto_buffer,      -1);
	rl_add_defun ("redraw-screen",    on_readline_redraw_screen,    -1);
	rl_add_defun ("insert-attribute", on_readline_insert_attribute, -1);
	rl_add_defun ("send-line",        on_readline_return,           -1);

	bind_common_keys (ctx);

	// Move native history commands
	input_bind_meta (self, 'p', "previous-history");
	input_bind_meta (self, 'n', "next-history");

	// We need to hide the prompt and input first
	rl_bind_key (RETURN, rl_named_function ("send-line"));

	rl_variable_bind ("completion-ignore-case", "on");
	rl_bind_key (TAB, rl_named_function ("menu-complete"));
	if (key_btab)
		input_bind (self, key_btab, "menu-complete-backward");
	return 0;
}

#endif // HAVE_READLINE

// --- BSD Editline user actions -----------------------------------------------

#ifdef HAVE_EDITLINE

static unsigned char
on_editline_goto_buffer (EditLine *editline, int key)
{
	(void) editline;

	struct app_context *ctx = g_ctx;
	if (!jump_to_buffer (ctx, key - '0'))
		return CC_ERROR;
	return CC_NORM;
}

static unsigned char
on_editline_previous_buffer (EditLine *editline, int key)
{
	(void) editline;
	(void) key;

	struct app_context *ctx = g_ctx;
	buffer_activate (ctx, buffer_previous (ctx, 1));
	return CC_NORM;
}

static unsigned char
on_editline_next_buffer (EditLine *editline, int key)
{
	(void) editline;
	(void) key;

	struct app_context *ctx = g_ctx;
	buffer_activate (ctx, buffer_next (ctx, 1));
	return CC_NORM;
}

static unsigned char
on_editline_redraw_screen (EditLine *editline, int key)
{
	(void) editline;
	(void) key;

	if (!redraw_screen (g_ctx))
		return CC_ERROR;
	return CC_NORM;
}

static unsigned char
on_editline_insert_attribute (EditLine *editline, int key)
{
	(void) editline;
	(void) key;

	await_mirc_escape (g_ctx);
	return CC_NORM;
}

static unsigned char
on_editline_complete (EditLine *editline, int key)
{
	(void) key;
	(void) editline;

	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_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]);
	bool only_match = !completions[1];
	for (char **p = completions; *p; p++)
		free (*p);
	free (completions);

	// I'm not sure if Readline's menu-complete can at all be implemented
	// with Editline.  Spamming the terminal with possible completions
	// probably isn't what the user wants and we have no way of detecting
	// what the last executed handler was.
	if (!only_match)
		return CC_REFRESH_BEEP;

	// But 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;

	const LineInfoW *info = el_wline (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);

	// XXX: Editline seems to remember its position in history,
	//   so it's not going to work as you'd expect it to
	if (*line)
	{
		HistEventW ev;
		history_w (ctx->input.current->history, &ev, H_ENTER, line);
		print_debug ("history: %d %ls", ev.num, ev.str);
	}
	free (line);

	// process_input() expects a multibyte string
	const LineInfo *info_mb = el_line (editline);
	char copy[info_mb->lastchar - info_mb->buffer + 1];
	memcpy (copy, info_mb->buffer, sizeof copy - 1);
	copy[sizeof copy - 1] = '\0';
	process_input (ctx, copy);

	el_cursor (editline, len - point);
	el_wdeletestr (editline, len);
	return CC_REFRESH;
}

static void
app_editline_init (struct input *self)
{
	static const struct { const char *name; const char *help;
		unsigned char (*func) (EditLine *, int); } x[] =
	{
		{ "goto-buffer",      "Go to buffer",    on_editline_goto_buffer      },
		{ "previous-buffer",  "Previous buffer", on_editline_previous_buffer  },
		{ "next-buffer",      "Next buffer",     on_editline_next_buffer      },
		{ "redraw-screen",    "Redraw screen",   on_editline_redraw_screen    },
		{ "insert-attribute", "mIRC formatting", on_editline_insert_attribute },
		{ "send-line",        "Send line",       on_editline_return           },
		{ "complete",         "Complete word",   on_editline_complete         },
	};
	for (size_t i = 0; i < N_ELEMENTS (x); i++)
		el_set (self->editline, EL_ADDFN, x[i].name, x[i].help, x[i].func);

	bind_common_keys (g_ctx);

	// Move native history commands
	input_bind_meta (self, 'p', "ed-prev-history");
	input_bind_meta (self, 'n', "ed-next-history");

	// No, editline, it's not supposed to kill the entire line
	input_bind_control (self, 'w', "ed-delete-prev-word");
	// Just what are you doing?
	input_bind_control (self, 'u', "vi-kill-line-prev");

	// We need to hide the prompt and input first
	input_bind (self, "\n", "send-line");

	input_bind_control (self, 'i', "complete");

	// Source the user's defaults file
	el_source (self->editline, NULL);
}

#endif // HAVE_EDITLINE

// --- Configuration loading ---------------------------------------------------

static bool
read_file (const char *filename, struct str *output, struct error **e)
{
	FILE *fp = fopen (filename, "rb");
	if (!fp)
	{
		error_set (e, "could not open `%s' for reading: %s",
			filename, strerror (errno));
		return false;
	}

	char buf[BUFSIZ];
	size_t len;

	while ((len = fread (buf, 1, sizeof buf, fp)) == sizeof buf)
		str_append_data (output, buf, len);
	str_append_data (output, buf, len);

	bool success = !ferror (fp);
	fclose (fp);

	if (success)
		return true;

	error_set (e, "error while reading `%s': %s",
		filename, strerror (errno));
	return false;
}

static struct config_item_ *
load_configuration_file (const char *filename, struct error **e)
{
	struct config_item_ *root = NULL;

	struct str data;
	str_init (&data);
	if (!read_file (filename, &data, e))
		goto end;

	struct error *error = NULL;
	if (!(root = config_item_parse (data.str, data.len, false, &error)))
	{
		error_set (e, "configuration parse error: %s", error->message);
		error_free (error);
	}
end:
	str_free (&data);
	return root;
}

static void
load_configuration (struct app_context *ctx)
{
	struct config_item_ *root = NULL;
	struct error *e = NULL;

	char *filename = resolve_config_filename (PROGRAM_NAME ".conf");
	if (filename)
		root = load_configuration_file (filename, &e);
	else
		print_status ("configuration file not found");
	free (filename);

	if (e)
	{
		print_error ("%s", e->message);
		error_free (e);
		e = NULL;
	}

	config_load (&ctx->config, root ? root : config_item_object ());

	ctx->isolate_buffers =
		get_config_boolean (ctx->config.root, "behaviour.isolate_buffers");
}

// --- 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
sigterm_handler (int signum)
{
	(void) signum;

	g_termination_requested = true;

	int original_errno = errno;
	if (write (g_signal_pipe[1], "t", 1) == -1)
		soft_assert (errno == EAGAIN);
	errno = original_errno;
}

static void
sigwinch_handler (int signum)
{
	(void) signum;

	g_winch_received = true;

	int original_errno = errno;
	if (write (g_signal_pipe[1], "w", 1) == -1)
		soft_assert (errno == EAGAIN);
	errno = original_errno;
}

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);

	struct sigaction sa;
	sa.sa_flags = SA_RESTART;
	sa.sa_handler = sigwinch_handler;
	sigemptyset (&sa.sa_mask);

	if (sigaction (SIGWINCH, &sa, NULL) == -1)
		exit_fatal ("sigaction: %s", strerror (errno));

	sa.sa_handler = sigterm_handler;
	if (sigaction (SIGINT, &sa, NULL) == -1
	 || sigaction (SIGTERM, &sa, NULL) == -1)
		exit_fatal ("sigaction: %s", strerror (errno));
}

// --- I/O event handlers ------------------------------------------------------

static void
on_signal_pipe_readable (const struct pollfd *fd, struct app_context *ctx)
{
	char dummy;
	(void) read (fd->fd, &dummy, 1);

	if (g_termination_requested && !ctx->quitting)
		// TODO: this way we don't send a QUIT message but just close the
		//   connection from our side and wait for a full close.
		//   Once we allow for custom quit messages, we will probably want to
		//   call irc_initiate_disconnect() for all servers.
		initiate_quit (ctx);

	if (g_winch_received)
	{
		if (ctx->input.active)
			input_on_terminal_resized (&ctx->input);

		update_screen_size ();
		g_winch_received = false;
	}
}

static void
process_mirc_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
	if (read (fd->fd, ctx->char_buf + ctx->char_buf_len, 1) != 1)
		goto error;

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

	size_t len = mbrlen (ctx->char_buf, ++ctx->char_buf_len, &state);

	// Illegal sequence
	if (len == (size_t) -1)
		goto error;

	// Incomplete multibyte character
	if (len == (size_t) -2)
		return;

	if (ctx->char_buf_len != 1)
		goto error;
	switch (ctx->char_buf[0])
	{
	case 'b': input_insert_c (&ctx->input, '\x02'); break;
	case 'c': input_insert_c (&ctx->input, '\x03'); break;
	case 'i':
	case ']': input_insert_c (&ctx->input, '\x1d'); break;
	case 'u':
	case '_': input_insert_c (&ctx->input, '\x1f'); break;
	case 'v': input_insert_c (&ctx->input, '\x16'); break;
	case 'o': input_insert_c (&ctx->input, '\x0f'); break;

	default:
		goto error;
	}
	goto done;

error:
	input_ding (&ctx->input);
done:
	ctx->awaiting_mirc_escape = false;
}

static void
on_tty_readable (const struct pollfd *fd, struct app_context *ctx)
{
	(void) ctx;

	if (fd->revents & ~(POLLIN | POLLHUP | POLLERR))
		print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents);

	if (ctx->awaiting_mirc_escape)
	{
		process_mirc_escape (fd, ctx);
		return;
	}

	// XXX: this may loop for a bit: stop the event or eat the input?
	//   (This prevents a segfault when the input has been stopped.)
	if (ctx->input.active)
		input_on_readable (&ctx->input);
}

static void
init_poller_events (struct app_context *ctx)
{
	poller_fd_init (&ctx->signal_event, &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);

	poller_fd_init (&ctx->tty_event, &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);
}

// --- Main program ------------------------------------------------------------

static void
display_logo (void)
{
	const char *logo =
		"       __                                __   \n"
		"    __/ / ____  ____  ____  ____  ____  / /_  \n"
		"   /   / / , / /   / / , / / __/ / __/ / __ \\ \n"
		"  / / / / __/ / / / / __/ /_  / / /_  / / / / \n"
		" /___/ /___/ /_  / /___/ /___/ /___/ /_/ /_/  \n"
		"            /___/                             \n"
		"                   ";

	struct str_vector v;
	str_vector_init (&v);
	char *x = xstrdup_printf ("%s%s",
		logo, PROGRAM_NAME " " PROGRAM_VERSION " starting");
	split_str (x, '\n', &v);
	free (x);

	for (size_t i = 0; i < v.len; i++)
		print_status ("%s", v.vector[i]);
	str_vector_free (&v);
}

static void
create_server (struct app_context *ctx)
{
	struct server *s = xmalloc (sizeof *s);
	server_init (s, &ctx->poller);

	s->ctx = ctx;
	s->name = xstrdup ("server");
	str_map_set (&ctx->servers, s->name, s);

	// Load configuration
	s->config = config_item_get (ctx->config.root, "server", NULL);
	hard_assert (s->config != NULL);

	struct error *e = NULL;
	if (!irc_autofill_user_info (s, &e))
	{
		print_error ("%s: %s", "failed to fill in user details", e->message);
		error_free (e);
	}

	// Add a buffer and activate it
	struct buffer *buffer = s->buffer = buffer_new ();
	buffer->type = BUFFER_SERVER;
	buffer->name = xstrdup (s->name);
	buffer->server = s;

	buffer_add (ctx, buffer);
	buffer_activate (ctx, buffer);

	// Connect to the server ASAP
	poller_timer_set (&s->reconnect_tmr, 0);
}

int
main (int argc, char *argv[])
{
	// We include a generated file from kike 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[] =
	{
		{ 'd', "debug", NULL, 0, "run in debug mode" },
		{ 'h', "help", NULL, 0, "display this help and exit" },
		{ 'V', "version", NULL, 0, "output version information and exit" },
		{ 0, NULL, NULL, 0, NULL }
	};

	struct opt_handler oh;
	opt_handler_init (&oh, argc, argv, opts, NULL, "Experimental IRC client.");

	int c;
	while ((c = opt_handler_get (&oh)) != -1)
	switch (c)
	{
	case 'd':
		g_debug_mode = true;
		break;
	case 'h':
		opt_handler_usage (&oh, stdout);
		exit (EXIT_SUCCESS);
	case 'V':
		printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
		exit (EXIT_SUCCESS);
	default:
		print_error ("wrong options");
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}

	opt_handler_free (&oh);
	display_logo ();

	// 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;

	SSL_library_init ();
	atexit (EVP_cleanup);
	SSL_load_error_strings ();
	atexit (ERR_free_strings);

	setup_signal_handlers ();
	register_config_modules (&ctx);
	load_configuration (&ctx);

	init_colors (&ctx);
	init_poller_events (&ctx);
	init_buffers (&ctx);

	refresh_prompt (&ctx);
	input_start (&ctx.input, argv[0]);

	// TODO: finish multi-server
	create_server (&ctx);

	ctx.polling = true;
	while (ctx.polling)
		poller_run (&ctx.poller);

	app_context_free (&ctx);
	free_terminal ();
	return EXIT_SUCCESS;
}