summaryrefslogtreecommitdiffstats
path: root/src/userintf.cpp
blob: 0814bcbb6127eaa09b5aa0548ebdec8437fe2193 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
/*
    Copyright (C) 2005-2009  Michel de Boer <michel@twinklephone.com>

    This program 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 2 of the License, or
    (at your option) any later version.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <iostream>
#include <cstdlib>
#include <readline/readline.h>
#include <readline/history.h>
#include "address_book.h"
#include "events.h"
#include "line.h"
#include "log.h"
#include "sys_settings.h"
#include "translator.h"
#include "userintf.h"
#include "util.h"
#include "user.h"
#include "audio/rtp_telephone_event.h"
#include "parser/parse_ctrl.h"
#include "sockets/interfaces.h"
#include "audits/memman.h"
#include "utils/file_utils.h"
#include "utils/mime_database.h"

#define CLI_PROMPT              "Twinkle> "
#define CLI_MAX_HISTORY_LENGTH	1000

extern string user_host;
extern t_event_queue *evq_trans_layer;

using namespace utils;



////////////////////////
// GNU Readline helpers
////////////////////////

char ** tw_completion (const char *text, int start, int end);
char * tw_command_generator (const char *text, int state);

char ** tw_completion (const char *text, int start, int end)
{
	char **matches;
	matches = (char **)NULL;
	if (start == 0)
		matches = rl_completion_matches (text, tw_command_generator);
	return (matches);
}



char * tw_command_generator (const char *text, int state)
{
	static int len;
	static list<string>::const_iterator i;

	if (!state){
		len = strlen(text);
		i = ui->get_all_commands().begin();
	}

	for (; i != ui->get_all_commands().end(); i++){
		const char * s = i->c_str();
		//cout << s << endl;
		if ( s && strncmp(s, text, len) == 0  ){
			i++;
			return strdup(s);
		}
	}

	/* If no names matched, then return NULL. */
	return ((char *)NULL);
}

char *tw_readline(const char *prompt)
{
	static char *line = NULL;
	
	if (!line) {
		free(line);
		line = NULL;
	}
	
	line = readline(prompt);
	
	if (line && *line) {
		add_history(line);
	}
	
	return line;
}

/////////////////////////////
// Private
/////////////////////////////

string t_userintf::expand_destination(t_user *user_config, const string &dst, const string &scheme) {
	assert(user_config);
	
	string s = dst;

	// Apply number conversion rules if applicable
	// Add domain if it is missing from a sip-uri
	if (s.find('@') == string::npos) {
		bool is_tel_uri = (s.substr(0, 4) == "tel:");
		
		// Strip tel-scheme
		if (is_tel_uri) s = s.substr(4);
	
		// Remove white space
		s = remove_white_space(s);
	
		// Remove special phone symbols
		if (user_config->get_remove_special_phone_symbols() &&
		    looks_like_phone(s, user_config->get_special_phone_symbols())) 
		{
			s = remove_symbols(s, user_config->get_special_phone_symbols());
		}
		
		// Convert number according to the number conversion rules
		s = user_config->convert_number(s);
			
		if (is_tel_uri) {
			// Add tel-scheme again.
			s = "tel:" + s;
		} else if (s.substr(0, 4) != "sip:" &&
		           (user_config->get_use_tel_uri_for_phone() || scheme == "tel") &&
		           user_config->get_numerical_user_is_phone() &&
		           looks_like_phone(s, user_config->get_special_phone_symbols()))
		{
			// Add tel-scheme if a telephone number must be expanded
		        // to a tel-uri according to user profile settings.
			s = "tel:" + s;
		} else {
			// Add domain
			s += '@';
			s += user_config->get_domain();
		}
	}
	
	// Add sip-scheme if a scheme is missing
	if (s.substr(0, 4) != "sip:" && s.substr(0, 4) != "tel:") {
		s = "sip:" + s;
	}

	// RFC 3261 19.1.1
	// Add user=phone for telehpone numbers in a SIP-URI
	// If the SIP-URI contains a telephone number it SHOULD contain
	// the user=phone parameter.
	if (user_config->get_numerical_user_is_phone() && s.substr(0, 4) == "sip:") {
		t_url u(s);
		if (u.get_user_param().empty() && 
		    u.user_looks_like_phone(user_config->get_special_phone_symbols())) {
			s += ";user=phone";
		}
	}

	return s;
}

void t_userintf::expand_destination(t_user *user_config, 
		const string &dst, string &display, string &dst_url) 
{
	display.clear();
	dst_url.clear();
		
	if (dst.empty()) {
		return;
	}
	
	// If there is a display name then the url part is between angle
	// brackets.
	if (dst[dst.size() - 1] != '>') {
		dst_url = expand_destination(user_config, dst);
		return;
	}
	
	// Find start of url
	string::size_type i = dst.rfind('<');
	if (i == string::npos) {
		// It seems the string is invalid.
		return;
	}
	
	dst_url = expand_destination(user_config, dst.substr(i + 1, dst.size() - i - 2));
	
	if (i > 0) {
		display = unquote(trim(dst.substr(0, i)));
	}
}

void t_userintf::expand_destination(t_user *user_config, 
		const string &dst, t_display_url &display_url) 
{
	string url_str;
	
	expand_destination(user_config, dst, display_url.display, url_str);
	display_url.url.set_url(url_str);
}

void t_userintf::expand_destination(t_user *user_config,
		const string &dst, t_display_url &display_url, string &subject,
		string &dst_no_headers)
{
	string headers;
	dst_no_headers = dst;
	t_url u(dst);	
	
	// Split headers from URI
	if (u.is_valid()) {
		// destination is a valid URI. Strip off the headers if any
		headers = u.get_headers();
		
		// Cut off headers
		// Note that a separator (?) will be in front of the 
		// headers string
		if (!headers.empty()) {
			string::size_type i = dst.find(headers);
			if (i != string::npos) {
				dst_no_headers = dst.substr(0, i - 1);
			}
		}
		
		expand_destination(user_config, dst_no_headers, display_url);
	} else {
		// destination may be a short URI.
		// Split at a '?' to find any headers.
		// NOTE: this is not fool proof. A user name may contain a '?'
		vector<string> l = split_on_first(dst, '?');
		dst_no_headers = l[0];
		expand_destination(user_config, dst_no_headers, display_url);
		if (display_url.is_valid() && l.size() == 2) {
			headers = l[1];
		}
	}
	
	// Parse headers to find subject header
	subject.clear();
	if (!headers.empty()) {
		try {
			list<string> parse_errors;
			t_sip_message *m = t_parser::parse_headers(headers, parse_errors);
			if (m->hdr_subject.is_populated()) {
				subject = m->hdr_subject.subject;
			}
			MEMMAN_DELETE(m);
			delete m;
		} catch (int) {
			// ignore invalid headers
		}
	}
}

bool t_userintf::parse_args(const list<string> command_list,
                            list<t_command_arg> &al)
{
	t_command_arg	arg;
	bool parsed_flag = false;

	al.clear();
	arg.flag = 0;
	arg.value = "";

	for (list<string>::const_iterator i = command_list.begin();
	     i != command_list.end(); i++)
	{
		if (i == command_list.begin()) continue;

		const string &s = *i;
		if (s[0] == '-') {
			if (s.size() == 1) return false;
			if (parsed_flag) al.push_back(arg);

			arg.flag = s[1];

			if (s.size() > 2) {
				arg.value = unquote(s.substr(2));
				al.push_back(arg);
				arg.flag = 0;
				arg.value = "";
				parsed_flag = false;
			} else {
				arg.value = "";
				parsed_flag = true;
			}
		} else {
			if (parsed_flag) {
				arg.value = unquote(s);
			} else {
				arg.flag = 0;
				arg.value = unquote(s);
			}

			al.push_back(arg);
			parsed_flag = false;
			arg.flag = 0;
			arg.value = "";
		}
	}

	// Last parsed argument was a flag only
	if (parsed_flag) al.push_back(arg);

	return true;
}

bool t_userintf::exec_invite(const list<string> command_list, bool immediate) {
	list<t_command_arg> al;
	string display;
	string subject;
	string destination;
	bool hide_user = false;

	if (!parse_args(command_list, al)) {
		exec_command("help call");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 'd':
			display = i->value;
			break;
		case 's':
			subject = i->value;
			break;
		case 'h':
			hide_user = true;
			break;
		case 0:
			destination = i->value;
			break;
		default:
			exec_command("help call");
			return false;
			break;
		}
	}

	return do_invite(destination, display, subject, immediate, hide_user);
}

bool t_userintf::do_invite(const string &destination, const string &display,
		const string &subject, bool immediate, bool anonymous)
{
	t_url dest_url(expand_destination(active_user, destination));
	
	if (!dest_url.is_valid()) {
		exec_command("help call");
		return false;
	}

	t_url vm_url(expand_destination(active_user, active_user->get_mwi_vm_address()));
	if (dest_url != vm_url) {
		// Keep call information for redial
		last_called_url = dest_url;
		last_called_display = display;
		last_called_subject = subject;
		last_called_profile = active_user->get_profile_name();
		last_called_hide_user = anonymous;
	}

	phone->pub_invite(active_user, dest_url, display, subject, anonymous);
	return true;
}

bool t_userintf::exec_redial(const list<string> command_list) {
	if (can_redial()) {
		do_redial();
		return true;
	}
	
	return false;
}

void t_userintf::do_redial(void) {
	t_user *user_config = phone->ref_user_profile(last_called_profile);
	phone->pub_invite(user_config, last_called_url, last_called_display,
		last_called_subject, last_called_hide_user);
}

bool t_userintf::exec_answer(const list<string> command_list) {
	do_answer();
	return true;
}

void t_userintf::do_answer(void) {
	cb_stop_call_notification(phone->get_active_line());
	phone->pub_answer();
}

bool t_userintf::exec_answerbye(const list<string> command_list) {
	do_answerbye();
	return true;
}

void t_userintf::do_answerbye(void) {
	unsigned short line = phone->get_active_line();
	
	switch (phone->get_line_substate(line)) {
	case LSSUB_INCOMING_PROGRESS:
		do_answer();
		break;
	case LSSUB_OUTGOING_PROGRESS:
	case LSSUB_ESTABLISHED:
		do_bye();
		break;
	default:
		break;
	}
}

bool t_userintf::exec_reject(const list<string> command_list) {
	do_reject();
	return true;
}

void t_userintf::do_reject(void) {
	cb_stop_call_notification(phone->get_active_line());
	phone->pub_reject();
	cout << endl;
	cout << "Line " << phone->get_active_line() + 1 << ": call rejected.\n";
	cout << endl;
}

