aboutsummaryrefslogtreecommitdiffstats
path: root/channels/chan_misdn.c
blob: 54ac7bec854f36bef3f222397eeed0322ea38580 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
/*
 * Asterisk -- An open source telephony toolkit.
 * 
 * Copyright (C) 2004 - 2006, Christian Richter
 *
 * Christian Richter <crich@beronet.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 *
 */

/*!
 * \file
 *
 * \brief the chan_misdn channel driver for Asterisk
 * \author Christian Richter <crich@beronet.com>
 *
 * \ingroup channel_drivers
 */

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision$")

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <sys/file.h>
#include <semaphore.h>

#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/logger.h"
#include "asterisk/module.h"
#include "asterisk/pbx.h"
#include "asterisk/options.h"
#include "asterisk/io.h"
#include "asterisk/frame.h"
#include "asterisk/translate.h"
#include "asterisk/cli.h"
#include "asterisk/musiconhold.h"
#include "asterisk/dsp.h"
#include "asterisk/translate.h"
#include "asterisk/config.h"
#include "asterisk/file.h"
#include "asterisk/callerid.h"
#include "asterisk/indications.h"
#include "asterisk/app.h"
#include "asterisk/features.h"
#include "asterisk/term.h"
#include "asterisk/sched.h"
#include "asterisk/stringfields.h"

#include "chan_misdn_config.h"
#include "isdn_lib.h"

char global_tracefile[BUFFERSIZE+1];


struct misdn_jb{
	int size;
	int upper_threshold;
	char *samples, *ok;
	int wp,rp;
	int state_empty;
	int state_full;
	int state_buffer;
	int bytes_wrote;
	ast_mutex_t mutexjb;
};



/* allocates the jb-structure and initialise the elements*/
struct misdn_jb *misdn_jb_init(int size, int upper_threshold);

/* frees the data and destroys the given jitterbuffer struct */
void misdn_jb_destroy(struct misdn_jb *jb);

/* fills the jitterbuffer with len data returns < 0 if there was an
error (bufferoverun). */
int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len);

/* gets len bytes out of the jitterbuffer if available, else only the
available data is returned and the return value indicates the number
of data. */
int misdn_jb_empty(struct misdn_jb *jb, char *data, int len);


enum misdn_chan_state {
	MISDN_NOTHING,		/*!< at beginning */
	MISDN_WAITING4DIGS, /*!<  when waiting for infos */
	MISDN_EXTCANTMATCH, /*!<  when asterisk couldnt match our ext */
	MISDN_DIALING, /*!<  when pbx_start */
	MISDN_PROGRESS, /*!<  we got a progress */
	MISDN_PROCEEDING, /*!<  we got a progress */
	MISDN_CALLING, /*!<  when misdn_call is called */
	MISDN_CALLING_ACKNOWLEDGE, /*!<  when we get SETUP_ACK */
	MISDN_ALERTING, /*!<  when Alerting */
	MISDN_BUSY, /*!<  when BUSY */
	MISDN_CONNECTED, /*!<  when connected */
	MISDN_PRECONNECTED, /*!<  when connected */
	MISDN_DISCONNECTED, /*!<  when connected */
	MISDN_RELEASED, /*!<  when connected */
	MISDN_BRIDGED, /*!<  when bridged */
	MISDN_CLEANING, /*!< when hangup from * but we were connected before */
	MISDN_HUNGUP_FROM_MISDN, /*!< when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
	MISDN_HUNGUP_FROM_AST, /*!< when DISCONNECT/RELEASE/REL_COMP came out of */
	/* misdn_hangup */
	MISDN_HOLDED, /*!< if this chan is holded */
	MISDN_HOLD_DISCONNECT /*!< if this chan is holded */
  
};

#define ORG_AST 1
#define ORG_MISDN 2

struct chan_list {
  
	char allowed_bearers[BUFFERSIZE+1];
	
	enum misdn_chan_state state;
	int need_queue_hangup;
	int need_hangup;
	int need_busy;
	
	int orginator;

	int norxtone;
	int notxtone; 

	int toggle_ec;
	
	int incoming_early_audio;

	int ignore_dtmf;

	int pipe[2];
	char ast_rd_buf[4096];
	struct ast_frame frame;

	int faxdetect; /* 0:no 1:yes 2:yes+nojump */
	int faxdetect_timeout;
	struct timeval faxdetect_tv;
	int faxhandled;

	int ast_dsp;

	int jb_len;
	int jb_upper_threshold;
	struct misdn_jb *jb;
	
	struct ast_dsp *dsp;
	struct ast_trans_pvt *trans;
  
	struct ast_channel * ast;

	int dummy;
  
	struct misdn_bchannel *bc;
	struct misdn_bchannel *holded_bc;

	unsigned int l3id;
	int addr;

	char context[BUFFERSIZE];

	int zero_read_cnt;
	int dropped_frame_cnt;

	int far_alerting;
	int other_pid;
	struct chan_list *other_ch;

	const struct tone_zone_sound *ts;
	
	int overlap_dial;
	int overlap_dial_task;
	ast_mutex_t overlap_tv_lock;
	struct timeval overlap_tv;
  
	struct chan_list *peer;
	struct chan_list *next;
	struct chan_list *prev;
	struct chan_list *first;
};



void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch);
void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch);

struct robin_list {
	char *group;
	int port;
	int channel;
	struct robin_list *next;
	struct robin_list *prev;
};
static struct robin_list *robin = NULL;



struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame);



static inline void free_robin_list_r (struct robin_list *r)
{
        if (r) {
                if (r->next) free_robin_list_r(r->next);
                if (r->group) free(r->group);
                free(r);
        }
}

static void free_robin_list ( void )
{
	free_robin_list_r(robin);
	robin = NULL;
}

static struct robin_list* get_robin_position (char *group) 
{
	struct robin_list *iter = robin;
	for (; iter; iter = iter->next) {
		if (!strcasecmp(iter->group, group))
			return iter;
	}
	struct robin_list *new = (struct robin_list *)calloc(1, sizeof(struct robin_list));
	new->group = strndup(group, strlen(group));
	new->channel = 1;
	if (robin) {
		new->next = robin;
		robin->prev = new;
	}
	robin = new;
	return robin;
}


/* the main schedule context for stuff like l1 watcher, overlap dial, ... */
static struct sched_context *misdn_tasks = NULL;
static pthread_t misdn_tasks_thread;

static int *misdn_ports;

static void chan_misdn_log(int level, int port, char *tmpl, ...);

static struct ast_channel *misdn_new(struct chan_list *cl, int state,  char *exten, char *callerid, int format, int port, int c);
static void send_digit_to_chan(struct chan_list *cl, char digit );

static void hangup_chan(struct chan_list *ch);
static int pbx_start_chan(struct chan_list *ch);


#define AST_CID_P(ast) ast->cid.cid_num
#define AST_BRIDGED_P(ast) ast_bridged_channel(ast) 
#define AST_LOAD_CFG ast_config_load
#define AST_DESTROY_CFG ast_config_destroy

#define MISDN_ASTERISK_TECH_PVT(ast) ast->tech_pvt
#define MISDN_ASTERISK_PVT(ast) 1

#include <asterisk/strings.h>

/* #define MISDN_DEBUG 1 */

static char *desc = "Channel driver for mISDN Support (Bri/Pri)";
static const char misdn_type[] = "mISDN";

static int tracing = 0 ;

static char **misdn_key_vector=NULL;
static int misdn_key_vector_size=0;

/* Only alaw and mulaw is allowed for now */
static int prefformat =  AST_FORMAT_ALAW ; /*  AST_FORMAT_SLINEAR ;  AST_FORMAT_ULAW | */

static int *misdn_debug;
static int *misdn_debug_only;
static int max_ports;

static int *misdn_in_calls;
static int *misdn_out_calls;


struct chan_list dummy_cl;

struct chan_list *cl_te=NULL;
ast_mutex_t cl_te_lock;

static enum event_response_e
cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data);

static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc, struct chan_list *ch);

static void cl_queue_chan(struct chan_list **list, struct chan_list *chan);
static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan);
static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc);
static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid);



static int dialtone_indicate(struct chan_list *cl);
static int hanguptone_indicate(struct chan_list *cl);
static int stop_indicate(struct chan_list *cl);

static int start_bc_tones(struct chan_list *cl);
static int stop_bc_tones(struct chan_list *cl);
static void release_chan(struct misdn_bchannel *bc);

static int misdn_set_opt_exec(struct ast_channel *chan, void *data);
static int misdn_facility_exec(struct ast_channel *chan, void *data);

int chan_misdn_jb_empty(struct misdn_bchannel *bc, char *buf, int len);


void debug_numplan(int port, int numplan, char *type);


int add_out_calls(int port);
int add_in_calls(int port);


static int update_ec_config(struct misdn_bchannel *bc);

/*************** Helpers *****************/

static struct chan_list * get_chan_by_ast(struct ast_channel *ast)
{
	struct chan_list *tmp;
  
	for (tmp=cl_te; tmp; tmp = tmp->next) {
		if ( tmp->ast == ast ) return tmp;
	}
  
	return NULL;
}

static struct chan_list * get_chan_by_ast_name(char *name)
{
	struct chan_list *tmp;
  
	for (tmp=cl_te; tmp; tmp = tmp->next) {
		if ( tmp->ast  && strcmp(tmp->ast->name,name) == 0) return tmp;
	}
  
	return NULL;
}



struct allowed_bearers {
	int cap;
	int val;
	char *name;
};

struct allowed_bearers allowed_bearers_array[]={
	{INFO_CAPABILITY_SPEECH,1,"speech"},
	{INFO_CAPABILITY_AUDIO_3_1K,2,"3_1khz"},
	{INFO_CAPABILITY_DIGITAL_UNRESTRICTED,4,"digital_unrestricted"},
	{INFO_CAPABILITY_DIGITAL_RESTRICTED,8,"digital_restriced"},
	{INFO_CAPABILITY_VIDEO,16,"video"}
};

static char *bearer2str(int cap) {
	static char *bearers[]={
		"Speech",
		"Audio 3.1k",
		"Unres Digital",
		"Res Digital",
		"Video",
		"Unknown Bearer"
	};
	
	switch (cap) {
	case INFO_CAPABILITY_SPEECH:
		return bearers[0];
		break;
	case INFO_CAPABILITY_AUDIO_3_1K:
		return bearers[1];
		break;
	case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
		return bearers[2];
		break;
	case INFO_CAPABILITY_DIGITAL_RESTRICTED:
		return bearers[3];
		break;
	case INFO_CAPABILITY_VIDEO:
		return bearers[4];
		break;
	default:
		return bearers[5];
		break;
	}
}


static void print_facility(struct FacParm *fac, struct misdn_bchannel *bc)
{
	switch (fac->Function) {
	case Fac_CD:
		chan_misdn_log(0,bc->port," --> calldeflect to: %s, screened: %s\n", fac->u.CDeflection.DeflectedToNumber,
					   fac->u.CDeflection.PresentationAllowed ? "yes" : "no");
		break;
	case Fac_AOCDCurrency:
		if (fac->u.AOCDcur.chargeNotAvailable)
			chan_misdn_log(0,bc->port," --> AOCD currency: charge not available\n");
		else if (fac->u.AOCDcur.freeOfCharge)
			chan_misdn_log(0,bc->port," --> AOCD currency: free of charge\n");
		else if (fac->u.AOCDchu.billingId >= 0)
			chan_misdn_log(0,bc->port," --> AOCD currency: currency:%s amount:%d multiplier:%d typeOfChargingInfo:%d billingId:%d\n",
						   fac->u.AOCDcur.currency, fac->u.AOCDcur.currencyAmount, fac->u.AOCDcur.multiplier,
						   (fac->u.AOCDcur.typeOfChargingInfo == 0) ? "subTotal" : "total", fac->u.AOCDcur.billingId);
		else
			chan_misdn_log(0,bc->port," --> AOCD currency: currency:%s amount:%d multiplier:%d typeOfChargingInfo:%d\n",
						   fac->u.AOCDcur.currency, fac->u.AOCDcur.currencyAmount, fac->u.AOCDcur.multiplier,
						   (fac->u.AOCDcur.typeOfChargingInfo == 0) ? "subTotal" : "total");
		break;
	case Fac_AOCDChargingUnit:
		if (fac->u.AOCDchu.chargeNotAvailable)
			chan_misdn_log(0,bc->port," --> AOCD charging unit: charge not available\n");
		else if (fac->u.AOCDchu.freeOfCharge)
			chan_misdn_log(0,bc->port," --> AOCD charging unit: free of charge\n");
		else if (fac->u.AOCDchu.billingId >= 0)
			chan_misdn_log(0,bc->port," --> AOCD charging unit: recordedUnits:%d typeOfChargingInfo:%s billingId:%d\n",
						   fac->u.AOCDchu.recordedUnits, (fac->u.AOCDchu.typeOfChargingInfo == 0) ? "subTotal" : "total", fac->u.AOCDchu.billingId);
		else
			chan_misdn_log(0,bc->port," --> AOCD charging unit: recordedUnits:%d typeOfChargingInfo:%s\n",
						   fac->u.AOCDchu.recordedUnits, (fac->u.AOCDchu.typeOfChargingInfo == 0) ? "subTotal" : "total");
		break;
	default:
		chan_misdn_log(0,bc->port," --> unknown\n");
	}
}

static void print_bearer(struct misdn_bchannel *bc) 
{
	
	chan_misdn_log(2, bc->port, " --> Bearer: %s\n",bearer2str(bc->capability));
	
	switch(bc->law) {
	case INFO_CODEC_ALAW:
		chan_misdn_log(2, bc->port, " --> Codec: Alaw\n");
		break;
	case INFO_CODEC_ULAW:
		chan_misdn_log(2, bc->port, " --> Codec: Ulaw\n");
		break;
	}
}
/*************** Helpers END *************/

static void sighandler(int sig)
{}

static void* misdn_tasks_thread_func (void *data)
{
	int wait;
	struct sigaction sa;

	sa.sa_handler = sighandler;
	sa.sa_flags = SA_NODEFER;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGUSR1);
	sigaction(SIGUSR1, &sa, NULL);
	
	sem_post((sem_t *)data);

	while (1) {
		wait = ast_sched_wait(misdn_tasks);
		if (wait < 0)
			wait = 8000;
		if (poll(NULL, 0, wait) < 0)
			chan_misdn_log(4, 0, "Waking up misdn_tasks thread\n");
		ast_sched_runq(misdn_tasks);
	}
	return NULL;
}

static void misdn_tasks_init (void)
{
	sem_t blocker;
	int i = 5;

	if (sem_init(&blocker, 0, 0)) {
		perror("chan_misdn: Failed to initialize semaphore!");
		exit(1);
	}

	chan_misdn_log(4, 0, "Starting misdn_tasks thread\n");
	
	misdn_tasks = sched_context_create();
	pthread_create(&misdn_tasks_thread, NULL, misdn_tasks_thread_func, &blocker);

	while (sem_wait(&blocker) && --i);
	sem_destroy(&blocker);
}

static void misdn_tasks_destroy (void)
{
	if (misdn_tasks) {
		chan_misdn_log(4, 0, "Killing misdn_tasks thread\n");
		if ( pthread_cancel(misdn_tasks_thread) == 0 ) {
			cb_log(4, 0, "Joining misdn_tasks thread\n");
			pthread_join(misdn_tasks_thread, NULL);
		}
		sched_context_destroy(misdn_tasks);
	}
}

static inline void misdn_tasks_wakeup (void)
{
	pthread_kill(misdn_tasks_thread, SIGUSR1);
}

static inline int _misdn_tasks_add_variable (int timeout, ast_sched_cb callback, void *data, int variable)
{
	int task_id;

	if (!misdn_tasks) {
		misdn_tasks_init();
	}
	task_id = ast_sched_add_variable(misdn_tasks, timeout, callback, data, variable);
	misdn_tasks_wakeup();

	return task_id;
}

static int misdn_tasks_add (int timeout, ast_sched_cb callback, void *data)
{
	return _misdn_tasks_add_variable(timeout, callback, data, 0);
}

static int misdn_tasks_add_variable (int timeout, ast_sched_cb callback, void *data)
{
	return _misdn_tasks_add_variable(timeout, callback, data, 1);
}

static void misdn_tasks_remove (int task_id)
{
	ast_sched_del(misdn_tasks, task_id);
}

static int misdn_l1_task (void *data)
{
	misdn_lib_isdn_l1watcher(*(int *)data);
	chan_misdn_log(5, *(int *)data, "L1watcher timeout\n");
	return 1;
}

static int misdn_overlap_dial_task (void *data)
{
	struct timeval tv_end, tv_now;
	int diff;
	struct chan_list *ch = (struct chan_list *)data;

	chan_misdn_log(4, ch->bc->port, "overlap dial task, chan_state: %d\n", ch->state);

	if (ch->state != MISDN_WAITING4DIGS) {
		ch->overlap_dial_task = -1;
		return 0;
	}
	
	ast_mutex_lock(&ch->overlap_tv_lock);
	tv_end = ch->overlap_tv;
	ast_mutex_unlock(&ch->overlap_tv_lock);
	
	tv_end.tv_sec += ch->overlap_dial;
	tv_now = ast_tvnow();

	diff = ast_tvdiff_ms(tv_end, tv_now);

	if (diff <= 100) {
		/* if we are 100ms near the timeout, we are satisfied.. */
		stop_indicate(ch);
		if (ast_exists_extension(ch->ast, ch->context, ch->bc->dad, 1, ch->bc->oad)) {
			ch->state=MISDN_DIALING;
			if (pbx_start_chan(ch) < 0) {
				chan_misdn_log(-1, ch->bc->port, "ast_pbx_start returned < 0 in misdn_overlap_dial_task\n");
				goto misdn_overlap_dial_task_disconnect;
			}
		} else {
misdn_overlap_dial_task_disconnect:
			hanguptone_indicate(ch);
			if (ch->bc->nt)
				misdn_lib_send_event(ch->bc, EVENT_RELEASE_COMPLETE );
			else
				misdn_lib_send_event(ch->bc, EVENT_RELEASE);
		}
		ch->overlap_dial_task = -1;
		return 0;
	} else
		return diff;
}

static void send_digit_to_chan(struct chan_list *cl, char digit )
{
	static const char* dtmf_tones[] = {
		"!941+1336/100,!0/100",	/* 0 */
		"!697+1209/100,!0/100",	/* 1 */
		"!697+1336/100,!0/100",	/* 2 */
		"!697+1477/100,!0/100",	/* 3 */
		"!770+1209/100,!0/100",	/* 4 */
		"!770+1336/100,!0/100",	/* 5 */
		"!770+1477/100,!0/100",	/* 6 */
		"!852+1209/100,!0/100",	/* 7 */
		"!852+1336/100,!0/100",	/* 8 */
		"!852+1477/100,!0/100",	/* 9 */
		"!697+1633/100,!0/100",	/* A */
		"!770+1633/100,!0/100",	/* B */
		"!852+1633/100,!0/100",	/* C */
		"!941+1633/100,!0/100",	/* D */
		"!941+1209/100,!0/100",	/* * */
		"!941+1477/100,!0/100" };	/* # */
	struct ast_channel *chan=cl->ast; 
  
	if (digit >= '0' && digit <='9')
		ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
	else if (digit >= 'A' && digit <= 'D')
		ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
	else if (digit == '*')
		ast_playtones_start(chan,0,dtmf_tones[14], 0);
	else if (digit == '#')
		ast_playtones_start(chan,0,dtmf_tones[15], 0);
	else {
		/* not handled */
		ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
    
    
	}
}
/*** CLI HANDLING ***/
static int misdn_set_debug(int fd, int argc, char *argv[])
{
	if (argc != 4 && argc != 5 && argc != 6 && argc != 7)
		return RESULT_SHOWUSAGE; 

	int level = atoi(argv[3]);

	switch (argc) {
		case 4:	
		case 5: {
					int only = 0;
					if (argc == 5) {
						if (strncasecmp(argv[4], "only", strlen(argv[4])))
							return RESULT_SHOWUSAGE;
						else
							only = 1;
					}
					int i;
					for (i=0; i<=max_ports; i++) {
						misdn_debug[i] = level;
						misdn_debug_only[i] = only;
					}
					ast_cli(fd, "changing debug level for all ports to %d%s\n",misdn_debug[0], only?" (only)":"");
				}
				break;
		case 6: 
		case 7: {
					if (strncasecmp(argv[4], "port", strlen(argv[4])))
						return RESULT_SHOWUSAGE;
					int port = atoi(argv[5]);
					if (port <= 0 || port > max_ports) {
						switch (max_ports) {
							case 0:
								ast_cli(fd, "port number not valid! no ports available so you won't get lucky with any number here...\n");
								break;
							case 1:
								ast_cli(fd, "port number not valid! only port 1 is availble.\n");
								break;
							default:
								ast_cli(fd, "port number not valid! only ports 1 to %d are available.\n", max_ports);
							}
							return 0;
					}
					if (argc == 7) {
						if (strncasecmp(argv[6], "only", strlen(argv[6])))
							return RESULT_SHOWUSAGE;
						else
							misdn_debug_only[port] = 1;
					} else
						misdn_debug_only[port] = 0;
					misdn_debug[port] = level;
					ast_cli(fd, "changing debug level to %d%s for port %d\n", misdn_debug[port], misdn_debug_only[port]?" (only)":"", port);
				}
	}
	return 0;
}

