summaryrefslogtreecommitdiff
path: root/plugins/!NotAdopted/Skype/skype.c
blob: 39a8c0c47f06d21f36c0fd3139de15bc7aa64231 (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
/*

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


*/

#include "skype.h"
#include "debug.h"
#include "skypeapi.h"
#include "skypesvc.h"
#include "contacts.h"
#include "utf8.h"
#include "pthread.h"
#include "gchat.h"
#include "m_toptoolbar.h"
#include "voiceservice.h"
#include "msglist.h"
#include "memlist.h"
#include <sys/timeb.h>
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
#endif
/*#ifdef _WIN64
#pragma comment (lib, "bufferoverflowU.lib")
#endif*/

#pragma warning (disable: 4706) // assignment within conditional expression

POPUPDATAT MessagePopup;

// Exported Globals
HWND hSkypeWnd=NULL, g_hWnd=NULL, hSkypeWndSecondary=NULL, hForbiddenSkypeWnd = NULL;
HANDLE SkypeReady, SkypeMsgReceived, hInitChat=NULL, httbButton=NULL, FetchMessageEvent=NULL;
BOOL SkypeInitialized=FALSE, MirandaShuttingDown=FALSE, PopupServiceExists=FALSE;
BOOL UseSockets=FALSE, bSkypeOut=FALSE, bProtocolSet=FALSE, bIsImoproxy=FALSE;
char skype_path[MAX_PATH], protocol=2, *pszProxyCallout=NULL, g_szProtoName[_MAX_FNAME]="SKYPE";
int SkypeStatus=ID_STATUS_OFFLINE, hSearchThread=-1, receivers=1;
long sendwatchers = 0, rcvwatchers = 0;
UINT ControlAPIAttach, ControlAPIDiscover;
LONG AttachStatus=-1;
HINSTANCE hInst;
HANDLE hProtocolAvatarsFolder;
char DefaultAvatarsFolder[MAX_PATH+1];
DWORD mirandaVersion;
int hLangpack = 0;

CRITICAL_SECTION RingAndEndcallMutex, QueryThreadMutex, TimeMutex;

// Module Internal Globals
HANDLE MessagePumpReady;
HANDLE hChatEvent=NULL, hChatMenu=NULL;
HANDLE hEvInitChat=NULL, hBuddyAdded=NULL;
HANDLE hMenuAddSkypeContact=NULL;

DWORD msgPumpThreadId = 0;
#ifdef SKYPEBUG_OFFLN
HANDLE GotUserstatus;
#endif

BOOL bModulesLoaded=FALSE;
char *RequestedStatus=NULL;	// To fix Skype-API Statusmode-bug
char cmdMessage[12]="MESSAGE", cmdPartner[8]="PARTNER";	// Compatibility commands



// Direct assignment of user properties to a DB-Setting
static const settings_map m_settings[]= {
		{"LANGUAGE", "Language1"},
		{"PROVINCE", "State"},
		{"CITY", "City"},
		{"PHONE_HOME", "Phone"},
		{"PHONE_OFFICE", "CompanyPhone"},
		{"PHONE_MOBILE", "Cellular"},
		{"HOMEPAGE", "Homepage"},
		{"ABOUT", "About"}
	};

// Imported Globals
extern status_map status_codes[];

BOOL (WINAPI *MyEnableThemeDialogTexture)(HANDLE, DWORD) = 0;

HMODULE hUxTheme = 0;

// function pointers, use typedefs for casting to shut up the compiler when using GetProcAddress()

typedef BOOL (WINAPI *PITA)();
typedef HANDLE (WINAPI *POTD)(HWND, LPCWSTR);
typedef UINT (WINAPI *PDTB)(HANDLE, HDC, int, int, RECT *, RECT *);
typedef UINT (WINAPI *PCTD)(HANDLE);
typedef UINT (WINAPI *PDTT)(HANDLE, HDC, int, int, LPCWSTR, int, DWORD, DWORD, RECT *);

PITA pfnIsThemeActive = 0;
POTD pfnOpenThemeData = 0;
PDTB pfnDrawThemeBackground = 0;
PCTD pfnCloseThemeData = 0;
PDTT pfnDrawThemeText = 0;

#define FIXED_TAB_SIZE 100                  // default value for fixed width tabs

typedef struct {
	char msgnum[16];
	BOOL getstatus;
	BOOL bIsRead;
	BOOL bDontMarkSeen;
	BOOL QueryMsgDirection;
	TYP_MSGLENTRY *pMsgEntry;
} fetchmsg_arg;

typedef struct {
	HANDLE hContact;
	char szId[16];
} msgsendwt_arg;

/*
 * visual styles support (XP+)
 * returns 0 on failure
 */

int InitVSApi()
{
    if((hUxTheme = LoadLibraryA("uxtheme.dll")) == 0)
        return 0;

    pfnIsThemeActive = (PITA)GetProcAddress(hUxTheme, "IsThemeActive");
    pfnOpenThemeData = (POTD)GetProcAddress(hUxTheme, "OpenThemeData");
    pfnDrawThemeBackground = (PDTB)GetProcAddress(hUxTheme, "DrawThemeBackground");
    pfnCloseThemeData = (PCTD)GetProcAddress(hUxTheme, "CloseThemeData");
    pfnDrawThemeText = (PDTT)GetProcAddress(hUxTheme, "DrawThemeText");

    MyEnableThemeDialogTexture = (BOOL (WINAPI *)(HANDLE, DWORD))GetProcAddress(hUxTheme, "EnableThemeDialogTexture");
    if(pfnIsThemeActive != 0 && pfnOpenThemeData != 0 && pfnDrawThemeBackground != 0 && pfnCloseThemeData != 0 && pfnDrawThemeText != 0) {
        return 1;
    }
    return 0;
}

/*
 * unload uxtheme.dll
 */

int FreeVSApi()
{
    if(hUxTheme != 0)
        FreeLibrary(hUxTheme);
    return 0;
}

// Plugin Info
PLUGININFOEX pluginInfo = {
	sizeof(PLUGININFOEX),
	"Skype Protocol",
	PLUGIN_MAKE_VERSION(0,0,0,52),
	"Support for Skype network",
	"leecher - tweety - jls17",
	"leecher@dose.0wnz.at - tweety@user.berlios.de",
	"© 2004-2011 leecher - tweety",
	"http://developer.berlios.de/projects/mgoodies/",
	UNICODE_AWARE,
	{ 0xa71f8335, 0x7b87, 0x4432, { 0xb8, 0xa3, 0x81, 0x47, 0x94, 0x31, 0xc6, 0xf5 } } // {A71F8335-7B87-4432-B8A3-81479431C6F5}
};

#define MAPDND	1	// Map Occupied to DND status and say that you support it
//#define MAPNA   1 // Map NA status to Away and say that you support it

/*                           P R O G R A M                                */

void RegisterToDbeditorpp(void)
{
    // known modules list
    if (ServiceExists("DBEditorpp/RegisterSingleModule"))
        CallService("DBEditorpp/RegisterSingleModule", (WPARAM)SKYPE_PROTONAME, 0);
}

/*void RegisterToUpdate(void)
{
	//Use for the Updater plugin
	if(ServiceExists(MS_UPDATE_REGISTER))
	{
		Update update = {0};
		char szVersion[16];

		update.szComponentName = pluginInfo.shortName;
		update.pbVersion = (BYTE *)CreateVersionStringPlugin((PLUGININFO *)&pluginInfo, szVersion);
		update.cpbVersion = (DWORD)strlen((char *)update.pbVersion);

#ifdef _WIN64
#ifdef _UNICODE
		update.szBetaUpdateURL = "http://dose.0wnz.at/miranda/Skype/Skype_protocol_unicode_x64.zip";
#else
		update.szBetaUpdateURL = "http://dose.0wnz.at/miranda/Skype/Skype_protocol_x64.zip";
#endif
		update.szBetaVersionURL = "http://dose.0wnz.at/miranda/Skype/";
		update.pbBetaVersionPrefix = (BYTE *)"SKYPE version ";
		update.szUpdateURL = update.szBetaUpdateURL;	// FIXME!!
		update.szVersionURL = update.szBetaVersionURL; // FIXME
		update.pbVersionPrefix = update.pbBetaVersionPrefix; //FIXME
#else 
#ifdef _UNICODE
		update.szBetaUpdateURL = "http://dose.0wnz.at/miranda/Skype/Skype_protocol_unicode.zip";
#else
	    update.szBetaUpdateURL = "http://dose.0wnz.at/miranda/Skype/Skype_protocol.zip";
#endif
		update.szBetaVersionURL = "http://dose.0wnz.at/miranda/Skype/";
		update.pbBetaVersionPrefix = (BYTE *)"SKYPE version ";
#ifdef _UNICODE
		update.szUpdateURL = update.szBetaUpdateURL;	// FIXME!!
		update.szVersionURL = update.szBetaVersionURL; // FIXME
		update.pbVersionPrefix = update.pbBetaVersionPrefix; //FIXME
#else
		update.szUpdateURL = "http://addons.miranda-im.org/feed.php?dlfile=3200";
		update.szVersionURL = "http://addons.miranda-im.org/details.php?action=viewfile&id=3200";
		update.pbVersionPrefix = (BYTE *)"<span class=\"fileNameHeader\">Skype Protocol</span>";
#endif
#endif

		update.cpbVersionPrefix = (DWORD)strlen((char *)update.pbVersionPrefix);
		update.cpbBetaVersionPrefix = (DWORD)strlen((char *)update.pbBetaVersionPrefix);

		CallService(MS_UPDATE_REGISTER, 0, (WPARAM)&update);

	}
}*/

/*
 * ShowMessage
 *
 * Shows a popup, if the popup plugin is enabled.
 * mustShow: 1 -> If Popup-Plugin is not available/disabled, show Message
 *                in a Messagewindow
 *                If the Popup-Plugin is enabled, let the message stay on
 *                screen until someone clicks it away.
 *           0 -> If Popup-Plugin is not available/disabled, skip message
 * Returns 0 on success, -1 on failure
 *
 */
int ShowMessage(int iconID, TCHAR *lpzText, int mustShow) {



	if (DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "SuppressErrors", 0)) return -1;
	lpzText=TranslateTS(lpzText);

	if (bModulesLoaded && PopupServiceExists && ServiceExists(MS_POPUP_ADDPOPUPT) && DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UsePopup", 0) && !MirandaShuttingDown) {
		BOOL showPopup, popupWindowColor;
		unsigned int popupBackColor, popupTextColor;
		int popupTimeSec;

		popupTimeSec = DBGetContactSettingDword(NULL, SKYPE_PROTONAME, "popupTimeSecErr", 4);
		popupTextColor = DBGetContactSettingDword(NULL, SKYPE_PROTONAME, "popupTextColorErr", GetSysColor(COLOR_WINDOWTEXT));
		popupBackColor = DBGetContactSettingDword(NULL, SKYPE_PROTONAME, "popupBackColorErr", GetSysColor(COLOR_BTNFACE));
		popupWindowColor = ( 0 != DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "popupWindowColorErr", TRUE));
		showPopup = ( 0 != DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "showPopupErr", TRUE));

		MessagePopup.lchContact = NULL;
		MessagePopup.lchIcon = LoadIcon(hInst,MAKEINTRESOURCE(iconID));
		MessagePopup.colorBack = ! popupWindowColor ? popupBackColor : GetSysColor(COLOR_BTNFACE);
		MessagePopup.colorText = ! popupWindowColor ? popupTextColor : GetSysColor(COLOR_WINDOWTEXT);
		MessagePopup.iSeconds = popupTimeSec;
		MessagePopup.PluginData = (void *)1;

		lstrcpy(MessagePopup.lptzText, lpzText);

#ifdef _UNICODE
		mbstowcs (MessagePopup.lptzContactName, SKYPE_PROTONAME, strlen(SKYPE_PROTONAME)+1);
#else
		lstrcpy(MessagePopup.lptzContactName, SKYPE_PROTONAME);
#endif

		if(showPopup)
			CallService(MS_POPUP_ADDPOPUPT,(WPARAM)&MessagePopup,0);

		return 0;
	}
	else {

		if (mustShow==1) MessageBox(NULL,lpzText,_T("Skype Protocol"), MB_OK | MB_ICONWARNING);
		return 0;
	}
}
#ifdef _UNICODE
int ShowMessageA(int iconID, char *lpzText, int mustShow) {
	WCHAR *lpwText;
	int iRet;
	size_t len = mbstowcs (NULL, lpzText, strlen(lpzText));
	if (len == -1 || !(lpwText = calloc(len+1,sizeof(WCHAR)))) return -1;
	mbstowcs (lpwText, lpzText, strlen(lpzText));
	iRet = ShowMessage(iconID, lpwText, mustShow);
	free (lpwText);
	return iRet;
}
#endif

// processing Hooks

int HookContactAdded(WPARAM wParam, LPARAM lParam) {
	char *szProto;

	UNREFERENCED_PARAMETER(lParam);

	szProto = (char*)CallService( MS_PROTO_GETCONTACTBASEPROTO, wParam, 0 );
	if (szProto!=NULL && !strcmp(szProto, SKYPE_PROTONAME))
		add_contextmenu((HANDLE)wParam);
	return 0;
}

int HookContactDeleted(WPARAM wParam, LPARAM lParam) {
	char *szProto;

	UNREFERENCED_PARAMETER(lParam);

	szProto = (char*)CallService( MS_PROTO_GETCONTACTBASEPROTO, wParam, 0 );
	if (szProto!=NULL && !strcmp(szProto, SKYPE_PROTONAME)) {
		DBVARIANT dbv;
		int retval;

		if (DBGetContactSettingString((HANDLE)wParam, SKYPE_PROTONAME, SKYPE_NAME, &dbv)) return 1;
		retval=SkypeSend("SET USER %s BUDDYSTATUS 1", dbv.pszVal);
		DBFreeVariant(&dbv);
		if (retval) return 1;
	}
	return 0;
}

void GetInfoThread(HANDLE hContact) {
	DBVARIANT dbv;
	int i;
	char *ptr;
	BOOL bSetNick = FALSE;
	// All properties are already handled in the WndProc, so we just consume the
	// messages here to do proper ERROR handling
	// If you add something here, be sure to handle it in WndProc, but let it
	// fall through there so that message gets added to the queue in order to be
	// consumed by SkypeGet
	char *pszProps[] = {
		"BIRTHDAY", "COUNTRY", "SEX", "MOOD_TEXT", "TIMEZONE", "IS_VIDEO_CAPABLE"};


	LOG (("GetInfoThread started."));
	EnterCriticalSection (&QueryThreadMutex);
	if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, SKYPE_NAME, &dbv))
	{
		LOG (("GetInfoThread terminated, cannot find Skype Name for contact %08X.", hContact));
		LeaveCriticalSection (&QueryThreadMutex);
		return;
	}

	if (ptr=SkypeGet ("USER", dbv.pszVal, "DISPLAYNAME")) {
		// WndProc sets Nick accordingly
		if (*ptr) bSetNick = TRUE;
		free (ptr);
	}

	if (ptr=SkypeGet ("USER", dbv.pszVal, "FULLNAME")) {
		if (*ptr && !bSetNick && DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "ShowFullname", 1)) {
			// No Displayname and FULLNAME requested
			SkypeDBWriteContactSettingUTF8String(hContact, SKYPE_PROTONAME, "Nick", ptr);
			bSetNick = TRUE;
		}
		free (ptr);
	}

	if (!bSetNick) {
		// Still no nick set, so use SKYPE Nickname
		DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "Nick", dbv.pszVal);
	}


	if (!bIsImoproxy)
	{
		for (i=0; i<sizeof(pszProps)/sizeof(pszProps[0]); i++)
			if (ptr=SkypeGet ("USER", dbv.pszVal, pszProps[i])) free (ptr);
	} else {
		if (ptr=SkypeGet ("USER", dbv.pszVal, "MOOD_TEXT")) free (ptr);
	}

	if (protocol >= 7 || bIsImoproxy) {
		// Notify about the possibility of an avatar
		ACKDATA ack = {0};
		ack.cbSize = sizeof( ACKDATA );
		ack.szModule = SKYPE_PROTONAME;
		ack.hContact = hContact;
		ack.type = ACKTYPE_AVATAR;
		ack.result = ACKRESULT_STATUS;

		CallService( MS_PROTO_BROADCASTACK, 0, ( LPARAM )&ack );
		//if (ptr=SkypeGet ("USER", dbv.pszVal, "RICH_MOOD_TEXT")) free (ptr);
	}

	if (!bIsImoproxy)
	{
		for (i=0; i<sizeof(m_settings)/sizeof(m_settings[0]); i++)
			if (ptr=SkypeGet ("USER", dbv.pszVal, m_settings[i].SkypeSetting)) free (ptr);
	}

	ProtoBroadcastAck(SKYPE_PROTONAME, hContact, ACKTYPE_GETINFO, ACKRESULT_SUCCESS, (HANDLE) 1, 0);
	LeaveCriticalSection(&QueryThreadMutex);
	DBFreeVariant(&dbv);
    LOG (("GetInfoThread terminated gracefully."));
}

time_t SkypeTime(time_t *timer) {
	struct _timeb tb;

	EnterCriticalSection (&TimeMutex);
	_ftime(&tb);
	if (timer) *timer=tb.time;
	LeaveCriticalSection (&TimeMutex);
	return tb.time;
}