bool t_userintf::exec_redirect(const list<string> command_list, bool immediate) {
	list<t_command_arg> al;
	list<string> dest_list;
	int num_redirections = 0;
	bool show_status = false;
	bool action_present = false;
	bool enable = true;
	bool type_present = false;
	t_cf_type cf_type = CF_ALWAYS;

	if (!parse_args(command_list, al)) {
		exec_command("help redirect");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 's':
			show_status = true;
			break;
		case 't':
			if (i->value == "always") {
				cf_type = CF_ALWAYS;
			} else if (i->value == "busy") {
				cf_type = CF_BUSY;
			} else if (i->value == "noanswer") {
				cf_type = CF_NOANSWER;
			} else {
				exec_command("help redirect");
				return false;
			}

			type_present = true;
			break;
		case 'a':
			if (i->value == "on") {
				enable = true;
			} else if (i->value == "off") {
				enable = false;
			} else {
				exec_command("help redirect");
				return false;
			}

			action_present = true;
			break;
		case 0:
			dest_list.push_back(i->value);
			num_redirections++;
			break;
		default:
			exec_command("help redirect");
			return false;
			break;
		}
	}

	if (type_present && enable && (num_redirections == 0 || num_redirections > 5)) {
		exec_command("help redirect");
		return false;
	}
	
	if (!type_present && action_present && enable) { 
		exec_command("help redirect");
		return false;
	}
	
	if (!type_present && !action_present && 
	    (num_redirections == 0 || num_redirections > 5)) 
	{
		exec_command("help redirect");
		return false;
	}
		
	do_redirect(show_status, type_present, cf_type, action_present, enable,
			num_redirections, dest_list, immediate);
	return true;
}

void t_userintf::do_redirect(bool show_status, bool type_present, t_cf_type cf_type, 
		bool action_present, bool enable, int num_redirections,
		const list<string> &dest_strlist, bool immediate)
{
	list<t_display_url> dest_list;
	for (list<string>::const_iterator i = dest_strlist.begin();
	     i != dest_strlist.end(); i++)
	{
		t_display_url du;
		du.url = expand_destination(active_user, *i);
		du.display.clear();
		if (!du.is_valid()) return;
		dest_list.push_back(du);
	}

	if (show_status) {
		list<t_display_url> cf_dest; // call forwarding destinations

		cout << endl;

		cout << "Redirect always: ";
		if (phone->ref_service(active_user)->get_cf_active(CF_ALWAYS, cf_dest)) {
			for (list<t_display_url>::iterator i = cf_dest.begin();
			     i != cf_dest.end(); i++)
			{
				if (i != cf_dest.begin()) cout << ", ";
				cout << i->encode();
			}
		} else {
			cout << "not active";
		}
		cout << endl;

		cout << "Redirect busy: ";
		if (phone->ref_service(active_user)->get_cf_active(CF_BUSY, cf_dest)) {
			for (list<t_display_url>::iterator i = cf_dest.begin();
			     i != cf_dest.end(); i++)
			{
				if (i != cf_dest.begin()) cout << ", ";
				cout << i->encode();
			}
		} else {
			cout << "not active";
		}
		cout << endl;

		cout << "Redirect noanswer: ";
		if (phone->ref_service(active_user)->get_cf_active(CF_NOANSWER, cf_dest)) {
			for (list<t_display_url>::iterator i = cf_dest.begin();
			     i != cf_dest.end(); i++)
			{
				if (i != cf_dest.begin()) cout << ", ";
				cout << i->encode();
			}
		} else {
			cout << "not active";
		}
		cout << endl;

		cout << endl;
		return;
	}

	// Enable/disable permanent redirections
	if (type_present) {
		if (enable) {
			phone->ref_service(active_user)->enable_cf(cf_type, dest_list);
			cout << "Redirection enabled.\n\n";
		} else {
			phone->ref_service(active_user)->disable_cf(cf_type);
			cout << "Redirection disabled.\n\n";
		}
		
		return;
	} else {
		if (action_present) {
			if (!enable) {
				phone->ref_service(active_user)->disable_cf(CF_ALWAYS);
				phone->ref_service(active_user)->disable_cf(CF_BUSY);
				phone->ref_service(active_user)->disable_cf(CF_NOANSWER);
				cout << "All redirections disabled.\n\n";
				return;
			}
			
			return;
		}
	}

	// Redirect current call
	cb_stop_call_notification(phone->get_active_line());
	phone->pub_redirect(dest_list, 302);
	cout << endl;
	cout << "Line " << phone->get_active_line() + 1 << ": call redirected.\n";
	cout << endl;
}

bool t_userintf::exec_dnd(const list<string> command_list) {
	list<t_command_arg> al;
	bool show_status = false;
	bool toggle = true;
	bool enable = false;

	if (!parse_args(command_list, al)) {
		exec_command("help dnd");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 's':
			show_status = true;
			break;
		case 'a':
			if (i->value == "on") {
				enable = true;
			} else if (i->value == "off") {
				enable = false;
			} else {
				exec_command("help dnd");
				return false;
			}
			toggle = false;
			break;
		default:
			exec_command("help dnd");
			return false;
			break;
		}
	}
	
	do_dnd(show_status, toggle, enable);
	return true;
}

void t_userintf::do_dnd(bool show_status, bool toggle, bool enable) {
	if (show_status) {
		cout << endl;
		cout << "Do not disturb: ";
		if (phone->ref_service(active_user)->is_dnd_active()) {
			cout << "active";
		} else {
			cout << "not active";
		}
		cout << endl;
		return;
	}
	
	if (toggle) {
		enable = !phone->ref_service(active_user)->is_dnd_active();
	}

	if (enable) {
		phone->ref_service(active_user)->enable_dnd();
		cout << "Do not disturb enabled.\n\n";
		return;
	} else {
		phone->ref_service(active_user)->disable_dnd();
		cout << "Do not disturb disabled.\n\n";
		return;
	}
}

bool t_userintf::exec_auto_answer(const list<string> command_list) {
	list<t_command_arg> al;
	bool show_status = false;
	bool toggle = true;
	bool enable = false;

	if (!parse_args(command_list, al)) {
		exec_command("help auto_answer");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 's':
			show_status = true;
			break;
		case 'a':
			if (i->value == "on") {
				enable = true;
			} else if (i->value == "off") {
				enable = false;
			} else {
				exec_command("help auto_answer");
				return false;
			}
			toggle = false;
			break;
		default:
			exec_command("help auto_answer");
			return false;
			break;
		}
	}
	
	do_auto_answer(show_status, toggle, enable);
	return true;
}

void t_userintf::do_auto_answer(bool show_status, bool toggle, bool enable) {
	if (show_status) {
		cout << endl;
		cout << "Auto answer: ";
		if (phone->ref_service(active_user)->is_auto_answer_active()) {
			cout << "active";
		} else {
			cout << "not active";
		}
		cout << endl;
		return;
	}
	
	if (toggle) {
		enable = !phone->ref_service(active_user)->is_auto_answer_active();
	}

	if (enable) {
		phone->ref_service(active_user)->enable_auto_answer(true);
		cout << "Auto answer enabled.\n\n";
		return;
	} else {
		phone->ref_service(active_user)->enable_auto_answer(false);
		cout << "Auto answer disabled.\n\n";
		return;
	}
}

bool t_userintf::exec_bye(const list<string> command_list) {
	do_bye();
	return true;
}

void t_userintf::do_bye(void) {
	phone->pub_end_call();
}

bool t_userintf::exec_hold(const list<string> command_list) {
	do_hold();
	return true;
}

void t_userintf::do_hold(void) {
	phone->pub_hold();
}

bool t_userintf::exec_retrieve(const list<string> command_list) {
	do_retrieve();
	return true;
}

void t_userintf::do_retrieve(void) {
	phone->pub_retrieve();
}

bool t_userintf::exec_refer(const list<string> command_list, bool immediate) {
	list<t_command_arg> al;
	string destination;
	bool dest_set = false;
	t_transfer_type transfer_type = TRANSFER_BASIC;

	if (!parse_args(command_list, al)) {
		exec_command("help transfer");
		return false;
	}
	
	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 'c':
			if (transfer_type != TRANSFER_BASIC) {
				exec_command("help transfer");
				return false;
			}
			transfer_type = TRANSFER_CONSULT;
			if (!i->value.empty()) {
				destination = i->value;
				dest_set = true;
			}
			break;
		case 'l':
			if (transfer_type != TRANSFER_BASIC) {
				exec_command("help transfer");
				return false;
			}
			transfer_type = TRANSFER_OTHER_LINE;
			break;
		case 0:
			destination = i->value;
			dest_set = true;
			break;
		default:
			exec_command("help transfer");
			return false;
			break;
		}
	}

	if (!dest_set && transfer_type == TRANSFER_BASIC) {
		exec_command("help transfer");
		return false;
	}

	return do_refer(destination, transfer_type, immediate);
}

bool t_userintf::do_refer(const string &destination, t_transfer_type transfer_type, 
		bool immediate) 
{
	t_url dest_url;
	
	if (transfer_type == TRANSFER_BASIC || 
	    (transfer_type == TRANSFER_CONSULT && !destination.empty())) 
	{
		dest_url.set_url(expand_destination(active_user, destination));
	
		if (!dest_url.is_valid()) {
			exec_command("help transfer");
			return false;
		}
	}
	
	unsigned short active_line;
	unsigned short other_line;
	unsigned short line_to_be_transferred;
	
	switch (transfer_type) {
	case TRANSFER_BASIC:
		phone->pub_refer(dest_url, "");
		break;
	case TRANSFER_CONSULT:
		if (destination.empty()) {
			active_line = phone->get_active_line();
			if (!phone->is_line_transfer_consult(active_line,
					line_to_be_transferred)) 
			{
				// There is no call to transfer
				return false;
			}
			phone->pub_refer(line_to_be_transferred, active_line);
		} else {
			phone->pub_setup_consultation_call(dest_url, "");
		}
		break;
	case TRANSFER_OTHER_LINE:
		active_line = phone->get_active_line();
		other_line = (active_line == 0 ? 1 : 0);
		phone->pub_refer(active_line, other_line);
		break;
	}
	
	return true;
}


bool t_userintf::exec_conference(const list<string> command_list) {
	do_conference();
	return true;
}

void t_userintf::do_conference(void) {
	if (phone->join_3way(0, 1)) {
		cout << endl;
		cout << "Started 3-way conference.\n";
		cout << endl;
	} else {
		cout << endl;
		cout << "Failed to start 3-way conference.\n";
		cout << endl;
	}
}