static int misdn_set_crypt_debug(int fd, int argc, char *argv[])
{
	if (argc != 5) return RESULT_SHOWUSAGE; 

	return 0;
}


static int misdn_port_block(int fd, int argc, char *argv[])
{
	int port;
  
	if (argc != 4)
		return RESULT_SHOWUSAGE;
  
	port = atoi(argv[3]);

	misdn_lib_port_block(port);

	return 0;
}

static int misdn_port_unblock(int fd, int argc, char *argv[])
{
	int port;
  
	if (argc != 4)
		return RESULT_SHOWUSAGE;
  
	port = atoi(argv[3]);

	misdn_lib_port_unblock(port);

	return 0;
}


static int misdn_restart_port (int fd, int argc, char *argv[])
{
	int port;
  
	if (argc != 4)
		return RESULT_SHOWUSAGE;
  
	port = atoi(argv[3]);

	misdn_lib_port_restart(port);

	return 0;
}

static int misdn_port_up (int fd, int argc, char *argv[])
{
	int port;
	
	if (argc != 4)
		return RESULT_SHOWUSAGE;
	
	port = atoi(argv[3]);
	
	misdn_lib_get_port_up(port);
  
	return 0;
}

static int misdn_port_down (int fd, int argc, char *argv[])
{
	int port;
	
	if (argc != 4)
		return RESULT_SHOWUSAGE;
	
	port = atoi(argv[3]);
	
	misdn_lib_get_port_down(port);
  
	return 0;
}

static inline void show_config_description (int fd, enum misdn_cfg_elements elem)
{
	char section[BUFFERSIZE];
	char name[BUFFERSIZE];
	char desc[BUFFERSIZE];
	char def[BUFFERSIZE];
	char tmp[BUFFERSIZE];

	misdn_cfg_get_name(elem, tmp, sizeof(tmp));
	term_color(name, tmp, COLOR_BRWHITE, 0, sizeof(tmp));
	misdn_cfg_get_desc(elem, desc, sizeof(desc), def, sizeof(def));

	if (elem < MISDN_CFG_LAST)
		term_color(section, "PORTS SECTION", COLOR_YELLOW, 0, sizeof(section));
	else
		term_color(section, "GENERAL SECTION", COLOR_YELLOW, 0, sizeof(section));

	if (*def)
		ast_cli(fd, "[%s] %s   (Default: %s)\n\t%s\n", section, name, def, desc);
	else
		ast_cli(fd, "[%s] %s\n\t%s\n", section, name, desc);
}

static int misdn_show_config (int fd, int argc, char *argv[])
{
	char buffer[BUFFERSIZE];
	enum misdn_cfg_elements elem;
	int linebreak;
	int onlyport = -1;
	int ok = 0;

	if (argc >= 4) {
		if (!strcmp(argv[3], "description")) {
			if (argc == 5) {
				enum misdn_cfg_elements elem = misdn_cfg_get_elem (argv[4]);
				if (elem == MISDN_CFG_FIRST)
					ast_cli(fd, "Unknown element: %s\n", argv[4]);
				else
					show_config_description(fd, elem);
				return 0;
			}
			return RESULT_SHOWUSAGE;
		}
		if (!strcmp(argv[3], "descriptions")) {
			if ((argc == 4) || ((argc == 5) && !strcmp(argv[4], "general"))) {
				for (elem = MISDN_GEN_FIRST + 1; elem < MISDN_GEN_LAST; ++elem) {
					show_config_description(fd, elem);
					ast_cli(fd, "\n");
				}
				ok = 1;
			}
			if ((argc == 4) || ((argc == 5) && !strcmp(argv[4], "ports"))) {
				for (elem = MISDN_CFG_FIRST + 1; elem < MISDN_CFG_LAST - 1 /* the ptp hack, remove the -1 when ptp is gone */; ++elem) {
					show_config_description(fd, elem);
					ast_cli(fd, "\n");
				}
				ok = 1;
			}
			return ok ? 0 : RESULT_SHOWUSAGE;
		}
		if (!sscanf(argv[3], "%d", &onlyport) || onlyport < 0) {
			ast_cli(fd, "Unknown option: %s\n", argv[3]);
			return RESULT_SHOWUSAGE;
		}
	}
	
	if (argc == 3 || onlyport == 0) {
		ast_cli(fd,"Misdn General-Config: \n"); 
		ast_cli(fd," -> Version: chan_misdn-" CHAN_MISDN_VERSION "\n");
		for (elem = MISDN_GEN_FIRST + 1, linebreak = 1; elem < MISDN_GEN_LAST; elem++, linebreak++) {
			misdn_cfg_get_config_string( 0, elem, buffer, BUFFERSIZE);
			ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
		}
		ast_cli(fd, "\n");
	}

	if (onlyport < 0) {
		int port = misdn_cfg_get_next_port(0);
		for (; port > 0; port = misdn_cfg_get_next_port(port)) {
			ast_cli(fd, "\n[PORT %d]\n", port);
			for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
				misdn_cfg_get_config_string( port, elem, buffer, BUFFERSIZE);
				ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
			}	
			ast_cli(fd, "\n");
		}
	}
	
	if (onlyport > 0) {
		if (misdn_cfg_is_port_valid(onlyport)) {
			ast_cli(fd, "[PORT %d]\n", onlyport);
			for (elem = MISDN_CFG_FIRST + 1, linebreak = 1; elem < MISDN_CFG_LAST; elem++, linebreak++) {
				misdn_cfg_get_config_string(onlyport, elem, buffer, BUFFERSIZE);
				ast_cli(fd, "%-36s%s", buffer, !(linebreak % 2) ? "\n" : "");
			}	
			ast_cli(fd, "\n");
		} else {
			ast_cli(fd, "Port %d is not active!\n", onlyport);
		}
	}
	return 0;
}

struct state_struct {
	enum misdn_chan_state state;
	char txt[255] ;
} ;

static struct state_struct state_array[] = {
	{MISDN_NOTHING,"NOTHING"}, /* at beginning */
	{MISDN_WAITING4DIGS,"WAITING4DIGS"}, /*  when waiting for infos */
	{MISDN_EXTCANTMATCH,"EXTCANTMATCH"}, /*  when asterisk couldnt match our ext */
	{MISDN_DIALING,"DIALING"}, /*  when pbx_start */
	{MISDN_PROGRESS,"PROGRESS"}, /*  when pbx_start */
	{MISDN_PROCEEDING,"PROCEEDING"}, /*  when pbx_start */
	{MISDN_CALLING,"CALLING"}, /*  when misdn_call is called */
	{MISDN_CALLING_ACKNOWLEDGE,"CALLING_ACKNOWLEDGE"}, /*  when misdn_call is called */
	{MISDN_ALERTING,"ALERTING"}, /*  when Alerting */
	{MISDN_BUSY,"BUSY"}, /*  when BUSY */
	{MISDN_CONNECTED,"CONNECTED"}, /*  when connected */
	{MISDN_PRECONNECTED,"PRECONNECTED"}, /*  when connected */
	{MISDN_DISCONNECTED,"DISCONNECTED"}, /*  when connected */
	{MISDN_RELEASED,"RELEASED"}, /*  when connected */
	{MISDN_BRIDGED,"BRIDGED"}, /*  when bridged */
	{MISDN_CLEANING,"CLEANING"}, /* when hangup from * but we were connected before */
	{MISDN_HUNGUP_FROM_MISDN,"HUNGUP_FROM_MISDN"}, /* when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
	{MISDN_HOLDED,"HOLDED"}, /* when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
	{MISDN_HOLD_DISCONNECT,"HOLD_DISCONNECT"}, /* when DISCONNECT/RELEASE/REL_COMP  cam from misdn */
	{MISDN_HUNGUP_FROM_AST,"HUNGUP_FROM_AST"} /* when DISCONNECT/RELEASE/REL_COMP came out of */
	/* misdn_hangup */
};

static char *misdn_get_ch_state(struct chan_list *p) 
{
	int i;
	static char state[8];
	
	if( !p) return NULL;
  
	for (i=0; i< sizeof(state_array)/sizeof(struct state_struct); i++) {
		if ( state_array[i].state == p->state) return state_array[i].txt; 
	}

 	sprintf(state,"%d",p->state) ;

	return state;
}



static void reload_config(void)
{
	int i, cfg_debug;
	
	free_robin_list();
	misdn_cfg_reload();
	misdn_cfg_update_ptp();
	misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, global_tracefile, BUFFERSIZE);
	misdn_cfg_get( 0, MISDN_GEN_DEBUG, &cfg_debug, sizeof(int));

	for (i = 0;  i <= max_ports; i++) {
		misdn_debug[i] = cfg_debug;
		misdn_debug_only[i] = 0;
	}
}

static int misdn_reload (int fd, int argc, char *argv[])
{
	ast_cli(fd, "Reloading mISDN Config\n");
	reload_config();
	return 0;
}

static void print_bc_info (int fd, struct chan_list* help, struct misdn_bchannel* bc)
{
	struct ast_channel *ast=help->ast;
	ast_cli(fd,
		"* Pid:%d Prt:%d Ch:%d Mode:%s Org:%s dad:%s oad:%s rad:%s ctx:%s state:%s\n",

		bc->pid, bc->port, bc->channel,
		bc->nt?"NT":"TE",
		help->orginator == ORG_AST?"*":"I",
		ast?ast->exten:NULL,
		ast?AST_CID_P(ast):NULL,
		bc->rad,
		ast?ast->context:NULL,
		misdn_get_ch_state(help)
		);
	if (misdn_debug[bc->port] > 0)
		ast_cli(fd,
			"  --> astname: %s\n"
			"  --> ch_l3id: %x\n"
			"  --> ch_addr: %x\n"
			"  --> bc_addr: %x\n"
			"  --> bc_l3id: %x\n"
			"  --> display: %s\n"
			"  --> activated: %d\n"
			"  --> state: %s\n"
			"  --> capability: %s\n"
			"  --> echo_cancel: %d\n"
			"  --> notone : rx %d tx:%d\n"
			"  --> bc_hold: %d holded_bc :%d\n",
			help->ast->name,
			help->l3id,
			help->addr,
			bc->addr,
			bc?bc->l3_id:-1,
			bc->display,
			
			bc->active,
			bc_state2str(bc->bc_state),
			bearer2str(bc->capability),
			bc->ec_enable,

			help->norxtone,help->notxtone,
			bc->holded, help->holded_bc?1:0
			);
  
}

static int misdn_show_cls (int fd, int argc, char *argv[])
{
	struct chan_list *help=cl_te;
  
	ast_cli(fd,"Chan List: %p\n",cl_te); 
  
	for (;help; help=help->next) {
		struct misdn_bchannel *bc=help->bc;   
		struct ast_channel *ast=help->ast;
		if (misdn_debug[0] > 2) ast_cli(fd, "Bc:%p Ast:%p\n", bc, ast);
		if (bc) {
			print_bc_info(fd, help, bc);
		} else if ( (bc=help->holded_bc) ) {
			chan_misdn_log(0, 0, "ITS A HOLDED BC:\n");
			print_bc_info(fd, help,  bc);
		} else {
			ast_cli(fd,"* Channel in unknown STATE !!! Exten:%s, Callerid:%s\n", ast->exten, AST_CID_P(ast));
		}
	}
  
  
	return 0;
}

static int misdn_show_cl (int fd, int argc, char *argv[])
{
	struct chan_list *help=cl_te;

	if (argc != 4)
		return RESULT_SHOWUSAGE;
  
	for (;help; help=help->next) {
		struct misdn_bchannel *bc=help->bc;   
		struct ast_channel *ast=help->ast;
    
		if (bc && ast) {
			if (!strcasecmp(ast->name,argv[3])) {
				print_bc_info(fd, help, bc);
				break; 
			}
		} 
	}
  
  
	return 0;
}

ast_mutex_t lock;
int MAXTICS=8;

static int misdn_set_tics (int fd, int argc, char *argv[])
{
	if (argc != 4)
		return RESULT_SHOWUSAGE;
  
	MAXTICS=atoi(argv[3]);
  
	return 0;
}

static int misdn_show_stacks (int fd, int argc, char *argv[])
{
	int port;

	ast_cli(fd, "BEGIN STACK_LIST:\n");

	for (port=misdn_cfg_get_next_port(0); port > 0;
	     port=misdn_cfg_get_next_port(port)) {
		char buf[128];
		get_show_stack_details(port,buf);
		ast_cli(fd,"  %s  Debug:%d%s\n", buf, misdn_debug[port], misdn_debug_only[port]?"(only)":"");
	}
		
	return 0;
}


static int misdn_show_ports_stats (int fd, int argc, char *argv[])
{
	int port;

	ast_cli(fd, "Port\tin_calls\tout_calls\n");
	
	for (port=misdn_cfg_get_next_port(0); port > 0;
	     port=misdn_cfg_get_next_port(port)) {
		ast_cli(fd,"%d\t%d\t\t%d\n",port,misdn_in_calls[port],misdn_out_calls[port]);
	}
	ast_cli(fd,"\n");
	
	return 0;

}


static int misdn_show_port (int fd, int argc, char *argv[])
{
	int port;
	
	if (argc != 4)
		return RESULT_SHOWUSAGE;
  
	port = atoi(argv[3]);
  
	ast_cli(fd, "BEGIN STACK_LIST:\n");

	char buf[128];
	get_show_stack_details(port,buf);
	ast_cli(fd,"  %s  Debug:%d%s\n",buf, misdn_debug[port], misdn_debug_only[port]?"(only)":"");

	
	return 0;
}

static int misdn_send_cd (int fd, int argc, char *argv[])
{
	char *channame; 
	char *nr; 
  
	if (argc != 5)
		return RESULT_SHOWUSAGE;
  
	channame = argv[3];
	nr = argv[4];

	ast_cli(fd, "Sending Calldeflection (%s) to %s\n",nr, channame);
	
	{
		struct chan_list *tmp=get_chan_by_ast_name(channame);
		
		if (!tmp) {
			ast_cli(fd, "Sending CD with nr %s to %s failed: Channel does not exist.\n",nr, channame);
			return 0; 
		} else {
			if (strlen(nr) >= 15) {
				ast_cli(fd, "Sending CD with nr %s to %s failed: Number too long (up to 15 digits are allowed).\n",nr, channame);
				return 0; 
			}
			tmp->bc->fac_out.Function = Fac_CD;
			strncpy((char *)tmp->bc->fac_out.u.CDeflection.DeflectedToNumber, nr, sizeof(tmp->bc->fac_out.u.CDeflection.DeflectedToNumber));
			misdn_lib_send_event(tmp->bc, EVENT_FACILITY);
		}
	}
  
	return 0; 
}

static int misdn_send_digit (int fd, int argc, char *argv[])
{
	char *channame; 
	char *msg; 
  
	if (argc != 5)
		return RESULT_SHOWUSAGE;
  
	channame = argv[3];
	msg = argv[4];

	ast_cli(fd, "Sending %s to %s\n",msg, channame);
  
	{
		struct chan_list *tmp=get_chan_by_ast_name(channame);
    
		if (!tmp) {
			ast_cli(fd, "Sending %s to %s failed Channel does not exist\n",msg, channame);
			return 0; 
		} else {
#if 1
			int i;
			int msglen = strlen(msg);
			for (i=0; i<msglen; i++) {
				ast_cli(fd, "Sending: %c\n",msg[i]);
				send_digit_to_chan(tmp, msg[i]);
				/* res = ast_safe_sleep(tmp->ast, 250); */
				usleep(250000);
				/* res = ast_waitfor(tmp->ast,100); */
			}
#else
			int res;
			res = ast_dtmf_stream(tmp->ast,NULL,msg,250);
#endif
		}
	}
  
	return 0; 
}

static int misdn_toggle_echocancel (int fd, int argc, char *argv[])
{
	char *channame; 

	if (argc != 4)
		return RESULT_SHOWUSAGE;
	
	channame = argv[3];
  
	ast_cli(fd, "Toggling EchoCancel on %s\n", channame);
  
	{
		struct chan_list *tmp=get_chan_by_ast_name(channame);
    
		if (!tmp) {
			ast_cli(fd, "Toggling EchoCancel %s failed Channel does not exist\n", channame);
			return 0; 
		} else {
			
			tmp->toggle_ec=tmp->toggle_ec?0:1;

			if (tmp->toggle_ec) {
				update_ec_config(tmp->bc);
				manager_ec_enable(tmp->bc);
			} else {
				manager_ec_disable(tmp->bc);
			}
		}
	}
  
	return 0; 
}

static int misdn_send_display (int fd, int argc, char *argv[])
{
	char *channame; 
	char *msg; 
  
	if (argc != 5)
		return RESULT_SHOWUSAGE;
  
	channame = argv[3];
	msg = argv[4];

	ast_cli(fd, "Sending %s to %s\n",msg, channame);
	{
		struct chan_list *tmp;
		tmp=get_chan_by_ast_name(channame);
    
		if (tmp && tmp->bc) {
			ast_copy_string(tmp->bc->display, msg, sizeof(tmp->bc->display));
			misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
		} else {
			ast_cli(fd,"No such channel %s\n",channame);
			return RESULT_FAILURE;
		}
	}

	return RESULT_SUCCESS ;
}

static char *complete_ch_helper(const char *line, const char *word, int pos, int state, int rpos)
{
	struct ast_channel *c;
	int which=0;
	char *ret;
	if (pos != rpos)
		return NULL;
	c = ast_channel_walk_locked(NULL);
	while(c) {
		if (!strncasecmp(word, c->name, strlen(word))) {
			if (++which > state)
				break;
		}
		ast_mutex_unlock(&c->lock);
		c = ast_channel_walk_locked(c);
	}
	if (c) {
		ret = strdup(c->name);
		ast_mutex_unlock(&c->lock);
	} else
		ret = NULL;
	return ret;
}

static char *complete_ch(const char *line, const char *word, int pos, int state)
{
	return complete_ch_helper(line, word, pos, state, 3);
}

static char *complete_debug_port (const char *line, const char *word, int pos, int state)
{
	if (state)
		return NULL;

	switch (pos) {
	case 4: if (*word == 'p')
				return strdup("port");
			else if (*word == 'o')
				return strdup("only");
			break;
	case 6: if (*word == 'o')
				return strdup("only");
			break;
	}
	return NULL;
}

static char *complete_show_config (const char *line, const char *word, int pos, int state)
{
	char buffer[BUFFERSIZE];
	enum misdn_cfg_elements elem;
	int wordlen = strlen(word);
	int which = 0;
	int port = 0;

	switch (pos) {
	case 3: if ((!strncmp(word, "description", wordlen)) && (++which > state))
				return strdup("description");
			if ((!strncmp(word, "descriptions", wordlen)) && (++which > state))
				return strdup("descriptions");
			if ((!strncmp(word, "0", wordlen)) && (++which > state))
				return strdup("0");
			while ((port = misdn_cfg_get_next_port(port)) != -1) {
				snprintf(buffer, sizeof(buffer), "%d", port);
				if ((!strncmp(word, buffer, wordlen)) && (++which > state)) {
					return strdup(buffer);
				}
			}
			break;
	case 4:
			if (strstr(line, "description ")) {
				for (elem = MISDN_CFG_FIRST + 1; elem < MISDN_GEN_LAST; ++elem) {
					if ((elem == MISDN_CFG_LAST) || (elem == MISDN_GEN_FIRST))
						continue;
					misdn_cfg_get_name(elem, buffer, BUFFERSIZE);
					if (!wordlen || !strncmp(word, buffer, wordlen)) {
						if (++which > state)
							return strdup(buffer);
					}
				}
			} else if (strstr(line, "descriptions ")) {
				if ((!wordlen || !strncmp(word, "general", wordlen)) && (++which > state))
					return strdup("general");
				if ((!wordlen || !strncmp(word, "ports", wordlen)) && (++which > state))
					return strdup("ports");
			}
			break;
	}
	return NULL;
}