void BasicSearchThread(char *nick) {
	PROTOSEARCHRESULT psr={0};
	char *cmd=NULL, *token=NULL, *ptr=NULL, *nextoken;
	time_t st;

    LOG (("BasicSearchThread started."));
	EnterCriticalSection (&QueryThreadMutex);
	SkypeTime(&st);
	if (SkypeSend("SEARCH USERS %s", nick)==0 && (cmd=SkypeRcvTime("USERS", st, INFINITE))) {
		if (strncmp(cmd, "ERROR", 5)) {
			psr.cbSize=sizeof(psr);
			for (token=strtok_r(cmd+5, ", ", &nextoken); token; token=strtok_r(NULL, ", ", &nextoken)) {
				TCHAR *t = mir_utf8decodeT(token), *_ptr = NULL;
				psr.nick=psr.id=t;
				psr.lastName=NULL;
				psr.firstName=NULL;
				psr.email=NULL;
				if (ptr=SkypeGet("USER", token, "FULLNAME")) {
					// We cannot use strtok() to seperate first & last name here,
					// because we already use it for parsing the user list
					// So we use our own function
					_ptr = mir_utf8decodeT(ptr);
					if (psr.lastName=_tcschr(_ptr, ' ')) {
						*psr.lastName=0;
						psr.lastName++;
						LOG(("BasicSearchThread: lastName=%s", psr.lastName));
					}
					psr.firstName=_ptr;
					LOG(("BasicSearchThread: firstName=%s", psr.firstName));
				}
				ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_SEARCH, ACKRESULT_DATA, (HANDLE)hSearchThread, (LPARAM)(PROTOSEARCHRESULT*)&psr);
				if (ptr) free(ptr);
				if(t) mir_free(t);
				if(_ptr) mir_free(_ptr);
			}
		} else {
			OUT(cmd);
		}
		free(cmd);
	}
	ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_SEARCH, ACKRESULT_SUCCESS, (HANDLE)hSearchThread, 0);
	free(nick);
	LeaveCriticalSection(&QueryThreadMutex);
    LOG (("BasicSearchThread terminated gracefully."));
	return;
}

INT_PTR SkypeDBWriteContactSettingUTF8String(HANDLE hContact,const char *szModule,const char *szSetting,const char *val)
{
	DBCONTACTWRITESETTING cws;
	INT_PTR iRet;

	// Try to save it as UTF8 sting to DB. If this doesn't succeed (i.e. older Miranda version), we convert
	// accordingly and try to save again.

	cws.szModule=szModule;
	cws.szSetting=szSetting;
	cws.value.type=DBVT_UTF8;
	cws.value.pszVal=(char*)val;
	// DBVT_UTF8 support started with version 0.5.0.0, right...?
	if (mirandaVersion < 0x050000 || (iRet = CallService(MS_DB_CONTACT_WRITESETTING,(WPARAM)hContact,(LPARAM)&cws)))
	{
		// Failed, try to convert and then try again
		cws.value.type=DBVT_TCHAR;
		if (!(cws.value.ptszVal = make_tchar_string((const unsigned char*)val))) return -1;
		iRet = CallService(MS_DB_CONTACT_WRITESETTING,(WPARAM)hContact,(LPARAM)&cws);
		free (cws.value.pszVal);
	}
	return iRet;
}


// added by TioDuke
void GetDisplaynameThread(char *dummy) {
	DBVARIANT dbv;
	char *ptr;

	UNREFERENCED_PARAMETER(dummy);

	LOG(("GetDisplaynameThread started."));
	if (DBGetContactSettingString(NULL, SKYPE_PROTONAME, SKYPE_NAME, &dbv)) {
		LOG(("GetDisplaynameThread terminated."));
		return;
	}
	EnterCriticalSection(&QueryThreadMutex);
    if ((ptr=SkypeGet("USER", dbv.pszVal, "FULLNAME"))) {
		if (*ptr) SkypeDBWriteContactSettingUTF8String(NULL, SKYPE_PROTONAME, "Nick", ptr);
		free(ptr);
	}
	DBFreeVariant(&dbv);
	LeaveCriticalSection(&QueryThreadMutex);
    LOG(("GetDisplaynameThread terminated gracefully."));
}


// Starts importing history from Skype
INT_PTR ImportHistory(WPARAM wParam, LPARAM lParam) {
	DBVARIANT dbv;

	UNREFERENCED_PARAMETER(lParam);

	if (DBGetContactSettingByte((HANDLE)wParam, SKYPE_PROTONAME, "ChatRoom", 0)) {
		if (DBGetContactSettingString((HANDLE)wParam, SKYPE_PROTONAME, "ChatRoomID", &dbv)) return 0;
		SkypeSend ("GET CHAT %s CHATMESSAGES", dbv.pszVal);
	} else {
		if (DBGetContactSettingString((HANDLE)wParam, SKYPE_PROTONAME, SKYPE_NAME, &dbv)) return 0;
		SkypeSend("SEARCH %sS %s", cmdMessage, dbv.pszVal);
	}
	DBFreeVariant(&dbv);
	return 0;
}

int SearchFriends(void) {
	char *ptr, *token, *pStat, *nextoken;
	int iRet = 0;
	time_t st;

	SkypeTime(&st);
	if (SkypeSend("SEARCH FRIENDS")!=-1 && (ptr=SkypeRcvTime("USERS", st, INFINITE)))
	{
		if (strncmp(ptr, "ERROR", 5)) {
			if (ptr+5) {
				for (token=strtok_r(ptr+5, ", ", &nextoken); token; token=strtok_r(NULL, ", ", &nextoken)) {
					if (!(pStat = SkypeGet("USER", token, "ONLINESTATUS")))
					{
						iRet = -1;
						break;
					}
					free (pStat);
				}
			}
		} else iRet=-1;
		free(ptr);
	} else iRet=-1;
	return iRet;
}

void __cdecl SearchUsersWaitingMyAuthorization(void *dummy) {
	char *cmd, *token, *nextoken;

	UNREFERENCED_PARAMETER(dummy);

	if (SkypeSend("#UWA SEARCH USERSWAITINGMYAUTHORIZATION")) return;
	if (!(cmd=SkypeRcv("#UWA USERS", INFINITE))) return;
	if (!strncmp(cmd, "ERROR", 5)) {
		free(cmd);
		return;
	}

	token=strtok_r(cmd+10, ", ", &nextoken);
	while (token) {
		CCSDATA ccs={0};
		PROTORECVEVENT pre={0};
		HANDLE hContact;
		char *firstname=NULL, *lastname=NULL, *pCurBlob;

		LOG(("Awaiting auth: %s", token));
		ccs.szProtoService=PSR_AUTH;
		ccs.hContact=hContact=add_contact(token, PALF_TEMPORARY);
		ccs.wParam=0;
		ccs.lParam=(LPARAM)&pre;
		pre.flags=0;
		pre.timestamp=(DWORD)SkypeTime(NULL);

		/* blob is: */
		//DWORD protocolSpecific HANDLE hContact
		//ASCIIZ nick, firstName, lastName, e-mail, requestReason
		if (firstname=SkypeGet("USER", token, "FULLNAME"))
			if (lastname=strchr(firstname, ' ')) {
				*lastname=0;
				lastname++;
			}

		pre.lParam=sizeof(DWORD)*2 + strlen(token)+5;
		if (firstname) pre.lParam += strlen(firstname);
		if (lastname) pre.lParam += strlen(lastname);
		if (pre.szMessage  = pCurBlob = (char *)calloc(1, pre.lParam)) {
			pCurBlob+=sizeof(DWORD); // Not used
			*(DWORD*)pCurBlob = (DWORD)hContact;  pCurBlob += sizeof(DWORD);
			strcpy((char *)pCurBlob,token);       pCurBlob += strlen((char *)pCurBlob)+1;
			if (firstname) {
				strcpy((char *)pCurBlob,firstname);
				if (lastname) {
					pCurBlob+=strlen((char *)pCurBlob)+1;
					strcpy((char *)pCurBlob,lastname);
				}
			}
			CallService(MS_PROTO_CHAINRECV,0,(LPARAM)&ccs);
			free(pre.szMessage);
		}
		if (firstname) free(firstname);
		token=strtok_r(NULL, ", ", &nextoken);
	}
	free(cmd);
	return;
}

void SearchFriendsThread(char *dummy) {
	UNREFERENCED_PARAMETER(dummy);

	if (!SkypeInitialized) return;
    LOG(("SearchFriendsThread started."));
	EnterCriticalSection(&QueryThreadMutex);
	SkypeInitialized=FALSE;
	SearchFriends();
	SkypeInitialized=TRUE;
	LeaveCriticalSection(&QueryThreadMutex);
    LOG(("SearchFriendsThread terminated gracefully."));
}

void __cdecl SearchRecentChats(void *dummy) {
	char *cmd, *token, *nextoken;

	UNREFERENCED_PARAMETER(dummy);

	if (SkypeSend("#RCH SEARCH RECENTCHATS")) return;
	if (!(cmd=SkypeRcv("#RCH CHATS", INFINITE))) return;
	if (!strncmp(cmd, "ERROR", 5)) {
		free(cmd);
		return;
	}

	for (token=strtok_r(cmd+10, ", ", &nextoken); token; token=strtok_r(NULL, ", ", &nextoken)) {
		char *pszStatus = SkypeGet ("CHAT", token, "STATUS");

		if (pszStatus) {
			if (!strcmp(pszStatus, "MULTI_SUBSCRIBED")) {
				// Add chatrooms for active multisubscribed chats
				/*if (!find_chatA(token)) */{
					char *pszTopic;

					EnterCriticalSection (&QueryThreadMutex);
					ChatStart(token, TRUE);
					if (pszTopic = SkypeGet ("CHAT", token, "TOPIC")) {
						TCHAR *psztChatName, *psztTopic;

						if (!*pszTopic) {
							free (pszTopic);
							if (pszTopic = SkypeGet ("CHAT", token, "FRIENDLYNAME"));
						}
						psztChatName = make_nonutf_tchar_string((const unsigned char*)token);
						psztTopic = make_tchar_string((const unsigned char*)pszTopic);
						SetChatTopic (psztChatName, psztTopic, FALSE);
						free_nonutf_tchar_string(psztChatName);
						free (psztTopic);
						free (pszTopic);
					}
					LeaveCriticalSection (&QueryThreadMutex);
				}
			}
			free (pszStatus);
		}
	}
	free(cmd);
	return;
}


void __cdecl SkypeSystemInit(char *dummy) {
	static BOOL Initializing=FALSE;
	DBVARIANT dbv={0};

	UNREFERENCED_PARAMETER(dummy);

    LOG (("SkypeSystemInit thread started."));
	if (SkypeInitialized || Initializing)
	{
		LOG (("SkypeSystemInit terminated, nothing to do."));
		return;
	}
	Initializing=TRUE;
// Do initial Skype-Tasks
	logoff_contacts(FALSE);
// Add friends

	// Clear currentuserhandle entries from queue
	while (testfor ("CURRENTUSERHANDLE", 0));
	if (SkypeSend(SKYPE_PROTO)==-1 || !testfor("PROTOCOL", INFINITE) ||
		SkypeSend("GET CURRENTUSERHANDLE")==-1 ||
		SkypeSend("GET PRIVILEGE SKYPEOUT")==-1) {
		Initializing=FALSE;
        LOG (("SkypeSystemInit thread stopped with failure."));
		return;
	}

	if(DBGetContactSettingString(NULL,SKYPE_PROTONAME,"LoginUserName",&dbv) == 0)
	{
		if (*dbv.pszVal)
		{
			char *pszUser;

			// Username is set in Plugin, therefore we need to match it
			// against CURRENTUSERHANDLE
			if (pszUser = SkypeRcv ("CURRENTUSERHANDLE", INFINITE))
			{
				memmove (pszUser, pszUser+18, strlen(pszUser+17));
				if (_stricmp(dbv.pszVal, pszUser))
				{
					char szError[256];

					// Doesn't match, maybe we have a second Skype instance we have to take
					// care of? If in doubt, let's wait a while for it to report its hWnd to us.
					LOG (("Userhandle %s doesn't match username %s from settings", pszUser, dbv.pszVal));
					if (!hSkypeWndSecondary) Sleep(3000);
					if (hSkypeWndSecondary)
					{
						hSkypeWnd = hSkypeWndSecondary;
						hSkypeWndSecondary = NULL;
						Initializing=FALSE;
						while (testfor ("CURRENTUSERHANDLE", 0));
						LOG (("Trying to init secondary Skype instance"));
						SkypeSystemInit(dummy);
					}
					else
					{
						hForbiddenSkypeWnd = hSkypeWnd;

						// If we need to start Skype as secondary instance, we should do it now
						if (DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "StartSkype", 1) &&
							DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "secondary", 0))
						{
							int oldstatus;

							hSkypeWnd = NULL;
							AttachStatus=-1;
							if (g_hWnd) KillTimer (g_hWnd, 1);
							oldstatus = SkypeStatus;
							InterlockedExchange((long *)&SkypeStatus, ID_STATUS_CONNECTING);
							ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldstatus, SkypeStatus);
							ConnectToSkypeAPI(skype_path, 1);
						}
						if (hForbiddenSkypeWnd == hSkypeWnd && !hSkypeWndSecondary)
						{
							int oldstatus;

							sprintf (szError, "Username '%s' provided by Skype API doesn't match username '%s' in "
								"your settings. Please either remove username setting in you configuration or correct "
								"it. Will not connect!", pszUser, dbv.pszVal);
							OUTPUTA (szError);
							Initializing=FALSE;
							AttachStatus=-1;
							logoff_contacts(FALSE);
							if (g_hWnd) KillTimer (g_hWnd, 1);
							hSkypeWnd = NULL;
							oldstatus = SkypeStatus;
							InterlockedExchange((long *)&SkypeStatus, ID_STATUS_OFFLINE);
							ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldstatus, SkypeStatus);
						}
					}
				}
				free (pszUser);
			}
		}
		DBFreeVariant(&dbv);
		if (!Initializing) return;
	}

#ifdef SKYPEBUG_OFFLN
    if (!ResetEvent(GotUserstatus) || SkypeSend("GET USERSTATUS")==-1 ||
		WaitForSingleObject(GotUserstatus, INFINITE)==WAIT_FAILED)
	{
        LOG (("SkypeSystemInit thread stopped with failure."));
		Initializing=FALSE;
		return;
	}
	if (SkypeStatus!=ID_STATUS_OFFLINE)
#endif
	if (SearchFriends()==-1) {
        LOG (("SkypeSystemInit thread stopped with failure."));
		Initializing=FALSE;
		return;
	}
	if (protocol>=5 || bIsImoproxy) {
		SkypeSend ("CREATE APPLICATION libpurple_typing");
		testfor ("CREATE APPLICATION libpurple_typing", 2000);
	}
	if (protocol>=5 || bIsImoproxy) {
		SearchUsersWaitingMyAuthorization(NULL);
		if (DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseGroupchat", 0))
			SearchRecentChats(NULL);
	}
	SkypeSend("SEARCH MISSED%sS", cmdMessage);


#ifndef SKYPEBUG_OFFLN
	if (SkypeSend("GET USERSTATUS")==-1)
	{
        LOG (("SkypeSystemInit thread stopped with failure."));
		Initializing=FALSE;
		return;
	}
#endif
	SetTimer (g_hWnd, 1, PING_INTERVAL, NULL);
	SkypeInitialized=TRUE;
	Initializing=FALSE;
	LOG (("SkypeSystemInit thread terminated gracefully."));
	return;
}

void FirstLaunch(char *dummy) {
	int counter=0;

	UNREFERENCED_PARAMETER(dummy);

	LOG (("FirstLaunch thread started."));
	if (!DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "StartSkype", 1) || ConnectToSkypeAPI(skype_path, FALSE)==-1)
	{
		int oldstatus=SkypeStatus;

		LOG(("OnModulesLoaded starting offline.."));
		InterlockedExchange((long *)&SkypeStatus, ID_STATUS_OFFLINE);
		ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldstatus, SkypeStatus);
	}
	if (AttachStatus==-1 || AttachStatus==SKYPECONTROLAPI_ATTACH_REFUSED || AttachStatus==SKYPECONTROLAPI_ATTACH_NOT_AVAILABLE) {
		LOG (("FirstLaunch thread stopped because of invalid Attachstatus."));
		return;
	}

	// When you launch Skype and Attach is Successfull, it still takes some time
	// until it becomes available for receiving messages.
	// Let's probe this with PINGing
	LOG(("CheckIfApiIsResponding Entering test loop"));
	for ( ;; ) {
		LOG(("Test #%d", counter));
		if (SkypeSend("PING")==-1) counter ++; else break;
		if (counter>=20) {
			OUTPUT(_T("Cannot reach Skype API, plugin disfunct."));
			LOG (("FirstLaunch thread stopped: cannot reach Skype API."));
			return;
		}
		Sleep(500);
	}
	LOG(("CheckIfApiIsResponding: Testing for PONG"));
	testfor("PONG", 2000); // Flush PONG from MsgQueue

	forkthread(( pThreadFunc )SkypeSystemInit, 0, NULL);
	LOG (("FirstLaunch thread terminated gracefully."));
}

int CreateTopToolbarButton(WPARAM wParam, LPARAM lParam) {
	TTBButton ttb={0};

	UNREFERENCED_PARAMETER(wParam);
	UNREFERENCED_PARAMETER(lParam);

	ttb.cbSize = sizeof(ttb);
	ttb.dwFlags = TTBBF_VISIBLE|TTBBF_SHOWTOOLTIP|TTBBF_DRAWBORDER;
	ttb.hbBitmapDown = ttb.hbBitmapUp = LoadBitmap(hInst,MAKEINTRESOURCE(IDB_CALL));
	ttb.pszServiceDown = ttb.pszServiceUp = SKYPEOUT_CALL;
	ttb.name=Translate("Do a SkypeOut-call");
	if ((int)(httbButton=(HANDLE)CallService(MS_TTB_ADDBUTTON, (WPARAM)&ttb, 0))==-1) httbButton=0;
	return 0;
}