bool t_userintf::exec_mute(const list<string> command_list) {
	list<t_command_arg> al;
	bool show_status = false;
	bool toggle = true;
	bool enable = true;

	if (!parse_args(command_list, al)) {
		exec_command("help mute");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 's':
			show_status = true;
			break;
		case 'a':
			if (i->value == "on") {
				enable = true;
			} else if (i->value == "off") {
				enable = false;
			} else {
				exec_command("help mute");
				return false;
			}
			toggle = false;
			break;
		default:
			exec_command("help mute");
			return false;
			break;
		}
	}
	
	do_mute(show_status, toggle, enable);
	return true;
}

void t_userintf::do_mute(bool show_status, bool toggle, bool enable) {
	if (show_status) {
		cout << endl;
		cout << "Line is ";
		if (phone->is_line_muted(phone->get_active_line())) {
			cout << "muted.";
		} else {
			cout << "not muted.";
		}
		cout << endl;
		return;
	}

	if (toggle) enable = !phone->is_line_muted(phone->get_active_line());
	if (enable) {
		phone->mute(enable);
		cout << "Line muted.\n\n";
		return;
	} else {
		phone->mute(enable);
		cout << "Line unmuted.\n\n";
		return;
	}
}

bool t_userintf::exec_dtmf(const list<string> command_list) {
	list<t_command_arg> al;
	string digits;
	bool raw_mode = false;

	if (phone->get_line_state(phone->get_active_line()) == LS_IDLE) {
		return false;
	}

	if (!parse_args(command_list, al)) {
		exec_command("help dtmf");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 'r':
			raw_mode = true;
			if (!i->value.empty()) digits = i->value;
			break;
		case 0:
			digits = i->value;
			break;
		default:
			exec_command("help dtmf");
			return false;
			break;
		}
	}

	if (!raw_mode) {
		digits = str2dtmf(digits);
	}
	
	if (digits == "") {
		exec_command("help dtmf");
		return false;
	}

	do_dtmf(digits);
	return true;
}

void t_userintf::do_dtmf(const string &digits) {
	const t_call_info call_info = phone->get_call_info(phone->get_active_line());
	throttle_dtmf_not_supported = false;
	
	if (!call_info.dtmf_supported) return;
	
	for (string::const_iterator i = digits.begin(); i != digits.end(); i++) {
		if (VALID_DTMF_SYM(*i)) {
			phone->pub_send_dtmf(*i, call_info.dtmf_inband, call_info.dtmf_info);
		}
	}
}

bool t_userintf::exec_register(const list<string> command_list) {
	list<t_command_arg> al;
	bool reg_all_profiles = false;

	if (!parse_args(command_list, al)) {
		exec_command("help register");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 'a':
			reg_all_profiles = true;
			break;
		default:
			exec_command("help register");
			return false;
			break;
		}
	}
	
	do_register(reg_all_profiles);
	return true;
}

void t_userintf::do_register(bool reg_all_profiles) {
	if (reg_all_profiles) {
		list<t_user *> user_list = phone->ref_users();
		
		for (list<t_user *>::iterator i = user_list.begin();
		     i != user_list.end(); i++)
		{
			phone->pub_registration(*i, REG_REGISTER, 
					DUR_REGISTRATION(*i));
		}	
	} else {
		phone->pub_registration(active_user, REG_REGISTER, 
				DUR_REGISTRATION(active_user));
	}
}

bool t_userintf::exec_deregister(const list<string> command_list) {
	list<t_command_arg> al;
	bool dereg_all_devices = false;
	bool dereg_all_profiles = false;

	if (!parse_args(command_list, al)) {
		exec_command("help deregister");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 'a':
			dereg_all_profiles = true;
			break;
		case 'd':
			dereg_all_devices = true;
			break;
		default:
			exec_command("help deregister");
			return false;
			break;
		}
	}

	do_deregister(dereg_all_profiles, dereg_all_devices);
	return true;
}

void t_userintf::do_deregister(bool dereg_all_profiles, bool dereg_all_devices) {
	t_register_type dereg_type = REG_DEREGISTER;
	
	if (dereg_all_devices) {
		dereg_type = REG_DEREGISTER_ALL;
	}
	
	if (dereg_all_profiles) {
		list<t_user *> user_list = phone->ref_users();
		
		for (list<t_user *>::iterator i = user_list.begin();
		     i != user_list.end(); i++)
		{
			phone->pub_registration(*i, dereg_type);
		}
	} else {
		phone->pub_registration(active_user, dereg_type);
	}
}

bool t_userintf::exec_fetch_registrations(const list<string> command_list) {
	do_fetch_registrations();
	return true;
}

void t_userintf::do_fetch_registrations(void) {
	phone->pub_registration(active_user, REG_QUERY);
}

bool t_userintf::exec_options(const list<string> command_list, bool immediate) {
	list<t_command_arg> al;
	string destination;
	bool dest_set = false;

	if (!parse_args(command_list, al)) {
		exec_command("help options");
		return false;
	}
	
	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 0:
			destination = i->value;
			dest_set = true;
			break;
		default:
			exec_command("help options");
			return false;
			break;
		}
	}

	if (!dest_set) {
		if (phone->get_line_state(phone->get_active_line()) == LS_IDLE) {
			exec_command("help options");
			return false;
		}
	}

	return do_options(dest_set, destination, immediate);
}

bool t_userintf::do_options(bool dest_set, const string &destination, bool immediate) {
	if (!dest_set) {
		phone->pub_options();
	} else {
		t_url dest_url;
		dest_url.set_url(expand_destination(active_user, destination));
		
		if (!dest_url.is_valid()) {
			exec_command("help options");
			return false;
		}
		
		phone->pub_options(active_user, dest_url);
	}
	
	return true;
}

bool t_userintf::exec_line(const list<string> command_list) {
	list<t_command_arg> al;
	int line = 0;

	if (!parse_args(command_list, al)) {
		exec_command("help line");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 0:
			line = atoi(i->value.c_str());
			break;
		default:
			exec_command("help line");
			return false;
			break;
		}
	}

	if (line < 0 || line > 2) {
		exec_command("help line");
		return false;
	}

	do_line(line);
	return true;
}

void t_userintf::do_line(int line) {
	if (line == 0) {
		cout << endl;
		cout << "Active line is: " << phone->get_active_line()+1 << endl;
		cout << endl;
		return;
	}

	int current = phone->get_active_line();

	if (line == current + 1) {
		cout << endl;
		cout << "Line " << current + 1 << " is already active.\n";
		cout << endl;
		return;
	}

	phone->pub_activate_line(line - 1);
	if (phone->get_active_line() == current) {
		cout << endl;
		cout << "Current call cannot be put on-hold.\n";
		cout << "Cannot switch to another line now.\n";
		cout << endl;
	} else {
		cout << endl;
		cout << "Line " << phone->get_active_line()+1 << " is now active.\n";
		cout << endl;
	}
}

bool t_userintf::exec_user(const list<string> command_list) {
	list<t_command_arg> al;
	string profile_name;

	if (!parse_args(command_list, al)) {
		exec_command("help user");
		return false;
	}
	
	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 0:
			profile_name = i->value;
			break;
		default:
			exec_command("help user");
			return false;
			break;
		}
	}
	
	do_user(profile_name);
	return true;
}

void t_userintf::do_user(const string &profile_name) {
	list<t_user *> user_list = phone->ref_users();
	if (profile_name.empty()) {
		// Show all users
		cout << endl;
		for (list<t_user *>::iterator i = user_list.begin();
		     i != user_list.end(); i++)
		{
			if (*i == active_user) {
				cout << "* ";
			} else {
				cout << "  ";
			}
			
			cout << (*i)->get_profile_name();
			cout << "\n    ";
			cout << (*i)->get_display(false);
			cout << " <sip:" << (*i)->get_name();
			cout << "@" << (*i)->get_domain() << ">\n";
		}
		cout << endl;
		return;
	}

	for (list<t_user *>::iterator i = user_list.begin();
	     i != user_list.end(); i++)
	{
		if ((*i)->get_profile_name() == profile_name) {
			active_user = (*i);
			cout << endl;
			cout << profile_name;
			cout << " activated.\n";
			cout << endl;
			
			return;
		}
	}
	
	cout << endl;
	cout << "Unknown user profile: ";
	cout << profile_name;
	cout << endl << endl;
}

bool t_userintf::exec_zrtp(const list<string> command_list) {
	list<t_command_arg> al;
	t_zrtp_cmd zrtp_cmd = ZRTP_ENCRYPT;

	if (!parse_args(command_list, al)) {
		exec_command("help zrtp");
		return false;
	}
	
	if (al.size() != 1) {
		exec_command("help zrtp");
		return false;
	}
	
	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 0:
			if (i->value == "encrypt") {
				zrtp_cmd = ZRTP_ENCRYPT;
			} else if (i->value == "go-clear") {
				zrtp_cmd = ZRTP_GO_CLEAR;
			} else if (i->value == "confirm-sas") {
				zrtp_cmd = ZRTP_CONFIRM_SAS;
			} else if (i->value == "reset-sas") {
				zrtp_cmd = ZRTP_RESET_SAS;
			} else {
				exec_command("help zrtp");
				return false;
			}
			break;
		default:
			exec_command("help zrtp");
			return false;
			break;
		}
	}
	
	do_zrtp(zrtp_cmd);
	return true;
}

void t_userintf::do_zrtp(t_zrtp_cmd zrtp_cmd) {
	switch (zrtp_cmd) {
	case ZRTP_ENCRYPT:
		phone->pub_enable_zrtp();
		break;
	case ZRTP_GO_CLEAR:
		phone->pub_zrtp_request_go_clear();
		break;
	case ZRTP_CONFIRM_SAS:
		phone->pub_confirm_zrtp_sas();
		break;
	case ZRTP_RESET_SAS:
		phone->pub_reset_zrtp_sas_confirmation();
		break;
	default:
		assert(false);
	}
}

bool t_userintf::exec_message(const list<string> command_list) {
	list<t_command_arg> al;
	string display;
	string subject;
	string filename;
	string destination;
	string text;

	if (!parse_args(command_list, al)) {
		exec_command("help message");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 's':
			subject = i->value;
			break;
		case 'f':
			filename = i->value;
			break;
		case 'd':
			display = i->value;
			break;
		case 0:
			if (destination.empty()) {
				destination = i->value;
			} else {
				text = i->value;
			}
			break;
		default:
			exec_command("help message");
			return false;
			break;
		}
	}
	
	if (destination.empty() || (text.empty() && filename.empty())) {
		exec_command("help message");
		return false;
	}
	
	im::t_msg msg(text, im::MSG_DIR_OUT, im::TXT_PLAIN);
	msg.subject = subject;
	
	if (!filename.empty()) {
		t_media media("application/octet-stream");
		string mime_type = mime_database->get_mimetype(filename);
		
		if (!mime_type.empty()) {
			media = t_media(mime_type);
		}
		
		msg.set_attachment(filename, media, strip_path_from_filename(filename));
	}

	return do_message(destination, display, msg);
}