static struct ast_cli_entry chan_misdn_clis[] = {
	{ {"misdn","send","calldeflect", NULL}, misdn_send_cd, "Sends CallDeflection to mISDN Channel",
		"Usage: misdn send calldeflect <channel> \"<nr>\" \n", complete_ch },
	{ {"misdn","send","digit", NULL}, misdn_send_digit,	"Sends DTMF Digit to mISDN Channel",
		"Usage: misdn send digit <channel> \"<msg>\" \n"
		"       Send <digit> to <channel> as DTMF Tone\n"
		"       when channel is a mISDN channel\n", complete_ch },
	{ {"misdn","toggle","echocancel", NULL}, misdn_toggle_echocancel, "Toggles EchoCancel on mISDN Channel",
		"Usage: misdn toggle echocancel <channel>\n", complete_ch },
	{ {"misdn","send","display", NULL}, misdn_send_display, "Sends Text to mISDN Channel", 
		"Usage: misdn send display <channel> \"<msg>\" \n"
		"       Send <msg> to <channel> as Display Message\n"
		"       when channel is a mISDN channel\n", complete_ch },
	{ {"misdn","show","config", NULL}, misdn_show_config, "Shows internal mISDN config, read from cfg-file",
		"Usage: misdn show config [<port> | description <config element> | descriptions [general|ports]]\n"
		"       Use 0 for <port> to only print the general config.\n", complete_show_config },
	{ {"misdn","reload", NULL}, misdn_reload, "Reloads internal mISDN config, read from cfg-file",
		"Usage: misdn reload\n" },
	{ {"misdn","set","tics", NULL}, misdn_set_tics, "", 
		"\n" },
	{ {"misdn","show","channels", NULL}, misdn_show_cls, "Shows internal mISDN chan_list",
		"Usage: misdn show channels\n" },
	{ {"misdn","show","channel", NULL}, misdn_show_cl, "Shows internal mISDN chan_list",
		"Usage: misdn show channels\n", complete_ch },
	{ {"misdn","port","block", NULL}, misdn_port_block, "Blocks the given port",
		"Usage: misdn port block\n" },
	{ {"misdn","port","unblock", NULL}, misdn_port_unblock, "Unblocks the given port",
		"Usage: misdn port unblock\n" },
	{ {"misdn","restart","port", NULL}, misdn_restart_port, "Restarts the given port",
		"Usage: misdn restart port\n" },
	{ {"misdn","port","up", NULL}, misdn_port_up, "Tries to establish L1 on the given port",
		"Usage: misdn port up <port>\n" },
	{ {"misdn","port","down", NULL}, misdn_port_down, "Tries to deacivate the L1 on the given port",
		"Usage: misdn port down <port>\n" },
	{ {"misdn","show","stacks", NULL}, misdn_show_stacks, "Shows internal mISDN stack_list",
		"Usage: misdn show stacks\n" },
	{ {"misdn","show","ports","stats", NULL}, misdn_show_ports_stats, "Shows chan_misdns call statistics per port",
		"Usage: misdn show port stats\n" },
	{ {"misdn","show","port", NULL}, misdn_show_port, "Shows detailed information for given port",
		"Usage: misdn show port <port>\n" },
	{ {"misdn","set","debug", NULL}, misdn_set_debug, "Sets Debuglevel of chan_misdn",
		"Usage: misdn set debug <level> [only] | [port <port> [only]]\n", complete_debug_port },
	{ {"misdn","set","crypt","debug", NULL}, misdn_set_crypt_debug, "Sets CryptDebuglevel of chan_misdn, at the moment, level={1,2}",
		"Usage: misdn set crypt debug <level>\n" }
};


static int update_config (struct chan_list *ch, int orig) 
{
	if (!ch) {
		ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
		return -1;
	}
	
	struct ast_channel *ast=ch->ast;
	struct misdn_bchannel *bc=ch->bc;
	if (! ast || ! bc ) {
		ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
		return -1;
	}
	
	int port=bc->port;
	
	chan_misdn_log(5,port,"update_config: Getting Config\n");


	int hdlc=0;
	misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
	
	if (hdlc) {
		switch (bc->capability) {
		case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
		case INFO_CAPABILITY_DIGITAL_RESTRICTED:
			chan_misdn_log(1,bc->port," --> CONF HDLC\n");
			bc->hdlc=1;
			break;
		}
		
	}
	
	
	int pres, screen;
			
	misdn_cfg_get( port, MISDN_CFG_PRES, &pres, sizeof(int));
	misdn_cfg_get( port, MISDN_CFG_SCREEN, &screen, sizeof(int));
	chan_misdn_log(2,port," --> pres: %d screen: %d\n",pres, screen);
		
	if ( (pres + screen) < 0 ) {

		chan_misdn_log(2,port," --> pres: %x\n", ast->cid.cid_pres);
			
		switch (ast->cid.cid_pres & 0x60){
				
		case AST_PRES_RESTRICTED:
			bc->pres=1;
			chan_misdn_log(2, port, " --> PRES: Restricted (0x1)\n");
			break;
				
				
		case AST_PRES_UNAVAILABLE:
			bc->pres=2;
			chan_misdn_log(2, port, " --> PRES: Unavailable (0x2)\n");
			break;
				
		default:
			bc->pres=0;
			chan_misdn_log(2, port, " --> PRES: Allowed (0x0)\n");
		}
			
		switch (ast->cid.cid_pres & 0x3){
				
		case AST_PRES_USER_NUMBER_UNSCREENED:
			bc->screen=0;
			chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
			break;

		case AST_PRES_USER_NUMBER_PASSED_SCREEN:
			bc->screen=1;
			chan_misdn_log(2, port, " --> SCREEN: Passed Screen (0x1)\n");
			break;
		case AST_PRES_USER_NUMBER_FAILED_SCREEN:
			bc->screen=2;
			chan_misdn_log(2, port, " --> SCREEN: Failed Screen (0x2)\n");
			break;
				
		case AST_PRES_NETWORK_NUMBER:
			bc->screen=3;
			chan_misdn_log(2, port, " --> SCREEN: Network Nr. (0x3)\n");
			break;
				
		default:
			bc->screen=0;
			chan_misdn_log(2, port, " --> SCREEN: Unscreened (0x0)\n");
		}

			
	} else {
		bc->screen=screen;
		bc->pres=pres;
	}

	return 0;
	
}




static void config_jitterbuffer(struct chan_list *ch)
{
	struct misdn_bchannel *bc=ch->bc;
	int len=ch->jb_len, threshold=ch->jb_upper_threshold;
	
	chan_misdn_log(5,bc->port, "config_jb: Called\n");
	
	if ( ! len ) {
		chan_misdn_log(1,bc->port, "config_jb: Deactivating Jitterbuffer\n");
		bc->nojitter=1;
	} else {
		
		if (len <=100 || len > 8000) {
			chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer out of Bounds, setting to 1000\n");
			len=1000;
		}
		
		if ( threshold > len ) {
			chan_misdn_log(0,bc->port,"config_jb: Jitterbuffer Threshold > Jitterbuffer setting to Jitterbuffer -1\n");
		}
		
		if ( ch->jb) {
			cb_log(0,bc->port,"config_jb: We've got a Jitterbuffer Already on this port.\n");
			misdn_jb_destroy(ch->jb);
			ch->jb=NULL;
		}
		
		ch->jb=misdn_jb_init(len, threshold);

		if (!ch->jb ) 
			bc->nojitter=1;
	}
}


void debug_numplan(int port, int numplan, char *type)
{
	switch (numplan) {
	case NUMPLAN_INTERNATIONAL:
		chan_misdn_log(2, port, " --> %s: International\n",type);
		break;
	case NUMPLAN_NATIONAL:
		chan_misdn_log(2, port, " --> %s: National\n",type);
		break;
	case NUMPLAN_SUBSCRIBER:
		chan_misdn_log(2, port, " --> %s: Subscriber\n",type);
		break;
	case NUMPLAN_UNKNOWN:
		chan_misdn_log(2, port, " --> %s: Unknown\n",type);
		break;
		/* Maybe we should cut off the prefix if present ? */
	default:
		chan_misdn_log(0, port, " --> !!!! Wrong dialplan setting, please see the misdn.conf sample file\n ");
		break;
	}
}




static int update_ec_config(struct misdn_bchannel *bc)
{
	int ec;
	int port=bc->port;
		
	misdn_cfg_get( port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
	
	if (ec == 1 ) {
		bc->ec_enable=1;
	} else if ( ec > 1 ) {
		bc->ec_enable=1;
		bc->ec_deftaps=ec;
	}
#ifdef WITH_ECHOTRAINING 
	int ectr;
	misdn_cfg_get( port, MISDN_CFG_ECHOTRAINING, &ectr, sizeof(int));
	
	if ( ectr >= 0 ) {
		bc->ec_training=ectr;
	}
#endif

	return 0;
}


static int read_config(struct chan_list *ch, int orig) {

	if (!ch) {
		ast_log(LOG_WARNING, "Cannot configure without chanlist\n");
		return -1;
	}

	struct ast_channel *ast=ch->ast;
	struct misdn_bchannel *bc=ch->bc;
	if (! ast || ! bc ) {
		ast_log(LOG_WARNING, "Cannot configure without ast || bc\n");
		return -1;
	}
	
	int port=bc->port;
	
	chan_misdn_log(1,port,"read_config: Getting Config\n");

	char lang[BUFFERSIZE+1];
	

	misdn_cfg_get( port, MISDN_CFG_LANGUAGE, lang, BUFFERSIZE);
	ast_string_field_set(ast, language, lang);

	char localmusicclass[BUFFERSIZE+1];
	
	misdn_cfg_get( port, MISDN_CFG_MUSICCLASS, localmusicclass, BUFFERSIZE);
	ast_string_field_set(ast, musicclass, localmusicclass);
	
	
	misdn_cfg_get( port, MISDN_CFG_TXGAIN, &bc->txgain, sizeof(int));
	misdn_cfg_get( port, MISDN_CFG_RXGAIN, &bc->rxgain, sizeof(int));
	
	misdn_cfg_get( port, MISDN_CFG_INCOMING_EARLY_AUDIO, &ch->incoming_early_audio, sizeof(int));
	
	misdn_cfg_get( port, MISDN_CFG_SENDDTMF, &bc->send_dtmf, sizeof(int));

	misdn_cfg_get( port, MISDN_CFG_NEED_MORE_INFOS, &bc->need_more_infos, sizeof(int));
	
	misdn_cfg_get( port, MISDN_CFG_FAR_ALERTING, &ch->far_alerting, sizeof(int));

	misdn_cfg_get( port, MISDN_CFG_ALLOWED_BEARERS, &ch->allowed_bearers, BUFFERSIZE);
	
  	char faxdetect[BUFFERSIZE+1];
  	misdn_cfg_get( port, MISDN_CFG_FAXDETECT, faxdetect, BUFFERSIZE);
	
	int hdlc=0;
	misdn_cfg_get( port, MISDN_CFG_HDLC, &hdlc, sizeof(int));
	
	if (hdlc) {
		switch (bc->capability) {
		case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
		case INFO_CAPABILITY_DIGITAL_RESTRICTED:
			chan_misdn_log(1,bc->port," --> CONF HDLC\n");
			bc->hdlc=1;
			break;
		}
		
	}
	/*Initialize new Jitterbuffer*/
	{
		misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER, &ch->jb_len, sizeof(int));
		misdn_cfg_get( port, MISDN_CFG_JITTERBUFFER_UPPER_THRESHOLD, &ch->jb_upper_threshold, sizeof(int));
		
		config_jitterbuffer(ch);
	}
	
	misdn_cfg_get( bc->port, MISDN_CFG_CONTEXT, ch->context, sizeof(ch->context));
	
	ast_copy_string (ast->context,ch->context,sizeof(ast->context));	

	update_ec_config(bc);

	{
		int eb3;
		
		misdn_cfg_get( bc->port, MISDN_CFG_EARLY_BCONNECT, &eb3, sizeof(int));
		bc->early_bconnect=eb3;
	}
	
	port=bc->port;
	
	{
		char buf[256];
		ast_group_t pg,cg;
		
		misdn_cfg_get(port, MISDN_CFG_PICKUPGROUP, &pg, sizeof(pg));
		misdn_cfg_get(port, MISDN_CFG_CALLGROUP, &cg, sizeof(cg));
		
		chan_misdn_log(5, port, " --> * CallGrp:%s PickupGrp:%s\n",ast_print_group(buf,sizeof(buf),cg),ast_print_group(buf,sizeof(buf),pg));
		ast->pickupgroup=pg;
		ast->callgroup=cg;
	}
	
	if ( orig  == ORG_AST) {
		misdn_cfg_get( port, MISDN_CFG_TE_CHOOSE_CHANNEL, &(bc->te_choose_channel), sizeof(int));
		
 		if (strstr(faxdetect, "outgoing") || strstr(faxdetect, "both")) {
 			if (strstr(faxdetect, "nojump"))
 				ch->faxdetect=2;
 			else
 				ch->faxdetect=1;
 		}

		{
			char callerid[BUFFERSIZE+1];
			misdn_cfg_get( port, MISDN_CFG_CALLERID, callerid, BUFFERSIZE);
			if ( ! ast_strlen_zero(callerid) ) {
				chan_misdn_log(1, port, " --> * Setting Cid to %s\n", callerid);
				{
					int l = sizeof(bc->oad);
					strncpy(bc->oad,callerid, l);
					bc->oad[l-1] = 0;
				}

			}

			
			misdn_cfg_get( port, MISDN_CFG_DIALPLAN, &bc->dnumplan, sizeof(int));
			misdn_cfg_get( port, MISDN_CFG_LOCALDIALPLAN, &bc->onumplan, sizeof(int));
			misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
			debug_numplan(port, bc->dnumplan,"TON");
			debug_numplan(port, bc->onumplan,"LTON");
			debug_numplan(port, bc->cpnnumplan,"CTON");
		}

		ch->overlap_dial = 0;
	} else { /** ORIGINATOR MISDN **/
 		if (strstr(faxdetect, "incoming") || strstr(faxdetect, "both")) {
 			if (strstr(faxdetect, "nojump"))
 				ch->faxdetect=2;
 			else
 				ch->faxdetect=1;
 		}
	
		misdn_cfg_get( port, MISDN_CFG_CPNDIALPLAN, &bc->cpnnumplan, sizeof(int));
		debug_numplan(port, bc->cpnnumplan,"CTON");
		
		char prefix[BUFFERSIZE+1]="";
		switch( bc->onumplan ) {
		case NUMPLAN_INTERNATIONAL:
			misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
			break;
			
		case NUMPLAN_NATIONAL:
			misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
			break;
		default:
			break;
		}
		
		{
			int l = strlen(prefix) + strlen(bc->oad);
			char tmp[l+1];
			strcpy(tmp,prefix);
			strcat(tmp,bc->oad);
			strcpy(bc->oad,tmp);
		}
		
		if (!ast_strlen_zero(bc->dad)) {
			ast_copy_string(bc->orig_dad,bc->dad, sizeof(bc->orig_dad));
		}
		
		if ( ast_strlen_zero(bc->dad) && !ast_strlen_zero(bc->keypad)) {
			ast_copy_string(bc->dad,bc->keypad, sizeof(bc->dad));
		}

		prefix[0] = 0;
		
		switch( bc->dnumplan ) {
		case NUMPLAN_INTERNATIONAL:
			misdn_cfg_get( bc->port, MISDN_CFG_INTERNATPREFIX, prefix, BUFFERSIZE);
			break;
		case NUMPLAN_NATIONAL:
			misdn_cfg_get( bc->port, MISDN_CFG_NATPREFIX, prefix, BUFFERSIZE);
			break;
		default:
			break;
		}
		
		{
			int l = strlen(prefix) + strlen(bc->dad);
			char tmp[l+1];
			strcpy(tmp,prefix);
			strcat(tmp,bc->dad);
			strcpy(bc->dad,tmp);
		}
		
		if ( strcmp(bc->dad,ast->exten)) {
			ast_copy_string(ast->exten, bc->dad, sizeof(ast->exten));
		}
		
		ast_set_callerid(ast, bc->oad, NULL, bc->oad);
		
		if ( !ast_strlen_zero(bc->rad) ) {
			if (ast->cid.cid_rdnis)
				free(ast->cid.cid_rdnis);
			ast->cid.cid_rdnis = strdup(bc->rad);
		}
	
		misdn_cfg_get(bc->port, MISDN_CFG_OVERLAP_DIAL, &ch->overlap_dial, sizeof(ch->overlap_dial));
		ast_mutex_init(&ch->overlap_tv_lock);
	} /* ORIG MISDN END */

	ch->overlap_dial_task = -1;
	
	if (ch->faxdetect) {
		misdn_cfg_get( port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
		if (!ch->dsp)
			ch->dsp = ast_dsp_new();
		if (ch->dsp)
			ast_dsp_set_features(ch->dsp, DSP_FEATURE_DTMF_DETECT | DSP_FEATURE_FAX_DETECT);
		if (!ch->trans)
			ch->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
	}

	/* AOCD initialization */
	bc->AOCDtype = Fac_None;

	return 0;
}


/*****************************/
/*** AST Indications Start ***/
/*****************************/

static int misdn_call(struct ast_channel *ast, char *dest, int timeout)
{
	int port=0;
	int r;
	struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
	struct misdn_bchannel *newbc;
	char *opts=NULL, *ext,*tokb;
	char dest_cp[256];

	{
		strncpy(dest_cp,dest,sizeof(dest_cp)-1);
		dest_cp[sizeof(dest_cp)]=0;
		
		ext=strtok_r(dest_cp,"/",&tokb);
		
		if (ext) {
			ext=strtok_r(NULL,"/",&tokb);
			if (ext) {
				opts=strtok_r(NULL,"/",&tokb);
			} else {
				chan_misdn_log(0,0,"misdn_call: No Extension given!\n");
				return -1;
			}
		}
	}

	if (!ast) {
		ast_log(LOG_WARNING, " --> ! misdn_call called on ast_channel *ast where ast == NULL\n");
		return -1;
	}

	if (((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) || !dest  ) {
		ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
		ast->hangupcause=41;
		ast_setstate(ast, AST_STATE_DOWN);
		return -1;
	}

	if (!ch) {
		ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
		ast->hangupcause=41;
		ast_setstate(ast, AST_STATE_DOWN);
		return -1;
	}
	
	newbc=ch->bc;
	
	if (!newbc) {
		ast_log(LOG_WARNING, " --> ! misdn_call called on %s, neither down nor reserved (or dest==NULL)\n", ast->name);
		ast->hangupcause=41;
		ast_setstate(ast, AST_STATE_DOWN);
		return -1;
	}
	
	port=newbc->port;
	strncpy(newbc->dad,ext,sizeof( newbc->dad));
	strncpy(ast->exten,ext,sizeof(ast->exten));

	int exceed;
	if ((exceed=add_out_calls(port))) {
		char tmp[16];
		sprintf(tmp,"%d",exceed);
		pbx_builtin_setvar_helper(ast,"MAX_OVERFLOW",tmp);
		return -1;
	}
	
	chan_misdn_log(1, port, "* CALL: %s\n",dest);
	
	chan_misdn_log(1, port, " --> * dad:%s tech:%s ctx:%s\n",ast->exten,ast->name, ast->context);
	
	chan_misdn_log(3, port, " --> * adding2newbc ext %s\n",ast->exten);
	if (ast->exten) {
		int l = sizeof(newbc->dad);
		strncpy(newbc->dad,ast->exten, l);
		newbc->dad[l-1] = 0;
	}
	newbc->rad[0]=0;
	chan_misdn_log(3, port, " --> * adding2newbc callerid %s\n",AST_CID_P(ast));
	if (ast_strlen_zero(newbc->oad) && AST_CID_P(ast) ) {

		if (AST_CID_P(ast)) {
			int l = sizeof(newbc->oad);
			strncpy(newbc->oad,AST_CID_P(ast), l);
			newbc->oad[l-1] = 0;
		}
	}
	
	{
		struct chan_list *ch=MISDN_ASTERISK_TECH_PVT(ast);
		if (!ch) { ast_verbose("No chan_list in misdn_call"); return -1;}
		
		newbc->capability=ast->transfercapability;
		pbx_builtin_setvar_helper(ast,"TRANSFERCAPABILITY",ast_transfercapability2str(newbc->capability));
		if ( ast->transfercapability == INFO_CAPABILITY_DIGITAL_UNRESTRICTED) {
			chan_misdn_log(2, port, " --> * Call with flag Digital\n");
		}
		

		/* update screening and presentation */ 
		update_config(ch,ORG_AST);
		
		/* fill in some ies from channel vary*/
		import_ch(ast, newbc, ch);
		
		/* Finally The Options Override Everything */
		if (opts)
			misdn_set_opt_exec(ast,opts);
		else
			chan_misdn_log(2,port,"NO OPTS GIVEN\n");
		
		ch->state=MISDN_CALLING;
		
		r=misdn_lib_send_event( newbc, EVENT_SETUP );
		
		/** we should have l3id after sending setup **/
		ch->l3id=newbc->l3_id;
	}
	
	if ( r == -ENOCHAN  ) {
		chan_misdn_log(0, port, " --> * Theres no Channel at the moment .. !\n");
		chan_misdn_log(1, port, " --> * SEND: State Down pid:%d\n",newbc?newbc->pid:-1);
		ast->hangupcause=34;
		ast_setstate(ast, AST_STATE_DOWN);
		return -1;
	}
	
	chan_misdn_log(1, port, " --> * SEND: State Dialing pid:%d\n",newbc?newbc->pid:1);

	ast_setstate(ast, AST_STATE_DIALING);
	ast->hangupcause=16;
	
	if (newbc->nt) stop_bc_tones(ch);
	
	return 0; 
}


static int misdn_answer(struct ast_channel *ast)
{
	struct chan_list *p;

	
	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
	
	chan_misdn_log(1, p? (p->bc? p->bc->port : 0) : 0, "* ANSWER:\n");
	
	if (!p) {
		ast_log(LOG_WARNING, " --> Channel not connected ??\n");
		ast_queue_hangup(ast);
	}

	if (!p->bc) {
		chan_misdn_log(1, 0, " --> Got Answer, but theres no bc obj ??\n");

		ast_queue_hangup(ast);
	}

	{
		const char *tmp_key = pbx_builtin_getvar_helper(p->ast, "CRYPT_KEY");
		
		if (tmp_key ) {
			chan_misdn_log(1, p->bc->port, " --> Connection will be BF crypted\n");
			{
				int l = sizeof(p->bc->crypt_key);
				strncpy(p->bc->crypt_key,tmp_key, l);
				p->bc->crypt_key[l-1] = 0;
			}
		} else {
			chan_misdn_log(3, p->bc->port, " --> Connection is without BF encryption\n");
		}
    
	}

	{
		const char *nodsp=pbx_builtin_getvar_helper(ast, "MISDN_DIGITAL_TRANS");
		if (nodsp) {
			chan_misdn_log(1, p->bc->port, " --> Connection is transparent digital\n");
			p->bc->nodsp=1;
			p->bc->hdlc=0;
			p->bc->nojitter=1;
		}
	}
	
	p->state = MISDN_CONNECTED;
	misdn_lib_echo(p->bc,0);
	stop_indicate(p);

	if ( ast_strlen_zero(p->bc->cad) ) {
		chan_misdn_log(2,p->bc->port," --> empty cad using dad\n");
		ast_copy_string(p->bc->cad,p->bc->dad,sizeof(p->bc->cad));
	}

	misdn_lib_send_event( p->bc, EVENT_CONNECT);
	start_bc_tones(p);
	
	return 0;
}

static int misdn_digit(struct ast_channel *ast, char digit )
{
	struct chan_list *p;
	
	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) return -1;

	struct misdn_bchannel *bc=p->bc;
	chan_misdn_log(1, bc?bc->port:0, "* IND : Digit %c\n",digit);
	
	if (!bc) {
		ast_log(LOG_WARNING, " --> !! Got Digit Event withut having bchannel Object\n");
		return -1;
	}
	
	switch (p->state ) {
		case MISDN_CALLING:
		{
			
			char buf[8];
			buf[0]=digit;
			buf[1]=0;
			
			int l = sizeof(bc->infos_pending);
			strncat(bc->infos_pending,buf,l);
			bc->infos_pending[l-1] = 0;
		}
		break;
		case MISDN_CALLING_ACKNOWLEDGE:
		{
			bc->info_dad[0]=digit;
			bc->info_dad[1]=0;
			
			{
				int l = sizeof(bc->dad);
				strncat(bc->dad,bc->info_dad, l - strlen(bc->dad));
				bc->dad[l-1] = 0;
		}
			{
				int l = sizeof(p->ast->exten);
				strncpy(p->ast->exten, bc->dad, l);
				p->ast->exten[l-1] = 0;
			}
			
			misdn_lib_send_event( bc, EVENT_INFORMATION);
		}
		break;
		
		default:
			if ( bc->send_dtmf ) {
				send_digit_to_chan(p,digit);
			}
		break;
	}
	
	return 0;
}


static int misdn_fixup(struct ast_channel *oldast, struct ast_channel *ast)
{
	struct chan_list *p;
	
	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) )) return -1;
	
	chan_misdn_log(1, p->bc?p->bc->port:0, "* IND: Got Fixup State:%s L3id:%x\n", misdn_get_ch_state(p), p->l3id);
	
	p->ast = ast ;
	p->state=MISDN_CONNECTED;
  
	return 0;
}



