summary refs log tree commit diff stats
path: root/compiler/ccgexprs.nim
blob: b03f7c5aa1fea57eddc445c2a13945382cd89c79 (plain) (blame)
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
#
#
#           The Nim Compiler
#        (c) Copyright 2013 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# included from cgen.nim

# -------------------------- constant expressions ------------------------

proc int64Literal(i: BiggestInt): Rope =
  if i > low(int64):
    result = rfmt(nil, "IL64($1)", rope(i))
  else:
    result = ~"(IL64(-9223372036854775807) - IL64(1))"

proc uint64Literal(i: uint64): Rope = rope($i & "ULL")

proc intLiteral(i: BiggestInt): Rope =
  if i > low(int32) and i <= high(int32):
    result = rope(i)
  elif i == low(int32):
    # Nim has the same bug for the same reasons :-)
    result = ~"(-2147483647 -1)"
  elif i > low(int64):
    result = rfmt(nil, "IL64($1)", rope(i))
  else:
    result = ~"(IL64(-9223372036854775807) - IL64(1))"

proc getStrLit(m: BModule, s: string): Rope =
  discard cgsym(m, "TGenericSeq")
  result = getTempName(m)
  addf(m.s[cfsData], "STRING_LITERAL($1, $2, $3);$n",
       [result, makeCString(s), rope(len(s))])

proc genLiteral(p: BProc, n: PNode, ty: PType): Rope =
  if ty == nil: internalError(n.info, "genLiteral: ty is nil")
  case n.kind
  of nkCharLit..nkUInt64Lit:
    case skipTypes(ty, abstractVarRange).kind
    of tyChar, tyNil:
      result = intLiteral(n.intVal)
    of tyBool:
      if n.intVal != 0: result = ~"NIM_TRUE"
      else: result = ~"NIM_FALSE"
    of tyInt64: result = int64Literal(n.intVal)
    of tyUInt64: result = uint64Literal(uint64(n.intVal))
    else:
      result = "(($1) $2)" % [getTypeDesc(p.module,
          ty), intLiteral(n.intVal)]
  of nkNilLit:
    let t = skipTypes(ty, abstractVarRange)
    if t.kind == tyProc and t.callConv == ccClosure:
      let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
      result = p.module.tmpBase & rope(id)
      if id == p.module.labels:
        # not found in cache:
        inc(p.module.labels)
        addf(p.module.s[cfsData],
             "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n",
             [getTypeDesc(p.module, ty), result])
    else:
      result = rope("NIM_NIL")
  of nkStrLit..nkTripleStrLit:
    if n.strVal.isNil:
      result = ropecg(p.module, "((#NimStringDesc*) NIM_NIL)", [])
    elif skipTypes(ty, abstractVarRange).kind == tyString:
      let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
      if id == p.module.labels:
        # string literal not found in the cache:
        result = ropecg(p.module, "((#NimStringDesc*) &$1)",
                        [getStrLit(p.module, n.strVal)])
      else:
        result = ropecg(p.module, "((#NimStringDesc*) &$1$2)",
                        [p.module.tmpBase, rope(id)])
    else:
      result = makeCString(n.strVal)
  of nkFloatLit..nkFloat64Lit:
    result = rope(n.floatVal.toStrMaxPrecision)
  else:
    internalError(n.info, "genLiteral(" & $n.kind & ')')
    result = nil

proc genLiteral(p: BProc, n: PNode): Rope =
  result = genLiteral(p, n, n.typ)

proc bitSetToWord(s: TBitSet, size: int): BiggestInt =
  result = 0
  when true:
    for j in countup(0, size - 1):
      if j < len(s): result = result or `shl`(ze64(s[j]), j * 8)
  else:
    # not needed, too complex thinking:
    if CPU[platform.hostCPU].endian == CPU[targetCPU].endian:
      for j in countup(0, size - 1):
        if j < len(s): result = result or `shl`(Ze64(s[j]), j * 8)
    else:
      for j in countup(0, size - 1):
        if j < len(s): result = result or `shl`(Ze64(s[j]), (Size - 1 - j) * 8)

proc genRawSetData(cs: TBitSet, size: int): Rope =
  var frmt: FormatStr
  if size > 8:
    result = "{$n" % []
    for i in countup(0, size - 1):
      if i < size - 1:
        # not last iteration?
        if (i + 1) mod 8 == 0: frmt = "0x$1,$n"
        else: frmt = "0x$1, "
      else:
        frmt = "0x$1}$n"
      addf(result, frmt, [rope(toHex(ze64(cs[i]), 2))])
  else:
    result = intLiteral(bitSetToWord(cs, size))
    #  result := rope('0x' + ToHex(bitSetToWord(cs, size), size * 2))

proc genSetNode(p: BProc, n: PNode): Rope =
  var cs: TBitSet
  var size = int(getSize(n.typ))
  toBitSet(n, cs)
  if size > 8:
    let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
    result = p.module.tmpBase & rope(id)
    if id == p.module.labels:
      # not found in cache:
      inc(p.module.labels)
      addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
           [getTypeDesc(p.module, n.typ), result, genRawSetData(cs, size)])
  else:
    result = genRawSetData(cs, size)

proc getStorageLoc(n: PNode): TStorageLoc =
  case n.kind
  of nkSym:
    case n.sym.kind
    of skParam, skTemp:
      result = OnStack
    of skVar, skForVar, skResult, skLet:
      if sfGlobal in n.sym.flags: result = OnHeap
      else: result = OnStack
    of skConst:
      if sfGlobal in n.sym.flags: result = OnHeap
      else: result = OnUnknown
    else: result = OnUnknown
  of nkDerefExpr, nkHiddenDeref:
    case n.sons[0].typ.kind
    of tyVar: result = OnUnknown
    of tyPtr: result = OnStack
    of tyRef: result = OnHeap
    else: internalError(n.info, "getStorageLoc")
  of nkBracketExpr, nkDotExpr, nkObjDownConv, nkObjUpConv:
    result = getStorageLoc(n.sons[0])
  else: result = OnUnknown

proc genRefAssign(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  if dest.s == OnStack or not usesNativeGC():
    linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  elif dest.s == OnHeap:
    # location is on heap
    # now the writer barrier is inlined for performance:
    #
    #    if afSrcIsNotNil in flags:
    #      UseMagic(p.module, 'nimGCref')
    #      lineF(p, cpsStmts, 'nimGCref($1);$n', [rdLoc(src)])
    #    elif afSrcIsNil notin flags:
    #      UseMagic(p.module, 'nimGCref')
    #      lineF(p, cpsStmts, 'if ($1) nimGCref($1);$n', [rdLoc(src)])
    #    if afDestIsNotNil in flags:
    #      UseMagic(p.module, 'nimGCunref')
    #      lineF(p, cpsStmts, 'nimGCunref($1);$n', [rdLoc(dest)])
    #    elif afDestIsNil notin flags:
    #      UseMagic(p.module, 'nimGCunref')
    #      lineF(p, cpsStmts, 'if ($1) nimGCunref($1);$n', [rdLoc(dest)])
    #    lineF(p, cpsStmts, '$1 = $2;$n', [rdLoc(dest), rdLoc(src)])
    if canFormAcycle(dest.t):
      linefmt(p, cpsStmts, "#asgnRef((void**) $1, $2);$n",
              addrLoc(dest), rdLoc(src))
    else:
      linefmt(p, cpsStmts, "#asgnRefNoCycle((void**) $1, $2);$n",
              addrLoc(dest), rdLoc(src))
  else:
    linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
            addrLoc(dest), rdLoc(src))

proc asgnComplexity(n: PNode): int =
  if n != nil:
    case n.kind
    of nkSym: result = 1
    of nkRecCase:
      # 'case objects' are too difficult to inline their assignment operation:
      result = 100
    of nkRecList:
      for t in items(n):
        result += asgnComplexity(t)
    else: discard

proc optAsgnLoc(a: TLoc, t: PType, field: Rope): TLoc =
  assert field != nil
  result.k = locField
  result.s = a.s
  result.t = t
  result.r = rdLoc(a) & "." & field

proc genOptAsgnTuple(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  let newflags =
    if src.s == OnStatic:
      flags + {needToCopy}
    elif tfShallow in dest.t.flags:
      flags - {needToCopy}
    else:
      flags
  let t = skipTypes(dest.t, abstractInst).getUniqueType()
  for i in 0 .. <t.len:
    let t = t.sons[i]
    let field = "Field$1" % [i.rope]
    genAssignment(p, optAsgnLoc(dest, t, field),
                     optAsgnLoc(src, t, field), newflags)

proc genOptAsgnObject(p: BProc, dest, src: TLoc, flags: TAssignmentFlags,
                      t: PNode, typ: PType) =
  if t == nil: return
  let newflags =
    if src.s == OnStatic:
      flags + {needToCopy}
    elif tfShallow in dest.t.flags:
      flags - {needToCopy}
    else:
      flags
  case t.kind
  of nkSym:
    let field = t.sym
    if field.loc.r == nil: fillObjectFields(p.module, typ)
    genAssignment(p, optAsgnLoc(dest, field.typ, field.loc.r),
                     optAsgnLoc(src, field.typ, field.loc.r), newflags)
  of nkRecList:
    for child in items(t): genOptAsgnObject(p, dest, src, newflags, child, typ)
  else: discard

proc genGenericAsgn(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  # Consider:
  # type TMyFastString {.shallow.} = string
  # Due to the implementation of pragmas this would end up to set the
  # tfShallow flag for the built-in string type too! So we check only
  # here for this flag, where it is reasonably safe to do so
  # (for objects, etc.):
  if needToCopy notin flags or
      tfShallow in skipTypes(dest.t, abstractVarRange).flags:
    if dest.s == OnStack or not usesNativeGC():
      useStringh(p.module)
      linefmt(p, cpsStmts,
           "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
           addrLoc(dest), addrLoc(src), rdLoc(dest))
    else:
      linefmt(p, cpsStmts, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n",
              addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
  else:
    linefmt(p, cpsStmts, "#genericAssign((void*)$1, (void*)$2, $3);$n",
            addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))

proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  # This function replaces all other methods for generating
  # the assignment operation in C.
  if src.t != nil and src.t.kind == tyPtr:
    # little HACK to support the new 'var T' as return type:
    linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
    return
  let ty = skipTypes(dest.t, abstractRange)
  case ty.kind
  of tyRef:
    genRefAssign(p, dest, src, flags)
  of tySequence:
    if needToCopy notin flags and src.s != OnStatic:
      genRefAssign(p, dest, src, flags)
    else:
      linefmt(p, cpsStmts, "#genericSeqAssign($1, $2, $3);$n",
              addrLoc(dest), rdLoc(src), genTypeInfo(p.module, dest.t))
  of tyString:
    if needToCopy notin flags and src.s != OnStatic:
      genRefAssign(p, dest, src, flags)
    else:
      if dest.s == OnStack or not usesNativeGC():
        linefmt(p, cpsStmts, "$1 = #copyString($2);$n", dest.rdLoc, src.rdLoc)
      elif dest.s == OnHeap:
        # we use a temporary to care for the dreaded self assignment:
        var tmp: TLoc
        getTemp(p, ty, tmp)
        linefmt(p, cpsStmts, "$3 = $1; $1 = #copyStringRC1($2);$n",
                dest.rdLoc, src.rdLoc, tmp.rdLoc)
        linefmt(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", tmp.rdLoc)
      else:
        linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, #copyString($2));$n",
               addrLoc(dest), rdLoc(src))
  of tyProc:
    if needsComplexAssignment(dest.t):
      # optimize closure assignment:
      let a = optAsgnLoc(dest, dest.t, "ClE_0".rope)
      let b = optAsgnLoc(src, dest.t, "ClE_0".rope)
      genRefAssign(p, a, b, flags)
      linefmt(p, cpsStmts, "$1.ClP_0 = $2.ClP_0;$n", rdLoc(dest), rdLoc(src))
    else:
      linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  of tyTuple:
    if needsComplexAssignment(dest.t):
      if dest.t.len <= 4: genOptAsgnTuple(p, dest, src, flags)
      else: genGenericAsgn(p, dest, src, flags)
    else:
      linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  of tyObject:
    # XXX: check for subtyping?
    if ty.isImportedCppType:
      linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
    elif not isObjLackingTypeField(ty):
      genGenericAsgn(p, dest, src, flags)
    elif needsComplexAssignment(ty):
      if ty.sons[0].isNil and asgnComplexity(ty.n) <= 4:
        discard getTypeDesc(p.module, ty)
        internalAssert ty.n != nil
        genOptAsgnObject(p, dest, src, flags, ty.n, ty)
      else:
        genGenericAsgn(p, dest, src, flags)
    else:
      linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  of tyArray:
    if needsComplexAssignment(dest.t):
      genGenericAsgn(p, dest, src, flags)
    else:
      useStringh(p.module)
      linefmt(p, cpsStmts,
           "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
           rdLoc(dest), rdLoc(src), getTypeDesc(p.module, dest.t))
  of tyOpenArray, tyVarargs:
    # open arrays are always on the stack - really? What if a sequence is
    # passed to an open array?
    if needsComplexAssignment(dest.t):
      linefmt(p, cpsStmts,     # XXX: is this correct for arrays?
           "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
           addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
    else:
      useStringh(p.module)
      linefmt(p, cpsStmts,
           "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len_0);$n",
           rdLoc(dest), rdLoc(src))
  of tySet:
    if mapType(ty) == ctArray:
      useStringh(p.module)
      linefmt(p, cpsStmts, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n",
              rdLoc(dest), rdLoc(src), rope(getSize(dest.t)))
    else:
      linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  of tyPtr, tyPointer, tyChar, tyBool, tyEnum, tyCString,
     tyInt..tyUInt64, tyRange, tyVar:
    linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  else: internalError("genAssignment: " & $ty.kind)

  if optMemTracker in p.options and dest.s in {OnHeap, OnUnknown}:
    #writeStackTrace()
    #echo p.currLineInfo, " requesting"
    linefmt(p, cpsStmts, "#memTrackerWrite((void*)$1, $2, $3, $4);$n",
            addrLoc(dest), rope getSize(dest.t),
            makeCString(p.currLineInfo.toFullPath),
            rope p.currLineInfo.safeLineNm)

proc genDeepCopy(p: BProc; dest, src: TLoc) =
  template addrLocOrTemp(a: TLoc): Rope =
    if a.k == locExpr:
      var tmp: TLoc
      getTemp(p, a.t, tmp)
      genAssignment(p, tmp, a, {})
      addrLoc(tmp)
    else:
      addrLoc(a)

  var ty = skipTypes(dest.t, abstractVarRange)
  case ty.kind
  of tyPtr, tyRef, tyProc, tyTuple, tyObject, tyArray:
    # XXX optimize this
    linefmt(p, cpsStmts, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n",
            addrLoc(dest), addrLocOrTemp(src), genTypeInfo(p.module, dest.t))
  of tySequence, tyString:
    linefmt(p, cpsStmts, "#genericSeqDeepCopy($1, $2, $3);$n",
            addrLoc(dest), rdLoc(src), genTypeInfo(p.module, dest.t))
  of tyOpenArray, tyVarargs:
    linefmt(p, cpsStmts,
         "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
         addrLoc(dest), addrLocOrTemp(src), genTypeInfo(p.module, dest.t))
  of tySet:
    if mapType(ty) == ctArray:
      useStringh(p.module)
      linefmt(p, cpsStmts, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n",
              rdLoc(dest), rdLoc(src), rope(getSize(dest.t)))
    else:
      linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  of tyPointer, tyChar, tyBool, tyEnum, tyCString,
     tyInt..tyUInt64, tyRange, tyVar:
    linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  else: internalError("genDeepCopy: " & $ty.kind)

proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc) =
  if d.k != locNone:
    if lfNoDeepCopy in d.flags: genAssignment(p, d, s, {})
    else: genAssignment(p, d, s, {needToCopy})
  else:
    d = s # ``d`` is free, so fill it with ``s``

proc putDataIntoDest(p: BProc, d: var TLoc, t: PType, r: Rope) =
  var a: TLoc
  if d.k != locNone:
    # need to generate an assignment here
    initLoc(a, locData, t, OnStatic)
    a.r = r
    if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
    else: genAssignment(p, d, a, {needToCopy})
  else:
    # we cannot call initLoc() here as that would overwrite
    # the flags field!
    d.k = locData
    d.t = t
    d.r = r

proc putIntoDest(p: BProc, d: var TLoc, t: PType, r: Rope; s=OnUnknown) =
  var a: TLoc
  if d.k != locNone:
    # need to generate an assignment here
    initLoc(a, locExpr, t, s)
    a.r = r
    if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
    else: genAssignment(p, d, a, {needToCopy})
  else:
    # we cannot call initLoc() here as that would overwrite
    # the flags field!
    d.k = locExpr
    d.t = t
    d.r = r

proc binaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  if d.k != locNone: internalError(e.info, "binaryStmt")
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  lineCg(p, cpsStmts, frmt, rdLoc(a), rdLoc(b))

proc unaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  if d.k != locNone: internalError(e.info, "unaryStmt")
  initLocExpr(p, e.sons[1], a)
  lineCg(p, cpsStmts, frmt, [rdLoc(a)])

proc binaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a), rdLoc(b)]))

proc binaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [a.rdCharLoc, b.rdCharLoc]))

proc unaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  initLocExpr(p, e.sons[1], a)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a)]))

proc unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  initLocExpr(p, e.sons[1], a)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdCharLoc(a)]))

proc binaryArithOverflowRaw(p: BProc, t: PType, a, b: TLoc;
                            frmt: string): Rope =
  var size = getSize(t)
  let storage = if size < platform.intSize: rope("NI")
                else: getTypeDesc(p.module, t)
  result = getTempName(p.module)
  linefmt(p, cpsLocals, "$1 $2;$n", storage, result)
  lineCg(p, cpsStmts, frmt, result, rdCharLoc(a), rdCharLoc(b))
  if size < platform.intSize or t.kind in {tyRange, tyEnum}:
    linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n",
            result, intLiteral(firstOrd(t)), intLiteral(lastOrd(t)))

proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  const
    prc: array[mAddI..mPred, string] = [
      "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n",
      "$# = #mulInt($#, $#);$n", "$# = #divInt($#, $#);$n",
      "$# = #modInt($#, $#);$n",
      "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n"]
    prc64: array[mAddI..mPred, string] = [
      "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n",
      "$# = #mulInt64($#, $#);$n", "$# = #divInt64($#, $#);$n",
      "$# = #modInt64($#, $#);$n",
      "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n"]
    opr: array[mAddI..mPred, string] = [
      "($#)($# + $#)", "($#)($# - $#)", "($#)($# * $#)",
      "($#)($# / $#)", "($#)($# % $#)",
      "($#)($# + $#)", "($#)($# - $#)"]
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  # skipping 'range' is correct here as we'll generate a proper range check
  # later via 'chckRange'
  let t = e.typ.skipTypes(abstractRange)
  if optOverflowCheck notin p.options:
    let res = opr[m] % [getTypeDesc(p.module, e.typ), rdLoc(a), rdLoc(b)]
    putIntoDest(p, d, e.typ, res)
  else:
    let res = binaryArithOverflowRaw(p, t, a, b,
                                   if t.kind == tyInt64: prc64[m] else: prc[m])
    putIntoDest(p, d, e.typ, "($#)($#)" % [getTypeDesc(p.module, e.typ), res])

proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  const
    opr: array[mUnaryMinusI..mAbsI, string] = [
      mUnaryMinusI: "((NI$2)-($1))",
      mUnaryMinusI64: "-($1)",
      mAbsI: "($1 > 0? ($1) : -($1))"]
  var
    a: TLoc
    t: PType
  assert(e.sons[1].typ != nil)
  initLocExpr(p, e.sons[1], a)
  t = skipTypes(e.typ, abstractRange)
  if optOverflowCheck in p.options:
    linefmt(p, cpsStmts, "if ($1 == $2) #raiseOverflow();$n",
            rdLoc(a), intLiteral(firstOrd(t)))
  putIntoDest(p, d, e.typ, opr[m] % [rdLoc(a), rope(getSize(t) * 8)])

proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  const
    binArithTab: array[mAddF64..mXor, string] = [
      "(($4)($1) + ($4)($2))", # AddF64
      "(($4)($1) - ($4)($2))", # SubF64
      "(($4)($1) * ($4)($2))", # MulF64
      "(($4)($1) / ($4)($2))", # DivF64

      "($4)((NU$3)($1) >> (NU$3)($2))", # ShrI
      "($4)((NU$3)($1) << (NU$3)($2))", # ShlI
      "($4)($1 & $2)",      # BitandI
      "($4)($1 | $2)",      # BitorI
      "($4)($1 ^ $2)",      # BitxorI
      "(($1 <= $2) ? $1 : $2)", # MinI
      "(($1 >= $2) ? $1 : $2)", # MaxI
      "(($1 <= $2) ? $1 : $2)", # MinF64
      "(($1 >= $2) ? $1 : $2)", # MaxF64
      "($4)((NU$3)($1) + (NU$3)($2))", # AddU
      "($4)((NU$3)($1) - (NU$3)($2))", # SubU
      "($4)((NU$3)($1) * (NU$3)($2))", # MulU
      "($4)((NU$3)($1) / (NU$3)($2))", # DivU
      "($4)((NU$3)($1) % (NU$3)($2))", # ModU
      "($1 == $2)",           # EqI
      "($1 <= $2)",           # LeI
      "($1 < $2)",            # LtI
      "($1 == $2)",           # EqF64
      "($1 <= $2)",           # LeF64
      "($1 < $2)",            # LtF64
      "((NU$3)($1) <= (NU$3)($2))", # LeU
      "((NU$3)($1) < (NU$3)($2))", # LtU
      "((NU64)($1) <= (NU64)($2))", # LeU64
      "((NU64)($1) < (NU64)($2))", # LtU64
      "($1 == $2)",           # EqEnum
      "($1 <= $2)",           # LeEnum
      "($1 < $2)",            # LtEnum
      "((NU8)($1) == (NU8)($2))", # EqCh
      "((NU8)($1) <= (NU8)($2))", # LeCh
      "((NU8)($1) < (NU8)($2))", # LtCh
      "($1 == $2)",           # EqB
      "($1 <= $2)",           # LeB
      "($1 < $2)",            # LtB
      "($1 == $2)",           # EqRef
      "($1 == $2)",           # EqPtr
      "($1 <= $2)",           # LePtr
      "($1 < $2)",            # LtPtr
      "($1 != $2)"]           # Xor
  var
    a, b: TLoc
    s: BiggestInt
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  # BUGFIX: cannot use result-type here, as it may be a boolean
  s = max(getSize(a.t), getSize(b.t)) * 8
  putIntoDest(p, d, e.typ,
              binArithTab[op] % [rdLoc(a), rdLoc(b), rope(s),
                                      getSimpleTypeDesc(p.module, e.typ)])

proc genEqProc(p: BProc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  if a.t.skipTypes(abstractInst).callConv == ccClosure:
    putIntoDest(p, d, e.typ,
      "($1.ClP_0 == $2.ClP_0 && $1.ClE_0 == $2.ClE_0)" % [rdLoc(a), rdLoc(b)])
  else:
    putIntoDest(p, d, e.typ, "($1 == $2)" % [rdLoc(a), rdLoc(b)])

proc genIsNil(p: BProc, e: PNode, d: var TLoc) =
  let t = skipTypes(e.sons[1].typ, abstractRange)
  if t.kind == tyProc and t.callConv == ccClosure:
    unaryExpr(p, e, d, "($1.ClP_0 == 0)")
  else:
    unaryExpr(p, e, d, "($1 == 0)")

proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  const
    unArithTab: array[mNot..mToBiggestInt, string] = ["!($1)", # Not
      "$1",                   # UnaryPlusI
      "($3)((NU$2) ~($1))",   # BitnotI
      "$1",                   # UnaryPlusF64
      "-($1)",                # UnaryMinusF64
      "($1 < 0? -($1) : ($1))", # AbsF64; BUGFIX: fabs() makes problems
                                # for Tiny C, so we don't use it
      "(($3)(NU)(NU8)($1))",  # mZe8ToI
      "(($3)(NU64)(NU8)($1))", # mZe8ToI64
      "(($3)(NU)(NU16)($1))", # mZe16ToI
      "(($3)(NU64)(NU16)($1))", # mZe16ToI64
      "(($3)(NU64)(NU32)($1))", # mZe32ToI64
      "(($3)(NU64)(NU)($1))", # mZeIToI64
      "(($3)(NU8)(NU)($1))", # ToU8
      "(($3)(NU16)(NU)($1))", # ToU16
      "(($3)(NU32)(NU64)($1))", # ToU32
      "((double) ($1))",      # ToFloat
      "((double) ($1))",      # ToBiggestFloat
      "float64ToInt32($1)",   # ToInt
      "float64ToInt64($1)"]   # ToBiggestInt
  var
    a: TLoc
    t: PType
  assert(e.sons[1].typ != nil)
  initLocExpr(p, e.sons[1], a)
  t = skipTypes(e.typ, abstractRange)
  putIntoDest(p, d, e.typ,
              unArithTab[op] % [rdLoc(a), rope(getSize(t) * 8),
                getSimpleTypeDesc(p.module, e.typ)])

proc isCppRef(p: BProc; typ: PType): bool {.inline.} =
  result = p.module.compileToCpp and
      skipTypes(typ, abstractInst).kind == tyVar and
      tfVarIsPtr notin skipTypes(typ, abstractInst).flags

proc genDeref(p: BProc, e: PNode, d: var TLoc; enforceDeref=false) =
  let mt = mapType(e.sons[0].typ)
  if mt in {ctArray, ctPtrToArray} and not enforceDeref:
    # XXX the amount of hacks for C's arrays is incredible, maybe we should
    # simply wrap them in a struct? --> Losing auto vectorization then?
    #if e[0].kind != nkBracketExpr:
    #  message(e.info, warnUser, "CAME HERE " & renderTree(e))
    expr(p, e.sons[0], d)
    if e.sons[0].typ.skipTypes(abstractInst).kind == tyRef:
      d.s = OnHeap
  else:
    var a: TLoc
    let typ = skipTypes(e.sons[0].typ, abstractInst)
    if typ.kind == tyVar and tfVarIsPtr notin typ.flags and p.module.compileToCpp and e.sons[0].kind == nkHiddenAddr:
      initLocExprSingleUse(p, e[0][0], d)
      return
    else:
      initLocExprSingleUse(p, e.sons[0], a)
    if d.k == locNone:
      # dest = *a;  <-- We do not know that 'dest' is on the heap!
      # It is completely wrong to set 'd.s' here, unless it's not yet
      # been assigned to.
      case typ.kind
      of tyRef:
        d.s = OnHeap
      of tyVar:
        d.s = OnUnknown
        if tfVarIsPtr notin typ.flags and p.module.compileToCpp and
            e.kind == nkHiddenDeref:
          putIntoDest(p, d, e.typ, rdLoc(a), a.s)
          return
      of tyPtr:
        d.s = OnUnknown         # BUGFIX!
      else:
        internalError(e.info, "genDeref " & $typ.kind)
    elif p.module.compileToCpp:
      if typ.kind == tyVar and tfVarIsPtr notin typ.flags and
           e.kind == nkHiddenDeref:
        putIntoDest(p, d, e.typ, rdLoc(a), a.s)
        return
    if enforceDeref and mt == ctPtrToArray:
      # we lie about the type for better C interop: 'ptr array[3,T]' is
      # translated to 'ptr T', but for deref'ing this produces wrong code.
      # See tmissingderef. So we get rid of the deref instead. The codegen
      # ends up using 'memcpy' for the array assignment,
      # so the '&' and '*' cancel out:
      putIntoDest(p, d, a.t.sons[0], rdLoc(a), a.s)
    else:
      putIntoDest(p, d, e.typ, "(*$1)" % [rdLoc(a)], a.s)

proc genAddr(p: BProc, e: PNode, d: var TLoc) =
  # careful  'addr(myptrToArray)' needs to get the ampersand:
  if e.sons[0].typ.skipTypes(abstractInst).kind in {tyRef, tyPtr}:
    var a: TLoc
    initLocExpr(p, e.sons[0], a)
    putIntoDest(p, d, e.typ, "&" & a.r, a.s)
    #Message(e.info, warnUser, "HERE NEW &")
  elif mapType(e.sons[0].typ) == ctArray or isCppRef(p, e.sons[0].typ):
    expr(p, e.sons[0], d)
  else:
    var a: TLoc
    initLocExpr(p, e.sons[0], a)
    putIntoDest(p, d, e.typ, addrLoc(a), a.s)

template inheritLocation(d: var TLoc, a: TLoc) =
  if d.k == locNone: d.s = a.s

proc genRecordFieldAux(p: BProc, e: PNode, d, a: var TLoc) =
  initLocExpr(p, e.sons[0], a)
  if e.sons[1].kind != nkSym: internalError(e.info, "genRecordFieldAux")
  d.inheritLocation(a)
  discard getTypeDesc(p.module, a.t) # fill the record's fields.loc

proc genTupleElem(p: BProc, e: PNode, d: var TLoc) =
  var
    a: TLoc
    i: int
  initLocExpr(p, e.sons[0], a)
  let tupType = a.t.skipTypes(abstractInst)
  assert tupType.kind == tyTuple
  d.inheritLocation(a)
  discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  var r = rdLoc(a)
  case e.sons[1].kind
  of nkIntLit..nkUInt64Lit: i = int(e.sons[1].intVal)
  else: internalError(e.info, "genTupleElem")
  addf(r, ".Field$1", [rope(i)])
  putIntoDest(p, d, tupType.sons[i], r, a.s)

proc lookupFieldAgain(p: BProc, ty: PType; field: PSym; r: var Rope): PSym =
  var ty = ty
  assert r != nil
  while ty != nil:
    ty = ty.skipTypes(skipPtrs)
    assert(ty.kind in {tyTuple, tyObject})
    result = lookupInRecord(ty.n, field.name)
    if result != nil: break
    if not p.module.compileToCpp: add(r, ".Sup")
    ty = ty.sons[0]
  if result == nil: internalError(field.info, "genCheckedRecordField")

proc genRecordField(p: BProc, e: PNode, d: var TLoc) =
  var a: TLoc
  genRecordFieldAux(p, e, d, a)
  var r = rdLoc(a)
  var f = e.sons[1].sym
  let ty = skipTypes(a.t, abstractInst)
  if ty.kind == tyTuple:
    # we found a unique tuple type which lacks field information
    # so we use Field$i
    addf(r, ".Field$1", [rope(f.position)])
    putIntoDest(p, d, f.typ, r, a.s)
  else:
    let field = lookupFieldAgain(p, ty, f, r)
    if field.loc.r == nil: fillObjectFields(p.module, ty)
    if field.loc.r == nil: internalError(e.info, "genRecordField 3 " & typeToString(ty))
    addf(r, ".$1", [field.loc.r])
    putIntoDest(p, d, field.typ, r, a.s)
  #d.s = a.s

proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc)

proc genFieldCheck(p: BProc, e: PNode, obj: Rope, field: PSym;
                   origTy: PType) =
  var test, u, v: TLoc
  for i in countup(1, sonsLen(e) - 1):
    var it = e.sons[i]
    assert(it.kind in nkCallKinds)
    assert(it.sons[0].kind == nkSym)
    let op = it.sons[0].sym
    if op.magic == mNot: it = it.sons[1]
    let disc = it.sons[2].skipConv
    assert(disc.kind == nkSym)
    initLoc(test, locNone, it.typ, OnStack)
    initLocExpr(p, it.sons[1], u)
    var o = obj
    let d = lookupFieldAgain(p, origTy, disc.sym, o)
    initLoc(v, locExpr, d.typ, OnUnknown)
    v.r = o
    v.r.add(".")
    v.r.add(d.loc.r)
    genInExprAux(p, it, u, v, test)
    let id = nodeTableTestOrSet(p.module.dataCache,
                               newStrNode(nkStrLit, field.name.s), p.module.labels)
    let strLit = if id == p.module.labels: getStrLit(p.module, field.name.s)
                 else: p.module.tmpBase & rope(id)
    if op.magic == mNot:
      linefmt(p, cpsStmts,
              "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n",
              rdLoc(test), strLit)
    else:
      linefmt(p, cpsStmts,
              "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n",
              rdLoc(test), strLit)

proc genCheckedRecordField(p: BProc, e: PNode, d: var TLoc) =
  if optFieldCheck in p.options:
    var a: TLoc
    genRecordFieldAux(p, e.sons[0], d, a)
    let ty = skipTypes(a.t, abstractInst)
    var r = rdLoc(a)
    let f = e.sons[0].sons[1].sym
    let field = lookupFieldAgain(p, ty, f, r)
    if field.loc.r == nil: fillObjectFields(p.module, ty)
    if field.loc.r == nil:
      internalError(e.info, "genCheckedRecordField") # generate the checks:
    genFieldCheck(p, e, r, field, ty)
    add(r, rfmt(nil, ".$1", field.loc.r))
    putIntoDest(p, d, field.typ, r, a.s)
  else:
    genRecordField(p, e.sons[0], d)

proc genArrayElem(p: BProc, x, y: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, x, a)
  initLocExpr(p, y, b)
  var ty = skipTypes(skipTypes(a.t, abstractVarRange), abstractPtrs)
  var first = intLiteral(firstOrd(ty))
  # emit range check:
  if optBoundsCheck in p.options and tfUncheckedArray notin ty.flags:
    if not isConstExpr(y):
      # semantic pass has already checked for const index expressions
      if firstOrd(ty) == 0:
        if (firstOrd(b.t) < firstOrd(ty)) or (lastOrd(b.t) > lastOrd(ty)):
          linefmt(p, cpsStmts, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n",
                  rdCharLoc(b), intLiteral(lastOrd(ty)))
      else:
        linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n",
                rdCharLoc(b), first, intLiteral(lastOrd(ty)))
    else:
      let idx = getOrdValue(y)
      if idx < firstOrd(ty) or idx > lastOrd(ty):
        localError(x.info, errIndexOutOfBounds)
  d.inheritLocation(a)
  putIntoDest(p, d, elemType(skipTypes(ty, abstractVar)),
              rfmt(nil, "$1[($2)- $3]", rdLoc(a), rdCharLoc(b), first), a.s)

proc genCStringElem(p: BProc, x, y: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, x, a)
  initLocExpr(p, y, b)
  var ty = skipTypes(a.t, abstractVarRange)
  if d.k == locNone: d.s = a.s
  putIntoDest(p, d, elemType(skipTypes(ty, abstractVar)),
              rfmt(nil, "$1[$2]", rdLoc(a), rdCharLoc(b)), a.s)