bool t_userintf::do_message(const string &destination, const string &display,
		const im::t_msg &msg)
{
	t_url dest_url(expand_destination(active_user, destination));
	
	if (!dest_url.is_valid()) {
		exec_command("help message");
		return false;
	}
	
	(void)phone->pub_send_message(active_user, dest_url, display, msg);
	return true;
}

bool t_userintf::exec_presence(const list<string> command_list) {
	list<t_command_arg> al;
	t_presence_state::t_basic_state basic_state = t_presence_state::ST_BASIC_OPEN;

	if (!parse_args(command_list, al)) {
		exec_command("help presence");
		return false;
	}

	for (list<t_command_arg>::iterator i = al.begin(); i != al.end(); i++) {
		switch (i->flag) {
		case 'b':
			if (i->value == "online") {
				basic_state = t_presence_state::ST_BASIC_OPEN;
			} else if (i->value == "offline") {
				basic_state = t_presence_state::ST_BASIC_CLOSED;
			} else {
				exec_command("help presence");
				return false;
			}
			break;
		default:
			exec_command("help presence");
			return false;
			break;
		}
	}

	do_presence(basic_state);
	return true;
}

void t_userintf::do_presence(t_presence_state::t_basic_state basic_state)
{
	phone->pub_publish_presence(active_user, basic_state);
}

bool t_userintf::exec_quit(const list<string> command_list) {
	do_quit();
	return true;
}

void t_userintf::do_quit(void) {
	end_interface = true;
}

bool t_userintf::exec_help(const list<string> command_list) {
	list<t_command_arg> al;

	if (!parse_args(command_list, al)) {
		exec_command("help help");
		return false;
	}

	if (al.size() > 1) {
		exec_command("help help");
		return false;
	}
	
	do_help(al);
	return true;
}
	
void t_userintf::do_help(const list<t_command_arg> &al) {
	if (al.size() == 0) {
		cout << endl;
		cout << "call		Call someone\n";
		cout << "answer		Answer an incoming call\n";
		cout << "answerbye	Answer an incoming call or end a call\n";
		cout << "reject		Reject an incoming call\n";
		cout << "redirect	Redirect an incoming call\n";
		cout << "transfer	Transfer a standing call\n";
		cout << "bye		End a call\n";
		cout << "hold		Put a call on-hold\n";
		cout << "retrieve	Retrieve a held call\n";
		cout << "conference	Join 2 calls in a 3-way conference\n";
		cout << "mute		Mute a line\n";
		cout << "dtmf		Send DTMF\n";
		cout << "redial		Repeat last call\n";
		cout << "register	Register your phone at a registrar\n";
		cout << "deregister	De-register your phone at a registrar\n";
		cout << "fetch_reg	Fetch registrations from registrar\n";
		cout << "options\t\tGet capabilities of another SIP endpoint\n";
		cout << "line		Toggle between phone lines\n";
		cout << "dnd		Do not disturb\n";
		cout << "auto_answer	Auto answer\n";
		cout << "user		Show users / set active user\n";
#ifdef HAVE_ZRTP
		cout << "zrtp		ZRTP command for voice encryption\n";
#endif
		cout << "message\t\tSend an instant message\n";
		cout << "presence	Publish your presence state\n";
		cout << "quit		Quit\n";
		cout << "help		Get help on a command\n";
		cout << endl;

		return;
	}

	bool ambiguous;
	string c = complete_command(tolower(al.front().value), ambiguous);

	if (c == "call") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tcall [-s subject] [-d display] [-h] dst\n";
		cout << "Description:\n";
		cout << "\tCall someone.\n";
		cout << "Arguments:\n";
		cout << "\t-s subject	Add a subject header to the INVITE\n";
		cout << "\t-d display	Add display name to To-header\n";
		cout << "\t-h		Hide your identity\n";
		cout << "\tdst		SIP uri of party to invite\n";
		cout << endl;

		return;
	}

	if (c == "answer") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tanswer\n";
		cout << "Description:\n";
		cout << "\tAnswer an incoming call.\n";
		cout << endl;

		return;
	}
	
	if (c == "answerbye") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tanswerbye\n";
		cout << "Description:\n";
		cout << "\tWith this command you can answer an incoming call or\n";
		cout << "\tend an established call.\n";
		cout << endl;

		return;
	}

	if (c == "reject") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\treject\n";
		cout << "Description:\n";
		cout << "\tReject an incoming call. A 603 Decline response\n";
		cout << "\twill be sent.\n";
		cout << endl;

		return;
	}

	if (c == "redirect") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tredirect [-s] [-t type] [-a on|off] [dst ... dst]\n";
		cout << "Description:\n";
		cout << "\tRedirect an incoming call. A 302 Moved Temporarily\n";
		cout << "\tresponse will be sent.\n";
		cout << "\tYou can redirect the current incoming call by specifying\n";
		cout << "\tone or more destinations without any other arguments.\n";
		cout << "Arguments:\n";
		cout << "\t-s		Show which redirections are active.\n";
		cout << "\t-t type\t	Type for permanent redirection of calls.\n";
		cout << "\t		Values: always, busy, noanswer.\n";
		cout << "\t-a on|off	Enable/disable permanent redirection.\n";
		cout << "\t		The default action is 'on'.\n";
		cout << "\t		You can disable all redirections with the\n";
		cout << "\t		'off' action and no type.\n";
		cout << "\tdst		SIP uri where the call should be redirected.\n";
		cout << "\t		You can specify up to 5 destinations.\n";
		cout << "\t		The destinations will be tried in sequence.\n";
		cout << "Examples:\n";
		cout << "\tRedirect current incoming call to michel@twinklephone.com\n";
		cout << "\tredirect michel@twinklephone.com\n";
		cout << endl;
		cout << "\tRedirect busy calls permanently to michel@twinklephone.com\n";
		cout << "\tredirect -t busy michel@twinklephone.com\n";
		cout << endl;
		cout << "\tDisable redirection of busy calls.\n";
		cout << "\tredirect -t busy -a off\n";
		cout << endl;

		return;
	}

	if (c == "transfer") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\ttransfer [-c] [-l] [dst]\n";
		cout << "Description:\n";
		cout << "\tTransfer a standing call to another destination.\n";
		cout << "\tFor a transfer with consultation, first use the -c flag with a\n";
		cout << "\tdestination. This sets up the consultation call. When the\n";
		cout << "\tconsulted party agrees, give the command with the -c flag once\n";
		cout << "\tmore, but now without a destination. This transfers the call.\n";
		cout << "Arguments:\n";
		cout << "\t-c	Consult destination before transferring call.\n";
		cout << "\t-l	Transfer call to party on other line.\n";
		cout << "\tdst	SIP uri of transfer destination\n";
		cout << endl;

		return;
	}

	if (c == "bye") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tbye\n";
		cout << "Description:\n";
		cout << "\tEnd a call.\n";
		cout << "\tFor a stable call a BYE will be sent.\n";
		cout << "\tIf the invited party did not yet sent a final answer,\n";
		cout << "\tthen a CANCEL will be sent.\n";
		cout << endl;

		return;
	}

	if (c == "hold") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\thold\n";
		cout << "Description:\n";
		cout << "\tPut the current call on the acitve line on-hold.\n";
		cout << endl;

		return;
	}

	if (c == "retrieve") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tretrieve\n";
		cout << "Description:\n";
		cout << "\tRetrieve a held call on the active line.\n";
		cout << endl;

		return;
	}

	if (c == "conference") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tconference\n";
		cout << "Description:\n";
		cout << "\tJoin 2 calls in a 3-way conference. Before you give this\n";
		cout << "\tcommand you must have a call on each line.\n";
		cout << endl;

		return;
	}

	if (c == "mute") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tmute [-s] [-a on|off]\n";
		cout << "Description:\n";
		cout << "\tMute/unmute the active line.\n";
		cout << "\tYou can hear the other side of the line, but they cannot\n";
		cout << "\thear you.\n";
		cout << "Arguments:\n";
		cout << "\t-s		Show if line is muted.\n";
		cout << "\t-a on|off	Mute/unmute.\n";
		cout << "Notes:\n";
		cout << "\tWithout any arguments you can toggle the status.\n";
		cout << endl;

		return;
	}

	if (c == "dtmf") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tdtmf digits\n";
		cout << "Description:\n";
		cout << "\tSend the digits as out-of-band DTMF telephone events ";
		cout << "(RFC 2833).\n";
		cout << "\tThis command can only be given when a call is ";
		cout << "established.\n";
		cout << "Arguments:\n";
		cout << "\t-r	Raw mode: do not convert letters to digits.\n";
		cout << "\tdigits	0-9 | A-D | * | #\n";
		cout << "Example:\n";
		cout << "\tdtmf 1234#\n";
		cout << "\tdmtf movies\n";
		cout << "Notes:\n";
		cout << "\tThe overdecadic digits A-D can only be sent in raw mode.\n";
		cout << endl;

		return;
	}
	
	if (c == "redial") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tredial\n";
		cout << "Description:\n";
		cout << "\tRepeat last call.\n";
		cout << endl;

		return;
	}

	if (c == "register") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tregister\n";
		cout << "Description:\n";
		cout << "\tRegister your phone at a registrar.\n";
		cout << "Arguments:\n";
		cout << "\t-a	Register all enabled user profiles.\n";
		cout << endl;

		return;
	}

	if (c == "deregister") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tderegister [-a]\n";
		cout << "Description:\n";
		cout << "\tDe-register your phone at a registrar.\n";
		cout << "Arguments:\n";
		cout << "\t-a	De-register all enabled user profiles.\n";
		cout << "\t-d	De-register all devices.\n";
		cout << endl;

		return;
	}

	if (c == "fetch_reg") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tfetch_reg\n";
		cout << "Description:\n";
		cout << "\tFetch current registrations from registrar.\n";
		cout << endl;

		return;
	}

	if (c == "options") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\toptions [dst]\n";
		cout << "Description:\n";
		cout << "\tGet capabilities of another SIP endpoint.\n";
		cout << "\tIf no destination is passed as an argument, then\n";
		cout << "\tthe capabilities of the far-end in the current call\n";
		cout << "\ton the active line are requested.\n";
		cout << "Arguments:\n";
		cout << "\tdst		SIP uri of end-point\n";
		cout << endl;

		return;
	}

	if (c == "line") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tline [lineno]\n";
		cout << "Description:\n";
		cout << "\tIf no argument is passed then the current active ";
		cout << "line is shown\n";
		cout << "\tOtherwise switch to another line. If the current active\n";
		cout << "\thas a call, then this call will be put on-hold.\n";
		cout << "\tIf the new active line has a held call, then this call\n";
		cout << "\twill be retrieved.\n";
		cout << "Arguments:\n";
		cout << "\tlineno		Switch to another line (values = ";
		cout << "1,2)\n";
		cout << endl;

		return;
	}

	if (c == "dnd") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tdnd [-s] [-a on|off]\n";
		cout << "Description:\n";
		cout << "\tEnable/disable the do not disturb service.\n";
		cout << "\tIf dnd is enabled then a 480 Temporarily Unavailable ";
		cout << "response is given\n";
		cout << "\ton incoming calls.\n";
		cout << "Arguments:\n";
		cout << "\t-s		Show if dnd is active.\n";
		cout << "\t-a on|off	Enable/disable dnd.\n";
		cout << "Notes:\n";
		cout << "\tWithout any arguments you can toggle the status.\n";
		cout << endl;

		return;
	}
	
	if (c == "auto_answer") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tauto_answer [-s] [-a on|off]\n";
		cout << "Description:\n";
		cout << "\tEnable/disable the auto answer service.\n";
		cout << "Arguments:\n";
		cout << "\t-s		Show if auto answer is active.\n";
		cout << "\t-a on|off	Enable/disable auto answer.\n";
		cout << "Notes:\n";
		cout << "\tWithout any arguments you can toggle the status.\n";
		cout << endl;

		return;
	}
	
	if (c == "user") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tuser [profile name]\n";
		cout << "Description:\n";
		cout << "\tMake a user profile the active profile.\n";
		cout << "\tCommands like 'invite' are executed for the active profile.\n";
		cout << "\tWithout an argument this command lists all users. The active\n";
		cout << "\tuser will be marked with '*'.\n";
		cout << "Arguments:\n";
		cout << "\tprofile name	The user profile to activate.\n";
		cout << endl;
		
		return;
	}
	