static int misdn_indication(struct ast_channel *ast, int cond, const void *data, size_t datalen)
{
	struct chan_list *p;

  
	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast))) {
		ast_log(LOG_WARNING, "Returnded -1 in misdn_indication\n");
		return -1;
	}
	
	if (!p->bc ) {
		chan_misdn_log(1, 0, "* IND : Indication from %s\n",ast->exten);
		ast_log(LOG_WARNING, "Private Pointer but no bc ?\n");
		return -1;
	}
	
	chan_misdn_log(1, p->bc->port, "* IND : Indication [%d] from %s\n",cond, ast->exten);
	
	switch (cond) {
	case AST_CONTROL_BUSY:
		chan_misdn_log(1, p->bc->port, "* IND :\tbusy\n");
		chan_misdn_log(1, p->bc->port, " --> * SEND: State Busy pid:%d\n",p->bc?p->bc->pid:-1);
		ast_setstate(ast,AST_STATE_BUSY);

		p->bc->out_cause=17;
		if (p->state != MISDN_CONNECTED) {
			start_bc_tones(p);
			misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
		} else {
			chan_misdn_log(-1, p->bc->port, " --> !! Got Busy in Connected State !?! ast:%s\n", ast->name);
		}
		return -1;
		break;
	case AST_CONTROL_RING:
		chan_misdn_log(1, p->bc->port, " --> * IND :\tring pid:%d\n",p->bc?p->bc->pid:-1);
		return -1;
		break;
		
	case AST_CONTROL_RINGING:
		switch (p->state) {
			case MISDN_ALERTING:
				chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d but I was Ringing before, so ignoreing it\n",p->bc?p->bc->pid:-1);
				break;
			case MISDN_CONNECTED:
				chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d but Connected, so just send TONE_ALERTING without state changes \n",p->bc?p->bc->pid:-1);
				return -1;
				break;
			default:
				p->state=MISDN_ALERTING;
				chan_misdn_log(1, p->bc->port, " --> * IND :\tringing pid:%d\n",p->bc?p->bc->pid:-1);
				misdn_lib_send_event( p->bc, EVENT_ALERTING);
			
				if (p->other_ch && p->other_ch->bc) {
					if (misdn_inband_avail(p->other_ch->bc)) {
						chan_misdn_log(1,p->bc->port, " --> other End is mISDN and has inband info available\n");
						break;
					}

					if (!p->other_ch->bc->nt) {
						chan_misdn_log(1,p->bc->port, " --> other End is mISDN TE so it has inband info for sure (?)\n");
						break;
					}
				}

				chan_misdn_log(1, p->bc->port, " --> * SEND: State Ring pid:%d\n",p->bc?p->bc->pid:-1);
				ast_setstate(ast,AST_STATE_RINGING);
			
				if ( !p->bc->nt && (p->orginator==ORG_MISDN) && !p->incoming_early_audio ) 
					chan_misdn_log(1,p->bc->port, " --> incoming_early_audio off\n");
				else 
					return -1;
		}
		break;
	case AST_CONTROL_ANSWER:
		chan_misdn_log(1, p->bc->port, " --> * IND :\tanswer pid:%d\n",p->bc?p->bc->pid:-1);
		start_bc_tones(p);
		break;
	case AST_CONTROL_TAKEOFFHOOK:
		chan_misdn_log(1, p->bc->port, " --> *\ttakeoffhook pid:%d\n",p->bc?p->bc->pid:-1);
		return -1;
		break;
	case AST_CONTROL_OFFHOOK:
		chan_misdn_log(1, p->bc->port, " --> *\toffhook pid:%d\n",p->bc?p->bc->pid:-1);
		return -1;
		break; 
	case AST_CONTROL_FLASH:
		chan_misdn_log(1, p->bc->port, " --> *\tflash pid:%d\n",p->bc?p->bc->pid:-1);
		break;
	case AST_CONTROL_PROGRESS:
		chan_misdn_log(1, p->bc->port, " --> * IND :\tprogress pid:%d\n",p->bc?p->bc->pid:-1);
		misdn_lib_send_event( p->bc, EVENT_PROGRESS);
		break;
	case AST_CONTROL_PROCEEDING:
		chan_misdn_log(1, p->bc->port, " --> * IND :\tproceeding pid:%d\n",p->bc?p->bc->pid:-1);
		misdn_lib_send_event( p->bc, EVENT_PROCEEDING);
		break;
	case AST_CONTROL_CONGESTION:
		chan_misdn_log(1, p->bc->port, " --> * IND :\tcongestion pid:%d\n",p->bc?p->bc->pid:-1);

		p->bc->out_cause=42;
		if (p->state != MISDN_CONNECTED) {
			start_bc_tones(p);
			misdn_lib_send_event( p->bc, EVENT_RELEASE);
		} else {
			misdn_lib_send_event( p->bc, EVENT_DISCONNECT);
		}

		if (p->bc->nt) {
			hanguptone_indicate(p);
		}
		break;
	case -1 :
		chan_misdn_log(1, p->bc->port, " --> * IND :\t-1! (stop indication) pid:%d\n",p->bc?p->bc->pid:-1);
		
		stop_indicate(p);

		if (p->state == MISDN_CONNECTED) 
			start_bc_tones(p);

		break;

	case AST_CONTROL_HOLD:
		chan_misdn_log(1, p->bc->port, " --> *\tHOLD pid:%d\n",p->bc?p->bc->pid:-1);
		break;
	case AST_CONTROL_UNHOLD:
		chan_misdn_log(1, p->bc->port, " --> *\tUNHOLD pid:%d\n",p->bc?p->bc->pid:-1);
		break;
	default:
		ast_log(LOG_NOTICE, " --> * Unknown Indication:%d pid:%d\n",cond,p->bc?p->bc->pid:-1);
	}
  
	return 0;
}

static int misdn_hangup(struct ast_channel *ast)
{
	struct chan_list *p;
	struct misdn_bchannel *bc=NULL;
	
	if (!ast || ! (p=MISDN_ASTERISK_TECH_PVT(ast) ) ) return -1;
	
	ast_log(LOG_DEBUG, "misdn_hangup(%s)\n", ast->name);
	
	if (!p) {
		chan_misdn_log(3, 0, "misdn_hangup called, without chan_list obj.\n");
		return 0 ;
	}
	
	bc=p->bc;

	if (!bc) {
		ast_log(LOG_WARNING,"Hangup with private but no bc ?\n");
		return 0;
	}

	
	MISDN_ASTERISK_TECH_PVT(ast)=NULL;
	p->ast=NULL;

	bc=p->bc;
	
	if (ast->_state == AST_STATE_RESERVED) {
		/* between request and call */
		MISDN_ASTERISK_TECH_PVT(ast)=NULL;
		
		cl_dequeue_chan(&cl_te, p);
		free(p);
		
		if (bc)
			misdn_lib_release(bc);
		
		return 0;
	}

	p->need_hangup=0;
	p->need_queue_hangup=0;
	p->need_busy=0;


	if (!p->bc->nt) 
		stop_bc_tones(p);

	
	{
		const char *varcause=NULL;
		bc->out_cause=ast->hangupcause?ast->hangupcause:16;
		
		if ( (varcause=pbx_builtin_getvar_helper(ast, "HANGUPCAUSE")) ||
		     (varcause=pbx_builtin_getvar_helper(ast, "PRI_CAUSE"))) {
			int tmpcause=atoi(varcause);
			bc->out_cause=tmpcause?tmpcause:16;
		}
    
		chan_misdn_log(1, bc->port, "* IND : HANGUP\tpid:%d ctx:%s dad:%s oad:%s State:%s\n",p->bc?p->bc->pid:-1, ast->context, ast->exten, AST_CID_P(ast), misdn_get_ch_state(p));
		chan_misdn_log(2, bc->port, " --> l3id:%x\n",p->l3id);
		chan_misdn_log(1, bc->port, " --> cause:%d\n",bc->cause);
		chan_misdn_log(1, bc->port, " --> out_cause:%d\n",bc->out_cause);
		chan_misdn_log(1, bc->port, " --> state:%s\n", misdn_get_ch_state(p));
		
		switch (p->state) {
		case MISDN_CALLING:
			p->state=MISDN_CLEANING;
			misdn_lib_send_event( bc, EVENT_RELEASE_COMPLETE);
			break;
		case MISDN_HOLDED:
		case MISDN_DIALING:
			start_bc_tones(p);
			hanguptone_indicate(p);
		
			if (bc->need_disconnect)
				misdn_lib_send_event( bc, EVENT_DISCONNECT);
			break;

		case MISDN_CALLING_ACKNOWLEDGE:
			start_bc_tones(p);
			hanguptone_indicate(p);
		
			if (bc->need_disconnect)
				misdn_lib_send_event( bc, EVENT_DISCONNECT);
			break;
      
		case MISDN_ALERTING:
		case MISDN_PROGRESS:
		case MISDN_PROCEEDING:
			if (p->orginator != ORG_AST) 
				hanguptone_indicate(p);
      
			/*p->state=MISDN_CLEANING;*/
			if (bc->need_disconnect)
				misdn_lib_send_event( bc, EVENT_DISCONNECT);
			break;
		case MISDN_CONNECTED:
		case MISDN_PRECONNECTED:
			/*  Alerting or Disconect */
			if (p->bc->nt) {
				start_bc_tones(p);
				hanguptone_indicate(p);
				p->bc->progress_indicator=8;
			}
			if (bc->need_disconnect)
				misdn_lib_send_event( bc, EVENT_DISCONNECT);

			/*p->state=MISDN_CLEANING;*/
			break;
		case MISDN_DISCONNECTED:
			misdn_lib_send_event( bc, EVENT_RELEASE);
			p->state=MISDN_CLEANING; /* MISDN_HUNGUP_FROM_AST; */
			break;

		case MISDN_RELEASED:
		case MISDN_CLEANING:
			p->state=MISDN_CLEANING;
			break;

		case MISDN_BUSY:
			break;
      
		case MISDN_HOLD_DISCONNECT:
			/* need to send release here */
			chan_misdn_log(1, bc->port, " --> cause %d\n",bc->cause);
			chan_misdn_log(1, bc->port, " --> out_cause %d\n",bc->out_cause);
			
			bc->out_cause=-1;
			misdn_lib_send_event(bc,EVENT_RELEASE);
			p->state=MISDN_CLEANING;
			break;
		default:
			if (bc->nt) {
				bc->out_cause=-1;
				misdn_lib_send_event(bc, EVENT_RELEASE);
				p->state=MISDN_CLEANING; 
			} else {
				if (bc->need_disconnect)
					misdn_lib_send_event(bc, EVENT_DISCONNECT);
			}
		}

		p->state=MISDN_CLEANING;
    
	}
	

	chan_misdn_log(1, bc->port, "Channel: %s hanguped new state:%s\n",ast->name,misdn_get_ch_state(p));
	
	return 0;
}


struct ast_frame *process_ast_dsp(struct chan_list *tmp, struct ast_frame *frame)
{
	struct ast_frame *f,*f2;
 
 	if (tmp->trans) {
 		f2 = ast_translate(tmp->trans, frame, 0);
 		f = ast_dsp_process(tmp->ast, tmp->dsp, f2);
 	} else {
		chan_misdn_log(0, tmp->bc->port, "No T-Path found\n");
		return NULL;
	}

 
 	if (!f || (f->frametype != AST_FRAME_DTMF))
 		return frame;
 
 	ast_log(LOG_DEBUG, "Detected inband DTMF digit: %c", f->subclass);
 