proc genOpenArrayElem(p: BProc, x, y: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, x, a)
  initLocExpr(p, y, b) # emit range check:
  if optBoundsCheck in p.options:
    linefmt(p, cpsStmts, "if ((NU)($1) >= (NU)($2Len_0)) #raiseIndexError();$n",
            rdLoc(b), rdLoc(a)) # BUGFIX: ``>=`` and not ``>``!
  if d.k == locNone: d.s = a.s
  putIntoDest(p, d, elemType(skipTypes(a.t, abstractVar)),
              rfmt(nil, "$1[$2]", rdLoc(a), rdCharLoc(b)), a.s)

proc genSeqElem(p: BProc, x, y: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, x, a)
  initLocExpr(p, y, b)
  var ty = skipTypes(a.t, abstractVarRange)
  if ty.kind in {tyRef, tyPtr}:
    ty = skipTypes(ty.lastSon, abstractVarRange) # emit range check:
  if optBoundsCheck in p.options:
    if ty.kind == tyString:
      linefmt(p, cpsStmts,
           "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n",
           rdLoc(b), rdLoc(a), lenField(p))
    else:
      linefmt(p, cpsStmts,
           "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n",
           rdLoc(b), rdLoc(a), lenField(p))
  if d.k == locNone: d.s = OnHeap
  if skipTypes(a.t, abstractVar).kind in {tyRef, tyPtr}:
    a.r = rfmt(nil, "(*$1)", a.r)
  putIntoDest(p, d, elemType(skipTypes(a.t, abstractVar)),
              rfmt(nil, "$1->data[$2]", rdLoc(a), rdCharLoc(b)), a.s)

proc genBracketExpr(p: BProc; n: PNode; d: var TLoc) =
  var ty = skipTypes(n.sons[0].typ, abstractVarRange + tyUserTypeClasses)
  if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.lastSon, abstractVarRange)
  case ty.kind
  of tyArray: genArrayElem(p, n.sons[0], n.sons[1], d)
  of tyOpenArray, tyVarargs: genOpenArrayElem(p, n.sons[0], n.sons[1], d)
  of tySequence, tyString: genSeqElem(p, n.sons[0], n.sons[1], d)
  of tyCString: genCStringElem(p, n.sons[0], n.sons[1], d)
  of tyTuple: genTupleElem(p, n, d)
  else: internalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')')

proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  # how to generate code?
  #  'expr1 and expr2' becomes:
  #     result = expr1
  #     fjmp result, end
  #     result = expr2
  #  end:
  #  ... (result computed)
  # BUGFIX:
  #   a = b or a
  # used to generate:
  # a = b
  # if a: goto end
  # a = a
  # end:
  # now it generates:
  # tmp = b
  # if tmp: goto end
  # tmp = a
  # end:
  # a = tmp
  var
    L: TLabel
    tmp: TLoc
  getTemp(p, e.typ, tmp)      # force it into a temp!
  inc p.splitDecls
  expr(p, e.sons[1], tmp)
  L = getLabel(p)
  if m == mOr:
    lineF(p, cpsStmts, "if ($1) goto $2;$n", [rdLoc(tmp), L])
  else:
    lineF(p, cpsStmts, "if (!($1)) goto $2;$n", [rdLoc(tmp), L])
  expr(p, e.sons[2], tmp)
  fixLabel(p, L)
  if d.k == locNone:
    d = tmp
  else:
    genAssignment(p, d, tmp, {}) # no need for deep copying
  dec p.splitDecls

proc genEcho(p: BProc, n: PNode) =
  # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)``
  # is threadsafe.
  internalAssert n.kind == nkBracket
  var args: Rope = nil
  var a: TLoc
  for i in countup(0, n.len-1):
    if n.sons[i].skipConv.kind == nkNilLit:
      add(args, ", \"nil\"")
    else:
      initLocExpr(p, n.sons[i], a)
      addf(args, ", $1? ($1)->data:\"nil\"", [rdLoc(a)])
  if platform.targetOS == osGenode:
    # bypass libc and print directly to the Genode LOG session
    p.module.includeHeader("<base/log.h>")
    linefmt(p, cpsStmts, """Genode::log(""$1);$n""", args)
  else:
    p.module.includeHeader("<stdio.h>")
    linefmt(p, cpsStmts, "printf($1$2);$n",
            makeCString(repeat("%s", n.len) & tnl), args)
    linefmt(p, cpsStmts, "fflush(stdout);$n")

proc gcUsage(n: PNode) =
  if gSelectedGC == gcNone: message(n.info, warnGcMem, n.renderTree)

proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
  #   <Nim code>
  #   s = 'Hello ' & name & ', how do you feel?' & 'z'
  #
  #   <generated C code>
  #  {
  #    string tmp0;
  #    ...
  #    tmp0 = rawNewString(6 + 17 + 1 + s2->len);
  #    // we cannot generate s = rawNewString(...) here, because
  #    // ``s`` may be used on the right side of the expression
  #    appendString(tmp0, strlit_1);
  #    appendString(tmp0, name);
  #    appendString(tmp0, strlit_2);
  #    appendChar(tmp0, 'z');
  #    asgn(s, tmp0);
  #  }
  var a, tmp: TLoc
  getTemp(p, e.typ, tmp)
  var L = 0
  var appends: Rope = nil
  var lens: Rope = nil
  for i in countup(0, sonsLen(e) - 2):
    # compute the length expression:
    initLocExpr(p, e.sons[i + 1], a)
    if skipTypes(e.sons[i + 1].typ, abstractVarRange).kind == tyChar:
      inc(L)
      add(appends, rfmt(p.module, "#appendChar($1, $2);$n", tmp.r, rdLoc(a)))
    else:
      if e.sons[i + 1].kind in {nkStrLit..nkTripleStrLit}:
        inc(L, len(e.sons[i + 1].strVal))
      else:
        addf(lens, "$1->$2 + ", [rdLoc(a), lenField(p)])
      add(appends, rfmt(p.module, "#appendString($1, $2);$n", tmp.r, rdLoc(a)))
  linefmt(p, cpsStmts, "$1 = #rawNewString($2$3);$n", tmp.r, lens, rope(L))
  add(p.s(cpsStmts), appends)
  if d.k == locNone:
    d = tmp
  else:
    genAssignment(p, d, tmp, {}) # no need for deep copying
  gcUsage(e)

proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
  #  <Nim code>
  #  s &= 'Hello ' & name & ', how do you feel?' & 'z'
  #  // BUG: what if s is on the left side too?
  #  <generated C code>
  #  {
  #    s = resizeString(s, 6 + 17 + 1 + name->len);
  #    appendString(s, strlit_1);
  #    appendString(s, name);
  #    appendString(s, strlit_2);
  #    appendChar(s, 'z');
  #  }
  var
    a, dest: TLoc
    appends, lens: Rope
  assert(d.k == locNone)
  var L = 0
  initLocExpr(p, e.sons[1], dest)
  for i in countup(0, sonsLen(e) - 3):
    # compute the length expression:
    initLocExpr(p, e.sons[i + 2], a)
    if skipTypes(e.sons[i + 2].typ, abstractVarRange).kind == tyChar:
      inc(L)
      add(appends, rfmt(p.module, "#appendChar($1, $2);$n",
                        rdLoc(dest), rdLoc(a)))
    else:
      if e.sons[i + 2].kind in {nkStrLit..nkTripleStrLit}:
        inc(L, len(e.sons[i + 2].strVal))
      else:
        addf(lens, "$1->$2 + ", [rdLoc(a), lenField(p)])
      add(appends, rfmt(p.module, "#appendString($1, $2);$n",
                        rdLoc(dest), rdLoc(a)))
  linefmt(p, cpsStmts, "$1 = #resizeString($1, $2$3);$n",
          rdLoc(dest), lens, rope(L))
  add(p.s(cpsStmts), appends)
  gcUsage(e)

proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) =
  # seq &= x  -->
  #    seq = (typeof seq) incrSeq(&seq->Sup, sizeof(x));
  #    seq->data[seq->len-1] = x;
  let seqAppendPattern = if not p.module.compileToCpp:
                           "$1 = ($2) #incrSeqV2(&($1)->Sup, sizeof($3));$n"
                         else:
                           "$1 = ($2) #incrSeqV2($1, sizeof($3));$n"
  var a, b, dest: TLoc
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  let bt = skipTypes(e.sons[2].typ, {tyVar})
  lineCg(p, cpsStmts, seqAppendPattern, [
      rdLoc(a),
      getTypeDesc(p.module, e.sons[1].typ),
      getTypeDesc(p.module, bt)])
  #if bt != b.t:
  #  echo "YES ", e.info, " new: ", typeToString(bt), " old: ", typeToString(b.t)
  initLoc(dest, locExpr, bt, OnHeap)
  dest.r = rfmt(nil, "$1->data[$1->$2]", rdLoc(a), lenField(p))
  genAssignment(p, dest, b, {needToCopy, afDestIsNil})
  lineCg(p, cpsStmts, "++$1->$2;$n", rdLoc(a), lenField(p))
  gcUsage(e)

proc genReset(p: BProc, n: PNode) =
  var a: TLoc
  initLocExpr(p, n.sons[1], a)
  linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
          addrLoc(a), genTypeInfo(p.module, skipTypes(a.t, {tyVar})))

proc rawGenNew(p: BProc, a: TLoc, sizeExpr: Rope) =
  var sizeExpr = sizeExpr
  let typ = a.t
  var b: TLoc
  initLoc(b, locExpr, a.t, OnHeap)
  let refType = typ.skipTypes(abstractInst)
  assert refType.kind == tyRef
  let bt = refType.lastSon
  if sizeExpr.isNil:
    sizeExpr = "sizeof($1)" %
        [getTypeDesc(p.module, bt)]
  let args = [getTypeDesc(p.module, typ),
              genTypeInfo(p.module, typ),
              sizeExpr]
  if a.s == OnHeap and usesNativeGC():
    # use newObjRC1 as an optimization
    if canFormAcycle(a.t):
      linefmt(p, cpsStmts, "if ($1) #nimGCunref($1);$n", a.rdLoc)
    else:
      linefmt(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", a.rdLoc)
    b.r = ropecg(p.module, "($1) #newObjRC1($2, $3)", args)
    linefmt(p, cpsStmts, "$1 = $2;$n", a.rdLoc, b.rdLoc)
  else:
    b.r = ropecg(p.module, "($1) #newObj($2, $3)", args)
    genAssignment(p, a, b, {})  # set the object type:
  genObjectInit(p, cpsStmts, bt, a, false)

proc genNew(p: BProc, e: PNode) =
  var a: TLoc
  initLocExpr(p, e.sons[1], a)
  # 'genNew' also handles 'unsafeNew':
  if e.len == 3:
    var se: TLoc
    initLocExpr(p, e.sons[2], se)
    rawGenNew(p, a, se.rdLoc)
  else:
    rawGenNew(p, a, nil)
  gcUsage(e)

proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope) =
  let seqtype = skipTypes(dest.t, abstractVarRange)
  let args = [getTypeDesc(p.module, seqtype),
              genTypeInfo(p.module, seqtype), length]
  var call: TLoc
  initLoc(call, locExpr, dest.t, OnHeap)
  if dest.s == OnHeap and usesNativeGC():
    if canFormAcycle(dest.t):
      linefmt(p, cpsStmts, "if ($1) #nimGCunref($1);$n", dest.rdLoc)
    else:
      linefmt(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", dest.rdLoc)
    call.r = ropecg(p.module, "($1) #newSeqRC1($2, $3)", args)
    linefmt(p, cpsStmts, "$1 = $2;$n", dest.rdLoc, call.rdLoc)
  else:
    call.r = ropecg(p.module, "($1) #newSeq($2, $3)", args)
    genAssignment(p, dest, call, {})

proc genNewSeq(p: BProc, e: PNode) =
  var a, b: TLoc
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  genNewSeqAux(p, a, b.rdLoc)
  gcUsage(e)

proc genNewSeqOfCap(p: BProc; e: PNode; d: var TLoc) =
  let seqtype = skipTypes(e.typ, abstractVarRange)
  var a: TLoc
  initLocExpr(p, e.sons[1], a)
  putIntoDest(p, d, e.typ, ropecg(p.module,
              "($1)#nimNewSeqOfCap($2, $3)", [
              getTypeDesc(p.module, seqtype),
              genTypeInfo(p.module, seqtype), a.rdLoc]))
  gcUsage(e)

proc genConstExpr(p: BProc, n: PNode): Rope
proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool =
  if d.k == locNone and n.len > ord(n.kind == nkObjConstr) and n.isDeepConstExpr:
    let t = n.typ
    discard getTypeDesc(p.module, t) # so that any fields are initialized
    let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
    fillLoc(d, locData, t, p.module.tmpBase & rope(id), OnStatic)
    if id == p.module.labels:
      # expression not found in the cache:
      inc(p.module.labels)
      addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
           [getTypeDesc(p.module, t), d.r, genConstExpr(p, n)])
    result = true
  else:
    result = false

proc genObjConstr(p: BProc, e: PNode, d: var TLoc) =
  #echo rendertree e, " ", e.isDeepConstExpr
  if handleConstExpr(p, e, d): return
  var tmp: TLoc
  var t = e.typ.skipTypes(abstractInst)
  getTemp(p, t, tmp)
  let isRef = t.kind == tyRef
  var r = rdLoc(tmp)
  if isRef:
    rawGenNew(p, tmp, nil)
    t = t.lastSon.skipTypes(abstractInst)
    r = "(*$1)" % [r]
    gcUsage(e)
  else:
    constructLoc(p, tmp)
  discard getTypeDesc(p.module, t)
  let ty = getUniqueType(t)
  for i in 1 .. <e.len:
    let it = e.sons[i]
    var tmp2: TLoc
    tmp2.r = r
    let field = lookupFieldAgain(p, ty, it.sons[0].sym, tmp2.r)
    if field.loc.r == nil: fillObjectFields(p.module, ty)
    if field.loc.r == nil: internalError(e.info, "genObjConstr")
    if it.len == 3 and optFieldCheck in p.options:
      genFieldCheck(p, it.sons[2], r, field, ty)
    add(tmp2.r, ".")
    add(tmp2.r, field.loc.r)
    tmp2.k = locTemp
    tmp2.t = field.loc.t
    tmp2.s = if isRef: OnHeap else: OnStack
    expr(p, it.sons[1], tmp2)

  if d.k == locNone:
    d = tmp
  else:
    genAssignment(p, d, tmp, {})

proc genSeqConstr(p: BProc, t: PNode, d: var TLoc) =
  var arr: TLoc
  if d.k == locNone:
    getTemp(p, t.typ, d)
  # generate call to newSeq before adding the elements per hand:
  genNewSeqAux(p, d, intLiteral(sonsLen(t)))
  for i in countup(0, sonsLen(t) - 1):
    initLoc(arr, locExpr, elemType(skipTypes(t.typ, typedescInst)), OnHeap)
    arr.r = rfmt(nil, "$1->data[$2]", rdLoc(d), intLiteral(i))
    arr.s = OnHeap            # we know that sequences are on the heap
    expr(p, t.sons[i], arr)
  gcUsage(t)

proc genArrToSeq(p: BProc, t: PNode, d: var TLoc) =
  var elem, a, arr: TLoc
  if t.sons[1].kind == nkBracket:
    t.sons[1].typ = t.typ
    genSeqConstr(p, t.sons[1], d)
    return
  if d.k == locNone:
    getTemp(p, t.typ, d)
  # generate call to newSeq before adding the elements per hand:
  var L = int(lengthOrd(t.sons[1].typ))

  genNewSeqAux(p, d, intLiteral(L))
  initLocExpr(p, t.sons[1], a)
  for i in countup(0, L - 1):
    initLoc(elem, locExpr, elemType(skipTypes(t.typ, abstractInst)), OnHeap)
    elem.r = rfmt(nil, "$1->data[$2]", rdLoc(d), intLiteral(i))
    elem.s = OnHeap # we know that sequences are on the heap
    initLoc(arr, locExpr, elemType(skipTypes(t.sons[1].typ, abstractInst)), a.s)
    arr.r = rfmt(nil, "$1[$2]", rdLoc(a), intLiteral(i))
    genAssignment(p, elem, arr, {afDestIsNil, needToCopy})

proc genNewFinalize(p: BProc, e: PNode) =
  var
    a, b, f: TLoc
    refType, bt: PType
    ti: Rope
  refType = skipTypes(e.sons[1].typ, abstractVarRange)
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], f)
  initLoc(b, locExpr, a.t, OnHeap)
  ti = genTypeInfo(p.module, refType)
  addf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [
      getTypeDesc(p.module, refType),
      ti, getTypeDesc(p.module, skipTypes(refType.lastSon, abstractRange))])
  genAssignment(p, a, b, {})  # set the object type:
  bt = skipTypes(refType.lastSon, abstractRange)
  genObjectInit(p, cpsStmts, bt, a, false)
  gcUsage(e)

proc genOfHelper(p: BProc; dest: PType; a: Rope): Rope =
  # unfortunately 'genTypeInfo' sets tfObjHasKids as a side effect, so we
  # have to call it here first:
  let ti = genTypeInfo(p.module, dest)
  if tfFinal in dest.flags or (objHasKidsValid in p.module.flags and
                               tfObjHasKids notin dest.flags):
    result = "$1.m_type == $2" % [a, ti]
  else:
    discard cgsym(p.module, "TNimType")
    inc p.module.labels
    let cache = "Nim_OfCheck_CACHE" & p.module.labels.rope
    addf(p.module.s[cfsVars], "static TNimType* $#[2];$n", [cache])
    result = rfmt(p.module, "#isObjWithCache($#.m_type, $#, $#)", a, ti, cache)
  when false:
    # former version:
    result = rfmt(p.module, "#isObj($1.m_type, $2)",
                  a, genTypeInfo(p.module, dest))

proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, x, a)
  var dest = skipTypes(typ, typedescPtrs)
  var r = rdLoc(a)
  var nilCheck: Rope = nil
  var t = skipTypes(a.t, abstractInst)
  while t.kind in {tyVar, tyPtr, tyRef}:
    if t.kind != tyVar: nilCheck = r
    if t.kind != tyVar or not p.module.compileToCpp:
      r = rfmt(nil, "(*$1)", r)
    t = skipTypes(t.lastSon, typedescInst)
  if not p.module.compileToCpp:
    while t.kind == tyObject and t.sons[0] != nil:
      add(r, ~".Sup")
      t = skipTypes(t.sons[0], skipPtrs)
  if isObjLackingTypeField(t):
    globalError(x.info, errGenerated,
      "no 'of' operator available for pure objects")
  if nilCheck != nil:
    r = rfmt(p.module, "(($1) && ($2))", nilCheck, genOfHelper(p, dest, r))
  else:
    r = rfmt(p.module, "($1)", genOfHelper(p, dest, r))
  putIntoDest(p, d, getSysType(tyBool), r, a.s)

proc genOf(p: BProc, n: PNode, d: var TLoc) =
  genOf(p, n.sons[1], n.sons[2].typ, d)

proc genRepr(p: BProc, e: PNode, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, e.sons[1], a)
  var t = skipTypes(e.sons[1].typ, abstractVarRange)
  case t.kind
  of tyInt..tyInt64, tyUInt..tyUInt64:
    putIntoDest(p, d, e.typ,
                ropecg(p.module, "#reprInt((NI64)$1)", [rdLoc(a)]), a.s)
  of tyFloat..tyFloat128:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprFloat($1)", [rdLoc(a)]), a.s)
  of tyBool:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprBool($1)", [rdLoc(a)]), a.s)
  of tyChar:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprChar($1)", [rdLoc(a)]), a.s)
  of tyEnum, tyOrdinal:
    putIntoDest(p, d, e.typ,
                ropecg(p.module, "#reprEnum((NI)$1, $2)", [
                rdLoc(a), genTypeInfo(p.module, t)]), a.s)
  of tyString:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprStr($1)", [rdLoc(a)]), a.s)
  of tySet:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprSet($1, $2)", [
                addrLoc(a), genTypeInfo(p.module, t)]), a.s)
  of tyOpenArray, tyVarargs:
    var b: TLoc
    case a.t.kind
    of tyOpenArray, tyVarargs:
      putIntoDest(p, b, e.typ, "$1, $1Len_0" % [rdLoc(a)], a.s)
    of tyString, tySequence:
      putIntoDest(p, b, e.typ,
                  "$1->data, $1->$2" % [rdLoc(a), lenField(p)], a.s)
    of tyArray:
      putIntoDest(p, b, e.typ,
                  "$1, $2" % [rdLoc(a), rope(lengthOrd(a.t))], a.s)
    else: internalError(e.sons[0].info, "genRepr()")
    putIntoDest(p, d, e.typ,
        ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b),
        genTypeInfo(p.module, elemType(t))]), a.s)
  of tyCString, tyArray, tyRef, tyPtr, tyPointer, tyNil, tySequence:
    putIntoDest(p, d, e.typ,
                ropecg(p.module, "#reprAny($1, $2)", [
                rdLoc(a), genTypeInfo(p.module, t)]), a.s)
  of tyEmpty, tyVoid:
    localError(e.info, "'repr' doesn't support 'void' type")
  else:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprAny($1, $2)",
                                   [addrLoc(a), genTypeInfo(p.module, t)]), a.s)
  gcUsage(e)

proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) =
  let t = e.sons[1].typ
  putIntoDest(p, d, e.typ, genTypeInfo(p.module, t))

proc genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  initLocExpr(p, n.sons[1], a)
  a.r = ropecg(p.module, frmt, [rdLoc(a)])
  if d.k == locNone: getTemp(p, n.typ, d)
  genAssignment(p, d, a, {})
  gcUsage(n)

proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  var a = e.sons[1]
  if a.kind == nkHiddenAddr: a = a.sons[0]
  var typ = skipTypes(a.typ, abstractVar + tyUserTypeClasses)
  case typ.kind
  of tyOpenArray, tyVarargs:
    if op == mHigh: unaryExpr(p, e, d, "($1Len_0-1)")
    else: unaryExpr(p, e, d, "$1Len_0")
  of tyCString:
    useStringh(p.module)
    if op == mHigh: unaryExpr(p, e, d, "($1 ? (strlen($1)-1) : -1)")
    else: unaryExpr(p, e, d, "($1 ? strlen($1) : 0)")
  of tyString, tySequence:
    if not p.module.compileToCpp:
      if op == mHigh: unaryExpr(p, e, d, "($1 ? ($1->Sup.len-1) : -1)")
      else: unaryExpr(p, e, d, "($1 ? $1->Sup.len : 0)")
    else:
      if op == mHigh: unaryExpr(p, e, d, "($1 ? ($1->len-1) : -1)")
      else: unaryExpr(p, e, d, "($1 ? $1->len : 0)")
  of tyArray:
    # YYY: length(sideeffect) is optimized away incorrectly?
    if op == mHigh: putIntoDest(p, d, e.typ, rope(lastOrd(typ)))
    else: putIntoDest(p, d, e.typ, rope(lengthOrd(typ)))
  else: internalError(e.info, "genArrayLen()")

proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  assert(d.k == locNone)
  var x = e.sons[1]
  if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  initLocExpr(p, x, a)
  initLocExpr(p, e.sons[2], b)
  let t = skipTypes(e.sons[1].typ, {tyVar})
  let setLenPattern = if not p.module.compileToCpp:
      "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n"
    else:
      "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n"

  lineCg(p, cpsStmts, setLenPattern, [
      rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
      getTypeDesc(p.module, t.skipTypes(abstractInst).sons[0])])
  gcUsage(e)

proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
  binaryStmt(p, e, d, "$1 = #setLengthStr($1, $2);$n")
  gcUsage(e)

proc genSwap(p: BProc, e: PNode, d: var TLoc) =
  # swap(a, b) -->
  # temp = a
  # a = b
  # b = temp
  var a, b, tmp: TLoc
  getTemp(p, skipTypes(e.sons[1].typ, abstractVar), tmp)
  initLocExpr(p, e.sons[1], a) # eval a
  initLocExpr(p, e.sons[2], b) # eval b
  genAssignment(p, tmp, a, {})
  genAssignment(p, a, b, {})
  genAssignment(p, b, tmp, {})

proc rdSetElemLoc(a: TLoc, setType: PType): Rope =
  # read a location of an set element; it may need a subtraction operation
  # before the set operation
  result = rdCharLoc(a)
  assert(setType.kind == tySet)
  if firstOrd(setType) != 0:
    result = "($1- $2)" % [result, rope(firstOrd(setType))]

proc fewCmps(s: PNode): bool =
  # this function estimates whether it is better to emit code
  # for constructing the set or generating a bunch of comparisons directly
  if s.kind != nkCurly: internalError(s.info, "fewCmps")
  if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags):
    result = false            # it is better to emit the set generation code
  elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}:
    result = true             # better not emit the set if int is basetype!
  else:
    result = sonsLen(s) <= 8  # 8 seems to be a good value

proc binaryExprIn(p: BProc, e: PNode, a, b, d: var TLoc, frmt: string) =
  putIntoDest(p, d, e.typ, frmt % [rdLoc(a), rdSetElemLoc(b, a.t)])

proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) =
  case int(getSize(skipTypes(e.sons[1].typ, abstractVar)))
  of 1: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&7U)))!=0)")
  of 2: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&15U)))!=0)")
  of 4: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&31U)))!=0)")
  of 8: binaryExprIn(p, e, a, b, d, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)")
  else: binaryExprIn(p, e, a, b, d, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)")

proc binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  assert(d.k == locNone)
  initLocExpr(p, e.sons[1], a)
  initLocExpr(p, e.sons[2], b)
  lineF(p, cpsStmts, frmt, [rdLoc(a), rdSetElemLoc(b, a.t)])

proc genInOp(p: BProc, e: PNode, d: var TLoc) =
  var a, b, x, y: TLoc
  if (e.sons[1].kind == nkCurly) and fewCmps(e.sons[1]):
    # a set constructor but not a constant set:
    # do not emit the set, but generate a bunch of comparisons; and if we do
    # so, we skip the unnecessary range check: This is a semantical extension
    # that code now relies on. :-/ XXX
    let ea = if e.sons[2].kind in {nkChckRange, nkChckRange64}:
               e.sons[2].sons[0]
             else:
               e.sons[2]
    initLocExpr(p, ea, a)
    initLoc(b, locExpr, e.typ, OnUnknown)
    b.r = rope("(")
    var length = sonsLen(e.sons[1])
    for i in countup(0, length - 1):
      if e.sons[1].sons[i].kind == nkRange:
        initLocExpr(p, e.sons[1].sons[i].sons[0], x)
        initLocExpr(p, e.sons[1].sons[i].sons[1], y)
        addf(b.r, "$1 >= $2 && $1 <= $3",
             [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)])
      else:
        initLocExpr(p, e.sons[1].sons[i], x)
        addf(b.r, "$1 == $2", [rdCharLoc(a), rdCharLoc(x)])
      if i < length - 1: add(b.r, " || ")
    add(b.r, ")")
    putIntoDest(p, d, e.typ, b.r)
  else:
    assert(e.sons[1].typ != nil)
    assert(e.sons[2].typ != nil)
    initLocExpr(p, e.sons[1], a)
    initLocExpr(p, e.sons[2], b)
    genInExprAux(p, e, a, b, d)

proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  const
    lookupOpr: array[mLeSet..mSymDiffSet, string] = [
      "for ($1 = 0; $1 < $2; $1++) { $n" &
        "  $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
        "  if (!$3) break;}$n", "for ($1 = 0; $1 < $2; $1++) { $n" &
        "  $3 = (($4[$1] & ~ $5[$1]) == 0);$n" & "  if (!$3) break;}$n" &
        "if ($3) $3 = (memcmp($4, $5, $2) != 0);$n",
      "&", "|", "& ~", "^"]
  var a, b, i: TLoc
  var setType = skipTypes(e.sons[1].typ, abstractVar)
  var size = int(getSize(setType))
  case size
  of 1, 2, 4, 8:
    case op
    of mIncl:
      var ts = "NU" & $(size * 8)
      binaryStmtInExcl(p, e, d,
          "$1 |= ((" & ts & ")1)<<(($2)%(sizeof(" & ts & ")*8));$n")
    of mExcl:
      var ts = "NU" & $(size * 8)
      binaryStmtInExcl(p, e, d, "$1 &= ~(((" & ts & ")1) << (($2) % (sizeof(" &
          ts & ")*8)));$n")
    of mCard:
      if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)")
      else: unaryExprChar(p, e, d, "#countBits64($1)")
    of mLtSet: binaryExprChar(p, e, d, "(($1 & ~ $2 ==0)&&($1 != $2))")
    of mLeSet: binaryExprChar(p, e, d, "(($1 & ~ $2)==0)")
    of mEqSet: binaryExpr(p, e, d, "($1 == $2)")
    of mMulSet: binaryExpr(p, e, d, "($1 & $2)")
    of mPlusSet: binaryExpr(p, e, d, "($1 | $2)")
    of mMinusSet: binaryExpr(p, e, d, "($1 & ~ $2)")
    of mSymDiffSet: binaryExpr(p, e, d, "($1 ^ $2)")
    of mInSet:
      genInOp(p, e, d)
    else: internalError(e.info, "genSetOp()")
  else:
    case op
    of mIncl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n")
    of mExcl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n")
    of mCard: unaryExprChar(p, e, d, "#cardSet($1, " & $size & ')')
    of mLtSet, mLeSet:
      getTemp(p, getSysType(tyInt), i) # our counter
      initLocExpr(p, e.sons[1], a)
      initLocExpr(p, e.sons[2], b)
      if d.k == locNone: getTemp(p, getSysType(tyBool), d)
      lineF(p, cpsStmts, lookupOpr[op],
           [rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b)])
    of mEqSet:
      useStringh(p.module)
      binaryExprChar(p, e, d, "(memcmp($1, $2, " & $(size) & ")==0)")
    of mMulSet, mPlusSet, mMinusSet, mSymDiffSet:
      # we inline the simple for loop for better code generation:
      getTemp(p, getSysType(tyInt), i) # our counter
      initLocExpr(p, e.sons[1], a)
      initLocExpr(p, e.sons[2], b)
      if d.k == locNone: getTemp(p, a.t, d)
      lineF(p, cpsStmts,
           "for ($1 = 0; $1 < $2; $1++) $n" &
           "  $3[$1] = $4[$1] $6 $5[$1];$n", [
          rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b),
          rope(lookupOpr[op])])
    of mInSet: genInOp(p, e, d)
    else: internalError(e.info, "genSetOp")

proc genOrd(p: BProc, e: PNode, d: var TLoc) =
  unaryExprChar(p, e, d, "$1")

proc genSomeCast(p: BProc, e: PNode, d: var TLoc) =
  const
    ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs}
  # we use whatever C gives us. Except if we have a value-type, we need to go
  # through its address:
  var a: TLoc
  initLocExpr(p, e.sons[1], a)
  let etyp = skipTypes(e.typ, abstractRange)
  if etyp.kind in ValueTypes and lfIndirect notin a.flags:
    putIntoDest(p, d, e.typ, "(*($1*) ($2))" %
        [getTypeDesc(p.module, e.typ), addrLoc(a)], a.s)
  elif etyp.kind == tyProc and etyp.callConv == ccClosure:
    putIntoDest(p, d, e.typ, "(($1) ($2))" %
        [getClosureType(p.module, etyp, clHalfWithEnv), rdCharLoc(a)], a.s)
  else:
    putIntoDest(p, d, e.typ, "(($1) ($2))" %
        [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.s)

proc genCast(p: BProc, e: PNode, d: var TLoc) =
  const ValueTypes = {tyFloat..tyFloat128, tyTuple, tyObject, tyArray}
  let
    destt = skipTypes(e.typ, abstractRange)
    srct = skipTypes(e.sons[1].typ, abstractRange)
  if destt.kind in ValueTypes or srct.kind in ValueTypes:
    # 'cast' and some float type involved? --> use a union.
    inc(p.labels)
    var lbl = p.labels.rope
    var tmp: TLoc
    tmp.r = "LOC$1.source" % [lbl]
    linefmt(p, cpsLocals, "union { $1 source; $2 dest; } LOC$3;$n",
      getTypeDesc(p.module, e.sons[1].typ), getTypeDesc(p.module, e.typ), lbl)
    tmp.k = locExpr
    tmp.t = srct
    tmp.s = OnStack
    tmp.flags = {}
    expr(p, e.sons[1], tmp)
    putIntoDest(p, d, e.typ, "LOC$#.dest" % [lbl], tmp.s)
  else:
    # I prefer the shorter cast version for pointer types -> generate less
    # C code; plus it's the right thing to do for closures:
    genSomeCast(p, e, d)

proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) =
  var a: TLoc
  var dest = skipTypes(n.typ, abstractVar)
  # range checks for unsigned turned out to be buggy and annoying:
  if optRangeCheck notin p.options or dest.skipTypes({tyRange}).kind in
                                             {tyUInt..tyUInt64}:
    initLocExpr(p, n.sons[0], a)
    putIntoDest(p, d, n.typ, "(($1) ($2))" %
        [getTypeDesc(p.module, dest), rdCharLoc(a)], a.s)
  else:
    initLocExpr(p, n.sons[0], a)
    putIntoDest(p, d, dest, ropecg(p.module, "(($1)#$5($2, $3, $4))", [
        getTypeDesc(p.module, dest), rdCharLoc(a),
        genLiteral(p, n.sons[1], dest), genLiteral(p, n.sons[2], dest),
        rope(magic)]), a.s)

proc genConv(p: BProc, e: PNode, d: var TLoc) =
  let destType = e.typ.skipTypes({tyVar, tyGenericInst, tyAlias})
  if compareTypes(destType, e.sons[1].typ, dcEqIgnoreDistinct):
    expr(p, e.sons[1], d)
  else:
    genSomeCast(p, e, d)

proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, n.sons[0], a)
  putIntoDest(p, d, skipTypes(n.typ, abstractVar), "$1->data" % [rdLoc(a)], a.s)

proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, n.sons[0], a)
  putIntoDest(p, d, skipTypes(n.typ, abstractVar),
              ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]), a.s)
  gcUsage(n)

proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  var x: TLoc
  var a = e.sons[1]
  var b = e.sons[2]
  if (a.kind == nkNilLit) or (b.kind == nkNilLit):
    binaryExpr(p, e, d, "($1 == $2)")
  elif (a.kind in {nkStrLit..nkTripleStrLit}) and (a.strVal == ""):
    initLocExpr(p, e.sons[2], x)
    putIntoDest(p, d, e.typ,
      rfmt(nil, "(($1) && ($1)->$2 == 0)", rdLoc(x), lenField(p)))
  elif (b.kind in {nkStrLit..nkTripleStrLit}) and (b.strVal == ""):
    initLocExpr(p, e.sons[1], x)
    putIntoDest(p, d, e.typ,
      rfmt(nil, "(($1) && ($1)->$2 == 0)", rdLoc(x), lenField(p)))
  else:
    binaryExpr(p, e, d, "#eqStrings($1, $2)")

proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  if {optNaNCheck, optInfCheck} * p.options != {}:
    const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
    var a, b: TLoc
    assert(e.sons[1].typ != nil)
    assert(e.sons[2].typ != nil)
    initLocExpr(p, e.sons[1], a)
    initLocExpr(p, e.sons[2], b)
    putIntoDest(p, d, e.typ, rfmt(nil, "(($4)($2) $1 ($4)($3))",
                                  rope(opr[m]), rdLoc(a), rdLoc(b),
                                  getSimpleTypeDesc(p.module, e[1].typ)))
    if optNaNCheck in p.options:
      linefmt(p, cpsStmts, "#nanCheck($1);$n", rdLoc(d))
    if optInfCheck in p.options:
      linefmt(p, cpsStmts, "#infCheck($1);$n", rdLoc(d))
  else:
    binaryArith(p, e, d, m)

proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  case op
  of mOr, mAnd: genAndOr(p, e, d, op)
  of mNot..mToBiggestInt: unaryArith(p, e, d, op)
  of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op)
  of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  of mShrI..mXor: binaryArith(p, e, d, op)
  of mEqProc: genEqProc(p, e, d)
  of mAddI..mPred: binaryArithOverflow(p, e, d, op)
  of mRepr: genRepr(p, e, d)
  of mGetTypeInfo: genGetTypeInfo(p, e, d)
  of mSwap: genSwap(p, e, d)
  of mUnaryLt:
    if optOverflowCheck notin p.options: unaryExpr(p, e, d, "($1 - 1)")
    else: unaryExpr(p, e, d, "#subInt($1, 1)")
  of mInc, mDec:
    const opr: array[mInc..mDec, string] = ["$1 += $2;$n", "$1 -= $2;$n"]
    const fun64: array[mInc..mDec, string] = ["$# = #addInt64($#, $#);$n",
                                               "$# = #subInt64($#, $#);$n"]
    const fun: array[mInc..mDec, string] = ["$# = #addInt($#, $#);$n",
                                             "$# = #subInt($#, $#);$n"]
    let underlying = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tyVar, tyRange})
    if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}:
      binaryStmt(p, e, d, opr[op])
    else:
      var a, b: TLoc
      assert(e.sons[1].typ != nil)
      assert(e.sons[2].typ != nil)
      initLocExpr(p, e.sons[1], a)
      initLocExpr(p, e.sons[2], b)

      let ranged = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tyVar})
      let res = binaryArithOverflowRaw(p, ranged, a, b,
        if underlying.kind == tyInt64: fun64[op] else: fun[op])
      putIntoDest(p, a, ranged, "($#)($#)" % [
        getTypeDesc(p.module, ranged), res])

  of mConStrStr: genStrConcat(p, e, d)
  of mAppendStrCh: binaryStmt(p, e, d, "$1 = #addChar($1, $2);$n")
  of mAppendStrStr: genStrAppend(p, e, d)
  of mAppendSeqElem: genSeqElemAppend(p, e, d)
  of mEqStr: genStrEquals(p, e, d)
  of mLeStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) <= 0)")
  of mLtStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) < 0)")
  of mIsNil: genIsNil(p, e, d)
  of mIntToStr: genDollar(p, e, d, "#nimIntToStr($1)")
  of mInt64ToStr: genDollar(p, e, d, "#nimInt64ToStr($1)")
  of mBoolToStr: genDollar(p, e, d, "#nimBoolToStr($1)")
  of mCharToStr: genDollar(p, e, d, "#nimCharToStr($1)")
  of mFloatToStr: genDollar(p, e, d, "#nimFloatToStr($1)")
  of mCStrToStr: genDollar(p, e, d, "#cstrToNimstr($1)")
  of mStrToStr: expr(p, e.sons[1], d)
  of mEnumToStr: genRepr(p, e, d)
  of mOf: genOf(p, e, d)
  of mNew: genNew(p, e)
  of mNewFinalize: genNewFinalize(p, e)
  of mNewSeq: genNewSeq(p, e)
  of mNewSeqOfCap: genNewSeqOfCap(p, e, d)
  of mSizeOf:
    let t = e.sons[1].typ.skipTypes({tyTypeDesc})
    putIntoDest(p, d, e.typ, "((NI)sizeof($1))" % [getTypeDesc(p.module, t)])
  of mChr: genSomeCast(p, e, d)
  of mOrd: genOrd(p, e, d)
  of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
    genArrayLen(p, e, d, op)
  of mXLenStr, mXLenSeq:
    if not p.module.compileToCpp:
      unaryExpr(p, e, d, "($1->Sup.len)")
    else:
      unaryExpr(p, e, d, "$1->len")
  of mGCref: unaryStmt(p, e, d, "#nimGCref($1);$n")
  of mGCunref: unaryStmt(p, e, d, "#nimGCunref($1);$n")
  of mSetLengthStr: genSetLengthStr(p, e, d)
  of mSetLengthSeq: genSetLengthSeq(p, e, d)
  of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
     mInSet:
    genSetOp(p, e, d, op)
  of mNewString, mNewStringOfCap, mCopyStr, mCopyStrLast, mExit,
      mParseBiggestFloat:
    var opr = e.sons[0].sym
    if lfNoDecl notin opr.loc.flags:
      discard cgsym(p.module, $opr.loc.r)
    genCall(p, e, d)
  of mReset: genReset(p, e)
  of mEcho: genEcho(p, e[1].skipConv)
  of mArrToSeq: genArrToSeq(p, e, d)
  of mNLen..mNError, mSlurp..mQuoteAst:
    localError(e.info, errXMustBeCompileTime, e.sons[0].sym.name.s)
  of mSpawn:
    let n = lowerings.wrapProcForSpawn(p.module.module, e, e.typ, nil, nil)
    expr(p, n, d)
  of mParallel:
    let n = semparallel.liftParallel(p.module.module, e)
    expr(p, n, d)
  of mDeepCopy:
    var a, b: TLoc
    let x = if e[1].kind in {nkAddr, nkHiddenAddr}: e[1][0] else: e[1]
    initLocExpr(p, x, a)
    initLocExpr(p, e.sons[2], b)
    genDeepCopy(p, a, b)
  of mDotDot, mEqCString: genCall(p, e, d)
  else: internalError(e.info, "genMagicExpr: " & $op)

proc genSetConstr(p: BProc, e: PNode, d: var TLoc) =
  # example: { a..b, c, d, e, f..g }
  # we have to emit an expression of the form:
  # memset(tmp, 0, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c);
  # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g);
  var
    a, b, idx: TLoc
  if nfAllConst in e.flags:
    putIntoDest(p, d, e.typ, genSetNode(p, e))
  else:
    if d.k == locNone: getTemp(p, e.typ, d)
    if getSize(e.typ) > 8:
      # big set:
      useStringh(p.module)
      lineF(p, cpsStmts, "memset($1, 0, sizeof($1));$n", [rdLoc(d)])
      for i in countup(0, sonsLen(e) - 1):
        if e.sons[i].kind == nkRange:
          getTemp(p, getSysType(tyInt), idx) # our counter
          initLocExpr(p, e.sons[i].sons[0], a)
          initLocExpr(p, e.sons[i].sons[1], b)
          lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
              "$2[(NU)($1)>>3] |=(1U<<((NU)($1)&7U));$n", [rdLoc(idx), rdLoc(d),
              rdSetElemLoc(a, e.typ), rdSetElemLoc(b, e.typ)])
        else:
          initLocExpr(p, e.sons[i], a)
          lineF(p, cpsStmts, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n",
               [rdLoc(d), rdSetElemLoc(a, e.typ)])
    else:
      # small set
      var ts = "NU" & $(getSize(e.typ) * 8)
      lineF(p, cpsStmts, "$1 = 0;$n", [rdLoc(d)])
      for i in countup(0, sonsLen(e) - 1):
        if e.sons[i].kind == nkRange:
          getTemp(p, getSysType(tyInt), idx) # our counter
          initLocExpr(p, e.sons[i].sons[0], a)
          initLocExpr(p, e.sons[i].sons[1], b)
          lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
              "$2 |=((" & ts & ")(1)<<(($1)%(sizeof(" & ts & ")*8)));$n", [
              rdLoc(idx), rdLoc(d), rdSetElemLoc(a, e.typ),
              rdSetElemLoc(b, e.typ)])
        else:
          initLocExpr(p, e.sons[i], a)
          lineF(p, cpsStmts,
               "$1 |=((" & ts & ")(1)<<(($2)%(sizeof(" & ts & ")*8)));$n",
               [rdLoc(d), rdSetElemLoc(a, e.typ)])

proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) =
  var rec: TLoc
  if not handleConstExpr(p, n, d):
    let t = n.typ
    discard getTypeDesc(p.module, t) # so that any fields are initialized
    if d.k == locNone: getTemp(p, t, d)
    for i in countup(0, sonsLen(n) - 1):
      var it = n.sons[i]
      if it.kind == nkExprColonExpr: it = it.sons[1]
      initLoc(rec, locExpr, it.typ, d.s)
      rec.r = "$1.Field$2" % [rdLoc(d), rope(i)]
      expr(p, it, rec)

proc isConstClosure(n: PNode): bool {.inline.} =
  result = n.sons[0].kind == nkSym and isRoutine(n.sons[0].sym) and
      n.sons[1].kind == nkNilLit

proc genClosure(p: BProc, n: PNode, d: var TLoc) =
  assert n.kind == nkClosure

  if isConstClosure(n):
    inc(p.module.labels)
    var tmp = "CNSTCLOSURE" & rope(p.module.labels)
    addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
        [getTypeDesc(p.module, n.typ), tmp, genConstExpr(p, n)])
    putIntoDest(p, d, n.typ, tmp, OnStatic)
  else:
    var tmp, a, b: TLoc
    initLocExpr(p, n.sons[0], a)
    initLocExpr(p, n.sons[1], b)
    if n.sons[0].skipConv.kind == nkClosure:
      internalError(n.info, "closure to closure created")
    # tasyncawait.nim breaks with this optimization:
    when false:
      if d.k != locNone:
        linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
                d.rdLoc, a.rdLoc, b.rdLoc)
    else:
      getTemp(p, n.typ, tmp)
      linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
              tmp.rdLoc, a.rdLoc, b.rdLoc)
      putLocIntoDest(p, d, tmp)

proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) =
  var arr: TLoc
  if not handleConstExpr(p, n, d):
    if d.k == locNone: getTemp(p, n.typ, d)
    for i in countup(0, sonsLen(n) - 1):
      initLoc(arr, locExpr, elemType(skipTypes(n.typ, abstractInst)), d.s)
      arr.r = "$1[$2]" % [rdLoc(d), intLiteral(i)]
      expr(p, n.sons[i], arr)

proc genComplexConst(p: BProc, sym: PSym, d: var TLoc) =
  requestConstImpl(p, sym)
  assert((sym.loc.r != nil) and (sym.loc.t != nil))
  putLocIntoDest(p, d, sym.loc)

proc genStmtListExpr(p: BProc, n: PNode, d: var TLoc) =
  var length = sonsLen(n)
  for i in countup(0, length - 2): genStmts(p, n.sons[i])
  if length > 0: expr(p, n.sons[length - 1], d)

proc upConv(p: BProc, n: PNode, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, n.sons[0], a)
  let dest = skipTypes(n.typ, abstractPtrs)
  if optObjCheck in p.options and not isObjLackingTypeField(dest):
    var r = rdLoc(a)
    var nilCheck: Rope = nil
    var t = skipTypes(a.t, abstractInst)
    while t.kind in {tyVar, tyPtr, tyRef}:
      if t.kind != tyVar: nilCheck = r
      if t.kind != tyVar or not p.module.compileToCpp:
        r = "(*$1)" % [r]
      t = skipTypes(t.lastSon, abstractInst)
    if not p.module.compileToCpp:
      while t.kind == tyObject and t.sons[0] != nil:
        add(r, ".Sup")
        t = skipTypes(t.sons[0], skipPtrs)
    if nilCheck != nil:
      linefmt(p, cpsStmts, "if ($1) #chckObj($2.m_type, $3);$n",
              nilCheck, r, genTypeInfo(p.module, dest))
    else:
      linefmt(p, cpsStmts, "#chckObj($1.m_type, $2);$n",
              r, genTypeInfo(p.module, dest))
  if n.sons[0].typ.kind != tyObject:
    putIntoDest(p, d, n.typ,
                "(($1) ($2))" % [getTypeDesc(p.module, n.typ), rdLoc(a)], a.s)
  else:
    putIntoDest(p, d, n.typ, "(*($1*) ($2))" %
                             [getTypeDesc(p.module, dest), addrLoc(a)], a.s)

proc downConv(p: BProc, n: PNode, d: var TLoc) =
  if p.module.compileToCpp:
    expr(p, ns="w"> = g_slist_next(curr);
        }

        if (group) {
            if (filtered == NULL) {
                cons_show("No contacts in group %s are %s.", group, presence);
            } else {
                cons_show("%s (%s):", group, presence);
                cons_show_contacts(filtered);
            }
        } else {
            if (filtered == NULL) {
                cons_show("No contacts are %s.", presence);
            } else {
                cons_show("Contacts (%s):", presence);
                cons_show_contacts(filtered);
            }
        }
        g_slist_free(filtered);

        // offline, no available resources
    } else if (strcmp("offline", presence) == 0) {
        GSList* filtered = NULL;

        GSList* curr = list;
        while (curr) {
            PContact contact = curr->data;
            if (!p_contact_has_available_resource(contact)) {
                filtered = g_slist_append(filtered, contact);
            }
            curr = g_slist_next(curr);
        }

        if (group) {
            if (filtered == NULL) {
                cons_show("No contacts in group %s are %s.", group, presence);
            } else {
                cons_show("%s (%s):", group, presence);
                cons_show_contacts(filtered);
            }
        } else {
            if (filtered == NULL) {
                cons_show("No contacts are %s.", presence);
            } else {
                cons_show("Contacts (%s):", presence);
                cons_show_contacts(filtered);
            }
        }
        g_slist_free(filtered);

        // show specific status
    } else {
        GSList* filtered = NULL;

        GSList* curr = list;
        while (curr) {
            PContact contact = curr->data;
            if (strcmp(p_contact_presence(contact), presence) == 0) {
                filtered = g_slist_append(filtered, contact);
            }
            curr = g_slist_next(curr);
        }

        if (group) {
            if (filtered == NULL) {
                cons_show("No contacts in group %s are %s.", group, presence);
            } else {
                cons_show("%s (%s):", group, presence);
                cons_show_contacts(filtered);
            }
        } else {
            if (filtered == NULL) {
                cons_show("No contacts are %s.", presence);
            } else {
                cons_show("Contacts (%s):", presence);
                cons_show_contacts(filtered);
            }
        }
        g_slist_free(filtered);
    }

    g_slist_free(list);
}

gboolean
cmd_who(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
    } else if (window->type == WIN_MUC) {
        _who_room(window, command, args);
    } else {
        _who_roster(window, command, args);
    }

    if (window->type != WIN_CONSOLE && window->type != WIN_MUC) {
        status_bar_new(1, WIN_CONSOLE, "console");
    }

    return TRUE;
}

static void
_cmd_msg_chatwin(const char* const barejid, const char* const msg)
{
    ProfChatWin* chatwin = wins_get_chat(barejid);
    if (!chatwin) {
        // NOTE: This will also start the new OMEMO session and send a MAM request.
        chatwin = chatwin_new(barejid);
    }
    ui_focus_win((ProfWin*)chatwin);

    if (msg) {
        // NOTE: In case the message is OMEMO encrypted, we can't be sure
        // whether the key bundles of the recipient have already been
        // received. In the case that *no* bundles have been received yet,
        // the message won't be sent, and an error is shown to the user.
        // Other cases are not handled here.
        cl_ev_send_msg(chatwin, msg, NULL);
    } else {
#ifdef HAVE_LIBOTR
        // Start the OTR session after this (i.e. the first) message was sent
        if (otr_is_secure(barejid)) {
            chatwin_otr_secured(chatwin, otr_is_trusted(barejid));
        }
#endif // HAVE_LIBOTR
    }
}

gboolean
cmd_msg(ProfWin* window, const char* const command, gchar** args)
{
    char* usr = args[0];
    char* msg = args[1];

    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    // send private message when in MUC room
    if (window->type == WIN_MUC) {
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

        Occupant* occupant = muc_roster_item(mucwin->roomjid, usr);
        if (occupant) {
            // in case of non-anon muc send regular chatmessage
            if (muc_anonymity_type(mucwin->roomjid) == MUC_ANONYMITY_TYPE_NONANONYMOUS) {
                Jid* jidp = jid_create(occupant->jid);

                _cmd_msg_chatwin(jidp->barejid, msg);
                win_println(window, THEME_DEFAULT, "-", "Starting direct message with occupant \"%s\" from room \"%s\" as \"%s\".", usr, mucwin->roomjid, jidp->barejid);
                cons_show("Starting direct message with occupant \"%s\" from room \"%s\" as \"%s\".", usr, mucwin->roomjid, jidp->barejid);

                jid_destroy(jidp);
            } else {
                // otherwise send mucpm
                GString* full_jid = g_string_new(mucwin->roomjid);
                g_string_append(full_jid, "/");
                g_string_append(full_jid, usr);

                ProfPrivateWin* privwin = wins_get_private(full_jid->str);
                if (!privwin) {
                    privwin = (ProfPrivateWin*)wins_new_private(full_jid->str);
                }
                ui_focus_win((ProfWin*)privwin);

                if (msg) {
                    cl_ev_send_priv_msg(privwin, msg, NULL);
                }

                g_string_free(full_jid, TRUE);
            }

        } else {
            win_println(window, THEME_DEFAULT, "-", "No such participant \"%s\" in room.", usr);
        }

        return TRUE;

        // send chat message
    } else {
        char* barejid = roster_barejid_from_name(usr);
        if (barejid == NULL) {
            barejid = usr;
        }

        _cmd_msg_chatwin(barejid, msg);

        return TRUE;
    }
}