#ifdef HAVE_ZRTP
	if (c == "zrtp") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tzrtp <zrtp-command>\n";
		cout << "Description:\n";
		cout << "\tExecute a ZRTP command.\n";
		cout << "ZRTP commands:\n";
		cout << "\tencrypt      Start ZRTP negotiation for encryption.\n";
		cout << "\tgo-clear     Send ZRTP go-clear request.\n";
		cout << "\tconfirm-sas  Confirm the SAS value.\n";
		cout << "\treset-sas    Reset SAS confirmation.\n";
		cout << endl;
		
		return;
	}
#endif
	
	if (c == "message") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tmessage [-s subject] [-f file name] [-d display] dst [text]\n";
		cout << "Description:\n";
		cout << "\tSend an instant message.\n";
		cout << "Arguments:\n";
		cout << "\t-s subject	Subject of the message.\n";
		cout << "\t-f file name	File name of the file to send.\n";
		cout << "\t-d display	Add display name to To-header\n";
		cout << "\tdst		SIP uri of party to message\n";
		cout << "\ttext		Message text to send. Surround with double quotes\n";
		cout << "\t\t\twhen your text contains whitespace.\n";
		cout << "\t\t\tWhen you send a file, then the text is ignored.\n";
		cout << endl;
		
		return;
	}
	
	if (c == "presence") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tpresence -b [online|offline]\n";
		cout << "Description:\n";
		cout << "\tPublish your presence state to a presence agent\n";
		cout << "Arguments:\n";
		cout << "\t-b		A basic presence state: online or offline\n";
		cout << endl;
		
		return;
	}

	if (c == "quit") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\tquit\n";
		cout << "Description:\n";
		cout << "\tQuit.\n";
		cout << endl;

		return;
	}

	if (c == "help") {
		cout << endl;
		cout << "Usage:\n";
		cout << "\thelp [command]\n";
		cout << "Description:\n";
		cout << "\tShow help on a command.\n";
		cout << "Arguments:\n";
		cout << "\tcommand		Command you want help with\n";
		cout << endl;

		return;
	}

	cout << endl;
	cout << "\nUnknown command\n\n";
	cout << endl;
}


/////////////////////////////
// Public
/////////////////////////////

t_userintf::t_userintf(t_phone *_phone) {
	phone = _phone;
	end_interface = false;
	tone_gen = NULL;
	active_user = NULL;
	use_stdout = true;
	throttle_dtmf_not_supported = false;
	thr_process_events = NULL;

	all_commands.push_back("invite");
	all_commands.push_back("call");
	all_commands.push_back("answer");
	all_commands.push_back("answerbye");
	all_commands.push_back("reject");
	all_commands.push_back("redirect");
	all_commands.push_back("bye");
	all_commands.push_back("hold");
	all_commands.push_back("retrieve");
	all_commands.push_back("refer");
	all_commands.push_back("transfer");
	all_commands.push_back("conference");
	all_commands.push_back("mute");
	all_commands.push_back("dtmf");
	all_commands.push_back("redial");
	all_commands.push_back("register");
	all_commands.push_back("deregister");
	all_commands.push_back("fetch_reg");
	all_commands.push_back("options");
	all_commands.push_back("line");
	all_commands.push_back("dnd");
	all_commands.push_back("auto_answer");
	all_commands.push_back("user");
#ifdef HAVE_ZRTP
	all_commands.push_back("zrtp");
#endif
	all_commands.push_back("message");
	all_commands.push_back("presence");
	all_commands.push_back("quit");
	all_commands.push_back("exit");
	all_commands.push_back("q");
	all_commands.push_back("x");
	all_commands.push_back("help");
	all_commands.push_back("h");
	all_commands.push_back("?");
}

t_userintf::~t_userintf() {
	if (tone_gen) {
		MEMMAN_DELETE(tone_gen);
		delete tone_gen;
	}
	
	if (thr_process_events) {
		evq_ui_events.push_quit();
		thr_process_events->join();
		log_file->write_report("thr_process_events stopped.", 
			"t_userintf::~t_userintf", LOG_NORMAL, LOG_DEBUG);
		MEMMAN_DELETE(thr_process_events);
		delete thr_process_events;
	}
}

string t_userintf::complete_command(const string &c, bool &ambiguous) {
	ambiguous = false;
	string full_command;

	for (list<string>::const_iterator i = all_commands.begin();
	     i != all_commands.end(); i++)
	{

		// If there is an exact match, then this is the command.
		// This allows a one command to be a prefix of another command.
		if (c == *i) {
			ambiguous = false;
			return c;
		}

		if (c.size() < i->size() && c == i->substr(0, c.size())) {
			if (full_command != "") {
				ambiguous = true;
				// Do not return here, as there might still be
				// an exact match.
			}

			full_command = *i;
		}
	}

	if (ambiguous) return "";
	return full_command;
}

bool t_userintf::exec_command(const string &command_line, bool immediate) {
	vector<string> v = split_ws(command_line, true);
	if (v.size() == 0) return false;

	bool ambiguous;
	string command = complete_command(tolower(v[0]), ambiguous);

	if (ambiguous) {
		if (use_stdout) {
			cout << endl;
			cout << "Ambiguous command\n";
			cout << endl;
		}
		
		return false;
	}
	
	list<string> l(v.begin(), v.end());

	if (command == "invite") return exec_invite(l, immediate);
	if (command == "call") return exec_invite(l, immediate);
	if (command == "answer") return exec_answer(l);
	if (command == "answerbye") return exec_answerbye(l);
	if (command == "reject") return exec_reject(l);
	if (command == "redirect") return exec_redirect(l, immediate);
	if (command == "bye") return exec_bye(l);
	if (command == "hold") return exec_hold(l);
	if (command == "retrieve") return exec_retrieve(l);
	if (command == "refer") return exec_refer(l, immediate);
	if (command == "transfer") return exec_refer(l, immediate);
	if (command == "conference") return exec_conference(l);
	if (command == "mute") return exec_mute(l);
	if (command == "dtmf") return exec_dtmf(l);
	if (command == "redial") return exec_redial(l);
	if (command == "register") return exec_register(l);
	if (command == "deregister") return exec_deregister(l);
	if (command == "fetch_reg") return exec_fetch_registrations(l);
	if (command == "options") return exec_options(l, immediate);
	if (command == "line") return exec_line(l);
	if (command == "dnd") return exec_dnd(l);
	if (command == "auto_answer") return exec_auto_answer(l);
	if (command == "user") return exec_user(l);
#ifdef HAVE_ZRTP
	if (command == "zrtp") return exec_zrtp(l);
#endif
	if (command == "message") return exec_message(l);
	if (command == "presence") return exec_presence(l);
	if (command == "quit") return exec_quit(l);
	if (command == "exit") return exec_quit(l);
	if (command == "x") return exec_quit(l);
	if (command == "q") return exec_quit(l);
	if (command == "help") return exec_help(l);
	if (command == "h") return exec_help(l);
	if (command == "?") return exec_help(l);

	if (use_stdout) {
		cout << endl;
		cout << "Unknown command\n";
		cout << endl;
	}
	
	return false;
}

string t_userintf::format_sip_address(t_user *user_config, const string &display,
	                              const t_url &uri) const
{
	string s;
	
	if (uri.encode() == ANONYMOUS_URI) {
		return TRANSLATE("Anonymous");
	}

	s = display;
	if (display != "") s += " <";
	
	string number;
	if (uri.get_scheme() == "tel") {
		number = uri.get_host();
	} else {
		number = uri.get_user();
	}

	if (user_config->get_display_useronly_phone() &&
	    uri.is_phone(user_config->get_numerical_user_is_phone(),
	    			user_config->get_special_phone_symbols()))
	{
		// Display telephone number only
		s += user_config->convert_number(number);
	} else {
		// Display full URI
		// Convert the username according to the number conversion
		// rules.
		t_url u(uri);
		string username = user_config->convert_number(number);
		if (username != number) {
			if (uri.get_scheme() == "tel") {
				u.set_host(username);
			} else {
				u.set_user(username);
			}
		}
		s += u.encode_no_params_hdrs(false);
	}

	if (display != "") s += ">";

	return s;
}

list<string> t_userintf::format_warnings(const t_hdr_warning &hdr_warning) const {
	string s;
	list<string> l;

	for (list<t_warning>::const_iterator i = hdr_warning.warnings.begin();
	     i != hdr_warning.warnings.end(); i++)
	{
		s = TRANSLATE("Warning:");
		s += " ";
		s += int2str(i->code);
		s += ' ';
		s += i->text;
		s += " (";
		s += i->host;
		if (i->port > 0) s += int2str(i->port, ":%d");
		s += ')';
		l.push_back(s);
	}

	return l;
}