 	if (tmp->faxdetect && (f->subclass == 'f')) {
 		/* Fax tone -- Handle and return NULL */
 		if (!tmp->faxhandled) {
  			struct ast_channel *ast = tmp->ast;
 			tmp->faxhandled++;
 			chan_misdn_log(0, tmp->bc->port, "Fax detected, preparing %s for fax transfer.\n", ast->name);
 			tmp->bc->rxgain = 0;
 			isdn_lib_update_rxgain(tmp->bc);
 			tmp->bc->txgain = 0;
 			isdn_lib_update_txgain(tmp->bc);
 			tmp->bc->ec_enable = 0;
 			isdn_lib_update_ec(tmp->bc);
 			isdn_lib_stop_dtmf(tmp->bc);
 			switch (tmp->faxdetect) {
 			case 1:
  				if (strcmp(ast->exten, "fax")) {
 					char *context;
 					char context_tmp[BUFFERSIZE];
 					misdn_cfg_get(tmp->bc->port, MISDN_CFG_FAXDETECT_CONTEXT, &context_tmp, sizeof(context_tmp));
 					context = ast_strlen_zero(context_tmp) ? (ast_strlen_zero(ast->macrocontext) ? ast->context : ast->macrocontext) : context_tmp;
 					if (ast_exists_extension(ast, context, "fax", 1, AST_CID_P(ast))) {
  						if (option_verbose > 2)
 							ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension (context:%s)\n", ast->name, context);
  						/* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
  						pbx_builtin_setvar_helper(ast,"FAXEXTEN",ast->exten);
 						if (ast_async_goto(ast, context, "fax", 1))
 							ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, context);
  					} else
 						ast_log(LOG_NOTICE, "Fax detected, but no fax extension ctx:%s exten:%s\n", context, ast->exten);
 				} else 
  					ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
 				break;
 			case 2:
 				ast_verbose(VERBOSE_PREFIX_3 "Not redirecting %s to fax extension, nojump is set.\n", ast->name);
 				break;
 			}
 		} else
 			ast_log(LOG_DEBUG, "Fax already handled\n");
  	}
 	
 	if (tmp->ast_dsp && (f->subclass != 'f')) {
 		chan_misdn_log(2, tmp->bc->port, " --> * SEND: DTMF (AST_DSP) :%c\n", f->subclass);
 	}

	return frame;
}


static struct ast_frame  *misdn_read(struct ast_channel *ast)
{
	struct chan_list *tmp;
	int len;
	
	if (!ast) {
		chan_misdn_log(1,0,"misdn_read called without ast\n");
		return NULL;
	}
 	if (!(tmp=MISDN_ASTERISK_TECH_PVT(ast))) {
		chan_misdn_log(1,0,"misdn_read called without ast->pvt\n");
		return NULL;
	}
	if (!tmp->bc) {
		chan_misdn_log(1,0,"misdn_read called without bc\n");
		return NULL;
	}

	len=read(tmp->pipe[0],tmp->ast_rd_buf,sizeof(tmp->ast_rd_buf));

	if (len<=0) {
		/* we hangup here, since our pipe is closed */
		chan_misdn_log(2,tmp->bc->port,"misdn_read: Pipe closed, hanging up\n");
		return NULL;
	}

	tmp->frame.frametype  = AST_FRAME_VOICE;
	tmp->frame.subclass = AST_FORMAT_ALAW;
	tmp->frame.datalen = len;
	tmp->frame.samples = len;
	tmp->frame.mallocd = 0;
	tmp->frame.offset = 0;
	tmp->frame.src = NULL;
	tmp->frame.data = tmp->ast_rd_buf;

	if (tmp->faxdetect && !tmp->faxhandled) {
		if (tmp->faxdetect_timeout) {
			if (ast_tvzero(tmp->faxdetect_tv)) {
				tmp->faxdetect_tv = ast_tvnow();
				chan_misdn_log(2,tmp->bc->port,"faxdetect: starting detection with timeout: %ds ...\n", tmp->faxdetect_timeout);
				return process_ast_dsp(tmp, &tmp->frame);
			} else {
				struct timeval tv_now = ast_tvnow();
				int diff = ast_tvdiff_ms(tv_now, tmp->faxdetect_tv);
				if (diff <= (tmp->faxdetect_timeout * 1000)) {
					chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ...\n");
					return process_ast_dsp(tmp, &tmp->frame);
				} else {
					chan_misdn_log(2,tmp->bc->port,"faxdetect: stopping detection (time ran out) ...\n");
					tmp->faxdetect = 0;
					return &tmp->frame;
				}
			}
		} else {
			chan_misdn_log(5,tmp->bc->port,"faxdetect: detecting ... (no timeout)\n");
			return process_ast_dsp(tmp, &tmp->frame);
		}
	} else {
		if (tmp->ast_dsp)
			return process_ast_dsp(tmp, &tmp->frame);
		else
			return &tmp->frame;
	}
}


static int misdn_write(struct ast_channel *ast, struct ast_frame *frame)
{
	struct chan_list *ch;
	int i  = 0;
	
	if (!ast || ! (ch=MISDN_ASTERISK_TECH_PVT(ast)) ) return -1;
	
	if (!ch->bc ) {
		ast_log(LOG_WARNING, "private but no bc\n");
		return -1;
	}
	
	if (ch->state == MISDN_HOLDED) {
		chan_misdn_log(7, ch->bc->port, "misdn_write: Returning because holded\n");
		return 0;
	}
	
	if (ch->notxtone) {
		chan_misdn_log(7, ch->bc->port, "misdn_write: Returning because notxone\n");
		return 0;
	}


	if ( !frame->subclass) {
		chan_misdn_log(4, ch->bc->port, "misdn_write: * prods us\n");
		return 0;
	}
	
	if ( !(frame->subclass & prefformat)) {
		
		chan_misdn_log(-1, ch->bc->port, "Got Unsupported Frame with Format:%d\n", frame->subclass);
		return 0;
	}
	

	if ( !frame->samples ) {
		chan_misdn_log(4, ch->bc->port, "misdn_write: zero write\n");
		return 0;
	}

	if ( ! ch->bc->addr ) {
		chan_misdn_log(8, ch->bc->port, "misdn_write: no addr for bc dropping:%d\n", frame->samples);
		return 0;
	}
	
#if MISDN_DEBUG
	{
		int i, max=5>frame->samples?frame->samples:5;
		
		printf("write2mISDN %p %d bytes: ", p, frame->samples);
		
		for (i=0; i<  max ; i++) printf("%2.2x ",((char*) frame->data)[i]);
		printf ("\n");
	}
#endif


	switch (ch->bc->bc_state) {
		case BCHAN_ACTIVATED:
		case BCHAN_BRIDGED:
			break;
		default:
		if (!ch->dropped_frame_cnt)
			chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x exten:%s cid:%s ch->state:%s bc_state:%d\n",frame->samples,ch->bc->addr, ast->exten, ast->cid.cid_num,misdn_get_ch_state( ch), ch->bc->bc_state);
		
		ch->dropped_frame_cnt++;
		if (ch->dropped_frame_cnt > 100) {
			ch->dropped_frame_cnt=0;
			chan_misdn_log(5, ch->bc->port, "BC not active (nor bridged) droping: %d frames addr:%x  dropped > 100 frames!\n",frame->samples,ch->bc->addr);

		}

		return 0;
	}

	chan_misdn_log(9, ch->bc->port, "Sending :%d bytes 2 MISDN\n",frame->samples);
	if ( !ch->bc->nojitter && misdn_cap_is_speech(ch->bc->capability) ) {
		/* Buffered Transmit (triggert by read from isdn side)*/
		if (misdn_jb_fill(ch->jb,frame->data,frame->samples) < 0) {
			if (ch->bc->active)
				cb_log(0,ch->bc->port,"Misdn Jitterbuffer Overflow.\n");
		}
		
	} else {
		/*transmit without jitterbuffer*/
		i=misdn_lib_tx2misdn_frm(ch->bc, frame->data, frame->samples);
	}

	
	
	return 0;
}




static enum ast_bridge_result  misdn_bridge (struct ast_channel *c0,
				      struct ast_channel *c1, int flags,
				      struct ast_frame **fo,
				      struct ast_channel **rc,
				      int timeoutms)

{
	struct chan_list *ch1,*ch2;
	struct ast_channel *carr[2], *who;
	int to=-1;
	struct ast_frame *f;
  
	ch1=get_chan_by_ast(c0);
	ch2=get_chan_by_ast(c1);

	carr[0]=c0;
	carr[1]=c1;
  
  
	if (ch1 && ch2 ) ;
	else
		return -1;
  

	int bridging;
	misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
	if (bridging) {
		int ecwb, ec;
		misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
		misdn_cfg_get( ch1->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
		if ( !ecwb && ec ) {
			chan_misdn_log(2, ch1->bc->port, "Disabling Echo Cancellor when Bridged\n");
			ch1->bc->ec_enable=0;
			manager_ec_disable(ch1->bc);
		}
		misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCELWHENBRIDGED, &ecwb, sizeof(int));
		misdn_cfg_get( ch2->bc->port, MISDN_CFG_ECHOCANCEL, &ec, sizeof(int));
		if ( !ecwb && ec) {
			chan_misdn_log(2, ch2->bc->port, "Disabling Echo Cancellor when Bridged\n");
			ch2->bc->ec_enable=0;
			manager_ec_disable(ch2->bc); 
		}
		
		/* trying to make a mISDN_dsp conference */
		chan_misdn_log(1, ch1->bc->port, "I SEND: Making conference with Number:%d\n", ch1->bc->pid +1);

		misdn_lib_bridge(ch1->bc,ch2->bc);
	}
	
	if (option_verbose > 2) 
		ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);

	chan_misdn_log(1, ch1->bc->port, "* Making Native Bridge between %s and %s\n", ch1->bc->oad, ch2->bc->oad);
 
	if (! (flags&AST_BRIDGE_DTMF_CHANNEL_0) )
		ch1->ignore_dtmf=1;

	if (! (flags&AST_BRIDGE_DTMF_CHANNEL_1) )
		ch2->ignore_dtmf=1;

	while(1) {
		to=-1;
		who = ast_waitfor_n(carr, 2, &to);

		if (!who) {
			ast_log(LOG_NOTICE,"misdn_bridge: empty read, breaking out\n");
			break;
		}
		f = ast_read(who);
    
		if (!f || f->frametype == AST_FRAME_CONTROL) {
			/* got hangup .. */

			if (!f) 
				chan_misdn_log(1,ch1->bc->port,"Read Null Frame\n");
			else
				chan_misdn_log(1,ch1->bc->port,"Read Frame Controll class:%d\n",f->subclass);
			
			*fo=f;
			*rc=who;
      
			break;
		}
		
		if ( f->frametype == AST_FRAME_DTMF ) {
			chan_misdn_log(1,0,"Read DTMF %d from %s\n",f->subclass, who->exten);

			*fo=f;
			*rc=who;
			break;
		}
		
		
		if (who == c0) {
			ast_write(c1,f);
		}
		else {
			ast_write(c0,f);
		}
    
	}
	
	chan_misdn_log(1, ch1->bc->port, "I SEND: Splitting conference with Number:%d\n", ch1->bc->pid +1);
	
	misdn_lib_split_bridge(ch1->bc,ch2->bc);
	
	
	return AST_BRIDGE_COMPLETE;
}

/** AST INDICATIONS END **/

static int dialtone_indicate(struct chan_list *cl)
{
	const struct tone_zone_sound *ts= NULL;
	struct ast_channel *ast=cl->ast;


	int nd=0;
	misdn_cfg_get( cl->bc->port, MISDN_CFG_NODIALTONE, &nd, sizeof(nd));

	if (nd) {
		chan_misdn_log(1,cl->bc->port,"Not sending Dialtone, because config wants it\n");
		return 0;
	}
	
	chan_misdn_log(3,cl->bc->port," --> Dial\n");
	ts=ast_get_indication_tone(ast->zone,"dial");
	cl->ts=ts;	
	
	if (ts) {
		cl->notxtone=0;
		cl->norxtone=0;
		ast_playtones_start(ast,0, ts->data, 0);
		chan_misdn_log(4,cl->bc->port,"Starting Playtones\n");
		misdn_lib_tone_generator_start(cl->bc);
	}

	return 0;
}

static int hanguptone_indicate(struct chan_list *cl)
{
	misdn_lib_send_tone(cl->bc,TONE_HANGUP);
	return 0;
}

static int stop_indicate(struct chan_list *cl)
{
	struct ast_channel *ast=cl->ast;
	chan_misdn_log(3,cl->bc->port," --> None\n");
	misdn_lib_tone_generator_stop(cl->bc);
	ast_playtones_stop(ast);
	/*ast_deactivate_generator(ast);*/
	
	return 0;
}


static int start_bc_tones(struct chan_list* cl)
{
	misdn_lib_tone_generator_stop(cl->bc);
	cl->notxtone=0;
	cl->norxtone=0;
	return 0;
}

static int stop_bc_tones(struct chan_list *cl)
{
	if (!cl) return -1;

	cl->notxtone=1;
	cl->norxtone=1;
	
	return 0;
}


static struct chan_list *init_chan_list(int orig)
{
	struct chan_list *cl=malloc(sizeof(struct chan_list));
	
	if (!cl) {
		chan_misdn_log(-1, 0, "misdn_request: malloc failed!");
		return NULL;
	}
	
	memset(cl,0,sizeof(struct chan_list));

	cl->orginator=orig;
	cl->need_queue_hangup=1;
	cl->need_hangup=1;
	cl->need_busy=1;
	cl->overlap_dial_task=-1;
	
	return cl;
	
}

static struct ast_channel *misdn_request(const char *type, int format, void *data, int *cause)

{
	struct ast_channel *tmp = NULL;
	char group[BUFFERSIZE+1]="";
	char buf[128];
	char buf2[128], *ext=NULL, *port_str;
	char *tokb=NULL, *p=NULL;
	int channel=0, port=0;
	struct misdn_bchannel *newbc = NULL;
	
	struct chan_list *cl=init_chan_list(ORG_AST);
	
	sprintf(buf,"%s/%s",misdn_type,(char*)data);
	ast_copy_string(buf2,data, 128);
	
	port_str=strtok_r(buf2,"/", &tokb);

	ext=strtok_r(NULL,"/", &tokb);

	if (port_str) {
		if (port_str[0]=='g' && port_str[1]==':' ) {
			/* We make a group call lets checkout which ports are in my group */
			port_str += 2;
			strncpy(group, port_str, BUFFERSIZE);
			group[127] = 0;
			chan_misdn_log(2, 0, " --> Group Call group: %s\n",group);
		} 
		else if ((p = strchr(port_str, ':'))) {
			/* we have a preselected channel */
			*p = 0;
			channel = atoi(++p);
			port = atoi(port_str);
			chan_misdn_log(2, port, " --> Call on preselected Channel (%d).\n", channel);
		}
		else {
			port = atoi(port_str);
		}
		
		
	} else {
		ast_log(LOG_WARNING, " --> ! IND : CALL dad:%s WITHOUT PORT/Group, check extension.conf\n",ext);
		return NULL;
	}

	if (!ast_strlen_zero(group)) {
	
		char cfg_group[BUFFERSIZE+1];
		struct robin_list *rr = NULL;

		if (misdn_cfg_is_group_method(group, METHOD_ROUND_ROBIN)) {
			chan_misdn_log(4, port, " --> STARTING ROUND ROBIN...");
			rr = get_robin_position(group);
		}
		
		if (rr) {
			int robin_channel = rr->channel;
			int port_start;
			int next_chan = 1;

			do {
				port_start = 0;
				for (port = misdn_cfg_get_next_port_spin(rr->port); port > 0 && port != port_start;
					 port = misdn_cfg_get_next_port_spin(port)) {

					if (!port_start)
						port_start = port;

					if (port >= port_start)
						next_chan = 1;
					
					if (port <= port_start && next_chan) {
						int maxbchans=misdn_lib_get_maxchans(port);
						if (++robin_channel >= maxbchans) {
							robin_channel = 1;
						}
						next_chan = 0;
					}

					misdn_cfg_get(port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);
					
					if (!strcasecmp(cfg_group, group)) {
						int port_up;
						int check;
						misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
						port_up = misdn_lib_port_up(port, check);

						if (check && !port_up) 
							chan_misdn_log(1,port,"L1 is not Up on this Port\n");
						
						if (check && port_up<0) {
							ast_log(LOG_WARNING,"This port (%d) is blocked\n", port);
						}
						
						
						if ( port_up>0 )	{
							newbc = misdn_lib_get_free_bc(port, robin_channel);
							if (newbc) {
								chan_misdn_log(4, port, " Success! Found port:%d channel:%d\n", newbc->port, newbc->channel);
								if (port_up)
									chan_misdn_log(4, port, "portup:%d\n",  port_up);
								rr->port = newbc->port;
								rr->channel = newbc->channel;
								break;
							}
						}
					}
				}
			} while (!newbc && robin_channel != rr->channel);
			
			if (!newbc)
				chan_misdn_log(-1, port, " Failed! No free channel in group %d!", group);
		}
		
		else {		
			for (port=misdn_cfg_get_next_port(0); port > 0;
				 port=misdn_cfg_get_next_port(port)) {
				
				misdn_cfg_get( port, MISDN_CFG_GROUPNAME, cfg_group, BUFFERSIZE);

				chan_misdn_log(3,port, "Group [%s] Port [%d]\n", group, port);
				if (!strcasecmp(cfg_group, group)) {
					int port_up;
					int check;
					misdn_cfg_get(port, MISDN_CFG_PMP_L1_CHECK, &check, sizeof(int));
					port_up = misdn_lib_port_up(port, check);
					
					chan_misdn_log(4, port, "portup:%d\n", port_up);
					
					if ( port_up>0 ) {
						newbc = misdn_lib_get_free_bc(port, 0);
						if (newbc)
							break;
					}
				}
			}
		}
		
	} else {
		if (channel)
			chan_misdn_log(1, port," --> preselected_channel: %d\n",channel);
		newbc = misdn_lib_get_free_bc(port, channel);
	}
	
	if (!newbc) {
		chan_misdn_log(-1, 0, "Could not create channel on port:%d with extensions:%s\n",port,ext);
		return NULL;
	}

	/* create ast_channel and link all the objects together */
	cl->bc=newbc;
	
	tmp = misdn_new(cl, AST_STATE_RESERVED, ext, NULL, format, port, channel);
	cl->ast=tmp;
	
	/* register chan in local list */
	cl_queue_chan(&cl_te, cl) ;
	
	/* fill in the config into the objects */
	read_config(cl, ORG_AST);

	/* important */
	cl->need_hangup=0;
	
	return tmp;
}


static int misdn_send_text (struct ast_channel *chan, const char *text)
{
	struct chan_list *tmp=chan->tech_pvt;
	
	if (tmp && tmp->bc) {
		ast_copy_string(tmp->bc->display,text,sizeof(tmp->bc->display));
		misdn_lib_send_event(tmp->bc, EVENT_INFORMATION);
	} else {
		ast_log(LOG_WARNING, "No chan_list but send_text request?\n");
		return -1;
	}
	
	return 0;
}

static struct ast_channel_tech misdn_tech = {
	.type="mISDN",
	.description="Channel driver for mISDN Support (Bri/Pri)",
	.capabilities= AST_FORMAT_ALAW ,
	.requester=misdn_request,
	.send_digit=misdn_digit,
	.call=misdn_call,
	.bridge=misdn_bridge, 
	.hangup=misdn_hangup,
	.answer=misdn_answer,
	.read=misdn_read,
	.write=misdn_write,
	.indicate=misdn_indication,
	.fixup=misdn_fixup,
	.send_text=misdn_send_text,
	.properties=0
};

static struct ast_channel_tech misdn_tech_wo_bridge = {
	.type="mISDN",
	.description="Channel driver for mISDN Support (Bri/Pri)",
	.capabilities=AST_FORMAT_ALAW ,
	.requester=misdn_request,
	.send_digit=misdn_digit,
	.call=misdn_call,
	.hangup=misdn_hangup,
	.answer=misdn_answer,
	.read=misdn_read,
	.write=misdn_write,
	.indicate=misdn_indication,
	.fixup=misdn_fixup,
	.send_text=misdn_send_text,
	.properties=0
};


static int glob_channel=0;

static void update_name(struct ast_channel *tmp, int port, int c) 
{
	int chan_offset=0;
	int tmp_port = misdn_cfg_get_next_port(0);
	for (; tmp_port > 0; tmp_port=misdn_cfg_get_next_port(tmp_port)) {
	if (tmp_port == port) break;
		chan_offset+=misdn_lib_port_is_pri(tmp_port)?30:2;	
	}
	if (c<0) c=0;

	ast_string_field_build(tmp, name, "%s/%d-u%d",
				 misdn_type, chan_offset+c, glob_channel++);

	chan_misdn_log(3,port," --> updating channel name to [%s]\n",tmp->name);
	
}

static struct ast_channel *misdn_new(struct chan_list *chlist, int state,  char *exten, char *callerid, int format, int port, int c)
{
	struct ast_channel *tmp;
	
	tmp = ast_channel_alloc(1);
	
	if (tmp) {
		chan_misdn_log(2, 0, " --> * NEW CHANNEL dad:%s oad:%s\n",exten,callerid);
		
		update_name(tmp,port,c);
	
		tmp->nativeformats = prefformat;

		tmp->readformat = format;
		tmp->rawreadformat = format;
		tmp->writeformat = format;
		tmp->rawwriteformat = format;
    
		tmp->tech_pvt = chlist;
		
		int bridging;
		misdn_cfg_get( 0, MISDN_GEN_BRIDGING, &bridging, sizeof(int));
		if (bridging)
			tmp->tech = &misdn_tech;
		else
			tmp->tech = &misdn_tech_wo_bridge;
		
		tmp->writeformat = format;
		tmp->readformat = format;
		tmp->priority=1;
		
		if (exten) 
			ast_copy_string(tmp->exten, exten,  sizeof(tmp->exten));
		else
			chan_misdn_log(1,0,"misdn_new: no exten given.\n");
		
		if (callerid) {
			char *cid_name, *cid_num;
      
			ast_callerid_parse(callerid, &cid_name, &cid_num);
			/* Don't use ast_set_callerid() here because it will
			 * generate a NewCallerID event before the NewChannel event */
			tmp->cid.cid_num = ast_strdup(cid_num);
			tmp->cid.cid_ani = ast_strdup(cid_num);
			tmp->cid.cid_name = ast_strdup(cid_name);
		}

		{
			if (pipe(chlist->pipe)<0)
				perror("Pipe failed\n");
			
			tmp->fds[0]=chlist->pipe[0];
			
		}
		
		ast_setstate(tmp, state);
		if (state == AST_STATE_RING)
			tmp->rings = 1;
		else
			tmp->rings = 0;
		
		
	} else {
		chan_misdn_log(-1,0,"Unable to allocate channel structure\n");
	}
	
	return tmp;
}

static struct chan_list *find_chan_by_bc(struct chan_list *list, struct misdn_bchannel *bc)
{
	struct chan_list *help=list;
	for (;help; help=help->next) {
		if (help->bc == bc) return help;
	}
  
	chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
  
	return NULL;
}

static struct chan_list *find_chan_by_pid(struct chan_list *list, int pid)
{
	struct chan_list *help=list;
	for (;help; help=help->next) {
		if (help->bc->pid == pid) return help;
	}
  
	chan_misdn_log(6, 0, "$$$ find_chan: No channel found for pid:%d\n",pid);
  
	return NULL;
}

static struct chan_list *find_holded(struct chan_list *list, struct misdn_bchannel *bc)
{
	struct chan_list *help=list;
	
	chan_misdn_log(6, bc->port, "$$$ find_holded: channel:%d oad:%s dad:%s\n",bc->channel, bc->oad,bc->dad);
	for (;help; help=help->next) {
		chan_misdn_log(4, bc->port, "$$$ find_holded: --> holded:%d channel:%d\n",help->bc->holded, help->bc->channel);
		if (help->bc->port == bc->port
		    && help->bc->holded ) return help;
	}
	
	chan_misdn_log(6, bc->port, "$$$ find_chan: No channel found for oad:%s dad:%s\n",bc->oad,bc->dad);
  
	return NULL;
}

static void cl_queue_chan(struct chan_list **list, struct chan_list *chan)
{
	chan_misdn_log(4, chan->bc? chan->bc->port : 0, "* Queuing chan %p\n",chan);
  
	ast_mutex_lock(&cl_te_lock);
	if (!*list) {
		*list = chan;
	} else {
		struct chan_list *help=*list;
		for (;help->next; help=help->next); 
		help->next=chan;
	}
	chan->next=NULL;
	ast_mutex_unlock(&cl_te_lock);
}

static void cl_dequeue_chan(struct chan_list **list, struct chan_list *chan) 
{
	if (chan->dsp) 
		ast_dsp_free(chan->dsp);
	if (chan->trans)
		ast_translator_free_path(chan->trans);

	

	ast_mutex_lock(&cl_te_lock);
	if (!*list) {
		ast_mutex_unlock(&cl_te_lock);
		return;
	}
  
	if (*list == chan) {
		*list=(*list)->next;
		ast_mutex_unlock(&cl_te_lock);
		return ;
	}
  
	{
		struct chan_list *help=*list;
		for (;help->next; help=help->next) {
			if (help->next == chan) {
				help->next=help->next->next;
				ast_mutex_unlock(&cl_te_lock);
				return;
			}
		}
	}
	
	ast_mutex_unlock(&cl_te_lock);
}

/** Channel Queue End **/


int pbx_start_chan(struct chan_list *ch)
{
	int ret=ast_pbx_start(ch->ast);	

	if (ret>=0) 
		ch->need_hangup=0;
	else
		ch->need_hangup=1;

	return ret;
}

static void hangup_chan(struct chan_list *ch)
{
	if (!ch) {
		cb_log(1,0,"Cannot hangup chan, no ch\n");
		return;
	}

	cb_log(1,ch->bc?ch->bc->port:0,"hangup_chan\n");

	if (ch->need_hangup) 
	{
		cb_log(1,ch->bc->port,"-> hangup\n");
		send_cause2ast(ch->ast,ch->bc,ch);
		ch->need_hangup=0;
		ch->need_queue_hangup=0;
		if (ch->ast)
			ast_hangup(ch->ast);
		return;
	}

	if (!ch->need_queue_hangup) {
		cb_log(1,ch->bc->port,"No need to queue hangup\n");
	}

	ch->need_queue_hangup=0;
	if (ch->ast) {
		send_cause2ast(ch->ast,ch->bc,ch);

		if (ch->ast)
			ast_queue_hangup(ch->ast);
		cb_log(1,ch->bc->port,"-> queue_hangup\n");
	} else {
		cb_log(1,ch->bc->port,"Cannot hangup chan, no ast\n");
	}
}

/** Isdn asks us to release channel, pendant to misdn_hangup **/
static void release_chan(struct misdn_bchannel *bc) {
	struct ast_channel *ast=NULL;
	{
		struct chan_list *ch=find_chan_by_bc(cl_te, bc);
		if (!ch)  {
			chan_misdn_log(0, bc->port, "release_chan: Ch not found!\n");
			return;
		}
		
		if (ch->ast) {
			ast=ch->ast;
		} 
		
		chan_misdn_log(1, bc->port, "release_chan: bc with l3id: %x\n",bc->l3_id);
		
		/*releaseing jitterbuffer*/
		if (ch->jb ) {
			misdn_jb_destroy(ch->jb);
			ch->jb=NULL;
		} else {
			if (!bc->nojitter)
				chan_misdn_log(5,bc->port,"Jitterbuffer already destroyed.\n");
		}

		if (ch->overlap_dial) {
			if (ch->overlap_dial_task != -1) {
				misdn_tasks_remove(ch->overlap_dial_task);
				ch->overlap_dial_task = -1;
			}
			ast_mutex_destroy(&ch->overlap_tv_lock);
		}

		if (ch->orginator == ORG_AST) {
			misdn_out_calls[bc->port]--;
		} else {
			misdn_in_calls[bc->port]--;
		}
		
		if (ch) {
			
			close(ch->pipe[0]);
			close(ch->pipe[1]);

			
			if (ast && MISDN_ASTERISK_TECH_PVT(ast)) {
				chan_misdn_log(1, bc->port, "* RELEASING CHANNEL pid:%d ctx:%s dad:%s oad:%s state: %s\n",bc?bc->pid:-1, ast->context, ast->exten,AST_CID_P(ast),misdn_get_ch_state(ch));
				chan_misdn_log(3, bc->port, " --> * State Down\n");
				MISDN_ASTERISK_TECH_PVT(ast)=NULL;
				
      
				if (ast->_state != AST_STATE_RESERVED) {
					chan_misdn_log(3, bc->port, " --> Setting AST State to down\n");
					ast_setstate(ast, AST_STATE_DOWN);
				}
			}
				
			ch->state=MISDN_CLEANING;
			cl_dequeue_chan(&cl_te, ch);
			
			free(ch);
		} else {
			/* chan is already cleaned, so exiting  */
		}
	}
}
/*** release end **/

static void misdn_transfer_bc(struct chan_list *tmp_ch, struct chan_list *holded_chan)
{
	chan_misdn_log(4,0,"TRANSFERING %s to %s\n",holded_chan->ast->name, tmp_ch->ast->name);
	
	tmp_ch->state=MISDN_HOLD_DISCONNECT;
  
	ast_moh_stop(AST_BRIDGED_P(holded_chan->ast));

	holded_chan->state=MISDN_CONNECTED;
	misdn_lib_transfer(holded_chan->bc?holded_chan->bc:holded_chan->holded_bc);
	ast_channel_masquerade(holded_chan->ast, AST_BRIDGED_P(tmp_ch->ast));
}


static void do_immediate_setup(struct misdn_bchannel *bc,struct chan_list *ch , struct ast_channel *ast)
{
	char predial[256]="";
	char *p = predial;
  
	struct ast_frame fr;
  
	strncpy(predial, ast->exten, sizeof(predial) -1 );
  
	ch->state=MISDN_DIALING;

	if (bc->nt) {
		int ret; 
		ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
	} else {
		int ret;
		if ( misdn_lib_is_ptp(bc->port)) {
			ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
		} else {
			ret = misdn_lib_send_event(bc, EVENT_PROCEEDING );
		}
	}

	if ( !bc->nt && (ch->orginator==ORG_MISDN) && !ch->incoming_early_audio ) 
		chan_misdn_log(1,bc->port, " --> incoming_early_audio off\n");
	 else  
		dialtone_indicate(ch);
  
	chan_misdn_log(1, bc->port, "* Starting Ast ctx:%s dad:%s oad:%s with 's' extension\n", ast->context, ast->exten, AST_CID_P(ast));
  
	strncpy(ast->exten,"s", 2);
  
	if (pbx_start_chan(ch)<0) {
		ast=NULL;
		hangup_chan(ch);
		hanguptone_indicate(ch);

		if (bc->nt)
			misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
		else
			misdn_lib_send_event(bc, EVENT_DISCONNECT );
	}
  
  
	while (!ast_strlen_zero(p) ) {
		fr.frametype = AST_FRAME_DTMF;
		fr.subclass = *p ;
		fr.src=NULL;
		fr.data = NULL ;
		fr.datalen = 0;
		fr.samples = 0 ;
		fr.mallocd =0 ;
		fr.offset= 0 ;

		if (ch->ast && MISDN_ASTERISK_PVT(ch->ast) && MISDN_ASTERISK_TECH_PVT(ch->ast)) {
			ast_queue_frame(ch->ast, &fr);
		}
		p++;
	}
}



static void send_cause2ast(struct ast_channel *ast, struct misdn_bchannel*bc, struct chan_list *ch) {
	if (!ast) {
		chan_misdn_log(1,0,"send_cause2ast: No Ast\n");
		return;
	}
	if (!bc) {
		chan_misdn_log(1,0,"send_cause2ast: No BC\n");
		return;
	}
	if (!ch) {
		chan_misdn_log(1,0,"send_cause2ast: No Ch\n");
		return;
	}
	
	ast->hangupcause=bc->cause;
	
	switch ( bc->cause) {
		
	case 1: /** Congestion Cases **/
	case 2:
	case 3:
 	case 4:
 	case 22:
 	case 27:
		/*
		 * Not Queueing the Congestion anymore, since we want to hear
		 * the inband message
		 *
		chan_misdn_log(1, bc?bc->port:0, " --> * SEND: Queue Congestion pid:%d\n", bc?bc->pid:-1);
		ch->state=MISDN_BUSY;
		
		ast_queue_control(ast, AST_CONTROL_CONGESTION);
		*/
		break;
		
	case 21:
	case 17: /* user busy */
	
		ch->state=MISDN_BUSY;
			
		if (!ch->need_busy) {
			chan_misdn_log(1,bc?bc->port:0, "Queued busy already\n");
			break;
		}
		
		chan_misdn_log(1,  bc?bc->port:0, " --> * SEND: Queue Busy pid:%d\n", bc?bc->pid:-1);
		
		ast_queue_control(ast, AST_CONTROL_BUSY);
		
		ch->need_busy=0;
		
		break;
	}
}




void import_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
{
	const char *tmp;
	tmp=pbx_builtin_getvar_helper(chan,"MISDN_PID");
	if (tmp) {
		ch->other_pid=atoi(tmp);
		chan_misdn_log(1,bc->port,"IMPORT_PID: importing pid:%s\n",tmp);
		if (ch->other_pid >0) {
			ch->other_ch=find_chan_by_pid(cl_te,ch->other_pid);
			if (ch->other_ch) ch->other_ch->other_ch=ch;
		}
	}
}

void export_ch(struct ast_channel *chan, struct misdn_bchannel *bc, struct chan_list *ch)
{
	char tmp[32];
	chan_misdn_log(1,bc->port,"EXPORT_PID: pid:%d\n",bc->pid);
	sprintf(tmp,"%d",bc->pid);
	pbx_builtin_setvar_helper(chan,"_MISDN_PID",tmp);
}

int add_in_calls(int port)
{
	int max_in_calls;
	
	misdn_cfg_get( port, MISDN_CFG_MAX_IN, &max_in_calls, sizeof(max_in_calls));

	misdn_in_calls[port]++;

	if (max_in_calls >=0 && max_in_calls<misdn_in_calls[port]) {
		ast_log(LOG_NOTICE,"Marking Incoming Call on port[%d]\n",port);
		return misdn_in_calls[port]-max_in_calls;
	}
	
	return 0;
}

int add_out_calls(int port)
{
	int max_out_calls;
	
	misdn_cfg_get( port, MISDN_CFG_MAX_OUT, &max_out_calls, sizeof(max_out_calls));
	

	if (max_out_calls >=0 && max_out_calls<=misdn_out_calls[port]) {
		ast_log(LOG_NOTICE,"Rejecting Outgoing Call on port[%d]\n",port);
		return (misdn_out_calls[port]+1)-max_out_calls;
	}

	misdn_out_calls[port]++;
	
	return 0;
}



/************************************************************/
/*  Receive Events from isdn_lib  here                     */
/************************************************************/
static enum event_response_e
cb_events(enum event_e event, struct misdn_bchannel *bc, void *user_data)
{
	struct chan_list *ch=find_chan_by_bc(cl_te, bc);
	
	if (event != EVENT_BCHAN_DATA && event != EVENT_TONE_GENERATE) { /*  Debug Only Non-Bchan */
		int debuglevel=1;
	
		if ( event==EVENT_CLEANUP && !user_data)
			debuglevel=5;

		chan_misdn_log(debuglevel, bc->port, "I IND :%s oad:%s dad:%s pid:%d state:%s\n", manager_isdn_get_info(event), bc->oad, bc->dad, bc->pid, ch?misdn_get_ch_state(ch):"none");
		if (debuglevel==1) {
			misdn_lib_log_ies(bc);
			chan_misdn_log(4,bc->port," --> bc_state:%s\n",bc_state2str(bc->bc_state));
		}
	}
	
	if (!ch) {
		switch(event) {
			case EVENT_SETUP:
			case EVENT_DISCONNECT:
			case EVENT_PORT_ALARM:
			case EVENT_RETRIEVE:
			case EVENT_NEW_BC:
			case EVENT_FACILITY:
				break;
			case EVENT_RELEASE_COMPLETE:
				chan_misdn_log(1, bc->port, " --> no Ch, so we've already released.\n");
				break;
			case EVENT_CLEANUP:
			case EVENT_TONE_GENERATE:
			case EVENT_BCHAN_DATA:
				return -1;

			default:
				chan_misdn_log(1,bc->port, "Chan not existing at the moment bc->l3id:%x bc:%p event:%s port:%d channel:%d\n",bc->l3_id, bc, manager_isdn_get_info( event), bc->port,bc->channel);
				return -1;
		}
	}
	
	if (ch ) {
		switch (event) {
		case EVENT_TONE_GENERATE:
		break;
		case EVENT_DISCONNECT:
		case EVENT_RELEASE:
		case EVENT_RELEASE_COMPLETE:
		case EVENT_CLEANUP:
		case EVENT_TIMEOUT:
			if (!ch->ast)
				chan_misdn_log(3,bc->port,"ast_hangup already called, so we have no ast ptr anymore in event(%s)\n",manager_isdn_get_info(event));
			break;
		default:
			if ( !ch->ast  || !MISDN_ASTERISK_PVT(ch->ast) || !MISDN_ASTERISK_TECH_PVT(ch->ast)) {
				if (event!=EVENT_BCHAN_DATA)
					ast_log(LOG_NOTICE, "No Ast or No private Pointer in Event (%d:%s)\n", event, manager_isdn_get_info(event));
				return -1;
			}
		}
	}
	
	
	switch (event) {
	case EVENT_PORT_ALARM:
		{
			int boa=0;
			misdn_cfg_get( bc->port, MISDN_CFG_ALARM_BLOCK, &boa, sizeof(int));
			if (boa) {
				cb_log(1,bc->port," --> blocking\n");
				misdn_lib_port_block(bc->port); 
			}
		}
	break;
	case EVENT_BCHAN_ACTIVATED:
		break;
		
	case EVENT_NEW_CHANNEL:
		update_name(ch->ast,bc->port,bc->channel);
		break;
		
	case EVENT_NEW_L3ID:
		ch->l3id=bc->l3_id;
		ch->addr=bc->addr;
		break;

	case EVENT_NEW_BC:
		if (!ch) {
			ch=find_holded(cl_te,bc);
		}
		
		if (!ch) {
			ast_log(LOG_WARNING,"NEW_BC without chan_list?\n");
			break;
		}

		if (bc)
			ch->bc=(struct misdn_bchannel*)user_data;
		break;
		
	case EVENT_DTMF_TONE:
	{
		/*  sending INFOS as DTMF-Frames :) */
		struct ast_frame fr;
		memset(&fr, 0 , sizeof(fr));
		fr.frametype = AST_FRAME_DTMF;
		fr.subclass = bc->dtmf ;
		fr.src=NULL;
		fr.data = NULL ;
		fr.datalen = 0;
		fr.samples = 0 ;
		fr.mallocd =0 ;
		fr.offset= 0 ;
		
		if (!ch->ignore_dtmf) {
			chan_misdn_log(2, bc->port, " --> DTMF:%c\n", bc->dtmf);
			ast_queue_frame(ch->ast, &fr);
		} else {
			chan_misdn_log(2, bc->port, " --> Ingoring DTMF:%c due to bridge flags\n", bc->dtmf);
		}
	}
	break;
	case EVENT_STATUS:
		break;
    
	case EVENT_INFORMATION:
	{
		int stop_tone;
		misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));
		if ( stop_tone ) {
			stop_indicate(ch);
		}
		
		if (ch->state == MISDN_WAITING4DIGS ) {
			/*  Ok, incomplete Setup, waiting till extension exists */
			{
				int l = sizeof(bc->dad);
				strncat(bc->dad,bc->info_dad, l);
				bc->dad[l-1] = 0;
			}
			
			
			{
				int l = sizeof(ch->ast->exten);
				strncpy(ch->ast->exten, bc->dad, l);
				ch->ast->exten[l-1] = 0;
			}
/*			chan_misdn_log(5, bc->port, "Can Match Extension: dad:%s oad:%s\n",bc->dad,bc->oad);*/
			
			/* Check for Pickup Request first */
			if (!strcmp(ch->ast->exten, ast_pickup_ext())) {
				int ret;/** Sending SETUP_ACK**/
				ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
				if (ast_pickup_call(ch->ast)) {
					hangup_chan(ch);
				} else {
					struct ast_channel *chan=ch->ast;
					ch->state = MISDN_CALLING_ACKNOWLEDGE;
					ast_setstate(chan, AST_STATE_DOWN);
					hangup_chan(ch);
					ch->ast=NULL;
					break;
				}
			}
			
			if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {

				chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");
				if (bc->nt)
					hanguptone_indicate(ch);
				ch->state=MISDN_EXTCANTMATCH;
				bc->out_cause=1;

				misdn_lib_send_event(bc, EVENT_DISCONNECT );

				break;
			}

			if (ch->overlap_dial) {
				ast_mutex_lock(&ch->overlap_tv_lock);
				ch->overlap_tv = ast_tvnow();
				ast_mutex_unlock(&ch->overlap_tv_lock);
				if (ch->overlap_dial_task == -1) {
					ch->overlap_dial_task = 
						misdn_tasks_add_variable(ch->overlap_dial, misdn_overlap_dial_task, ch);
				}
				break;
			}

			if (ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
				ch->state=MISDN_DIALING;
	  
				stop_indicate(ch);
/*				chan_misdn_log(1, bc->port, " --> * Starting Ast ctx:%s\n", ch->context);*/
				if (pbx_start_chan(ch)<0) {
					hangup_chan(ch);

					chan_misdn_log(-1, bc->port, "ast_pbx_start returned < 0 in INFO\n");
				 	if (bc->nt) hanguptone_indicate(ch);

					misdn_lib_send_event(bc, EVENT_DISCONNECT );
				}
			}
	
		} else {
			/*  sending INFOS as DTMF-Frames :) */
			struct ast_frame fr;
			fr.frametype = AST_FRAME_DTMF;
			fr.subclass = bc->info_dad[0] ;
			fr.src=NULL;
			fr.data = NULL ;
			fr.datalen = 0;
			fr.samples = 0 ;
			fr.mallocd =0 ;
			fr.offset= 0 ;

			
			int digits;
			misdn_cfg_get( 0, MISDN_GEN_APPEND_DIGITS2EXTEN, &digits, sizeof(int));
			if (ch->state != MISDN_CONNECTED ) {
				if (digits) {
					int l = sizeof(bc->dad);
					strncat(bc->dad,bc->info_dad, l);
					bc->dad[l-1] = 0;
					l = sizeof(ch->ast->exten);
					strncpy(ch->ast->exten, bc->dad, l);
					ch->ast->exten[l-1] = 0;

					ast_cdr_update(ch->ast);
				}
				
				ast_queue_frame(ch->ast, &fr);
			}
		}
	}
	break;
	case EVENT_SETUP:
	{
		struct chan_list *ch=find_chan_by_bc(cl_te, bc);
		if (ch && ch->state != MISDN_NOTHING ) {
			chan_misdn_log(1, bc->port, " --> Ignoring Call we have already one\n");
			return RESPONSE_IGNORE_SETUP_WITHOUT_CLOSE;
		}
	}
	

	int msn_valid = misdn_cfg_is_msn_valid(bc->port, bc->dad);
	if (!bc->nt && ! msn_valid) {
		chan_misdn_log(1, bc->port, " --> Ignoring Call, its not in our MSN List\n");
		return RESPONSE_IGNORE_SETUP; /*  Ignore MSNs which are not in our List */
	}

	
	print_bearer(bc);
    
	{
		struct chan_list *ch=init_chan_list(ORG_MISDN);
		struct ast_channel *chan;
		int exceed;

		if (!ch) { chan_misdn_log(-1, bc->port, "cb_events: malloc for chan_list failed!\n"); return 0;}
		
		ch->bc = bc;
		ch->l3id=bc->l3_id;
		ch->addr=bc->addr;
		ch->orginator = ORG_MISDN;

		chan=misdn_new(ch, AST_STATE_RESERVED,bc->dad, bc->oad, AST_FORMAT_ALAW, bc->port, bc->channel);
		ch->ast = chan;

		if ((exceed=add_in_calls(bc->port))) {
			char tmp[16];
			sprintf(tmp,"%d",exceed);
			pbx_builtin_setvar_helper(chan,"MAX_OVERFLOW",tmp);
		}

		read_config(ch, ORG_MISDN);
		
		export_ch(chan, bc, ch);

		ch->ast->rings=1;
		ast_setstate(ch->ast, AST_STATE_RINGING);

		int pres,screen;

		switch (bc->pres) {
			case 1:
			pres=AST_PRES_RESTRICTED; chan_misdn_log(2,bc->port," --> PRES: Restricted (1)\n");
			break;
			case 2:
			pres=AST_PRES_UNAVAILABLE; chan_misdn_log(2,bc->port," --> PRES: Restricted (2)\n");
			break;
			default:
			pres=AST_PRES_ALLOWED; chan_misdn_log(2,bc->port," --> PRES: Restricted (%d)\n", bc->pres);
		}

		switch (bc->screen) {
			case 0:
			screen=AST_PRES_USER_NUMBER_UNSCREENED;  chan_misdn_log(2,bc->port," --> SCREEN: Unscreened (0)\n");
			break;
			case 1:
			screen=AST_PRES_USER_NUMBER_PASSED_SCREEN; chan_misdn_log(2,bc->port," --> SCREEN: Passed screen (1)\n");
			break;
			case 2:
			screen=AST_PRES_USER_NUMBER_FAILED_SCREEN; chan_misdn_log(2,bc->port," --> SCREEN: failed screen (2)\n");
			break;
			case 3:
			screen=AST_PRES_NETWORK_NUMBER; chan_misdn_log(2,bc->port," --> SCREEN: Network Number (3)\n");
			break;
			default:
			screen=AST_PRES_USER_NUMBER_UNSCREENED; chan_misdn_log(2,bc->port," --> SCREEN: Unscreened (%d)\n",bc->screen);
		}

		chan->cid.cid_pres=pres+screen;

		pbx_builtin_setvar_helper(chan, "TRANSFERCAPABILITY", ast_transfercapability2str(bc->capability));
		chan->transfercapability=bc->capability;
		
		switch (bc->capability) {
		case INFO_CAPABILITY_DIGITAL_UNRESTRICTED:
			pbx_builtin_setvar_helper(chan,"CALLTYPE","DIGITAL");
			break;
		default:
			pbx_builtin_setvar_helper(chan,"CALLTYPE","SPEECH");
		}

		/** queue new chan **/
		cl_queue_chan(&cl_te, ch) ;


		if (!strstr(ch->allowed_bearers,"all")) {
			int i;
			for (i=0; i< sizeof(allowed_bearers_array)/sizeof(struct allowed_bearers); i++) {
				if (allowed_bearers_array[i].cap == bc->capability) {
					if (  !strstr( ch->allowed_bearers, allowed_bearers_array[i].name)) {
						chan_misdn_log(0,bc->port,"Bearer Not allowed\b");
						bc->out_cause=88;
						
						ch->state=MISDN_EXTCANTMATCH;
						misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
						return RESPONSE_OK;
					}
				}
				
			}
		}
		
		/* Check for Pickup Request first */
		if (!strcmp(chan->exten, ast_pickup_ext())) {
			int ret;/** Sending SETUP_ACK**/
			ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
			if (ast_pickup_call(chan)) {
				hangup_chan(ch);
			} else {
				ch->state = MISDN_CALLING_ACKNOWLEDGE;
				ast_setstate(chan, AST_STATE_DOWN);
				hangup_chan(ch);
				ch->ast=NULL;
				break;
			}
		}
		
		/*
		  added support for s extension hope it will help those poor cretains
		  which haven't overlap dial.
		*/
		{
			int ai;
			misdn_cfg_get( bc->port, MISDN_CFG_ALWAYS_IMMEDIATE, &ai, sizeof(ai));
			if ( ai ) {
				do_immediate_setup(bc, ch , chan);
				break;
			}
			
			
			
		}

		/* check if we should jump into s when we have no dad */
		{
			int im;
			misdn_cfg_get( bc->port, MISDN_CFG_IMMEDIATE, &im, sizeof(im));
			if ( im && ast_strlen_zero(bc->dad) ) {
				do_immediate_setup(bc, ch , chan);
				break;
			}
		}

		
			chan_misdn_log(5,bc->port,"CONTEXT:%s\n",ch->context);
			if(!ast_canmatch_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
			
			chan_misdn_log(-1, bc->port, "Extension can never match, so disconnecting\n");

			if (bc->nt)
				hanguptone_indicate(ch);
			ch->state=MISDN_EXTCANTMATCH;
			bc->out_cause=1;

			if (bc->nt)
				misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
			else
				misdn_lib_send_event(bc, EVENT_RELEASE );
				
			break;
		}
		
		if (!ch->overlap_dial && ast_exists_extension(ch->ast, ch->context, bc->dad, 1, bc->oad)) {
			ch->state=MISDN_DIALING;
			
			if (bc->nt || (bc->need_more_infos && misdn_lib_is_ptp(bc->port)) ) {
				int ret; 
				ret = misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
			} else {
				int ret;
				ret= misdn_lib_send_event(bc, EVENT_PROCEEDING );
			}
	
			if (pbx_start_chan(ch)<0) {
				hangup_chan(ch);

				chan_misdn_log(-1, bc->port, "ast_pbx_start returned <0 in SETUP\n");
				chan=NULL;

				if (bc->nt) {
					hanguptone_indicate(ch);
					misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE );
				} else
					misdn_lib_send_event(bc, EVENT_RELEASE);
			}
		} else {

			if (bc->sending_complete) {
				ch->state=MISDN_EXTCANTMATCH;
				bc->out_cause=1;

				if (bc->nt)  {
					chan_misdn_log(0,bc->port," --> sending_complete so we never match ..\n");
					misdn_lib_send_event(bc, EVENT_RELEASE_COMPLETE);
				} else {
					chan_misdn_log(0,bc->port," --> sending_complete so we never match ..\n");
					misdn_lib_send_event(bc, EVENT_RELEASE);
				}

			} else {

				int ret= misdn_lib_send_event(bc, EVENT_SETUP_ACKNOWLEDGE );
				if (ret == -ENOCHAN) {
					ast_log(LOG_WARNING,"Channel was catched, before we could Acknowledge\n");
					misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
				}
				/*  send tone to phone :) */
				
				/** ADD IGNOREPAT **/
				
				int stop_tone, dad_len;
				misdn_cfg_get( 0, MISDN_GEN_STOP_TONE, &stop_tone, sizeof(int));

				dad_len = ast_strlen_zero(bc->dad);
				
				if ( !dad_len && stop_tone )
					stop_indicate(ch);
				else
					dialtone_indicate(ch);
				
				ch->state=MISDN_WAITING4DIGS;
				
				if (ch->overlap_dial && !dad_len) {
					ast_mutex_lock(&ch->overlap_tv_lock);
					ch->overlap_tv = ast_tvnow();
					ast_mutex_unlock(&ch->overlap_tv_lock);
					if (ch->overlap_dial_task == -1) {
						ch->overlap_dial_task = 
							misdn_tasks_add_variable(ch->overlap_dial, misdn_overlap_dial_task, ch);
					}
				}
			}
		}
		
	}
	break;
	case EVENT_SETUP_ACKNOWLEDGE:
	{
		ch->state = MISDN_CALLING_ACKNOWLEDGE;

		if (bc->channel) 
			update_name(ch->ast,bc->port,bc->channel);
		
		if (!ast_strlen_zero(bc->infos_pending)) {
			/* TX Pending Infos */
			
			{
				int l = sizeof(bc->dad);
				strncat(bc->dad,bc->infos_pending, l - strlen(bc->dad));
				bc->dad[l-1] = 0;
			}	
			{
				int l = sizeof(ch->ast->exten);
				strncpy(ch->ast->exten, bc->dad, l);
				ch->ast->exten[l-1] = 0;
			}
			{
				int l = sizeof(bc->info_dad);
				strncpy(bc->info_dad, bc->infos_pending, l);
				bc->info_dad[l-1] = 0;
			}
			strncpy(bc->infos_pending,"", 1);

			misdn_lib_send_event(bc, EVENT_INFORMATION);
		}
	}
	break;
	case EVENT_PROCEEDING:
	{
		
		if ( misdn_cap_is_speech(bc->capability) &&
		     misdn_inband_avail(bc) ) {
			start_bc_tones(ch);
		}

		ch->state = MISDN_PROCEEDING;
		
		ast_queue_control(ch->ast, AST_CONTROL_PROCEEDING);
	}
	break;
	case EVENT_PROGRESS:
		if (!bc->nt ) {
			if ( misdn_cap_is_speech(bc->capability) &&
			     misdn_inband_avail(bc)
				) {
				start_bc_tones(ch);
			}
			
			ast_queue_control(ch->ast, AST_CONTROL_PROGRESS);
			
			ch->state=MISDN_PROGRESS;
		}
		break;
		
		
	case EVENT_ALERTING:
	{
		ch->state = MISDN_ALERTING;
		
		ast_queue_control(ch->ast, AST_CONTROL_RINGING);
		ast_setstate(ch->ast, AST_STATE_RINGING);
		
		cb_log(1,bc->port,"Set State Ringing\n");
		
		if ( misdn_cap_is_speech(bc->capability) && misdn_inband_avail(bc)) {
			cb_log(1,bc->port,"Starting Tones, we have inband Data\n");
			start_bc_tones(ch);
		} else {
			cb_log(1,bc->port,"We have no inband Data, the other end must create ringing\n");
			if (ch->far_alerting) {
				cb_log(1,bc->port,"The other end can not do ringing eh ?.. we must do all ourself..");
				start_bc_tones(ch);
				/*tone_indicate(ch, TONE_FAR_ALERTING);*/
			}
		}
	}
	break;
	case EVENT_CONNECT:
	{
		/*we answer when we've got our very new L3 ID from the NT stack */
		misdn_lib_send_event(bc,EVENT_CONNECT_ACKNOWLEDGE);
	
		struct ast_channel *bridged=AST_BRIDGED_P(ch->ast);
		
		misdn_lib_echo(bc,0);
		stop_indicate(ch);

		if (bridged && !strcasecmp(bridged->tech->type,"mISDN")) {
			struct chan_list *bridged_ch=MISDN_ASTERISK_TECH_PVT(bridged);

			chan_misdn_log(1,bc->port," --> copying cpndialplan:%d and cad:%s to the A-Channel\n",bc->cpnnumplan,bc->cad);
			if (bridged_ch) {
				bridged_ch->bc->cpnnumplan=bc->cpnnumplan;
				ast_copy_string(bridged_ch->bc->cad,bc->cad,sizeof(bc->cad));
			}
		}
	}
	
	
	/* notice that we don't break here!*/

	case EVENT_CONNECT_ACKNOWLEDGE:
	{
		ch->l3id=bc->l3_id;
		ch->addr=bc->addr;
		
		start_bc_tones(ch);
		
		
		ch->state = MISDN_CONNECTED;
		ast_queue_control(ch->ast, AST_CONTROL_ANSWER);
	}
	break;
	case EVENT_DISCONNECT:
	/*we might not have an ch->ast ptr here anymore*/
	if (ch) {
		struct chan_list *holded_ch=find_holded(cl_te, bc);
	
		chan_misdn_log(3,bc->port," --> org:%d nt:%d, inbandavail:%d state:%d\n", ch->orginator, bc->nt, misdn_inband_avail(bc), ch->state);
		if ( ch->orginator==ORG_AST && !bc->nt && misdn_inband_avail(bc) && ch->state != MISDN_CONNECTED) {
			/* If there's inband information available (e.g. a
			   recorded message saying what was wrong with the
			   dialled number, or perhaps even giving an
			   alternative number, then play it instead of
			   immediately releasing the call */
			chan_misdn_log(1,bc->port, " --> Inband Info Avail, not sending RELEASE\n");
		
			ch->state=MISDN_DISCONNECTED;
			start_bc_tones(ch);
			break;
		}
		
		/*Check for holded channel, to implement transfer*/
		if (holded_ch && ch->ast ) {
			cb_log(1,bc->port," --> found holded ch\n");
			if  (ch->state == MISDN_CONNECTED ) {
				misdn_transfer_bc(ch, holded_ch) ;
			}
			hangup_chan(ch);
			release_chan(bc);
			break;
		}
		
		stop_bc_tones(ch);
		hangup_chan(ch);
	}
	bc->out_cause=-1;
	if (bc->need_release) misdn_lib_send_event(bc,EVENT_RELEASE);
	break;
	
	case EVENT_RELEASE:
		{
			bc->out_cause=16;
			
			hangup_chan(ch);
			release_chan(bc);
		
			if (bc->need_release_complete) 
				misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
		}
		break;
	case EVENT_RELEASE_COMPLETE:
	{
		stop_bc_tones(ch);
		hangup_chan(ch);
		release_chan(bc);
		if(ch)	
			ch->state=MISDN_CLEANING;
	}
	break;
	case EVENT_CLEANUP:
	{
		stop_bc_tones(ch);
		
		switch(ch->state) {
			case MISDN_CALLING:
				bc->cause=27; /* Destination out of order */
			break;
			default:
			break;
		}
		
		hangup_chan(ch);
		release_chan(bc);
	}
	break;

	case EVENT_TONE_GENERATE:
	{
		int tone_len=bc->tone_cnt;
		struct ast_channel *ast=ch->ast;
		void *tmp;
		int res;
		int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);

		chan_misdn_log(9,bc->port,"TONE_GEN: len:%d\n");

		if (!ast) break;

		if (!ast->generator) break;
	
		
	
		tmp = ast->generatordata;
		ast->generatordata = NULL;
		generate = ast->generator->generate;

		if (tone_len <0 || tone_len > 512 ) {
			ast_log(LOG_NOTICE, "TONE_GEN: len was %d, set to 128\n",tone_len);
			tone_len=128;
		}

		res = generate(ast, tmp, tone_len, tone_len);
		ast->generatordata = tmp;
		
		if (res) {
			ast_log(LOG_WARNING, "Auto-deactivating generator\n");
			ast_deactivate_generator(ast);
		} else {
			bc->tone_cnt=0;
		}
	}
	break;
		