int OnModulesLoaded(WPARAM wParam, LPARAM lParam) {
	bModulesLoaded=TRUE;

	UNREFERENCED_PARAMETER(wParam);
	UNREFERENCED_PARAMETER(lParam);

	PopupServiceExists = ServiceExists(MS_POPUP_ADDPOPUPEX);

	logoff_contacts(FALSE);

	HookEventsLoaded();
	//RegisterToUpdate();
	RegisterToDbeditorpp();
	VoiceServiceModulesLoaded();
	GCInit();

	add_contextmenu(NULL);
	if ( ServiceExists( MS_GC_REGISTER ))
	{
		GCREGISTER gcr = {0};
		static COLORREF crCols[1] = {0};
		char szEvent[MAXMODULELABELLENGTH];

		gcr.cbSize = sizeof( GCREGISTER );
		gcr.dwFlags = GC_CHANMGR | GC_TCHAR; // |GC_ACKMSG; // TODO: Not implemented yet
        gcr.ptszModuleDispName = _T("Skype protocol");
		gcr.pszModule = SKYPE_PROTONAME;
		if (CallService(MS_GC_REGISTER, 0, (LPARAM)&gcr))
		{
			OUTPUT(_T("Unable to register with Groupchat module!"));
		}
		_snprintf (szEvent, sizeof(szEvent), "%s\\ChatInit", SKYPE_PROTONAME);
		hInitChat = CreateHookableEvent(szEvent);
		hEvInitChat = HookEvent(szEvent, ChatInit);

		hChatEvent = HookEvent(ME_GC_EVENT, GCEventHook);
		hChatMenu = HookEvent(ME_GC_BUILDMENU, GCMenuHook);
        CreateServiceFunction (SKYPE_CHATNEW, SkypeChatCreate);
		CreateProtoService (PS_LEAVECHAT, GCOnLeaveChat);
		CreateProtoService (PS_JOINCHAT, GCOnJoinChat);
	}
	// Try folder service first
	hProtocolAvatarsFolder = NULL;
	if (ServiceExists(MS_FOLDERS_REGISTER_PATH))
	{
		char *tmpPath;

		if (!ServiceExists (MS_UTILS_REPLACEVARS) || !(tmpPath = Utils_ReplaceVars("%miranda_avatarcache%")))
			tmpPath = PROFILE_PATH;
		mir_snprintf(DefaultAvatarsFolder, sizeof(DefaultAvatarsFolder), "%s\\%s", tmpPath, SKYPE_PROTONAME);
		hProtocolAvatarsFolder = (HANDLE) FoldersRegisterCustomPath(SKYPE_PROTONAME, "Avatars Cache", DefaultAvatarsFolder);
	}

	if (hProtocolAvatarsFolder == NULL)
	{
		// Use defaults
		CallService(MS_DB_GETPROFILEPATH, (WPARAM) MAX_PATH, (LPARAM) DefaultAvatarsFolder);
		mir_snprintf(DefaultAvatarsFolder, sizeof(DefaultAvatarsFolder), "%s\\%s", DefaultAvatarsFolder, SKYPE_PROTONAME);
		CreateDirectoryA(DefaultAvatarsFolder, NULL);
	}

	forkthread(( pThreadFunc )FirstLaunch, 0, NULL);
	return 0;
}

void FetchMessageThread(fetchmsg_arg *pargs) {
	char *who=NULL, *type=NULL, *chat=NULL, *users=NULL, *msg=NULL, *status=NULL;
	char *ptr, *msgptr, szPartnerHandle[32], szBuf[128];
	int direction=0, msglen = 0;
	DWORD timestamp = 0, lwr=0;
    CCSDATA ccs={0};
    PROTORECVEVENT pre={0};
    HANDLE hContact = NULL, hDbEvent, hChat = NULL;
	DBEVENTINFO dbei={0};
	DBVARIANT dbv={0};
	fetchmsg_arg args;
	BOOL bEmoted=FALSE, isGroupChat=FALSE, bHasPartList=FALSE;
	BOOL bUseGroupChat = DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseGroupchat", 0);

	if (!pargs) return;
	args = *pargs;
	free (pargs);

	sprintf (szPartnerHandle, "%s_HANDLE", cmdPartner);
	pre.lParam = strtoul(args.msgnum, NULL, 10);
	if (args.bIsRead) pre.flags |= PREF_CREATEREAD;
	//pEvent = MsgList_FindMessage(pre.lParam);

	// Get Timestamp
	if (!args.pMsgEntry || !args.pMsgEntry->tEdited) {
		if (!(ptr=SkypeGet (cmdMessage, args.msgnum, "TIMESTAMP"))) return;
		if (strncmp(ptr, "ERROR", 5)) timestamp=atol(ptr);
		else timestamp=(DWORD)SkypeTime(NULL);
		free(ptr);
	} else timestamp=(DWORD)(args.pMsgEntry->tEdited);

	__try {
		// Get Chatname (also to determine if we need to relay this to a groupchat)
		if (!(chat=SkypeGetErr (cmdMessage, args.msgnum, "CHATNAME"))) __leave;
		if (hChat = find_chatA(chat)) isGroupChat=TRUE;

		// Get chat status
		if ((status=SkypeGetErr ("CHAT", chat, "STATUS")) &&
			!strcmp(status, "MULTI_SUBSCRIBED")) isGroupChat=TRUE;

		// Get chat type
		if (!(type=SkypeGetErr (cmdMessage, args.msgnum, "TYPE"))) __leave;
		bEmoted = strcmp(type, "EMOTED")==0;
		if (strcmp(type, "MULTI_SUBSCRIBED")==0) isGroupChat=TRUE;

		// Group chat handling
		if (isGroupChat && strcmp(type, "TEXT") && strcmp(type, "SAID") && strcmp(type, "UNKNOWN") && !bEmoted) {
			if (bUseGroupChat) {
				BOOL bAddedMembers = FALSE;

				if (!strcmp(type,"SAWMEMBERS") || !strcmp(type, "CREATEDCHATWITH"))
				{
					// We have a new Groupchat
					LOG(("FetchMessageThread CHAT SAWMEMBERS"));
					if (!hChat) ChatStart(chat, FALSE);
					__leave;
				}
				if (!strcmp(type,"KICKED"))
				{
					GCDEST gcd = {0};
					GCEVENT gce = {0};
					CONTACTINFO ci = {0};

					if (!hChat) __leave;
					gcd.pszModule = SKYPE_PROTONAME;
					gcd.ptszID = make_nonutf_tchar_string((const unsigned char*)chat);
					gcd.iType = GC_EVENT_KICK;
					gce.cbSize = sizeof(GCEVENT);
					gce.pDest = &gcd;
					gce.dwFlags = GCEF_ADDTOLOG | GC_TCHAR;
					gce.time = timestamp;

					if (users=SkypeGetErr (cmdMessage, args.msgnum, "USERS")) {
						ci.hContact = find_contact(users);
						gce.ptszUID= make_nonutf_tchar_string((const unsigned char*)users);
						if (who=SkypeGetErr (cmdMessage, args.msgnum, szPartnerHandle)) {
							gce.ptszStatus= make_nonutf_tchar_string((const unsigned char*)who);
							ci.cbSize = sizeof(ci);
							ci.szProto = SKYPE_PROTONAME;
							ci.dwFlag = CNF_DISPLAY | CNF_TCHAR;
							if (ci.hContact && !CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci)) gce.ptszNick=ci.pszVal;
							else gce.ptszNick=gce.ptszUID;

							CallService(MS_GC_EVENT, 0, (LPARAM)&gce);
							RemChatContact (GetChat(gcd.ptszID), gce.ptszUID);
							free_nonutf_tchar_string((void*)gce.ptszStatus);
							if (ci.pszVal) mir_free (ci.pszVal);
						}
						free_nonutf_tchar_string((void*)gce.ptszUID);
					}
					free_nonutf_tchar_string((void*)gcd.ptszID);
					__leave;
				}
				if (!strcmp(type,"SETROLE"))
				{
					GCDEST gcd = {0};
					GCEVENT gce = {0};
					CONTACTINFO ci = {0};
					gchat_contact *gcContact;
					char *pszRole;

					// FROM_HANDLE - Wer hats gesetzt
					// USERS - Wessen Rolle wurde gesetzt
					// ROLE - Die neue Rolle
					if (!hChat) __leave;
					gcd.pszModule = SKYPE_PROTONAME;
					gcd.ptszID = make_nonutf_tchar_string((const unsigned char*)chat);
					gcd.iType = GC_EVENT_REMOVESTATUS;
					gce.cbSize = sizeof(GCEVENT);
					gce.pDest = &gcd;
					gce.dwFlags = GCEF_ADDTOLOG | GC_TCHAR;
					gce.time = timestamp;

					if (users=SkypeGetErr (cmdMessage, args.msgnum, "USERS")) {
						gce.ptszUID= make_nonutf_tchar_string((const unsigned char*)users);
						if (who=SkypeGetErr (cmdMessage, args.msgnum, szPartnerHandle)) {
							ci.cbSize = sizeof(ci);
							ci.szProto = SKYPE_PROTONAME;
							ci.dwFlag = CNF_DISPLAY | CNF_TCHAR;
							ci.hContact = find_contact(who);
							if (ci.hContact && !CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci)) {
								gce.ptszText=_tcsdup(ci.pszVal);
								mir_free (ci.pszVal);
								ci.pszVal = NULL;
							}
							else gce.ptszText=make_tchar_string((const unsigned char*)who);

							ci.hContact = find_contact(users);
							if (ci.hContact && !CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci)) gce.ptszNick=ci.pszVal;
							else gce.ptszNick=gce.ptszUID;

							if (gcContact = GetChatContact(GetChat(gcd.ptszID), gce.ptszUID))
							{
								gce.ptszStatus = gcContact->szRole;
								CallService(MS_GC_EVENT, 0, (LPARAM)&gce);
							}
							if (pszRole=SkypeGetErr (cmdMessage, args.msgnum, "ROLE")) {
								gce.ptszStatus = make_nonutf_tchar_string((const unsigned char*)pszRole);
								gcd.iType = GC_EVENT_ADDSTATUS;
								CallService(MS_GC_EVENT, 0, (LPARAM)&gce);
								free_nonutf_tchar_string((void*)gce.ptszStatus);
								free (pszRole);
							}
							free((void*)gce.ptszText);
							if (ci.pszVal) mir_free (ci.pszVal);
						}
						free_nonutf_tchar_string((void*)gce.ptszUID);
					}
					free_nonutf_tchar_string((void*)gcd.ptszID);
					__leave;
				}
				if (!strcmp(type,"SETTOPIC"))
				{
					GCDEST gcd = {0};
					GCEVENT gce = {0};
					CONTACTINFO ci = {0};

					LOG(("FetchMessageThread CHAT SETTOPIC"));
					gcd.pszModule = SKYPE_PROTONAME;
					gcd.ptszID = make_nonutf_tchar_string((const unsigned char*)chat);
					gcd.iType = GC_EVENT_TOPIC;
					gce.cbSize = sizeof(GCEVENT);
					gce.pDest = &gcd;
					gce.dwFlags = GCEF_ADDTOLOG | GC_TCHAR;
					gce.time = timestamp;
					if (who=SkypeGetErr (cmdMessage, args.msgnum, szPartnerHandle)) {
						ci.hContact = find_contact(who);
						gce.ptszUID = make_nonutf_tchar_string((const unsigned char*)who);
						ci.cbSize = sizeof(ci);
						ci.szProto = SKYPE_PROTONAME;
						ci.dwFlag = CNF_DISPLAY | CNF_TCHAR;
						if (ci.hContact && !CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci)) gce.ptszNick=ci.pszVal;
						else gce.ptszNick=gce.ptszUID;

						if (ptr=SkypeGetErr (cmdMessage, args.msgnum, "BODY")) {
							gce.ptszText = make_tchar_string((const unsigned char*)ptr);
							CallService(MS_GC_EVENT, 0, (LPARAM)&gce);
							free ((void*)gce.ptszText);
							free (ptr);
						}
						free_nonutf_tchar_string ((void*)gce.ptszUID);
						if (ci.pszVal) mir_free (ci.pszVal);
					}
					free_nonutf_tchar_string((void*)gcd.ptszID);
					if (!args.bDontMarkSeen)
					{
						MsgList_Add (pre.lParam, INVALID_HANDLE_VALUE);
						SkypeSend("SET %s %s SEEN", cmdMessage, args.msgnum);
					}
					__leave;
				}
				if (!strcmp(type,"LEFT") || (bAddedMembers = strcmp(type,"ADDEDMEMBERS")==0))
				{
					GCDEST gcd = {0};
					GCEVENT gce = {0};
					CONTACTINFO ci = {0};
					char *pszInvited = Translate("invited ");

					LOG(("FetchMessageThread CHAT LEFT or ADDEDMEMBERS"));
					if (bAddedMembers) {
						gcd.pszModule = SKYPE_PROTONAME;
						gcd.ptszID = make_nonutf_tchar_string((const unsigned char*)chat);
						gcd.iType = GC_EVENT_ACTION;
						gce.cbSize = sizeof(GCEVENT);
						gce.pDest = &gcd;
						gce.dwFlags = GCEF_ADDTOLOG | GC_TCHAR;
						gce.time = timestamp;
						if (users=SkypeGetErr (cmdMessage, args.msgnum, "USERS")) {
							// We assume that users buffer has enough room for "invited" string
							memmove (users+strlen(pszInvited), users, strlen(users)+1);
							memcpy (users, pszInvited, strlen(pszInvited));
							gce.ptszText= make_tchar_string((const unsigned char*)users);
							if (who=SkypeGetErr (cmdMessage, args.msgnum, szPartnerHandle)) {
								DBVARIANT dbv;

								if (DBGetContactSettingString(NULL, SKYPE_PROTONAME, SKYPE_NAME, &dbv)==0) {
									gce.bIsMe = strcmp(who, dbv.pszVal)==0;
									DBFreeVariant(&dbv);
								}
								if (!gce.bIsMe) ci.hContact = find_contact(who);
								gce.ptszUID= make_nonutf_tchar_string((const unsigned char*)who);
								ci.cbSize = sizeof(ci);
								ci.szProto = SKYPE_PROTONAME;
								ci.dwFlag = CNF_DISPLAY | CNF_TCHAR;
								if (!CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci)) gce.ptszNick=ci.pszVal;
								else gce.ptszNick=gce.ptszUID;

								CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);
								free_nonutf_tchar_string((void*)gce.ptszUID);
								if (ci.pszVal) mir_free (ci.pszVal);
							}
							if (gce.ptszText) free ((void*)gce.ptszText);
						}
						free_nonutf_tchar_string ((void*)gcd.ptszID);
					}
					if (!args.QueryMsgDirection) SkypeSend ("GET CHAT %s MEMBERS", chat);
					__leave;
				}
			}
			__leave;
		}

		// Need to get the status?
		if (args.getstatus) {
			char *status;

			if (protocol<4) InterlockedIncrement (&rcvwatchers);
			status=SkypeGetID(cmdMessage, args.msgnum, "STATUS");
			if (protocol<4) InterlockedDecrement (&rcvwatchers);
			if (!status) __leave;
			if (!strcmp(status, "SENT")) direction=DBEF_SENT;
			free(status);
		}

		// Who sent it?
		if (!(who=SkypeGetErr (cmdMessage, args.msgnum, szPartnerHandle))) __leave;

		// Get contact handle
		LOG(("FetchMessageThread Finding contact handle"));
		DBGetContactSettingString(NULL, SKYPE_PROTONAME, SKYPE_NAME, &dbv);
		if (dbv.pszVal && !strcmp (who, dbv.pszVal))
		{
			char *pTok, *nextoken;

			// It's from me.. But to whom?
			// CHATMESSAGE .. USERS doesn't return anything, so we have to query the CHAT-Object
			if (!(ptr=SkypeGetErr ("CHAT", chat, "ACTIVEMEMBERS"))) {
				DBFreeVariant (&dbv);
				__leave;
			}

			for (pTok = strtok_r (ptr, " ", &nextoken); pTok; pTok=strtok_r(NULL, " ", &nextoken)) {
				if (strcmp (pTok, dbv.pszVal)) break; // Take the first dude in the list who is not me
			}

			if (!pTok) {
				free (ptr);
				DBFreeVariant (&dbv);
				__leave; // We failed
			}
			free (who);
			who=memmove (ptr, pTok, strlen(pTok)+1);
			direction = DBEF_SENT;
		}
		DBFreeVariant (&dbv);

		if (!(hContact=find_contact(who))) {
			// Permanent adding of user obsolete, we use the BUDDYSTATUS now (bug #0000005)
			ResetEvent(hBuddyAdded);
			SkypeSend("GET USER %s BUDDYSTATUS", who);
			WaitForSingleObject(hBuddyAdded, INFINITE);
			if (!(hContact=find_contact(who))) {
				// Arrgh, the user has been deleted from contact list.
				// In this case, we add him temp. to receive the msg at least.
				hContact=add_contact(who, PALF_TEMPORARY);
			}
		}
		// Text which was sent (on edited msg, BODY may already be in queue, check)
		sprintf (szBuf, "GET %s %s BODY", cmdMessage, args.msgnum);
		if (!args.pMsgEntry || !args.pMsgEntry->tEdited || !(ptr=SkypeRcv(szBuf+4, 1000)))
		{
			if (SkypeSend(szBuf)==-1 || !(ptr=SkypeRcv(szBuf+4, INFINITE)))
				__leave;
		}
		if (strncmp(ptr, "ERROR", 5)) {
			msgptr = ptr+strlen(szBuf+4)+1;
			bHasPartList = strncmp(msgptr,"<partlist ",10)==0;
			if (args.pMsgEntry && args.pMsgEntry->tEdited) {
				// Mark the message as edited
				if (!*msgptr && args.pMsgEntry->hEvent != INVALID_HANDLE_VALUE) {
					// Empty message and edited -> Delete event
					if ((int)(hContact = (HANDLE)CallService (MS_DB_EVENT_GETCONTACT, (WPARAM)args.pMsgEntry->hEvent, 0)) != -1) {
						CallService (MS_DB_EVENT_DELETE, (WPARAM)hContact, (LPARAM)args.pMsgEntry->hEvent);
						free (ptr);
						__leave;
					}
				} else {
					msgptr-=9;
					memcpy (msgptr, "[EDITED] ", 9);
				}
			}
			if( bEmoted && !isGroupChat) {
				CONTACTINFO ci = {0};
				int newlen;
				char *pMsg, *pszUTFnick=NULL;
				ci.cbSize = sizeof(ci);
				ci.szProto = SKYPE_PROTONAME;
				ci.dwFlag = CNF_DISPLAY | CNF_TCHAR;
				if (ci.hContact = hContact) {
					CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci);
					if (ci.pszVal) {
#ifdef _UNICODE
						pszUTFnick = (char*)make_utf8_string(ci.pszVal);
#else
						utf8_encode (ci.pszVal, &pszUTFnick);
#endif
						mir_free (ci.pszVal);
					}
				}
				newlen = strlen(msgptr) + (pszUTFnick?strlen(pszUTFnick):0) + 9;
				if (pMsg = malloc(newlen)) {
					sprintf (pMsg, "** %s%s%s **", (pszUTFnick?pszUTFnick:""),(pszUTFnick?" ":""),(char*)msgptr);
					free (ptr);
					ptr = msgptr = pMsg;
				}
				if (pszUTFnick) free(pszUTFnick);
			}

			if (mirandaVersion >= 0x070000 &&	// 0.7.0+ supports PREF_UTF flag, no need to decode UTF8
				!isGroupChat) {				// I guess Groupchat doesn't support UTF8?
				msg = ptr;
				pre.flags |= PREF_UTF;
			} else {	// Older version has to decode either UTF8->ANSI or UTF8->UNICODE
				// This could be replaced by mir_getUTFI - functions for Miranda 0.5+ builds, but we stay
				// 0.4 compatible for backwards compatibility. Unfortunately this requires us to link with utf8.c
#ifdef _UNICODE
				int wcLen;
#endif

				if (utf8_decode(msgptr, &msg)==-1) {
					free(ptr);
					__leave;
				}
#ifdef _UNICODE
				msglen = strlen(msg)+1;
				msgptr = (char*)make_unicode_string ((const unsigned char*)msgptr);
				wcLen  = (_tcslen((TCHAR*)msgptr)+1)*sizeof(TCHAR);
				msg=realloc(msg, msglen+wcLen);
				memcpy (msg+msglen, msgptr, wcLen);
				free(msgptr);
				pre.flags |= PREF_UNICODE;
#endif
				msgptr = msg;
				free (ptr);
			}
			msglen = strlen(msgptr)+1;
		} else {
			free (ptr);
			__leave;
		}
		// skype sends some xml statics after a call has finished. Check if thats the case and suppress it if necessary...
		if ((DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "SuppressCallSummaryMessage", 1) &&
			bHasPartList) || msgptr[0]==0) __leave;

		if (isGroupChat && bUseGroupChat) {
			GCDEST gcd = {0};
			GCEVENT gce = {0};
			DBVARIANT dbv = {0};
			CONTACTINFO ci = {0};

			LOG(("FetchMessageThread This is a group chat message"));
			if (!hChat) ChatStart(chat, FALSE);
			gcd.pszModule = SKYPE_PROTONAME;
			gcd.ptszID = make_nonutf_tchar_string((const unsigned char*)chat);
			gcd.iType = bEmoted?GC_EVENT_ACTION:GC_EVENT_MESSAGE;
			gce.cbSize = sizeof(GCEVENT);
			gce.pDest = &gcd;
			if ((gce.bIsMe = (direction&DBEF_SENT)?TRUE:FALSE) &&
				DBGetContactSettingString(NULL, SKYPE_PROTONAME, SKYPE_NAME, &dbv)==0)
			{
				free(who);
				who = _strdup(dbv.pszVal);
				DBFreeVariant(&dbv);
			}
			gce.ptszUID = make_nonutf_tchar_string((const unsigned char*)who);
			ci.cbSize = sizeof(ci);
			ci.szProto = SKYPE_PROTONAME;
			ci.dwFlag = CNF_DISPLAY | CNF_TCHAR;
			ci.hContact = !gce.bIsMe?hContact:NULL;
			gce.ptszNick=gce.ptszUID;
			if (!CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci)) gce.ptszNick=ci.pszVal;
			gce.time = timestamp>0?timestamp:(DWORD)SkypeTime(NULL);
			gce.pszText = msgptr;
			if (pre.flags & PREF_UNICODE) gce.pszText += msglen;
			gce.dwFlags = GCEF_ADDTOLOG | GC_TCHAR;
			CallService(MS_GC_EVENT, 0, (LPARAM)&gce);
			MsgList_Add (pre.lParam, INVALID_HANDLE_VALUE);	// Mark as groupchat
			if (ci.pszVal) mir_free (ci.pszVal);
			free_nonutf_tchar_string((void*)gce.ptszUID);
			free_nonutf_tchar_string(gcd.ptszID);

			// Yes, we have successfully read the msg
			if (!args.bDontMarkSeen)
				SkypeSend("SET %s %s SEEN", cmdMessage, args.msgnum);
			__leave;
		}

		if (args.QueryMsgDirection || (direction&DBEF_SENT)) {
			// Check if the timestamp is valid
			dbei.cbSize=sizeof(dbei);
			dbei.cbBlob=0;
			if (hDbEvent=(HANDLE)CallService(MS_DB_EVENT_FINDFIRST,(WPARAM)hContact,0)) {
				CallService(MS_DB_EVENT_GET,(WPARAM)hDbEvent,(LPARAM)&dbei);
				lwr=dbei.timestamp;
			}
			dbei.cbSize=sizeof(dbei);
			dbei.cbBlob=0;
			dbei.timestamp=0;
			if (hDbEvent=(HANDLE)CallService(MS_DB_EVENT_FINDLAST,(WPARAM)hContact,0))
				CallService(MS_DB_EVENT_GET,(WPARAM)hDbEvent,(LPARAM)&dbei);
			LOG(("FetchMessageThread timestamp %ld between %ld and %ld", timestamp, lwr, dbei.timestamp));
			if (timestamp<lwr || (direction&DBEF_SENT)) {
				TYP_MSGLENTRY *pme;

				LOG(("FetchMessageThread Adding event"));
				if (!(dbei.szModule=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0)))
					dbei.szModule=SKYPE_PROTONAME;
				dbei.cbBlob=msglen;
				if (pre.flags & PREF_UNICODE)
					dbei.cbBlob += sizeof(WCHAR)*( (DWORD)wcslen((WCHAR*)&msgptr[dbei.cbBlob])+1);
				dbei.pBlob=(PBYTE)msgptr;
				dbei.timestamp=timestamp>0?timestamp:(DWORD)SkypeTime(NULL);
				dbei.flags=direction;
				if (pre.flags & PREF_CREATEREAD) dbei.flags|=DBEF_READ;
				if (pre.flags & PREF_UTF) dbei.flags|=DBEF_UTF;
				dbei.eventType=EVENTTYPE_MESSAGE;
				pme = MsgList_Add (pre.lParam, (HANDLE)CallServiceSync(MS_DB_EVENT_ADD, (WPARAM)(HANDLE)hContact, (LPARAM)&dbei));

				// We could call MS_PROTO_CHAINSEND if we want to have MetaContact adding the history for us,
				// however we all know that CCSDATA doesn't contain timestamp-information which is
				// really bad on importing history for example, as all messages would be added with current
				// timestamp. This would cause unreliable jumbled timestamps in metacontact, so we better do this
				// ourself.
				if (DBGetContactSettingByte(hContact, "MetaContacts", "IsSubcontact", 0))
				{
					DWORD dwMetaLink = DBGetContactSettingDword(hContact, "MetaContacts", "MetaLink", MAXDWORD);
					HANDLE hMetaContact;

					if (dwMetaLink != MAXDWORD && (hMetaContact = GetMetaHandle(dwMetaLink)))
					{
						dbei.szModule=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hMetaContact, 0);
						pme->hMetaEvent = (HANDLE)CallServiceSync(MS_DB_EVENT_ADD, (WPARAM)(HANDLE)hMetaContact, (LPARAM)&dbei);
					}
				}

				if (!args.QueryMsgDirection && !args.bDontMarkSeen)
					SkypeSend("SET %s %s SEEN", cmdMessage, args.msgnum);
			}
		}


		if (!(direction&DBEF_SENT) && (!args.QueryMsgDirection || (args.QueryMsgDirection && timestamp>dbei.timestamp))) {
			LOG(("FetchMessageThread Normal message add..."));
			// Normal message received, process it
			ccs.szProtoService = PSR_MESSAGE;
			ccs.hContact = hContact;
			ccs.wParam = 0;
			ccs.lParam = (LPARAM)&pre;
			pre.flags |= direction;
			if(isGroupChat && DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "MarkGroupchatRead", 0))
				pre.flags |= PREF_CREATEREAD;
			pre.timestamp = timestamp>0?timestamp:(DWORD)SkypeTime(NULL);
			pre.szMessage = msgptr;
			CallServiceSync(MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);

			// Yes, we have successfully read the msg
			if (!args.bDontMarkSeen) SkypeSend("SET %s %s SEEN", cmdMessage, args.msgnum);
		}
	}
	__finally {
		if (status) free(status);
		if (msg) free(msg);
		if (users) free(users);
		if (chat) free(chat);
		if (type) free(type);
		if (who) free (who);
	}

}