string t_userintf::format_codec(t_audio_codec codec) const {
	switch (codec) {
	case CODEC_NULL: 	return "null";
	case CODEC_UNSUPPORTED:	return "???";
	case CODEC_G711_ALAW:	return "g711a";
	case CODEC_G711_ULAW:	return "g711u";
	case CODEC_GSM:		return "gsm";
	case CODEC_SPEEX_NB:	return "spx-nb";
	case CODEC_SPEEX_WB:	return "spx-wb";
	case CODEC_SPEEX_UWB:	return "spx-uwb";
	case CODEC_ILBC:	return "ilbc";
	case CODEC_G726_16:	return "g726-16";
	case CODEC_G726_24:	return "g726-24";
	case CODEC_G726_32:	return "g726-32";
	case CODEC_G726_40:	return "g726-40";
	default:		return "???";
	}
}

void t_userintf::run(void) {
	// Start asynchronous event processor
	thr_process_events = new t_thread(process_events_main, NULL);
	MEMMAN_NEW(thr_process_events);
	
	list<t_user *> user_list = phone->ref_users();
	active_user = user_list.front();

	cout << PRODUCT_NAME << " " << PRODUCT_VERSION << ", " << PRODUCT_DATE;
	cout << endl;
	cout << "Copyright (C) 2005-2009  " << PRODUCT_AUTHOR << endl;
	cout << endl;
	
	cout << "Users:";
	exec_command("user");
	
	cout << "Local IP:       " << user_host << endl;
	cout << endl;
	
	restore_state();

	// Initialize phone functions
	phone->init();

	//Initialize GNU readline functions
	rl_attempted_completion_function = tw_completion;
	using_history();
	read_history(sys_config->get_history_file().c_str());
	stifle_history(CLI_MAX_HISTORY_LENGTH);


	while (!end_interface) {
		char *command_line = tw_readline(CLI_PROMPT);
		if (!command_line){
			cout << endl;
			break;
		}
		
		exec_command(command_line);
	}
	
	// Terminate phone functions
	write_history(sys_config->get_history_file().c_str());
	phone->terminate();
	
	save_state();
	cout << endl;
}

void t_userintf::process_events(void) {
	t_event		*event;
	t_event_ui	*ui_event;
	
	bool quit = false;
	while (!quit) {
		event = evq_ui_events.pop();
		switch (event->get_type()) {
		case EV_UI:
			ui_event = dynamic_cast<t_event_ui *>(event);
			assert(ui_event);
			ui_event->exec(this);
			break;
		case EV_QUIT:
			quit = true;
			break;
		default:
			assert(false);
			break;
		}
			
		MEMMAN_DELETE(event);
		delete event;
	}
}

void t_userintf::save_state(void) {
	string err_msg;
	
	sys_config->set_redial_url(last_called_url);
	sys_config->set_redial_display(last_called_display);
	sys_config->set_redial_subject(last_called_subject);
	sys_config->set_redial_profile(last_called_profile);
	sys_config->set_redial_hide_user(last_called_hide_user);
	
	sys_config->write_config(err_msg);
}

void t_userintf::restore_state(void) {
	last_called_url = sys_config->get_redial_url();
	last_called_display = sys_config->get_redial_display();
	last_called_subject = sys_config->get_redial_subject();
	last_called_profile = sys_config->get_redial_profile();
	last_called_hide_user = sys_config->get_redial_hide_user();
}

void t_userintf::lock(void) {
	assert(!is_prohibited_thread());
	// TODO: lock for CLI
}

void t_userintf::unlock(void) {
	// TODO: lock for CLI
}

string t_userintf::select_network_intf(void) {
	string ip;
	list<t_interface> *l = get_interfaces();
	// As memman has no hooks in the socket routines, report it here.
	MEMMAN_NEW(l);
	if (l->size() == 0) {
		// cout << "Cannot find a network interface\n";
		cout << "Cannot find a network interface. Twinkle will use\n"
			"127.0.0.1 as the local IP address. When you connect to\n"
			"the network you have to restart Twinkle to use the correct\n"
			"IP address.\n";
		MEMMAN_DELETE(l);
		delete l;
		return "127.0.0.1";
	}

	if (l->size() == 1) {
		ip = l->front().get_ip_addr();
	} else {
		size_t num = 1;
		cout << "Multiple network interfaces found.\n";
		for (list<t_interface>::iterator i = l->begin(); i != l->end(); i++) {
			cout << num << ") " << i->name << ": ";
			cout << i->get_ip_addr() << endl;
			num++;
		}

		cout << endl;

		size_t selection = 0;
		while (selection < 1 || selection > l->size()) {
			cout << "Which interface do you want to use (enter number): ";
			string choice;
			getline(cin, choice);
			selection = atoi(choice.c_str());
		}

		num = 1;
		for (list<t_interface>::iterator i = l->begin(); i != l->end(); i++) {
			if (num == selection) {
				ip = i->get_ip_addr();
				break;
			}
			num++;
		}

	}

	MEMMAN_DELETE(l);
	delete l;
	return ip;
}

bool t_userintf::select_user_config(list<string> &config_files) {
	// In CLI mode, simply select the default config file
	config_files.clear();
	config_files.push_back(USER_CONFIG_FILE);
	return true;
}

void t_userintf::cb_incoming_call(t_user *user_config, int line, const t_request *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "incoming call\n";
	cout << "From:\t\t";
	
	string from_party = format_sip_address(user_config, 
		r->hdr_from.get_display_presentation(), r->hdr_from.uri);
	cout << from_party << endl;

	if (r->hdr_organization.is_populated()) {
		cout << "Organization:\t" << r->hdr_organization.name << endl;
	}

	cout << "To:\t\t";
	cout << format_sip_address(user_config, r->hdr_to.display, r->hdr_to.uri) << endl;

	if (r->hdr_referred_by.is_populated()) {
		cout << "Referred-by:\t";
		cout << format_sip_address(user_config, r->hdr_referred_by.display,
			r->hdr_referred_by.uri);
		cout << endl;
	}

	if (r->hdr_subject.is_populated()) {
		cout << "Subject:\t" << r->hdr_subject.subject << endl;
	}

	cout << endl;
	cout.flush();

	cb_notify_call(line, from_party);
}