	case EVENT_BCHAN_DATA:
	{
		if ( !misdn_cap_is_speech(ch->bc->capability) ) {
			struct ast_frame frame;
			/*In Data Modes we queue frames*/
			frame.frametype  = AST_FRAME_VOICE; /*we have no data frames yet*/
			frame.subclass = AST_FORMAT_ALAW;
			frame.datalen = bc->bframe_len;
			frame.samples = bc->bframe_len ;
			frame.mallocd =0 ;
			frame.offset= 0 ;
			frame.src = NULL;
			frame.data = bc->bframe ;
			
			ast_queue_frame(ch->ast,&frame);
		} else {
			fd_set wrfs;
			struct timeval tv;
			tv.tv_sec=0;
			tv.tv_usec=0;
			
			
			FD_ZERO(&wrfs);
			FD_SET(ch->pipe[1],&wrfs);
			
			int t=select(FD_SETSIZE,NULL,&wrfs,NULL,&tv);

			if (!t) {
				chan_misdn_log(9, bc->port, "Select Timed out\n");
				break;
			}
			
			if (t<0) {
				chan_misdn_log(-1, bc->port, "Select Error (err=%s)\n",strerror(errno));
				break;
			}
			
			if (FD_ISSET(ch->pipe[1],&wrfs)) {
				chan_misdn_log(9, bc->port, "writing %d bytes 2 asterisk\n",bc->bframe_len);
				int ret=write(ch->pipe[1], bc->bframe, bc->bframe_len);
				
				if (ret<=0) {
					chan_misdn_log(-1, bc->port, "Write returned <=0 (err=%s)\n",strerror(errno));
				}
			} else {
				chan_misdn_log(1, bc->port, "Wripe Pipe full!\n");
			}
		}
	}
	break;
	case EVENT_TIMEOUT:
		{
		if (ch && bc)
			chan_misdn_log(1,bc->port,"--> state: %s\n",misdn_get_ch_state(ch));

		switch (ch->state) {
			case MISDN_CALLING:
			case MISDN_DIALING:
			case MISDN_PROGRESS:
			case MISDN_ALERTING:
			case MISDN_PROCEEDING:
			case MISDN_CALLING_ACKNOWLEDGE:
				if (bc->nt) {
					bc->progress_indicator=8;
					hanguptone_indicate(ch);
				}
				
				bc->out_cause=1;
				misdn_lib_send_event(bc,EVENT_DISCONNECT);
			break;

			case MISDN_WAITING4DIGS:
				if (bc->nt) {
					bc->progress_indicator=8;
					bc->out_cause=1;
					hanguptone_indicate(ch);
					misdn_lib_send_event(bc,EVENT_DISCONNECT);
				} else {
					bc->out_cause=16;
					misdn_lib_send_event(bc,EVENT_RELEASE);
				}
				
			break;


			case MISDN_CLEANING: 
				chan_misdn_log(1,bc->port," --> in state cleaning .. so ingoring, the stack should clean it for us\n");
			break;

			default:
				misdn_lib_send_event(bc,EVENT_RELEASE_COMPLETE);
			}
		}
		break;

    
	/***************************/
	/** Suplementary Services **/
	/***************************/
	case EVENT_RETRIEVE:
	{
		ch=find_holded(cl_te, bc);
		if (!ch) {
			ast_log(LOG_WARNING, "Found no Holded channel, cannot Retrieve\n");
			misdn_lib_send_event(bc, EVENT_RETRIEVE_REJECT);
			break;
		}
		struct ast_channel *hold_ast=AST_BRIDGED_P(ch->ast);
		ch->state = MISDN_CONNECTED;
		
		if (hold_ast) {
			ast_moh_stop(hold_ast);
		}
		
		if ( misdn_lib_send_event(bc, EVENT_RETRIEVE_ACKNOWLEDGE) < 0)
			misdn_lib_send_event(bc, EVENT_RETRIEVE_REJECT);
		
		
	}
	break;
    