void FetchMessageThreadSync(fetchmsg_arg *pargs) {
	// Secure this thread with a mutex.
	// This is needed to ensure that we get called after an old msg in the queue has
	// been added so that MsgList_FindEntry will find it.
	WaitForSingleObject (FetchMessageEvent, 30000);	// Wait max. 30 sec. for previous message fetch to complete
	if ((pargs->pMsgEntry = MsgList_FindMessage(strtoul(pargs->msgnum, NULL, 10))) && !pargs->pMsgEntry->tEdited) {
		// Better don't do this, as we set the msg as read and with this code, we would
		// mark messages not opened by user as read which isn't that good
		/*
		if (pargs->bIsRead && pMsgEvent->hEvent != INVALID_HANDLE_VALUE)
		{
			HANDLE hContact;
			if ((int)(hContact = (HANDLE)CallService (MS_DB_EVENT_GETCONTACT, (WPARAM)pMsgEntry->hEvent, 0)) != -1)
				CallService (MS_DB_EVENT_MARKREAD, (WPARAM)hContact, (LPARAM)hDBEvent);
		}
		*/
		free (pargs);
	}
	else FetchMessageThread (pargs);
	SetEvent (FetchMessageEvent);
}

static int MsglCmpProc(const void *pstPElement,const void *pstPToFind)
{
	return strcmp ((char*)((fetchmsg_arg*)pstPElement)->pMsgEntry, (char*)((fetchmsg_arg*)pstPToFind)->pMsgEntry);
}

void MessageListProcessingThread(char *str) {
	char *token, *nextoken, *chat=NULL;
	fetchmsg_arg *args;
	TYP_LIST *hListMsgs = List_Init(32);
	int i, nCount;

	// Frst we need to sort the message timestamps
	for ((token=strtok_r(str, ", ", &nextoken)); token; token=strtok_r(NULL, ", ", &nextoken)) {
		if (args=calloc(1, sizeof(fetchmsg_arg)+sizeof(DWORD))) {
			strncpy (args->msgnum, token, sizeof(args->msgnum));
			args->getstatus=TRUE;
			args->bIsRead=TRUE;
			args->bDontMarkSeen=TRUE;
			args->QueryMsgDirection=TRUE;
			(char*)args->pMsgEntry = SkypeGet ("CHATMESSAGE", token, "TIMESTAMP"); // Bad abuse of pointer
			if (!chat) chat=SkypeGet ("CHATMESSAGE", token, "CHATNAME");
			if (args->pMsgEntry) List_InsertSort (hListMsgs, MsglCmpProc, args);
			else free(args);
		}
	}
	for (i=0, nCount=List_Count(hListMsgs); i<nCount; i++) {
		args = List_ElementAt (hListMsgs, i);
		free (args->pMsgEntry);
		args->pMsgEntry = NULL;
		FetchMessageThreadSync (args);
	}
	if (chat) {
		SkypeSend ("GET CHAT %s MEMBERS", chat);
		free (chat);
	}
	List_Exit (hListMsgs);
	free (str);
}

char *GetCallerHandle(char *szSkypeMsg) {
	return SkypeGet(szSkypeMsg, "PARTNER_HANDLE", "");
}


HANDLE GetCallerContact(char *szSkypeMsg) {
	char *szHandle;
	HANDLE hContact=NULL;

	if (!(szHandle=GetCallerHandle(szSkypeMsg))) return NULL;
	if (!(hContact=find_contact(szHandle))) {
		// If it's a SkypeOut-contact, PARTNER_HANDLE = SkypeOUT number
		DBVARIANT dbv;
		int tCompareResult;

		for (hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);hContact != NULL;hContact=(HANDLE)CallService( MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0)) {
			if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, "SkypeOutNr", &dbv)) continue;
			tCompareResult = strcmp(dbv.pszVal, szHandle);
			DBFreeVariant(&dbv);
			if (tCompareResult) continue; else break;
		}
	}
	free(szHandle);
	if (!hContact) {LOG(("GetCallerContact Not found!"));}
	return hContact;
}

HANDLE GetMetaHandle(DWORD dwId) {
    HANDLE hContact;
    char *szProto;

	for (hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);hContact != NULL;hContact=(HANDLE)CallService( MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0)) {
		szProto = (char*)CallService( MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0 );
		if (szProto!=NULL && !strcmp(szProto, "MetaContacts") &&
			DBGetContactSettingDword(hContact, "MetaContacts", "MetaID", MAXDWORD)==dwId)
				return hContact;
    }
    return 0;
}

LRESULT CALLBACK InCallPopUpProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
	switch(msg)
	{
		case WM_COMMAND:
			break;

		case WM_CONTEXTMENU:
			SendMessage(hwnd,UM_DESTROYPOPUP,0,0);
			break;
		case UM_FREEPLUGINDATA:
			//Here we'd free our own data, if we had it.
			return FALSE;
		case UM_INITPOPUP:
			break;
		case UM_DESTROYPOPUP:
			break;
		case WM_NOTIFY:
		default:
			break;
	}
	return DefWindowProc(hwnd,msg,wParam,lParam);
}

void RingThread(char *szSkypeMsg) {
	HANDLE hContact;
	DBEVENTINFO dbei={0};
	DBVARIANT dbv;
	char *ptr = NULL;

	// We use a single critical section for the RingThread- and the EndCallThread-functions
	// so that only one function is running at the same time. This is needed, because when
	// a initated and unaccepted call (which is still ringing) is hangup/canceled, skype
	// sends two messages. First "CALL xxx STATUS RINGING" .. second "CALL xx STATUS CANCELED".
	// This starts two independend threads (first: RingThread; second: EndCallThread). Now
	// the two message are processed in reverse order sometimes. This causes the EndCallThread to
	// delete the contacts "CallId" property and after that the RingThread saves the contacts
	// "CallId" again. After that its not possible to call this contact, because the plugin
	// thinks that there is already a call going and the hangup-function isnt working, because
	// skype doesnt accept status-changes for finished calls. The CriticalSection syncronizes
	// the threads and the messages are processed in correct order.
	// Not the best solution, but it works.
	EnterCriticalSection (&RingAndEndcallMutex);

  LOG(("RingThread started."));
	if (protocol >= 5) SkypeSend ("MINIMIZE");
	if (hContact=GetCallerContact(szSkypeMsg)) {
		// Make sure that an answering thread is not already in progress so that we don't get
		// the 'Incoming call' event twice
		if (!DBGetContactSettingString(hContact, SKYPE_PROTONAME, "CallId", &dbv)) {
			DBFreeVariant(&dbv);
            LOG(("RingThread terminated."));
			goto l_exitRT;
		}
		DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "CallId", szSkypeMsg);
	}

	if (!(ptr=SkypeGet(szSkypeMsg, "TYPE", ""))) {
        LOG(("RingThread terminated."));
		goto l_exitRT;;
	}

	if (!strncmp(ptr, "INCOMING", 8))
		NofifyVoiceService(hContact, szSkypeMsg, VOICE_STATE_RINGING);
	else
		NofifyVoiceService(hContact, szSkypeMsg, VOICE_STATE_CALLING);

	if (!strncmp(ptr, "INCOMING", 8)) {
		if (!hContact) {
			char *szHandle;

			if (szHandle=GetCallerHandle(szSkypeMsg)) {
				if (!(hContact=add_contact(szHandle, PALF_TEMPORARY))) {
					free(szHandle);
					goto l_exitRT;
				}
				DBDeleteContactSetting(hContact, "CList", "Hidden");
				DBWriteContactSettingWord(hContact, SKYPE_PROTONAME, "Status", (WORD)SkypeStatusToMiranda("SKYPEOUT"));
				DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "SkypeOutNr", szHandle);
				free(szHandle);
			} else goto l_exitRT;
		}
	}

	if (HasVoiceService()) {
		// Voice service will handle it
		goto l_exitRT;
	}

	dbei.cbSize=sizeof(dbei);
	dbei.eventType=EVENTTYPE_CALL;
	dbei.szModule=SKYPE_PROTONAME;
	dbei.timestamp=(DWORD)SkypeTime(NULL);
	dbei.pBlob=(unsigned char*)Translate("Phonecall");
	dbei.cbBlob=strlen((const char*)dbei.pBlob)+1;
	if (!strncmp(ptr, "INCOMING", 8))
	{
		CLISTEVENT cle={0};
		char toolTip[256];

		if(PopupServiceExists)
		{
			BOOL showPopup, popupWindowColor;
			unsigned int popupBackColor, popupTextColor;
			int popupTimeSec;
			POPUPDATAT InCallPopup;
			TCHAR * lpzContactName = (TCHAR*)CallService(MS_CLIST_GETCONTACTDISPLAYNAME,(WPARAM)hContact,GCDNF_TCHAR);

			popupTimeSec = DBGetContactSettingDword(NULL, SKYPE_PROTONAME, "popupTimeSec", 4);
			popupTextColor = DBGetContactSettingDword(NULL, SKYPE_PROTONAME, "popupTextColor", GetSysColor(COLOR_WINDOWTEXT));
			popupBackColor = DBGetContactSettingDword(NULL, SKYPE_PROTONAME, "popupBackColor", GetSysColor(COLOR_BTNFACE));
			popupWindowColor = (0 != DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "popupWindowColor", TRUE));
			showPopup = (0 != DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "showPopup", TRUE));

			InCallPopup.lchContact = hContact;
			InCallPopup.lchIcon = LoadIcon(hInst,MAKEINTRESOURCE(IDI_CALL));
			InCallPopup.colorBack = ! popupWindowColor ? popupBackColor : GetSysColor(COLOR_BTNFACE);
			InCallPopup.colorText = ! popupWindowColor ? popupTextColor : GetSysColor(COLOR_WINDOWTEXT);
			InCallPopup.iSeconds = popupTimeSec;
			InCallPopup.PluginWindowProc = (WNDPROC)InCallPopUpProc;
			InCallPopup.PluginData = (void *)1;

			lstrcpy(InCallPopup.lptzText, TranslateT("Incoming Skype Call"));

			lstrcpy(InCallPopup.lptzContactName, lpzContactName);

			if(showPopup)
				CallService(MS_POPUP_ADDPOPUPT,(WPARAM)&InCallPopup,0);

		}
		cle.cbSize=sizeof(cle);
		cle.hIcon=LoadIcon(hInst,MAKEINTRESOURCE(IDI_CALL));
		cle.pszService=SKYPE_ANSWERCALL;
		dbei.flags=DBEF_READ;
		cle.hContact=hContact;
		cle.hDbEvent=(HANDLE)CallService(MS_DB_EVENT_ADD,(WPARAM)hContact,(LPARAM)&dbei);
		_snprintf(toolTip,sizeof(toolTip),Translate("Incoming call from %s"),(char*)CallService(MS_CLIST_GETCONTACTDISPLAYNAME,(WPARAM)hContact,0));
		cle.pszTooltip=toolTip;
		CallServiceSync(MS_CLIST_ADDEVENT,0,(LPARAM)&cle);
	}
	else
	{
		dbei.flags=DBEF_SENT;
		CallService(MS_DB_EVENT_ADD,(WPARAM)hContact,(LPARAM)&dbei);
	}