void t_userintf::cb_call_cancelled(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "far end cancelled call.\n";
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_far_end_hung_up(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "far end ended call.\n";
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_answer_timeout(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "answer timeout.\n";
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_sdp_answer_not_supported(int line, const string &reason) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "SDP answer from far end not supported.\n";
	cout << reason << endl;
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_sdp_answer_missing(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "SDP answer from far end missing.\n";
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_unsupported_content_type(int line, const t_sip_message *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "Unsupported content type in answer from far end.\n";
	cout << r->hdr_content_type.media.type << "/";
	cout << r->hdr_content_type.media.subtype << endl;
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_ack_timeout(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "no ACK received, call will be terminated.\n";
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_100rel_timeout(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ";
	cout << "no PRACK received, call will be terminated.\n";
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_prack_failed(int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": PRACK failed.\n";
	cout << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();

	cb_stop_call_notification(line);
}

void t_userintf::cb_provisional_resp_invite(int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": received ";
	cout << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_cancel_failed(int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": cancel failed.\n";
	cout << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_call_answered(t_user *user_config, int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": far end answered call.\n";
	cout << r->code << ' ' << r->reason << endl;

	cout << "To: ";
	cout << format_sip_address(user_config, r->hdr_to.display, r->hdr_to.uri) << endl;

	if (r->hdr_organization.is_populated()) {
		cout << "Organization: " << r->hdr_organization.name << endl;
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_call_failed(t_user *user_config, int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": call failed.\n";
	cout << r->code << ' ' << r->reason << endl;

	// Warnings
	if (r->hdr_warning.is_populated()) {
		list<string> l = format_warnings(r->hdr_warning);
		for (list<string>::iterator i = l.begin(); i != l.end(); i++) {
			cout << *i << endl;
		}
	}

	// Redirection response
	if (r->get_class() == R_3XX && r->hdr_contact.is_populated()) {
		list<t_contact_param> l = r->hdr_contact.contact_list;
		l.sort();
		cout << "You can try the following contacts:\n";
		for (list<t_contact_param>::iterator i = l.begin();
		     i != l.end(); i++)
		{
			cout << format_sip_address(user_config, i->display, i->uri) << endl;
		}
	}

	// Unsupported extensions
	if (r->code == R_420_BAD_EXTENSION) {
		cout << r->hdr_unsupported.encode();
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_stun_failed_call_ended(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": call failed.\n";
	cout << endl;
	cout.flush();		
}

void t_userintf::cb_call_ended(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": call ended.\n";
	cout.flush();
}

void t_userintf::cb_call_established(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": call established.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_options_response(const t_response *r) {
	cout << endl;
	cout << "OPTIONS response received: ";
	cout << r->code << ' ' << r->reason << endl;

	cout << "Capabilities of " << r->hdr_to.uri.encode() << endl;

	cout << "Accepted body types\n";
	if (r->hdr_accept.is_populated()) {
		cout << "\t" << r->hdr_accept.encode();
	} else {
		cout << "\tUnknown\n";
	}

	cout << "Accepted encodings\n";
	if (r->hdr_accept_encoding.is_populated()) {
		cout << "\t" << r->hdr_accept_encoding.encode();
	} else {
		cout << "\tUnknown\n";
	}

	cout << "Accepted languages\n";
	if (r->hdr_accept_language.is_populated()) {
		cout << "\t" << r->hdr_accept_language.encode();
	} else {
		cout << "\tUnknown\n";
	}

	cout << "Allowed requests\n";
	if (r->hdr_allow.is_populated()) {
		cout << "\t" << r->hdr_allow.encode();
	} else {
		cout << "\tUnknown\n";
	}

	cout << "Supported extensions\n";
	if (r->hdr_supported.is_populated()) {
		if (r->hdr_supported.features.empty()) {
			cout << "\tNone\n";
		} else {
			cout << "\t" << r->hdr_supported.encode();
		}
	} else {
		cout << "\tUnknown\n";
	}

	cout << "End point type\n";
	bool endpoint_known = false;
	if (r->hdr_server.is_populated()) {
		cout << "\t" << r->hdr_server.encode();
		endpoint_known = true;
	}

	if (r->hdr_user_agent.is_populated()) {
		// Some end-point put a User-Agent header in the response
		// instead of a Server header.
		cout << "\t" << r->hdr_user_agent.encode();
		endpoint_known = true;
	}

	if (!endpoint_known) {
		cout << "\tUnknown\n";
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_reinvite_success(int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": re-INVITE successful.\n";
	cout << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_reinvite_failed(int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": re-INVITE failed.\n";
	cout << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_retrieve_failed(int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	// The status code from the response has already been reported
	// by cb_reinvite_failed.

	cout << endl;
	cout << "Line " << line + 1 << ": retrieve failed.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_invalid_reg_resp(t_user *user_config, 
		const t_response *r, const string &reason) 
{
	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", registration failed: " << r->code << ' ' << r->reason << endl;
	cout << reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_register_success(t_user *user_config, 
	const t_response *r, unsigned long expires, bool first_success)
{
	// Only report success if this is the first success in a sequence
	if (!first_success) return;

	cout << endl;
	cout << user_config->get_profile_name();
	cout << ": registration succeeded (expires = " << expires << " seconds)\n";

	// Date at registrar
	if (r->hdr_date.is_populated()) {
		cout << "Registrar ";
		cout << r->hdr_date.encode() << endl;
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_register_failed(t_user *user_config, 
		const t_response *r, bool first_failure) 
{
	// Only report the first failure in a sequence of failures
	if (!first_failure) return;

	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", registration failed: " << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_register_stun_failed(t_user *user_config, bool first_failure) {
	// Only report the first failure in a sequence of failures
	if (!first_failure) return;

	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", registration failed: STUN failure";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_deregister_success(t_user *user_config, const t_response *r) {
	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", de-registration succeeded: " << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_deregister_failed(t_user *user_config,  const t_response *r) {
	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", de-registration failed: " << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}
void t_userintf::cb_fetch_reg_failed(t_user *user_config, const t_response *r) {
	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", fetch registrations failed: " << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_fetch_reg_result(t_user *user_config, const t_response *r) {
	cout << endl;

	cout << user_config->get_profile_name();
	const list<t_contact_param> &l = r->hdr_contact.contact_list;
	if (l.size() == 0) {
		cout << ": you are not registered\n";
	} else {
		cout << ": you have the following registrations\n";
		for (list<t_contact_param>::const_iterator i = l.begin();
		     i != l.end(); i++)
		{
			cout << i->encode() << endl;
		}
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_register_inprog(t_user *user_config, t_register_type register_type) {
	switch (register_type) {
	case REG_REGISTER:
		// Do not report a register refreshment
		if (phone->get_is_registered(user_config)) return;

		// Do not report an automatic register re-attempt
		if (phone->get_last_reg_failed(user_config)) return;

		cout << endl;
		cout << user_config->get_profile_name();
		cout << ": registering phone...\n";
		break;
	case REG_DEREGISTER:
		cout << endl;
		cout << user_config->get_profile_name();
		cout << ": deregistering phone...\n";
		break;
	case REG_DEREGISTER_ALL:
		cout << endl;
		cout << user_config->get_profile_name();
		cout << ": deregistering all phones...";
		break;
	case REG_QUERY:
		cout << endl;
		cout << user_config->get_profile_name();
		cout << ": fetching registrations...";
		break;
	default:
		assert(false);
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_redirecting_request(t_user *user_config, 
		int line, const t_contact_param &contact) 
{
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": redirecting request to:\n";

	cout << format_sip_address(user_config, contact.display, contact.uri) << endl;

	cout << endl;
	cout.flush();
}

void t_userintf::cb_redirecting_request(t_user *user_config, const t_contact_param &contact) {
	cout << endl;
	cout << "Redirecting request to: ";

	cout << format_sip_address(user_config, contact.display, contact.uri) << endl;

	cout << endl;
	cout.flush();
}

void t_userintf::cb_play_ringtone(int line) {
	if (!sys_config->get_play_ringtone()) return;

	if (tone_gen) {
		tone_gen->stop();
		MEMMAN_DELETE(tone_gen);
		delete tone_gen;
	}
	
	// Determine ring tone
	string ringtone_file = phone->get_ringtone(line);

	tone_gen = new t_tone_gen(ringtone_file, sys_config->get_dev_ringtone());
	MEMMAN_NEW(tone_gen);
	
	// If ring tone does not exist, then fall back to system default.
	if (!tone_gen->is_valid() && ringtone_file != FILE_RINGTONE) {
		MEMMAN_DELETE(tone_gen);
		delete tone_gen;
		tone_gen = new t_tone_gen(FILE_RINGTONE, sys_config->get_dev_ringtone());
		MEMMAN_NEW(tone_gen);
	}
	
	// Play ring tone
	tone_gen->start_play_thread(true, INTERVAL_RINGTONE);
}

void t_userintf::cb_play_ringback(t_user *user_config) {
	if (!sys_config->get_play_ringback()) return;
	
	if (tone_gen) {
		tone_gen->stop();
		MEMMAN_DELETE(tone_gen);
		delete tone_gen;
	}
	
	// Determine ring back tone
	string ringback_file;
	if (!user_config->get_ringback_file().empty()) {
		ringback_file = user_config->get_ringback_file();
	} else if (!sys_config->get_ringback_file().empty()) {
		ringback_file = sys_config->get_ringback_file();
	} else {
		// System default
		ringback_file = FILE_RINGBACK;
	}

	tone_gen = new t_tone_gen(ringback_file, sys_config->get_dev_speaker());
	MEMMAN_NEW(tone_gen);
	
	// If ring back tone does not exist, then fall back to system default.
	if (!tone_gen->is_valid() && ringback_file != FILE_RINGBACK) {
		MEMMAN_DELETE(tone_gen);
		delete tone_gen;
		tone_gen = new t_tone_gen(FILE_RINGBACK, sys_config->get_dev_speaker());
		MEMMAN_NEW(tone_gen);
	}
	
	// Play ring back tone
	tone_gen->start_play_thread(true, INTERVAL_RINGBACK);
}

void t_userintf::cb_stop_tone(int line) {
	// Only stop the tone if the current line is the active line
	if (line != phone->get_active_line()) return;

	if (!tone_gen) return;
	tone_gen->stop();
	MEMMAN_DELETE(tone_gen);
	delete tone_gen;
	tone_gen = NULL;
}

void t_userintf::cb_notify_call(int line, string from_party) {
	// Play ringtone if the call is received on the active line
	if (line == phone->get_active_line() &&
	    !phone->is_line_auto_answered(line))
	{
		cb_play_ringtone(line);
	}
}

void t_userintf::cb_stop_call_notification(int line) {
	cb_stop_tone(line);
}

void t_userintf::cb_dtmf_detected(int line, char dtmf_event) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": DTMF detected: ";

	if (VALID_DTMF_EV(dtmf_event)) {
		cout << dtmf_ev2char(dtmf_event) << endl;
	} else {
		cout << "invalid DTMF telephone event (" << (int)dtmf_event << endl;
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_async_dtmf_detected(int line, char dtmf_event) {
	if (line >= NUM_USER_LINES) return;
	
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_DTMF_DETECTED);
	MEMMAN_NEW(event);
	
	event->set_line(line);
	event->set_dtmf_event(dtmf_event);	
	evq_ui_events.push(event);
}

void t_userintf::cb_send_dtmf(int line, char dtmf_event) {
	// No feed back in CLI
}

void t_userintf::cb_async_send_dtmf(int line, char dtmf_event) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_SEND_DTMF);
	MEMMAN_NEW(event);
	
	event->set_line(line);
	event->set_dtmf_event(dtmf_event);	
	evq_ui_events.push(event);
}

void t_userintf::cb_dtmf_not_supported(int line) {
	if (line >= NUM_USER_LINES) return;
	
	if (throttle_dtmf_not_supported) return;

	cout << endl;
	cout << "Line " << line + 1 << ": far end does not support DTMF events.\n";
	cout << endl;
	cout.flush();

	// Throttle subsequent call backs
	throttle_dtmf_not_supported = true;
}

void t_userintf::cb_dtmf_supported(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": far end supports DTMF telephone event.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_line_state_changed(void) {
	// Nothing to do for CLI
}

void t_userintf::cb_async_line_state_changed(void) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_LINE_STATE_CHANGED);
	MEMMAN_NEW(event);
	
	evq_ui_events.push(event);
}

void t_userintf::cb_send_codec_changed(int line, t_audio_codec codec) {
	// No feedback in CLI
}

void t_userintf::cb_recv_codec_changed(int line, t_audio_codec codec) {
	// No feedback in CLI
}

void t_userintf::cb_async_recv_codec_changed(int line, t_audio_codec codec) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_RECV_CODEC_CHANGED);
	MEMMAN_NEW(event);
	
	event->set_line(line);
	event->set_codec(codec);	
	evq_ui_events.push(event);
}

void t_userintf::cb_notify_recvd(int line, const t_request *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 <<  ": received notification.\n";
	cout << "Event:    " << r->hdr_event.event_type << endl;
	cout << "State:    " << r->hdr_subscription_state.substate << endl;

	if (r->hdr_subscription_state.substate == SUBSTATE_TERMINATED) {
		cout << "Reason:   " << r->hdr_subscription_state.reason << endl;
	}

	t_response *sipfrag = (t_response *)((t_sip_body_sipfrag *)r->body)->sipfrag;
	cout << "Progress: " << sipfrag->code << ' ' << sipfrag->reason << endl;

	cout << endl;
	cout.flush();
}

void t_userintf::cb_refer_failed(int line, const t_response *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": refer request failed.\n";
	cout << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_refer_result_success(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": call succesfully referred.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_refer_result_failed(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": call refer failed.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_refer_result_inprog(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": call refer in progress.\n";
	cout << "No further notifications will be received.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_call_referred(t_user *user_config, int line, t_request *r) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": transferring call to ";
	cout << format_sip_address(user_config, r->hdr_refer_to.display,
		r->hdr_refer_to.uri);
	cout << endl;

	if (r->hdr_referred_by.is_populated()) {
		cout << "Tranfer requested by ";
		cout << format_sip_address(user_config, r->hdr_referred_by.display,
			r->hdr_referred_by.uri);
		cout << endl;
	}

	cout << endl;
	cout.flush();
}

void t_userintf::cb_retrieve_referrer(t_user *user_config, int line) {
	if (line >= NUM_USER_LINES) return;
	
	const t_call_info call_info = phone->get_call_info(line);

	cout << endl;
	cout << "Line " << line + 1 << ": call transfer failed.\n";
	cout << "Retrieving call: \n";
	cout << "From:    ";
	cout << format_sip_address(user_config, call_info.from_display, call_info.from_uri);
	cout << endl;
	if (!call_info.from_organization.empty()) {
		cout << "         " << call_info.from_organization;
		cout << endl;
	}
	cout << "To:      ";
	cout << format_sip_address(user_config, call_info.to_display, call_info.to_uri);
	cout << endl;
	if (!call_info.to_organization.empty()) {
		cout << "         " << call_info.to_organization;
		cout << endl;
	}
	cout << "Subject: ";
	cout << call_info.subject;
	cout << endl << endl;
	cout.flush();
}

void t_userintf::cb_consultation_call_setup(t_user *user_config, int line) {
	if (line >= NUM_USER_LINES) return;
	
	const t_call_info call_info = phone->get_call_info(line);

	cout << endl;
	cout << "Line " << line + 1 << ": setup consultation call.\n";
	cout << "From:    ";
	cout << format_sip_address(user_config, call_info.from_display, call_info.from_uri);
	cout << endl;
	if (!call_info.from_organization.empty()) {
		cout << "         " << call_info.from_organization;
		cout << endl;
	}
	cout << "To:      ";
	cout << format_sip_address(user_config, call_info.to_display, call_info.to_uri);
	cout << endl;
	if (!call_info.to_organization.empty()) {
		cout << "         " << call_info.to_organization;
		cout << endl;
	}
	cout << "Subject: ";
	cout << call_info.subject;
	cout << endl << endl;
	cout.flush();
}

void t_userintf::cb_stun_failed(t_user *user_config, int err_code, const string &err_reason) {
	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", STUN request failed: ";
	cout << err_code << " " << err_reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_stun_failed(t_user *user_config) {
	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", STUN request failed.\n";
	cout << endl;
	cout.flush();
}


bool t_userintf::cb_ask_user_to_redirect_invite(t_user *user_config, 
		const t_url &destination, const string &display)
{
	// Cannot ask user for permission in CLI, so deny redirection.
	return false;
}

bool t_userintf::cb_ask_user_to_redirect_request(t_user *user_config, 
		const t_url &destination, const string &display, t_method method)
{
	// Cannot ask user for permission in CLI, so deny redirection.
	return false;
}

bool t_userintf::cb_ask_credentials(t_user *user_config, 
		const string &realm, string &username, string &password)
{
	// Cannot ask user for username/password in CLI
	return false;
}

void t_userintf::cb_ask_user_to_refer(t_user *user_config, 
			const t_url &refer_to_uri,
			const string &refer_to_display,
			const t_url &referred_by_uri,
			const string &referred_by_display)
{
	// Cannot ask user for permission in CLI, so deny REFER
	send_refer_permission(false);
}

void t_userintf::send_refer_permission(bool permission) {
	evq_trans_layer->push_refer_permission_response(permission);
}

void t_userintf::cb_show_msg(const string &msg, t_msg_priority prio) {
	cout << endl;

	switch (prio) {
	case MSG_NO_PRIO:
		break;
	case MSG_INFO:
		cout << "Info: ";
		break;
	case MSG_WARNING:
		cout << "Warning: ";
		break;
	case MSG_CRITICAL:
		cout << "Critical: ";
		break;
	default:
		cout << "???: ";
	}

	cout << msg << endl;

	cout << endl;
	cout.flush();
}

bool t_userintf::cb_ask_msg(const string &msg, t_msg_priority prio) {
	// Cannot ask questions in CLI mode.
	// Print message and return false
	cb_show_msg(msg, prio);
	return false;
}

void t_userintf::cb_display_msg(const string &msg, t_msg_priority prio) {
	// In CLI mode this is the same as cb_show_msg
	cb_show_msg(msg, prio);
}

void t_userintf::cb_async_display_msg(const string &msg, t_msg_priority prio) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_DISPLAY_MSG);
	MEMMAN_NEW(event);
	
	event->set_display_msg(msg, prio);
	evq_ui_events.push(event);
}

void t_userintf::cb_log_updated(bool log_zapped) {
	// In CLI mode there is no log viewer.
}

void t_userintf::cb_call_history_updated(void) {
	// In CLI mode there is no call history viewer.
}

void t_userintf::cb_missed_call(int num_missed_calls) {
	// In CLI mode there is no missed call indication.
}

void t_userintf::cb_nat_discovery_progress_start(int num_steps) {
	cout << endl;
	cout << "Firewall/NAT discovery in progress.\n";
	cout << "Please wait.\n";
	cout << endl;
}

void t_userintf::cb_nat_discovery_finished(void) {
	// Nothing to do in CLI mode.
}

void t_userintf::cb_nat_discovery_progress_step(int step) {
	// Nothing to do in CLI mode.
}

bool t_userintf::cb_nat_discovery_cancelled(void) {
	// User cannot cancel NAT discovery in CLI mode.
	return false;
}

void t_userintf::cb_line_encrypted(int line, bool encrypted, const string &cipher_mode) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	if (encrypted) {
		cout << "Line " << line + 1 << ": audio encryption enabled (";
		cout << cipher_mode << ").\n";
	} else {
		cout << "Line " << line + 1 << ": audio encryption disabled.\n";
	}
	cout << endl;
	cout.flush();
}

void t_userintf::cb_async_line_encrypted(int line, bool encrypted, const string &cipher_mode) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_LINE_ENCRYPTED);
	MEMMAN_NEW(event);
	
	event->set_line(line);
	event->set_encrypted(encrypted);
	event->set_cipher_mode(cipher_mode);	
	evq_ui_events.push(event);
}

void t_userintf::cb_show_zrtp_sas(int line, const string &sas) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": ZRTP SAS = " << sas << endl;
	cout << "Confirm the SAS if it is correct.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_async_show_zrtp_sas(int line, const string &sas) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_SHOW_ZRTP_SAS);
	MEMMAN_NEW(event);
	
	event->set_line(line);
	event->set_zrtp_sas(sas);
	evq_ui_events.push(event);
}

void t_userintf::cb_zrtp_confirm_go_clear(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": remote user disabled encryption.\n";
	cout << endl;
	cout.flush();
	
	phone->pub_zrtp_go_clear_ok(line);
}

void t_userintf::cb_async_zrtp_confirm_go_clear(int line) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_ZRTP_CONFIRM_GO_CLEAR);
	MEMMAN_NEW(event);
	
	event->set_line(line);
	evq_ui_events.push(event);
}

void t_userintf::cb_zrtp_sas_confirmed(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": SAS confirmed.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_zrtp_sas_confirmation_reset(int line) {
	if (line >= NUM_USER_LINES) return;
	
	cout << endl;
	cout << "Line " << line + 1 << ": SAS confirmation reset.\n";
	cout << endl;
	cout.flush();
}

void t_userintf::cb_update_mwi(void) {
	// Nothing to do in CLI mode.
}

void t_userintf::cb_mwi_subscribe_failed(t_user *user_config, t_response *r, bool first_failure) {
	// Only report the first failure in a sequence of failures
	if (!first_failure) return;

	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", MWI subscription failed: " << r->code << ' ' << r->reason << endl;
	cout << endl;
	cout.flush();
}

void t_userintf::cb_mwi_terminated(t_user *user_config, const string &reason) {
	cout << endl;
	cout << user_config->get_profile_name();
	cout << ", MWI subscription terminated: " << reason << endl;
	cout << endl;
	cout.flush();
}

bool t_userintf::cb_message_request(t_user *user_config, t_request *r) {
	cout << endl;
	cout << "Received message\n";
	cout << "From:\t\t";
	
	string from_party = format_sip_address(user_config, 
		r->hdr_from.get_display_presentation(), r->hdr_from.uri);
	cout << from_party << endl;

	if (r->hdr_organization.is_populated()) {
		cout << "Organization:\t" << r->hdr_organization.name << endl;
	}

	cout << "To:\t\t";
	cout << format_sip_address(user_config, r->hdr_to.display, r->hdr_to.uri) << endl;

	if (r->hdr_subject.is_populated()) {
		cout << "Subject:\t" << r->hdr_subject.subject << endl;
	}
	
	cout << endl;
	if (r->body && r->body->get_type() == BODY_PLAIN_TEXT)
	{
		t_sip_body_plain_text *sb = dynamic_cast<t_sip_body_plain_text *>(r->body);
		cout << sb->text << endl;
	} else if (r->body && r->body->get_type() == BODY_HTML_TEXT) {
		t_sip_body_html_text *sb = dynamic_cast<t_sip_body_html_text *>(r->body);
		cout << sb->text << endl;
	} else {
		cout << "Unsupported content type.\n";
	}

	cout << endl;
	cout.flush();
	
	// There are no session in CLI mode, so all messages are accepted.
	return true;
}

void t_userintf::cb_message_response(t_user *user_config, t_response *r, t_request *req) {
	if (r->is_success()) return;
	
	cout << endl;
	cout << "Failed to send MESSAGE.\n";
	cout << r->code << " " << r->reason << endl;
	
	cout << endl;
	cout.flush();	
}

void t_userintf::cb_im_iscomposing_request(t_user *user_config, t_request *r,
			im::t_composing_state state, time_t refresh)
{
	// Nothing to do in CLI mode
	return;
}

void t_userintf::cb_im_iscomposing_not_supported(t_user *user_config, t_response *r) {
	// Nothing to do in CLI mode
	return;
}

bool t_userintf::get_last_call_info(t_url &url, string &display,
			string &subject, t_user **user_config, bool &hide_user) const
{
	if (!last_called_url.is_valid()) return false;
	
	url = last_called_url;
	display = last_called_display;
	subject = last_called_subject;
	*user_config = phone->ref_user_profile(last_called_profile);
	hide_user = last_called_hide_user;
	
	return *user_config != NULL;
}

bool t_userintf::can_redial(void) const {
	return last_called_url.is_valid() && 
	       phone->ref_user_profile(last_called_profile) != NULL;
}

void t_userintf::cmd_call(const string &destination, bool immediate) {
	string s = "invite ";
	s += destination;
	exec_command(s);
}

void t_userintf::cmd_quit(void) {
	exec_command("quit");
}

void t_userintf::cmd_quit_async(void) {
	t_event_ui *event = new t_event_ui(TYPE_UI_CB_QUIT);
	MEMMAN_NEW(event);
	evq_ui_events.push(event);
}

void t_userintf::cmd_cli(const string &command, bool immediate) {
	exec_command(command, immediate);
}

void t_userintf::cmd_show(void) {
	// Do nothing in CLI mode.
}

void t_userintf::cmd_hide(void) {
	// Do nothing in CLI mode.
}

string t_userintf::get_name_from_abook(t_user *user_config, const t_url &u) {
	return ab_local->find_name(user_config, u);
}

void *process_events_main(void *arg) {
	ui->process_events();
	return NULL;
}

const list<string>& t_userintf::get_all_commands(void)
{
	return all_commands;
}