about summary refs log tree commit diff stats
path: root/cpp/.traces/channel-write-full
blob: 121c73bfcf2d9b3a89628bdb40b81223ae5c6381 (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
parse/0: instruction: init-channel
parse/0:   ingredient: {name: "1", value: 0, type: 0, properties: ["1": "literal", "capacity": ]}
parse/0:   product: {name: "1", value: 0, type: 2-10, properties: ["1": "address":"channel"]}
parse/0: instruction: write
parse/0:   ingredient: {name: "1", value: 0, type: 2-10, properties: ["1": "address":"channel"]}
parse/0:   ingredient: {name: "34", value: 0, type: 0, properties: ["34": "literal"]}
parse/0:   product: {name: "1", value: 0, type: 2-10, properties: ["1": "address":"channel"]}
parse/0: instruction: channel-empty?
parse/0:   ingredient: {name: "1", value: 0, type: 2-10, properties: ["1": "address":"channel"]}
parse/0:   product: {name: "2", value: 0, type: 1, properties: ["2": "integer"]}
parse/0: instruction: channel-full?
parse/0:   ingredient: {name: "1", value: 0, type: 2-10, properties: ["1": "address":"channel"]}
parse/0:   product: {name: "3", value: 0, type: 1, properties: ["3": "integer"]}
after-brace/0: recipe test-channel-write-full
after-brace/0: init-channel ...
after-brace/0: write ...
after-brace/0: channel-empty? ...
after-brace/0: channel-full? ...
new/0: routine allocated memory from 1000 to 101000
schedule/0: test-channel-write-full
run/0: instruction test-channel-write-full/0
run/0: {name: "1", value: 1, type: 2-10, properties: ["1": "address":"channel"]} <- init-channel {name: "1", value: 1, type: 0, properties: ["1": "literal", "capacity": ]}
run/0: instruction init-channel/0
run/0: {name: "default-space", value: 0, type: 2-5-1, properties: ["default-space": "address":"array":"location"]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "30", value: 30, type: 0, properties: ["30": "literal"]}
mem/0: array size is 30
mem/0: new alloc: 1000
run/0: instruction init-channel/1
run/0: {name: "result", value: 1, type: 2-10, properties: ["result": "address":"channel"]} <- new {name: "channel", value: 10, type: 0, properties: ["channel": "type"]}
mem/0: new alloc: 1031
mem/0: storing 1031 in location 1002
run/0: instruction init-channel/2
run/0: {name: "full", value: 2, type: 2-1, properties: ["full": "address":"integer"]} <- get-address {name: "result", value: 1, type: 2-10, properties: ["result": "address":"channel", "deref": ]}, {name: "first-full", value: 0, type: 0, properties: ["first-full": "offset"]}
run/0: ingredient 0 is result
mem/0: location 1002 is 1031
run/0: ingredient 1 is first-full
run/0: address to copy is 1031
run/0: product 0 is 1031
mem/0: storing 1031 in location 1003
run/0: instruction init-channel/3
run/0: {name: "full", value: 2, type: 2-1, properties: ["full": "address":"integer", "deref": ]} <- copy {name: "0", value: 0, type: 0, properties: ["0": "literal"]}
run/0: ingredient 0 is 0
mem/0: location 1003 is 1031
mem/0: storing 0 in location 1031
run/0: instruction init-channel/4
run/0: {name: "free", value: 3, type: 2-1, properties: ["free": "address":"integer"]} <- get-address {name: "result", value: 1, type: 2-10, properties: ["result": "address":"channel", "deref": ]}, {name: "first-free", value: 1, type: 0, properties: ["first-free": "offset"]}
run/0: ingredient 0 is result
mem/0: location 1002 is 1031
run/0: ingredient 1 is first-free
run/0: address to copy is 1032
run/0: product 0 is 1032
mem/0: storing 1032 in location 1004
run/0: instruction init-channel/5
run/0: {name: "free", value: 3, type: 2-1, properties: ["free": "address":"integer", "deref": ]} <- copy {name: "0", value: 0, type: 0, properties: ["0": "literal"]}
run/0: ingredient 0 is 0
mem/0: location 1004 is 1032
mem/0: storing 0 in location 1032
run/0: instruction init-channel/6
run/0: {name: "capacity", value: 4, type: 1, properties: ["capacity": "integer"]} <- next-ingredient 
run/0: product 0 is 1
mem/0: storing 1 in location 1005
run/0: instruction init-channel/7
run/0: {name: "capacity", value: 4, type: 1, properties: ["capacity": "integer"]} <- add {name: "capacity", value: 4, type: 1, properties: ["capacity": "integer"]}, {name: "1", value: 1, type: 0, properties: ["1": "literal"]}
run/0: ingredient 0 is capacity
mem/0: location 1005 is 1
run/0: ingredient 1 is 1
run/0: product 0 is 2
mem/0: storing 2 in location 1005
run/0: instruction init-channel/8
run/0: {name: "dest", value: 5, type: 2-2-5-1, properties: ["dest": "address":"address":"array":"location"]} <- get-address {name: "result", value: 1, type: 2-10, properties: ["result": "address":"channel", "deref": ]}, {name: "data", value: 2, type: 0, properties: ["data": "offset"]}
run/0: ingredient 0 is result
mem/0: location 1002 is 1031
run/0: ingredient 1 is data
run/0: address to copy is 1033
run/0: product 0 is 1033
mem/0: storing 1033 in location 1006
run/0: instruction init-channel/9
run/0: {name: "dest", value: 5, type: 2-2-5-1, properties: ["dest": "address":"address":"array":"location", "deref": ]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "capacity", value: 4, type: 1, properties: ["capacity": "integer"]}
mem/0: location 1005 is 2
mem/0: array size is 2
mem/0: new alloc: 1034
mem/0: location 1006 is 1033
mem/0: storing 1034 in location 1033
run/0: instruction init-channel/10
run/0: reply {name: "result", value: 1, type: 2-10, properties: ["result": "address":"channel"]}
mem/0: location 1002 is 1031
run/0: result 0 is 1031
mem/0: storing 1031 in location 1
run/0: instruction test-channel-write-full/1
run/0: {name: "1", value: 1, type: 2-10, properties: ["1": "address":"channel"]} <- write {name: "1", value: 1, type: 2-10, properties: ["1": "address":"channel"]}, {name: "34", value: 34, type: 0, properties: ["34": "literal"]}
mem/0: location 1 is 1031
run/0: instruction write/0
run/0: {name: "default-space", value: 0, type: 2-5-1, properties: ["default-space": "address":"array":"location"]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "30", value: 30, type: 0, properties: ["30": "literal"]}
mem/0: array size is 30
mem/0: new alloc: 1037
run/0: instruction write/1
run/0: {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]} <- next-ingredient 
run/0: product 0 is 1031
mem/0: storing 1031 in location 1039
run/0: instruction write/2
run/0: {name: "val", value: 2, type: 1, properties: ["val": "location"]} <- next-ingredient 
run/0: product 0 is 34
mem/0: storing 34 in location 1040
run/0: instruction write/4
run/0: {name: "full", value: 3, type: 3, properties: ["full": "boolean"]} <- channel-full? {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]}
mem/0: location 1039 is 1031
run/0: instruction channel-full?/0
run/0: {name: "default-space", value: 0, type: 2-5-1, properties: ["default-space": "address":"array":"location"]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "30", value: 30, type: 0, properties: ["30": "literal"]}
mem/0: array size is 30
mem/0: new alloc: 1068
run/0: instruction channel-full?/1
run/0: {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]} <- next-ingredient 
run/0: product 0 is 1031
mem/0: storing 1031 in location 1070
run/0: instruction channel-full?/2
run/0: {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "first-free", value: 1, type: 0, properties: ["first-free": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1070 is 1031
run/0: ingredient 1 is first-free
run/0: address to copy is 1032
run/0: its type is 1
mem/0: location 1032 is 0
run/0: product 0 is 0
mem/0: storing 0 in location 1071
run/0: instruction channel-full?/3
run/0: {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]} <- add {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]}, {name: "1", value: 1, type: 0, properties: ["1": "literal"]}
run/0: ingredient 0 is tmp
mem/0: location 1071 is 0
run/0: ingredient 1 is 1
run/0: product 0 is 1
mem/0: storing 1 in location 1071
run/0: instruction channel-full?/5
run/0: {name: "len", value: 3, type: 1, properties: ["len": "integer"]} <- channel-capacity {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]}
mem/0: location 1070 is 1031
run/0: instruction channel-capacity/0
run/0: {name: "default-space", value: 0, type: 2-5-1, properties: ["default-space": "address":"array":"location"]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "30", value: 30, type: 0, properties: ["30": "literal"]}
mem/0: array size is 30
mem/0: new alloc: 1099
run/0: instruction channel-capacity/1
run/0: {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]} <- next-ingredient 
run/0: product 0 is 1031
mem/0: storing 1031 in location 1101
run/0: instruction channel-capacity/2
run/0: {name: "q", value: 2, type: 2-5-1, properties: ["q": "address":"array":"location"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "data", value: 2, type: 0, properties: ["data": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1101 is 1031
run/0: ingredient 1 is data
run/0: address to copy is 1033
run/0: its type is 2
mem/0: location 1033 is 1034
run/0: product 0 is 1034
mem/0: storing 1034 in location 1102
run/0: instruction channel-capacity/3
run/0: {name: "result", value: 3, type: 1, properties: ["result": "integer"]} <- length {name: "q", value: 2, type: 2-5-1, properties: ["q": "address":"array":"location", "deref": ]}
mem/0: location 1102 is 1034
mem/0: storing 2 in location 1103
run/0: instruction channel-capacity/4
run/0: reply {name: "result", value: 3, type: 1, properties: ["result": "integer"]}
mem/0: location 1103 is 2
run/0: result 0 is 2
mem/0: storing 2 in location 1072
run/0: instruction channel-full?/6
run/0: {name: "at-end?", value: 4, type: 3, properties: ["at-end?": "boolean"]} <- greater-or-equal {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]}, {name: "len", value: 3, type: 1, properties: ["len": "integer"]}
run/0: ingredient 0 is tmp
mem/0: location 1071 is 1
run/0: ingredient 1 is len
mem/0: location 1072 is 2
run/0: product 0 is 0
mem/0: storing 0 in location 1073
run/0: instruction channel-full?/7
run/0: break-unless {name: "at-end?", value: 4, type: 3, properties: ["at-end?": "boolean"]}, {name: "", value: 1, type: , properties: ["": ]}
mem/0: location 1073 is 0
run/0: ingredient 0 is 0
run/0: ingredient 1 is 
run/0: jumping to instruction 9
run/0: instruction channel-full?/10
run/0: {name: "full", value: 5, type: 1, properties: ["full": "integer"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "first-full", value: 0, type: 0, properties: ["first-full": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1070 is 1031
run/0: ingredient 1 is first-full
run/0: address to copy is 1031
run/0: its type is 1
mem/0: location 1031 is 0
run/0: product 0 is 0
mem/0: storing 0 in location 1074
run/0: instruction channel-full?/11
run/0: {name: "result", value: 6, type: 3, properties: ["result": "boolean"]} <- equal {name: "full", value: 5, type: 1, properties: ["full": "integer"]}, {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]}
run/0: ingredient 0 is full
mem/0: location 1074 is 0
run/0: ingredient 1 is tmp
mem/0: location 1071 is 1
run/0: product 0 is 0
mem/0: storing 0 in location 1075
run/0: instruction channel-full?/12
run/0: reply {name: "result", value: 6, type: 3, properties: ["result": "boolean"]}
mem/0: location 1075 is 0
run/0: result 0 is 0
mem/0: storing 0 in location 1041
run/0: instruction write/5
run/0: break-unless {name: "full", value: 3, type: 3, properties: ["full": "boolean"]}, {name: "", value: 2, type: , properties: ["": ]}
mem/0: location 1041 is 0
run/0: ingredient 0 is 0
run/0: ingredient 1 is 
run/0: jumping to instruction 8
run/0: instruction write/9
run/0: {name: "circular-buffer", value: 5, type: 2-5-1, properties: ["circular-buffer": "address":"array":"location"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "data", value: 2, type: 0, properties: ["data": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1039 is 1031
run/0: ingredient 1 is data
run/0: address to copy is 1033
run/0: its type is 2
mem/0: location 1033 is 1034
run/0: product 0 is 1034
mem/0: storing 1034 in location 1043
run/0: instruction write/10
run/0: {name: "free", value: 6, type: 2-1, properties: ["free": "address":"integer"]} <- get-address {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "first-free", value: 1, type: 0, properties: ["first-free": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1039 is 1031
run/0: ingredient 1 is first-free
run/0: address to copy is 1032
run/0: product 0 is 1032
mem/0: storing 1032 in location 1044
run/0: instruction write/11
run/0: {name: "dest", value: 7, type: 2-1, properties: ["dest": "address":"location"]} <- index-address {name: "circular-buffer", value: 5, type: 2-5-1, properties: ["circular-buffer": "address":"array":"location", "deref": ]}, {name: "free", value: 6, type: 2-1, properties: ["free": "address":"integer", "deref": ]}
run/0: ingredient 0 is circular-buffer
mem/0: location 1043 is 1034
run/0: ingredient 1 is {name: "free", value: 6, type: 2-1, properties: ["free": "address":"integer", "deref": ]}
mem/0: location 1044 is 1032
mem/0: location 1032 is 0
run/0: address to copy is 1035
run/0: product 0 is 1035
mem/0: storing 1035 in location 1045
run/0: instruction write/12
run/0: {name: "dest", value: 7, type: 2-1, properties: ["dest": "address":"location", "deref": ]} <- copy {name: "val", value: 2, type: 1, properties: ["val": "location"]}
run/0: ingredient 0 is val
mem/0: location 1040 is 34
mem/0: location 1045 is 1035
mem/0: storing 34 in location 1035
run/0: instruction write/13
run/0: {name: "free", value: 6, type: 2-1, properties: ["free": "address":"integer", "deref": ]} <- add {name: "free", value: 6, type: 2-1, properties: ["free": "address":"integer", "deref": ]}, {name: "1", value: 1, type: 0, properties: ["1": "literal"]}
run/0: ingredient 0 is free
mem/0: location 1044 is 1032
mem/0: location 1032 is 0
run/0: ingredient 1 is 1
run/0: product 0 is 1
mem/0: location 1044 is 1032
mem/0: storing 1 in location 1032
run/0: instruction write/15
run/0: {name: "len", value: 8, type: 1, properties: ["len": "integer"]} <- length {name: "circular-buffer", value: 5, type: 2-5-1, properties: ["circular-buffer": "address":"array":"location", "deref": ]}
mem/0: location 1043 is 1034
mem/0: storing 2 in location 1046
run/0: instruction write/16
run/0: {name: "at-end?", value: 9, type: 3, properties: ["at-end?": "boolean"]} <- greater-or-equal {name: "free", value: 6, type: 2-1, properties: ["free": "address":"integer", "deref": ]}, {name: "len", value: 8, type: 1, properties: ["len": "integer"]}
run/0: ingredient 0 is free
mem/0: location 1044 is 1032
mem/0: location 1032 is 1
run/0: ingredient 1 is len
mem/0: location 1046 is 2
run/0: product 0 is 0
mem/0: storing 0 in location 1047
run/0: instruction write/17
run/0: break-unless {name: "at-end?", value: 9, type: 3, properties: ["at-end?": "boolean"]}, {name: "", value: 1, type: , properties: ["": ]}
mem/0: location 1047 is 0
run/0: ingredient 0 is 0
run/0: ingredient 1 is 
run/0: jumping to instruction 19
run/0: instruction write/20
run/0: reply {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "same-as-ingredient": "0"]}
mem/0: location 1039 is 1031
run/0: result 0 is 1031
mem/0: storing 1031 in location 1
run/0: instruction test-channel-write-full/2
run/0: {name: "2", value: 2, type: 1, properties: ["2": "integer"]} <- channel-empty? {name: "1", value: 1, type: 2-10, properties: ["1": "address":"channel"]}
mem/0: location 1 is 1031
run/0: instruction channel-empty?/0
run/0: {name: "default-space", value: 0, type: 2-5-1, properties: ["default-space": "address":"array":"location"]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "30", value: 30, type: 0, properties: ["30": "literal"]}
mem/0: array size is 30
mem/0: new alloc: 1130
run/0: instruction channel-empty?/1
run/0: {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]} <- next-ingredient 
run/0: product 0 is 1031
mem/0: storing 1031 in location 1132
run/0: instruction channel-empty?/2
run/0: {name: "full", value: 2, type: 1, properties: ["full": "integer"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "first-full", value: 0, type: 0, properties: ["first-full": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1132 is 1031
run/0: ingredient 1 is first-full
run/0: address to copy is 1031
run/0: its type is 1
mem/0: location 1031 is 0
run/0: product 0 is 0
mem/0: storing 0 in location 1133
run/0: instruction channel-empty?/3
run/0: {name: "free", value: 3, type: 1, properties: ["free": "integer"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "first-free", value: 1, type: 0, properties: ["first-free": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1132 is 1031
run/0: ingredient 1 is first-free
run/0: address to copy is 1032
run/0: its type is 1
mem/0: location 1032 is 1
run/0: product 0 is 1
mem/0: storing 1 in location 1134
run/0: instruction channel-empty?/4
run/0: {name: "result", value: 4, type: 3, properties: ["result": "boolean"]} <- equal {name: "full", value: 2, type: 1, properties: ["full": "integer"]}, {name: "free", value: 3, type: 1, properties: ["free": "integer"]}
run/0: ingredient 0 is full
mem/0: location 1133 is 0
run/0: ingredient 1 is free
mem/0: location 1134 is 1
run/0: product 0 is 0
mem/0: storing 0 in location 1135
run/0: instruction channel-empty?/5
run/0: reply {name: "result", value: 4, type: 3, properties: ["result": "boolean"]}
mem/0: location 1135 is 0
run/0: result 0 is 0
mem/0: storing 0 in location 2
run/0: instruction test-channel-write-full/3
run/0: {name: "3", value: 3, type: 1, properties: ["3": "integer"]} <- channel-full? {name: "1", value: 1, type: 2-10, properties: ["1": "address":"channel"]}
mem/0: location 1 is 1031
run/0: instruction channel-full?/0
run/0: {name: "default-space", value: 0, type: 2-5-1, properties: ["default-space": "address":"array":"location"]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "30", value: 30, type: 0, properties: ["30": "literal"]}
mem/0: array size is 30
mem/0: new alloc: 1161
run/0: instruction channel-full?/1
run/0: {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]} <- next-ingredient 
run/0: product 0 is 1031
mem/0: storing 1031 in location 1163
run/0: instruction channel-full?/2
run/0: {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "first-free", value: 1, type: 0, properties: ["first-free": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1163 is 1031
run/0: ingredient 1 is first-free
run/0: address to copy is 1032
run/0: its type is 1
mem/0: location 1032 is 1
run/0: product 0 is 1
mem/0: storing 1 in location 1164
run/0: instruction channel-full?/3
run/0: {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]} <- add {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]}, {name: "1", value: 1, type: 0, properties: ["1": "literal"]}
run/0: ingredient 0 is tmp
mem/0: location 1164 is 1
run/0: ingredient 1 is 1
run/0: product 0 is 2
mem/0: storing 2 in location 1164
run/0: instruction channel-full?/5
run/0: {name: "len", value: 3, type: 1, properties: ["len": "integer"]} <- channel-capacity {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]}
mem/0: location 1163 is 1031
run/0: instruction channel-capacity/0
run/0: {name: "default-space", value: 0, type: 2-5-1, properties: ["default-space": "address":"array":"location"]} <- new {name: "location", value: 1, type: 0, properties: ["location": "type"]}, {name: "30", value: 30, type: 0, properties: ["30": "literal"]}
mem/0: array size is 30
mem/0: new alloc: 1192
run/0: instruction channel-capacity/1
run/0: {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel"]} <- next-ingredient 
run/0: product 0 is 1031
mem/0: storing 1031 in location 1194
run/0: instruction channel-capacity/2
run/0: {name: "q", value: 2, type: 2-5-1, properties: ["q": "address":"array":"location"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "data", value: 2, type: 0, properties: ["data": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1194 is 1031
run/0: ingredient 1 is data
run/0: address to copy is 1033
run/0: its type is 2
mem/0: location 1033 is 1034
run/0: product 0 is 1034
mem/0: storing 1034 in location 1195
run/0: instruction channel-capacity/3
run/0: {name: "result", value: 3, type: 1, properties: ["result": "integer"]} <- length {name: "q", value: 2, type: 2-5-1, properties: ["q": "address":"array":"location", "deref": ]}
mem/0: location 1195 is 1034
mem/0: storing 2 in location 1196
run/0: instruction channel-capacity/4
run/0: reply {name: "result", value: 3, type: 1, properties: ["result": "integer"]}
mem/0: location 1196 is 2
run/0: result 0 is 2
mem/0: storing 2 in location 1165
run/0: instruction channel-full?/6
run/0: {name: "at-end?", value: 4, type: 3, properties: ["at-end?": "boolean"]} <- greater-or-equal {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]}, {name: "len", value: 3, type: 1, properties: ["len": "integer"]}
run/0: ingredient 0 is tmp
mem/0: location 1164 is 2
run/0: ingredient 1 is len
mem/0: location 1165 is 2
run/0: product 0 is 1
mem/0: storing 1 in location 1166
run/0: instruction channel-full?/7
run/0: break-unless {name: "at-end?", value: 4, type: 3, properties: ["at-end?": "boolean"]}, {name: "", value: 1, type: , properties: ["": ]}
mem/0: location 1166 is 1
run/0: ingredient 0 is 1
run/0: jump-unless fell through
run/0: instruction channel-full?/8
run/0: {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]} <- copy {name: "0", value: 0, type: 0, properties: ["0": "literal"]}
run/0: ingredient 0 is 0
mem/0: storing 0 in location 1164
run/0: instruction channel-full?/10
run/0: {name: "full", value: 5, type: 1, properties: ["full": "integer"]} <- get {name: "chan", value: 1, type: 2-10, properties: ["chan": "address":"channel", "deref": ]}, {name: "first-full", value: 0, type: 0, properties: ["first-full": "offset"]}
run/0: ingredient 0 is chan
mem/0: location 1163 is 1031
run/0: ingredient 1 is first-full
run/0: address to copy is 1031
run/0: its type is 1
mem/0: location 1031 is 0
run/0: product 0 is 0
mem/0: storing 0 in location 1167
run/0: instruction channel-full?/11
run/0: {name: "result", value: 6, type: 3, properties: ["result": "boolean"]} <- equal {name: "full", value: 5, type: 1, properties: ["full": "integer"]}, {name: "tmp", value: 2, type: 1, properties: ["tmp": "integer"]}
run/0: ingredient 0 is full
mem/0: location 1167 is 0
run/0: ingredient 1 is tmp
mem/0: location 1164 is 0
run/0: product 0 is 1
mem/0: storing 1 in location 1168
run/0: instruction channel-full?/12
run/0: reply {name: "result", value: 6, type: 3, properties: ["result": "boolean"]}
mem/0: location 1168 is 1
run/0: result 0 is 1
mem/0: storing 1 in location 3
1425'>1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
/*
 * commands.c
 *
 * Copyright (C) 2012 - 2014 James Booth <boothj5@gmail.com>
 *
 * This file is part of Profanity.
 *
 * Profanity is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Profanity is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Profanity.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give permission to
 * link the code of portions of this program with the OpenSSL library under
 * certain conditions as described in each individual source file, and
 * distribute linked combinations including the two.
 *
 * You must obey the GNU General Public License in all respects for all of the
 * code used other than OpenSSL. If you modify file(s) with this exception, you
 * may extend this exception to your version of the file(s), but you are not
 * obligated to do so. If you do not wish to do so, delete this exception
 * statement from your version. If you delete this exception statement from all
 * source files in the program, then also delete it here.
 *
 */

#include "config.h"

#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <glib.h>
#ifdef HAVE_LIBOTR
#include <libotr/proto.h>
#endif

#include "chat_session.h"
#include "command/commands.h"
#include "command/command.h"
#include "common.h"
#include "config/accounts.h"
#include "config/account.h"
#include "config/preferences.h"
#include "config/theme.h"
#include "contact.h"
#include "roster_list.h"
#include "jid.h"
#include "log.h"
#include "muc.h"
#ifdef HAVE_LIBOTR
#include "otr/otr.h"
#endif
#include "profanity.h"
#include "tools/autocomplete.h"
#include "tools/parser.h"
#include "tools/tinyurl.h"
#include "xmpp/xmpp.h"
#include "xmpp/bookmark.h"
#include "ui/ui.h"

static void _update_presence(const resource_presence_t presence,
    const char * const show, gchar **args);
static gboolean _cmd_set_boolean_preference(gchar *arg, struct cmd_help_t help,
    const char * const display, preference_t pref);
static int _strtoi(char *str, int *saveptr, int min, int max);
static void _cmd_show_filtered_help(char *heading, gchar *cmd_filter[], int filter_size);
static gint _compare_commands(Command *a, Command *b);
static void _who_room(const char * const presence);
static void _who_roster(const char * const group, const char * const presence);

extern GHashTable *commands;

gboolean
cmd_connect(gchar **args, struct cmd_help_t help)
{
    gboolean result = FALSE;

    jabber_conn_status_t conn_status = jabber_get_connection_status();

    if ((conn_status != JABBER_DISCONNECTED) && (conn_status != JABBER_STARTED)) {
        cons_show("You are either connected already, or a login is in process.");
        result = TRUE;
    } else {
        gchar *opt_keys[] = { "server", "port", NULL };
        gboolean parsed;

        GHashTable *options = parse_options(&args[1], opt_keys, &parsed);
        if (!parsed) {
            cons_show("Usage: %s", help.usage);
            cons_show("");
            return TRUE;
        }

        char *altdomain = g_hash_table_lookup(options, "server");

        int port = 0;
        if (g_hash_table_contains(options, "port")) {
            char *port_str = g_hash_table_lookup(options, "port");
            if (_strtoi(port_str, &port, 1, 65535) != 0) {
                port = 0;
                cons_show("");
                return TRUE;
            }
        }

        options_destroy(options);

        char *user = args[0];
        char *lower = g_utf8_strdown(user, -1);
        char *jid;

        ProfAccount *account = accounts_get_account(lower);
        if (account != NULL) {
            jid = account_create_full_jid(account);
            if (account->password == NULL) {
                account->password = ui_ask_password();
            }
            cons_show("Connecting with account %s as %s", account->name, jid);
            conn_status = jabber_connect_with_account(account);
            account_free(account);
        } else {
            char *passwd = ui_ask_password();
            jid = strdup(lower);
            cons_show("Connecting as %s", jid);
            conn_status = jabber_connect_with_details(jid, passwd, altdomain, port);
            free(passwd);
        }
        g_free(lower);

        if (conn_status == JABBER_DISCONNECTED) {
            cons_show_error("Connection attempt for %s failed.", jid);
            log_info("Connection attempt for %s failed", jid);
        }

        free(jid);

        result = TRUE;
    }

    return result;
}

gboolean
cmd_account(gchar **args, struct cmd_help_t help)
{
    char *command = args[0];

    if (command == NULL) {
        if (jabber_get_connection_status() != JABBER_CONNECTED) {
            cons_show("Usage: %s", help.usage);
        } else {
            ProfAccount *account = accounts_get_account(jabber_get_account_name());
            cons_show_account(account);
            account_free(account);
        }
    } else if (strcmp(command, "list") == 0) {
        gchar **accounts = accounts_get_list();
        cons_show_account_list(accounts);
        g_strfreev(accounts);
    } else if (strcmp(command, "show") == 0) {
        char *account_name = args[1];
        if (account_name == NULL) {
            cons_show("Usage: %s", help.usage);
        } else {
            ProfAccount *account = accounts_get_account(account_name);
            if (account == NULL) {
                cons_show("No such account.");
                cons_show("");
            } else {
                cons_show_account(account);
                account_free(account);
            }
        }
    } else if (strcmp(command, "add") == 0) {
        char *account_name = args[1];
        if (account_name == NULL) {
            cons_show("Usage: %s", help.usage);
        } else {
            accounts_add(account_name, NULL, 0);
            cons_show("Account created.");
            cons_show("");
        }
    } else if (strcmp(command, "enable") == 0) {
        char *account_name = args[1];
        if (account_name == NULL) {
            cons_show("Usage: %s", help.usage);
        } else {
            if (accounts_enable(account_name)) {
                cons_show("Account enabled.");
                cons_show("");
            } else {
                cons_show("No such account: %s", account_name);
                cons_show("");
            }
        }
    } else if (strcmp(command, "disable") == 0) {
        char *account_name = args[1];
        if (account_name == NULL) {
            cons_show("Usage: %s", help.usage);
        } else {
            if (accounts_disable(account_name)) {
                cons_show("Account disabled.");
                cons_show("");
            } else {
                cons_show("No such account: %s", account_name);
                cons_show("");
            }
        }
    } else if (strcmp(command, "rename") == 0) {
        if (g_strv_length(args) != 3) {
            cons_show("Usage: %s", help.usage);
        } else {
            char *account_name = args[1];
            char *new_name = args[2];

            if (accounts_rename(account_name, new_name)) {
                cons_show("Account renamed.");
                cons_show("");
            } else {
                cons_show("Either account %s doesn't exist, or account %s already exists.", account_name, new_name);
                cons_show("");
            }
        }
    } else if (strcmp(command, "set") == 0) {
        if (g_strv_length(args) != 4) {
            cons_show("Usage: %s", help.usage);
        } else {
            char *account_name = args[1];
            char *property = args[2];
            char *value = args[3];

            if (!accounts_account_exists(account_name)) {
                cons_show("Account %s doesn't exist", account_name);
                cons_show("");
            } else {
                if (strcmp(property, "jid") == 0) {
                    Jid *jid = jid_create(args[3]);
                    if (jid == NULL) {
                        cons_show("Malformed jid: %s", value);
                    } else {
                        accounts_set_jid(account_name, jid->barejid);
                        cons_show("Updated jid for account %s: %s", account_name, jid->barejid);
                        if (jid->resourcepart != NULL) {
                            accounts_set_resource(account_name, jid->resourcepart);
                            cons_show("Updated resource for account %s: %s", account_name, jid->resourcepart);
                        }
                        cons_show("");
                    }
                    jid_destroy(jid);
                } else if (strcmp(property, "server") == 0) {
                    accounts_set_server(account_name, value);
                    cons_show("Updated server for account %s: %s", account_name, value);
                    cons_show("");
                } else if (strcmp(property, "port") == 0) {
                    int port;
                    if (_strtoi(value, &port, 1, 65535) != 0) {
                        cons_show("");
                        return TRUE;
                    } else {
                        accounts_set_port(account_name, port);
                        cons_show("Updated port for account %s: %s", account_name, value);
                        cons_show("");
                    }
                } else if (strcmp(property, "resource") == 0) {
                    accounts_set_resource(account_name, value);
                    cons_show("Updated resource for account %s: %s", account_name, value);
                    cons_show("");
                } else if (strcmp(property, "password") == 0) {
                    accounts_set_password(account_name, value);
                    cons_show("Updated password for account %s", account_name);
                    cons_show("");
                } else if (strcmp(property, "muc") == 0) {
                    accounts_set_muc_service(account_name, value);
                    cons_show("Updated muc service for account %s: %s", account_name, value);
                    cons_show("");
                } else if (strcmp(property, "nick") == 0) {
                    accounts_set_muc_nick(account_name, value);
                    cons_show("Updated muc nick for account %s: %s", account_name, value);
                    cons_show("");
                } else if (strcmp(property, "otr") == 0) {
                    if ((g_strcmp0(value, "manual") != 0)
                            && (g_strcmp0(value, "opportunistic") != 0)
                            && (g_strcmp0(value, "always") != 0)) {
                        cons_show("OTR policy must be one of: manual, opportunistic or always.");
                    } else {
                        accounts_set_otr_policy(account_name, value);
                        cons_show("Updated OTR policy for account %s: %s", account_name, value);
                        cons_show("");
                    }
                } else if (strcmp(property, "status") == 0) {
                    if (!valid_resource_presence_string(value) && (strcmp(value, "last") != 0)) {
                        cons_show("Invalid status: %s", value);
                    } else {
                        accounts_set_login_presence(account_name, value);
                        cons_show("Updated login status for account %s: %s", account_name, value);
                    }
                    cons_show("");
                } else if (valid_resource_presence_string(property)) {
                        int intval;

                        if (_strtoi(value, &intval, -128, 127) == 0) {
                            resource_presence_t presence_type = resource_presence_from_string(property);
                            switch (presence_type)
                            {
                                case (RESOURCE_ONLINE):
                                    accounts_set_priority_online(account_name, intval);
                                    break;
                                case (RESOURCE_CHAT):
                                    accounts_set_priority_chat(account_name, intval);
                                    break;
                                case (RESOURCE_AWAY):
                                    accounts_set_priority_away(account_name, intval);
                                    break;
                                case (RESOURCE_XA):
                                    accounts_set_priority_xa(account_name, intval);
                                    break;
                                case (RESOURCE_DND):
                                    accounts_set_priority_dnd(account_name, intval);
                                    break;
                            }

                            jabber_conn_status_t conn_status = jabber_get_connection_status();
                            if (conn_status == JABBER_CONNECTED) {
                                char *connected_account = jabber_get_account_name();
                                resource_presence_t last_presence = accounts_get_last_presence(connected_account);

                                if (presence_type == last_presence) {
                                    char *message = jabber_get_presence_message();
                                    presence_update(last_presence, message, 0);
                                }
                            }
                            cons_show("Updated %s priority for account %s: %s", property, account_name, value);
                            cons_show("");
                        }
                } else {
                    cons_show("Invalid property: %s", property);
                    cons_show("");
                }
            }
        }
    } else if (strcmp(command, "clear") == 0) {
        if (g_strv_length(args) != 3) {
            cons_show("Usage: %s", help.usage);
        } else {
            char *account_name = args[1];
            char *property = args[2];

            if (!accounts_account_exists(account_name)) {
                cons_show("Account %s doesn't exist", account_name);
                cons_show("");
            } else {
                if (strcmp(property, "password") == 0) {
                    accounts_clear_password(account_name);
                    cons_show("Removed password for account %s", account_name);
                    cons_show("");
                } else if (strcmp(property, "otr") == 0) {
                    accounts_clear_otr(account_name);
                    cons_show("OTR policy removed for account %s", account_name);
                    cons_show("");
                } else {
                    cons_show("Invalid property: %s", property);
                    cons_show("");
                }
            }
        }
    } else {
        cons_show("");
    }

    return TRUE;
}

gboolean
cmd_sub(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    char *subcmd, *jid;
    subcmd = args[0];
    jid = args[1];

    if (subcmd == NULL) {
        cons_show("Usage: %s", help.usage);
        return TRUE;
    }

    if (strcmp(subcmd, "sent") == 0) {
        cons_show_sent_subs();
        return TRUE;
    }

    if (strcmp(subcmd, "received") == 0) {
        cons_show_received_subs();
        return TRUE;
    }

    win_type_t win_type = ui_current_win_type();
    if ((win_type != WIN_CHAT) && (jid == NULL)) {
        cons_show("You must specify a contact.");
        return TRUE;
    }

    if (jid == NULL) {
        jid = ui_current_recipient();
    }

    Jid *jidp = jid_create(jid);

    if (strcmp(subcmd, "allow") == 0) {
        presence_subscription(jidp->barejid, PRESENCE_SUBSCRIBED);
        cons_show("Accepted subscription for %s", jidp->barejid);
        log_info("Accepted subscription for %s", jidp->barejid);
    } else if (strcmp(subcmd, "deny") == 0) {
        presence_subscription(jidp->barejid, PRESENCE_UNSUBSCRIBED);
        cons_show("Deleted/denied subscription for %s", jidp->barejid);
        log_info("Deleted/denied subscription for %s", jidp->barejid);
    } else if (strcmp(subcmd, "request") == 0) {
        presence_subscription(jidp->barejid, PRESENCE_SUBSCRIBE);
        cons_show("Sent subscription request to %s.", jidp->barejid);
        log_info("Sent subscription request to %s.", jidp->barejid);
    } else if (strcmp(subcmd, "show") == 0) {
        PContact contact = roster_get_contact(jidp->barejid);
        if ((contact == NULL) || (p_contact_subscription(contact) == NULL)) {
            if (win_type == WIN_CHAT) {
                ui_current_print_line("No subscription information for %s.", jidp->barejid);
            } else {
                cons_show("No subscription information for %s.", jidp->barejid);
            }
        } else {
            if (win_type == WIN_CHAT) {
                if (p_contact_pending_out(contact)) {
                    ui_current_print_line("%s subscription status: %s, request pending.",
                        jidp->barejid, p_contact_subscription(contact));
                } else {
                    ui_current_print_line("%s subscription status: %s.", jidp->barejid,
                        p_contact_subscription(contact));
                }
            } else {
                if (p_contact_pending_out(contact)) {
                    cons_show("%s subscription status: %s, request pending.",
                        jidp->barejid, p_contact_subscription(contact));
                } else {
                    cons_show("%s subscription status: %s.", jidp->barejid,
                        p_contact_subscription(contact));
                }
            }
        }
    } else {
        cons_show("Usage: %s", help.usage);
    }

    jid_destroy(jidp);

    return TRUE;
}

gboolean
cmd_disconnect(gchar **args, struct cmd_help_t help)
{
    if (jabber_get_connection_status() == JABBER_CONNECTED) {
        char *jid = strdup(jabber_get_fulljid());
        cons_show("%s logged out successfully.", jid);
        jabber_disconnect();
        roster_clear();
        muc_clear_invites();
        chat_sessions_clear();
        ui_disconnected();
        free(jid);
    } else {
        cons_show("You are not currently connected.");
    }

    return TRUE;
}

gboolean
cmd_quit(gchar **args, struct cmd_help_t help)
{
    log_info("Profanity is shutting down...");
    exit(0);
    return FALSE;
}

gboolean
cmd_wins(gchar **args, struct cmd_help_t help)
{
    if (args[0] == NULL) {
        cons_show_wins();
    } else if (strcmp(args[0], "tidy") == 0) {
        ui_tidy_wins();
    } else if (strcmp(args[0], "prune") == 0) {
        ui_prune_wins();
    } else if (strcmp(args[0], "swap") == 0) {
        if ((args[1] == NULL) || (args[2] == NULL)) {
            cons_show("Usage: %s", help.usage);
        } else {
            int source_win = atoi(args[1]);
            int target_win = atoi(args[2]);
            if ((source_win == 1) || (target_win == 1)) {
                cons_show("Cannot move console window.");
            } else if (source_win == 10 || target_win == 10) {
                cons_show("Window 10 does not exist");
            } else if (source_win != target_win) {
                gboolean swapped = ui_swap_wins(source_win, target_win);
                if (swapped) {
                    cons_show("Swapped windows %d <-> %d", source_win, target_win);
                } else {
                    cons_show("Window %d does not exist", source_win);
                }
            } else {
                cons_show("Same source and target window supplied.");
            }
        }
    }

    return TRUE;
}

gboolean
cmd_win(gchar **args, struct cmd_help_t help)
{
    int num = atoi(args[0]);
    gboolean switched = ui_switch_win(num);
    if (switched == FALSE) {
        cons_show("Window %d does not exist.", num);
    }
    return TRUE;
}

gboolean
cmd_help(gchar **args, struct cmd_help_t help)
{
    int num_args = g_strv_length(args);
    if (num_args == 0) {
        cons_help();
    } else if (strcmp(args[0], "commands") == 0) {
        cons_show("");
        cons_show("All commands");
        cons_show("");

        GList *ordered_commands = NULL;
        GHashTableIter iter;
        gpointer key;
        gpointer value;

        g_hash_table_iter_init(&iter, commands);
        while (g_hash_table_iter_next(&iter, &key, &value)) {
            ordered_commands = g_list_insert_sorted(ordered_commands, value, (GCompareFunc)_compare_commands);
        }

        GList *curr = ordered_commands;
        while (curr != NULL) {
            Command *cmd = curr->data;
            cons_show("%-12s: %s", cmd->cmd, cmd->help.short_help);
            curr = g_list_next(curr);
        }
        g_list_free(ordered_commands);
        g_list_free(curr);

        cons_show("");
        cons_show("Use /help [command] without the leading slash, for help on a specific command");
        cons_show("");

    } else if (strcmp(args[0], "basic") == 0) {
        gchar *filter[] = { "/about", "/clear", "/close", "/connect",
            "/disconnect", "/help", "/msg", "/join", "/quit", "/vercheck",
            "/wins" };
        _cmd_show_filtered_help("Basic commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "chatting") == 0) {
        gchar *filter[] = { "/chlog", "/otr", "/duck", "/gone", "/history",
            "/info", "/intype", "/msg", "/notify", "/outtype", "/status",
            "/close", "/clear", "/tiny" };
        _cmd_show_filtered_help("Chat commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "groupchat") == 0) {
        gchar *filter[] = { "/close", "/clear", "/decline", "/grlog",
            "/invite", "/invites", "/join", "/leave", "/notify", "/msg",
            "/rooms", "/tiny", "/who", "/nick" };
        _cmd_show_filtered_help("Groupchat commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "presence") == 0) {
        gchar *filter[] = { "/autoaway", "/away", "/chat", "/dnd",
            "/online", "/priority", "/account", "/status", "/statuses", "/who",
            "/xa" };
        _cmd_show_filtered_help("Presence commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "contacts") == 0) {
        gchar *filter[] = { "/group", "/roster", "/sub", "/who" };
        _cmd_show_filtered_help("Roster commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "service") == 0) {
        gchar *filter[] = { "/caps", "/disco", "/info", "/software", "/rooms" };
        _cmd_show_filtered_help("Service discovery commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "settings") == 0) {
        gchar *filter[] = { "/account", "/autoaway", "/autoping", "/autoconnect", "/beep",
            "/chlog", "/flash", "/gone", "/grlog", "/history", "/intype",
            "/log", "/mouse", "/notify", "/outtype", "/prefs", "/priority",
            "/reconnect", "/roster", "/splash", "/states", "/statuses", "/theme",
            "/titlebar", "/vercheck" };
        _cmd_show_filtered_help("Settings commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "other") == 0) {
        gchar *filter[] = { "/duck", "/vercheck" };
        _cmd_show_filtered_help("Other commands", filter, ARRAY_SIZE(filter));

    } else if (strcmp(args[0], "navigation") == 0) {
        cons_navigation_help();
    } else {
        char *cmd = args[0];
        char cmd_with_slash[1 + strlen(cmd) + 1];
        sprintf(cmd_with_slash, "/%s", cmd);

        const gchar **help_text = NULL;
        Command *command = g_hash_table_lookup(commands, cmd_with_slash);

        if (command != NULL) {
            help_text = command->help.long_help;
        }

        cons_show("");

        if (help_text != NULL) {
            int i;
            for (i = 0; help_text[i] != NULL; i++) {
                cons_show(help_text[i]);
            }
        } else {
            cons_show("No such command.");
        }

        cons_show("");
    }

    return TRUE;
}

gboolean
cmd_about(gchar **args, struct cmd_help_t help)
{
    ui_about();
    return TRUE;
}

gboolean
cmd_prefs(gchar **args, struct cmd_help_t help)
{
    if (args[0] == NULL) {
        cons_prefs();
        cons_show("Use the /account command for preferences for individual accounts.");
    } else if (strcmp(args[0], "ui") == 0) {
        cons_show("");
        cons_show_ui_prefs();
        cons_show("");
    } else if (strcmp(args[0], "desktop") == 0) {
        cons_show("");
        cons_show_desktop_prefs();
        cons_show("");
    } else if (strcmp(args[0], "chat") == 0) {
        cons_show("");
        cons_show_chat_prefs();
        cons_show("");
    } else if (strcmp(args[0], "log") == 0) {
        cons_show("");
        cons_show_log_prefs();
        cons_show("");
    } else if (strcmp(args[0], "conn") == 0) {
        cons_show("");
        cons_show_connection_prefs();
        cons_show("");
    } else if (strcmp(args[0], "presence") == 0) {
        cons_show("");
        cons_show_presence_prefs();
        cons_show("");
    } else if (strcmp(args[0], "otr") == 0) {
        cons_show("");
        cons_show_otr_prefs();
        cons_show("");
    } else {
        cons_show("Usage: %s", help.usage);
    }

    return TRUE;
}

gboolean
cmd_theme(gchar **args, struct cmd_help_t help)
{
    // list themes
    if (strcmp(args[0], "list") == 0) {
        GSList *themes = theme_list();
        cons_show_themes(themes);
        g_slist_free_full(themes, g_free);

    // load a theme
    } else if (strcmp(args[0], "set") == 0) {
        if (args[1] == NULL) {
            cons_show("Usage: %s", help.usage);
        } else if (theme_load(args[1])) {
            ui_load_colours();
            prefs_set_string(PREF_THEME, args[1]);
            cons_show("Loaded theme: %s", args[1]);
        } else {
            cons_show("Couldn't find theme: %s", args[1]);
        }
    } else {
        cons_show("Usage: %s", help.usage);
    }

    return TRUE;
}

static void
_who_room(const char * const presence)
{
    char *room = ui_current_recipient();
    GList *list = muc_get_roster(room);

    // no arg, show all contacts
    if ((presence == NULL) || (g_strcmp0(presence, "any") == 0)) {
        ui_room_roster(room, list, NULL);

    // available
    } else if (strcmp("available", presence) == 0) {
        GList *filtered = NULL;

        while (list != NULL) {
            PContact contact = list->data;
            if (p_contact_is_available(contact)) {
                filtered = g_list_append(filtered, contact);
            }
            list = g_list_next(list);
        }

        ui_room_roster(room, filtered, "available");

    // unavailable
    } else if (strcmp("unavailable", presence) == 0) {
        GList *filtered = NULL;

        while (list != NULL) {
            PContact contact = list->data;
            if (!p_contact_is_available(contact)) {
                filtered = g_list_append(filtered, contact);
            }
            list = g_list_next(list);
        }

        ui_room_roster(room, filtered, "unavailable");

    // online, available resources
    } else if (strcmp("online", presence) == 0) {
        GList *filtered = NULL;

        while (list != NULL) {
            PContact contact = list->data;
            if (p_contact_has_available_resource(contact)) {
                filtered = g_list_append(filtered, contact);
            }
            list = g_list_next(list);
        }

        ui_room_roster(room, filtered, "online");

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

        while (list != NULL) {
            PContact contact = list->data;
            if (!p_contact_has_available_resource(contact)) {
                filtered = g_list_append(filtered, contact);
            }
            list = g_list_next(list);
        }

        ui_room_roster(room, filtered, "offline");

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

        while (list != NULL) {
            PContact contact = list->data;
            if (strcmp(p_contact_presence(contact), presence) == 0) {
                filtered = g_list_append(filtered, contact);
            }
            list = g_list_next(list);
        }

        ui_room_roster(room, filtered, presence);
    }
}

static void
_who_roster(const char * const group, const char * const presence)
{
    cons_show("");
    GSList *list = NULL;
    if (group != NULL) {
        list = roster_get_group(group);
        if (list == NULL) {
            cons_show("No such group: %s.", group);
            return;
        }
    } else {
        list = roster_get_contacts();
        if (list == NULL) {
            cons_show("No contacts in roster.");
            return;
        }
    }

    // no arg, show all contacts
    if ((presence == NULL) || (g_strcmp0(presence, "any") == 0)) {
        if (group != NULL) {
            if (list == NULL) {
                cons_show("No contacts in group %s.", group);
            } else {
                cons_show("%s:", group);
                cons_show_contacts(list);
            }
        } else {
            if (list == NULL) {
                cons_show("You have no contacts.");
            } else {
                cons_show("All contacts:");
                cons_show_contacts(list);
            }
        }

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

        while (list != NULL) {
            PContact contact = list->data;
            if (p_contact_is_available(contact)) {
                filtered = g_slist_append(filtered, contact);
            }
            list = g_slist_next(list);
        }

        if (group != NULL) {
            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);
            }
        }

    // unavailable
    } else if (strcmp("unavailable", presence) == 0) {
        GSList *filtered = NULL;

        while (list != NULL) {
            PContact contact = list->data;
            if (!p_contact_is_available(contact)) {
                filtered = g_slist_append(filtered, contact);
            }
            list = g_slist_next(list);
        }

        if (group != NULL) {
            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);
            }
        }

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

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

        if (group != NULL) {
            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);
            }
        }

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

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

        if (group != NULL) {
            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);
            }
        }

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

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

        if (group != NULL) {
            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);
            }
        }
    }
}

gboolean
cmd_who(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();
    win_type_t win_type = ui_current_win_type();

    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
    } else {
        char *presence = args[0];
        char *group = NULL;
        if ((g_strv_length(args) == 2) && (args[1] != NULL)) {
            group = args[1];
        }

        // bad arg
        if ((presence != NULL)
                && (strcmp(presence, "online") != 0)
                && (strcmp(presence, "available") != 0)
                && (strcmp(presence, "unavailable") != 0)
                && (strcmp(presence, "offline") != 0)
                && (strcmp(presence, "away") != 0)
                && (strcmp(presence, "chat") != 0)
                && (strcmp(presence, "xa") != 0)
                && (strcmp(presence, "dnd") != 0)
                && (strcmp(presence, "any") != 0)) {
            cons_show("Usage: %s", help.usage);

        } else {
            if (win_type == WIN_MUC) {
                if (group != NULL) {
                    cons_show("The group argument is not valid when in a chat room.");
                } else {
                    _who_room(presence);
                }

            } else {
                _who_roster(group, presence);
            }
        }
    }

    if (win_type != WIN_CONSOLE && win_type != WIN_MUC) {
        ui_statusbar_new(1);
    }

    return TRUE;
}

gboolean
cmd_msg(gchar **args, struct cmd_help_t help)
{
    char *usr = args[0];
    char *msg = args[1];

    jabber_conn_status_t conn_status = jabber_get_connection_status();
    win_type_t win_type = ui_current_win_type();

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

    if (win_type == WIN_MUC) {
        char *room_name = ui_current_recipient();
        if (muc_nick_in_roster(room_name, usr)) {
            GString *full_jid = g_string_new(room_name);
            g_string_append(full_jid, "/");
            g_string_append(full_jid, usr);

            if (msg != NULL) {
                message_send(msg, full_jid->str);
                ui_outgoing_msg("me", full_jid->str, msg);
            } else {
                ui_new_chat_win(full_jid->str);
            }

            g_string_free(full_jid, TRUE);

        } else {
            ui_current_print_line("No such participant \"%s\" in room.", usr);
        }

        return TRUE;

    } else {
        char *usr_jid = roster_barejid_from_name(usr);
        if (usr_jid == NULL) {
            usr_jid = usr;
        }
        if (msg != NULL) {
#ifdef HAVE_LIBOTR
            if (otr_is_secure(usr_jid)) {
                char *encrypted = otr_encrypt_message(usr_jid, msg);
                if (encrypted != NULL) {
                    message_send(encrypted, usr_jid);
                    otr_free_message(encrypted);
                    ui_outgoing_msg("me", usr_jid, msg);

                    if (((win_type == WIN_CHAT) || (win_type == WIN_CONSOLE)) && prefs_get_boolean(PREF_CHLOG)) {
                        const char *jid = jabber_get_fulljid();
                        Jid *jidp = jid_create(jid);
                        char *pref_otr_log = prefs_get_string(PREF_OTR_LOG);
                        if (strcmp(pref_otr_log, "on") == 0) {
                            chat_log_chat(jidp->barejid, usr_jid, msg, PROF_OUT_LOG, NULL);
                        } else if (strcmp(pref_otr_log, "redact") == 0) {
                            chat_log_chat(jidp->barejid, usr_jid, "[redacted]", PROF_OUT_LOG, NULL);
                        }
                        prefs_free_string(pref_otr_log);
                        jid_destroy(jidp);
                    }
                } else {
                    cons_show_error("Failed to encrypt and send message,");
                }
            } else {
                prof_otrpolicy_t policy = otr_get_policy(usr_jid);

                if (policy == PROF_OTRPOLICY_ALWAYS) {
                    cons_show_error("Failed to send message. Please check OTR policy");
                    return TRUE;
                } else if (policy == PROF_OTRPOLICY_OPPORTUNISTIC) {
                    char *otr_base_tag = OTRL_MESSAGE_TAG_BASE;
                    char *otr_v2_tag = OTRL_MESSAGE_TAG_V2;
                    int N = strlen(otr_base_tag) + strlen(otr_v2_tag) + strlen(msg) + 1;
                    char *temp = (char *) malloc( (unsigned) N*sizeof(char *) );
                    strcpy( temp , msg );
                    strcat( temp , otr_base_tag);
                    strcat( temp, otr_v2_tag);
                    message_send(temp, usr_jid);
                    free(temp);
                } else {
                    message_send(msg, usr_jid);
                }
                ui_outgoing_msg("me", usr_jid, msg);

                if (((win_type == WIN_CHAT) || (win_type == WIN_CONSOLE)) && prefs_get_boolean(PREF_CHLOG)) {
                    const char *jid = jabber_get_fulljid();
                    Jid *jidp = jid_create(jid);
                    chat_log_chat(jidp->barejid, usr_jid, msg, PROF_OUT_LOG, NULL);
                    jid_destroy(jidp);
                }
            }
            return TRUE;
#else
            message_send(msg, usr_jid);
            ui_outgoing_msg("me", usr_jid, msg);

            if (((win_type == WIN_CHAT) || (win_type == WIN_CONSOLE)) && prefs_get_boolean(PREF_CHLOG)) {
                const char *jid = jabber_get_fulljid();
                Jid *jidp = jid_create(jid);
                chat_log_chat(jidp->barejid, usr_jid, msg, PROF_OUT_LOG, NULL);
                jid_destroy(jidp);
            }
            return TRUE;
#endif

        } else {
            const char * jid = NULL;

            if (roster_barejid_from_name(usr_jid) != NULL) {
                jid = roster_barejid_from_name(usr_jid);
            } else {
                jid = usr_jid;
            }

            if (prefs_get_boolean(PREF_STATES)) {
                if (!chat_session_exists(jid)) {
                    chat_session_start(jid, TRUE);
                }
            }

            ui_new_chat_win(usr_jid);
#ifdef HAVE_LIBOTR
            if (otr_is_secure(jid)) {
                ui_gone_secure(jid, otr_is_trusted(jid));
            }
#endif
            return TRUE;
        }
    }
}

gboolean
cmd_group(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

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

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

    // show contacts in group
    if (strcmp(args[0], "show") == 0) {
        char *group = args[1];
        if (group == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        }

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

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

        if ((group == NULL) || (contact == NULL)) {
            cons_show("Usage: %s", help.usage);
            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[0], "remove") == 0) {
        char *group = args[1];
        char *contact = args[2];

        if ((group == NULL) || (contact == NULL)) {
            cons_show("Usage: %s", help.usage);
            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_show("Usage: %s", help.usage);
    return TRUE;
}

gboolean
cmd_roster(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    // show roster
    if (args[0] == NULL) {
        GSList *list = roster_get_contacts();
        cons_show_roster(list);
        return TRUE;

    // add contact
    } else if (strcmp(args[0], "add") == 0) {
        char *jid = args[1];
        if (jid == NULL) {
            cons_show("Usage: %s", help.usage);
        } else {
            char *name = args[2];
            roster_send_add_new(jid, name);
        }
        return TRUE;

    // remove contact
    } else if (strcmp(args[0], "remove") == 0) {
        char *jid = args[1];
        if (jid == NULL) {
            cons_show("Usage: %s", help.usage);
        } else {
            roster_send_remove(jid);
        }
        return TRUE;

    // change nickname
    } else if (strcmp(args[0], "nick") == 0) {
        char *jid = args[1];
        if (jid == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        }

        char *name = args[2];
        if (name == NULL) {
            cons_show("Usage: %s", help.usage);
            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);
        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) {
        char *jid = args[1];
        if (jid == NULL) {
            cons_show("Usage: %s", help.usage);
            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);
        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_show("Usage: %s", help.usage);
        return TRUE;
    }
}

gboolean
cmd_duck(gchar **args, struct cmd_help_t help)
{
    char *query = args[0];

    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    // if no duck win open, create it and send a help command
    if (!ui_duck_exists()) {
        ui_create_duck_win();

        if (query != NULL) {
            message_send_duck(query);
            ui_duck(query);
        }

    // window exists, send query
    } else {
        ui_open_duck_win();

        if (query != NULL) {
            message_send_duck(query);
            ui_duck(query);
        }
    }

    return TRUE;
}

gboolean
cmd_status(gchar **args, struct cmd_help_t help)
{
    char *usr = args[0];

    jabber_conn_status_t conn_status = jabber_get_connection_status();
    win_type_t win_type = ui_current_win_type();

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

    switch (win_type)
    {
        case WIN_MUC:
            if (usr != NULL) {
                ui_status_room(usr);
            } else {
                ui_current_print_line("You must specify a nickname.");
            }
            break;
        case WIN_CHAT:
            if (usr != NULL) {
                ui_current_print_line("No parameter required when in chat.");
            } else {
                ui_status();
            }
            break;
        case WIN_PRIVATE:
            if (usr != NULL) {
                ui_current_print_line("No parameter required when in chat.");
            } else {
                ui_status_private();
            }
            break;
        case WIN_CONSOLE:
            if (usr != NULL) {
                char *usr_jid = roster_barejid_from_name(usr);
                if (usr_jid == NULL) {
                    usr_jid = usr;
                }
                cons_show_status(usr_jid);
            } else {
                cons_show("Usage: %s", help.usage);
            }
            break;
        default:
            break;
    }

    return TRUE;
}

gboolean
cmd_info(gchar **args, struct cmd_help_t help)
{
    char *usr = args[0];

    jabber_conn_status_t conn_status = jabber_get_connection_status();
    win_type_t win_type = ui_current_win_type();
    PContact pcontact = NULL;

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

    switch (win_type)
    {
        case WIN_MUC:
            if (usr != NULL) {
                ui_info_room(usr);
            } else {
                ui_current_print_line("You must specify a nickname.");
            }
            break;
        case WIN_CHAT:
            if (usr != NULL) {
                ui_current_print_line("No parameter required when in chat.");
            } else {
                ui_info();
            }
            break;
        case WIN_PRIVATE:
            if (usr != NULL) {
                ui_current_print_line("No parameter required when in chat.");
            } else {
                ui_info_private();
            }
            break;
        case WIN_CONSOLE:
            if (usr != NULL) {
                char *usr_jid = roster_barejid_from_name(usr);
                if (usr_jid == NULL) {
                    usr_jid = usr;
                }
                pcontact = roster_get_contact(usr_jid);
                if (pcontact != NULL) {
                    cons_show_info(pcontact);
                } else {
                    cons_show("No such contact \"%s\" in roster.", usr);
                }
            } else {
                cons_show("Usage: %s", help.usage);
            }
            break;
        default:
            break;
    }

    return TRUE;
}

gboolean
cmd_caps(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();
    win_type_t win_type = ui_current_win_type();
    PContact pcontact = NULL;
    char *recipient;

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

    switch (win_type)
    {
        case WIN_MUC:
            if (args[0] != NULL) {
                recipient = ui_current_recipient();
                pcontact = muc_get_participant(recipient, args[0]);
                if (pcontact != NULL) {
                    Resource *resource = p_contact_get_resource(pcontact, args[0]);
                    cons_show_caps(args[0], resource);
                } 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] != NULL) {
                Jid *jid = jid_create(args[0]);

                if (jid->fulljid == NULL) {
                    cons_show("You must provide a full jid to the /caps command.");
                } else {
                    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);
                        }
                    }
                }
            } else {
                cons_show("You must provide a jid to the /caps command.");
            }
            break;
        case WIN_PRIVATE:
            if (args[0] != NULL) {
                cons_show("No parameter needed to /caps when in private chat.");
            } else {
                recipient = ui_current_recipient();
                Jid *jid = jid_create(recipient);
                if (jid) {
                    pcontact = muc_get_participant(jid->barejid, jid->resourcepart);
                    Resource *resource = p_contact_get_resource(pcontact, jid->resourcepart);
                    cons_show_caps(jid->resourcepart, resource);
                    jid_destroy(jid);
                }
            }
            break;
        default:
            break;
    }

    return TRUE;
}


gboolean
cmd_software(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();
    win_type_t win_type = ui_current_win_type();
    PContact pcontact = NULL;
    char *recipient;

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

    switch (win_type)
    {
        case WIN_MUC:
            if (args[0] != NULL) {
                recipient = ui_current_recipient();
                pcontact = muc_get_participant(recipient, args[0]);
                if (pcontact != NULL) {
                    Jid *jid = jid_create_from_bare_and_resource(recipient, 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:
        case WIN_CONSOLE:
            if (args[0] != NULL) {
                Jid *jid = jid_create(args[0]);

                if (jid == NULL || jid->fulljid == NULL) {
                    cons_show("You must provide a full jid to the /software command.");
                } else {
                    iq_send_software_version(jid->fulljid);
                }
                jid_destroy(jid);
            } else {
                cons_show("You must provide a jid to the /software command.");
            }
            break;
        case WIN_PRIVATE:
            if (args[0] != NULL) {
                cons_show("No parameter needed to /software when in private chat.");
            } else {
                recipient = ui_current_recipient();
                iq_send_software_version(recipient);
            }
            break;
        default:
            break;
    }

    return TRUE;
}

gboolean
cmd_join(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();
    if (conn_status != JABBER_CONNECTED) {
        cons_show("You are not currently connected.");
        return TRUE;
    }

    if (args[0] == NULL) {
        cons_show("Usage: %s", help.usage);
        cons_show("");
        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;
    GString *room_str = g_string_new("");
    char *account_name = jabber_get_account_name();
    ProfAccount *account = accounts_get_account(account_name);

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

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

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

    GHashTable *options = parse_options(&args[1], opt_keys, &parsed);
    if (!parsed) {
        cons_show("Usage: %s", help.usage);
        cons_show("");
        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 == NULL) {
        nick = account->muc_nick;
    }

    if (!muc_room_is_active(room)) {
        presence_join_room(room, nick, passwd);
        muc_join_room(room, nick, passwd, FALSE);
    } else if (muc_get_roster_received(room)) {
        ui_room_join(room, TRUE);
    }

    jid_destroy(room_arg);
    g_string_free(room_str, TRUE);
    account_free(account);

    return TRUE;
}

gboolean
cmd_invite(gchar **args, struct cmd_help_t help)
{
    char *contact = args[0];
    char *reason = args[1];
    char *room = NULL;
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    if (ui_current_win_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;
    }
    room = ui_current_recipient();
    message_send_invite(room, usr_jid, reason);
    if (reason != NULL) {
        cons_show("Room invite sent, contact: %s, room: %s, reason: \"%s\".",
            contact, room, reason);
    } else {
        cons_show("Room invite sent, contact: %s, room: %s.",
            contact, room);
    }

    return TRUE;
}

gboolean
cmd_invites(gchar **args, struct cmd_help_t help)
{
    GSList *invites = muc_get_invites();
    cons_show_room_invites(invites);
    g_slist_free_full(invites, g_free);
    return TRUE;
}

gboolean
cmd_decline(gchar **args, struct cmd_help_t help)
{
    if (!muc_invites_include(args[0])) {
        cons_show("No such invite exists.");
    } else {
        muc_remove_invite(args[0]);
        cons_show("Declined invite to %s.", args[0]);
    }

    return TRUE;
}

gboolean
cmd_room(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    if (g_strcmp0(args[1], "accept") == 0) {
        // TODO check that we're in room, we're owner and room requires configuration
        char *room = ui_current_recipient();
        iq_create_instant_room(room);

    } else if (g_strcmp0(args[1], "cancel") == 0) {
        // check that we're in room, we're owner and room requires configuration
        char *room = ui_current_recipient();
        iq_destroy_instant_room(room);

    } else {
        cons_show("Usage: %s", help.usage);
    }
    return TRUE;
}

gboolean
cmd_rooms(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    if (args[0] == NULL) {
        ProfAccount *account = accounts_get_account(jabber_get_account_name());
        iq_room_list_request(account->muc_service);
    } else {
        iq_room_list_request(args[0]);
    }

    return TRUE;
}

gboolean
cmd_bookmark(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    win_type_t win_type = ui_current_win_type();

    if (win_type == WIN_MUC) {
        gchar *cmd = args[0];

        // default to current nickname, password, and autojoin "on"
        if (cmd == NULL) {
            char *jid = ui_current_recipient();
            char *nick = muc_get_room_nick(jid);
            char *password = muc_get_room_password(jid);
            gboolean added = bookmark_add(jid, nick, password, "on");
            if (added) {
                ui_current_print_formatted_line('!', 0, "Bookmark added for %s.", jid);
            } else {
                ui_current_print_formatted_line('!', 0, "Bookmark already exists for %s.", jid);
            }
            return TRUE;
        } else {
            ui_current_print_formatted_line('!', 0, "No arguments required for /bookmark in a chat room");
            return TRUE;
        }

    } else {
        gchar *cmd = args[0];
        if (cmd == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        }

        if (strcmp(cmd, "list") == 0) {
            const GList *bookmarks = bookmark_get_list();
            cons_show_bookmarks(bookmarks);
        } else {
            char *jid = args[1];
            if (jid == NULL) {
                cons_show("Usage: %s", help.usage);
                cons_show("");
                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);
                }
                return TRUE;
            }

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

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

            GHashTable *options = parse_options(&args[2], opt_keys, &parsed);
            if (!parsed) {
                cons_show("Usage: %s", help.usage);
                cons_show("");
                return TRUE;
            }

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

            if (autojoin != NULL) {
                if ((strcmp(autojoin, "on") != 0) && (strcmp(autojoin, "off") != 0)) {
                    cons_show("Usage: %s", help.usage);
                    cons_show("");
                    return TRUE;
                }
            }

            if (strcmp(cmd, "add") == 0) {
                if (strchr(jid, '@')==NULL) {
                    cons_show("Can't add bookmark with JID '%s'; should be '%s@domain.tld'", jid, jid);
                } else {
                    gboolean added = bookmark_add(jid, nick, password, autojoin);
                    if (added) {
                        cons_show("Bookmark added for %s.", jid);
                    } else {
                        cons_show("Bookmark already exists, use /bookmark update to edit.");
                    }
                }
            } else if (strcmp(cmd, "update") == 0) {
                gboolean updated = bookmark_update(jid, nick, password, autojoin);
                if (updated) {
                    cons_show("Bookmark updated.");
                } else {
                    cons_show("No bookmark exists for %s.", jid);
                }
            } else {
                cons_show("Usage: %s", help.usage);
            }

            options_destroy(options);
        }
    }

    return TRUE;
}

gboolean
cmd_disco(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    GString *jid = g_string_new("");
    if (args[1] != NULL) {
        jid = g_string_append(jid, args[1]);
    } else {
        Jid *jidp = jid_create(jabber_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;
}

gboolean
cmd_nick(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    char *room = ui_current_recipient();
    char *nick = args[0];
    presence_change_room_nick(room, nick);

    return TRUE;
}

gboolean
cmd_alias(gchar **args, struct cmd_help_t help)
{
    char *subcmd = args[0];

    if (strcmp(subcmd, "add") == 0) {
        char *alias = args[1];
        if (alias == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        } else {
            GString *ac_value = g_string_new("/");
            g_string_append(ac_value, alias);

            char *value = args[2];
            if (value == NULL) {
                cons_show("Usage: %s", help.usage);
                g_string_free(ac_value, TRUE);
                return TRUE;
            } else if (cmd_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, value);
                cmd_autocomplete_add(ac_value->str);
                cmd_alias_add(alias);
                cons_show("Command alias added /%s -> %s", alias, value);
                g_string_free(ac_value, TRUE);
                return TRUE;
            }
        }
    } else if (strcmp(subcmd, "remove") == 0) {
        char *alias = args[1];
        if (alias == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        } else {
            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_autocomplete_remove(ac_value->str);
                cmd_alias_remove(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_show("Usage: %s", help.usage);
        return TRUE;
    }
}

gboolean
cmd_tiny(gchar **args, struct cmd_help_t help)
{
    char *url = args[0];
    win_type_t win_type = ui_current_win_type();

    if (!tinyurl_valid(url)) {
        GString *error = g_string_new("/tiny, badly formed URL: ");
        g_string_append(error, url);
        cons_show_error(error->str);
        if (win_type != WIN_CONSOLE) {
            ui_current_error_line(error->str);
        }
        g_string_free(error, TRUE);
    } else if (win_type != WIN_CONSOLE) {
        char *tiny = tinyurl_get(url);

        if (tiny != NULL) {
            if (win_type == WIN_CHAT) {
                char *recipient = ui_current_recipient();
#ifdef HAVE_LIBOTR
                if (otr_is_secure(recipient)) {
                    char *encrypted = otr_encrypt_message(recipient, tiny);
                    if (encrypted != NULL) {
                        message_send(encrypted, recipient);
                        otr_free_message(encrypted);
                        if (prefs_get_boolean(PREF_CHLOG)) {
                            const char *jid = jabber_get_fulljid();
                            Jid *jidp = jid_create(jid);
                            char *pref_otr_log = prefs_get_string(PREF_OTR_LOG);
                            if (strcmp(pref_otr_log, "on") == 0) {
                                chat_log_chat(jidp->barejid, recipient, tiny, PROF_OUT_LOG, NULL);
                            } else if (strcmp(pref_otr_log, "redact") == 0) {
                                chat_log_chat(jidp->barejid, recipient, "[redacted]", PROF_OUT_LOG, NULL);
                            }
                            prefs_free_string(pref_otr_log);
                            jid_destroy(jidp);
                        }

                        ui_outgoing_msg("me", recipient, tiny);
                    } else {
                        cons_show_error("Failed to send message.");
                    }
                } else {
                    message_send(tiny, recipient);
                    if (prefs_get_boolean(PREF_CHLOG)) {
                        const char *jid = jabber_get_fulljid();
                        Jid *jidp = jid_create(jid);
                        chat_log_chat(jidp->barejid, recipient, tiny, PROF_OUT_LOG, NULL);
                        jid_destroy(jidp);
                    }

                    ui_outgoing_msg("me", recipient, tiny);
                }
#else
                message_send(tiny, recipient);
                if (prefs_get_boolean(PREF_CHLOG)) {
                    const char *jid = jabber_get_fulljid();
                    Jid *jidp = jid_create(jid);
                    chat_log_chat(jidp->barejid, recipient, tiny, PROF_OUT_LOG, NULL);
                    jid_destroy(jidp);
                }

                ui_outgoing_msg("me", recipient, tiny);
#endif
            } else if (win_type == WIN_PRIVATE) {
                char *recipient = ui_current_recipient();
                message_send(tiny, recipient);
                ui_outgoing_msg("me", recipient, tiny);
            } else { // groupchat
                char *recipient = ui_current_recipient();
                message_send_groupchat(tiny, recipient);
            }
            free(tiny);
        } else {
            cons_show_error("Couldn't get tinyurl.");
        }
    } else {
        cons_show("/tiny can only be used in chat windows");
    }

    return TRUE;
}

gboolean
cmd_clear(gchar **args, struct cmd_help_t help)
{
    ui_clear_current();
    return TRUE;
}

gboolean
cmd_close(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();
    int index = 0;
    int count = 0;

    if (args[0] == NULL) {
        index = ui_current_win_index();
    } else if (strcmp(args[0], "all") == 0) {
        count = ui_close_all_wins();
        if (count == 0) {
            cons_show("No windows to close.");
        } else if (count == 1) {
            cons_show("Closed 1 window.");
        } else {
            cons_show("Closed %d windows.", count);
        }
        return TRUE;
    } else if (strcmp(args[0], "read") == 0) {
        count = ui_close_read_wins();
        if (count == 0) {
            cons_show("No windows to close.");
        } else if (count == 1) {
            cons_show("Closed 1 window.");
        } else {
            cons_show("Closed %d windows.", count);
        }
        return TRUE;
    } else {
        index = atoi(args[0]);
    }

    if (index < 0 || index == 10) {
        cons_show("No such window exists.");
        return TRUE;
    }

    if (index == 1) {
        cons_show("Cannot close console window.");
        return TRUE;
    }

    if (index == 0) {
        index = 10;
    }

    if (!ui_win_exists(index)) {
        cons_show("Window is not open.");
        return TRUE;
    }

    // handle leaving rooms, or chat
    if (conn_status == JABBER_CONNECTED) {
        ui_close_connected_win(index);
    }

    // close the window
    ui_close_win(index);
    cons_show("Closed window %d", index);

    return TRUE;
}

gboolean
cmd_leave(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();
    win_type_t win_type = ui_current_win_type();
    int index = ui_current_win_index();

    if (win_type != WIN_MUC) {
        cons_show("You can only use the /leave command in a chat room.");
        cons_alert();
        return TRUE;
    }

    // handle leaving rooms, or chat
    if (conn_status == JABBER_CONNECTED) {
        ui_close_connected_win(index);
    }

    // close the window
    ui_close_win(index);

    return TRUE;
}

gboolean
cmd_beep(gchar **args, struct cmd_help_t help)
{
    return _cmd_set_boolean_preference(args[0], help, "Sound", PREF_BEEP);
}

gboolean
cmd_states(gchar **args, struct cmd_help_t help)
{
    gboolean result = _cmd_set_boolean_preference(args[0], help, "Sending chat states",
        PREF_STATES);

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

    return result;
}

gboolean
cmd_titlebar(gchar **args, struct cmd_help_t help)
{
    if (g_strcmp0(args[0], "off") == 0) {
        ui_clear_win_title();
    }
    return _cmd_set_boolean_preference(args[0], help, "Titlebar", PREF_TITLEBAR);
}

gboolean
cmd_outtype(gchar **args, struct cmd_help_t help)
{
    gboolean result = _cmd_set_boolean_preference(args[0], help,
        "Sending typing notifications", PREF_OUTTYPE);

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

    return result;
}

gboolean
cmd_gone(gchar **args, struct cmd_help_t help)
{
    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(gchar **args, struct cmd_help_t help)
{
    char *kind = args[0];

    // bad kind
    if ((strcmp(kind, "message") != 0) && (strcmp(kind, "typing") != 0) &&
            (strcmp(kind, "remind") != 0) && (strcmp(kind, "invite") != 0) &&
            (strcmp(kind, "sub") != 0) && (strcmp(kind, "room") != 0)) {
        cons_show("Usage: %s", help.usage);

    // set message setting
    } else if (strcmp(kind, "message") == 0) {
        if (strcmp(args[1], "on") == 0) {
            cons_show("Message notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_MESSAGE, TRUE);
        } else if (strcmp(args[1], "off") == 0) {
            cons_show("Message notifications disabled.");
            prefs_set_boolean(PREF_NOTIFY_MESSAGE, FALSE);
        } else if (strcmp(args[1], "current") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Current window message notifications enabled.");
                prefs_set_boolean(PREF_NOTIFY_MESSAGE_CURRENT, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Current window message notifications disabled.");
                prefs_set_boolean(PREF_NOTIFY_MESSAGE_CURRENT, FALSE);
            } else {
                cons_show("Usage: /notify message current on|off");
            }
        } else if (strcmp(args[1], "text") == 0) {
            if (g_strcmp0(args[2], "on") == 0) {
                cons_show("Showing text in message notifications enabled.");
                prefs_set_boolean(PREF_NOTIFY_MESSAGE_TEXT, TRUE);
            } else if (g_strcmp0(args[2], "off") == 0) {
                cons_show("Showing text in message notifications disabled.");
                prefs_set_boolean(PREF_NOTIFY_MESSAGE_TEXT, FALSE);
            } else {
                cons_show("Usage: /notify message text on|off");
            }
        } else {
            cons_show("Usage: /notify message on|off");
        }

    // set room setting
    } else if (strcmp(kind, "room") == 0) {
        if (strcmp(args[1], "on") == 0) {
            cons_show("Chat room notifications enabled.");
            prefs_set_string(PREF_NOTIFY_ROOM, "on");
        } else if (strcmp(args[1], "off") == 0) {
            cons_show("Chat room notifications disabled.");
            prefs_set_string(PREF_NOTIFY_ROOM, "off");
        } else if (strcmp(args[1], "mention") == 0) {
            cons_show("Chat room notifications enabled on mention.");
            prefs_set_string(PREF_NOTIFY_ROOM, "mention");
        } else if (strcmp(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 (strcmp(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 {
            cons_show("Usage: /notify room on|off|mention");
        }

    // set typing setting
    } else if (strcmp(kind, "typing") == 0) {
        if (strcmp(args[1], "on") == 0) {
            cons_show("Typing notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_TYPING, TRUE);
        } else if (strcmp(args[1], "off") == 0) {
            cons_show("Typing notifications disabled.");
            prefs_set_boolean(PREF_NOTIFY_TYPING, FALSE);
        } else if (strcmp(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");
        }

    // set invite setting
    } else if (strcmp(kind, "invite") == 0) {
        if (strcmp(args[1], "on") == 0) {
            cons_show("Chat room invite notifications enabled.");
            prefs_set_boolean(PREF_NOTIFY_INVITE, TRUE);
        } else if (strcmp(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");
        }

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

    // set remind setting
    } else if (strcmp(kind, "remind") == 0) {
        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);
        }

    } else {
        cons_show("Unknown command: %s.", kind);
    }

    return TRUE;
}

gboolean
cmd_log(gchar **args, struct cmd_help_t help)
{
    char *subcmd = args[0];
    char *value = args[1];
    int intval;

    if (strcmp(subcmd, "maxsize") == 0) {
        if (value == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        }
        if (_strtoi(value, &intval, PREFS_MIN_LOG_SIZE, INT_MAX) == 0) {
            prefs_set_max_log_size(intval);
            cons_show("Log maxinum size set to %d bytes", intval);
        }
        return TRUE;
    }

    if (strcmp(subcmd, "rotate") == 0) {
        if (value == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        }
        return _cmd_set_boolean_preference(value, help, "Log rotate", PREF_LOG_ROTATE);
    }

    if (strcmp(subcmd, "shared") == 0) {
        if (value == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        }
        gboolean result = _cmd_set_boolean_preference(value, help, "Shared log", PREF_LOG_SHARED);
        log_reinit();
        return result;
    }

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

    cons_show("Usage: %s", help.usage);

    /* TODO: make 'level' subcommand for debug level */

    return TRUE;
}

gboolean
cmd_reconnect(gchar **args, struct cmd_help_t help)
{
    char *value = args[0];
    int intval;

    if (_strtoi(value, &intval, 0, INT_MAX) == 0) {
        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("Usage: %s", help.usage);
    }

    return TRUE;
}

gboolean
cmd_autoping(gchar **args, struct cmd_help_t help)
{
    char *value = args[0];
    int intval;

    if (_strtoi(value, &intval, 0, INT_MAX) == 0) {
        prefs_set_autoping(intval);
        iq_set_autoping(intval);
        if (intval == 0) {
            cons_show("Autoping disabled.", intval);
        } else {
            cons_show("Autoping interval set to %d seconds.", intval);
        }
    } else {
        cons_show("Usage: %s", help.usage);
    }

    return TRUE;
}

gboolean
cmd_autoaway(gchar **args, struct cmd_help_t help)
{
    char *setting = args[0];
    char *value = args[1];
    int minutesval;

    if ((strcmp(setting, "mode") != 0) && (strcmp(setting, "time") != 0) &&
            (strcmp(setting, "message") != 0) && (strcmp(setting, "check") != 0)) {
        cons_show("Setting must be one of 'mode', 'time', 'message' or 'check'");
        return TRUE;
    }

    if (strcmp(setting, "mode") == 0) {
        if ((strcmp(value, "idle") != 0) && (strcmp(value, "away") != 0) &&
                (strcmp(value, "off") != 0)) {
            cons_show("Mode must be one of 'idle', 'away' or 'off'");
        } else {
            prefs_set_string(PREF_AUTOAWAY_MODE, value);
            cons_show("Auto away mode set to: %s.", value);
        }

        return TRUE;
    }

    if (strcmp(setting, "time") == 0) {
        if (_strtoi(value, &minutesval, 1, INT_MAX) == 0) {
            prefs_set_autoaway_time(minutesval);
            cons_show("Auto away time set to: %d minutes.", minutesval);
        }

        return TRUE;
    }

    if (strcmp(setting, "message") == 0) {
        if (strcmp(value, "off") == 0) {
            prefs_set_string(PREF_AUTOAWAY_MESSAGE, NULL);
            cons_show("Auto away message cleared.");
        } else {
            prefs_set_string(PREF_AUTOAWAY_MESSAGE, value);
            cons_show("Auto away message set to: \"%s\".", value);
        }

        return TRUE;
    }

    if (strcmp(setting, "check") == 0) {
        return _cmd_set_boolean_preference(value, help, "Online check",
            PREF_AUTOAWAY_CHECK);
    }

    return TRUE;
}

gboolean
cmd_priority(gchar **args, struct cmd_help_t help)
{
    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

    char *value = args[0];
    int intval;

    if (_strtoi(value, &intval, -128, 127) == 0) {
        accounts_set_priority_all(jabber_get_account_name(), intval);
        resource_presence_t last_presence = accounts_get_last_presence(jabber_get_account_name());
        presence_update(last_presence, jabber_get_presence_message(), 0);
        cons_show("Priority set to %d.", intval);
    }

    return TRUE;
}

gboolean
cmd_statuses(gchar **args, struct cmd_help_t help)
{
    if (strcmp(args[0], "console") != 0 &&
            strcmp(args[0], "chat") != 0 &&
            strcmp(args[0], "muc") != 0) {
        cons_show("Usage: %s", help.usage);
        return TRUE;
    }

    if (strcmp(args[1], "all") != 0 &&
            strcmp(args[1], "online") != 0 &&
            strcmp(args[1], "none") != 0) {
        cons_show("Usage: %s", help.usage);
        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], "muc") == 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_vercheck(gchar **args, struct cmd_help_t help)
{
    int num_args = g_strv_length(args);

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

gboolean
cmd_xmlconsole(gchar **args, struct cmd_help_t help)
{
    if (!ui_xmlconsole_exists()) {
        ui_create_xmlconsole_win();
    } else {
        ui_open_xmlconsole_win();
    }

    return TRUE;
}

gboolean
cmd_flash(gchar **args, struct cmd_help_t help)
{
    return _cmd_set_boolean_preference(args[0], help,
        "Screen flash", PREF_FLASH);
}

gboolean
cmd_intype(gchar **args, struct cmd_help_t help)
{
    return _cmd_set_boolean_preference(args[0], help,
        "Show contact typing", PREF_INTYPE);
}

gboolean
cmd_splash(gchar **args, struct cmd_help_t help)
{
    return _cmd_set_boolean_preference(args[0], help,
        "Splash screen", PREF_SPLASH);
}

gboolean
cmd_autoconnect(gchar **args, struct cmd_help_t help)
{
    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) {
        prefs_set_string(PREF_CONNECT_ACCOUNT, args[1]);
        cons_show("Autoconnect account set to: %s.", args[1]);
    } else {
        cons_show("Usage: %s", help.usage);
    }
    return true;
}

gboolean
cmd_chlog(gchar **args, struct cmd_help_t help)
{
    gboolean result = _cmd_set_boolean_preference(args[0], help,
        "Chat logging", PREF_CHLOG);

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

    return result;
}

gboolean
cmd_grlog(gchar **args, struct cmd_help_t help)
{
    gboolean result = _cmd_set_boolean_preference(args[0], help,
        "Groupchat logging", PREF_GRLOG);

    return result;
}

gboolean
cmd_mouse(gchar **args, struct cmd_help_t help)
{
    return _cmd_set_boolean_preference(args[0], help,
        "Mouse handling", PREF_MOUSE);
}

gboolean
cmd_history(gchar **args, struct cmd_help_t help)
{
    gboolean result = _cmd_set_boolean_preference(args[0], help,
        "Chat history", PREF_HISTORY);

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

    return result;
}

gboolean
cmd_away(gchar **args, struct cmd_help_t help)
{
    _update_presence(RESOURCE_AWAY, "away", args);
    return TRUE;
}

gboolean
cmd_online(gchar **args, struct cmd_help_t help)
{
    _update_presence(RESOURCE_ONLINE, "online", args);
    return TRUE;
}

gboolean
cmd_dnd(gchar **args, struct cmd_help_t help)
{
    _update_presence(RESOURCE_DND, "dnd", args);
    return TRUE;
}

gboolean
cmd_chat(gchar **args, struct cmd_help_t help)
{
    _update_presence(RESOURCE_CHAT, "chat", args);
    return TRUE;
}

gboolean
cmd_xa(gchar **args, struct cmd_help_t help)
{
    _update_presence(RESOURCE_XA, "xa", args);
    return TRUE;
}

gboolean
cmd_otr(gchar **args, struct cmd_help_t help)
{
#ifdef HAVE_LIBOTR
    if (args[0] == NULL) {
        cons_show("Usage: %s", help.usage);
        return TRUE;
    }

    if (strcmp(args[0], "log") == 0) {
        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 '/chlog 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 '/chlog on' to enable.");
            }
        } else {
            cons_show("Usage: %s", help.usage);
        }
        return TRUE;

    } else if (strcmp(args[0], "warn") == 0) {
        gboolean result =  _cmd_set_boolean_preference(args[1], help,
            "OTR warning message", PREF_OTR_WARN);
        return result;

    } else if (strcmp(args[0], "libver") == 0) {
        char *version = otr_libotr_version();
        cons_show("Using libotr version %s", version);
        return TRUE;

    } else if (strcmp(args[0], "policy") == 0) {
        if (args[1] == NULL) {
            char *policy = prefs_get_string(PREF_OTR_POLICY);
            cons_show("OTR policy is now set to: %s", policy);
            prefs_free_string(policy);
            return TRUE;
        }

        char *choice = args[1];
        if ((g_strcmp0(choice, "manual") != 0) &&
                (g_strcmp0(choice, "opportunistic") != 0) &&
                (g_strcmp0(choice, "always") != 0)) {
            cons_show("OTR policy can be set to: manual, opportunistic or always.");
            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;
        } else {
            if (jabber_get_connection_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(jabber_get_account_name(), contact_jid, choice);
            cons_show("OTR policy for %s set to: %s", contact_jid, choice);
            return TRUE;
        }
    }

    if (jabber_get_connection_status() != JABBER_CONNECTED) {
        cons_show("You must be connected with an account to load OTR information.");
        return TRUE;
    }

    if (strcmp(args[0], "gen") == 0) {
        ProfAccount *account = accounts_get_account(jabber_get_account_name());
        otr_keygen(account);
        account_free(account);
        return TRUE;

    } else if (strcmp(args[0], "myfp") == 0) {
        if (!otr_key_loaded()) {
            ui_current_print_formatted_line('!', 0, "You have not generated or loaded a private key, use '/otr gen'");
        } else {
            char *fingerprint = otr_get_my_fingerprint();
            ui_current_print_formatted_line('!', 0, "Your OTR fingerprint: %s", fingerprint);
            free(fingerprint);
        }
        return TRUE;

    } else if (strcmp(args[0], "theirfp") == 0) {
        win_type_t win_type = ui_current_win_type();

        if (win_type != WIN_CHAT) {
            ui_current_print_line("You must be in a regular chat window to view a recipient's fingerprint.");
        } else if (!ui_current_win_is_otr()) {
            ui_current_print_formatted_line('!', 0, "You are not currently in an OTR session.");
        } else {
            char *recipient = ui_current_recipient();
            char *fingerprint = otr_get_their_fingerprint(recipient);
            ui_current_print_formatted_line('!', 0, "%s's OTR fingerprint: %s", recipient, fingerprint);
            free(fingerprint);
        }
        return TRUE;

    } else if (strcmp(args[0], "start") == 0) {
        if (args[1] != NULL) {
            char *contact = args[1];
            char *barejid = roster_barejid_from_name(contact);
            if (barejid == NULL) {
                barejid = contact;
            }

            if (prefs_get_boolean(PREF_STATES)) {
                if (!chat_session_exists(barejid)) {
                    chat_session_start(barejid, TRUE);
                }
            }

            ui_new_chat_win(barejid);

            if (ui_current_win_is_otr()) {
                ui_current_print_formatted_line('!', 0, "You are already in an OTR session.");
            } else {
                if (!otr_key_loaded()) {
                    ui_current_print_formatted_line('!', 0, "You have not generated or loaded a private key, use '/otr gen'");
                } else if (!otr_is_secure(barejid)) {
                    char *otr_query_message = otr_start_query();
                    message_send(otr_query_message, barejid);
                } else {
                    ui_gone_secure(barejid, otr_is_trusted(barejid));
                }
            }
        } else {
            win_type_t win_type = ui_current_win_type();

            if (win_type != WIN_CHAT) {
                ui_current_print_line("You must be in a regular chat window to start an OTR session.");
            } else if (ui_current_win_is_otr()) {
                ui_current_print_formatted_line('!', 0, "You are already in an OTR session.");
            } else {
                if (!otr_key_loaded()) {
                    ui_current_print_formatted_line('!', 0, "You have not generated or loaded a private key, use '/otr gen'");
                } else {
                    char *recipient = ui_current_recipient();
                    char *otr_query_message = otr_start_query();
                    message_send(otr_query_message, recipient);
                }
            }
        }
        return TRUE;

    } else if (strcmp(args[0], "end") == 0) {
        win_type_t win_type = ui_current_win_type();

        if (win_type != WIN_CHAT) {
            ui_current_print_line("You must be in a regular chat window to use OTR.");
        } else if (!ui_current_win_is_otr()) {
            ui_current_print_formatted_line('!', 0, "You are not currently in an OTR session.");
        } else {
            char *recipient = ui_current_recipient();
            ui_gone_insecure(recipient);
            otr_end_session(recipient);
        }
        return TRUE;

    } else if (strcmp(args[0], "trust") == 0) {
        win_type_t win_type = ui_current_win_type();

        if (win_type != WIN_CHAT) {
            ui_current_print_line("You must be in an OTR session to trust a recipient.");
        } else if (!ui_current_win_is_otr()) {
            ui_current_print_formatted_line('!', 0, "You are not currently in an OTR session.");
        } else {
            char *recipient = ui_current_recipient();
            ui_trust(recipient);
            otr_trust(recipient);
        }
        return TRUE;

    } else if (strcmp(args[0], "untrust") == 0) {
        win_type_t win_type = ui_current_win_type();

        if (win_type != WIN_CHAT) {
            ui_current_print_line("You must be in an OTR session to untrust a recipient.");
        } else if (!ui_current_win_is_otr()) {
            ui_current_print_formatted_line('!', 0, "You are not currently in an OTR session.");
        } else {
            char *recipient = ui_current_recipient();
            ui_untrust(recipient);
            otr_untrust(recipient);
        }
        return TRUE;

    } else if (strcmp(args[0], "secret") == 0) {
        win_type_t win_type = ui_current_win_type();
        if (win_type != WIN_CHAT) {
            ui_current_print_line("You must be in an OTR session to trust a recipient.");
        } else if (!ui_current_win_is_otr()) {
            ui_current_print_formatted_line('!', 0, "You are not currently in an OTR session.");
        } else {
            char *secret = args[1];
            if (secret == NULL) {
                cons_show("Usage: %s", help.usage);
            } else {
                char *recipient = ui_current_recipient();
                otr_smp_secret(recipient, secret);
            }
        }
        return TRUE;

    } else if (strcmp(args[0], "question") == 0) {
        char *question = args[1];
        char *answer = args[2];

        if (question == NULL || answer == NULL) {
            cons_show("Usage: %s", help.usage);
            return TRUE;
        } else {
            win_type_t win_type = ui_current_win_type();
            if (win_type != WIN_CHAT) {
                ui_current_print_line("You must be in an OTR session to trust a recipient.");
            } else if (!ui_current_win_is_otr()) {
                ui_current_print_formatted_line('!', 0, "You are not currently in an OTR session.");
            } else {
                char *recipient = ui_current_recipient();
                otr_smp_question(recipient, question, answer);
            }
            return TRUE;
        }

    } else if (strcmp(args[0], "answer") == 0) {
        win_type_t win_type = ui_current_win_type();
        if (win_type != WIN_CHAT) {
            ui_current_print_line("You must be in an OTR session to trust a recipient.");
        } else if (!ui_current_win_is_otr()) {
            ui_current_print_formatted_line('!', 0, "You are not currently in an OTR session.");
        } else {
            char *answer = args[1];
            if (answer == NULL) {
                cons_show("Usage: %s", help.usage);
            } else {
                char *recipient = ui_current_recipient();
                otr_smp_answer(recipient, answer);
            }
        }
        return TRUE;

    } else {
        cons_show("Usage: %s", help.usage);
        return TRUE;
    }
#else
    cons_show("This version of Profanity has not been built with OTR support enabled");
    return TRUE;
#endif
}

// 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 (num_args == 1) {
        msg = args[0];
    }

    jabber_conn_status_t conn_status = jabber_get_connection_status();

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

// helper function for boolean preference commands
static gboolean
_cmd_set_boolean_preference(gchar *arg, struct cmd_help_t help,
    const char * const display, preference_t pref)
{
    GString *enabled = g_string_new(display);
    g_string_append(enabled, " enabled.");

    GString *disabled = g_string_new(display);
    g_string_append(disabled, " disabled.");

    if (arg == NULL) {
        char usage[strlen(help.usage) + 8];
        sprintf(usage, "Usage: %s", help.usage);
        cons_show(usage);
    } else if (strcmp(arg, "on") == 0) {
        cons_show(enabled->str);
        prefs_set_boolean(pref, TRUE);
    } else if (strcmp(arg, "off") == 0) {
        cons_show(disabled->str);
        prefs_set_boolean(pref, FALSE);
    } else {
        char usage[strlen(help.usage) + 8];
        sprintf(usage, "Usage: %s", help.usage);
        cons_show(usage);
    }

    g_string_free(enabled, TRUE);
    g_string_free(disabled, TRUE);

    return TRUE;
}

static int
_strtoi(char *str, int *saveptr, int min, int max)
{
    char *ptr;
    int val;

    errno = 0;
    val = (int)strtol(str, &ptr, 0);
    if (errno != 0 || *str == '\0' || *ptr != '\0') {
        cons_show("Could not convert \"%s\" to a number.", str);
        return -1;
    } else if (val < min || val > max) {
        cons_show("Value %s out of range. Must be in %d..%d.", str, min, max);
        return -1;
    }

    *saveptr = val;

    return 0;
}

static void
_cmd_show_filtered_help(char *heading, gchar *cmd_filter[], int filter_size)
{
    cons_show("");
    cons_show("%s", heading);
    cons_show("");

    GList *ordered_commands = NULL;
    int i;
    for (i = 0; i < filter_size; i++) {
        Command *cmd = g_hash_table_lookup(commands, cmd_filter[i]);
        ordered_commands = g_list_insert_sorted(ordered_commands, cmd, (GCompareFunc)_compare_commands);
    }

    GList *curr = ordered_commands;
    while (curr != NULL) {
        Command *cmd = curr->data;
        cons_show("%-12s: %s", cmd->cmd, cmd->help.short_help);
        curr = g_list_next(curr);
    }
    g_list_free(ordered_commands);
    g_list_free(curr);

    cons_show("");
    cons_show("Use /help [command] without the leading slash, for help on a specific command");
    cons_show("");
}

static
gint _compare_commands(Command *a, Command *b)
{
    const char * utf8_str_a = a->cmd;
    const char * utf8_str_b = b->cmd;

    gchar *key_a = g_utf8_collate_key(utf8_str_a, -1);
    gchar *key_b = g_utf8_collate_key(utf8_str_b, -1);

    gint result = g_strcmp0(key_a, key_b);

    g_free(key_a);
    g_free(key_b);

    return result;
}