l_exitRT:
	if (ptr) free (ptr);
	free(szSkypeMsg);
	LeaveCriticalSection (&RingAndEndcallMutex);
}

void EndCallThread(char *szSkypeMsg) {
	HANDLE hContact=NULL, hDbEvent;
	DBEVENTINFO dbei={0};
	DBVARIANT dbv;
	int tCompareResult;

	// We use a single critical section for the RingThread- and the EndCallThread-functions
	// so that only one function is running at the same time. This is needed, because when
	// a initated and unaccepted call (which is still ringing) is hangup/canceled, skype
	// sends two messages. First "CALL xxx STATUS RINGING" .. second "CALL xx STATUS CANCELED".
	// This starts two independend threads (first: RingThread; second: EndCallThread). Now
	// the two message are processed in reverse order sometimes. This causes the EndCallThread to
	// delete the contacts "CallId" property and after that the RingThread saves the contacts
	// "CallId" again. After that its not possible to call this contact, because the plugin
	// thinks that there is already a call going and the hangup-function isnt working, because
	// skype doesnt accept status-changes for finished calls. The CriticalSection syncronizes
	// the threads and the messages are processed in correct order.
	// Not the best solution, but it works.
	EnterCriticalSection (&RingAndEndcallMutex);

  LOG(("EndCallThread started."));
	if (szSkypeMsg) {
		for (hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);hContact != NULL;hContact=(HANDLE)CallService( MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0)) {
			if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, "CallId", &dbv)) continue;
			tCompareResult = strcmp(dbv.pszVal, szSkypeMsg);
			DBFreeVariant(&dbv);
			if (tCompareResult) continue; else break;
		}
	}
	if (hContact)
	{
		NofifyVoiceService(hContact, szSkypeMsg, VOICE_STATE_ENDED);

		DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "CallId");

		if (!HasVoiceService()) {
			dbei.cbSize=sizeof(dbei);
			hDbEvent=(HANDLE)CallService(MS_DB_EVENT_FINDFIRSTUNREAD,(WPARAM)hContact,0);
			while(hDbEvent) {
				dbei.cbBlob=0;
				CallService(MS_DB_EVENT_GET,(WPARAM)hDbEvent,(LPARAM)&dbei);
					if (!(dbei.flags&(DBEF_SENT|DBEF_READ)) && dbei.eventType==EVENTTYPE_CALL) {
					CallService(MS_DB_EVENT_MARKREAD,(WPARAM)hContact,(LPARAM)hDbEvent);
					CallService(MS_CLIST_REMOVEEVENT,(WPARAM)hContact,(LPARAM)hDbEvent);
				}
				if (dbei.pBlob) free(dbei.pBlob);
				hDbEvent=(HANDLE)CallService(MS_DB_EVENT_FINDNEXT,(WPARAM)hDbEvent,0);
			}
		}

		if (!DBGetContactSettingString(hContact, SKYPE_PROTONAME, "SkypeOutNr", &dbv)) {
			DBFreeVariant(&dbv);
			if (!strcmp((char *)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0), SKYPE_PROTONAME) &&
				DBGetContactSettingByte(hContact, "CList", "NotOnList", 0)
			   )
					CallService(MS_DB_CONTACT_DELETE, (WPARAM)hContact, 0);
		}
	}
	free(szSkypeMsg);
	LeaveCriticalSection (&RingAndEndcallMutex);
}

void HoldCallThread(char *szSkypeMsg) {
	HANDLE hContact;

	LOG(("HoldCallThread started"));
    if (!szSkypeMsg) {
		LOG(("HoldCallThread terminated."));
		return;
	}
	if (hContact=GetCallerContact(szSkypeMsg)) {
		DBWriteContactSettingByte(hContact, SKYPE_PROTONAME, "OnHold", 1);
		NofifyVoiceService(hContact, szSkypeMsg, VOICE_STATE_ON_HOLD);
	}
	free(szSkypeMsg);
	LOG(("HoldCallThread terminated gracefully"));
}

void ResumeCallThread(char *szSkypeMsg) {
	HANDLE hContact;

	LOG(("ResumeCallThread started"));
	if (!szSkypeMsg) {
		LOG(("ResumeCallThread terminated."));
		return;
	}
	if (hContact=GetCallerContact(szSkypeMsg)) {
		DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "OnHold");
		NofifyVoiceService(hContact, szSkypeMsg, VOICE_STATE_TALKING);
	}
	free(szSkypeMsg);
    LOG(("ResumeCallThread terminated gracefully."));
}

int SetUserStatus(void) {
   if (RequestedStatus && AttachStatus!=-1) {
	if (SkypeSend("SET USERSTATUS %s", RequestedStatus)==-1) return 1;
   }
   return 0;
}

void LaunchSkypeAndSetStatusThread(void *newStatus) {

/*	   if (!DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UnloadOnOffline", 0)) {
		   logoff_contacts();
		   return 1;
	   }
*/
	int oldStatus=SkypeStatus;
	static BOOL bLaunching = FALSE;

	UNREFERENCED_PARAMETER(newStatus);

	if (bLaunching) return;
	bLaunching = TRUE;
	LOG (("LaunchSkypeAndSetStatusThread started."));
	InterlockedExchange((long *)&SkypeStatus, (int)ID_STATUS_CONNECTING);
	ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, SkypeStatus);

	if (ConnectToSkypeAPI(skype_path, 1)!=-1) {
		forkthread(( pThreadFunc )SkypeSystemInit, 0, NULL);
		//InterlockedExchange((long *)&SkypeStatus, (int)newStatus);
		//ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, SkypeStatus);
		SetUserStatus();
	}

	LOG (("LaunchSkypeAndSetStatusThread terminated gracefully."));
	bLaunching = FALSE;
}