	case EVENT_HOLD:
	{
		int hold_allowed;
		misdn_cfg_get( bc->port, MISDN_CFG_HOLD_ALLOWED, &hold_allowed, sizeof(int));
		
		if (!hold_allowed) {

			chan_misdn_log(-1, bc->port, "Hold not allowed this port.\n");
			misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
			break;
		}

#if 0
		{
			struct chan_list *holded_ch=find_holded(cl_te, bc);
			if (holded_ch) {
				misdn_lib_send_event(bc, EVENT_HOLD_REJECT);

				chan_misdn_log(-1, bc->port, "We can't use RETRIEVE at the moment due to mISDN bug!\n");
				break;
			}
		}
#endif
		struct ast_channel *bridged=AST_BRIDGED_P(ch->ast);
		
		if (bridged){
			struct chan_list *bridged_ch=MISDN_ASTERISK_TECH_PVT(bridged);
			ch->state = MISDN_HOLDED;
			ch->l3id = bc->l3_id;
			
			bc->holded_bc=bridged_ch->bc;
			misdn_lib_send_event(bc, EVENT_HOLD_ACKNOWLEDGE);

			/* XXX This should queue an AST_CONTROL_HOLD frame on this channel
			 * instead of starting moh on the bridged channel directly */
			ast_moh_start(bridged, NULL, NULL);
		} else {
			misdn_lib_send_event(bc, EVENT_HOLD_REJECT);
			chan_misdn_log(0, bc->port, "We aren't bridged to anybody\n");
		}
	} 
	break;
	
	case EVENT_FACILITY:
		print_facility(&(bc->fac_in), bc);
		
		switch (bc->fac_in.Function) {
		case Fac_CD:
			{
				struct ast_channel *bridged=AST_BRIDGED_P(ch->ast);
				struct chan_list *ch_br;
				if (bridged && MISDN_ASTERISK_TECH_PVT(bridged)) {
					ch_br=MISDN_ASTERISK_TECH_PVT(bridged);
					/*ch->state=MISDN_FACILITY_DEFLECTED;*/
					if (ch_br->bc) {
						if (ast_exists_extension(bridged, ch->context, (char *)bc->fac_in.u.CDeflection.DeflectedToNumber, 1, bc->oad)) {
							ch_br->state=MISDN_DIALING;
							if (pbx_start_chan(ch_br) < 0) {
								chan_misdn_log(-1, ch_br->bc->port, "ast_pbx_start returned < 0 in misdn_overlap_dial_task\n");
							}
						}
					}

				}
				misdn_lib_send_event(bc, EVENT_DISCONNECT);
			} 
			break;
		case Fac_AOCDCurrency:
			bc->AOCDtype = Fac_AOCDCurrency;
			memcpy(&(bc->AOCD.currency), &(bc->fac_in.u.AOCDcur), sizeof(struct FacAOCDCurrency));
			break;
		case Fac_AOCDChargingUnit:
			bc->AOCDtype = Fac_AOCDChargingUnit;
			memcpy(&(bc->AOCD.chargingUnit), &(bc->fac_in.u.AOCDchu), sizeof(struct FacAOCDChargingUnit));
			break;
		default:
			chan_misdn_log(0, bc->port," --> not yet handled: facility type:%p\n", bc->fac_in.Function);
		}
		
		break;

	case EVENT_RESTART:

		stop_bc_tones(ch);
		release_chan(bc);
		