gboolean
cmd_group(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    // list all groups
    if (args[1] == NULL) {
        GList* groups = roster_get_groups();
        GList* curr = groups;
        if (curr) {
            cons_show("Groups:");
            while (curr) {
                cons_show("  %s", curr->data);
                curr = g_list_next(curr);
            }

            g_list_free_full(groups, g_free);
        } else {
            cons_show("No groups.");
        }
        return TRUE;
    }

    // show contacts in group
    if (strcmp(args[1], "show") == 0) {
        char* group = args[2];
        if (group == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        GSList* list = roster_get_group(group, ROSTER_ORD_NAME);
        cons_show_roster_group(group, list);
        return TRUE;
    }

    // add contact to group
    if (strcmp(args[1], "add") == 0) {
        char* group = args[2];
        char* contact = args[3];

        if ((group == NULL) || (contact == NULL)) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* barejid = roster_barejid_from_name(contact);
        if (barejid == NULL) {
            barejid = contact;
        }

        PContact pcontact = roster_get_contact(barejid);
        if (pcontact == NULL) {
            cons_show("Contact not found in roster: %s", barejid);
            return TRUE;
        }

        if (p_contact_in_group(pcontact, group)) {
            const char* display_name = p_contact_name_or_jid(pcontact);
            ui_contact_already_in_group(display_name, group);
        } else {
            roster_send_add_to_group(group, pcontact);
        }

        return TRUE;
    }

    // remove contact from group
    if (strcmp(args[1], "remove") == 0) {
        char* group = args[2];
        char* contact = args[3];

        if ((group == NULL) || (contact == NULL)) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* barejid = roster_barejid_from_name(contact);
        if (barejid == NULL) {
            barejid = contact;
        }

        PContact pcontact = roster_get_contact(barejid);
        if (pcontact == NULL) {
            cons_show("Contact not found in roster: %s", barejid);
            return TRUE;
        }

        if (!p_contact_in_group(pcontact, group)) {
            const char* display_name = p_contact_name_or_jid(pcontact);
            ui_contact_not_in_group(display_name, group);
        } else {
            roster_send_remove_from_group(group, pcontact);
        }

        return TRUE;
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_roster(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    // show roster
    if (args[0] == NULL) {
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }

        GSList* list = roster_get_contacts(ROSTER_ORD_NAME);
        cons_show_roster(list);
        g_slist_free(list);
        return TRUE;

        // show roster, only online contacts
    } else if (g_strcmp0(args[0], "online") == 0) {
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }

        GSList* list = roster_get_contacts_online();
        cons_show_roster(list);
        g_slist_free(list);
        return TRUE;

        // set roster size
    } else if (g_strcmp0(args[0], "size") == 0) {
        if (!args[1]) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(args[1], &intval, 1, 99, &err_msg);
        if (res) {
            prefs_set_roster_size(intval);
            cons_show("Roster screen size set to: %d%%", intval);
            if (conn_status == JABBER_CONNECTED && prefs_get_boolean(PREF_ROSTER)) {
                wins_resize_all();
            }
            return TRUE;
        } else {
            cons_show(err_msg);
            free(err_msg);
            return TRUE;
        }

        // set line wrapping
    } else if (g_strcmp0(args[0], "wrap") == 0) {
        if (!args[1]) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            _cmd_set_boolean_preference(args[1], command, "Roster panel line wrap", PREF_ROSTER_WRAP);
            rosterwin_roster();
            return TRUE;
        }

        // header settings
    } else if (g_strcmp0(args[0], "header") == 0) {
        if (g_strcmp0(args[1], "char") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else if (g_strcmp0(args[2], "none") == 0) {
                prefs_clear_roster_header_char();
                cons_show("Roster header char removed.");
                rosterwin_roster();
            } else {
                prefs_set_roster_header_char(args[2]);
                cons_show("Roster header char set to %s.", args[2]);
                rosterwin_roster();
            }
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;

        // contact settings
    } else if (g_strcmp0(args[0], "contact") == 0) {
        if (g_strcmp0(args[1], "char") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else if (g_strcmp0(args[2], "none") == 0) {
                prefs_clear_roster_contact_char();
                cons_show("Roster contact char removed.");
                rosterwin_roster();
            } else {
                prefs_set_roster_contact_char(args[2]);
                cons_show("Roster contact char set to %s.", args[2]);
                rosterwin_roster();
            }
        } else if (g_strcmp0(args[1], "indent") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else {
                int intval = 0;
                char* err_msg = NULL;
                gboolean res = strtoi_range(args[2], &intval, 0, 10, &err_msg);
                if (res) {
                    prefs_set_roster_contact_indent(intval);
                    cons_show("Roster contact indent set to: %d", intval);
                    rosterwin_roster();
                } else {
                    cons_show(err_msg);
                    free(err_msg);
                }
            }
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;

        // resource settings
    } else if (g_strcmp0(args[0], "resource") == 0) {
        if (g_strcmp0(args[1], "char") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else if (g_strcmp0(args[2], "none") == 0) {
                prefs_clear_roster_resource_char();
                cons_show("Roster resource char removed.");
                rosterwin_roster();
            } else {
                prefs_set_roster_resource_char(args[2]);
                cons_show("Roster resource char set to %s.", args[2]);
                rosterwin_roster();
            }
        } else if (g_strcmp0(args[1], "indent") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else {
                int intval = 0;
                char* err_msg = NULL;
                gboolean res = strtoi_range(args[2], &intval, 0, 10, &err_msg);
                if (res) {
                    prefs_set_roster_resource_indent(intval);
                    cons_show("Roster resource indent set to: %d", intval);
                    rosterwin_roster();
                } else {
                    cons_show(err_msg);
                    free(err_msg);
                }
            }
        } else if (g_strcmp0(args[1], "join") == 0) {
            _cmd_set_boolean_preference(args[2], command, "Roster join", PREF_ROSTER_RESOURCE_JOIN);
            rosterwin_roster();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;

        // presence settings
    } else if (g_strcmp0(args[0], "presence") == 0) {
        if (g_strcmp0(args[1], "indent") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else {
                int intval = 0;
                char* err_msg = NULL;
                gboolean res = strtoi_range(args[2], &intval, -1, 10, &err_msg);
                if (res) {
                    prefs_set_roster_presence_indent(intval);
                    cons_show("Roster presence indent set to: %d", intval);
                    rosterwin_roster();
                } else {
                    cons_show(err_msg);
                    free(err_msg);
                }
            }
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;

        // show/hide roster
    } else if ((g_strcmp0(args[0], "show") == 0) || (g_strcmp0(args[0], "hide") == 0)) {
        preference_t pref;
        const char* pref_str;
        if (args[1] == NULL) {
            pref = PREF_ROSTER;
            pref_str = "";
        } else if (g_strcmp0(args[1], "offline") == 0) {
            pref = PREF_ROSTER_OFFLINE;
            pref_str = "offline";
        } else if (g_strcmp0(args[1], "resource") == 0) {
            pref = PREF_ROSTER_RESOURCE;
            pref_str = "resource";
        } else if (g_strcmp0(args[1], "presence") == 0) {
            pref = PREF_ROSTER_PRESENCE;
            pref_str = "presence";
        } else if (g_strcmp0(args[1], "status") == 0) {
            pref = PREF_ROSTER_STATUS;
            pref_str = "status";
        } else if (g_strcmp0(args[1], "empty") == 0) {
            pref = PREF_ROSTER_EMPTY;
            pref_str = "empty";
        } else if (g_strcmp0(args[1], "priority") == 0) {
            pref = PREF_ROSTER_PRIORITY;
            pref_str = "priority";
        } else if (g_strcmp0(args[1], "contacts") == 0) {
            pref = PREF_ROSTER_CONTACTS;
            pref_str = "contacts";
        } else if (g_strcmp0(args[1], "rooms") == 0) {
            pref = PREF_ROSTER_ROOMS;
            pref_str = "rooms";
        } else if (g_strcmp0(args[1], "unsubscribed") == 0) {
            pref = PREF_ROSTER_UNSUBSCRIBED;
            pref_str = "unsubscribed";
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        gboolean val;
        if (g_strcmp0(args[0], "show") == 0) {
            val = TRUE;
        } else { // "hide"
            val = FALSE;
        }

        cons_show("Roster%s%s %s (was %s)", strlen(pref_str) == 0 ? "" : " ", pref_str,
                  val == TRUE ? "enabled" : "disabled",
                  prefs_get_boolean(pref) == TRUE ? "enabled" : "disabled");
        prefs_set_boolean(pref, val);
        if (conn_status == JABBER_CONNECTED) {
            if (pref == PREF_ROSTER) {
                if (val == TRUE) {
                    ui_show_roster();
                } else {
                    ui_hide_roster();
                }
            } else {
                rosterwin_roster();
            }
        }
        return TRUE;

        // roster grouping
    } else if (g_strcmp0(args[0], "by") == 0) {
        if (g_strcmp0(args[1], "group") == 0) {
            cons_show("Grouping roster by roster group");
            prefs_set_string(PREF_ROSTER_BY, "group");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "presence") == 0) {
            cons_show("Grouping roster by presence");
            prefs_set_string(PREF_ROSTER_BY, "presence");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "none") == 0) {
            cons_show("Roster grouping disabled");
            prefs_set_string(PREF_ROSTER_BY, "none");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        // roster item order
    } else if (g_strcmp0(args[0], "order") == 0) {
        if (g_strcmp0(args[1], "name") == 0) {
            cons_show("Ordering roster by name");
            prefs_set_string(PREF_ROSTER_ORDER, "name");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "presence") == 0) {
            cons_show("Ordering roster by presence");
            prefs_set_string(PREF_ROSTER_ORDER, "presence");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

    } else if (g_strcmp0(args[0], "count") == 0) {
        if (g_strcmp0(args[1], "zero") == 0) {
            _cmd_set_boolean_preference(args[2], command, "Roster header zero count", PREF_ROSTER_COUNT_ZERO);
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "unread") == 0) {
            cons_show("Roster header count set to unread");
            prefs_set_string(PREF_ROSTER_COUNT, "unread");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "items") == 0) {
            cons_show("Roster header count set to items");
            prefs_set_string(PREF_ROSTER_COUNT, "items");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Disabling roster header count");
            prefs_set_string(PREF_ROSTER_COUNT, "off");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

    } else if (g_strcmp0(args[0], "color") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Roster consistent colors", PREF_ROSTER_COLOR_NICK);
        ui_show_roster();
        return TRUE;

    } else if (g_strcmp0(args[0], "unread") == 0) {
        if (g_strcmp0(args[1], "before") == 0) {
            cons_show("Roster unread message count: before");
            prefs_set_string(PREF_ROSTER_UNREAD, "before");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "after") == 0) {
            cons_show("Roster unread message count: after");
            prefs_set_string(PREF_ROSTER_UNREAD, "after");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Roster unread message count: off");
            prefs_set_string(PREF_ROSTER_UNREAD, "off");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

    } else if (g_strcmp0(args[0], "private") == 0) {
        if (g_strcmp0(args[1], "char") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else if (g_strcmp0(args[2], "none") == 0) {
                prefs_clear_roster_private_char();
                cons_show("Roster private room chat char removed.");
                rosterwin_roster();
            } else {
                prefs_set_roster_private_char(args[2]);
                cons_show("Roster private room chat char set to %s.", args[2]);
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "room") == 0) {
            cons_show("Showing room private chats under room.");
            prefs_set_string(PREF_ROSTER_PRIVATE, "room");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "group") == 0) {
            cons_show("Showing room private chats as roster group.");
            prefs_set_string(PREF_ROSTER_PRIVATE, "group");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Hiding room private chats in roster.");
            prefs_set_string(PREF_ROSTER_PRIVATE, "off");
            if (conn_status == JABBER_CONNECTED) {
                rosterwin_roster();
            }
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

    } else if (g_strcmp0(args[0], "room") == 0) {
        if (g_strcmp0(args[1], "char") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else if (g_strcmp0(args[2], "none") == 0) {
                prefs_clear_roster_room_char();
                cons_show("Roster room char removed.");
                rosterwin_roster();
            } else {
                prefs_set_roster_room_char(args[2]);
                cons_show("Roster room char set to %s.", args[2]);
                rosterwin_roster();
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "position") == 0) {
            if (g_strcmp0(args[2], "first") == 0) {
                cons_show("Showing rooms first in roster.");
                prefs_set_string(PREF_ROSTER_ROOMS_POS, "first");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else if (g_strcmp0(args[2], "last") == 0) {
                cons_show("Showing rooms last in roster.");
                prefs_set_string(PREF_ROSTER_ROOMS_POS, "last");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else if (g_strcmp0(args[1], "order") == 0) {
            if (g_strcmp0(args[2], "name") == 0) {
                cons_show("Ordering roster rooms by name");
                prefs_set_string(PREF_ROSTER_ROOMS_ORDER, "name");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else if (g_strcmp0(args[2], "unread") == 0) {
                cons_show("Ordering roster rooms by unread messages");
                prefs_set_string(PREF_ROSTER_ROOMS_ORDER, "unread");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else if (g_strcmp0(args[1], "unread") == 0) {
            if (g_strcmp0(args[2], "before") == 0) {
                cons_show("Roster rooms unread message count: before");
                prefs_set_string(PREF_ROSTER_ROOMS_UNREAD, "before");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else if (g_strcmp0(args[2], "after") == 0) {
                cons_show("Roster rooms unread message count: after");
                prefs_set_string(PREF_ROSTER_ROOMS_UNREAD, "after");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Roster rooms unread message count: off");
                prefs_set_string(PREF_ROSTER_ROOMS_UNREAD, "off");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else if (g_strcmp0(args[1], "private") == 0) {
            if (g_strcmp0(args[2], "char") == 0) {
                if (!args[3]) {
                    cons_bad_cmd_usage(command);
                } else if (g_strcmp0(args[3], "none") == 0) {
                    prefs_clear_roster_room_private_char();
                    cons_show("Roster room private char removed.");
                    rosterwin_roster();
                } else {
                    prefs_set_roster_room_private_char(args[3]);
                    cons_show("Roster room private char set to %s.", args[3]);
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else if (g_strcmp0(args[1], "by") == 0) {
            if (g_strcmp0(args[2], "service") == 0) {
                cons_show("Grouping rooms by service");
                prefs_set_string(PREF_ROSTER_ROOMS_BY, "service");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else if (g_strcmp0(args[2], "none") == 0) {
                cons_show("Roster room grouping disabled");
                prefs_set_string(PREF_ROSTER_ROOMS_BY, "none");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else if (g_strcmp0(args[1], "show") == 0) {
            if (g_strcmp0(args[2], "server") == 0) {
                cons_show("Roster room server enabled.");
                prefs_set_boolean(PREF_ROSTER_ROOMS_SERVER, TRUE);
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else if (g_strcmp0(args[1], "hide") == 0) {
            if (g_strcmp0(args[2], "server") == 0) {
                cons_show("Roster room server disabled.");
                prefs_set_boolean(PREF_ROSTER_ROOMS_SERVER, FALSE);
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else if (g_strcmp0(args[1], "use") == 0) {
            if (g_strcmp0(args[2], "jid") == 0) {
                cons_show("Roster room display jid as name.");
                prefs_set_string(PREF_ROSTER_ROOMS_USE_AS_NAME, "jid");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else if (g_strcmp0(args[2], "name") == 0) {
                cons_show("Roster room display room name as name.");
                prefs_set_string(PREF_ROSTER_ROOMS_USE_AS_NAME, "name");
                if (conn_status == JABBER_CONNECTED) {
                    rosterwin_roster();
                }
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                return TRUE;
            }
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        // add contact
    } else if (strcmp(args[0], "add") == 0) {
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }
        char* jid = args[1];
        if (jid == NULL) {
            cons_bad_cmd_usage(command);
        } else {
            char* name = args[2];
            roster_send_add_new(jid, name);
        }
        return TRUE;

        // remove contact
    } else if (strcmp(args[0], "remove") == 0) {
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }
        char* jid = args[1];
        if (jid == NULL) {
            cons_bad_cmd_usage(command);
        } else {
            roster_send_remove(jid);
        }
        return TRUE;

    } else if (strcmp(args[0], "remove_all") == 0) {
        if (g_strcmp0(args[1], "contacts") != 0) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }

        GSList* all = roster_get_contacts(ROSTER_ORD_NAME);
        GSList* curr = all;
        while (curr) {
            PContact contact = curr->data;
            roster_send_remove(p_contact_barejid(contact));
            curr = g_slist_next(curr);
        }

        g_slist_free(all);
        return TRUE;

        // change nickname
    } else if (strcmp(args[0], "nick") == 0) {
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }
        char* jid = args[1];
        if (jid == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* name = args[2];
        if (name == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        // contact does not exist
        PContact contact = roster_get_contact(jid);
        if (contact == NULL) {
            cons_show("Contact not found in roster: %s", jid);
            return TRUE;
        }

        const char* barejid = p_contact_barejid(contact);

        // TODO wait for result stanza before updating
        const char* oldnick = p_contact_name(contact);
        wins_change_nick(barejid, oldnick, name);
        roster_change_name(contact, name);
        GSList* groups = p_contact_groups(contact);
        roster_send_name_change(barejid, name, groups);

        cons_show("Nickname for %s set to: %s.", jid, name);

        return TRUE;

        // remove nickname
    } else if (strcmp(args[0], "clearnick") == 0) {
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }
        char* jid = args[1];
        if (jid == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        // contact does not exist
        PContact contact = roster_get_contact(jid);
        if (contact == NULL) {
            cons_show("Contact not found in roster: %s", jid);
            return TRUE;
        }

        const char* barejid = p_contact_barejid(contact);

        // TODO wait for result stanza before updating
        const char* oldnick = p_contact_name(contact);
        wins_remove_nick(barejid, oldnick);
        roster_change_name(contact, NULL);
        GSList* groups = p_contact_groups(contact);
        roster_send_name_change(barejid, NULL, groups);

        cons_show("Nickname for %s removed.", jid);

        return TRUE;
    } else {
        cons_bad_cmd_usage(command);
        return TRUE;
    }
}

gboolean
cmd_blocked(ProfWin* window, const char* const command, gchar** args)
{
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (!connection_supports(XMPP_FEATURE_BLOCKING)) {
        cons_show("Blocking (%s) not supported by server.", XMPP_FEATURE_BLOCKING);
        return TRUE;
    }

    blocked_report br = BLOCKED_NO_REPORT;

    if (g_strcmp0(args[0], "add") == 0) {
        char* jid = args[1];

        if (jid == NULL && (window->type == WIN_CHAT)) {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            jid = chatwin->barejid;
        }

        if (jid == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        gboolean res = blocked_add(jid, br, NULL);
        if (!res) {
            cons_show("User %s already blocked.", jid);
        }

        return TRUE;
    }

    if (g_strcmp0(args[0], "remove") == 0) {
        if (args[1] == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        gboolean res = blocked_remove(args[1]);
        if (!res) {
            cons_show("User %s is not currently blocked.", args[1]);
        }

        return TRUE;
    }

    if (args[0] && strncmp(args[0], "report-", 7) == 0) {
        char* jid = NULL;
        char* msg = NULL;
        guint argn = g_strv_length(args);

        if (argn >= 2) {
            jid = args[1];
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        if (argn >= 3) {
            msg = args[2];
        }

        if (args[1] && g_strcmp0(args[0], "report-abuse") == 0) {
            br = BLOCKED_REPORT_ABUSE;
        } else if (args[1] && g_strcmp0(args[0], "report-spam") == 0) {
            br = BLOCKED_REPORT_SPAM;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        if (!connection_supports(XMPP_FEATURE_SPAM_REPORTING)) {
            cons_show("Spam reporting (%s) not supported by server.", XMPP_FEATURE_SPAM_REPORTING);
            return TRUE;
        }

        gboolean res = blocked_add(jid, br, msg);
        if (!res) {
            cons_show("User %s already blocked.", args[1]);
        }
        return TRUE;
    }

    GList* blocked = blocked_list();
    GList* curr = blocked;
    if (curr) {
        cons_show("Blocked users:");
        while (curr) {
            cons_show("  %s", curr->data);
            curr = g_list_next(curr);
        }
    } else {
        cons_show("No blocked users.");
    }

    return TRUE;
}

gboolean
cmd_resource(ProfWin* window, const char* const command, gchar** args)
{
    char* cmd = args[0];
    char* setting = NULL;
    if (g_strcmp0(cmd, "message") == 0) {
        setting = args[1];
        if (!setting) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            _cmd_set_boolean_preference(setting, command, "Message resource", PREF_RESOURCE_MESSAGE);
            return TRUE;
        }
    } else if (g_strcmp0(cmd, "title") == 0) {
        setting = args[1];
        if (!setting) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            _cmd_set_boolean_preference(setting, command, "Title resource", PREF_RESOURCE_TITLE);
            return TRUE;
        }
    }

    if (window->type != WIN_CHAT) {
        cons_show("Resource can only be changed in chat windows.");
        return TRUE;
    }

    jabber_conn_status_t conn_status = connection_get_status();
    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;

    if (g_strcmp0(cmd, "set") == 0) {
        char* resource = args[1];
        if (!resource) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

#ifdef HAVE_LIBOTR
        if (otr_is_secure(chatwin->barejid)) {
            cons_show("Cannot choose resource during an OTR session.");
            return TRUE;
        }
#endif

        PContact contact = roster_get_contact(chatwin->barejid);
        if (!contact) {
            cons_show("Cannot choose resource for contact not in roster.");
            return TRUE;
        }

        if (!p_contact_get_resource(contact, resource)) {
            cons_show("No such resource %s.", resource);
            return TRUE;
        }

        chatwin->resource_override = strdup(resource);
        chat_state_free(chatwin->state);
        chatwin->state = chat_state_new();
        chat_session_resource_override(chatwin->barejid, resource);
        return TRUE;

    } else if (g_strcmp0(cmd, "off") == 0) {
        FREE_SET_NULL(chatwin->resource_override);
        chat_state_free(chatwin->state);
        chatwin->state = chat_state_new();
        chat_session_remove(chatwin->barejid);
        return TRUE;
    } else {
        cons_bad_cmd_usage(command);
        return TRUE;
    }
}

static void
_cmd_status_show_status(char* usr)
{
    char* usr_jid = roster_barejid_from_name(usr);
    if (usr_jid == NULL) {
        usr_jid = usr;
    }
    cons_show_status(usr_jid);
}

gboolean
cmd_status_set(ProfWin* window, const char* const command, gchar** args)
{
    char* state = args[1];

    if (g_strcmp0(state, "online") == 0) {
        _update_presence(RESOURCE_ONLINE, "online", args);
    } else if (g_strcmp0(state, "away") == 0) {
        _update_presence(RESOURCE_AWAY, "away", args);
    } else if (g_strcmp0(state, "dnd") == 0) {
        _update_presence(RESOURCE_DND, "dnd", args);
    } else if (g_strcmp0(state, "chat") == 0) {
        _update_presence(RESOURCE_CHAT, "chat", args);
    } else if (g_strcmp0(state, "xa") == 0) {
        _update_presence(RESOURCE_XA, "xa", args);
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_status_get(ProfWin* window, const char* const command, gchar** args)
{
    char* usr = args[1];

    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    switch (window->type) {
    case WIN_MUC:
        if (usr) {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            Occupant* occupant = muc_roster_item(mucwin->roomjid, usr);
            if (occupant) {
                win_show_occupant(window, occupant);
            } else {
                win_println(window, THEME_DEFAULT, "-", "No such participant \"%s\" in room.", usr);
            }
        } else {
            win_println(window, THEME_DEFAULT, "-", "You must specify a nickname.");
        }
        break;
    case WIN_CHAT:
        if (usr) {
            _cmd_status_show_status(usr);
        } else {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
            PContact pcontact = roster_get_contact(chatwin->barejid);
            if (pcontact) {
                win_show_contact(window, pcontact);
            } else {
                win_println(window, THEME_DEFAULT, "-", "Error getting contact info.");
            }
        }
        break;
    case WIN_PRIVATE:
        if (usr) {
            _cmd_status_show_status(usr);
        } else {
            ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
            assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
            Jid* jid = jid_create(privatewin->fulljid);
            Occupant* occupant = muc_roster_item(jid->barejid, jid->resourcepart);
            if (occupant) {
                win_show_occupant(window, occupant);
            } else {
                win_println(window, THEME_DEFAULT, "-", "Error getting contact info.");
            }
            jid_destroy(jid);
        }
        break;
    case WIN_CONSOLE:
        if (usr) {
            _cmd_status_show_status(usr);
        } else {
            cons_bad_cmd_usage(command);
        }
        break;
    default:
        break;
    }

    return TRUE;
}

static void
_cmd_info_show_contact(char* usr)
{
    char* usr_jid = roster_barejid_from_name(usr);
    if (usr_jid == NULL) {
        usr_jid = usr;
    }
    PContact pcontact = roster_get_contact(usr_jid);
    if (pcontact) {
        cons_show_info(pcontact);
    } else {
        cons_show("No such contact \"%s\" in roster.", usr);
    }
}

gboolean
cmd_info(ProfWin* window, const char* const command, gchar** args)
{
    char* usr = args[0];

    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    switch (window->type) {
    case WIN_MUC:
        if (usr) {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            Occupant* occupant = muc_roster_item(mucwin->roomjid, usr);
            if (occupant) {
                win_show_occupant_info(window, mucwin->roomjid, occupant);
            } else {
                win_println(window, THEME_DEFAULT, "-", "No such occupant \"%s\" in room.", usr);
            }
        } else {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            iq_room_info_request(mucwin->roomjid, TRUE);
            mucwin_info(mucwin);
            return TRUE;
        }
        break;
    case WIN_CHAT:
        if (usr) {
            _cmd_info_show_contact(usr);
        } else {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
            PContact pcontact = roster_get_contact(chatwin->barejid);
            if (pcontact) {
                win_show_info(window, pcontact);
            } else {
                win_println(window, THEME_DEFAULT, "-", "Error getting contact info.");
            }
        }
        break;
    case WIN_PRIVATE:
        if (usr) {
            _cmd_info_show_contact(usr);
        } else {
            ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
            assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
            Jid* jid = jid_create(privatewin->fulljid);
            Occupant* occupant = muc_roster_item(jid->barejid, jid->resourcepart);
            if (occupant) {
                win_show_occupant_info(window, jid->barejid, occupant);
            } else {
                win_println(window, THEME_DEFAULT, "-", "Error getting contact info.");
            }
            jid_destroy(jid);
        }
        break;
    case WIN_CONSOLE:
        if (usr) {
            _cmd_info_show_contact(usr);
        } else {
            cons_bad_cmd_usage(command);
        }
        break;
    default:
        break;
    }

    return TRUE;
}

gboolean
cmd_caps(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();
    Occupant* occupant = NULL;

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    switch (window->type) {
    case WIN_MUC:
        if (args[0]) {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            occupant = muc_roster_item(mucwin->roomjid, args[0]);
            if (occupant) {
                Jid* jidp = jid_create_from_bare_and_resource(mucwin->roomjid, args[0]);
                cons_show_caps(jidp->fulljid, occupant->presence);
                jid_destroy(jidp);
            } else {
                cons_show("No such participant \"%s\" in room.", args[0]);
            }
        } else {
            cons_show("No nickname supplied to /caps in chat room.");
        }
        break;
    case WIN_CHAT:
    case WIN_CONSOLE:
        if (args[0]) {
            Jid* jid = jid_create(args[0]);

            if (jid->fulljid == NULL) {
                cons_show("You must provide a full jid to the /caps command.");
            } else {
                PContact pcontact = roster_get_contact(jid->barejid);
                if (pcontact == NULL) {
                    cons_show("Contact not found in roster: %s", jid->barejid);
                } else {
                    Resource* resource = p_contact_get_resource(pcontact, jid->resourcepart);
                    if (resource == NULL) {
                        cons_show("Could not find resource %s, for contact %s", jid->barejid, jid->resourcepart);
                    } else {
                        cons_show_caps(jid->fulljid, resource->presence);
                    }
                }
            }
            jid_destroy(jid);
        } else {
            cons_show("You must provide a jid to the /caps command.");
        }
        break;
    case WIN_PRIVATE:
        if (args[0]) {
            cons_show("No parameter needed to /caps when in private chat.");
        } else {
            ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
            assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
            Jid* jid = jid_create(privatewin->fulljid);
            if (jid) {
                occupant = muc_roster_item(jid->barejid, jid->resourcepart);
                cons_show_caps(jid->resourcepart, occupant->presence);
                jid_destroy(jid);
            }
        }
        break;
    default:
        break;
    }

    return TRUE;
}

static void
_send_software_version_iq_to_fulljid(char* request)
{
    char* mybarejid = connection_get_barejid();
    Jid* jid = jid_create(request);

    if (jid == NULL || jid->fulljid == NULL) {
        cons_show("You must provide a full jid to the /software command.");
    } else if (g_strcmp0(jid->barejid, mybarejid) == 0) {
        cons_show("Cannot request software version for yourself.");
    } else {
        iq_send_software_version(jid->fulljid);
    }
    free(mybarejid);
    jid_destroy(jid);
}

gboolean
cmd_software(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    switch (window->type) {
    case WIN_MUC:
        if (args[0]) {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            Occupant* occupant = muc_roster_item(mucwin->roomjid, args[0]);
            if (occupant) {
                Jid* jid = jid_create_from_bare_and_resource(mucwin->roomjid, args[0]);
                iq_send_software_version(jid->fulljid);
                jid_destroy(jid);
            } else {
                cons_show("No such participant \"%s\" in room.", args[0]);
            }
        } else {
            cons_show("No nickname supplied to /software in chat room.");
        }
        break;
    case WIN_CHAT:
        if (args[0]) {
            _send_software_version_iq_to_fulljid(args[0]);
            break;
        } else {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);

            char* resource = NULL;
            ChatSession* session = chat_session_get(chatwin->barejid);
            if (chatwin->resource_override) {
                resource = chatwin->resource_override;
            } else if (session && session->resource) {
                resource = session->resource;
            }

            if (resource) {
                GString* fulljid = g_string_new(chatwin->barejid);
                g_string_append_printf(fulljid, "/%s", resource);
                iq_send_software_version(fulljid->str);
                g_string_free(fulljid, TRUE);
            } else {
                win_println(window, THEME_DEFAULT, "-", "Unknown resource for /software command. See /help resource.");
            }
            break;
        }
    case WIN_CONSOLE:
        if (args[0]) {
            _send_software_version_iq_to_fulljid(args[0]);
        } else {
            cons_show("You must provide a jid to the /software command.");
        }
        break;
    case WIN_PRIVATE:
        if (args[0]) {
            cons_show("No parameter needed to /software when in private chat.");
        } else {
            ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
            assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
            iq_send_software_version(privatewin->fulljid);
        }
        break;
    default:
        break;
    }

    return TRUE;
}

gboolean
cmd_serversoftware(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (args[0]) {
        iq_send_software_version(args[0]);
    } else {
        cons_show("You must provide a jid to the /serversoftware command.");
    }

    return TRUE;
}

gboolean
cmd_join(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();
    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (args[0] == NULL) {
        char* account_name = session_get_account_name();
        ProfAccount* account = accounts_get_account(account_name);
        if (account->muc_service) {
            GString* room_str = g_string_new("");
            char* uuid = connection_create_uuid();
            g_string_append_printf(room_str, "private-chat-%s@%s", uuid, account->muc_service);
            connection_free_uuid(uuid);

            presence_join_room(room_str->str, account->muc_nick, NULL);
            muc_join(room_str->str, account->muc_nick, NULL, FALSE);

            g_string_free(room_str, TRUE);
            account_free(account);
        } else {
            cons_show("Account MUC service property not found.");
        }

        return TRUE;
    }

    Jid* room_arg = jid_create(args[0]);
    if (room_arg == NULL) {
        cons_show_error("Specified room has incorrect format.");
        cons_show("");
        return TRUE;
    }

    char* room = NULL;
    char* nick = NULL;
    char* passwd = NULL;
    char* account_name = session_get_account_name();
    ProfAccount* account = accounts_get_account(account_name);

    // full room jid supplied (room@server)
    if (room_arg->localpart) {
        room = g_strdup(args[0]);

        // server not supplied (room), use account preference
    } else if (account->muc_service) {
        GString* room_str = g_string_new("");
        g_string_append(room_str, args[0]);
        g_string_append(room_str, "@");
        g_string_append(room_str, account->muc_service);
        room = room_str->str;
        g_string_free(room_str, FALSE);

        // no account preference
    } else {
        cons_show("Account MUC service property not found.");
        return TRUE;
    }

    // Additional args supplied
    gchar* opt_keys[] = { "nick", "password", NULL };
    gboolean parsed;

    GHashTable* options = parse_options(&args[1], opt_keys, &parsed);
    if (!parsed) {
        cons_bad_cmd_usage(command);
        cons_show("");
        g_free(room);
        jid_destroy(room_arg);
        return TRUE;
    }

    nick = g_hash_table_lookup(options, "nick");
    passwd = g_hash_table_lookup(options, "password");

    options_destroy(options);

    // In the case that a nick wasn't provided by the optional args...
    if (!nick) {
        nick = account->muc_nick;
    }

    // When no password, check for invite with password
    if (!passwd) {
        passwd = muc_invite_password(room);
    }

    if (!muc_active(room)) {
        presence_join_room(room, nick, passwd);
        muc_join(room, nick, passwd, FALSE);
        iq_room_affiliation_list(room, "member", false);
        iq_room_affiliation_list(room, "admin", false);
        iq_room_affiliation_list(room, "owner", false);
    } else if (muc_roster_complete(room)) {
        ui_switch_to_room(room);
    }

    g_free(room);
    jid_destroy(room_arg);
    account_free(account);

    return TRUE;
}

gboolean
cmd_invite(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (g_strcmp0(args[0], "send") == 0) {
        char* contact = args[1];
        char* reason = args[2];

        if (window->type != WIN_MUC) {
            cons_show("You must be in a chat room to send an invite.");
            return TRUE;
        }

        char* usr_jid = roster_barejid_from_name(contact);
        if (usr_jid == NULL) {
            usr_jid = contact;
        }

        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
        message_send_invite(mucwin->roomjid, usr_jid, reason);
        if (reason) {
            cons_show("Room invite sent, contact: %s, room: %s, reason: \"%s\".",
                      contact, mucwin->roomjid, reason);
        } else {
            cons_show("Room invite sent, contact: %s, room: %s.",
                      contact, mucwin->roomjid);
        }
    } else if (g_strcmp0(args[0], "list") == 0) {
        GList* invites = muc_invites();
        cons_show_room_invites(invites);
        g_list_free_full(invites, g_free);
    } else if (g_strcmp0(args[0], "decline") == 0) {
        if (!muc_invites_contain(args[1])) {
            cons_show("No such invite exists.");
        } else {
            muc_invites_remove(args[1]);
            cons_show("Declined invite to %s.", args[1]);
        }
    }

    return TRUE;
}

gboolean
cmd_form_field(ProfWin* window, char* tag, gchar** args)
{
    if (window->type != WIN_CONFIG) {
        return TRUE;
    }

    ProfConfWin* confwin = (ProfConfWin*)window;
    DataForm* form = confwin->form;
    if (form) {
        if (!form_tag_exists(form, tag)) {
            win_println(window, THEME_DEFAULT, "-", "Form does not contain a field with tag %s", tag);
            return TRUE;
        }

        form_field_type_t field_type = form_get_field_type(form, tag);
        char* cmd = NULL;
        char* value = NULL;
        gboolean valid = FALSE;
        gboolean added = FALSE;
        gboolean removed = FALSE;

        switch (field_type) {
        case FIELD_BOOLEAN:
            value = args[0];
            if (g_strcmp0(value, "on") == 0) {
                form_set_value(form, tag, "1");
                win_println(window, THEME_DEFAULT, "-", "Field updated...");
                confwin_show_form_field(confwin, form, tag);
            } else if (g_strcmp0(value, "off") == 0) {
                form_set_value(form, tag, "0");
                win_println(window, THEME_DEFAULT, "-", "Field updated...");
                confwin_show_form_field(confwin, form, tag);
            } else {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
            }
            break;

        case FIELD_TEXT_PRIVATE:
        case FIELD_TEXT_SINGLE:
        case FIELD_JID_SINGLE:
            value = args[0];
            if (value == NULL) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
            } else {
                form_set_value(form, tag, value);
                win_println(window, THEME_DEFAULT, "-", "Field updated...");
                confwin_show_form_field(confwin, form, tag);
            }
            break;
        case FIELD_LIST_SINGLE:
            value = args[0];
            if ((value == NULL) || !form_field_contains_option(form, tag, value)) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
            } else {
                form_set_value(form, tag, value);
                win_println(window, THEME_DEFAULT, "-", "Field updated...");
                confwin_show_form_field(confwin, form, tag);
            }
            break;

        case FIELD_TEXT_MULTI:
            cmd = args[0];
            if (cmd) {
                value = args[1];
            }
            if (!_string_matches_one_of(NULL, cmd, FALSE, "add", "remove", NULL)) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
                break;
            }
            if (value == NULL) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
                break;
            }
            if (g_strcmp0(cmd, "add") == 0) {
                form_add_value(form, tag, value);
                win_println(window, THEME_DEFAULT, "-", "Field updated...");
                confwin_show_form_field(confwin, form, tag);
                break;
            }
            if (g_strcmp0(args[0], "remove") == 0) {
                if (!g_str_has_prefix(value, "val")) {
                    win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                    confwin_field_help(confwin, tag);
                    win_println(window, THEME_DEFAULT, "-", "");
                    break;
                }
                if (strlen(value) < 4) {
                    win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                    confwin_field_help(confwin, tag);
                    win_println(window, THEME_DEFAULT, "-", "");
                    break;
                }

                int index = strtol(&value[3], NULL, 10);
                if ((index < 1) || (index > form_get_value_count(form, tag))) {
                    win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                    confwin_field_help(confwin, tag);
                    win_println(window, THEME_DEFAULT, "-", "");
                    break;
                }

                removed = form_remove_text_multi_value(form, tag, index);
                if (removed) {
                    win_println(window, THEME_DEFAULT, "-", "Field updated...");
                    confwin_show_form_field(confwin, form, tag);
                } else {
                    win_println(window, THEME_DEFAULT, "-", "Could not remove %s from %s", value, tag);
                }
            }
            break;
        case FIELD_LIST_MULTI:
            cmd = args[0];
            if (cmd) {
                value = args[1];
            }
            if (!_string_matches_one_of(NULL, cmd, FALSE, "add", "remove", NULL)) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
                break;
            }
            if (value == NULL) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
                break;
            }
            if (g_strcmp0(args[0], "add") == 0) {
                valid = form_field_contains_option(form, tag, value);
                if (valid) {
                    added = form_add_unique_value(form, tag, value);
                    if (added) {
                        win_println(window, THEME_DEFAULT, "-", "Field updated...");
                        confwin_show_form_field(confwin, form, tag);
                    } else {
                        win_println(window, THEME_DEFAULT, "-", "Value %s already selected for %s", value, tag);
                    }
                } else {
                    win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                    confwin_field_help(confwin, tag);
                    win_println(window, THEME_DEFAULT, "-", "");
                }
                break;
            }
            if (g_strcmp0(args[0], "remove") == 0) {
                valid = form_field_contains_option(form, tag, value);
                if (valid == TRUE) {
                    removed = form_remove_value(form, tag, value);
                    if (removed) {
                        win_println(window, THEME_DEFAULT, "-", "Field updated...");
                        confwin_show_form_field(confwin, form, tag);
                    } else {
                        win_println(window, THEME_DEFAULT, "-", "Value %s is not currently set for %s", value, tag);
                    }
                } else {
                    win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                    confwin_field_help(confwin, tag);
                    win_println(window, THEME_DEFAULT, "-", "");
                }
            }
            break;
        case FIELD_JID_MULTI:
            cmd = args[0];
            if (cmd) {
                value = args[1];
            }
            if (!_string_matches_one_of(NULL, cmd, FALSE, "add", "remove", NULL)) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
                break;
            }
            if (value == NULL) {
                win_println(window, THEME_DEFAULT, "-", "Invalid command, usage:");
                confwin_field_help(confwin, tag);
                win_println(window, THEME_DEFAULT, "-", "");
                break;
            }
            if (g_strcmp0(args[0], "add") == 0) {
                added = form_add_unique_value(form, tag, value);
                if (added) {
                    win_println(window, THEME_DEFAULT, "-", "Field updated...");
                    confwin_show_form_field(confwin, form, tag);
                } else {
                    win_println(window, THEME_DEFAULT, "-", "JID %s already exists in %s", value, tag);
                }
                break;
            }
            if (g_strcmp0(args[0], "remove") == 0) {
                removed = form_remove_value(form, tag, value);
                if (removed) {
                    win_println(window, THEME_DEFAULT, "-", "Field updated...");
                    confwin_show_form_field(confwin, form, tag);
                } else {
                    win_println(window, THEME_DEFAULT, "-", "Field %s does not contain %s", tag, value);
                }
            }
            break;

        default:
            break;
        }
    }

    return TRUE;
}

gboolean
cmd_form(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_CONFIG) {
        cons_show("Command '/form' does not apply to this window.");
        return TRUE;
    }

    if (!_string_matches_one_of(NULL, args[0], FALSE, "submit", "cancel", "show", "help", NULL)) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    ProfConfWin* confwin = (ProfConfWin*)window;
    assert(confwin->memcheck == PROFCONFWIN_MEMCHECK);

    if (g_strcmp0(args[0], "show") == 0) {
        confwin_show_form(confwin);
        return TRUE;
    }

    if (g_strcmp0(args[0], "help") == 0) {
        char* tag = args[1];
        if (tag) {
            confwin_field_help(confwin, tag);
        } else {
            confwin_form_help(confwin);

            gchar** help_text = NULL;
            Command* command = cmd_get("/form");

            if (command) {
                help_text = command->help.synopsis;
            }

            ui_show_lines((ProfWin*)confwin, help_text);
        }
        win_println(window, THEME_DEFAULT, "-", "");
        return TRUE;
    }

    if (g_strcmp0(args[0], "submit") == 0 && confwin->submit != NULL) {
        confwin->submit(confwin);
    }

    if (g_strcmp0(args[0], "cancel") == 0 && confwin->cancel != NULL) {
        confwin->cancel(confwin);
    }

    if ((g_strcmp0(args[0], "submit") == 0) || (g_strcmp0(args[0], "cancel") == 0)) {
        if (confwin->form) {
            cmd_ac_remove_form_fields(confwin->form);
        }

        int num = wins_get_num(window);

        ProfWin* new_current = (ProfWin*)wins_get_muc(confwin->roomjid);
        if (!new_current) {
            new_current = wins_get_console();
        }
        ui_focus_win(new_current);
        wins_close_by_num(num);
        wins_tidy();
    }

    return TRUE;
}

gboolean
cmd_kick(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_MUC) {
        cons_show("Command '/kick' only applies in chat rooms.");
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

    char* nick = args[0];
    if (nick) {
        if (muc_roster_contains_nick(mucwin->roomjid, nick)) {
            char* reason = args[1];
            iq_room_kick_occupant(mucwin->roomjid, nick, reason);
        } else {
            win_println(window, THEME_DEFAULT, "!", "Occupant does not exist: %s", nick);
        }
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_ban(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_MUC) {
        cons_show("Command '/ban' only applies in chat rooms.");
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

    char* jid = args[0];
    if (jid) {
        char* reason = args[1];
        iq_room_affiliation_set(mucwin->roomjid, jid, "outcast", reason);
    } else {
        cons_bad_cmd_usage(command);
    }
    return TRUE;
}

gboolean
cmd_subject(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_MUC) {
        cons_show("Command '/room' does not apply to this window.");
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

    if (args[0] == NULL) {
        char* subject = muc_subject(mucwin->roomjid);
        if (subject) {
            win_print(window, THEME_ROOMINFO, "!", "Room subject: ");
            win_appendln(window, THEME_DEFAULT, "%s", subject);
        } else {
            win_println(window, THEME_ROOMINFO, "!", "Room has no subject");
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "set") == 0) {
        if (args[1]) {
            message_send_groupchat_subject(mucwin->roomjid, args[1]);
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "edit") == 0) {
        if (args[1]) {
            message_send_groupchat_subject(mucwin->roomjid, args[1]);
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "editor") == 0) {
        gchar* message = NULL;
        char* subject = muc_subject(mucwin->roomjid);

        if (get_message_from_editor(subject, &message)) {
            return TRUE;
        }

        if (message) {
            message_send_groupchat_subject(mucwin->roomjid, message);
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "prepend") == 0) {
        if (args[1]) {
            char* old_subject = muc_subject(mucwin->roomjid);
            if (old_subject) {
                GString* new_subject = g_string_new(args[1]);
                g_string_append(new_subject, old_subject);
                message_send_groupchat_subject(mucwin->roomjid, new_subject->str);
                g_string_free(new_subject, TRUE);
            } else {
                win_print(window, THEME_ROOMINFO, "!", "Room does not have a subject, use /subject set <subject>");
            }
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "append") == 0) {
        if (args[1]) {
            char* old_subject = muc_subject(mucwin->roomjid);
            if (old_subject) {
                GString* new_subject = g_string_new(old_subject);
                g_string_append(new_subject, args[1]);
                message_send_groupchat_subject(mucwin->roomjid, new_subject->str);
                g_string_free(new_subject, TRUE);
            } else {
                win_print(window, THEME_ROOMINFO, "!", "Room does not have a subject, use /subject set <subject>");
            }
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "clear") == 0) {
        message_send_groupchat_subject(mucwin->roomjid, NULL);
        return TRUE;
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_affiliation(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_MUC) {
        cons_show("Command '/affiliation' does not apply to this window.");
        return TRUE;
    }

    char* cmd = args[0];
    if (cmd == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    char* affiliation = args[1];
    if (!_string_matches_one_of(NULL, affiliation, TRUE, "owner", "admin", "member", "none", "outcast", NULL)) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

    if (g_strcmp0(cmd, "list") == 0) {
        if (!affiliation) {
            iq_room_affiliation_list(mucwin->roomjid, "owner", true);
            iq_room_affiliation_list(mucwin->roomjid, "admin", true);
            iq_room_affiliation_list(mucwin->roomjid, "member", true);
            iq_room_affiliation_list(mucwin->roomjid, "outcast", true);
        } else if (g_strcmp0(affiliation, "none") == 0) {
            win_println(window, THEME_DEFAULT, "!", "Cannot list users with no affiliation.");
        } else {
            iq_room_affiliation_list(mucwin->roomjid, affiliation, true);
        }
        return TRUE;
    }

    if (g_strcmp0(cmd, "set") == 0) {
        if (!affiliation) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* jid = args[2];
        if (jid == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            char* reason = args[3];
            iq_room_affiliation_set(mucwin->roomjid, jid, affiliation, reason);
            return TRUE;
        }
    }

    if (g_strcmp0(cmd, "request") == 0) {
        message_request_voice(mucwin->roomjid);
        return TRUE;
    }

    if (g_strcmp0(cmd, "register") == 0) {
        iq_muc_register_nick(mucwin->roomjid);
        return TRUE;
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_role(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_MUC) {
        cons_show("Command '/role' does not apply to this window.");
        return TRUE;
    }

    char* cmd = args[0];
    if (cmd == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    char* role = args[1];
    if (!_string_matches_one_of(NULL, role, TRUE, "visitor", "participant", "moderator", "none", NULL)) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

    if (g_strcmp0(cmd, "list") == 0) {
        if (!role) {
            iq_room_role_list(mucwin->roomjid, "moderator");
            iq_room_role_list(mucwin->roomjid, "participant");
            iq_room_role_list(mucwin->roomjid, "visitor");
        } else if (g_strcmp0(role, "none") == 0) {
            win_println(window, THEME_DEFAULT, "!", "Cannot list users with no role.");
        } else {
            iq_room_role_list(mucwin->roomjid, role);
        }
        return TRUE;
    }

    if (g_strcmp0(cmd, "set") == 0) {
        if (!role) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* nick = args[2];
        if (nick == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            char* reason = args[3];
            iq_room_role_set(mucwin->roomjid, nick, role, reason);
            return TRUE;
        }
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_room(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_MUC) {
        cons_show("Command '/room' does not apply to this window.");
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

    if (g_strcmp0(args[0], "accept") == 0) {
        gboolean requires_config = muc_requires_config(mucwin->roomjid);
        if (!requires_config) {
            win_println(window, THEME_ROOMINFO, "!", "Current room does not require configuration.");
            return TRUE;
        } else {
            iq_confirm_instant_room(mucwin->roomjid);
            muc_set_requires_config(mucwin->roomjid, FALSE);
            win_println(window, THEME_ROOMINFO, "!", "Room unlocked.");
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "destroy") == 0) {
        iq_destroy_room(mucwin->roomjid);
        return TRUE;
    } else if (g_strcmp0(args[0], "config") == 0) {
        ProfConfWin* confwin = wins_get_conf(mucwin->roomjid);

        if (confwin) {
            ui_focus_win((ProfWin*)confwin);
        } else {
            iq_request_room_config_form(mucwin->roomjid);
        }
        return TRUE;
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_occupants(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "size") == 0) {
        if (!args[1]) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            int intval = 0;
            char* err_msg = NULL;
            gboolean res = strtoi_range(args[1], &intval, 1, 99, &err_msg);
            if (res) {
                prefs_set_occupants_size(intval);
                cons_show("Occupants screen size set to: %d%%", intval);
                wins_resize_all();
                return TRUE;
            } else {
                cons_show(err_msg);
                free(err_msg);
                return TRUE;
            }
        }
    }

    if (g_strcmp0(args[0], "indent") == 0) {
        if (!args[1]) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            int intval = 0;
            char* err_msg = NULL;
            gboolean res = strtoi_range(args[1], &intval, 0, 10, &err_msg);
            if (res) {
                prefs_set_occupants_indent(intval);
                cons_show("Occupants indent set to: %d", intval);

                occupantswin_occupants_all();
            } else {
                cons_show(err_msg);
                free(err_msg);
            }
            return TRUE;
        }
    }

    if (g_strcmp0(args[0], "wrap") == 0) {
        if (!args[1]) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            _cmd_set_boolean_preference(args[1], command, "Occupants panel line wrap", PREF_OCCUPANTS_WRAP);
            occupantswin_occupants_all();
            return TRUE;
        }
    }

    if (g_strcmp0(args[0], "char") == 0) {
        if (!args[1]) {
            cons_bad_cmd_usage(command);
        } else if (g_strcmp0(args[1], "none") == 0) {
            prefs_clear_occupants_char();
            cons_show("Occupants char removed.");

            occupantswin_occupants_all();
        } else {
            prefs_set_occupants_char(args[1]);
            cons_show("Occupants char set to %s.", args[1]);

            occupantswin_occupants_all();
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "color") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Occupants consistent colors", PREF_OCCUPANTS_COLOR_NICK);
        occupantswin_occupants_all();
        return TRUE;
    }

    if (g_strcmp0(args[0], "default") == 0) {
        if (g_strcmp0(args[1], "show") == 0) {
            if (g_strcmp0(args[2], "jid") == 0) {
                cons_show("Occupant jids enabled.");
                prefs_set_boolean(PREF_OCCUPANTS_JID, TRUE);
            } else if (g_strcmp0(args[2], "offline") == 0) {
                cons_show("Occupants offline enabled.");
                prefs_set_boolean(PREF_OCCUPANTS_OFFLINE, TRUE);
            } else {
                cons_show("Occupant list enabled.");
                prefs_set_boolean(PREF_OCCUPANTS, TRUE);
            }
            return TRUE;
        } else if (g_strcmp0(args[1], "hide") == 0) {
            if (g_strcmp0(args[2], "jid") == 0) {
                cons_show("Occupant jids disabled.");
                prefs_set_boolean(PREF_OCCUPANTS_JID, FALSE);
            } else if (g_strcmp0(args[2], "offline") == 0) {
                cons_show("Occupants offline disabled.");
                prefs_set_boolean(PREF_OCCUPANTS_OFFLINE, FALSE);
            } else {
                cons_show("Occupant list disabled.");
                prefs_set_boolean(PREF_OCCUPANTS, FALSE);
            }
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    }

    // header settings
    if (g_strcmp0(args[0], "header") == 0) {
        if (g_strcmp0(args[1], "char") == 0) {
            if (!args[2]) {
                cons_bad_cmd_usage(command);
            } else if (g_strcmp0(args[2], "none") == 0) {
                prefs_clear_occupants_header_char();
                cons_show("Occupants header char removed.");

                occupantswin_occupants_all();
            } else {
                prefs_set_occupants_header_char(args[2]);
                cons_show("Occupants header char set to %s.", args[2]);

                occupantswin_occupants_all();
            }
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    jabber_conn_status_t conn_status = connection_get_status();
    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (window->type != WIN_MUC) {
        cons_show("Cannot apply setting when not in chat room.");
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

    if (g_strcmp0(args[0], "show") == 0) {
        if (g_strcmp0(args[1], "jid") == 0) {
            mucwin->showjid = TRUE;
            mucwin_update_occupants(mucwin);
        } else if (g_strcmp0(args[1], "offline") == 0) {
            mucwin->showoffline = TRUE;
            mucwin_update_occupants(mucwin);
        } else {
            mucwin_show_occupants(mucwin);
        }
    } else if (g_strcmp0(args[0], "hide") == 0) {
        if (g_strcmp0(args[1], "jid") == 0) {
            mucwin->showjid = FALSE;
            mucwin_update_occupants(mucwin);
        } else if (g_strcmp0(args[1], "offline") == 0) {
            mucwin->showoffline = FALSE;
            mucwin_update_occupants(mucwin);
        } else {
            mucwin_hide_occupants(mucwin);
        }
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_rooms(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    gchar* service = NULL;
    gchar* filter = NULL;
    if (args[0] != NULL) {
        if (g_strcmp0(args[0], "service") == 0) {
            if (args[1] == NULL) {
                cons_bad_cmd_usage(command);
                cons_show("");
                return TRUE;
            }
            service = g_strdup(args[1]);
        } else if (g_strcmp0(args[0], "filter") == 0) {
            if (args[1] == NULL) {
                cons_bad_cmd_usage(command);
                cons_show("");
                return TRUE;
            }
            filter = g_strdup(args[1]);
        } else if (g_strcmp0(args[0], "cache") == 0) {
            if (g_strv_length(args) != 2) {
                cons_bad_cmd_usage(command);
                cons_show("");
                return TRUE;
            } else if (g_strcmp0(args[1], "on") == 0) {
                prefs_set_boolean(PREF_ROOM_LIST_CACHE, TRUE);
                cons_show("Rooms list cache enabled.");
                return TRUE;
            } else if (g_strcmp0(args[1], "off") == 0) {
                prefs_set_boolean(PREF_ROOM_LIST_CACHE, FALSE);
                cons_show("Rooms list cache disabled.");
                return TRUE;
            } else if (g_strcmp0(args[1], "clear") == 0) {
                iq_rooms_cache_clear();
                cons_show("Rooms list cache cleared.");
                return TRUE;
            } else {
                cons_bad_cmd_usage(command);
                cons_show("");
                return TRUE;
            }
        } else {
            cons_bad_cmd_usage(command);
            cons_show("");
            return TRUE;
        }
    }
    if (g_strv_length(args) >= 3) {
        if (g_strcmp0(args[2], "service") == 0) {
            if (args[3] == NULL) {
                cons_bad_cmd_usage(command);
                cons_show("");
                g_free(service);
                g_free(filter);
                return TRUE;
            }
            g_free(service);
            service = g_strdup(args[3]);
        } else if (g_strcmp0(args[2], "filter") == 0) {
            if (args[3] == NULL) {
                cons_bad_cmd_usage(command);
                cons_show("");
                g_free(service);
                g_free(filter);
                return TRUE;
            }
            g_free(filter);
            filter = g_strdup(args[3]);
        } else {
            cons_bad_cmd_usage(command);
            cons_show("");
            g_free(service);
            g_free(filter);
            return TRUE;
        }
    }

    if (service == NULL) {
        ProfAccount* account = accounts_get_account(session_get_account_name());
        if (account->muc_service) {
            service = g_strdup(account->muc_service);
            account_free(account);
        } else {
            cons_show("Account MUC service property not found.");
            account_free(account);
            g_free(service);
            g_free(filter);
            return TRUE;
        }
    }

    cons_show("");
    if (filter) {
        cons_show("Room list request sent: %s, filter: '%s'", service, filter);
    } else {
        cons_show("Room list request sent: %s", service);
    }
    iq_room_list_request(service, filter);

    g_free(service);
    g_free(filter);

    return TRUE;
}

gboolean
cmd_bookmark(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        cons_alert(NULL);
        return TRUE;
    }

    int num_args = g_strv_length(args);
    gchar* cmd = args[0];
    if (window->type == WIN_MUC
        && num_args < 2
        && (cmd == NULL || g_strcmp0(cmd, "add") == 0)) {
        // default to current nickname, password, and autojoin "on"
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
        char* nick = muc_nick(mucwin->roomjid);
        char* password = muc_password(mucwin->roomjid);
        gboolean added = bookmark_add(mucwin->roomjid, nick, password, "on", NULL);
        if (added) {
            win_println(window, THEME_DEFAULT, "!", "Bookmark added for %s.", mucwin->roomjid);
        } else {
            win_println(window, THEME_DEFAULT, "!", "Bookmark already exists for %s.", mucwin->roomjid);
        }
        return TRUE;
    }

    if (window->type == WIN_MUC
        && num_args < 2
        && g_strcmp0(cmd, "remove") == 0) {
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
        gboolean removed = bookmark_remove(mucwin->roomjid);
        if (removed) {
            win_println(window, THEME_DEFAULT, "!", "Bookmark removed for %s.", mucwin->roomjid);
        } else {
            win_println(window, THEME_DEFAULT, "!", "Bookmark does not exist for %s.", mucwin->roomjid);
        }
        return TRUE;
    }

    if (cmd == NULL) {
        cons_bad_cmd_usage(command);
        cons_alert(NULL);
        return TRUE;
    }

    if (strcmp(cmd, "invites") == 0) {
        if (g_strcmp0(args[1], "on") == 0) {
            prefs_set_boolean(PREF_BOOKMARK_INVITE, TRUE);
            cons_show("Auto bookmarking accepted invites enabled.");
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_boolean(PREF_BOOKMARK_INVITE, FALSE);
            cons_show("Auto bookmarking accepted invites disabled.");
        } else {
            cons_bad_cmd_usage(command);
            cons_show("");
        }
        cons_alert(NULL);
        return TRUE;
    }

    if (strcmp(cmd, "list") == 0) {
        char* bookmark_jid = args[1];
        if (bookmark_jid == NULL) {
            // list all bookmarks
            GList* bookmarks = bookmark_get_list();
            cons_show_bookmarks(bookmarks);
            g_list_free(bookmarks);
        } else {
            // list one bookmark
            Bookmark* bookmark = bookmark_get_by_jid(bookmark_jid);
            cons_show_bookmark(bookmark);
        }

        return TRUE;
    }

    char* jid = args[1];
    if (jid == NULL) {
        cons_bad_cmd_usage(command);
        cons_show("");
        cons_alert(NULL);
        return TRUE;
    }
    if (strchr(jid, '@') == NULL) {
        cons_show("Invalid room, must be of the form room@domain.tld");
        cons_show("");
        cons_alert(NULL);
        return TRUE;
    }

    if (strcmp(cmd, "remove") == 0) {
        gboolean removed = bookmark_remove(jid);
        if (removed) {
            cons_show("Bookmark removed for %s.", jid);
        } else {
            cons_show("No bookmark exists for %s.", jid);
        }
        cons_alert(NULL);
        return TRUE;
    }

    if (strcmp(cmd, "join") == 0) {
        gboolean joined = bookmark_join(jid);
        if (!joined) {
            cons_show("No bookmark exists for %s.", jid);
        }
        cons_alert(NULL);
        return TRUE;
    }

    gchar* opt_keys[] = { "autojoin", "nick", "password", "name", NULL };
    gboolean parsed;

    GHashTable* options = parse_options(&args[2], opt_keys, &parsed);
    if (!parsed) {
        cons_bad_cmd_usage(command);
        cons_show("");
        cons_alert(NULL);
        return TRUE;
    }

    char* autojoin = g_hash_table_lookup(options, "autojoin");

    if (autojoin && ((strcmp(autojoin, "on") != 0) && (strcmp(autojoin, "off") != 0))) {
        cons_bad_cmd_usage(command);
        cons_show("");
        options_destroy(options);
        cons_alert(NULL);
        return TRUE;
    }

    char* nick = g_hash_table_lookup(options, "nick");
    char* password = g_hash_table_lookup(options, "password");
    char* name = g_hash_table_lookup(options, "name");

    if (strcmp(cmd, "add") == 0) {
        gboolean added = bookmark_add(jid, nick, password, autojoin, name);
        if (added) {
            cons_show("Bookmark added for %s.", jid);
        } else {
            cons_show("Bookmark already exists, use /bookmark update to edit.");
        }
        options_destroy(options);
        cons_alert(NULL);
        return TRUE;
    }

    if (strcmp(cmd, "update") == 0) {
        gboolean updated = bookmark_update(jid, nick, password, autojoin, name);
        if (updated) {
            cons_show("Bookmark updated.");
        } else {
            cons_show("No bookmark exists for %s.", jid);
        }
        options_destroy(options);
        cons_alert(NULL);
        return TRUE;
    }

    cons_bad_cmd_usage(command);
    options_destroy(options);
    cons_alert(NULL);

    return TRUE;
}

gboolean
cmd_bookmark_ignore(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        cons_alert(NULL);
        return TRUE;
    }

    // `/bookmark ignore` lists them
    if (args[1] == NULL) {
        gsize len = 0;
        gchar** list = bookmark_ignore_list(&len);
        cons_show_bookmarks_ignore(list, len);
        g_strfreev(list);
        return TRUE;
    }

    if (strcmp(args[1], "add") == 0 && args[2] != NULL) {
        bookmark_ignore_add(args[2]);
        cons_show("Autojoin for bookmark %s added to ignore list.", args[2]);
        return TRUE;
    }

    if (strcmp(args[1], "remove") == 0 && args[2] != NULL) {
        bookmark_ignore_remove(args[2]);
        cons_show("Autojoin for bookmark %s removed from ignore list.", args[2]);
        return TRUE;
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_disco(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    GString* jid = g_string_new("");
    if (args[1]) {
        jid = g_string_append(jid, args[1]);
    } else {
        Jid* jidp = jid_create(connection_get_fulljid());
        jid = g_string_append(jid, jidp->domainpart);
        jid_destroy(jidp);
    }

    if (g_strcmp0(args[0], "info") == 0) {
        iq_disco_info_request(jid->str);
    } else {
        iq_disco_items_request(jid->str);
    }

    g_string_free(jid, TRUE);

    return TRUE;
}

// TODO: Move this into its own tools such as HTTPUpload or AESGCMDownload.
#ifdef HAVE_OMEMO
char*
_add_omemo_stream(int* fd, FILE** fh, char** err)
{
    // Create temporary file for writing ciphertext.
    int tmpfd;
    char* tmpname = NULL;
    if ((tmpfd = g_file_open_tmp("profanity.XXXXXX", &tmpname, NULL)) == -1) {
        *err = "Unable to create temporary file for encrypted transfer.";
        return NULL;
    }
    FILE* tmpfh = fdopen(tmpfd, "w+b");

    // The temporary ciphertext file should be removed after it has
    // been closed.
    remove(tmpname);
    free(tmpname);

    int crypt_res;
    char* fragment;
    fragment = omemo_encrypt_file(*fh, tmpfh, file_size(*fd), &crypt_res);
    if (crypt_res != 0) {
        fclose(tmpfh);
        return NULL;
    }

    // Force flush as the upload will read from the same stream.
    fflush(tmpfh);
    rewind(tmpfh);

    fclose(*fh); // Also closes descriptor.

    // Switch original stream with temporary ciphertext stream.
    *fd = tmpfd;
    *fh = tmpfh;

    return fragment;
}
#endif

gboolean
cmd_sendfile(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();
    gchar* filename;
    char* alt_scheme = NULL;
    char* alt_fragment = NULL;

    // expand ~ to $HOME
    filename = get_expanded_path(args[0]);

    if (access(filename, R_OK) != 0) {
        cons_show_error("Uploading '%s' failed: File not found!", filename);
        goto out;
    }

    if (!is_regular_file(filename)) {
        cons_show_error("Uploading '%s' failed: Not a file!", filename);
        goto out;
    }

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        goto out;
    }

    if (window->type != WIN_CHAT && window->type != WIN_PRIVATE && window->type != WIN_MUC) {
        cons_show_error("Unsupported window for file transmission.");
        goto out;
    }

    int fd;
    if ((fd = open(filename, O_RDONLY)) == -1) {
        cons_show_error("Unable to open file descriptor for '%s'.", filename);
        goto out;
    }

    FILE* fh = fdopen(fd, "rb");

    gboolean omemo_enabled = FALSE;
    gboolean sendfile_enabled = TRUE;

    switch (window->type) {
    case WIN_MUC:
    {
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
        omemo_enabled = mucwin->is_omemo == TRUE;
        break;
    }
    case WIN_CHAT:
    {
        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        omemo_enabled = chatwin->is_omemo == TRUE;
        sendfile_enabled = !((chatwin->pgp_send == TRUE && !prefs_get_boolean(PREF_PGP_SENDFILE))
                             || (chatwin->is_otr == TRUE && !prefs_get_boolean(PREF_OTR_SENDFILE)));
        break;
    }

    case WIN_PRIVATE: // We don't support encryption in private MUC windows.
    default:
        cons_show_error("Unsupported window for file transmission.");
        goto out;
    }

    if (!sendfile_enabled) {
        cons_show_error("Uploading unencrypted files disabled. See /otr sendfile or /pgp sendfile.");
        win_println(window, THEME_ERROR, "-", "Sending encrypted files via http_upload is not possible yet.");
        goto out;
    }

    if (omemo_enabled) {
#ifdef HAVE_OMEMO
        char* err = NULL;
        alt_scheme = OMEMO_AESGCM_URL_SCHEME;
        alt_fragment = _add_omemo_stream(&fd, &fh, &err);
        if (err != NULL) {
            cons_show_error(err);
            win_println(window, THEME_ERROR, "-", err);
            goto out;
        }
#endif
    }

    HTTPUpload* upload = malloc(sizeof(HTTPUpload));
    upload->window = window;

    upload->filename = strdup(filename);
    upload->filehandle = fh;
    upload->filesize = file_size(fd);
    upload->mime_type = file_mime_type(filename);

    if (alt_scheme != NULL) {
        upload->alt_scheme = strdup(alt_scheme);
    } else {
        upload->alt_scheme = NULL;
    }

    if (alt_fragment != NULL) {
        upload->alt_fragment = strdup(alt_fragment);
    } else {
        upload->alt_fragment = NULL;
    }

    iq_http_upload_request(upload);

out:
#ifdef HAVE_OMEMO
    if (alt_fragment != NULL)
        omemo_free(alt_fragment);
#endif
    if (filename != NULL)
        free(filename);

    return TRUE;
}

gboolean
cmd_lastactivity(ProfWin* window, const char* const command, gchar** args)
{
    if ((g_strcmp0(args[0], "set") == 0)) {
        if ((g_strcmp0(args[1], "on") == 0) || (g_strcmp0(args[1], "off") == 0)) {
            _cmd_set_boolean_preference(args[1], command, "Last activity", PREF_LASTACTIVITY);
            if (g_strcmp0(args[1], "on") == 0) {
                caps_add_feature(XMPP_FEATURE_LASTACTIVITY);
            }
            if (g_strcmp0(args[1], "off") == 0) {
                caps_remove_feature(XMPP_FEATURE_LASTACTIVITY);
            }
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    }

    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if ((g_strcmp0(args[0], "get") == 0)) {
        if (args[1] == NULL) {
            Jid* jidp = jid_create(connection_get_fulljid());
            GString* jid = g_string_new(jidp->domainpart);

            iq_last_activity_request(jid->str);

            g_string_free(jid, TRUE);
            jid_destroy(jidp);

            return TRUE;
        } else {
            iq_last_activity_request(args[1]);
            return TRUE;
        }
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_nick(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }
    if (window->type != WIN_MUC) {
        cons_show("You can only change your nickname in a chat room window.");
        return TRUE;
    }

    ProfMucWin* mucwin = (ProfMucWin*)window;
    assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
    char* nick = args[0];
    presence_change_room_nick(mucwin->roomjid, nick);

    return TRUE;
}

gboolean
cmd_alias(ProfWin* window, const char* const command, gchar** args)
{
    char* subcmd = args[0];

    if (strcmp(subcmd, "add") == 0) {
        char* alias = args[1];
        if (alias == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            char* alias_p = alias;
            GString* ac_value = g_string_new("");
            if (alias[0] == '/') {
                g_string_append(ac_value, alias);
                alias_p = &alias[1];
            } else {
                g_string_append(ac_value, "/");
                g_string_append(ac_value, alias);
            }

            char* value = args[2];
            if (value == NULL) {
                cons_bad_cmd_usage(command);
                g_string_free(ac_value, TRUE);
                return TRUE;
            } else if (cmd_ac_exists(ac_value->str)) {
                cons_show("Command or alias '%s' already exists.", ac_value->str);
                g_string_free(ac_value, TRUE);
                return TRUE;
            } else {
                prefs_add_alias(alias_p, value);
                cmd_ac_add(ac_value->str);
                cmd_ac_add_alias_value(alias_p);
                cons_show("Command alias added %s -> %s", ac_value->str, value);
                g_string_free(ac_value, TRUE);
                return TRUE;
            }
        }
    } else if (strcmp(subcmd, "remove") == 0) {
        char* alias = args[1];
        if (alias == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else {
            if (alias[0] == '/') {
                alias = &alias[1];
            }
            gboolean removed = prefs_remove_alias(alias);
            if (!removed) {
                cons_show("No such command alias /%s", alias);
            } else {
                GString* ac_value = g_string_new("/");
                g_string_append(ac_value, alias);
                cmd_ac_remove(ac_value->str);
                cmd_ac_remove_alias_value(alias);
                g_string_free(ac_value, TRUE);
                cons_show("Command alias removed -> /%s", alias);
            }
            return TRUE;
        }
    } else if (strcmp(subcmd, "list") == 0) {
        GList* aliases = prefs_get_aliases();
        cons_show_aliases(aliases);
        prefs_free_aliases(aliases);
        return TRUE;
    } else {
        cons_bad_cmd_usage(command);
        return TRUE;
    }
}

gboolean
cmd_clear(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        win_clear(window);
        return TRUE;
    } else {
        if ((g_strcmp0(args[0], "persist_history") == 0)) {

            if (args[1] != NULL) {
                if ((g_strcmp0(args[1], "on") == 0) || (g_strcmp0(args[1], "off") == 0)) {
                    _cmd_set_boolean_preference(args[1], command, "Persistent history", PREF_CLEAR_PERSIST_HISTORY);
                    return TRUE;
                }
            } else {
                if (prefs_get_boolean(PREF_CLEAR_PERSIST_HISTORY)) {
                    win_println(window, THEME_DEFAULT, "!", "  Persistently clear screen  : ON");
                } else {
                    win_println(window, THEME_DEFAULT, "!", "  Persistently clear screen  : OFF");
                }
                return TRUE;
            }
        }
    }
    cons_bad_cmd_usage(command);

    return TRUE;
}

gboolean
cmd_privileges(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "MUC privileges", PREF_MUC_PRIVILEGES);

    ui_redraw_all_room_rosters();

    return TRUE;
}

gboolean
cmd_charset(ProfWin* window, const char* const command, gchar** args)
{
    char* codeset = nl_langinfo(CODESET);
    char* lang = getenv("LANG");

    cons_show("Charset information:");

    if (lang) {
        cons_show("  LANG:       %s", lang);
    }
    if (codeset) {
        cons_show("  CODESET:    %s", codeset);
    }
    cons_show("  MB_CUR_MAX: %d", MB_CUR_MAX);
    cons_show("  MB_LEN_MAX: %d", MB_LEN_MAX);

    return TRUE;
}

gboolean
cmd_beep(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "Sound", PREF_BEEP);
    return TRUE;
}

gboolean
cmd_console(ProfWin* window, const char* const command, gchar** args)
{
    gboolean isMuc = (g_strcmp0(args[0], "muc") == 0);

    if (!_string_matches_one_of(NULL, args[0], FALSE, "chat", "private", NULL) && !isMuc) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    gchar* setting = args[1];
    if (!_string_matches_one_of(NULL, setting, FALSE, "all", "first", "none", NULL)) {
        if (!(isMuc && (g_strcmp0(setting, "mention") == 0))) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    }

    if (g_strcmp0(args[0], "chat") == 0) {
        prefs_set_string(PREF_CONSOLE_CHAT, setting);
        cons_show("Console chat messages set: %s", setting);
        return TRUE;
    }

    if (g_strcmp0(args[0], "muc") == 0) {
        prefs_set_string(PREF_CONSOLE_MUC, setting);
        cons_show("Console MUC messages set: %s", setting);
        return TRUE;
    }

    if (g_strcmp0(args[0], "private") == 0) {
        prefs_set_string(PREF_CONSOLE_PRIVATE, setting);
        cons_show("Console private room messages set: %s", setting);
        return TRUE;
    }

    return TRUE;
}

gboolean
cmd_presence(ProfWin* window, const char* const command, gchar** args)
{
    if (strcmp(args[0], "console") != 0 && strcmp(args[0], "chat") != 0 && strcmp(args[0], "room") != 0 && strcmp(args[0], "titlebar") != 0) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (strcmp(args[0], "titlebar") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Contact presence", PREF_PRESENCE);
        return TRUE;
    }

    if (strcmp(args[1], "all") != 0 && strcmp(args[1], "online") != 0 && strcmp(args[1], "none") != 0) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (strcmp(args[0], "console") == 0) {
        prefs_set_string(PREF_STATUSES_CONSOLE, args[1]);
        if (strcmp(args[1], "all") == 0) {
            cons_show("All presence updates will appear in the console.");
        } else if (strcmp(args[1], "online") == 0) {
            cons_show("Only online/offline presence updates will appear in the console.");
        } else {
            cons_show("Presence updates will not appear in the console.");
        }
    }

    if (strcmp(args[0], "chat") == 0) {
        prefs_set_string(PREF_STATUSES_CHAT, args[1]);
        if (strcmp(args[1], "all") == 0) {
            cons_show("All presence updates will appear in chat windows.");
        } else if (strcmp(args[1], "online") == 0) {
            cons_show("Only online/offline presence updates will appear in chat windows.");
        } else {
            cons_show("Presence updates will not appear in chat windows.");
        }
    }

    if (strcmp(args[0], "room") == 0) {
        prefs_set_string(PREF_STATUSES_MUC, args[1]);
        if (strcmp(args[1], "all") == 0) {
            cons_show("All presence updates will appear in chat room windows.");
        } else if (strcmp(args[1], "online") == 0) {
            cons_show("Only join/leave presence updates will appear in chat room windows.");
        } else {
            cons_show("Presence updates will not appear in chat room windows.");
        }
    }

    return TRUE;
}

gboolean
cmd_wrap(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "Word wrap", PREF_WRAP);

    wins_resize_all();

    return TRUE;
}

gboolean
cmd_time(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "lastactivity") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_LASTACTIVITY);
            cons_show("Last activity time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_LASTACTIVITY, args[2]);
            cons_show("Last activity time format set to '%s'.", args[2]);
            ui_redraw();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Last activity time cannot be disabled.");
            ui_redraw();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "statusbar") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_STATUSBAR);
            cons_show("Status bar time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_STATUSBAR, args[2]);
            cons_show("Status bar time format set to '%s'.", args[2]);
            ui_redraw();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_STATUSBAR, "off");
            cons_show("Status bar time display disabled.");
            ui_redraw();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "console") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_CONSOLE);
            cons_show("Console time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_CONSOLE, args[2]);
            cons_show("Console time format set to '%s'.", args[2]);
            wins_resize_all();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_CONSOLE, "off");
            cons_show("Console time display disabled.");
            wins_resize_all();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "chat") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_CHAT);
            cons_show("Chat time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_CHAT, args[2]);
            cons_show("Chat time format set to '%s'.", args[2]);
            wins_resize_all();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_CHAT, "off");
            cons_show("Chat time display disabled.");
            wins_resize_all();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "muc") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_MUC);
            cons_show("MUC time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_MUC, args[2]);
            cons_show("MUC time format set to '%s'.", args[2]);
            wins_resize_all();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_MUC, "off");
            cons_show("MUC time display disabled.");
            wins_resize_all();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "config") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_CONFIG);
            cons_show("config time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_CONFIG, args[2]);
            cons_show("config time format set to '%s'.", args[2]);
            wins_resize_all();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_CONFIG, "off");
            cons_show("config time display disabled.");
            wins_resize_all();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "private") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_PRIVATE);
            cons_show("Private chat time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_PRIVATE, args[2]);
            cons_show("Private chat time format set to '%s'.", args[2]);
            wins_resize_all();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_PRIVATE, "off");
            cons_show("Private chat time display disabled.");
            wins_resize_all();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "xml") == 0) {
        if (args[1] == NULL) {
            char* format = prefs_get_string(PREF_TIME_XMLCONSOLE);
            cons_show("XML Console time format: '%s'.", format);
            g_free(format);
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_XMLCONSOLE, args[2]);
            cons_show("XML Console time format set to '%s'.", args[2]);
            wins_resize_all();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_XMLCONSOLE, "off");
            cons_show("XML Console time display disabled.");
            wins_resize_all();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else if (g_strcmp0(args[0], "all") == 0) {
        if (args[1] == NULL) {
            cons_time_setting();
            return TRUE;
        } else if (g_strcmp0(args[1], "set") == 0 && args[2] != NULL) {
            prefs_set_string(PREF_TIME_CONSOLE, args[2]);
            cons_show("Console time format set to '%s'.", args[2]);
            prefs_set_string(PREF_TIME_CHAT, args[2]);
            cons_show("Chat time format set to '%s'.", args[2]);
            prefs_set_string(PREF_TIME_MUC, args[2]);
            cons_show("MUC time format set to '%s'.", args[2]);
            prefs_set_string(PREF_TIME_CONFIG, args[2]);
            cons_show("config time format set to '%s'.", args[2]);
            prefs_set_string(PREF_TIME_PRIVATE, args[2]);
            cons_show("Private chat time format set to '%s'.", args[2]);
            prefs_set_string(PREF_TIME_XMLCONSOLE, args[2]);
            cons_show("XML Console time format set to '%s'.", args[2]);
            wins_resize_all();
            return TRUE;
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_TIME_CONSOLE, "off");
            cons_show("Console time display disabled.");
            prefs_set_string(PREF_TIME_CHAT, "off");
            cons_show("Chat time display disabled.");
            prefs_set_string(PREF_TIME_MUC, "off");
            cons_show("MUC time display disabled.");
            prefs_set_string(PREF_TIME_CONFIG, "off");
            cons_show("config time display disabled.");
            prefs_set_string(PREF_TIME_PRIVATE, "off");
            cons_show("config time display disabled.");
            prefs_set_string(PREF_TIME_XMLCONSOLE, "off");
            cons_show("XML Console time display disabled.");
            ui_redraw();
            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    } else {
        cons_bad_cmd_usage(command);
        return TRUE;
    }
}

gboolean
cmd_states(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        return FALSE;
    }

    _cmd_set_boolean_preference(args[0], command, "Sending chat states", PREF_STATES);

    // if disabled, disable outtype and gone
    if (strcmp(args[0], "off") == 0) {
        prefs_set_boolean(PREF_OUTTYPE, FALSE);
        prefs_set_gone(0);
    }

    return TRUE;
}

gboolean
cmd_wintitle(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "show") != 0 && g_strcmp0(args[0], "goodbye") != 0) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }
    if (g_strcmp0(args[0], "show") == 0 && g_strcmp0(args[1], "off") == 0) {
        ui_clear_win_title();
    }
    if (g_strcmp0(args[0], "show") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Window title show", PREF_WINTITLE_SHOW);
    } else {
        _cmd_set_boolean_preference(args[1], command, "Window title goodbye", PREF_WINTITLE_GOODBYE);
    }

    return TRUE;
}

gboolean
cmd_outtype(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        return FALSE;
    }

    _cmd_set_boolean_preference(args[0], command, "Sending typing notifications", PREF_OUTTYPE);

    // if enabled, enable states
    if (strcmp(args[0], "on") == 0) {
        prefs_set_boolean(PREF_STATES, TRUE);
    }

    return TRUE;
}

gboolean
cmd_gone(ProfWin* window, const char* const command, gchar** args)
{
    char* value = args[0];

    gint period = atoi(value);
    prefs_set_gone(period);
    if (period == 0) {
        cons_show("Automatic leaving conversations after period disabled.");
    } else if (period == 1) {
        cons_show("Leaving conversations after 1 minute of inactivity.");
    } else {
        cons_show("Leaving conversations after %d minutes of inactivity.", period);
    }

    // if enabled, enable states
    if (period > 0) {
        prefs_set_boolean(PREF_STATES, TRUE);
    }

    return TRUE;
}

gboolean
cmd_notify(ProfWin* window, const char* const command, gchar** args)
{
    if (!args[0]) {
        ProfWin* current = wins_get_current();
        if (current->type == WIN_MUC) {
            win_println(current, THEME_DEFAULT, "-", "");
            ProfMucWin* mucwin = (ProfMucWin*)current;

            win_println(window, THEME_DEFAULT, "!", "Notification settings for %s:", mucwin->roomjid);
            if (prefs_has_room_notify(mucwin->roomjid)) {
                if (prefs_get_room_notify(mucwin->roomjid)) {
                    win_println(window, THEME_DEFAULT, "!", "  Message  : ON");
                } else {
                    win_println(window, THEME_DEFAULT, "!", "  Message  : OFF");
                }
            } else {
                if (prefs_get_boolean(PREF_NOTIFY_ROOM)) {
                    win_println(window, THEME_DEFAULT, "!", "  Message  : ON (global setting)");
                } else {
                    win_println(window, THEME_DEFAULT, "!", "  Message  : OFF (global setting)");
                }
            }
            if (prefs_has_room_notify_mention(mucwin->roomjid)) {
                if (prefs_get_room_notify_mention(mucwin->roomjid)) {
                    win_println(window, THEME_DEFAULT, "!", "  Mention  : ON");
                } else {
                    win_println(window, THEME_DEFAULT, "!", "  Mention  : OFF");
                }
            } else {
                if (prefs_get_boolean(PREF_NOTIFY_ROOM_MENTION)) {
                    win_println(window, THEME_DEFAULT, "!", "  Mention  : ON (global setting)");
                } else {
                    win_println(window, THEME_DEFAULT, "!", "  Mention  : OFF (global setting)");
                }
            }
            if (prefs_has_room_notify_trigger(mucwin->roomjid)) {
                if (prefs_get_room_notify_trigger(mucwin->roomjid)) {
                    win_println(window, THEME_DEFAULT, "!", "  Triggers : ON");
                } else {
                    win_println(window, THEME_DEFAULT, "!", "  Triggers : OFF");
                }
            } else {
                if (prefs_get_boolean(PREF_NOTIFY_ROOM_TRIGGER)) {
                    win_println(window, THEME_DEFAULT, "!", "  Triggers : ON (global setting)");
                } else {
                    win_println(window, THEME_DEFAULT, "!", "  Triggers : OFF (global setting)");
                }
            }
            win_println(current, THEME_DEFAULT, "-", "");
        } else {
            cons_show("");
            cons_notify_setting();
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    // chat settings
    if (g_strcmp0(args[0], "chat") == 0) {
        if (g_strcmp0(args[1], "on") == 0) {
            cons_show("Chat notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_CHAT, TRUE);
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Chat notifications disabled.");
            prefs_set_boolean(PREF_NOTIFY_CHAT, FALSE);
        } else if (g_strcmp0(args[1], "current") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Current window chat notifications enabled.");
                prefs_set_boolean(PREF_NOTIFY_CHAT_CURRENT, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Current window chat notifications disabled.");
                prefs_set_boolean(PREF_NOTIFY_CHAT_CURRENT, FALSE);
            } else {
                cons_show("Usage: /notify chat current on|off");
            }
        } else if (g_strcmp0(args[1], "text") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Showing text in chat notifications enabled.");
                prefs_set_boolean(PREF_NOTIFY_CHAT_TEXT, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Showing text in chat notifications disabled.");
                prefs_set_boolean(PREF_NOTIFY_CHAT_TEXT, FALSE);
            } else {
                cons_show("Usage: /notify chat text on|off");
            }
        }

        // chat room settings
    } else if (g_strcmp0(args[0], "room") == 0) {
        if (g_strcmp0(args[1], "on") == 0) {
            cons_show("Room notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_ROOM, TRUE);
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Room notifications disabled.");
            prefs_set_boolean(PREF_NOTIFY_ROOM, FALSE);
        } else if (g_strcmp0(args[1], "mention") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Room notifications with mention enabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_MENTION, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Room notifications with mention disabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_MENTION, FALSE);
            } else if (g_strcmp0(args[2], "case_sensitive") == 0) {
                cons_show("Room mention matching set to case sensitive.");
                prefs_set_boolean(PREF_NOTIFY_MENTION_CASE_SENSITIVE, TRUE);
            } else if (g_strcmp0(args[2], "case_insensitive") == 0) {
                cons_show("Room mention matching set to case insensitive.");
                prefs_set_boolean(PREF_NOTIFY_MENTION_CASE_SENSITIVE, FALSE);
            } else if (g_strcmp0(args[2], "word_whole") == 0) {
                cons_show("Room mention matching set to whole word.");
                prefs_set_boolean(PREF_NOTIFY_MENTION_WHOLE_WORD, TRUE);
            } else if (g_strcmp0(args[2], "word_part") == 0) {
                cons_show("Room mention matching set to partial word.");
                prefs_set_boolean(PREF_NOTIFY_MENTION_WHOLE_WORD, FALSE);
            } else {
                cons_show("Usage: /notify room mention on|off");
            }
        } else if (g_strcmp0(args[1], "offline") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Room notifications for offline messages enabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_OFFLINE, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Room notifications for offline messages disabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_OFFLINE, FALSE);
            } else {
                cons_show("Usage: /notify room offline on|off");
            }
        } else if (g_strcmp0(args[1], "current") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Current window chat room message notifications enabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_CURRENT, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Current window chat room message notifications disabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_CURRENT, FALSE);
            } else {
                cons_show("Usage: /notify room current on|off");
            }
        } else if (g_strcmp0(args[1], "text") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Showing text in chat room message notifications enabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_TEXT, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Showing text in chat room message notifications disabled.");
                prefs_set_boolean(PREF_NOTIFY_ROOM_TEXT, FALSE);
            } else {
                cons_show("Usage: /notify room text on|off");
            }
        } else if (g_strcmp0(args[1], "trigger") == 0) {
            if (g_strcmp0(args[2], "add") == 0) {
                if (!args[3]) {
                    cons_bad_cmd_usage(command);
                } else {
                    gboolean res = prefs_add_room_notify_trigger(args[3]);
                    if (res) {
                        cons_show("Adding room notification trigger: %s", args[3]);
                    } else {
                        cons_show("Room notification trigger already exists: %s", args[3]);
                    }
                }
            } else if (g_strcmp0(args[2], "remove") == 0) {
                if (!args[3]) {
                    cons_bad_cmd_usage(command);
                } else {
                    gboolean res = prefs_remove_room_notify_trigger(args[3]);
                    if (res) {
                        cons_show("Removing room notification trigger: %s", args[3]);
                    } else {
                        cons_show("Room notification trigger does not exist: %s", args[3]);
                    }
                }
            } else if (g_strcmp0(args[2], "list") == 0) {
                GList* triggers = prefs_get_room_notify_triggers();
                GList* curr = triggers;
                if (curr) {
                    cons_show("Room notification triggers:");
                } else {
                    cons_show("No room notification triggers");
                }
                while (curr) {
                    cons_show("  %s", curr->data);
                    curr = g_list_next(curr);
                }
                g_list_free_full(triggers, free);
            } else if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Enabling room notification triggers");
                prefs_set_boolean(PREF_NOTIFY_ROOM_TRIGGER, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Disabling room notification triggers");
                prefs_set_boolean(PREF_NOTIFY_ROOM_TRIGGER, FALSE);
            } else {
                cons_bad_cmd_usage(command);
            }
        } else {
            cons_show("Usage: /notify room on|off|mention");
        }

        // typing settings
    } else if (g_strcmp0(args[0], "typing") == 0) {
        if (g_strcmp0(args[1], "on") == 0) {
            cons_show("Typing notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_TYPING, TRUE);
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Typing notifications disabled.");
            prefs_set_boolean(PREF_NOTIFY_TYPING, FALSE);
        } else if (g_strcmp0(args[1], "current") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Current window typing notifications enabled.");
                prefs_set_boolean(PREF_NOTIFY_TYPING_CURRENT, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Current window typing notifications disabled.");
                prefs_set_boolean(PREF_NOTIFY_TYPING_CURRENT, FALSE);
            } else {
                cons_show("Usage: /notify typing current on|off");
            }
        } else {
            cons_show("Usage: /notify typing on|off");
        }

        // invite settings
    } else if (g_strcmp0(args[0], "invite") == 0) {
        if (g_strcmp0(args[1], "on") == 0) {
            cons_show("Chat room invite notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_INVITE, TRUE);
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Chat room invite notifications disabled.");
            prefs_set_boolean(PREF_NOTIFY_INVITE, FALSE);
        } else {
            cons_show("Usage: /notify invite on|off");
        }

        // subscription settings
    } else if (g_strcmp0(args[0], "sub") == 0) {
        if (g_strcmp0(args[1], "on") == 0) {
            cons_show("Subscription notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_SUB, TRUE);
        } else if (g_strcmp0(args[1], "off") == 0) {
            cons_show("Subscription notifications disabled.");
            prefs_set_boolean(PREF_NOTIFY_SUB, FALSE);
        } else {
            cons_show("Usage: /notify sub on|off");
        }

        // remind settings
    } else if (g_strcmp0(args[0], "remind") == 0) {
        if (!args[1]) {
            cons_bad_cmd_usage(command);
        } else {
            gint period = atoi(args[1]);
            prefs_set_notify_remind(period);
            if (period == 0) {
                cons_show("Message reminders disabled.");
            } else if (period == 1) {
                cons_show("Message reminder period set to 1 second.");
            } else {
                cons_show("Message reminder period set to %d seconds.", period);
            }
        }

        // current chat room settings
    } else if (g_strcmp0(args[0], "on") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();

        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
        } else {
            ProfWin* window = wins_get_current();
            if (window->type != WIN_MUC) {
                cons_show("You must be in a chat room.");
            } else {
                ProfMucWin* mucwin = (ProfMucWin*)window;
                prefs_set_room_notify(mucwin->roomjid, TRUE);
                win_println(window, THEME_DEFAULT, "!", "Notifications enabled for %s", mucwin->roomjid);
            }
        }
    } else if (g_strcmp0(args[0], "off") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();

        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
        } else {
            ProfWin* window = wins_get_current();
            if (window->type != WIN_MUC) {
                cons_show("You must be in a chat room.");
            } else {
                ProfMucWin* mucwin = (ProfMucWin*)window;
                prefs_set_room_notify(mucwin->roomjid, FALSE);
                win_println(window, THEME_DEFAULT, "!", "Notifications disabled for %s", mucwin->roomjid);
            }
        }
    } else if (g_strcmp0(args[0], "mention") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();

        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
        } else {
            if (g_strcmp0(args[1], "on") == 0) {
                ProfWin* window = wins_get_current();
                if (window->type != WIN_MUC) {
                    cons_show("You must be in a chat room.");
                } else {
                    ProfMucWin* mucwin = (ProfMucWin*)window;
                    prefs_set_room_notify_mention(mucwin->roomjid, TRUE);
                    win_println(window, THEME_DEFAULT, "!", "Mention notifications enabled for %s", mucwin->roomjid);
                }
            } else if (g_strcmp0(args[1], "off") == 0) {
                ProfWin* window = wins_get_current();
                if (window->type != WIN_MUC) {
                    cons_show("You must be in a chat rooms.");
                } else {
                    ProfMucWin* mucwin = (ProfMucWin*)window;
                    prefs_set_room_notify_mention(mucwin->roomjid, FALSE);
                    win_println(window, THEME_DEFAULT, "!", "Mention notifications disabled for %s", mucwin->roomjid);
                }
            } else {
                cons_bad_cmd_usage(command);
            }
        }
    } else if (g_strcmp0(args[0], "trigger") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();

        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
        } else {
            if (g_strcmp0(args[1], "on") == 0) {
                ProfWin* window = wins_get_current();
                if (window->type != WIN_MUC) {
                    cons_show("You must be in a chat room.");
                } else {
                    ProfMucWin* mucwin = (ProfMucWin*)window;
                    prefs_set_room_notify_trigger(mucwin->roomjid, TRUE);
                    win_println(window, THEME_DEFAULT, "!", "Custom trigger notifications enabled for %s", mucwin->roomjid);
                }
            } else if (g_strcmp0(args[1], "off") == 0) {
                ProfWin* window = wins_get_current();
                if (window->type != WIN_MUC) {
                    cons_show("You must be in a chat rooms.");
                } else {
                    ProfMucWin* mucwin = (ProfMucWin*)window;
                    prefs_set_room_notify_trigger(mucwin->roomjid, FALSE);
                    win_println(window, THEME_DEFAULT, "!", "Custom trigger notifications disabled for %s", mucwin->roomjid);
                }
            } else {
                cons_bad_cmd_usage(command);
            }
        }
    } else if (g_strcmp0(args[0], "reset") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();

        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
        } else {
            ProfWin* window = wins_get_current();
            if (window->type != WIN_MUC) {
                cons_show("You must be in a chat room.");
            } else {
                ProfMucWin* mucwin = (ProfMucWin*)window;
                gboolean res = prefs_reset_room_notify(mucwin->roomjid);
                if (res) {
                    win_println(window, THEME_DEFAULT, "!", "Notification settings set to global defaults for %s", mucwin->roomjid);
                } else {
                    win_println(window, THEME_DEFAULT, "!", "No custom notification settings for %s", mucwin->roomjid);
                }
            }
        }
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_inpblock(ProfWin* window, const char* const command, gchar** args)
{
    char* subcmd = args[0];
    char* value = args[1];

    if (g_strcmp0(subcmd, "timeout") == 0) {
        if (value == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(value, &intval, 1, 1000, &err_msg);
        if (res) {
            cons_show("Input blocking set to %d milliseconds.", intval);
            prefs_set_inpblock(intval);
            inp_nonblocking(FALSE);
        } else {
            cons_show(err_msg);
            free(err_msg);
        }

        return TRUE;
    }

    if (g_strcmp0(subcmd, "dynamic") == 0) {
        if (value == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        if (g_strcmp0(value, "on") != 0 && g_strcmp0(value, "off") != 0) {
            cons_show("Dynamic must be one of 'on' or 'off'");
            return TRUE;
        }

        _cmd_set_boolean_preference(value, command, "Dynamic input blocking", PREF_INPBLOCK_DYNAMIC);
        return TRUE;
    }

    cons_bad_cmd_usage(command);

    return TRUE;
}

gboolean
cmd_titlebar(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "up") == 0) {
        gboolean result = prefs_titlebar_pos_up();
        if (result) {
            ui_resize();
            cons_show("Title bar moved up.");
        } else {
            cons_show("Could not move title bar up.");
        }

        return TRUE;
    }
    if (g_strcmp0(args[0], "down") == 0) {
        gboolean result = prefs_titlebar_pos_down();
        if (result) {
            ui_resize();
            cons_show("Title bar moved down.");
        } else {
            cons_show("Could not move title bar down.");
        }

        return TRUE;
    }

    cons_bad_cmd_usage(command);

    return TRUE;
}

gboolean
cmd_titlebar_show_hide(ProfWin* window, const char* const command, gchar** args)
{
    if (args[1] != NULL) {
        if (g_strcmp0(args[0], "show") == 0) {

            if (g_strcmp0(args[1], "tls") == 0) {
                cons_show("TLS titlebar indicator enabled.");
                prefs_set_boolean(PREF_TLS_SHOW, TRUE);
            } else if (g_strcmp0(args[1], "encwarn") == 0) {
                cons_show("Encryption warning titlebar indicator enabled.");
                prefs_set_boolean(PREF_ENC_WARN, TRUE);
            } else if (g_strcmp0(args[1], "resource") == 0) {
                cons_show("Showing resource in titlebar enabled.");
                prefs_set_boolean(PREF_RESOURCE_TITLE, TRUE);
            } else if (g_strcmp0(args[1], "presence") == 0) {
                cons_show("Showing contact presence in titlebar enabled.");
                prefs_set_boolean(PREF_PRESENCE, TRUE);
            } else if (g_strcmp0(args[1], "jid") == 0) {
                cons_show("Showing MUC JID in titlebar as title enabled.");
                prefs_set_boolean(PREF_TITLEBAR_MUC_TITLE_JID, TRUE);
            } else if (g_strcmp0(args[1], "name") == 0) {
                cons_show("Showing MUC name in titlebar as title enabled.");
                prefs_set_boolean(PREF_TITLEBAR_MUC_TITLE_NAME, TRUE);
            } else {
                cons_bad_cmd_usage(command);
            }
        } else if (g_strcmp0(args[0], "hide") == 0) {

            if (g_strcmp0(args[1], "tls") == 0) {
                cons_show("TLS titlebar indicator disabled.");
                prefs_set_boolean(PREF_TLS_SHOW, FALSE);
            } else if (g_strcmp0(args[1], "encwarn") == 0) {
                cons_show("Encryption warning titlebar indicator disabled.");
                prefs_set_boolean(PREF_ENC_WARN, FALSE);
            } else if (g_strcmp0(args[1], "resource") == 0) {
                cons_show("Showing resource in titlebar disabled.");
                prefs_set_boolean(PREF_RESOURCE_TITLE, FALSE);
            } else if (g_strcmp0(args[1], "presence") == 0) {
                cons_show("Showing contact presence in titlebar disabled.");
                prefs_set_boolean(PREF_PRESENCE, FALSE);
            } else if (g_strcmp0(args[1], "jid") == 0) {
                cons_show("Showing MUC JID in titlebar as title disabled.");
                prefs_set_boolean(PREF_TITLEBAR_MUC_TITLE_JID, FALSE);
            } else if (g_strcmp0(args[1], "name") == 0) {
                cons_show("Showing MUC name in titlebar as title disabled.");
                prefs_set_boolean(PREF_TITLEBAR_MUC_TITLE_NAME, FALSE);
            } else {
                cons_bad_cmd_usage(command);
            }
        } else {
            cons_bad_cmd_usage(command);
        }
    }

    return TRUE;
}

gboolean
cmd_mainwin(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "up") == 0) {
        gboolean result = prefs_mainwin_pos_up();
        if (result) {
            ui_resize();
            cons_show("Main window moved up.");
        } else {
            cons_show("Could not move main window up.");
        }

        return TRUE;
    }
    if (g_strcmp0(args[0], "down") == 0) {
        gboolean result = prefs_mainwin_pos_down();
        if (result) {
            ui_resize();
            cons_show("Main window moved down.");
        } else {
            cons_show("Could not move main window down.");
        }

        return TRUE;
    }

    cons_bad_cmd_usage(command);

    return TRUE;
}

gboolean
cmd_statusbar(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "show") == 0) {
        if (g_strcmp0(args[1], "name") == 0) {
            prefs_set_boolean(PREF_STATUSBAR_SHOW_NAME, TRUE);
            cons_show("Enabled showing tab names.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "number") == 0) {
            prefs_set_boolean(PREF_STATUSBAR_SHOW_NUMBER, TRUE);
            cons_show("Enabled showing tab numbers.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "read") == 0) {
            prefs_set_boolean(PREF_STATUSBAR_SHOW_READ, TRUE);
            cons_show("Enabled showing inactive tabs.");
            ui_resize();
            return TRUE;
        }
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[0], "hide") == 0) {
        if (g_strcmp0(args[1], "name") == 0) {
            if (prefs_get_boolean(PREF_STATUSBAR_SHOW_NUMBER) == FALSE) {
                cons_show("Cannot disable both names and numbers in statusbar.");
                cons_show("Use '/statusbar maxtabs 0' to hide tabs.");
                return TRUE;
            }
            prefs_set_boolean(PREF_STATUSBAR_SHOW_NAME, FALSE);
            cons_show("Disabled showing tab names.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "number") == 0) {
            if (prefs_get_boolean(PREF_STATUSBAR_SHOW_NAME) == FALSE) {
                cons_show("Cannot disable both names and numbers in statusbar.");
                cons_show("Use '/statusbar maxtabs 0' to hide tabs.");
                return TRUE;
            }
            prefs_set_boolean(PREF_STATUSBAR_SHOW_NUMBER, FALSE);
            cons_show("Disabled showing tab numbers.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "read") == 0) {
            prefs_set_boolean(PREF_STATUSBAR_SHOW_READ, FALSE);
            cons_show("Disabled showing inactive tabs.");
            ui_resize();
            return TRUE;
        }
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[0], "maxtabs") == 0) {
        if (args[1] == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* value = args[1];
        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(value, &intval, 0, INT_MAX, &err_msg);
        if (res) {
            if (intval < 0 || intval > 10) {
                cons_bad_cmd_usage(command);
                return TRUE;
            }

            prefs_set_statusbartabs(intval);
            if (intval == 0) {
                cons_show("Status bar tabs disabled.");
            } else {
                cons_show("Status bar tabs set to %d.", intval);
            }
            ui_resize();
            return TRUE;
        } else {
            cons_show(err_msg);
            cons_bad_cmd_usage(command);
            free(err_msg);
            return TRUE;
        }
    }

    if (g_strcmp0(args[0], "tablen") == 0) {
        if (args[1] == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* value = args[1];
        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(value, &intval, 0, INT_MAX, &err_msg);
        if (res) {
            if (intval < 0) {
                cons_bad_cmd_usage(command);
                return TRUE;
            }

            prefs_set_statusbartablen(intval);
            if (intval == 0) {
                cons_show("Maximum tab length disabled.");
            } else {
                cons_show("Maximum tab length set to %d.", intval);
            }
            ui_resize();
            return TRUE;
        } else {
            cons_show(err_msg);
            cons_bad_cmd_usage(command);
            free(err_msg);
            return TRUE;
        }
    }

    if (g_strcmp0(args[0], "self") == 0) {
        if (g_strcmp0(args[1], "barejid") == 0) {
            prefs_set_string(PREF_STATUSBAR_SELF, "barejid");
            cons_show("Using barejid for statusbar title.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "fulljid") == 0) {
            prefs_set_string(PREF_STATUSBAR_SELF, "fulljid");
            cons_show("Using fulljid for statusbar title.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "user") == 0) {
            prefs_set_string(PREF_STATUSBAR_SELF, "user");
            cons_show("Using user for statusbar title.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_string(PREF_STATUSBAR_SELF, "off");
            cons_show("Disabling statusbar title.");
            ui_resize();
            return TRUE;
        }
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[0], "chat") == 0) {
        if (g_strcmp0(args[1], "jid") == 0) {
            prefs_set_string(PREF_STATUSBAR_CHAT, "jid");
            cons_show("Using jid for chat tabs.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "user") == 0) {
            prefs_set_string(PREF_STATUSBAR_CHAT, "user");
            cons_show("Using user for chat tabs.");
            ui_resize();
            return TRUE;
        }
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[0], "room") == 0) {
        if (g_strcmp0(args[1], "jid") == 0) {
            prefs_set_string(PREF_STATUSBAR_ROOM, "jid");
            cons_show("Using jid for room tabs.");
            ui_resize();
            return TRUE;
        }
        if (g_strcmp0(args[1], "room") == 0) {
            prefs_set_string(PREF_STATUSBAR_ROOM, "room");
            cons_show("Using room name for room tabs.");
            ui_resize();
            return TRUE;
        }
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[0], "up") == 0) {
        gboolean result = prefs_statusbar_pos_up();
        if (result) {
            ui_resize();
            cons_show("Status bar moved up");
        } else {
            cons_show("Could not move status bar up.");
        }

        return TRUE;
    }
    if (g_strcmp0(args[0], "down") == 0) {
        gboolean result = prefs_statusbar_pos_down();
        if (result) {
            ui_resize();
            cons_show("Status bar moved down.");
        } else {
            cons_show("Could not move status bar down.");
        }

        return TRUE;
    }

    cons_bad_cmd_usage(command);

    return TRUE;
}

gboolean
cmd_inputwin(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "up") == 0) {
        gboolean result = prefs_inputwin_pos_up();
        if (result) {
            ui_resize();
            cons_show("Input window moved up.");
        } else {
            cons_show("Could not move input window up.");
        }

        return TRUE;
    }
    if (g_strcmp0(args[0], "down") == 0) {
        gboolean result = prefs_inputwin_pos_down();
        if (result) {
            ui_resize();
            cons_show("Input window moved down.");
        } else {
            cons_show("Could not move input window down.");
        }

        return TRUE;
    }

    cons_bad_cmd_usage(command);

    return TRUE;
}

gboolean
cmd_log(ProfWin* window, const char* const command, gchar** args)
{
    char* subcmd = args[0];
    char* value = args[1];

    if (strcmp(subcmd, "maxsize") == 0) {
        if (value == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(value, &intval, PREFS_MIN_LOG_SIZE, INT_MAX, &err_msg);
        if (res) {
            prefs_set_max_log_size(intval);
            cons_show("Log maximum size set to %d bytes", intval);
        } else {
            cons_show(err_msg);
            free(err_msg);
        }
        return TRUE;
    }

    if (strcmp(subcmd, "rotate") == 0) {
        if (value == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
        _cmd_set_boolean_preference(value, command, "Log rotate", PREF_LOG_ROTATE);
        return TRUE;
    }

    if (strcmp(subcmd, "shared") == 0) {
        if (value == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
        _cmd_set_boolean_preference(value, command, "Shared log", PREF_LOG_SHARED);
        cons_show("Setting only takes effect after saving and restarting Profanity.");
        return TRUE;
    }

    if (strcmp(subcmd, "where") == 0) {
        cons_show("Log file: %s", get_log_file_location());
        return TRUE;
    }

    if (strcmp(subcmd, "level") == 0) {
        if (g_strcmp0(value, "INFO") == 0 || g_strcmp0(value, "DEBUG") == 0 || g_strcmp0(value, "WARN") == 0 || g_strcmp0(value, "ERROR") == 0) {

            log_level_t prof_log_level = log_level_from_string(value);
            log_close();
            log_init(prof_log_level, NULL);

            cons_show("Log level changed to: %s.", value);
            return TRUE;
        }
    }

    cons_bad_cmd_usage(command);

    return TRUE;
}

gboolean
cmd_reconnect(ProfWin* window, const char* const command, gchar** args)
{
    char* value = args[0];

    int intval = 0;
    char* err_msg = NULL;
    gboolean res = strtoi_range(value, &intval, 0, INT_MAX, &err_msg);
    if (res) {
        prefs_set_reconnect(intval);
        if (intval == 0) {
            cons_show("Reconnect disabled.", intval);
        } else {
            cons_show("Reconnect interval set to %d seconds.", intval);
        }
    } else {
        cons_show(err_msg);
        cons_bad_cmd_usage(command);
        free(err_msg);
    }

    return TRUE;
}

gboolean
cmd_autoping(ProfWin* window, const char* const command, gchar** args)
{
    char* cmd = args[0];
    char* value = args[1];

    if (g_strcmp0(cmd, "set") == 0) {
        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(value, &intval, 0, INT_MAX, &err_msg);
        if (res) {
            prefs_set_autoping(intval);
            iq_set_autoping(intval);
            if (intval == 0) {
                cons_show("Autoping disabled.");
            } else {
                cons_show("Autoping interval set to %d seconds.", intval);
            }
        } else {
            cons_show(err_msg);
            cons_bad_cmd_usage(command);
            free(err_msg);
        }

    } else if (g_strcmp0(cmd, "timeout") == 0) {
        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(value, &intval, 0, INT_MAX, &err_msg);
        if (res) {
            prefs_set_autoping_timeout(intval);
            if (intval == 0) {
                cons_show("Autoping timeout disabled.");
            } else {
                cons_show("Autoping timeout set to %d seconds.", intval);
            }
        } else {
            cons_show(err_msg);
            cons_bad_cmd_usage(command);
            free(err_msg);
        }

    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_ping(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (args[0] == NULL && connection_supports(XMPP_FEATURE_PING) == FALSE) {
        cons_show("Server does not support ping requests (%s).", XMPP_FEATURE_PING);
        return TRUE;
    }

    if (args[0] != NULL && caps_jid_has_feature(args[0], XMPP_FEATURE_PING) == FALSE) {
        cons_show("%s does not support ping requests.", args[0]);
        return TRUE;
    }

    iq_send_ping(args[0]);

    if (args[0] == NULL) {
        cons_show("Pinged server...");
    } else {
        cons_show("Pinged %s...", args[0]);
    }
    return TRUE;
}

gboolean
cmd_autoaway(ProfWin* window, const char* const command, gchar** args)
{
    if (!_string_matches_one_of("Setting", args[0], FALSE, "mode", "time", "message", "check", NULL)) {
        return TRUE;
    }

    if (g_strcmp0(args[0], "mode") == 0) {
        if (_string_matches_one_of("Mode", args[1], FALSE, "idle", "away", "off", NULL)) {
            prefs_set_string(PREF_AUTOAWAY_MODE, args[1]);
            cons_show("Auto away mode set to: %s.", args[1]);
        }

        return TRUE;
    }

    if ((g_strcmp0(args[0], "time") == 0) && (args[2] != NULL)) {
        if (g_strcmp0(args[1], "away") == 0) {
            int minutesval = 0;
            char* err_msg = NULL;
            gboolean res = strtoi_range(args[2], &minutesval, 1, INT_MAX, &err_msg);
            if (res) {
                prefs_set_autoaway_time(minutesval);
                if (minutesval == 1) {
                    cons_show("Auto away time set to: 1 minute.");
                } else {
                    cons_show("Auto away time set to: %d minutes.", minutesval);
                }
            } else {
                cons_show(err_msg);
                free(err_msg);
            }

            return TRUE;
        } else if (g_strcmp0(args[1], "xa") == 0) {
            int minutesval = 0;
            char* err_msg = NULL;
            gboolean res = strtoi_range(args[2], &minutesval, 0, INT_MAX, &err_msg);
            if (res) {
                int away_time = prefs_get_autoaway_time();
                if (minutesval != 0 && minutesval <= away_time) {
                    cons_show("Auto xa time must be larger than auto away time.");
                } else {
                    prefs_set_autoxa_time(minutesval);
                    if (minutesval == 0) {
                        cons_show("Auto xa time disabled.");
                    } else if (minutesval == 1) {
                        cons_show("Auto xa time set to: 1 minute.");
                    } else {
                        cons_show("Auto xa time set to: %d minutes.", minutesval);
                    }
                }
            } else {
                cons_show(err_msg);
                free(err_msg);
            }

            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    }

    if (g_strcmp0(args[0], "message") == 0) {
        if (g_strcmp0(args[1], "away") == 0 && args[2] != NULL) {
            if (g_strcmp0(args[2], "off") == 0) {
                prefs_set_string(PREF_AUTOAWAY_MESSAGE, NULL);
                cons_show("Auto away message cleared.");
            } else {
                prefs_set_string(PREF_AUTOAWAY_MESSAGE, args[2]);
                cons_show("Auto away message set to: \"%s\".", args[2]);
            }

            return TRUE;
        } else if (g_strcmp0(args[1], "xa") == 0 && args[2] != NULL) {
            if (g_strcmp0(args[2], "off") == 0) {
                prefs_set_string(PREF_AUTOXA_MESSAGE, NULL);
                cons_show("Auto xa message cleared.");
            } else {
                prefs_set_string(PREF_AUTOXA_MESSAGE, args[2]);
                cons_show("Auto xa message set to: \"%s\".", args[2]);
            }

            return TRUE;
        } else {
            cons_bad_cmd_usage(command);
            return TRUE;
        }
    }

    if (g_strcmp0(args[0], "check") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Online check", PREF_AUTOAWAY_CHECK);
        return TRUE;
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_priority(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    char* value = args[0];

    int intval = 0;
    char* err_msg = NULL;
    gboolean res = strtoi_range(value, &intval, -128, 127, &err_msg);
    if (res) {
        accounts_set_priority_all(session_get_account_name(), intval);
        resource_presence_t last_presence = accounts_get_last_presence(session_get_account_name());
        cl_ev_presence_send(last_presence, 0);
        cons_show("Priority set to %d.", intval);
    } else {
        cons_show(err_msg);
        free(err_msg);
    }

    return TRUE;
}

gboolean
cmd_vercheck(ProfWin* window, const char* const command, gchar** args)
{
    int num_args = g_strv_length(args);

    if (num_args == 0) {
        cons_check_version(TRUE);
        return TRUE;
    } else {
        _cmd_set_boolean_preference(args[0], command, "Version checking", PREF_VERCHECK);
        return TRUE;
    }
}

gboolean
cmd_xmlconsole(ProfWin* window, const char* const command, gchar** args)
{
    ProfXMLWin* xmlwin = wins_get_xmlconsole();
    if (xmlwin) {
        ui_focus_win((ProfWin*)xmlwin);
    } else {
        ProfWin* window = wins_new_xmlconsole();
        ui_focus_win(window);
    }

    return TRUE;
}

gboolean
cmd_flash(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "Screen flash", PREF_FLASH);
    return TRUE;
}

gboolean
cmd_tray(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_GTK
    if (g_strcmp0(args[0], "timer") == 0) {
        if (args[1] == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        if (prefs_get_boolean(PREF_TRAY) == FALSE) {
            cons_show("Tray icon not currently enabled, see /help tray");
            return TRUE;
        }

        int intval = 0;
        char* err_msg = NULL;
        gboolean res = strtoi_range(args[1], &intval, 1, 10, &err_msg);
        if (res) {
            if (intval == 1) {
                cons_show("Tray timer set to 1 second.");
            } else {
                cons_show("Tray timer set to %d seconds.", intval);
            }
            prefs_set_tray_timer(intval);
            if (prefs_get_boolean(PREF_TRAY)) {
                tray_set_timer(intval);
            }
        } else {
            cons_show(err_msg);
            free(err_msg);
        }

        return TRUE;
    } else if (g_strcmp0(args[0], "read") == 0) {
        if (prefs_get_boolean(PREF_TRAY) == FALSE) {
            cons_show("Tray icon not currently enabled, see /help tray");
        } else if (g_strcmp0(args[1], "on") == 0) {
            prefs_set_boolean(PREF_TRAY_READ, TRUE);
            cons_show("Tray icon enabled when no unread messages.");
        } else if (g_strcmp0(args[1], "off") == 0) {
            prefs_set_boolean(PREF_TRAY_READ, FALSE);
            cons_show("Tray icon disabled when no unread messages.");
        } else {
            cons_bad_cmd_usage(command);
        }

        return TRUE;
    } else {
        gboolean old = prefs_get_boolean(PREF_TRAY);
        _cmd_set_boolean_preference(args[0], command, "Tray icon", PREF_TRAY);
        gboolean new = prefs_get_boolean(PREF_TRAY);
        if (old != new) {
            if (new) {
                tray_enable();
            } else {
                tray_disable();
            }
        }

        return TRUE;
    }
#else
    cons_show("This version of Profanity has not been built with GTK Tray Icon support enabled");
    return TRUE;
#endif
}

gboolean
cmd_intype(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "console") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Show contact typing in console", PREF_INTYPE_CONSOLE);
    } else if (g_strcmp0(args[0], "titlebar") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Show contact typing in titlebar", PREF_INTYPE);
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_splash(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "Splash screen", PREF_SPLASH);
    return TRUE;
}

gboolean
cmd_autoconnect(ProfWin* window, const char* const command, gchar** args)
{
    if (strcmp(args[0], "off") == 0) {
        prefs_set_string(PREF_CONNECT_ACCOUNT, NULL);
        cons_show("Autoconnect account disabled.");
    } else if (strcmp(args[0], "set") == 0) {
        if (args[1] == NULL || strlen(args[1]) == 0) {
            cons_bad_cmd_usage(command);
        } else {
            if (accounts_account_exists(args[1])) {
                prefs_set_string(PREF_CONNECT_ACCOUNT, args[1]);
                cons_show("Autoconnect account set to: %s.", args[1]);
            } else {
                cons_show_error("Account '%s' does not exist.", args[1]);
            }
        }
    } else {
        cons_bad_cmd_usage(command);
    }
    return TRUE;
}

gboolean
cmd_logging(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        cons_logging_setting();
        return TRUE;
    }

    if (strcmp(args[0], "chat") == 0 && args[1] != NULL) {
        _cmd_set_boolean_preference(args[1], command, "Chat logging", PREF_CHLOG);

        // if set to off, disable history
        if (strcmp(args[1], "off") == 0) {
            prefs_set_boolean(PREF_HISTORY, FALSE);
        }

        return TRUE;
    } else if (g_strcmp0(args[0], "group") == 0 && args[1] != NULL) {
        if (g_strcmp0(args[1], "on") == 0 || g_strcmp0(args[1], "off") == 0) {
            _cmd_set_boolean_preference(args[1], command, "Groupchat logging", PREF_GRLOG);
            return TRUE;
        }
    }

    cons_bad_cmd_usage(command);
    return TRUE;
}

gboolean
cmd_history(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        return FALSE;
    }

    _cmd_set_boolean_preference(args[0], command, "Chat history", PREF_HISTORY);

    // if set to on, set chlog (/logging chat on)
    if (strcmp(args[0], "on") == 0) {
        prefs_set_boolean(PREF_CHLOG, TRUE);
    }

    return TRUE;
}

gboolean
cmd_carbons(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        return FALSE;
    }

    _cmd_set_boolean_preference(args[0], command, "Message carbons preference", PREF_CARBONS);

    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status == JABBER_CONNECTED) {
        // enable carbons
        if (strcmp(args[0], "on") == 0) {
            iq_enable_carbons();
        } else if (strcmp(args[0], "off") == 0) {
            iq_disable_carbons();
        }
    }

    return TRUE;
}

gboolean
cmd_receipts(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "send") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Send delivery receipts", PREF_RECEIPTS_SEND);
        if (g_strcmp0(args[1], "on") == 0) {
            caps_add_feature(XMPP_FEATURE_RECEIPTS);
        }
        if (g_strcmp0(args[1], "off") == 0) {
            caps_remove_feature(XMPP_FEATURE_RECEIPTS);
        }
    } else if (g_strcmp0(args[0], "request") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Request delivery receipts", PREF_RECEIPTS_REQUEST);
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_plugins_install(ProfWin* window, const char* const command, gchar** args)
{
    char* path = NULL;

    if (args[1] == NULL) {
        cons_show("Please provide a path to the plugin file or directory, see /help plugins");
        return TRUE;
    }

    // take whole path or build it in case it's just the plugin name
    if (strchr(args[1], '/')) {
        path = get_expanded_path(args[1]);
    } else {
        if (g_str_has_suffix(args[1], ".py")) {
            path = g_strdup_printf("%s/%s", GLOBAL_PYTHON_PLUGINS_PATH, args[1]);
        } else if (g_str_has_suffix(args[1], ".so")) {
            path = g_strdup_printf("%s/%s", GLOBAL_C_PLUGINS_PATH, args[1]);
        } else {
            cons_show("Plugins must have one of the following extensions: '.py' '.so'");
            return TRUE;
        }
    }

    if (access(path, R_OK) != 0) {
        cons_show("Cannot access: %s", path);
        free(path);
        return TRUE;
    }

    if (is_regular_file(path)) {
        if (!g_str_has_suffix(path, ".py") && !g_str_has_suffix(path, ".so")) {
            cons_show("Plugins must have one of the following extensions: '.py' '.so'");
            free(path);
            return TRUE;
        }

        GString* error_message = g_string_new(NULL);
        gchar* plugin_name = g_path_get_basename(path);
        gboolean result = plugins_install(plugin_name, path, error_message);
        if (result) {
            cons_show("Plugin installed and loaded: %s", plugin_name);
        } else {
            cons_show("Failed to install plugin: %s. %s", plugin_name, error_message->str);
        }
        g_free(plugin_name);
        g_string_free(error_message, TRUE);
        free(path);
        return TRUE;
    } else if (is_dir(path)) {
        PluginsInstallResult* result = plugins_install_all(path);
        if (result->installed || result->failed) {
            if (result->installed) {
                cons_show("");
                cons_show("Installed and loaded plugins:");
                GSList* curr = result->installed;
                while (curr) {
                    cons_show("  %s", curr->data);
                    curr = g_slist_next(curr);
                }
            }
            if (result->failed) {
                cons_show("");
                cons_show("Failed installs:");
                GSList* curr = result->failed;
                while (curr) {
                    cons_show("  %s", curr->data);
                    curr = g_slist_next(curr);
                }
            }
        } else {
            cons_show("No plugins found in: %s", path);
        }
        free(path);
        plugins_free_install_result(result);
        return TRUE;
    } else {
        cons_show("Argument must be a file or directory.");
    }

    free(path);
    return TRUE;
}

gboolean
cmd_plugins_update(ProfWin* window, const char* const command, gchar** args)
{
    char* path;

    if (args[1] == NULL) {
        cons_show("Please provide a path to the plugin file, see /help plugins");
        return TRUE;
    } else {
        path = get_expanded_path(args[1]);
    }

    if (access(path, R_OK) != 0) {
        cons_show("File not found: %s", path);
        free(path);
        return TRUE;
    }

    if (is_regular_file(path)) {
        if (!g_str_has_suffix(path, ".py") && !g_str_has_suffix(path, ".so")) {
            cons_show("Plugins must have one of the following extensions: '.py' '.so'");
            free(path);
            return TRUE;
        }

        GString* error_message = g_string_new(NULL);
        gchar* plugin_name = g_path_get_basename(path);
        if (plugins_unload(plugin_name)) {
            if (plugins_uninstall(plugin_name)) {
                if (plugins_install(plugin_name, path, error_message)) {
                    cons_show("Plugin installed: %s", plugin_name);
                } else {
                    cons_show("Failed to install plugin: %s. %s", plugin_name, error_message->str);
                }
            } else {
                cons_show("Failed to uninstall plugin: %s.", plugin_name);
            }
        } else {
            cons_show("Failed to unload plugin: %s.", plugin_name);
        }
        g_free(plugin_name);
        g_string_free(error_message, TRUE);
        free(path);
        return TRUE;
    }

    free(path);
    cons_show("Argument must be a file.");
    return TRUE;
}

gboolean
cmd_plugins_uninstall(ProfWin* window, const char* const command, gchar** args)
{
    if (args[1] == NULL) {
        cons_show("Please specify plugin name, see /help plugins");
        return TRUE;
    }

    gboolean res = plugins_uninstall(args[1]);
    if (res) {
        cons_show("Uninstalled plugin: %s", args[1]);
    } else {
        cons_show("Failed to uninstall plugin: %s", args[1]);
    }

    return TRUE;
}

gboolean
cmd_plugins_load(ProfWin* window, const char* const command, gchar** args)
{
    if (args[1] == NULL) {
        GSList* loaded = plugins_load_all();
        if (loaded) {
            cons_show("Loaded plugins:");
            GSList* curr = loaded;
            while (curr) {
                cons_show("  %s", curr->data);
                curr = g_slist_next(curr);
            }
            g_slist_free_full(loaded, g_free);
        } else {
            cons_show("No plugins loaded.");
        }
        return TRUE;
    }

    GString* error_message = g_string_new(NULL);
    gboolean res = plugins_load(args[1], error_message);
    if (res) {
        cons_show("Loaded plugin: %s", args[1]);
    } else {
        cons_show("Failed to load plugin: %s. %s", args[1], error_message->str);
    }
    g_string_free(error_message, TRUE);

    return TRUE;
}

gboolean
cmd_plugins_unload(ProfWin* window, const char* const command, gchar** args)
{
    if (args[1] == NULL) {
        gboolean res = plugins_unload_all();
        if (res) {
            cons_show("Unloaded all plugins.");
        } else {
            cons_show("No plugins unloaded.");
        }
        return TRUE;
    }

    gboolean res = plugins_unload(args[1]);
    if (res) {
        cons_show("Unloaded plugin: %s", args[1]);
    } else {
        cons_show("Failed to unload plugin: %s", args[1]);
    }

    return TRUE;
}

gboolean
cmd_plugins_reload(ProfWin* window, const char* const command, gchar** args)
{
    if (args[1] == NULL) {
        plugins_reload_all();
        cons_show("Reloaded all plugins");
        return TRUE;
    }

    GString* error_message = g_string_new(NULL);
    gboolean res = plugins_reload(args[1], error_message);
    if (res) {
        cons_show("Reloaded plugin: %s", args[1]);
    } else {
        cons_show("Failed to reload plugin: %s, %s", args[1], error_message);
    }
    g_string_free(error_message, TRUE);

    return TRUE;
}

gboolean
cmd_plugins_python_version(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_PYTHON
    const char* version = python_get_version_string();
    cons_show("Python version:");
    cons_show("%s", version);
#else
    cons_show("This build does not support python plugins.");
#endif
    return TRUE;
}

gboolean
cmd_plugins(ProfWin* window, const char* const command, gchar** args)
{
    GDir* global_pyp_dir = NULL;
    GDir* global_cp_dir = NULL;

    if (access(GLOBAL_PYTHON_PLUGINS_PATH, R_OK) == 0) {
        GError* error = NULL;
        global_pyp_dir = g_dir_open(GLOBAL_PYTHON_PLUGINS_PATH, 0, &error);
        if (error) {
            log_warning("Error when trying to open global plugins path: %s", GLOBAL_PYTHON_PLUGINS_PATH);
            g_error_free(error);
            return TRUE;
        }
    }
    if (access(GLOBAL_C_PLUGINS_PATH, R_OK) == 0) {
        GError* error = NULL;
        global_cp_dir = g_dir_open(GLOBAL_C_PLUGINS_PATH, 0, &error);
        if (error) {
            log_warning("Error when trying to open global plugins path: %s", GLOBAL_C_PLUGINS_PATH);
            g_error_free(error);
            return TRUE;
        }
    }
    if (global_pyp_dir) {
        const gchar* filename;
        cons_show("The following Python plugins are available globally and can be installed:");
        while ((filename = g_dir_read_name(global_pyp_dir))) {
            cons_show("  %s", filename);
        }
    }
    if (global_cp_dir) {
        const gchar* filename;
        cons_show("The following C plugins are available globally and can be installed:");
        while ((filename = g_dir_read_name(global_cp_dir))) {
            cons_show("  %s", filename);
        }
    }

    GSList* unloaded_plugins = plugins_unloaded_list();
    if (unloaded_plugins) {
        GSList* curr = unloaded_plugins;
        cons_show("The following plugins already installed and can be loaded:");
        while (curr) {
            cons_show("  %s", curr->data);
            curr = g_slist_next(curr);
        }
        g_slist_free_full(unloaded_plugins, g_free);
    }

    GList* plugins = plugins_loaded_list();
    if (plugins == NULL) {
        cons_show("No loaded plugins.");
        return TRUE;
    }

    GList* curr = plugins;
    cons_show("Loaded plugins:");
    while (curr) {
        cons_show("  %s", curr->data);
        curr = g_list_next(curr);
    }
    g_list_free(plugins);

    return TRUE;
}

gboolean
cmd_pgp(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBGPGME
    if (args[0] == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (strcmp(args[0], "char") == 0) {
        if (args[1] == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else if (g_utf8_strlen(args[1], 4) == 1) {
            if (prefs_set_pgp_char(args[1])) {
                cons_show("PGP char set to %s.", args[1]);
            } else {
                cons_show_error("Could not set PGP char: %s.", args[1]);
            }
            return TRUE;
        }
        cons_bad_cmd_usage(command);
        return TRUE;
    } else if (g_strcmp0(args[0], "log") == 0) {
        char* choice = args[1];
        if (g_strcmp0(choice, "on") == 0) {
            prefs_set_string(PREF_PGP_LOG, "on");
            cons_show("PGP messages will be logged as plaintext.");
            if (!prefs_get_boolean(PREF_CHLOG)) {
                cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
            }
        } else if (g_strcmp0(choice, "off") == 0) {
            prefs_set_string(PREF_PGP_LOG, "off");
            cons_show("PGP message logging disabled.");
        } else if (g_strcmp0(choice, "redact") == 0) {
            prefs_set_string(PREF_PGP_LOG, "redact");
            cons_show("PGP messages will be logged as '[redacted]'.");
            if (!prefs_get_boolean(PREF_CHLOG)) {
                cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
            }
        } else {
            cons_bad_cmd_usage(command);
        }
        return TRUE;
    }

    if (g_strcmp0(args[0], "keys") == 0) {
        GHashTable* keys = p_gpg_list_keys();
        if (!keys || g_hash_table_size(keys) == 0) {
            cons_show("No keys found");
            return TRUE;
        }

        cons_show("PGP keys:");
        GList* keylist = g_hash_table_get_keys(keys);
        GList* curr = keylist;
        while (curr) {
            ProfPGPKey* key = g_hash_table_lookup(keys, curr->data);
            cons_show("  %s", key->name);
            cons_show("    ID          : %s", key->id);
            char* format_fp = p_gpg_format_fp_str(key->fp);
            cons_show("    Fingerprint : %s", format_fp);
            free(format_fp);
            if (key->secret) {
                cons_show("    Type        : PUBLIC, PRIVATE");
            } else {
                cons_show("    Type        : PUBLIC");
            }
            curr = g_list_next(curr);
        }
        g_list_free(keylist);
        p_gpg_free_keys(keys);
        return TRUE;
    }

    if (g_strcmp0(args[0], "setkey") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }

        char* jid = args[1];
        if (!args[1]) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        char* keyid = args[2];
        if (!args[2]) {
            cons_bad_cmd_usage(command);
            return TRUE;
        }

        gboolean res = p_gpg_addkey(jid, keyid);
        if (!res) {
            cons_show("Key ID not found.");
        } else {
            cons_show("Key %s set for %s.", keyid, jid);
        }

        return TRUE;
    }

    if (g_strcmp0(args[0], "contacts") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }
        GHashTable* pubkeys = p_gpg_pubkeys();
        GList* jids = g_hash_table_get_keys(pubkeys);
        if (!jids) {
            cons_show("No contacts found with PGP public keys assigned.");
            return TRUE;
        }

        cons_show("Assigned PGP public keys:");
        GList* curr = jids;
        while (curr) {
            char* jid = curr->data;
            ProfPGPPubKeyId* pubkeyid = g_hash_table_lookup(pubkeys, jid);
            if (pubkeyid->received) {
                cons_show("  %s: %s (received)", jid, pubkeyid->id);
            } else {
                cons_show("  %s: %s (stored)", jid, pubkeyid->id);
            }
            curr = g_list_next(curr);
        }
        g_list_free(jids);
        return TRUE;
    }

    if (g_strcmp0(args[0], "libver") == 0) {
        const char* libver = p_gpg_libver();
        if (!libver) {
            cons_show("Could not get libgpgme version");
            return TRUE;
        }

        GString* fullstr = g_string_new("Using libgpgme version ");
        g_string_append(fullstr, libver);
        cons_show("%s", fullstr->str);
        g_string_free(fullstr, TRUE);

        return TRUE;
    }

    if (g_strcmp0(args[0], "start") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You must be connected to start PGP encrpytion.");
            return TRUE;
        }

        if (window->type != WIN_CHAT && args[1] == NULL) {
            cons_show("You must be in a regular chat window to start PGP encrpytion.");
            return TRUE;
        }

        ProfChatWin* chatwin = NULL;

        if (args[1]) {
            char* contact = args[1];
            char* barejid = roster_barejid_from_name(contact);
            if (barejid == NULL) {
                barejid = contact;
            }

            chatwin = wins_get_chat(barejid);
            if (!chatwin) {
                chatwin = chatwin_new(barejid);
            }
            ui_focus_win((ProfWin*)chatwin);
        } else {
            chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        }

        if (chatwin->is_otr) {
            win_println(window, THEME_DEFAULT, "!", "You must end the OTR session to start PGP encryption.");
            return TRUE;
        }

        if (chatwin->pgp_send) {
            win_println(window, THEME_DEFAULT, "!", "You have already started PGP encryption.");
            return TRUE;
        }

        if (chatwin->is_omemo) {
            win_println(window, THEME_DEFAULT, "!", "You must disable OMEMO before starting an PGP encrypted session.");
            return TRUE;
        }

        ProfAccount* account = accounts_get_account(session_get_account_name());
        char* err_str = NULL;
        if (!p_gpg_valid_key(account->pgp_keyid, &err_str)) {
            win_println(window, THEME_DEFAULT, "!", "Invalid PGP key ID %s: %s, cannot start PGP encryption.", account->pgp_keyid, err_str);
            free(err_str);
            account_free(account);
            return TRUE;
        }
        free(err_str);
        account_free(account);

        if (!p_gpg_available(chatwin->barejid)) {
            win_println(window, THEME_DEFAULT, "!", "No PGP key found for %s.", chatwin->barejid);
            return TRUE;
        }

        chatwin->pgp_send = TRUE;
        accounts_add_pgp_state(session_get_account_name(), chatwin->barejid, TRUE);
        win_println(window, THEME_DEFAULT, "!", "PGP encryption enabled.");
        return TRUE;
    }

    if (g_strcmp0(args[0], "end") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
            return TRUE;
        }

        if (window->type != WIN_CHAT) {
            cons_show("You must be in a regular chat window to end PGP encrpytion.");
            return TRUE;
        }

        ProfChatWin* chatwin = (ProfChatWin*)window;
        if (chatwin->pgp_send == FALSE) {
            win_println(window, THEME_DEFAULT, "!", "PGP encryption is not currently enabled.");
            return TRUE;
        }

        chatwin->pgp_send = FALSE;
        accounts_add_pgp_state(session_get_account_name(), chatwin->barejid, FALSE);
        win_println(window, THEME_DEFAULT, "!", "PGP encryption disabled.");
        return TRUE;
    }

    if (g_strcmp0(args[0], "sendfile") == 0) {
        _cmd_set_boolean_preference(args[1], command, "Sending unencrypted files using /sendfile while otherwise using PGP", PREF_PGP_SENDFILE);
        return TRUE;
    }

    cons_bad_cmd_usage(command);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with PGP support enabled");
    return TRUE;
#endif
}

#ifdef HAVE_LIBGPGME

gboolean
cmd_ox(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (strcmp(args[0], "char") == 0) {
        if (args[1] == NULL) {
            cons_bad_cmd_usage(command);
            return TRUE;
        } else if (g_utf8_strlen(args[1], 4) == 1) {
            if (prefs_set_ox_char(args[1])) {
                cons_show("OX char set to %s.", args[1]);
            } else {
                cons_show_error("Could not set OX char: %s.", args[1]);
            }
            return TRUE;
        }
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    // The '/ox keys' command - same like in pgp
    // Should we move this to a common command
    // e.g. '/openpgp keys'?.
    else if (g_strcmp0(args[0], "keys") == 0) {
        GHashTable* keys = p_gpg_list_keys();
        if (!keys || g_hash_table_size(keys) == 0) {
            cons_show("No keys found");
            return TRUE;
        }

        cons_show("OpenPGP keys:");
        GList* keylist = g_hash_table_get_keys(keys);
        GList* curr = keylist;
        while (curr) {
            ProfPGPKey* key = g_hash_table_lookup(keys, curr->data);
            cons_show("  %s", key->name);
            cons_show("    ID          : %s", key->id);
            char* format_fp = p_gpg_format_fp_str(key->fp);
            cons_show("    Fingerprint : %s", format_fp);
            free(format_fp);
            if (key->secret) {
                cons_show("    Type        : PUBLIC, PRIVATE");
            } else {
                cons_show("    Type        : PUBLIC");
            }
            curr = g_list_next(curr);
        }
        g_list_free(keylist);
        p_gpg_free_keys(keys);
        return TRUE;
    }

    else if (g_strcmp0(args[0], "contacts") == 0) {
        GHashTable* keys = ox_gpg_public_keys();
        cons_show("OpenPGP keys:");
        GList* keylist = g_hash_table_get_keys(keys);
        GList* curr = keylist;

        GSList* roster_list = NULL;
        jabber_conn_status_t conn_status = connection_get_status();
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You are not currently connected.");
        } else {
            roster_list = roster_get_contacts(ROSTER_ORD_NAME);
        }

        while (curr) {
            ProfPGPKey* key = g_hash_table_lookup(keys, curr->data);
            PContact contact = NULL;
            if (roster_list) {
                GSList* curr_c = roster_list;
                while (!contact && curr_c) {
                    contact = curr_c->data;
                    const char* jid = p_contact_barejid(contact);
                    GString* xmppuri = g_string_new("xmpp:");
                    g_string_append(xmppuri, jid);
                    if (g_strcmp0(key->name, xmppuri->str)) {
                        contact = NULL;
                    }
                    curr_c = g_slist_next(curr_c);
                }
            }

            if (contact) {
                cons_show("%s - %s", key->fp, key->name);
            } else {
                cons_show("%s - %s (not in roster)", key->fp, key->name);
            }
            curr = g_list_next(curr);
        }

    } else if (g_strcmp0(args[0], "start") == 0) {
        jabber_conn_status_t conn_status = connection_get_status();
        if (conn_status != JABBER_CONNECTED) {
            cons_show("You must be connected to start OX encrpytion.");
            return TRUE;
        }

        if (window->type != WIN_CHAT && args[1] == NULL) {
            cons_show("You must be in a regular chat window to start OX encrpytion.");
            return TRUE;
        }

        ProfChatWin* chatwin = NULL;

        if (args[1]) {
            char* contact = args[1];
            char* barejid = roster_barejid_from_name(contact);
            if (barejid == NULL) {
                barejid = contact;
            }

            chatwin = wins_get_chat(barejid);
            if (!chatwin) {
                chatwin = chatwin_new(barejid);
            }
            ui_focus_win((ProfWin*)chatwin);
        } else {
            chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        }

        if (chatwin->is_otr) {
            win_println(window, THEME_DEFAULT, "!", "You must end the OTR session to start OX encryption.");
            return TRUE;
        }

        if (chatwin->pgp_send) {
            win_println(window, THEME_DEFAULT, "!", "You must end the PGP session to start OX encryption.");
            return TRUE;
        }

        if (chatwin->is_ox) {
            win_println(window, THEME_DEFAULT, "!", "You have already started an OX encrypted session.");
            return TRUE;
        }

        ProfAccount* account = accounts_get_account(session_get_account_name());

        if (!ox_is_private_key_available(account->jid)) {
            win_println(window, THEME_DEFAULT, "!", "No private OpenPGP found, cannot start OX encryption.");
            account_free(account);
            return TRUE;
        }
        account_free(account);

        if (!ox_is_public_key_available(chatwin->barejid)) {
            win_println(window, THEME_DEFAULT, "!", "No OX-OpenPGP key found for %s.", chatwin->barejid);
            return TRUE;
        }

        chatwin->is_ox = TRUE;
        accounts_add_ox_state(session_get_account_name(), chatwin->barejid, TRUE);
        win_println(window, THEME_DEFAULT, "!", "OX encryption enabled.");
        return TRUE;
    } else if (g_strcmp0(args[0], "end") == 0) {
        if (window->type != WIN_CHAT && args[1] == NULL) {
            cons_show("You must be in a regular chat window to stop OX encryption.");
            return TRUE;
        }

        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);

        if (!chatwin->is_ox) {
            win_println(window, THEME_DEFAULT, "!", "No OX session has been started.");
        } else {
            chatwin->is_ox = FALSE;
            accounts_add_ox_state(session_get_account_name(), chatwin->barejid, FALSE);
            win_println(window, THEME_DEFAULT, "!", "OX encryption disabled.");
        }
        return TRUE;
    } else if (g_strcmp0(args[0], "announce") == 0) {
        if (args[1]) {
            gchar* filename = get_expanded_path(args[1]);

            if (access(filename, R_OK) != 0) {
                cons_show_error("File not found: %s", filename);
                g_free(filename);
                return TRUE;
            }

            if (!is_regular_file(filename)) {
                cons_show_error("Not a file: %s", filename);
                g_free(filename);
                return TRUE;
            }

            ox_announce_public_key(filename);
            free(filename);
        } else {
            cons_show("Filename is required");
        }
    } else if (g_strcmp0(args[0], "discover") == 0) {
        if (args[1]) {
            ox_discover_public_key(args[1]);
        } else {
            cons_show("To discover the OpenPGP keys of an user, the JID is required");
        }
    } else if (g_strcmp0(args[0], "request") == 0) {
        if (args[1] && args[2]) {
            ox_request_public_key(args[1], args[2]);
        } else {
            cons_show("JID and OpenPGP Key ID are required");
        }
    } else {
        cons_bad_cmd_usage(command);
    }
    return TRUE;
}

gboolean
cmd_ox_log(ProfWin* window, const char* const command, gchar** args)
{
    char* choice = args[1];
    if (g_strcmp0(choice, "on") == 0) {
        prefs_set_string(PREF_OX_LOG, "on");
        cons_show("OX messages will be logged as plaintext.");
        if (!prefs_get_boolean(PREF_CHLOG)) {
            cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
        }
    } else if (g_strcmp0(choice, "off") == 0) {
        prefs_set_string(PREF_OX_LOG, "off");
        cons_show("OX message logging disabled.");
    } else if (g_strcmp0(choice, "redact") == 0) {
        prefs_set_string(PREF_OX_LOG, "redact");
        cons_show("OX messages will be logged as '[redacted]'.");
        if (!prefs_get_boolean(PREF_CHLOG)) {
            cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
        }
    } else {
        cons_bad_cmd_usage(command);
    }
    return TRUE;
}
#endif // HAVE_LIBGPGME

gboolean
cmd_otr_char(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (args[1] == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    } else if (g_utf8_strlen(args[1], 4) == 1) {
        if (prefs_set_otr_char(args[1])) {
            cons_show("OTR char set to %s.", args[1]);
        } else {
            cons_show_error("Could not set OTR char: %s.", args[1]);
        }
        return TRUE;
    }
    cons_bad_cmd_usage(command);
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
#endif
    return TRUE;
}

gboolean
cmd_otr_log(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    char* choice = args[1];
    if (g_strcmp0(choice, "on") == 0) {
        prefs_set_string(PREF_OTR_LOG, "on");
        cons_show("OTR messages will be logged as plaintext.");
        if (!prefs_get_boolean(PREF_CHLOG)) {
            cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
        }
    } else if (g_strcmp0(choice, "off") == 0) {
        prefs_set_string(PREF_OTR_LOG, "off");
        cons_show("OTR message logging disabled.");
    } else if (g_strcmp0(choice, "redact") == 0) {
        prefs_set_string(PREF_OTR_LOG, "redact");
        cons_show("OTR messages will be logged as '[redacted]'.");
        if (!prefs_get_boolean(PREF_CHLOG)) {
            cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
        }
    } else {
        cons_bad_cmd_usage(command);
    }
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_libver(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    char* version = otr_libotr_version();
    cons_show("Using libotr version %s", version);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_policy(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (args[1] == NULL) {
        char* policy = prefs_get_string(PREF_OTR_POLICY);
        cons_show("OTR policy is now set to: %s", policy);
        g_free(policy);
        return TRUE;
    }

    char* choice = args[1];
    if (!_string_matches_one_of("OTR policy", choice, FALSE, "manual", "opportunistic", "always", NULL)) {
        return TRUE;
    }

    char* contact = args[2];
    if (contact == NULL) {
        prefs_set_string(PREF_OTR_POLICY, choice);
        cons_show("OTR policy is now set to: %s", choice);
        return TRUE;
    }

    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected to set the OTR policy for a contact.");
        return TRUE;
    }

    char* contact_jid = roster_barejid_from_name(contact);
    if (contact_jid == NULL) {
        contact_jid = contact;
    }
    accounts_add_otr_policy(session_get_account_name(), contact_jid, choice);
    cons_show("OTR policy for %s set to: %s", contact_jid, choice);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_gen(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    ProfAccount* account = accounts_get_account(session_get_account_name());
    otr_keygen(account);
    account_free(account);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_myfp(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (!otr_key_loaded()) {
        win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a private key, use '/otr gen'");
        return TRUE;
    }

    char* fingerprint = otr_get_my_fingerprint();
    win_println(window, THEME_DEFAULT, "!", "Your OTR fingerprint: %s", fingerprint);
    free(fingerprint);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_theirfp(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (window->type != WIN_CHAT) {
        win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to view a recipient's fingerprint.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;
    assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
    if (chatwin->is_otr == FALSE) {
        win_println(window, THEME_DEFAULT, "!", "You are not currently in an OTR session.");
        return TRUE;
    }

    char* fingerprint = otr_get_their_fingerprint(chatwin->barejid);
    win_println(window, THEME_DEFAULT, "!", "%s's OTR fingerprint: %s", chatwin->barejid, fingerprint);
    free(fingerprint);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_start(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    // recipient supplied
    if (args[1]) {
        char* contact = args[1];
        char* barejid = roster_barejid_from_name(contact);
        if (barejid == NULL) {
            barejid = contact;
        }

        ProfChatWin* chatwin = wins_get_chat(barejid);
        if (!chatwin) {
            chatwin = chatwin_new(barejid);
        }
        ui_focus_win((ProfWin*)chatwin);

        if (chatwin->pgp_send) {
            win_println(window, THEME_DEFAULT, "!", "You must disable PGP encryption before starting an OTR session.");
            return TRUE;
        }

        if (chatwin->is_omemo) {
            win_println(window, THEME_DEFAULT, "!", "You must disable OMEMO before starting an OTR session.");
            return TRUE;
        }

        if (chatwin->is_otr) {
            win_println(window, THEME_DEFAULT, "!", "You are already in an OTR session.");
            return TRUE;
        }

        if (!otr_key_loaded()) {
            win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a private key, use '/otr gen'");
            return TRUE;
        }

        if (!otr_is_secure(barejid)) {
            char* otr_query_message = otr_start_query();
            char* id = message_send_chat_otr(barejid, otr_query_message, FALSE, NULL);
            free(id);
            return TRUE;
        }

        chatwin_otr_secured(chatwin, otr_is_trusted(barejid));
        return TRUE;

        // no recipient, use current chat
    } else {
        if (window->type != WIN_CHAT) {
            win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to start an OTR session.");
            return TRUE;
        }

        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        if (chatwin->pgp_send) {
            win_println(window, THEME_DEFAULT, "!", "You must disable PGP encryption before starting an OTR session.");
            return TRUE;
        }

        if (chatwin->is_otr) {
            win_println(window, THEME_DEFAULT, "!", "You are already in an OTR session.");
            return TRUE;
        }

        if (!otr_key_loaded()) {
            win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a private key, use '/otr gen'");
            return TRUE;
        }

        char* otr_query_message = otr_start_query();
        char* id = message_send_chat_otr(chatwin->barejid, otr_query_message, FALSE, NULL);

        free(id);
        return TRUE;
    }
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_end(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (window->type != WIN_CHAT) {
        win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to use OTR.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;
    assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
    if (chatwin->is_otr == FALSE) {
        win_println(window, THEME_DEFAULT, "!", "You are not currently in an OTR session.");
        return TRUE;
    }

    chatwin_otr_unsecured(chatwin);
    otr_end_session(chatwin->barejid);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_trust(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (window->type != WIN_CHAT) {
        win_println(window, THEME_DEFAULT, "-", "You must be in an OTR session to trust a recipient.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;
    assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
    if (chatwin->is_otr == FALSE) {
        win_println(window, THEME_DEFAULT, "!", "You are not currently in an OTR session.");
        return TRUE;
    }

    chatwin_otr_trust(chatwin);
    otr_trust(chatwin->barejid);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_untrust(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (window->type != WIN_CHAT) {
        win_println(window, THEME_DEFAULT, "-", "You must be in an OTR session to untrust a recipient.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;
    assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
    if (chatwin->is_otr == FALSE) {
        win_println(window, THEME_DEFAULT, "!", "You are not currently in an OTR session.");
        return TRUE;
    }

    chatwin_otr_untrust(chatwin);
    otr_untrust(chatwin->barejid);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_secret(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (window->type != WIN_CHAT) {
        win_println(window, THEME_DEFAULT, "-", "You must be in an OTR session to trust a recipient.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;
    assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
    if (chatwin->is_otr == FALSE) {
        win_println(window, THEME_DEFAULT, "!", "You are not currently in an OTR session.");
        return TRUE;
    }

    char* secret = args[1];
    if (secret == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    otr_smp_secret(chatwin->barejid, secret);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_question(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    char* question = args[1];
    char* answer = args[2];
    if (question == NULL || answer == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (window->type != WIN_CHAT) {
        win_println(window, THEME_DEFAULT, "-", "You must be in an OTR session to trust a recipient.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;
    assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
    if (chatwin->is_otr == FALSE) {
        win_println(window, THEME_DEFAULT, "!", "You are not currently in an OTR session.");
        return TRUE;
    }

    otr_smp_question(chatwin->barejid, question, answer);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_answer(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (window->type != WIN_CHAT) {
        win_println(window, THEME_DEFAULT, "-", "You must be in an OTR session to trust a recipient.");
        return TRUE;
    }

    ProfChatWin* chatwin = (ProfChatWin*)window;
    assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
    if (chatwin->is_otr == FALSE) {
        win_println(window, THEME_DEFAULT, "!", "You are not currently in an OTR session.");
        return TRUE;
    }

    char* answer = args[1];
    if (answer == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    otr_smp_answer(chatwin->barejid, answer);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_otr_sendfile(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_LIBOTR
    _cmd_set_boolean_preference(args[1], command, "Sending unencrypted files in an OTR session via /sendfile", PREF_OTR_SENDFILE);

    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

gboolean
cmd_command_list(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (connection_supports(XMPP_FEATURE_COMMANDS) == FALSE) {
        cons_show("Server does not support ad hoc commands (%s).", XMPP_FEATURE_COMMANDS);
        return TRUE;
    }

    char* jid = args[1];
    if (jid == NULL) {
        switch (window->type) {
        case WIN_MUC:
        {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            jid = mucwin->roomjid;
            break;
        }
        case WIN_CHAT:
        {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
            jid = chatwin->barejid;
            break;
        }
        case WIN_PRIVATE:
        {
            ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
            assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
            jid = privatewin->fulljid;
            break;
        }
        case WIN_CONSOLE:
        {
            jid = connection_get_domain();
            break;
        }
        default:
            cons_show("Cannot send ad hoc commands.");
            return TRUE;
        }
    }

    iq_command_list(jid);

    cons_show("List available ad hoc commands");
    return TRUE;
}

gboolean
cmd_command_exec(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (connection_supports(XMPP_FEATURE_COMMANDS) == FALSE) {
        cons_show("Server does not support ad hoc commands (%s).", XMPP_FEATURE_COMMANDS);
        return TRUE;
    }

    if (args[1] == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    char* jid = args[2];
    if (jid == NULL) {
        switch (window->type) {
        case WIN_MUC:
        {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            jid = mucwin->roomjid;
            break;
        }
        case WIN_CHAT:
        {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
            jid = chatwin->barejid;
            break;
        }
        case WIN_PRIVATE:
        {
            ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
            assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
            jid = privatewin->fulljid;
            break;
        }
        case WIN_CONSOLE:
        {
            jid = connection_get_domain();
            break;
        }
        default:
            cons_show("Cannot send ad hoc commands.");
            return TRUE;
        }
    }

    iq_command_exec(jid, args[1]);

    cons_show("Execute %s...", args[1]);
    return TRUE;
}

static gboolean
_cmd_execute(ProfWin* window, const char* const command, const char* const inp)
{
    if (g_str_has_prefix(command, "/field") && window->type == WIN_CONFIG) {
        gboolean result = FALSE;
        gchar** args = parse_args_with_freetext(inp, 1, 2, &result);
        if (!result) {
            win_println(window, THEME_DEFAULT, "!", "Invalid command, see /form help");
            result = TRUE;
        } else {
            gchar** tokens = g_strsplit(inp, " ", 2);
            char* field = tokens[0] + 1;
            result = cmd_form_field(window, field, args);
            g_strfreev(tokens);
        }

        g_strfreev(args);
        return result;
    }

    Command* cmd = cmd_get(command);
    gboolean result = FALSE;

    if (cmd) {
        gchar** args = cmd->parser(inp, cmd->min_args, cmd->max_args, &result);
        if (result == FALSE) {
            ui_invalid_command_usage(cmd->cmd, cmd->setting_func);
            return TRUE;
        }
        if (args[0] && cmd->sub_funcs[0][0]) {
            int i = 0;
            while (cmd->sub_funcs[i][0]) {
                if (g_strcmp0(args[0], (char*)cmd->sub_funcs[i][0]) == 0) {
                    gboolean (*func)(ProfWin * window, const char* const command, gchar** args) = cmd->sub_funcs[i][1];
                    gboolean result = func(window, command, args);
                    g_strfreev(args);
                    return result;
                }
                i++;
            }
        }
        if (!cmd->func) {
            ui_invalid_command_usage(cmd->cmd, cmd->setting_func);
            return TRUE;
        }
        gboolean result = cmd->func(window, command, args);
        g_strfreev(args);
        return result;
    } else if (plugins_run_command(inp)) {
        return TRUE;
    } else {
        gboolean ran_alias = FALSE;
        gboolean alias_result = _cmd_execute_alias(window, inp, &ran_alias);
        if (!ran_alias) {
            return _cmd_execute_default(window, inp);
        } else {
            return alias_result;
        }
    }
}

static gboolean
_cmd_execute_default(ProfWin* window, const char* inp)
{
    // handle escaped commands - treat as normal message
    if (g_str_has_prefix(inp, "//")) {
        inp++;

        // handle unknown commands
    } else if ((inp[0] == '/') && (!g_str_has_prefix(inp, "/me "))) {
        cons_show("Unknown command: %s", inp);
        cons_alert(NULL);
        return TRUE;
    }

    // handle non commands in non chat or plugin windows
    if (window->type != WIN_CHAT && window->type != WIN_MUC && window->type != WIN_PRIVATE && window->type != WIN_PLUGIN && window->type != WIN_XML) {
        cons_show("Unknown command: %s", inp);
        cons_alert(NULL);
        return TRUE;
    }

    // handle plugin window
    if (window->type == WIN_PLUGIN) {
        ProfPluginWin* pluginwin = (ProfPluginWin*)window;
        plugins_win_process_line(pluginwin->tag, inp);
        return TRUE;
    }

    jabber_conn_status_t status = connection_get_status();
    if (status != JABBER_CONNECTED) {
        win_println(window, THEME_DEFAULT, "-", "You are not currently connected.");
        return TRUE;
    }

    switch (window->type) {
    case WIN_CHAT:
    {
        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        cl_ev_send_msg(chatwin, inp, NULL);
        break;
    }
    case WIN_PRIVATE:
    {
        ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
        assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
        cl_ev_send_priv_msg(privatewin, inp, NULL);
        break;
    }
    case WIN_MUC:
    {
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
        cl_ev_send_muc_msg(mucwin, inp, NULL);
        break;
    }
    case WIN_XML:
    {
        connection_send_stanza(inp);
        break;
    }
    default:
        break;
    }

    return TRUE;
}

static gboolean
_cmd_execute_alias(ProfWin* window, const char* const inp, gboolean* ran)
{
    if (inp[0] != '/') {
        *ran = FALSE;
        return TRUE;
    }

    char* alias = strdup(inp + 1);
    char* value = prefs_get_alias(alias);
    free(alias);
    if (value) {
        *ran = TRUE;
        gboolean result = cmd_process_input(window, value);
        g_free(value);
        return result;
    }

    *ran = FALSE;
    return TRUE;
}

// helper function for status change commands
static void
_update_presence(const resource_presence_t resource_presence,
                 const char* const show, gchar** args)
{
    char* msg = NULL;
    int num_args = g_strv_length(args);

    // if no message, use status as message
    if (num_args == 2) {
        msg = args[1];
    } else {
        msg = args[2];
    }

    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
    } else {
        connection_set_presence_msg(msg);
        cl_ev_presence_send(resource_presence, 0);
        ui_update_presence(resource_presence, msg, show);
    }
}

// helper function for boolean preference commands
static void
_cmd_set_boolean_preference(gchar* arg, const char* const command,
                            const char* const display, preference_t pref)
{
    if (arg == NULL) {
        cons_bad_cmd_usage(command);
    } else if (strcmp(arg, "on") == 0) {
        GString* enabled = g_string_new(display);
        g_string_append(enabled, " enabled.");

        cons_show(enabled->str);
        prefs_set_boolean(pref, TRUE);

        g_string_free(enabled, TRUE);
    } else if (strcmp(arg, "off") == 0) {
        GString* disabled = g_string_new(display);
        g_string_append(disabled, " disabled.");

        cons_show(disabled->str);
        prefs_set_boolean(pref, FALSE);

        g_string_free(disabled, TRUE);
    } else {
        cons_bad_cmd_usage(command);
    }
}

gboolean
cmd_omemo_gen(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to initialize OMEMO.");
        return TRUE;
    }

    if (omemo_loaded()) {
        cons_show("OMEMO crytographic materials have already been generated.");
        return TRUE;
    }

    cons_show("Generating OMEMO crytographic materials, it may take a while...");
    ui_update();
    ProfAccount* account = accounts_get_account(session_get_account_name());
    omemo_generate_crypto_materials(account);
    cons_show("OMEMO crytographic materials generated. Your Device ID is %d.", omemo_device_id());
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_start(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OMEMO information.");
        return TRUE;
    }

    if (!omemo_loaded()) {
        win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a cryptographic materials, use '/omemo gen'");
        return TRUE;
    }

    ProfChatWin* chatwin = NULL;

    // recipient supplied
    if (args[1]) {
        char* contact = args[1];
        char* barejid = roster_barejid_from_name(contact);
        if (barejid == NULL) {
            barejid = contact;
        }

        chatwin = wins_get_chat(barejid);
        if (!chatwin) {
            chatwin = chatwin_new(barejid);
        }
        ui_focus_win((ProfWin*)chatwin);
    } else {
        if (window->type == WIN_CHAT) {
            chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        }
    }

    if (chatwin) {
        if (chatwin->pgp_send) {
            win_println((ProfWin*)chatwin, THEME_DEFAULT, "!", "You must disable PGP encryption before starting an OMEMO session.");
            return TRUE;
        }

        if (chatwin->is_otr) {
            win_println((ProfWin*)chatwin, THEME_DEFAULT, "!", "You must disable OTR encryption before starting an OMEMO session.");
            return TRUE;
        }

        if (chatwin->is_omemo) {
            win_println((ProfWin*)chatwin, THEME_DEFAULT, "!", "You are already in an OMEMO session.");
            return TRUE;
        }

        accounts_add_omemo_state(session_get_account_name(), chatwin->barejid, TRUE);
        omemo_start_session(chatwin->barejid);
        chatwin->is_omemo = TRUE;
    } else if (window->type == WIN_MUC) {
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

        if (muc_anonymity_type(mucwin->roomjid) == MUC_ANONYMITY_TYPE_NONANONYMOUS
            && muc_member_type(mucwin->roomjid) == MUC_MEMBER_TYPE_MEMBERS_ONLY) {
            accounts_add_omemo_state(session_get_account_name(), mucwin->roomjid, TRUE);
            omemo_start_muc_sessions(mucwin->roomjid);
            mucwin->is_omemo = TRUE;
        } else {
            win_println(window, THEME_DEFAULT, "!", "MUC must be non-anonymous (i.e. be configured to present real jid to anyone) and members-only in order to support OMEMO.");
        }
    } else {
        win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to start an OMEMO session.");
    }

    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_trust_mode(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO

    if (!args[1]) {
        cons_show("Current trust mode is %s", prefs_get_string(PREF_OMEMO_TRUST_MODE));
        return TRUE;
    }

    if (g_strcmp0(args[1], "manual") == 0) {
        cons_show("Current trust mode is %s - setting to %s", prefs_get_string(PREF_OMEMO_TRUST_MODE), args[1]);
        cons_show("You need to trust all OMEMO fingerprints manually");
    } else if (g_strcmp0(args[1], "firstusage") == 0) {
        cons_show("Current trust mode is %s - setting to %s", prefs_get_string(PREF_OMEMO_TRUST_MODE), args[1]);
        cons_show("The first seen OMEMO fingerprints will be trusted automatically - new keys must be trusted manually");
    } else if (g_strcmp0(args[1], "blind") == 0) {
        cons_show("Current trust mode is %s - setting to %s", prefs_get_string(PREF_OMEMO_TRUST_MODE), args[1]);
        cons_show("ALL OMEMO fingerprints will be trusted automatically");
    } else {
        cons_bad_cmd_usage(command);
        return TRUE;
    }
    prefs_set_string(PREF_OMEMO_TRUST_MODE, args[1]);

#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
#endif
    return TRUE;
}

gboolean
cmd_omemo_char(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (args[1] == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    } else if (g_utf8_strlen(args[1], 4) == 1) {
        if (prefs_set_omemo_char(args[1])) {
            cons_show("OMEMO char set to %s.", args[1]);
        } else {
            cons_show_error("Could not set OMEMO char: %s.", args[1]);
        }
        return TRUE;
    }
    cons_bad_cmd_usage(command);
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
#endif
    return TRUE;
}

gboolean
cmd_omemo_log(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    char* choice = args[1];
    if (g_strcmp0(choice, "on") == 0) {
        prefs_set_string(PREF_OMEMO_LOG, "on");
        cons_show("OMEMO messages will be logged as plaintext.");
        if (!prefs_get_boolean(PREF_CHLOG)) {
            cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
        }
    } else if (g_strcmp0(choice, "off") == 0) {
        prefs_set_string(PREF_OMEMO_LOG, "off");
        cons_show("OMEMO message logging disabled.");
    } else if (g_strcmp0(choice, "redact") == 0) {
        prefs_set_string(PREF_OMEMO_LOG, "redact");
        cons_show("OMEMO messages will be logged as '[redacted]'.");
        if (!prefs_get_boolean(PREF_CHLOG)) {
            cons_show("Chat logging is currently disabled, use '/logging chat on' to enable.");
        }
    } else {
        cons_bad_cmd_usage(command);
    }
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_end(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OMEMO information.");
        return TRUE;
    }

    if (window->type == WIN_CHAT) {
        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);

        if (!chatwin->is_omemo) {
            win_println(window, THEME_DEFAULT, "!", "You are not currently in an OMEMO session.");
            return TRUE;
        }

        chatwin->is_omemo = FALSE;
        accounts_add_omemo_state(session_get_account_name(), chatwin->barejid, FALSE);
    } else if (window->type == WIN_MUC) {
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

        if (!mucwin->is_omemo) {
            win_println(window, THEME_DEFAULT, "!", "You are not currently in an OMEMO session.");
            return TRUE;
        }

        mucwin->is_omemo = FALSE;
        accounts_add_omemo_state(session_get_account_name(), mucwin->roomjid, FALSE);
    } else {
        win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to start an OMEMO session.");
        return TRUE;
    }

    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_fingerprint(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OMEMO information.");
        return TRUE;
    }

    if (!omemo_loaded()) {
        win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a cryptographic materials, use '/omemo gen'");
        return TRUE;
    }

    Jid* jid;
    if (!args[1]) {
        if (window->type == WIN_CONSOLE) {
            char* fingerprint = omemo_own_fingerprint(TRUE);
            cons_show("Your OMEMO fingerprint: %s", fingerprint);
            free(fingerprint);
            jid = jid_create(connection_get_fulljid());
        } else if (window->type == WIN_CHAT) {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            jid = jid_create(chatwin->barejid);
        } else {
            win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to print fingerprint without providing the contact.");
            return TRUE;
        }
    } else {
        char* barejid = roster_barejid_from_name(args[1]);
        if (barejid) {
            jid = jid_create(barejid);
        } else {
            jid = jid_create(args[1]);
            if (!jid) {
                cons_show("%s is not a valid jid", args[1]);
                return TRUE;
            }
        }
    }

    GList* fingerprints = omemo_known_device_identities(jid->barejid);

    if (!fingerprints) {
        win_println(window, THEME_DEFAULT, "-", "There is no known fingerprints for %s", jid->barejid);
        return TRUE;
    }

    for (GList* fingerprint = fingerprints; fingerprint != NULL; fingerprint = fingerprint->next) {
        char* formatted_fingerprint = omemo_format_fingerprint(fingerprint->data);
        gboolean trusted = omemo_is_trusted_identity(jid->barejid, fingerprint->data);

        win_println(window, THEME_DEFAULT, "-", "%s's OMEMO fingerprint: %s%s", jid->barejid, formatted_fingerprint, trusted ? " (trusted)" : "");

        free(formatted_fingerprint);
    }

    g_list_free(fingerprints);

    win_println(window, THEME_DEFAULT, "-", "You can trust it with '/omemo trust <fingerprint>'");
    win_println(window, THEME_DEFAULT, "-", "You can untrust it with '/omemo untrust <fingerprint>'");

    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_trust(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OMEMO information.");
        return TRUE;
    }

    if (!args[1]) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (!omemo_loaded()) {
        win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a cryptographic materials, use '/omemo gen'");
        return TRUE;
    }

    char* fingerprint;
    char* barejid;

    /* Contact not provided */
    if (!args[2]) {
        fingerprint = args[1];

        if (window->type != WIN_CHAT) {
            win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to trust a device without providing the contact.");
            return TRUE;
        }

        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        barejid = chatwin->barejid;
    } else {
        fingerprint = args[2];
        char* contact = args[1];
        barejid = roster_barejid_from_name(contact);
        if (barejid == NULL) {
            barejid = contact;
        }
    }

    omemo_trust(barejid, fingerprint);

    char* unformatted_fingerprint = malloc(strlen(fingerprint));
    int i;
    int j;
    for (i = 0, j = 0; fingerprint[i] != '\0'; i++) {
        if (!g_ascii_isxdigit(fingerprint[i])) {
            continue;
        }
        unformatted_fingerprint[j++] = fingerprint[i];
    }

    unformatted_fingerprint[j] = '\0';
    gboolean trusted = omemo_is_trusted_identity(barejid, unformatted_fingerprint);

    win_println(window, THEME_DEFAULT, "-", "%s's OMEMO fingerprint: %s%s", barejid, fingerprint, trusted ? " (trusted)" : "");

    free(unformatted_fingerprint);

    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_untrust(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OMEMO information.");
        return TRUE;
    }

    if (!args[1]) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (!omemo_loaded()) {
        win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a cryptographic materials, use '/omemo gen'");
        return TRUE;
    }

    char* fingerprint;
    char* barejid;

    /* Contact not provided */
    if (!args[2]) {
        fingerprint = args[1];

        if (window->type != WIN_CHAT) {
            win_println(window, THEME_DEFAULT, "-", "You must be in a regular chat window to trust a device without providing the contact.");
            return TRUE;
        }

        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
        barejid = chatwin->barejid;
    } else {
        fingerprint = args[2];
        char* contact = args[1];
        barejid = roster_barejid_from_name(contact);
        if (barejid == NULL) {
            barejid = contact;
        }
    }

    omemo_untrust(barejid, fingerprint);

    char* unformatted_fingerprint = malloc(strlen(fingerprint));
    int i, j;
    for (i = 0, j = 0; fingerprint[i] != '\0'; i++) {
        if (!g_ascii_isxdigit(fingerprint[i])) {
            continue;
        }
        unformatted_fingerprint[j++] = fingerprint[i];
    }

    unformatted_fingerprint[j] = '\0';
    gboolean trusted = omemo_is_trusted_identity(barejid, unformatted_fingerprint);

    win_println(window, THEME_DEFAULT, "-", "%s's OMEMO fingerprint: %s%s", barejid, fingerprint, trusted ? " (trusted)" : "");

    free(unformatted_fingerprint);

    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_clear_device_list(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to initialize OMEMO.");
        return TRUE;
    }

    omemo_devicelist_publish(NULL);
    cons_show("Cleared OMEMO device list");
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_policy(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (args[1] == NULL) {
        char* policy = prefs_get_string(PREF_OMEMO_POLICY);
        cons_show("OMEMO policy is now set to: %s", policy);
        g_free(policy);
        return TRUE;
    }

    char* choice = args[1];
    if (!_string_matches_one_of("OMEMO policy", choice, FALSE, "manual", "automatic", "always", NULL)) {
        return TRUE;
    }

    prefs_set_string(PREF_OMEMO_POLICY, choice);
    cons_show("OMEMO policy is now set to: %s", choice);
    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_omemo_qrcode(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_OMEMO
    if (connection_get_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OMEMO information.");
        return TRUE;
    }

    if (!omemo_loaded()) {
        win_println(window, THEME_DEFAULT, "!", "You have not generated or loaded a cryptographic materials, use '/omemo gen'");
        return TRUE;
    }

    char* qrstr = omemo_qrcode_str();
    cons_show_qrcode(qrstr);
    free(qrstr);

    return TRUE;
#else
    cons_show("This version of Profanity has not been built with OMEMO support enabled");
    return TRUE;
#endif
}

gboolean
cmd_save(ProfWin* window, const char* const command, gchar** args)
{
    log_info("Saving preferences to configuration file");
    cons_show("Saving preferences.");
    prefs_save();
    return TRUE;
}

gboolean
cmd_reload(ProfWin* window, const char* const command, gchar** args)
{
    log_info("Reloading preferences");
    cons_show("Reloading preferences.");
    prefs_reload();
    return TRUE;
}

gboolean
cmd_paste(ProfWin* window, const char* const command, gchar** args)
{
#ifdef HAVE_GTK
    char* clipboard_buffer = clipboard_get();

    if (clipboard_buffer) {
        switch (window->type) {
        case WIN_MUC:
        {
            ProfMucWin* mucwin = (ProfMucWin*)window;
            assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);
            cl_ev_send_muc_msg(mucwin, clipboard_buffer, NULL);
            break;
        }
        case WIN_CHAT:
        {
            ProfChatWin* chatwin = (ProfChatWin*)window;
            assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);
            cl_ev_send_msg(chatwin, clipboard_buffer, NULL);
            break;
        }
        case WIN_PRIVATE:
        {
            ProfPrivateWin* privatewin = (ProfPrivateWin*)window;
            assert(privatewin->memcheck == PROFPRIVATEWIN_MEMCHECK);
            cl_ev_send_priv_msg(privatewin, clipboard_buffer, NULL);
            break;
        }
        case WIN_CONSOLE:
        case WIN_XML:
        default:
            cons_bad_cmd_usage(command);
            break;
        }

        free(clipboard_buffer);
    }
#else
    cons_show("This version of Profanity has not been built with GTK support enabled. It is needed for the clipboard feature to work.");
#endif

    return TRUE;
}

gboolean
cmd_stamp(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strv_length(args) == 0) {
        char* def = prefs_get_string(PREF_OUTGOING_STAMP);
        if (def) {
            cons_show("The outgoing stamp is: %s", def);
            free(def);
        } else {
            cons_show("The default outgoing stamp is used.");
        }
        def = prefs_get_string(PREF_INCOMING_STAMP);
        if (def) {
            cons_show("The incoming stamp is: %s", def);
            free(def);
        } else {
            cons_show("The default incoming stamp is used.");
        }
        return TRUE;
    }

    if (g_strv_length(args) == 1) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strv_length(args) == 2) {
        if (g_strcmp0(args[0], "outgoing") == 0) {
            prefs_set_string(PREF_OUTGOING_STAMP, args[1]);
            cons_show("Outgoing stamp set to: %s", args[1]);
        } else if (g_strcmp0(args[0], "incoming") == 0) {
            prefs_set_string(PREF_INCOMING_STAMP, args[1]);
            cons_show("Incoming stamp set to: %s", args[1]);
        } else if (g_strcmp0(args[0], "unset") == 0) {
            if (g_strcmp0(args[1], "incoming") == 0) {
                prefs_set_string(PREF_INCOMING_STAMP, NULL);
                cons_show("Incoming stamp unset");
            } else if (g_strcmp0(args[1], "outgoing") == 0) {
                prefs_set_string(PREF_OUTGOING_STAMP, NULL);
                cons_show("Outgoing stamp unset");
            } else {
                cons_bad_cmd_usage(command);
            }
        } else {
            cons_bad_cmd_usage(command);
        }
    }

    return TRUE;
}

gboolean
cmd_color(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "on") == 0) {
        prefs_set_string(PREF_COLOR_NICK, "true");
    } else if (g_strcmp0(args[0], "off") == 0) {
        prefs_set_string(PREF_COLOR_NICK, "false");
    } else if (g_strcmp0(args[0], "redgreen") == 0) {
        prefs_set_string(PREF_COLOR_NICK, "redgreen");
    } else if (g_strcmp0(args[0], "blue") == 0) {
        prefs_set_string(PREF_COLOR_NICK, "blue");
    } else if (g_strcmp0(args[0], "own") == 0) {
        if (g_strcmp0(args[1], "on") == 0) {
            _cmd_set_boolean_preference(args[1], command, "Color generation for own nick", PREF_COLOR_NICK_OWN);
        }
    } else {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    cons_show("Consistent color generation for nicks set to: %s", args[0]);

    char* theme = prefs_get_string(PREF_THEME);
    if (theme) {
        gboolean res = theme_load(theme, false);

        if (res) {
            cons_show("Theme reloaded: %s", theme);
        } else {
            theme_load("default", false);
        }

        g_free(theme);
    }

    return TRUE;
}

gboolean
cmd_avatar(ProfWin* window, const char* const command, gchar** args)
{
    if (args[1] == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[0], "set") == 0) {
#ifdef HAVE_PIXBUF
        if (avatar_set(args[1])) {
            cons_show("Avatar updated successfully");
        }
#else
        cons_show("Profanity has not been built with GDK Pixbuf support enabled which is needed to scale the avatar when uploading.");
#endif
    } else if (g_strcmp0(args[0], "get") == 0) {
        avatar_get_by_nick(args[1], false);
    } else if (g_strcmp0(args[0], "open") == 0) {
        avatar_get_by_nick(args[1], true);
    } else if (g_strcmp0(args[0], "cmd") == 0) {
        prefs_set_string(PREF_AVATAR_CMD, args[1]);
        cons_show("Avatar cmd set to: %s", args[1]);
    }

    return TRUE;
}

gboolean
cmd_os(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "Revealing OS name", PREF_REVEAL_OS);

    return TRUE;
}

gboolean
cmd_correction(ProfWin* window, const char* const command, gchar** args)
{
    // enable/disable
    if (g_strcmp0(args[0], "on") == 0) {
        _cmd_set_boolean_preference(args[0], command, "Last Message Correction", PREF_CORRECTION_ALLOW);
        caps_add_feature(XMPP_FEATURE_LAST_MESSAGE_CORRECTION);
        return TRUE;
    } else if (g_strcmp0(args[0], "off") == 0) {
        _cmd_set_boolean_preference(args[0], command, "Last Message Correction", PREF_CORRECTION_ALLOW);
        caps_remove_feature(XMPP_FEATURE_LAST_MESSAGE_CORRECTION);
        return TRUE;
    }

    // char
    if (g_strcmp0(args[0], "char") == 0) {
        if (args[1] == NULL) {
            cons_bad_cmd_usage(command);
        } else if (strlen(args[1]) != 1) {
            cons_bad_cmd_usage(command);
        } else {
            prefs_set_correction_char(args[1][0]);
            cons_show("LMC char set to %c.", args[1][0]);
        }
    }

    return TRUE;
}

gboolean
_can_correct(ProfWin* window)
{
    jabber_conn_status_t conn_status = connection_get_status();
    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are currently not connected.");
        return FALSE;
    } else if (!prefs_get_boolean(PREF_CORRECTION_ALLOW)) {
        win_println(window, THEME_DEFAULT, "!", "Corrections not enabled. See /help correction.");
        return FALSE;
    } else if (window->type == WIN_CHAT) {
        ProfChatWin* chatwin = (ProfChatWin*)window;
        assert(chatwin->memcheck == PROFCHATWIN_MEMCHECK);

        if (chatwin->last_msg_id == NULL || chatwin->last_message == NULL) {
            win_println(window, THEME_DEFAULT, "!", "No last message to correct.");
            return FALSE;
        }
    } else if (window->type == WIN_MUC) {
        ProfMucWin* mucwin = (ProfMucWin*)window;
        assert(mucwin->memcheck == PROFMUCWIN_MEMCHECK);

        if (mucwin->last_msg_id == NULL || mucwin->last_message == NULL) {
            win_println(window, THEME_DEFAULT, "!", "No last message to correct.");
            return FALSE;
        }
    } else {
        win_println(window, THEME_DEFAULT, "!", "Command /correct-editor only valid in regular chat windows.");
        return FALSE;
    }

    return TRUE;
}

gboolean
cmd_correct(ProfWin* window, const char* const command, gchar** args)
{
    if (!_can_correct(window)) {
        return TRUE;
    }

    if (window->type == WIN_CHAT) {
        ProfChatWin* chatwin = (ProfChatWin*)window;

        // send message again, with replace flag
        gchar* message = g_strjoinv(" ", args);
        cl_ev_send_msg_correct(chatwin, message, FALSE, TRUE);

        free(message);
    } else if (window->type == WIN_MUC) {
        ProfMucWin* mucwin = (ProfMucWin*)window;

        // send message again, with replace flag
        gchar* message = g_strjoinv(" ", args);
        cl_ev_send_muc_msg_corrected(mucwin, message, FALSE, TRUE);

        free(message);
    }

    return TRUE;
}

gboolean
cmd_slashguard(ProfWin* window, const char* const command, gchar** args)
{
    if (args[0] == NULL) {
        return FALSE;
    }

    _cmd_set_boolean_preference(args[0], command, "Slashguard", PREF_SLASH_GUARD);

    return TRUE;
}

#ifdef HAVE_OMEMO
void
_url_aesgcm_method(ProfWin* window, const char* cmd_template, const char* url, const char* filename)
{
    AESGCMDownload* download = malloc(sizeof(AESGCMDownload));
    download->window = window;
    download->url = strdup(url);
    download->filename = strdup(filename);
    if (cmd_template != NULL) {
        download->cmd_template = strdup(cmd_template);
    } else {
        download->cmd_template = NULL;
    }

    pthread_create(&(download->worker), NULL, &aesgcm_file_get, download);
    aesgcm_download_add_download(download);
}
#endif

void
_url_http_method(ProfWin* window, const char* cmd_template, const char* url, const char* filename)
{

    HTTPDownload* download = malloc(sizeof(HTTPDownload));
    download->window = window;
    download->url = strdup(url);
    download->filename = strdup(filename);
    if (cmd_template != NULL) {
        download->cmd_template = strdup(cmd_template);
    } else {
        download->cmd_template = NULL;
    }

    pthread_create(&(download->worker), NULL, &http_file_get, download);
    http_download_add_download(download);
}

void
_url_external_method(const char* cmd_template, const char* url, const char* filename)
{
    gchar** argv = format_call_external_argv(cmd_template, url, filename);

    if (!call_external(argv, NULL, NULL)) {
        cons_show_error("Unable to call external executable for url: check the logs for more information.");
    } else {
        cons_show("URL '%s' has been called with '%s'.", url, cmd_template);
    }

    g_strfreev(argv);
}

gboolean
cmd_url_open(ProfWin* window, const char* const command, gchar** args)
{
    if (window->type != WIN_CHAT && window->type != WIN_MUC && window->type != WIN_PRIVATE) {
        cons_show_error("url open not supported in this window");
        return TRUE;
    }

    gchar* url = args[1];
    if (url == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    gchar* scheme = NULL;
    char* cmd_template = NULL;
    char* filename = NULL;

    scheme = g_uri_parse_scheme(url);
    if (scheme == NULL) {
        cons_show_error("URL '%s' is not valid.", args[1]);
        goto out;
    }

    cmd_template = prefs_get_string(PREF_URL_OPEN_CMD);
    if (cmd_template == NULL) {
        cons_show_error("No default `url open` command found in executables preferences.");
        goto out;
    }

#ifdef HAVE_OMEMO
    // OMEMO URLs (aesgcm://) must be saved and decrypted before being opened.
    if (g_strcmp0(scheme, "aesgcm") == 0) {

        // Ensure that the downloads directory exists for saving cleartexts.
        gchar* downloads_dir = files_get_data_path(DIR_DOWNLOADS);
        if (g_mkdir_with_parents(downloads_dir, S_IRWXU) != 0) {
            cons_show_error("Failed to create download directory "
                            "at '%s' with error '%s'",
                            downloads_dir, strerror(errno));
            g_free(downloads_dir);
            goto out;
        }

        // Generate an unique filename from the URL that should be stored in the
        // downloads directory.
        filename = unique_filename_from_url(url, downloads_dir);
        g_free(downloads_dir);

        // Download, decrypt and open the cleartext version of the AESGCM
        // encrypted file.
        _url_aesgcm_method(window, cmd_template, url, filename);
        goto out;
    }
#endif

    _url_external_method(cmd_template, url, NULL);

out:
    // reset autocompletion to start from latest url and not where we left of
    autocomplete_reset(window->urls_ac);

    free(cmd_template);
    free(filename);

    g_free(scheme);

    return TRUE;
}

gboolean
cmd_url_save(ProfWin* window, const char* const command, gchar** args)
{
    if (window->type != WIN_CHAT && window->type != WIN_MUC && window->type != WIN_PRIVATE) {
        cons_show_error("`/url save` is not supported in this window.");
        return TRUE;
    }

    if (args[1] == NULL) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    gchar* url = args[1];
    gchar* path = g_strdup(args[2]);
    gchar* scheme = NULL;
    char* filename = NULL;
    char* cmd_template = NULL;

    scheme = g_uri_parse_scheme(url);
    if (scheme == NULL) {
        cons_show_error("URL '%s' is not valid.", args[1]);
        goto out;
    }

    filename = unique_filename_from_url(url, path);
    if (filename == NULL) {
        cons_show_error("Failed to generate unique filename"
                        "from URL '%s' for path '%s'",
                        url, path);
        goto out;
    }

    cmd_template = prefs_get_string(PREF_URL_SAVE_CMD);
    if (cmd_template == NULL && (g_strcmp0(scheme, "http") == 0 || g_strcmp0(scheme, "https") == 0)) {
        _url_http_method(window, cmd_template, url, filename);
#ifdef HAVE_OMEMO
    } else if (g_strcmp0(scheme, "aesgcm") == 0) {
        _url_aesgcm_method(window, cmd_template, url, filename);
#endif
    } else if (cmd_template != NULL) {
        _url_external_method(cmd_template, url, filename);
    } else {
        cons_show_error("No download method defined for the scheme '%s'.", scheme);
    }

out:
    // reset autocompletion to start from latest url and not where we left of
    autocomplete_reset(window->urls_ac);

    free(filename);
    free(cmd_template);

    g_free(scheme);
    g_free(path);

    return TRUE;
}

gboolean
cmd_executable_avatar(ProfWin* window, const char* const command, gchar** args)
{
    prefs_set_string(PREF_AVATAR_CMD, args[1]);
    cons_show("`avatar` command set to invoke '%s'", args[1]);
    return TRUE;
}

gboolean
cmd_executable_urlopen(ProfWin* window, const char* const command, gchar** args)
{
    guint num_args = g_strv_length(args);
    if (num_args < 2) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[1], "set") == 0 && num_args >= 3) {
        gchar* str = g_strjoinv(" ", &args[2]);
        prefs_set_string(PREF_URL_OPEN_CMD, str);
        cons_show("`url open` command set to invoke '%s'", str);
        g_free(str);

    } else if (g_strcmp0(args[1], "default") == 0) {
        prefs_set_string(PREF_URL_OPEN_CMD, NULL);
        gchar* def = prefs_get_string(PREF_URL_OPEN_CMD);
        cons_show("`url open` command set to invoke %s (default)", def);
        g_free(def);
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_executable_urlsave(ProfWin* window, const char* const command, gchar** args)
{

    guint num_args = g_strv_length(args);
    if (num_args < 2) {
        cons_bad_cmd_usage(command);
        return TRUE;
    }

    if (g_strcmp0(args[1], "set") == 0 && num_args >= 3) {
        gchar* str = g_strjoinv(" ", &args[2]);
        prefs_set_string(PREF_URL_SAVE_CMD, str);
        cons_show("`url save` command set to invoke '%s'", str);
        g_free(str);

    } else if (g_strcmp0(args[1], "default") == 0) {
        prefs_set_string(PREF_URL_SAVE_CMD, NULL);
        cons_show("`url save` will use built-in download method (default)");
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_executable_editor(ProfWin* window, const char* const command, gchar** args)
{
    guint num_args = g_strv_length(args);

    if (g_strcmp0(args[1], "set") == 0 && num_args >= 3) {
        prefs_set_string(PREF_COMPOSE_EDITOR, args[2]);
        cons_show("`editor` command set to invoke '%s'", args[2]);
    } else {
        cons_bad_cmd_usage(command);
    }

    return TRUE;
}

gboolean
cmd_mam(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "Message Archive Management", PREF_MAM);

    return TRUE;
}

gboolean
cmd_change_password(ProfWin* window, const char* const command, gchar** args)
{
    jabber_conn_status_t conn_status = connection_get_status();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    char* user = connection_get_user();
    char* passwd = ui_ask_password(false);
    char* confirm_passwd = ui_ask_password(true);

    if (g_strcmp0(passwd, confirm_passwd) == 0) {
        iq_register_change_password(user, passwd);
    } else {
        cons_show("Aborted! The new password and the confirmed password do not match.");
    }

    free(user);
    free(passwd);
    free(confirm_passwd);

    return TRUE;
}

gboolean
cmd_editor(ProfWin* window, const char* const command, gchar** args)
{
    gchar* message = NULL;

    if (get_message_from_editor(NULL, &message)) {
        return TRUE;
    }

    rl_insert_text(message);
    ui_resize();
    rl_point = rl_end;
    rl_forced_update_display();
    g_free(message);

    return TRUE;
}

gboolean
cmd_correct_editor(ProfWin* window, const char* const command, gchar** args)
{
    if (!_can_correct(window)) {
        return TRUE;
    }

    gchar* initial_message = win_get_last_sent_message(window);

    gchar* message = NULL;
    if (get_message_from_editor(initial_message, &message)) {
        return TRUE;
    }

    if (window->type == WIN_CHAT) {
        ProfChatWin* chatwin = (ProfChatWin*)window;

        cl_ev_send_msg_correct(chatwin, message, FALSE, TRUE);
    } else if (window->type == WIN_MUC) {
        ProfMucWin* mucwin = (ProfMucWin*)window;

        cl_ev_send_muc_msg_corrected(mucwin, message, FALSE, TRUE);
    }

    g_free(message);

    return TRUE;
}

gboolean
cmd_silence(ProfWin* window, const char* const command, gchar** args)
{
    _cmd_set_boolean_preference(args[0], command, "Block all messages from JIDs that are not in the roster", PREF_SILENCE_NON_ROSTER);

    return TRUE;
}

gboolean
cmd_register(ProfWin* window, const char* const command, gchar** args)
{
    gchar* opt_keys[] = { "port", "tls", "auth", NULL };
    gboolean parsed;

    GHashTable* options = parse_options(&args[2], opt_keys, &parsed);
    if (!parsed) {
        cons_bad_cmd_usage(command);
        cons_show("");
        options_destroy(options);
        return TRUE;
    }

    char* tls_policy = g_hash_table_lookup(options, "tls");
    if (!_string_matches_one_of("TLS policy", tls_policy, TRUE, "force", "allow", "trust", "disable", "legacy", NULL)) {
        cons_bad_cmd_usage(command);
        cons_show("");
        options_destroy(options);
        return TRUE;
    }

    int port = 0;
    if (g_hash_table_contains(options, "port")) {
        char* port_str = g_hash_table_lookup(options, "port");
        char* err_msg = NULL;
        gboolean res = strtoi_range(port_str, &port, 1, 65535, &err_msg);
        if (!res) {
            cons_show(err_msg);
            cons_show("");
            free(err_msg);
            port = 0;
            options_destroy(options);
            return TRUE;
        }
    }

    char* username = args[0];
    char* server = args[1];

    char* passwd = ui_ask_password(false);
    char* confirm_passwd = ui_ask_password(true);

    if (g_strcmp0(passwd, confirm_passwd) == 0) {
        log_info("Attempting to register account %s on server %s.", username, server);
        connection_register(server, port, tls_policy, username, passwd);
    } else {
        cons_show("The two passwords do not match.");
    }

    if (connection_get_status() == JABBER_DISCONNECTED) {
        cons_show_error("Connection attempt to server %s port %d failed.", server, port);
        log_info("Connection attempt to server %s port %d failed.", server, port);
        return TRUE;
    }

    free(passwd);
    free(confirm_passwd);

    options_destroy(options);

    log_info("we are leaving the registration process");
    return TRUE;
}

gboolean
cmd_mood(ProfWin* window, const char* const command, gchar** args)
{
    if (g_strcmp0(args[0], "on") == 0) {
        _cmd_set_boolean_preference(args[0], command, "User mood", PREF_MOOD);
        caps_add_feature(STANZA_NS_MOOD_NOTIFY);
    } else if (g_strcmp0(args[0], "off") == 0) {
        _cmd_set_boolean_preference(args[0], command, "User mood", PREF_MOOD);
        caps_remove_feature(STANZA_NS_MOOD_NOTIFY);
    } else if (g_strcmp0(args[0], "set") == 0) {
        if (args[1]) {
            cons_show("Your mood: %s", args[1]);
            if (args[2]) {
                publish_user_mood(args[1], args[2]);
            } else {
                publish_user_mood(args[1], args[1]);
            }
        }
    } else if (g_strcmp0(args[0], "clear") == 0) {
        cons_show("Clearing the user mood.");
        publish_user_mood(NULL, NULL);
    }

    return TRUE;
}