LONG APIENTRY WndProc(HWND hWndDlg, UINT message, UINT wParam, LONG lParam)
{
    PCOPYDATASTRUCT CopyData;
	char *ptr, *szSkypeMsg=NULL, *nick, *buf;
	static char *onlinestatus=NULL;
	static BOOL RestoreUserStatus=FALSE;
	int sstat, oldstatus, flag;
	HANDLE hContact;
	fetchmsg_arg *args;
	static int iReentranceCnt = 0;

	iReentranceCnt++;
    switch (message)
    {
        case WM_COPYDATA:
		 LOG(("WM_COPYDATA start"));
		 if(hSkypeWnd==(HWND)wParam) {
			char *pData;
			CopyData=(PCOPYDATASTRUCT)lParam;
			pData = (char*)CopyData->lpData;
			while (*pData==' ') pData++;
			szSkypeMsg=_strdup((char*)pData);
			ReplyMessage(1);
			LOG(("< %s", szSkypeMsg));

 			if (!strncmp(szSkypeMsg, "CONNSTATUS", 10)) {
				if (!strncmp(szSkypeMsg+11, "LOGGEDOUT", 9)) {
					SkypeInitialized=FALSE;
					ResetEvent(SkypeReady);
					AttachStatus=-1;
					sstat=ID_STATUS_OFFLINE;
				    if (g_hWnd) KillTimer (g_hWnd, 1);
					logoff_contacts(TRUE);
				} else
					sstat=SkypeStatusToMiranda(szSkypeMsg+11);

				if (sstat) {
					oldstatus=SkypeStatus;
					InterlockedExchange((long*)&SkypeStatus, sstat);
					ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldstatus, SkypeStatus);
					if (sstat!=ID_STATUS_OFFLINE) {
						if (sstat!=ID_STATUS_CONNECTING && (oldstatus==ID_STATUS_OFFLINE || oldstatus==ID_STATUS_CONNECTING)) {

							SkypeInitialized=FALSE;
							forkthread(( pThreadFunc )SkypeSystemInit, 0, NULL);
						}
						if (DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "KeepState", 0)) RestoreUserStatus=TRUE;
					}

//					if (SkypeStatus==ID_STATUS_ONLINE) SkypeSend("SEARCH MISSEDMESSAGES");
				}
//				break;
			}
			if (!strncmp(szSkypeMsg, "USERSTATUS", 10)) {
//				if ((sstat=SkypeStatusToMiranda(szSkypeMsg+11)) && SkypeStatus!=ID_STATUS_CONNECTING) {
				if ((sstat=SkypeStatusToMiranda(szSkypeMsg+11))) {
						if (RestoreUserStatus && RequestedStatus) {
							RestoreUserStatus=FALSE;
							SkypeSend ("SET USERSTATUS %s", RequestedStatus);
						}
						oldstatus=SkypeStatus;
						InterlockedExchange((long*)&SkypeStatus, sstat);
						ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldstatus, sstat);
#ifdef SKYPEBUG_OFFLN
						if ((oldstatus==ID_STATUS_OFFLINE || oldstatus==ID_STATUS_CONNECTING) &&
							SkypeStatus!=ID_STATUS_CONNECTING && SkypeStatus!=ID_STATUS_OFFLINE)
							forkthread(( pThreadFunc )SearchFriendsThread, 0, NULL);
#endif
				}
#ifdef SKYPEBUG_OFFLN
				SetEvent(GotUserstatus);
#endif
				break;
			}
			if (!strncmp(szSkypeMsg, "APPLICATION libpurple_typing", 28)) {
				char *nextoken, *p;

				if (p=strtok_r(szSkypeMsg+29, " ", &nextoken))
				{
					if (!strcmp (p, "STREAMS")) {
						char *pStr;

						while (p=strtok_r(NULL, " ", &nextoken)) {
							if (pStr = strchr(p, ':')) {
								*pStr=0;
								if (hContact=find_contact(p)) {
									*pStr=':';
									DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "Typing_Stream", p);
								}
							}
						}
					}
					else if (!strcmp (p, "DATAGRAM")) {
						if (p=strtok_r(NULL, " ", &nextoken)) {
							char *pStr;

							if (pStr = strchr(p, ':')) {
								*pStr=0;
								if (hContact=find_contact(p)) {
									*pStr=':';
									DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "Typing_Stream", p);

									if (p=strtok_r(NULL, " ", &nextoken)) {
										LPARAM lTyping = PROTOTYPE_CONTACTTYPING_OFF;

										if (!strcmp(p, "PURPLE_TYPING")) lTyping=PROTOTYPE_CONTACTTYPING_INFINITE;
										CallService(MS_PROTO_CONTACTISTYPING, (WPARAM)hContact, lTyping);
										break;
									}
								}
							}
						}
					}
				}
			}
			if (!strncmp(szSkypeMsg, "USER ", 5)) {
				char *nextoken;

				buf=_strdup(szSkypeMsg+5);
				nick=strtok_r(buf, " ", &nextoken);
				ptr=strtok_r(NULL, " ", &nextoken);

				if (strcmp(ptr, "BUDDYSTATUS")) {
					if (!strcmp(ptr, "RECEIVEDAUTHREQUEST")) {
						forkthread(( pThreadFunc )SearchUsersWaitingMyAuthorization, 0, NULL);
						free (buf);
						break;
					}

					if (!(hContact=find_contact(nick)) && strcmp(ptr, "FULLNAME")) {
						SkypeSend("GET USER %s BUDDYSTATUS", nick);
						free (buf);
						break;
					}

					if (!strcmp(ptr, "ONLINESTATUS")) {
						if (SkypeStatus!=ID_STATUS_OFFLINE)
						{
							DBWriteContactSettingWord(hContact, SKYPE_PROTONAME, "Status", (WORD)SkypeStatusToMiranda(ptr+13));
							if((WORD)SkypeStatusToMiranda(ptr+13) != ID_STATUS_OFFLINE)
							{
								LOG(("WndProc Status is not offline so get user info"));
								forkthread(GetInfoThread, 0, hContact);
							}
						}
					}


					/* We handle the following properties right here in the wndProc, in case that
					 * Skype protocol broadcasts them to us.
					 *
					 * However, we still let them be added to the Message queue im memory, as they
					 * may get consumed by GetInfoThread.
					 * This is necessary to have a proper error handling in case the property is
					 * not supported (i.e. imo2sproxy).
					 *
					 * If one of the property GETs returns an error, the error-message has to be
					 * removed from the message queue, as the error is the answer to the query.
					 * If we don't remove the ERRORs from the list, another consumer may see the ERROR
					 * as a reply to his query and process it.
					 * In case the SKYPE Protocol really broadcasts one of these messages without being
					 * requested by GetInfoThread (i.e. MOOD_TEXT), the garbage collector will take
					 * care of them and remove them after some time.
					 * This may not be the most efficient way, but ensures that we finally do proper
					 * error handling.
					 */
					if (!strcmp(ptr, "FULLNAME")) {
						char *nm;

						if (nm = strtok_r(NULL, " ", &nextoken))
						{
							SkypeDBWriteContactSettingUTF8String(hContact, SKYPE_PROTONAME, "FirstName", nm);
							if (!(nm=strtok_r(NULL, "", &nextoken))) DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "LastName");
							else
								SkypeDBWriteContactSettingUTF8String(hContact, SKYPE_PROTONAME, "LastName", nm);
						}
					} else
					if (!strcmp(ptr, "BIRTHDAY")) {
						unsigned int y, m, d;
						if (sscanf(ptr+9, "%04d%02d%02d", &y, &m, &d)==3) {
							DBWriteContactSettingWord(hContact, SKYPE_PROTONAME, "BirthYear", (WORD)y);
							DBWriteContactSettingByte(hContact, SKYPE_PROTONAME, "BirthMonth", (BYTE)m);
							DBWriteContactSettingByte(hContact, SKYPE_PROTONAME, "BirthDay", (BYTE)d);
						} else {
							DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "BirthYear");
							DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "BirthMonth");
							DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "BirthDay");
						}
					} else
					if (!strcmp(ptr, "COUNTRY")) {
						if (ptr[8]) {
							struct CountryListEntry *countries;
							int countryCount, i;

							CallService(MS_UTILS_GETCOUNTRYLIST, (WPARAM)&countryCount, (LPARAM)&countries);
							for (i=0; i<countryCount; i++) {
								if (countries[i].id == 0 || countries[i].id == 0xFFFF) continue;
								if (!_stricmp(countries[i].szName, ptr+8))
								{
									DBWriteContactSettingWord(hContact, SKYPE_PROTONAME, "Country", (BYTE)countries[i].id);
									break;
								}
							}
						} else DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "Country");
					} else
					if (!strcmp(ptr, "SEX")) {
						if (ptr[4]) {
							BYTE sex=0;
							if (!_stricmp(ptr+4, "MALE")) sex=0x4D;
							if (!_stricmp(ptr+4, "FEMALE")) sex=0x46;
							if (sex) DBWriteContactSettingByte(hContact, SKYPE_PROTONAME, "Gender", sex);
						} else DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "Gender");
					} else
	/*				if (!strcmp(ptr, "AVATAR" )){
						LOG("WndProc", "AVATAR");
						if (!(hContact=find_contact(nick)))
							SkypeSend("GET USER %s BUDDYSTATUS", nick);
						else
						{
							TCHAR *unicode = NULL;

							if(utf8_decode((ptr+9), &Avatar)==-1) break;

							if( ServiceExists(MS_AV_SETAVATAR) )
							{
								CallService(MS_AV_SETAVATAR,(WPARAM) hContact,(LPARAM) Avatar);
							}
							else
							{

								if(DBWriteContactSettingTString(hContact, "ContactPhoto", "File", Avatar))
								{
									#if defined( _UNICODE )
										char buff[TEXT_LEN];
										WideCharToMultiByte(code_page, 0, Avatar, -1, buff, TEXT_LEN, 0, 0);
										buff[TEXT_LEN] = 0;
										DBWriteContactSettingString(hContact, "ContactPhoto", "File", buff);
									#endif
								}

							}


						}
						free(buf);
						break;
					}
					*/
					if (!strcmp(ptr, "MOOD_TEXT")){

						LOG(("WndProc MOOD_TEXT"));
						SkypeDBWriteContactSettingUTF8String (hContact, "CList", "StatusMsg", ptr+10);
					} else
					if (!strcmp(ptr, "TIMEZONE")){
						time_t temp;
						struct tm tms;
						int value=atoi(ptr+9), tz;

						LOG(("WndProc: TIMEZONE %s", nick));

						if (value && !DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "IgnoreTimeZones", 0)) {
							temp = SkypeTime(NULL);
							tms = *localtime(&temp);
							//memcpy(&tms,localtime(&temp), sizeof(tm));
							//tms = localtime(&temp)
							tz=(value >= 86400 )?(256-((2*(atoi(ptr+9)-86400))/3600)):((-2*(atoi(ptr+9)-86400))/3600);
							if (tms.tm_isdst == 1 && DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseTimeZonePatch", 0))
							{
								LOG(("WndProc: Using the TimeZonePatch"));
								DBWriteContactSettingByte(hContact, "UserInfo", "Timezone", (BYTE)(tz+2));
							}
							else
							{
								LOG(("WndProc: Not using the TimeZonePatch"));
								DBWriteContactSettingByte(hContact, "UserInfo", "Timezone", (BYTE)(tz+0));
							}
						} else 	{
							LOG(("WndProc: Deleting the TimeZone in UserInfo Section"));
							DBDeleteContactSetting(hContact, "UserInfo", "Timezone");
						}
					} else
					if (!strcmp(ptr, "IS_VIDEO_CAPABLE")){
						if (!_stricmp(ptr + 17, "True"))
							DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "MirVer", "Skype 2.0");
						else
							DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "MirVer", "Skype");
					} else
					if (!strcmp(ptr, "RICH_MOOD_TEXT")) {
						DBWriteContactSettingString(hContact, SKYPE_PROTONAME, "MirVer", "Skype 3.0");
					} else
					if (!strcmp(ptr, "DISPLAYNAME")) {
						// Skype Bug? -> If nickname isn't customised in the Skype-App, this won't return anything :-(
						if (ptr[12])
							SkypeDBWriteContactSettingUTF8String(hContact, SKYPE_PROTONAME, "Nick", ptr+12);
					} else	// Other proerties that can be directly assigned to a DB-Value
					{
						int i;
						char *pszProp;

						for (i=0; i<sizeof(m_settings)/sizeof(m_settings[0]); i++) {
							if (!strcmp(ptr, m_settings[i].SkypeSetting)) {
								pszProp = ptr+strlen(m_settings[i].SkypeSetting)+1;
								if (*pszProp)
									SkypeDBWriteContactSettingUTF8String(hContact, SKYPE_PROTONAME, m_settings[i].MirandaSetting, pszProp);
								else
									DBDeleteContactSetting(hContact, SKYPE_PROTONAME, m_settings[i].MirandaSetting);
							}
						}
					}
				} else { // BUDDYSTATUS:
					flag=0;
					switch(atoi(ptr+12)) {
						case 1: if (hContact=find_contact(nick)) CallService(MS_DB_CONTACT_DELETE, (WPARAM)hContact, 0); break;
						case 0: break;
						case 2: flag=PALF_TEMPORARY;
						case 3: add_contact(nick, flag);
								SkypeSend("GET USER %s ONLINESTATUS", nick);
								break;
					}
					free(buf);
					if (!SetEvent(hBuddyAdded)) TellError(GetLastError());
					break;
				}
				free(buf);
			}
			if (!strncmp(szSkypeMsg, "CURRENTUSERHANDLE", 17)) {	// My username
				DBVARIANT dbv={0};

				if(DBGetContactSettingString(NULL,SKYPE_PROTONAME,"LoginUserName",&dbv) ||
					!*dbv.pszVal || _stricmp (szSkypeMsg+18, dbv.pszVal)==0)
				{
					DBWriteContactSettingString(NULL, SKYPE_PROTONAME, SKYPE_NAME, szSkypeMsg+18);
					DBWriteContactSettingString(NULL, SKYPE_PROTONAME, "Nick", szSkypeMsg+18);
					forkthread(( pThreadFunc )GetDisplaynameThread, 0, NULL);
				}
				if (dbv.pszVal) DBFreeVariant(&dbv);
			}
			if (strstr(szSkypeMsg, "AUTOAWAY") || !strncmp(szSkypeMsg, "OPEN ",5) ||
				 (SkypeInitialized && !strncmp (szSkypeMsg, "PONG", 4)) ||
				 !strncmp (szSkypeMsg, "MINIMIZE", 8))
			{
				// Currently we do not process these messages
				break;
			}
			if (!strncmp(szSkypeMsg, "CHAT ", 5)) {
				// Currently we only process these notifications
				if (DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseGroupchat", 0) &&
					(ptr = strchr (szSkypeMsg, ' ')) && (ptr = strchr (++ptr, ' ')))
				{
					if (strncmp(ptr, " MEMBERS", 8) == 0) {
						LOG(("WndProc AddMembers"));
						forkthread(( pThreadFunc )AddMembersThread, 0, _strdup(szSkypeMsg));
					} else
					if (strncmp(ptr, " FRIENDLYNAME ", 14) == 0) {
						// Chat session name
						HANDLE hContact;

						*ptr=0;
						if (hContact = find_chatA(szSkypeMsg+5))
						{
							GCDEST gcd = {0};
							GCEVENT gce = {0};

							if (DBGetContactSettingWord(hContact, SKYPE_PROTONAME, "Status", ID_STATUS_OFFLINE) !=
								ID_STATUS_OFFLINE)
							{
								gcd.pszModule = SKYPE_PROTONAME;
								gcd.ptszID = make_nonutf_tchar_string((const unsigned char*)szSkypeMsg+5);
								gcd.iType = GC_EVENT_CHANGESESSIONAME;
								gce.cbSize = sizeof(GCEVENT);
								gce.pDest = &gcd;
								gce.ptszText = make_tchar_string((const unsigned char*)ptr+14);
								gce.dwFlags = GC_TCHAR;
								if (gce.ptszText) {
									CallService(MS_GC_EVENT, 0, (LPARAM)&gce);
									DBWriteContactSettingTString (hContact, SKYPE_PROTONAME, "Nick", gce.ptszText);
									free((void*)gce.ptszText);
								}
								free_nonutf_tchar_string((void*)gcd.ptszID);
							}
						}
						*ptr=' ';
					} else
					if (strncmp(ptr, " CHATMESSAGES ", 14) == 0) {
						forkthread(( pThreadFunc )MessageListProcessingThread, 0, _strdup(ptr+14));
						break;
					}
				}
			}
			if (!strncmp(szSkypeMsg, "CALL ",5)) {
				// incoming calls are already processed by Skype, so no need for us
				// to do this.
				// However we can give a user the possibility to hang up a call via Miranda's
				// context menu
				if (ptr=strstr(szSkypeMsg, " STATUS ")) {
					ptr[0]=0; ptr+=8;
					if (!strcmp(ptr, "RINGING") || !strcmp(ptr, "ROUTING")) forkthread(( pThreadFunc )RingThread, 0, _strdup(szSkypeMsg));
					if (!strcmp(ptr, "FAILED") || !strcmp(ptr, "FINISHED") ||
						!strcmp(ptr, "MISSED") || !strcmp(ptr, "REFUSED")  ||
						!strcmp(ptr, "BUSY")   || !strcmp(ptr, "CANCELLED"))
						forkthread(( pThreadFunc )EndCallThread, 0, _strdup(szSkypeMsg));
					if (!strcmp(ptr, "ONHOLD") || !strcmp(ptr, "LOCALHOLD") ||
						!strcmp(ptr, "REMOTEHOLD")) forkthread(( pThreadFunc )HoldCallThread, 0, _strdup(szSkypeMsg));
					if (!strcmp(ptr, "INPROGRESS")) forkthread(( pThreadFunc )ResumeCallThread, 0, _strdup(szSkypeMsg));
					break;
				} else if ((!strstr(szSkypeMsg, "PARTNER_HANDLE") && !strstr(szSkypeMsg, "FROM_HANDLE"))
							&& !strstr(szSkypeMsg, "TYPE")) break;
			}
			if (!strncmp(szSkypeMsg, "PRIVILEGE SKYPEOUT", 18)) {
				if (!strncmp(szSkypeMsg+19, "TRUE", 4)) {
					if (!bSkypeOut) {
						CLISTMENUITEM mi={0};

						bSkypeOut=TRUE;
						mi.cbSize=sizeof(mi);
						mi.position=-2000005000;
						mi.flags=0;
						mi.hIcon=LoadIcon(hInst,MAKEINTRESOURCE(IDI_CALLSKYPEOUT));
						mi.pszContactOwner=SKYPE_PROTONAME;
						mi.pszName=Translate("Do a SkypeOut-call");
						mi.pszService=SKYPEOUT_CALL;
						Menu_AddMainMenuItem(&mi);
					}

				} else {
					bSkypeOut=FALSE;
					if (httbButton) {
						CallService(MS_TTB_REMOVEBUTTON, (WPARAM)httbButton, 0);
						httbButton=0;
					}
				}
				break;
			}
			if (!strncmp(szSkypeMsg, "MESSAGES", 8) || !strncmp(szSkypeMsg, "CHATMESSAGES", 12)) {
				if (strlen(szSkypeMsg)<=(UINT)(strchr(szSkypeMsg, ' ')-szSkypeMsg+1))
				{
					LOG(( "%s %d %s %d", szSkypeMsg,(UINT)(strchr(szSkypeMsg, ' ')-szSkypeMsg+1),
						strchr(szSkypeMsg, ' '), strlen(szSkypeMsg)));
					break;
				}
				LOG(("MessageListProcessingThread launched"));
				forkthread(( pThreadFunc )MessageListProcessingThread, 0, _strdup(strchr(szSkypeMsg, ' ')+1));
				break;
			}
			if (!strncmp(szSkypeMsg, "MESSAGE", 7) || !strncmp(szSkypeMsg, "CHATMESSAGE", 11))
			{
				char *pMsgNum;
				TYP_MSGLENTRY *pEntry;

				if ((pMsgNum = strchr (szSkypeMsg, ' ')) && (ptr = strchr (++pMsgNum, ' ')))
				{
					BOOL bFetchMsg = FALSE;

					if (strncmp(ptr, " EDITED_TIMESTAMP", 17) == 0) {
						ptr[0]=0;
						if (pEntry = MsgList_FindMessage(strtoul(pMsgNum, NULL, 10))) {
							pEntry->tEdited = atol(ptr+18);
						}
						bFetchMsg = TRUE;
					} else bFetchMsg = (strncmp(ptr, " STATUS RE", 10) == 0 && !rcvwatchers) ||
						(strncmp(ptr, " STATUS SENT", 12) == 0 && !sendwatchers);

					if (bFetchMsg) {
						// If new message is available, fetch it
						ptr[0]=0;
						if (!(args=(fetchmsg_arg *)calloc(1, sizeof(*args)))) break;
						strncpy (args->msgnum, pMsgNum, sizeof(args->msgnum));
						args->getstatus=FALSE;
						//args->bIsRead = strncmp(ptr+8, "READ", 4) == 0;
						forkthread(( pThreadFunc )FetchMessageThreadSync, 0, args);
						break;
					}
				}
			}
			if (!strncmp(szSkypeMsg, "ERROR 68", 8)) {
				LOG(("We got a sync problem :( ->  SendMessage() will try to recover..."));
				break;
			}
			if (!strncmp(szSkypeMsg, "PROTOCOL ", 9)) {
				if ((protocol=(char)atoi(szSkypeMsg+9))>=3) {
					strcpy(cmdMessage, "CHATMESSAGE");
					strcpy(cmdPartner, "FROM");
				}
				bProtocolSet = TRUE;

				if (protocol<5 && !hMenuAddSkypeContact &&
					DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "EnableMenu", 1))
				{
					hMenuAddSkypeContact = add_mainmenu();
				}
			}
			LOG(("SkypeMsgAdd launched"));
			SkypeMsgAdd(szSkypeMsg);
			ReleaseSemaphore(SkypeMsgReceived, receivers, NULL);
		}
        break;

        case WM_TIMER:
			if (iReentranceCnt>1) break;
			if (!bIsImoproxy) SkypeSend("PING");
			SkypeMsgCollectGarbage(MAX_MSG_AGE);
			MsgList_CollectGarbage();
			if (receivers>1)
			{
				LOG(("Watchdog WARNING: there are still %d receivers waiting for MSGs", receivers));
			}
			break;

		case WM_CLOSE:
			PostQuitMessage (0);
			break;
		case WM_DESTROY:
			KillTimer (hWndDlg, 1);
			break;

        default:
		 if(message==ControlAPIAttach) {
				// Skype responds with Attach to the discover-message
				 if ((HWND)wParam == hForbiddenSkypeWnd) {
					 ResetEvent(SkypeReady);
					 break;
				 }
				AttachStatus=lParam;
				if (lParam==SKYPECONTROLAPI_ATTACH_SUCCESS) {
					LOG (("AttachStatus success, got hWnd %08X", (HWND)wParam));

					if (hSkypeWnd && (HWND)wParam!=hSkypeWnd && IsWindow(hSkypeWnd))
						hSkypeWndSecondary = (HWND)wParam;
					else {
						hSkypeWnd=(HWND)wParam;	   // Skype gave us the communication window handle
						hSkypeWndSecondary = NULL;
					}
				}
				if (AttachStatus!=SKYPECONTROLAPI_ATTACH_API_AVAILABLE &&
					AttachStatus!=SKYPECONTROLAPI_ATTACH_NOT_AVAILABLE)
				{
					LOG(("Attaching: SkypeReady fired, Attachstatus is %d", AttachStatus));
					SetEvent(SkypeReady);
				}
				AttachStatus=lParam;
				break;
		 }
		 --iReentranceCnt;
		 return (DefWindowProc(hWndDlg, message, wParam, lParam));
    }
	LOG(("WM_COPYDATA exit (%08X)", message));
	if (szSkypeMsg) free(szSkypeMsg);
	--iReentranceCnt;
	return 1;
}

void TellError(DWORD err) {
	LPVOID lpMsgBuf;

		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err,
					  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL);
        MessageBox( NULL, (TCHAR*)lpMsgBuf, _T("GetLastError"), MB_OK|MB_ICONINFORMATION );
        LocalFree( lpMsgBuf );
		return;
}


// SERVICES //
INT_PTR SkypeSetStatus(WPARAM wParam, LPARAM lParam)
{
	int oldStatus, iRet;
	BOOL UseCustomCommand, UnloadOnOffline;

	UNREFERENCED_PARAMETER(lParam);

	if (MirandaShuttingDown) return 0;
	LOG (("SkypeSetStatus enter"));
	UseCustomCommand = DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseCustomCommand", 0);
	UnloadOnOffline = DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UnloadOnOffline", 0);

	//if (!SkypeInitialized && !DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UnloadOnOffline", 0)) return 0;

	// Workaround for Skype status-bug
    if ((int)wParam==ID_STATUS_OFFLINE) logoff_contacts(TRUE);
	if (SkypeStatus==(int)wParam) return 0;
	oldStatus = SkypeStatus;

	if ((int)wParam==ID_STATUS_CONNECTING) return 0;
#ifdef MAPDND
	if ((int)wParam==ID_STATUS_OCCUPIED || (int)wParam==ID_STATUS_ONTHEPHONE) wParam=ID_STATUS_DND;
	if ((int)wParam==ID_STATUS_OUTTOLUNCH) wParam=ID_STATUS_NA;
#endif
#ifdef MAPNA
	if ((int)wParam==ID_STATUS_NA) wParam = ID_STATUS_AWAY;
#endif

   RequestedStatus=MirandaStatusToSkype((int)wParam);

   /*
   if (SkypeStatus != ID_STATUS_OFFLINE)
   {
     InterlockedExchange((long*)&SkypeStatus, (int)wParam);
     ProtoBroadcastAck(SKYPE_PROTONAME, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, SkypeStatus);
   }
   */

   if ((int)wParam==ID_STATUS_OFFLINE && UnloadOnOffline)
   {
			if(UseCustomCommand)
			{
				DBVARIANT dbv;
				if(!DBGetContactSettingString(NULL,SKYPE_PROTONAME,"CommandLine",&dbv))
				{
					CloseSkypeAPI(dbv.pszVal);
					DBFreeVariant(&dbv);
				}
			}
			else
			{
				CloseSkypeAPI(skype_path);
			}

   } else if (AttachStatus==-1)
   {
	   forkthread(LaunchSkypeAndSetStatusThread, 0, (void *)wParam);
	   return 0;
   }

   iRet = SetUserStatus();
   LOG (("SkypeSetStatus exit"));
   return iRet;
}

INT64 __stdcall SendBroadcast( HANDLE hContact, int type, int result, HANDLE hProcess, LPARAM lParam )
{
	ACKDATA ack = {0};
	ack.cbSize = sizeof( ACKDATA );
	ack.szModule = SKYPE_PROTONAME;
	ack.hContact = hContact;
	ack.type = type;
	ack.result = result;
	ack.hProcess = hProcess;
	ack.lParam = lParam;
	return CallService( MS_PROTO_BROADCASTACK, 0, ( LPARAM )&ack );
}

static void __cdecl SkypeGetAwayMessageThread( HANDLE hContact )
{
	DBVARIANT dbv;
	if ( !DBGetContactSettingString( hContact, "CList", "StatusMsg", &dbv )) {
		SendBroadcast( hContact, ACKTYPE_AWAYMSG, ACKRESULT_SUCCESS, ( HANDLE )1, ( LPARAM )dbv.pszVal );
		DBFreeVariant( &dbv );
	}
	else SendBroadcast( hContact, ACKTYPE_AWAYMSG, ACKRESULT_SUCCESS, ( HANDLE )1, ( LPARAM )0 );
}

INT_PTR SkypeGetAwayMessage(WPARAM wParam,LPARAM lParam)
{
	CCSDATA* ccs = ( CCSDATA* )lParam;

	UNREFERENCED_PARAMETER(wParam);

	forkthread( SkypeGetAwayMessageThread, 0, ccs->hContact );
	return 1;
}