		break;
				
	default:
		ast_log(LOG_NOTICE, "Got Unknown Event\n");
		break;
	}
	
	return RESPONSE_OK;
}

/** TE STUFF END **/

/******************************************
 *
 *   Asterisk Channel Endpoint END
 *
 *
 *******************************************/


static int g_config_initialized=0;

static int unload_module(void *mod)
{
	/* First, take us out of the channel loop */
	ast_log(LOG_VERBOSE, "-- Unregistering mISDN Channel Driver --\n");

	misdn_tasks_destroy();
	
	if (!g_config_initialized) return 0;
	
	ast_cli_unregister_multiple(chan_misdn_clis, sizeof(chan_misdn_clis) / sizeof(chan_misdn_clis[0]));
	
	/* ast_unregister_application("misdn_crypt"); */
	ast_unregister_application("misdn_set_opt");
	ast_unregister_application("misdn_facility");
  
	ast_channel_unregister(&misdn_tech);


	free_robin_list();
	misdn_cfg_destroy();
	misdn_lib_destroy();
  
	if (misdn_debug)
		free(misdn_debug);
	if (misdn_debug_only)
		free(misdn_debug_only);
 	free(misdn_ports);
 	
	return 0;
}

static int load_module(void *mod)
{
	int i, port;
	
	char ports[256]="";

	max_ports=misdn_lib_maxports_get();
	
	if (max_ports<=0) {
		ast_log(LOG_ERROR, "Unable to initialize mISDN\n");
		return 0;
	}
	
	if (misdn_cfg_init(max_ports)) {
		ast_log(LOG_ERROR, "Unable to initialize misdn_config.\n");
		return 0;
	}
	g_config_initialized=1;
	
	misdn_debug = (int *)malloc(sizeof(int) * (max_ports+1));
	misdn_ports = (int *)malloc(sizeof(int) * (max_ports+1));
	misdn_cfg_get( 0, MISDN_GEN_DEBUG, &misdn_debug[0], sizeof(int));
	for (i = 1; i <= max_ports; i++) {
		misdn_debug[i] = misdn_debug[0];
		misdn_ports[i] = i;
	}
	*misdn_ports = 0;
	misdn_debug_only = (int *)calloc(max_ports + 1, sizeof(int));

	{
		char tempbuf[BUFFERSIZE+1];
		misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, tempbuf, BUFFERSIZE);
		if (strlen(tempbuf))
			tracing = 1;
	}
	
	misdn_in_calls = (int *)malloc(sizeof(int) * (max_ports+1));
	misdn_out_calls = (int *)malloc(sizeof(int) * (max_ports+1));

	for (i=1; i <= max_ports; i++) {
		misdn_in_calls[i]=0;
		misdn_out_calls[i]=0;
	}
	
	ast_mutex_init(&cl_te_lock);

	misdn_cfg_update_ptp();
	misdn_cfg_get_ports_string(ports);

	if (strlen(ports))
		chan_misdn_log(0, 0, "Got: %s from get_ports\n",ports);
	
	{
		struct misdn_lib_iface iface = {
			.cb_event = cb_events,
			.cb_log = chan_misdn_log,
			.cb_jb_empty = chan_misdn_jb_empty,
		};
		
		if (misdn_lib_init(ports, &iface, NULL))
			chan_misdn_log(0, 0, "No te ports initialized\n");
	
		int ntflags=0;
		char ntfile[BUFFERSIZE+1];

		misdn_cfg_get( 0, MISDN_GEN_NTDEBUGFLAGS, &ntflags, sizeof(int));
		misdn_cfg_get( 0, MISDN_GEN_NTDEBUGFILE, &ntfile, BUFFERSIZE);

		misdn_lib_nt_debug_init(ntflags,ntfile);

	}

	{
		if (ast_channel_register(&misdn_tech)) {
			ast_log(LOG_ERROR, "Unable to register channel class %s\n", misdn_type);
			unload_module(mod);
			return -1;
		}
	}
  
	ast_cli_register_multiple(chan_misdn_clis, sizeof(chan_misdn_clis) / sizeof(chan_misdn_clis[0]));
  
	ast_register_application("misdn_set_opt", misdn_set_opt_exec, "misdn_set_opt",
				 "misdn_set_opt(:<opt><optarg>:<opt><optarg>..):\n"
				 "Sets mISDN opts. and optargs\n"
				 "\n"
				 "The available options are:\n"
				 "    d - Send display text on called phone, text is the optparam\n"
				 "    n - don't detect dtmf tones on called channel\n"
				 "    h - make digital outgoing call\n" 
				 "    c - make crypted outgoing call, param is keyindex\n"
				 "    e - perform echo cancelation on this channel,\n"
				 "        takes taps as arguments (32,64,128,256)\n"
				 "    s - send Non Inband DTMF as inband\n"
				 "   vr - rxgain control\n"
				 "   vt - txgain control\n"
		);

	
	ast_register_application("misdn_facility", misdn_facility_exec, "misdn_facility",
				 "misdn_facility(<FACILITY_TYPE>|<ARG1>|..)\n"
				 "Sends the Facility Message FACILITY_TYPE with \n"
				 "the given Arguments to the current ISDN Channel\n"
				 "Supported Facilities are:\n"
				 "\n"
				 "type=calldeflect args=Nr where to deflect\n"
		);


	misdn_cfg_get( 0, MISDN_GEN_TRACEFILE, global_tracefile, BUFFERSIZE);

	/* start the l1 watchers */
	
	for (port = misdn_cfg_get_next_port(0); port >= 0; port = misdn_cfg_get_next_port(port)) {
		int l1timeout;
		misdn_cfg_get(port, MISDN_CFG_L1_TIMEOUT, &l1timeout, sizeof(l1timeout));
		if (l1timeout) {
			chan_misdn_log(4, 0, "Adding L1watcher task: port:%d timeout:%ds\n", port, l1timeout);
			misdn_tasks_add(l1timeout * 1000, misdn_l1_task, &misdn_ports[port]);  
		}
	}
	
	chan_misdn_log(0, 0, "-- mISDN Channel Driver Registered -- (BE AWARE THIS DRIVER IS EXPERIMENTAL!)\n");

	return 0;
}



static int reload(void *mod)
{
	reload_config();

	return 0;
}

static const char *description(void)
{
	return desc;
}

static const char *key(void)
{
	return ASTERISK_GPL_KEY;
}




/*** SOME APPS ;)***/

static int misdn_facility_exec(struct ast_channel *chan, void *data)
{
	struct chan_list *ch = MISDN_ASTERISK_TECH_PVT(chan);
	char *tok, *tokb;

	chan_misdn_log(0,0,"TYPE: %s\n",chan->tech->type);
	
	if (strcasecmp(chan->tech->type,"mISDN")) {
		ast_log(LOG_WARNING, "misdn_facility makes only sense with chan_misdn channels!\n");
		return -1;
	}
	
	if (ast_strlen_zero((char *)data)) {
		ast_log(LOG_WARNING, "misdn_facility Requires arguments\n");
		return -1;
	}
	
	tok=strtok_r((char*)data,"|", &tokb) ;
	
	if (!tok) {
		ast_log(LOG_WARNING, "misdn_facility Requires arguments\n");
		return -1;
	}
	
	if (!strcasecmp(tok,"calldeflect")) {
		tok=strtok_r(NULL,"|", &tokb) ;
		
		if (!tok) {
			ast_log(LOG_WARNING, "Facility: Call Defl Requires arguments\n");
		}
	
		if (strlen(tok) >= sizeof(ch->bc->fac_out.u.CDeflection.DeflectedToNumber)) {
			ast_log(LOG_WARNING, "Facility: Number argument too long (up to 15 digits are allowed). Ignoring.\n");
			return 0; 
		}
		ch->bc->fac_out.Function = Fac_CD;
		strncpy((char *)ch->bc->fac_out.u.CDeflection.DeflectedToNumber, tok, sizeof(ch->bc->fac_out.u.CDeflection.DeflectedToNumber));
		misdn_lib_send_event(ch->bc, EVENT_FACILITY);
	} else {
		ast_log(LOG_WARNING, "Unknown Facility: %s\n",tok);
	}
	
	return 0;
	
}


static int misdn_set_opt_exec(struct ast_channel *chan, void *data)
{
	struct chan_list *ch = MISDN_ASTERISK_TECH_PVT(chan);
	char *tok,*tokb;
	int  keyidx=0;
	int rxgain=0;
	int txgain=0;
	int change_jitter=0;
	
	if (strcasecmp(chan->tech->type,"mISDN")) {
		ast_log(LOG_WARNING, "misdn_set_opt makes only sense with chan_misdn channels!\n");
		return -1;
	}
	
	if (ast_strlen_zero((char *)data)) {
		ast_log(LOG_WARNING, "misdn_set_opt Requires arguments\n");
		return -1;
	}

	for (tok=strtok_r((char*)data, ":",&tokb);
	     tok;
	     tok=strtok_r(NULL,":",&tokb) ) {
		int neglect=0;
		
		if (tok[0] == '!' ) {
			neglect=1;
			tok++;
		}
		
		switch(tok[0]) {
			
		case 'd' :
			ast_copy_string(ch->bc->display,++tok,84);
			chan_misdn_log(1, ch->bc->port, "SETOPT: Display:%s\n",ch->bc->display);
			break;
			
		case 'n':
			chan_misdn_log(1, ch->bc->port, "SETOPT: No DSP\n");
			ch->bc->nodsp=1;
			break;

		case 'j':
			chan_misdn_log(1, ch->bc->port, "SETOPT: jitter\n");
			tok++;
			change_jitter=1;
			
			switch ( tok[0] ) {
			case 'b' :
				ch->jb_len=atoi(++tok);
				chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d\n",ch->jb_len);
				break;
			case 't' :
				ch->jb_upper_threshold=atoi(++tok);
				chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d\n",ch->jb_upper_threshold);
				break;

			case 'n':
				ch->bc->nojitter=1;
				chan_misdn_log(1, ch->bc->port, " --> nojitter\n");
				break;
				
			default:
				ch->jb_len=4000;
				ch->jb_upper_threshold=0;
				chan_misdn_log(1, ch->bc->port, " --> buffer_len:%d (default)\n",ch->jb_len);
				chan_misdn_log(1, ch->bc->port, " --> upper_threshold:%d (default)\n",ch->jb_upper_threshold);
			}
			
			break;
      
		case 'v':
			tok++;

			switch ( tok[0] ) {
			case 'r' :
				rxgain=atoi(++tok);
				if (rxgain<-8) rxgain=-8;
				if (rxgain>8) rxgain=8;
				ch->bc->rxgain=rxgain;
				chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n",rxgain);
				break;
			case 't':
				txgain=atoi(++tok);
				if (txgain<-8) txgain=-8;
				if (txgain>8) txgain=8;
				ch->bc->txgain=txgain;
				chan_misdn_log(1, ch->bc->port, "SETOPT: Volume:%d\n",txgain);
				break;
			}
			break;
      
		case 'c':
			keyidx=atoi(++tok);
      
			if (keyidx > misdn_key_vector_size  || keyidx < 0 ) {
				ast_log(LOG_WARNING, "You entered the keyidx: %d but we have only %d keys\n",keyidx, misdn_key_vector_size );
				continue; 
			}
      
			{
				ast_copy_string(ch->bc->crypt_key,  misdn_key_vector[keyidx], sizeof(ch->bc->crypt_key));
			}
			
			chan_misdn_log(0, ch->bc->port, "SETOPT: crypt with key:%s\n",misdn_key_vector[keyidx]);
			break;

		case 'e':
			chan_misdn_log(1, ch->bc->port, "SETOPT: EchoCancel\n");
			
			if (neglect) {
				chan_misdn_log(1, ch->bc->port, " --> disabled\n");
				ch->bc->ec_enable=0;
			} else {
				ch->bc->ec_enable=1;
				ch->bc->orig=ch->orginator;
				tok++;
				if (tok) {
					ch->bc->ec_deftaps=atoi(tok);
				}
			}
			
			break;
      
		case 'h':
			chan_misdn_log(1, ch->bc->port, "SETOPT: Digital\n");
			
			if (strlen(tok) > 1 && tok[1]=='1') {
				chan_misdn_log(1, ch->bc->port, "SETOPT: HDLC \n");
				ch->bc->hdlc=1;
			}  
			ch->bc->capability=INFO_CAPABILITY_DIGITAL_UNRESTRICTED;
			break;
            
		case 's':
			chan_misdn_log(1, ch->bc->port, "SETOPT: Send DTMF\n");
			ch->bc->send_dtmf=1;
			break;
			
		case 'f':
			chan_misdn_log(1, ch->bc->port, "SETOPT: Faxdetect\n");
			ch->faxdetect=1;
			misdn_cfg_get(ch->bc->port, MISDN_CFG_FAXDETECT_TIMEOUT, &ch->faxdetect_timeout, sizeof(ch->faxdetect_timeout));
			break;

		case 'a':
			chan_misdn_log(1, ch->bc->port, "SETOPT: AST_DSP (for DTMF)\n");
			ch->ast_dsp=1;
			break;

		case 'p':
			chan_misdn_log(1, ch->bc->port, "SETOPT: callerpres: %s\n",&tok[1]);
			/* CRICH: callingpres!!! */
			if (strstr(tok,"allowed") ) {
				ch->bc->pres=0;
			} else if (strstr(tok,"not_screened")) {
				ch->bc->pres=1;
			}
			
			
			break;
      
      
		default:
			break;
		}
	}

	if (change_jitter)
		config_jitterbuffer(ch);
	
	
	if (ch->faxdetect || ch->ast_dsp) {
		if (!ch->dsp) ch->dsp = ast_dsp_new();
		if (ch->dsp) ast_dsp_set_features(ch->dsp, DSP_FEATURE_DTMF_DETECT| DSP_FEATURE_FAX_DETECT);
		if (!ch->trans) ch->trans=ast_translator_build_path(AST_FORMAT_SLINEAR, AST_FORMAT_ALAW);
	}

	if (ch->ast_dsp) {
		chan_misdn_log(1,ch->bc->port,"SETOPT: with AST_DSP we deactivate mISDN_dsp\n");
		ch->bc->nodsp=1;
		ch->bc->nojitter=1;
	}
	
	return 0;
}


int chan_misdn_jb_empty ( struct misdn_bchannel *bc, char *buf, int len) 
{
	struct chan_list *ch=find_chan_by_bc(cl_te, bc);
	
	if (ch && ch->jb) {
		return misdn_jb_empty(ch->jb, buf, len);
	}
	
	return -1;
}



/*******************************************************/
/***************** JITTERBUFFER ************************/
/*******************************************************/


/* allocates the jb-structure and initialise the elements*/
struct misdn_jb *misdn_jb_init(int size, int upper_threshold)
{
    int i;
    struct misdn_jb *jb = (struct misdn_jb*) malloc(sizeof(struct misdn_jb));
    jb->size = size;
    jb->upper_threshold = upper_threshold;
    jb->wp = 0;
    jb->rp = 0;
    jb->state_full = 0;
    jb->state_empty = 0;
    jb->bytes_wrote = 0;
    jb->samples = (char *)malloc(size*sizeof(char));

    if (!jb->samples) {
	    chan_misdn_log(-1,0,"No free Mem for jb->samples\n");
	    return NULL;
    }
    
    jb->ok = (char *)malloc(size*sizeof(char));

    if (!jb->ok) {
	    chan_misdn_log(-1,0,"No free Mem for jb->ok\n");
	    return NULL;
    }

    for(i=0; i<size; i++)
 	jb->ok[i]=0;

    ast_mutex_init(&jb->mutexjb);

    return jb;
}

/* frees the data and destroys the given jitterbuffer struct */
void misdn_jb_destroy(struct misdn_jb *jb)
{
	ast_mutex_destroy(&jb->mutexjb);
	
	free(jb->samples);
	free(jb);
}

/* fills the jitterbuffer with len data returns < 0 if there was an
   error (bufferoverflow). */
int misdn_jb_fill(struct misdn_jb *jb, const char *data, int len)
{
    int i, j, rp, wp;

    if (!jb || ! data) return 0;

    ast_mutex_lock (&jb->mutexjb);
    
    wp=jb->wp;
    rp=jb->rp;
	
    for(i=0; i<len; i++)
    {
	jb->samples[wp]=data[i];
	jb->ok[wp]=1;
	wp = (wp!=jb->size-1 ? wp+1 : 0);

	if(wp==jb->rp)
	    jb->state_full=1;
    }
    
    if(wp>=rp)
      jb->state_buffer=wp-rp;
    else
      jb->state_buffer= jb->size-rp+wp;
    chan_misdn_log(9,0,"misdn_jb_fill: written:%d | Bufferstatus:%d p:%x\n",len,jb->state_buffer,jb);
    
    if(jb->state_full)
    {
	jb->wp=wp;

	rp=wp;
	for(j=0; j<jb->upper_threshold; j++)
	    rp = (rp!=0 ? rp-1 : jb->size-1);
	jb->rp=rp;
	jb->state_full=0;
	jb->state_empty=1;

	ast_mutex_unlock (&jb->mutexjb);
	
	return -1;
    }

    if(!jb->state_empty)
    {
	jb->bytes_wrote+=len;
	if(jb->bytes_wrote>=jb->upper_threshold)
	{
	    jb->state_empty=1;
	    jb->bytes_wrote=0;
	}
    }
    jb->wp=wp;

    ast_mutex_unlock (&jb->mutexjb);
    
    return 0;
}

/* gets len bytes out of the jitterbuffer if available, else only the
available data is returned and the return value indicates the number
of data. */
int misdn_jb_empty(struct misdn_jb *jb, char *data, int len)
{
    int i, wp, rp, read=0;

    ast_mutex_lock (&jb->mutexjb);

    rp=jb->rp;
    wp=jb->wp;

    if(jb->state_empty)
    {	
	for(i=0; i<len; i++)
	{
	    if(wp==rp)
	    {
		jb->rp=rp;
		jb->state_empty=0;

		ast_mutex_unlock (&jb->mutexjb);
		
		return read;
	    }
	    else
	    {
		if(jb->ok[rp]==1)
		{
		    data[i]=jb->samples[rp];
		    jb->ok[rp]=0;
		    rp=(rp!=jb->size-1 ? rp+1 : 0);
		    read+=1;
		}
	    }
	}

	if(wp >= rp)
		jb->state_buffer=wp-rp;
	else
		jb->state_buffer= jb->size-rp+wp;
	chan_misdn_log(9,0,"misdn_jb_empty: read:%d | Bufferstatus:%d p:%x\n",len,jb->state_buffer,jb);
	
	jb->rp=rp;
    }
    else
	    chan_misdn_log(9,0,"misdn_jb_empty: Wait...requested:%d p:%x\n",len,jb);
    
    ast_mutex_unlock (&jb->mutexjb);

    return read;
}




/*******************************************************/
/*************** JITTERBUFFER  END *********************/
/*******************************************************/




void chan_misdn_log(int level, int port, char *tmpl, ...)
{
	if (! ((0 <= port) && (port <= max_ports))) {
		ast_log(LOG_WARNING, "cb_log called with out-of-range port number! (%d)\n", port);
		port=0;
		level=-1;
	}
		
	va_list ap;
	char buf[1024];
	char port_buf[8];
	sprintf(port_buf,"P[%2d] ",port);
	
	va_start(ap, tmpl);
	vsnprintf( buf, 1023, tmpl, ap );
	va_end(ap);

	if (level == -1)
		ast_log(LOG_WARNING, buf);

	else if (misdn_debug_only[port] ? 
			(level==1 && misdn_debug[port]) || (level==misdn_debug[port]) 
		 : level <= misdn_debug[port]) {
		
		ast_console_puts(port_buf);
		ast_console_puts(buf);
	}
	
	if ((level <= misdn_debug[0]) && !ast_strlen_zero(global_tracefile) ) {
		time_t tm = time(NULL);
		char *tmp=ctime(&tm),*p;
		
		FILE *fp= fopen(global_tracefile, "a+");
		
		p=strchr(tmp,'\n');
		if (p) *p=':';
		
		if (!fp) {
			ast_console_puts("Error opening Tracefile: [ ");
			ast_console_puts(global_tracefile);
			ast_console_puts(" ] ");
			
			ast_console_puts(strerror(errno));
			ast_console_puts("\n");
			return ;
		}
		
		fputs(tmp,fp);
		fputs(" ", fp);
		fputs(port_buf,fp);
		fputs(" ", fp);
		fputs(buf, fp);

		fclose(fp);
	}
}

STD_MOD(MOD_0, reload, NULL, NULL);