#define POLYNOMIAL (0x488781ED) /* This is the CRC Poly */
#define TOPBIT (1 << (WIDTH - 1)) /* MSB */
#define WIDTH 32

static int GetFileHash(char* filename)
{
	HANDLE hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	int remainder = 0, byte, bit;
	char data[1024];
	DWORD dwRead;

	if(hFile == INVALID_HANDLE_VALUE) return 0;

	do
	{
		// Read file chunk
		dwRead = 0;
		ReadFile(hFile, data, 1024, &dwRead, NULL);

		/* loop through each byte of data */
		for (byte = 0; byte < (int) dwRead; ++byte) {
			/* store the next byte into the remainder */
			remainder ^= (data[byte] << (WIDTH - 8));
			/* calculate for all 8 bits in the byte */
			for ( bit = 8; bit > 0; --bit) {
				/* check if MSB of remainder is a one */
				if (remainder & TOPBIT)
					remainder = (remainder << 1) ^ POLYNOMIAL;
				else
					remainder = (remainder << 1);
			}
		}
	} while(dwRead == 1024);

	CloseHandle(hFile);

	return remainder;
}

static int _GetFileSize(char* filename)
{
	HANDLE hFile = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	int size;

	if(hFile == INVALID_HANDLE_VALUE)
		return 0;
	size = GetFileSize(hFile, NULL);
	CloseHandle(hFile);
	return size;
}

/* RetrieveUserAvatar
 *
 * Purpose: Get a user avatar from skype itself
 * Params : param=(void *)(HANDLE)hContact
 */
void RetrieveUserAvatar(void *param)
{
	HANDLE hContact = (HANDLE) param, file;
	PROTO_AVATAR_INFORMATION AI={0};
	ACKDATA ack = {0};
	DBVARIANT dbv;
	char AvatarFile[MAX_PATH+1], AvatarTmpFile[MAX_PATH+10], *ptr, *pszTempFile;

	if (hContact == NULL)
		return;

	// Mount default ack
	ack.cbSize = sizeof( ACKDATA );
	ack.szModule = SKYPE_PROTONAME;
	ack.hContact = hContact;
	ack.type = ACKTYPE_AVATAR;
	ack.result = ACKRESULT_FAILED;

	AI.cbSize = sizeof( AI );
	AI.hContact = hContact;

	// Get skype name
	if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, SKYPE_NAME, &dbv) == 0)
	{
		if (dbv.pszVal)
		{
			// Get filename
			FoldersGetCustomPath(hProtocolAvatarsFolder, AvatarFile, sizeof(AvatarFile), DefaultAvatarsFolder);
			mir_snprintf(AvatarTmpFile, sizeof(AvatarTmpFile), "AVATAR 1 %s\\%s_tmp.jpg", AvatarFile, dbv.pszVal);
			pszTempFile = AvatarTmpFile+9;
			mir_snprintf(AvatarFile, sizeof(AvatarFile), "%s\\%s.jpg", AvatarFile, dbv.pszVal);

			// Just to be sure
			DeleteFileA(pszTempFile);
			file = CreateFileA(pszTempFile, 0, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if (file != INVALID_HANDLE_VALUE)
			{
				CloseHandle(file);
				if (ptr=SkypeGet ("USER", dbv.pszVal, AvatarTmpFile))
				{
					if (strncmp(ptr, "ERROR", 5) &&
						GetFileAttributesA(pszTempFile) != INVALID_FILE_ATTRIBUTES)
					{
						ack.result = ACKRESULT_SUCCESS;

						// Is no avatar image?
						if (!DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "ShowDefaultSkypeAvatar", 0)
							&& GetFileHash(pszTempFile) == 0x8d34e05d && _GetFileSize(pszTempFile) == 3751)
						{
							// Has no avatar
							AI.format = PA_FORMAT_UNKNOWN;
							ack.hProcess = (HANDLE)&AI;
							DeleteFileA(AvatarFile);
						}
						else
						{
							// Got it
							MoveFileExA(pszTempFile, AvatarFile, MOVEFILE_REPLACE_EXISTING);
							AI.format = PA_FORMAT_JPEG;
							strcpy(AI.filename, AvatarFile);
							ack.hProcess = (HANDLE)&AI;
						}

					}
					free (ptr);
				}
				DeleteFileA(pszTempFile);
			}

		}
		DBFreeVariant(&dbv);
	}
	CallService( MS_PROTO_BROADCASTACK, 0, ( LPARAM )&ack );
}


/* SkypeGetAvatarInfo
 *
 * Purpose: Set user avatar in profile
 * Params : wParam=0
 *			lParam=(LPARAM)(const char*)filename
 * Returns: 0 - Success
 *		   -1 - Failure
 */
INT_PTR SkypeGetAvatarInfo(WPARAM wParam,LPARAM lParam)
{

	DBVARIANT dbv;
	PROTO_AVATAR_INFORMATION* AI = ( PROTO_AVATAR_INFORMATION* )lParam;
	if (AI->hContact == NULL) // User
	{
		if (!DBGetContactSettingString(NULL,SKYPE_PROTONAME, "AvatarFile", &dbv))
		{
			lstrcpynA(AI->filename, dbv.pszVal, sizeof(AI->filename));
			DBFreeVariant(&dbv);
			return GAIR_SUCCESS;
		}
		else
			return GAIR_NOAVATAR;
	}
	else // Contact
	{
		DBVARIANT dbv;
		char AvatarFile[MAX_PATH+1];

		if (protocol < 7 && !bIsImoproxy)
			return GAIR_NOAVATAR;

		if (wParam & GAIF_FORCE)
		{
			// Request anyway
			forkthread(RetrieveUserAvatar, 0, (void *) AI->hContact);
			return GAIR_WAITFOR;
		}

		if (DBGetContactSettingString(AI->hContact, SKYPE_PROTONAME, SKYPE_NAME, &dbv))
			// No skype name ??
			return GAIR_NOAVATAR;

		if (dbv.pszVal == NULL)
		{
			// No skype name ??
			DBFreeVariant(&dbv);
			return GAIR_NOAVATAR;
		}

		// Get filename
		FoldersGetCustomPath(hProtocolAvatarsFolder, AvatarFile, sizeof(AvatarFile), DefaultAvatarsFolder);
		mir_snprintf(AvatarFile, sizeof(AvatarFile), "%s\\%s.jpg", AvatarFile, dbv.pszVal);
		DBFreeVariant(&dbv);

		// Check if the file exists
		if (GetFileAttributesA(AvatarFile) == INVALID_FILE_ATTRIBUTES)
			return GAIR_NOAVATAR;

		// Return the avatar
		AI->format = PA_FORMAT_JPEG;
		strcpy(AI->filename, AvatarFile);
		return GAIR_SUCCESS;
	}
}


/* SkypeGetAvatarCaps
 *
 * Purpose: Query avatar caps for a protocol
 * Params : wParam=One of AF_*
 *			lParam=Depends on wParam
 * Returns: Depends on wParam
 */
INT_PTR SkypeGetAvatarCaps(WPARAM wParam, LPARAM lParam)
{
	switch(wParam)
	{
		case AF_MAXSIZE:
		{
			POINT *p = (POINT *) lParam;
			if (p == NULL)
				return -1;

			p->x = 96;
			p->y = 96;
			return 0;
		}
		case AF_PROPORTION:
		{
			return PIP_NONE;
		}
		case AF_FORMATSUPPORTED:
		{
			if (lParam == PA_FORMAT_PNG || lParam == PA_FORMAT_JPEG)
				return TRUE;
			else
				return FALSE;
		}
		case AF_ENABLED:
		{
			return TRUE;
		}
		case AF_DONTNEEDDELAYS:
		{
			return FALSE;
		}
	}
	return -1;
}


INT_PTR SkypeGetStatus(WPARAM wParam, LPARAM lParam) {
	UNREFERENCED_PARAMETER(wParam);
	UNREFERENCED_PARAMETER(lParam);

	return SkypeStatus;
}

INT_PTR SkypeGetInfo(WPARAM wParam,LPARAM lParam) {
    CCSDATA *ccs = (CCSDATA *) lParam;

	UNREFERENCED_PARAMETER(wParam);

	forkthread(GetInfoThread, 0, ccs->hContact);
	return 0;
}

INT_PTR SkypeAddToList(WPARAM wParam, LPARAM lParam) {
	PROTOSEARCHRESULT *psr=(PROTOSEARCHRESULT*)lParam;
	char *name = NULL;
	HANDLE ret = INVALID_HANDLE_VALUE;

	LOG(("SkypeAddToList Adding API function called"));
	if (psr->cbSize!=sizeof(PROTOSEARCHRESULT) || !psr->nick) return 0;
	LOG(("SkypeAddToList OK"));
	name = mir_utf8encodeT(psr->nick);
	ret = add_contact(name, wParam);
	mir_free(name);
    return (INT_PTR)ret;
}

INT_PTR SkypeBasicSearch(WPARAM wParam, LPARAM lParam) {
	UNREFERENCED_PARAMETER(wParam);

	LOG(("SkypeBasicSearch %s", (char *)lParam));
	if (!SkypeInitialized) return 0;
	return (hSearchThread=forkthread(( pThreadFunc )BasicSearchThread, 0, _strdup((char *)lParam)));
}

void MessageSendWatchThread(msgsendwt_arg *arg) {
	char *str, *err;

	// sendwatchers need to be incremented before starting this thread
	LOG(("MessageSendWatchThread started."));
	str=SkypeRcvMsg(arg->szId, SkypeTime(NULL)-1, arg->hContact, DBGetContactSettingDword(NULL,"SRMsg","MessageTimeout",TIMEOUT_MSGSEND)+1000);
	InterlockedDecrement (&sendwatchers);
	if (str)
	{
		if (!DBGetContactSettingByte(arg->hContact, SKYPE_PROTONAME, "ChatRoom", 0)) {
			if (err=GetSkypeErrorMsg(str)) {
				ProtoBroadcastAck(SKYPE_PROTONAME, arg->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, (HANDLE) 1, (LPARAM)Translate(err));
				free(err);
				free(str);
				free(arg);
				LOG(("MessageSendWatchThread terminated."));
				return;
			}
			ProtoBroadcastAck(SKYPE_PROTONAME, arg->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, (HANDLE) 1, 0);
		}
		free(str);
		LOG(("MessageSendWatchThread terminated gracefully."));
	}
	free (arg);
}

INT_PTR SkypeSendMessage(WPARAM wParam, LPARAM lParam) {
    CCSDATA *ccs = (CCSDATA *) lParam;
	DBVARIANT dbv;
	BOOL sendok=TRUE;
    char *msg = (char *) ccs->lParam, *utfmsg=NULL, *mymsgcmd=cmdMessage, szId[16]={0};
	static DWORD dwMsgNum = 0;
	BYTE bIsChatroom = 0 != DBGetContactSettingByte(ccs->hContact, SKYPE_PROTONAME, "ChatRoom", 0);

	UNREFERENCED_PARAMETER(wParam);

	if (bIsChatroom)
	{
		if (DBGetContactSettingString(ccs->hContact, SKYPE_PROTONAME, "ChatRoomID", &dbv))
			return 0;
		mymsgcmd="CHATMESSAGE";
	}
	else
	{
		if (DBGetContactSettingString(ccs->hContact, SKYPE_PROTONAME, SKYPE_NAME, &dbv))
			return 0;
		mymsgcmd="MESSAGE";
	}

	if (ccs->wParam & PREF_UTF) {
		utfmsg = msg;
	} else if (ccs->wParam & PREF_UNICODE) {
		utfmsg = (char*)make_utf8_string((WCHAR*)(msg+strlen(msg)+1));
	} else {
		if (utf8_encode(msg, &utfmsg)==-1) utfmsg=NULL;
	}
	if (protocol>=4) {
		InterlockedIncrement ((LONG*)&dwMsgNum);
		sprintf (szId, "#M%d ", dwMsgNum++);
	}
	InterlockedIncrement (&sendwatchers);
	if (!utfmsg || SkypeSend("%s%s %s %s", szId, mymsgcmd, dbv.pszVal, utfmsg)) sendok=FALSE;
	if (utfmsg && utfmsg!=msg) free(utfmsg);
	DBFreeVariant(&dbv);

	if (sendok) {
		msgsendwt_arg *psendarg = calloc(1, sizeof(msgsendwt_arg));

		if (psendarg) {
			psendarg->hContact = ccs->hContact;
			strcpy (psendarg->szId, szId);
			forkthread(MessageSendWatchThread, 0, psendarg);
		} else InterlockedDecrement (&sendwatchers);
		return 1;
	} else InterlockedDecrement (&sendwatchers);
	if (!bIsChatroom)
		ProtoBroadcastAck(SKYPE_PROTONAME, ccs->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, (HANDLE) 1, (LPARAM)Translate("Connection to Skype lost"));
	return 0;
}

INT_PTR SkypeRecvMessage(WPARAM wParam, LPARAM lParam)
{
    DBEVENTINFO dbei={0};
    CCSDATA *ccs = (CCSDATA *) lParam;
    PROTORECVEVENT *pre = (PROTORECVEVENT *) ccs->lParam;

	UNREFERENCED_PARAMETER(wParam);

    DBDeleteContactSetting(ccs->hContact, "CList", "Hidden");
    dbei.cbSize = sizeof(dbei);
    dbei.szModule = SKYPE_PROTONAME;
    dbei.timestamp = pre->timestamp;
	if (pre->flags & PREF_CREATEREAD) dbei.flags|=DBEF_READ;
    if (pre->flags & PREF_UTF) dbei.flags|=DBEF_UTF;
    dbei.eventType = EVENTTYPE_MESSAGE;
    dbei.cbBlob = strlen(pre->szMessage) + 1;
	if (pre->flags & PREF_UNICODE)
		dbei.cbBlob += sizeof( wchar_t )*( (DWORD)wcslen(( wchar_t* )&pre->szMessage[dbei.cbBlob] )+1 );
    dbei.pBlob = (PBYTE) pre->szMessage;
    MsgList_Add (pre->lParam, (HANDLE)CallService(MS_DB_EVENT_ADD, (WPARAM)ccs->hContact, (LPARAM)&dbei));
    return 0;
}

INT_PTR SkypeUserIsTyping(WPARAM wParam, LPARAM lParam) {
	DBVARIANT dbv={0};
	HANDLE hContact = (HANDLE)wParam;

	if (protocol<5 && !bIsImoproxy) return 0;
	if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, "Typing_Stream", &dbv)) {
		if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, SKYPE_NAME, &dbv) == 0) {
			char szCmd[256];
			_snprintf (szCmd, sizeof(szCmd),
				"ALTER APPLICATION libpurple_typing CONNECT %s", dbv.pszVal);
			SkypeSend (szCmd);
			DBFreeVariant (&dbv);
			testfor (szCmd, 2000);
			// TODO: We should somehow cache the typing notify result and send it
			// after we got a connection, but in the meantime this notification won't
			// get sent on first run
		}
		return 0;
	}

	SkypeSend ("ALTER APPLICATION libpurple_typing DATAGRAM %s %s", dbv.pszVal,
		(lParam==PROTOTYPE_SELFTYPING_ON?"PURPLE_TYPING":"PURPLE_NOT_TYPING"));
	DBFreeVariant(&dbv);
	return 0;
}


INT_PTR SkypeSendAuthRequest(WPARAM wParam, LPARAM lParam) {
	CCSDATA* ccs = (CCSDATA*)lParam;
	DBVARIANT dbv;
	int retval;

	UNREFERENCED_PARAMETER(wParam);

	if (!ccs->lParam || DBGetContactSettingString(ccs->hContact, SKYPE_PROTONAME, SKYPE_NAME, &dbv))
		return 1;
	retval = SkypeSend("SET USER %s BUDDYSTATUS 2 %s", dbv.pszVal, (char *)ccs->lParam);
	DBFreeVariant(&dbv);
	if (retval) return 1; else return 0;
}

INT_PTR SkypeRecvAuth(WPARAM wParam, LPARAM lParam) {
	DBEVENTINFO dbei = {0};
	CCSDATA* ccs = (CCSDATA*)lParam;
	PROTORECVEVENT* pre = (PROTORECVEVENT*)ccs->lParam;

	UNREFERENCED_PARAMETER(wParam);

	DBDeleteContactSetting(ccs->hContact, "CList", "Hidden");

	dbei.cbSize    = sizeof(dbei);
	dbei.szModule  = SKYPE_PROTONAME;
	dbei.timestamp = pre->timestamp;
	dbei.flags     = ((pre->flags & PREF_CREATEREAD)?DBEF_READ:0);
	dbei.eventType = EVENTTYPE_AUTHREQUEST;
	dbei.cbBlob	   = pre->lParam;
	dbei.pBlob     = (PBYTE)pre->szMessage;

	CallService(MS_DB_EVENT_ADD, (WPARAM)NULL, (LPARAM)&dbei);
	return 0;
}

char *__skypeauth(WPARAM wParam) {
	DBEVENTINFO dbei={0};

	if (!SkypeInitialized) return NULL;

	dbei.cbSize = sizeof(dbei);
	if ((dbei.cbBlob = CallService(MS_DB_EVENT_GETBLOBSIZE, wParam, 0))==-1 ||
		!(dbei.pBlob = (unsigned char*)malloc(dbei.cbBlob)))
	{	return NULL; }

	if (CallService(MS_DB_EVENT_GET, wParam, (LPARAM)&dbei) ||
		dbei.eventType != EVENTTYPE_AUTHREQUEST ||
		strcmp(dbei.szModule, SKYPE_PROTONAME))
	{
		free(dbei.pBlob);
		return NULL;
	}
	return (char *)dbei.pBlob;
}

INT_PTR SkypeAuthAllow(WPARAM wParam, LPARAM lParam) {
	char *pBlob;

	UNREFERENCED_PARAMETER(lParam);

	if (pBlob=__skypeauth(wParam))
	{
		int retval=SkypeSend("SET USER %s ISAUTHORIZED TRUE", pBlob+sizeof(DWORD)*2);
		free(pBlob);
		if (!retval) return 0;
	}
	return 1;
}

INT_PTR SkypeAuthDeny(WPARAM wParam, LPARAM lParam) {
	char *pBlob;

	UNREFERENCED_PARAMETER(lParam);

	if (pBlob=__skypeauth(wParam))
	{
		int retval=SkypeSend("SET USER %s ISAUTHORIZED FALSE", pBlob+sizeof(DWORD)*2);
		free(pBlob);
		if (!retval) return 0;
	}
	return 1;
}


INT_PTR SkypeAddToListByEvent(WPARAM wParam, LPARAM lParam) {
	char *pBlob;

	UNREFERENCED_PARAMETER(lParam);

	if (pBlob=__skypeauth(wParam))
	{
		HANDLE hContact = add_contact(pBlob+sizeof(DWORD)*2, LOWORD(wParam));
		free(pBlob);
		if (hContact) return (int)hContact;
	}
	return 0;
}

INT_PTR SkypeRegisterProxy(WPARAM wParam, LPARAM lParam) {
	UNREFERENCED_PARAMETER(wParam);

	if (!lParam) {
		free (pszProxyCallout);
		pszProxyCallout = NULL;
	}
	pszProxyCallout = _strdup((char*)lParam);
	bIsImoproxy = TRUE;
	return 0;
}


void CleanupNicknames(char *dummy) {
	HANDLE hContact;
	char *szProto;
	DBVARIANT dbv, dbv2;

	UNREFERENCED_PARAMETER(dummy);

	LOG(("CleanupNicknames Cleaning up..."));
	for (hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);hContact != NULL;hContact=(HANDLE)CallService( MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0)) {
		szProto = (char*)CallService( MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0 );
		if (szProto!=NULL && !strcmp(szProto, SKYPE_PROTONAME) &&
			DBGetContactSettingByte(hContact, SKYPE_PROTONAME, "ChatRoom", 0)==0)
		{
			if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, SKYPE_NAME, &dbv)) continue;
			if (DBGetContactSettingString(hContact, SKYPE_PROTONAME, "Nick", &dbv2)) {
				DBFreeVariant(&dbv);
				continue;
			}
			DBDeleteContactSetting(hContact, SKYPE_PROTONAME, "Nick");
			GetInfoThread(hContact);
			DBFreeVariant(&dbv);
			DBFreeVariant(&dbv2);
		}
	}
	OUTPUT(_T("Cleanup finished."));
}

/////////////////////////////////////////////////////////////////////////////////////////
// EnterBitmapFileName - enters a bitmap filename

int __stdcall EnterBitmapFileName( char* szDest )
{
	char szFilter[ 512 ];
	OPENFILENAMEA ofn = {0};
	*szDest = 0;

	CallService( MS_UTILS_GETBITMAPFILTERSTRINGS, sizeof szFilter, ( LPARAM )szFilter );
	ofn.lStructSize = sizeof( OPENFILENAME );
	ofn.lpstrFilter = szFilter;
	ofn.lpstrFile = szDest;
	ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
	ofn.nMaxFile = MAX_PATH;
	ofn.nMaxFileTitle = MAX_PATH;
	ofn.lpstrDefExt = "bmp";
	if ( !GetOpenFileNameA( &ofn ))
		return 1;

	return ERROR_SUCCESS;
}

int MirandaExit(WPARAM wParam, LPARAM lParam) {
	UNREFERENCED_PARAMETER(wParam);
	UNREFERENCED_PARAMETER(lParam);

	MirandaShuttingDown=TRUE;
	return 0;
}

int OkToExit(WPARAM wParam, LPARAM lParam) {
	UNREFERENCED_PARAMETER(wParam);
	UNREFERENCED_PARAMETER(lParam);

//	logoff_contacts();
	MirandaShuttingDown=TRUE;

	// Trigger all semaphores and events just to be sure that there is no deadlock
	ReleaseSemaphore(SkypeMsgReceived, receivers, NULL);
    SetEvent (SkypeReady);
	SetEvent (MessagePumpReady);
#ifdef SKYPEBUG_OFFLN
	SetEvent(GotUserstatus);
#endif
	SetEvent (hBuddyAdded);

	SkypeFlush ();
	PostMessage (g_hWnd, WM_CLOSE, 0, 0);
	return 0;
}


struct PLUGINDI {
	char **szSettings;
	int dwCount;
};

// Taken from pluginopts.c and modified
int EnumOldPluginName(const char *szSetting,LPARAM lParam)
{
	struct PLUGINDI *pdi=(struct PLUGINDI*)lParam;
	if (pdi && lParam) {
			pdi->szSettings=(char**)realloc(pdi->szSettings,(pdi->dwCount+1)*sizeof(char*));
			pdi->szSettings[pdi->dwCount++]=_strdup(szSetting);
	}
	return 0;
}

// Are there any Skype users on list?
// 1 --> Yes
// 0 --> No
int AnySkypeusers(void)
{
	HANDLE hContact;
	DBVARIANT dbv;
	int tCompareResult;

	// already on list?
	for (hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
		 hContact != NULL;
		 hContact=(HANDLE)CallService( MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0))
	{
		// GETCONTACTBASEPROTO doesn't work on not loaded protocol, therefore get
		// protocol from DB
		if (DBGetContactSettingString(hContact, "Protocol", "p", &dbv)) continue;
        tCompareResult = !strcmp(dbv.pszVal, SKYPE_PROTONAME);
		DBFreeVariant(&dbv);
		if (tCompareResult) return 1;
	}
	return 0;
}


void UpgradeName(char *OldName)
{
	DBCONTACTENUMSETTINGS cns;
	DBCONTACTWRITESETTING cws;
	DBVARIANT dbv;
	HANDLE hContact=NULL;
	struct PLUGINDI pdi;

	LOG(("Updating old database settings if there are any..."));
	cns.pfnEnumProc=EnumOldPluginName;
	cns.lParam=(LPARAM)&pdi;
	cns.szModule=OldName;
	cns.ofsSettings=0;

	hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);

	for ( ;; ) {
		memset(&pdi,0,sizeof(pdi));
		CallService(MS_DB_CONTACT_ENUMSETTINGS,(WPARAM)hContact,(LPARAM)&cns);
		// Upgrade Protocol settings to new string
		if (pdi.szSettings) {
			int i;

			LOG(("We're currently upgrading..."));
			for (i=0;i<pdi.dwCount;i++) {
				if (!DBGetContactSettingString(hContact, OldName, pdi.szSettings[i], &dbv)) {
					cws.szModule=SKYPE_PROTONAME;
					cws.szSetting=pdi.szSettings[i];
					cws.value=dbv;
					if (!CallService(MS_DB_CONTACT_WRITESETTING,(WPARAM)hContact,(LPARAM)&cws))
						DBDeleteContactSetting(hContact,OldName,pdi.szSettings[i]);
					DBFreeVariant(&dbv);
				}
				free(pdi.szSettings[i]);
			}
			free(pdi.szSettings);
		}
		// Upgrade Protocol assignment, if we are not main contact
		if (hContact && !DBGetContactSettingString(hContact, "Protocol", "p", &dbv)) {
			if (!strcmp(dbv.pszVal, OldName))
				DBWriteContactSettingString(hContact, "Protocol", "p", SKYPE_PROTONAME);
			DBFreeVariant(&dbv);
		}
		if (!hContact) break;
		hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0);
	}

	DBWriteContactSettingByte(NULL, SKYPE_PROTONAME, "UpgradeDone", (BYTE)1);
	return;
}

void __cdecl MsgPump (char *dummy)
{
  MSG msg;

  WNDCLASS WndClass;

  UNREFERENCED_PARAMETER(dummy);

  // Create window class
  WndClass.style = CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS;
  WndClass.lpfnWndProc = (WNDPROC)WndProc;
  WndClass.cbClsExtra = 0;
  WndClass.cbWndExtra = 0;
  WndClass.hInstance =  hInst;
  WndClass.hIcon = NULL;
  WndClass.hCursor = NULL;
  WndClass.hbrBackground = NULL;
  WndClass.lpszMenuName = NULL;
  WndClass.lpszClassName = _T("SkypeApiDispatchWindow");
  RegisterClass(&WndClass);
  // Do not check the retval of RegisterClass, because on non-unicode
  // win98 it will fail, as it is a stub that returns false() there

  // Create main window
  g_hWnd=CreateWindowEx( WS_EX_APPWINDOW|WS_EX_WINDOWEDGE,
		_T("SkypeApiDispatchWindow"), _T(""), WS_BORDER|WS_SYSMENU|WS_MINIMIZEBOX,
		CW_USEDEFAULT, CW_USEDEFAULT, 128, 128, NULL, 0, (HINSTANCE)WndClass.hInstance, 0);

  LOG (("Created Dispatch window with handle %08X", (long)g_hWnd));
  if (!g_hWnd) {
	OUTPUT(_T("Cannot create window."));
	TellError(GetLastError());
	SetEvent(MessagePumpReady);
    return;
  }
  ShowWindow(g_hWnd, 0);
  UpdateWindow(g_hWnd);
  msgPumpThreadId = GetCurrentThreadId();
  SetEvent(MessagePumpReady);

  LOG (("Messagepump started."));
  while (GetMessage (&msg, NULL, 0, 0) > 0 && !Miranda_Terminated()) {
	  TranslateMessage (&msg);
	  DispatchMessage (&msg);
  }
  UnregisterClass (WndClass.lpszClassName, hInst);
  LOG (("Messagepump stopped."));
}

// DLL Stuff //

__declspec(dllexport) PLUGININFOEX* MirandaPluginInfo(DWORD mirVersion)
{
	mirandaVersion = mirVersion;

	pluginInfo.cbSize = sizeof(PLUGININFOEX);
	return (PLUGININFOEX*) &pluginInfo;
}

__declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirVersion)
{
	mirandaVersion = mirVersion;

	return &pluginInfo;
}

static const MUUID interfaces[] = {MUUID_SKYPE_CALL, MIID_LAST};
__declspec(dllexport) const MUUID * MirandaPluginInterfaces(void)
{
	return interfaces;
}


BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{
	UNREFERENCED_PARAMETER(fdwReason);
	UNREFERENCED_PARAMETER(lpvReserved);

	hInst = hinstDLL;
	return TRUE;
}


int PreShutdown(WPARAM wParam, LPARAM lParam) {
	UNREFERENCED_PARAMETER(wParam);
	UNREFERENCED_PARAMETER(lParam);

	PostThreadMessage(msgPumpThreadId, WM_QUIT, 0, 0);
	return 0;
}

int __declspec(dllexport) Load()
{
	PROTOCOLDESCRIPTOR pd = {0};
	DWORD Buffsize;
	HKEY MyKey;
	BOOL SkypeInstalled;
	BOOL UseCustomCommand;
	WSADATA wsaData = {0};
	char path[MAX_PATH];

	mir_getLP(&pluginInfo);

	GetModuleFileNameA( hInst, path, sizeof( path ));
	_splitpath (path, NULL, NULL, SKYPE_PROTONAME, NULL);
	CharUpperA( SKYPE_PROTONAME );

	InitializeCriticalSection(&RingAndEndcallMutex);
	InitializeCriticalSection(&QueryThreadMutex);
	InitializeCriticalSection(&TimeMutex);


#ifdef _DEBUG
	init_debug();
#endif

	LOG(("Load: Skype Plugin loading..."));

	// We need to upgrade SKYPE_PROTOCOL internal name to Skype if not already done
	if (!DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UpgradeDone", 0))
		UpgradeName("SKYPE_PROTOCOL");

    // Initialisation of Skype MsgQueue must be done because of Cleanup in end and
	// Mutex is also initialized here.
	LOG(("SkypeMsgInit initializing Skype MSG-queue"));
	if (SkypeMsgInit()==-1) {
		OUTPUT(_T("Memory allocation error on startup."));
		return 0;
	}

	// On first run on new profile, ask user, if he wants to enable the plugin in
	// this profile
	// --> Fixing Issue #0000006 from bugtracker.
	if (!DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "FirstRun", 0)) {
		DBWriteContactSettingByte(NULL, SKYPE_PROTONAME, "FirstRun", 1);
		if (AnySkypeusers()==0) // First run, it seems :)
			if (MessageBox(NULL, TranslateT("This seems to be the first time that you're running the Skype protocol plugin. Do you want to enable the protocol for this Miranda-Profile? (If you chose NO, you can always enable it in the plugin options later."), _T("Welcome!"), MB_ICONQUESTION|MB_YESNO)==IDNO) {
				char path[MAX_PATH], *filename;
				GetModuleFileNameA(hInst, path, sizeof(path));
				if (filename = strrchr(path,'\\')+1)
					DBWriteContactSettingByte(NULL,"PluginDisable",filename,1);
				return 0;
			}
	}


	// Check if Skype is installed
	SkypeInstalled=TRUE;
	UseCustomCommand = (BYTE)DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseCustomCommand", 0);
	UseSockets = (BOOL)DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseSkype2Socket", 0);

	if (!UseSockets && !UseCustomCommand)
	{
		BOOL is_key_opened = FALSE;
		if (RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Skype\\Phone"), 0, KEY_READ, &MyKey)!=ERROR_SUCCESS)
		{
			if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\Skype\\Phone"), 0, KEY_READ, &MyKey)!=ERROR_SUCCESS)
			{
				SkypeInstalled=FALSE;
			}
			else
				is_key_opened = TRUE;
		}
		else
			is_key_opened = TRUE;

		Buffsize=sizeof(skype_path);

		if(is_key_opened)
		{
			if (SkypeInstalled==FALSE)
				skype_path[0]=0;
			else if (RegQueryValueExA(MyKey, "SkypePath", NULL, NULL, (unsigned char *)skype_path,  &Buffsize)!=ERROR_SUCCESS)
			{
				//OUTPUT("Skype was not found installed :( \nMaybe you are using portable skype.");
				RegCloseKey(MyKey);
				skype_path[0]=0;
				//return 0;
			}
			else
				RegCloseKey(MyKey);
		}
	}
	WSAStartup(MAKEWORD(2,2), &wsaData);

	// Start Skype connection
	if (!(ControlAPIAttach=RegisterWindowMessage(_T("SkypeControlAPIAttach"))) || !(ControlAPIDiscover=RegisterWindowMessage(_T("SkypeControlAPIDiscover"))))
	{
			OUTPUT(_T("Cannot register Window message."));
			return 0;
	}

	SkypeMsgReceived=CreateSemaphore(NULL, 0, MAX_MSGS, NULL);
	if (!(SkypeReady=CreateEvent(NULL, TRUE, FALSE, NULL)) ||
		!(MessagePumpReady=CreateEvent(NULL, FALSE, FALSE, NULL)) ||
#ifdef SKYPEBUG_OFFLN
	    !(GotUserstatus=CreateEvent(NULL, TRUE, FALSE, NULL)) ||
#endif
		!(hBuddyAdded=CreateEvent(NULL, FALSE, FALSE, NULL)) ||
		!(FetchMessageEvent=CreateEvent(NULL, FALSE, TRUE, NULL))) {
		 OUTPUT(_T("Unable to create Mutex!"));
		return 0;
	}

	/* Register the module */
	ZeroMemory(&pd, sizeof(pd));
	pd.cbSize = PROTOCOLDESCRIPTOR_V3_SIZE;
	pd.szName = SKYPE_PROTONAME;
	pd.type   = PROTOTYPE_PROTOCOL;
	CallService(MS_PROTO_REGISTERMODULE, 0, (LPARAM)&pd);

	VoiceServiceInit();

	CreateServices();
	HookEvents();
	InitVSApi();
	MsgList_Init();

	HookEvent(ME_SYSTEM_PRESHUTDOWN, PreShutdown);

	// Startup Message-pump
    forkthread (( pThreadFunc )MsgPump, 0, NULL);
	WaitForSingleObject(MessagePumpReady, INFINITE);
	return 0;
}



int __declspec( dllexport ) Unload(void)
{
	BOOL UseCustomCommand = DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "UseCustomCommand", 0);
	BOOL Shutdown = DBGetContactSettingByte(NULL, SKYPE_PROTONAME, "Shutdown", 0);

	LOG (("Unload started"));

	if ( Shutdown && ((skype_path && skype_path[0]) ||UseCustomCommand) ) {

		if(UseCustomCommand)
		{
			DBVARIANT dbv;
			if(!DBGetContactSettingString(NULL,SKYPE_PROTONAME,"CommandLine",&dbv))
			{
				char szAbsolutePath[MAX_PATH];

				TranslateMirandaRelativePathToAbsolute(dbv.pszVal, szAbsolutePath, FALSE);
				_spawnl(_P_NOWAIT, szAbsolutePath, szAbsolutePath, "/SHUTDOWN", NULL);
				LOG (("Unload Sent /shutdown to %s", szAbsolutePath));
				DBFreeVariant(&dbv);
			}
		}
		else
		{
			_spawnl(_P_NOWAIT, skype_path, skype_path, "/SHUTDOWN", NULL);
			LOG (("Unload Sent /shutdown to %s", skype_path));
		}

	}
	SkypeMsgCleanup();
	//WSACleanup();
	FreeVSApi();
	UnhookEvents();
	UnhookEvent(hChatEvent);
	UnhookEvent (hChatMenu);
	UnhookEvent (hEvInitChat);
	DestroyHookableEvent(hInitChat);
	VoiceServiceExit();
	GCExit();
	MsgList_Exit();

	CloseHandle(SkypeReady);
	CloseHandle(SkypeMsgReceived);
#ifdef SKYPEBUG_OFFLN
	CloseHandle(GotUserstatus);
#endif
	CloseHandle(MessagePumpReady);
	CloseHandle(hBuddyAdded);
	CloseHandle(FetchMessageEvent);

	DeleteCriticalSection(&RingAndEndcallMutex);
	DeleteCriticalSection(&QueryThreadMutex);

	SkypeRegisterProxy (0, 0);
	LOG (("Unload: Shutdown complete"));
#ifdef _DEBUG
	end_debug();
#endif
	DeleteCriticalSection(&TimeMutex);
	return 0;
}