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

/*
 *  Plugin of miranda IM(ICQ) for Communicating with users of the XFire Network.
 *
 *  Copyright (C) 2010 by
 *          dufte <dufte@justmail.de>
 *
 *  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 *  Based on J. Lawler              - BaseProtocol
 *			 Herbert Poul/Beat Wolf - xfirelib
 *
 *  Miranda ICQ: the free icq client for MS Windows
 *  Copyright (C) 2000-2008  Richard Hughes, Roland Rabien & Tristan Van de Vreede
 *
 */

//xfire stuff
#include "client.h"
#include "xfirepacket.h"
#include "loginfailedpacket.h"
#include "otherloginpacket.h"
#include "loginsuccesspacket.h"
#include "messagepacket.h"
#include "sendstatusmessagepacket.h"
#include "sendmessagepacket.h"
#include "invitebuddypacket.h"
#include "sendacceptinvitationpacket.h"
#include "senddenyinvitationpacket.h"
#include "sendremovebuddypacket.h"
#include "sendnickchangepacket.h"
#include "sendgamestatuspacket.h"
#include "sendgamestatus2packet.h"
#include "dummyxfiregameresolver.h"
#include "sendgameserverpacket.h"
#include "recvstatusmessagepacket.h"
#include "recvoldversionpacket.h"
#include "packetlistener.h"
#include "inviterequestpacket.h"
#include "buddylistgames2packet.h"
#include "dummyxfiregameresolver.h"
#include "sendtypingpacket.h"
#include "xfireclanpacket.h"
#include "recvremovebuddypacket.h"
#include "gameinfopacket.h"
#include "claninvitationpacket.h"
#include "xfireprefpacket.h"
#include "searchbuddy.h"
#include "xfirefoundbuddys.h"
#include "getbuddyinfo.h"
#include "buddyinfo.h"
#include "variables.h"
#include "passworddialog.h"
#include "setnickname.h"
#include "all_statusmsg.h"
#include "processbuddyinfo.h"
#include "recvprefspacket.h"
#include "sendsidpacket.h"
#include "friendsoffriendlist.h"
#include "recvbuddychangednick.h"

//miranda stuff
#include "baseProtocol.h"
#include "Xfire_gamelist.h"
#include "Xfire_proxy.h"
#include "Xfire_avatar_loader.h"
#include "Xfire_voicechat.h"

#include "variables.h"

#include <stdexcept>
#include <sstream>

Xfire_gamelist xgamelist;
Xfire_voicechat voicechat;

HANDLE hLogEvent;
int bpStatus = ID_STATUS_OFFLINE;
int previousMode;
int OptInit(WPARAM wParam,LPARAM lParam);
int OnDetailsInit(WPARAM wParam,LPARAM lParam);
HANDLE hFillListEvent = 0;
CONTACT user;
HINSTANCE hinstance = NULL;
int hLangpack;
HANDLE hExtraIcon1, hExtraIcon2;
HANDLE heventXStatusIconChanged;
HGENMENU copyipport,gotoclansite,vipport,joingame,startthisgame,removefriend,blockfriend;
int foundgames=0;
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR           gdiplusToken;

//xfire preferences, wichtige variablen
xfire_prefitem xfireconfig[XFIRE_RECVPREFSPACKET_MAXCONFIGS];
extern xfireconfigitem xfireconfigitems[XFIRE_RECVPREFSPACKET_SUPPORTEDONFIGS];

CRITICAL_SECTION modeMsgsMutex;
CRITICAL_SECTION avatarMutex;
CRITICAL_SECTION connectingMutex;

DWORD pid=NULL; //processid des gefunden spiels
DWORD ts2pid=NULL; // processid vom teamspeak/ventrilo

HANDLE	 XFireAvatarFolder = NULL;
HANDLE	 XFireWorkingFolder = NULL;
HANDLE	 XFireIconFolder = NULL;
HANDLE	 hookgamestart = NULL;
char statusmessage[2][1024];
BOOL sendonrecieve=FALSE;
HANDLE hNetlib=NULL;
pGetExtendedUdpTable _GetExtendedUdpTable=NULL;
extern LPtsrGetServerInfo tsrGetServerInfo;

//eventhandles
HANDLE hGameDetection = CreateEvent(NULL,FALSE,FALSE,NULL);
HANDLE hConnectionClose = CreateEvent(NULL,TRUE,FALSE,NULL);

PLUGININFOEX pluginInfoEx={
		sizeof(PLUGININFOEX),
		"Xfire protocol",
		PLUGIN_MAKE_VERSION(0,1,8,4),
		"Xfire protocol support for Miranda NG.",
		"dufte",
		"dufte@justmail.de",
		"(c) 2012 Xfirelib by Herbert Poul, Xfire Miranda protocol plugin by dufte",
		"http://miranda-ng.org",
		UNICODE_AWARE,
		{ 0x9b8e1735, 0x970d, 0x4ce0, { 0x93, 0xc, 0xa5, 0x61, 0x95, 0x6b, 0xdc, 0xa2 } } // {9B8E1735-970D-4ce0-930C-A561956BDCA2}
};

static IconItem icon = { LPGEN("Protocol icon"), "XFIRE_main", IDI_TM };

INT_PTR RecvMessage(WPARAM wParam, LPARAM lParam);
INT_PTR SendMessage(WPARAM wParam, LPARAM lParam);

int FillList(WPARAM wParam, LPARAM lParam);
HANDLE CList_AddContact(XFireContact xfc, bool InList, bool SetOnline,int clan);
HANDLE CList_FindContact (int uid);
void CList_MakeAllOffline();
static INT_PTR UserIsTyping(WPARAM wParam, LPARAM lParam);
HANDLE LoadGameIcon(char* g, int id, HICON* ico,BOOL onyico=FALSE,char * gamename=NULL,int*uu=NULL);
void SetIcon(HANDLE hcontact,HANDLE hicon,int ctype=1);
BOOL GetAvatar(char* username,XFireAvatar* av);
//void SetAvatar(HANDLE hContact, char* username);
static void SetAvatar(LPVOID lparam);
static INT_PTR GetIPPort(WPARAM /*wParam*/,LPARAM lParam);
static INT_PTR GetVIPPort(WPARAM /*wParam*/,LPARAM lParam);
int RebuildContactMenu( WPARAM wParam, LPARAM lParam );
int doneQuery( WPARAM wParam, LPARAM lParam );

static INT_PTR GotoProfile(WPARAM wParam,LPARAM lParam);
static INT_PTR GotoProfileAct(WPARAM wParam,LPARAM lParam);
static INT_PTR GotoXFireClanSite(WPARAM wParam,LPARAM lParam);
static INT_PTR ReScanMyGames(WPARAM wParam,LPARAM lParam);
static INT_PTR SetNickDlg(WPARAM wParam,LPARAM lParam);
static INT_PTR CustomGameSetup(WPARAM wParam,LPARAM lParam);

#ifndef NO_PTHREAD
	void *gamedetectiont(void *ptr);
	void *inigamedetectiont(void *ptr);
	pthread_t gamedetection;
#else
	void inigamedetectiont(LPVOID lParam);
	void gamedetectiont(LPVOID lparam);
#endif

INT_PTR AddtoList( WPARAM wParam, LPARAM lParam );
INT_PTR BasicSearch(WPARAM wParam,LPARAM lParam);
INT_PTR GetAvatarInfo(WPARAM wParam, LPARAM lParam); //GAIR_NOAVATAR
INT_PTR SearchAddtoList(WPARAM wParam,LPARAM lParam);
INT_PTR SendPrefs(WPARAM wparam, LPARAM lparam);
INT_PTR SetAwayMsg(WPARAM wParam, LPARAM lParam);
INT_PTR GetAwayMsg(WPARAM /*wParam*/, LPARAM lParam);
INT_PTR GetXStatusIcon(WPARAM wParam, LPARAM lParam);

static INT_PTR GotoProfile2(WPARAM wParam,LPARAM lParam);
HANDLE handlingBuddys(BuddyListEntry *entry, int clan=0,char* group=NULL,BOOL dontscan=FALSE);
int StatusIcon(WPARAM wParam,LPARAM lParam);

void CreateGroup(char*grpn,char*field); //void CreateGroup(char*grp);
int ContactDeleted(WPARAM wParam,LPARAM /*lParam*/);
INT_PTR JoinGame(WPARAM wParam,LPARAM lParam);
extern void Scan4Games( LPVOID lparam  );
INT_PTR RemoveFriend(WPARAM wParam,LPARAM lParam);
INT_PTR BlockFriend(WPARAM wParam,LPARAM lParam);
INT_PTR StartThisGame(WPARAM wParam,LPARAM lParam);
int IconLibChanged(WPARAM wParam, LPARAM lParam);
void SetAvatar2(LPVOID lparam);
int ExtraListRebuild(WPARAM wparam, LPARAM lparam);
int ExtraImageApply(WPARAM wparam, LPARAM lparam);

//XFire Stuff
using namespace xfirelib;

class XFireClient : public PacketListener {

  public:
    Client* client;
	Xfire_avatar_loader* avatarloader;
	BOOL useutf8;

    XFireClient(string username, string password,char protover,int useproxy=0,string proxyip="",int proxyport=0);
    ~XFireClient();
    void run();

    void Status(string s);

    void receivedPacket(XFirePacket *packet);

	void getBuddyList();
	void sendmsg(char*usr,char*msg);
	void setNick(char*nnick);
	void handlingBuddy(HANDLE handle);
	void CheckAvatar(BuddyListEntry* entry);

  private:
    vector<string> explodeString(string s, string e);
    string joinString(vector<string> s, int startindex, int endindex=-1, string delimiter=" ");
    void BuddyList();

    string *lastInviteRequest;

    string username;
    string password;
	string proxyip;
	int useproxy;
	int proxyport;
	BOOL connected;
	unsigned int myuid;
 };

XFireClient* myClient=NULL;

void XFireClient::CheckAvatar(BuddyListEntry* entry) {
	//kein entry, zurück
	if(!entry)
		return;

	//keine avatars?
	if(db_get_b(NULL,protocolname,"noavatars",-1)==0)
	{
		//avatar gelocked?
		if(db_get_b(entry->hcontact, "ContactPhoto", "Locked", -1)!=1)
		{
			//avatar lade auftrag übergeben
			this->avatarloader->loadAvatar(entry->hcontact,(char*)entry->username.c_str(),entry->userid);
		}
	}
}

void XFireClient::handlingBuddy(HANDLE handle){
	vector<BuddyListEntry*> *entries = client->getBuddyList()->getEntries();
	for(uint i = 0 ; i < entries->size() ; i ++) {
		BuddyListEntry *entry = entries->at(i);
		if(entry->hcontact==handle)
		{
			handlingBuddys(entry,0,NULL);
			break;
		}
	}
	//mir_forkthread(
}

void XFireClient::setNick(char*nnick) {
	/*if(strlen(nnick)==0)
		return;*/
	  SendNickChangePacket nick;
	  if(this->useutf8)
		nick.nick = ( char* )nnick;
	  else
		nick.nick = mir_utf8encode(( char* )nnick);
	  client->send( &nick );
}


void XFireClient::sendmsg(char*usr,char*cmsg) {
		SendMessagePacket msg;
	//	if(strlen(cmsg)>255)
	//		*(cmsg+255)=0;
		msg.init(client, usr, cmsg);
		client->send( &msg );
	}


  XFireClient::XFireClient(string username_,string password_,char protover,int useproxy,string proxyip,int proxyport)
    : username(username_), password(password_) {
    client = new Client();
    client->setGameResolver( new DummyXFireGameResolver() );
	client->protocolVersion=protover;
	avatarloader = new Xfire_avatar_loader(client);
	this->useproxy=useproxy;
	this->proxyip=proxyip;
	this->proxyport=proxyport;
	useutf8=FALSE;

	avatarloader=new Xfire_avatar_loader(client);

    lastInviteRequest = NULL;
	connected = FALSE;
  }

  XFireClient::~XFireClient() {
	if(client!=NULL) {
		client->disconnect();
		delete client;
	}
	if(avatarloader) {
		delete avatarloader;
		avatarloader=NULL;
	}
    if(lastInviteRequest!=NULL) delete lastInviteRequest;
  }

  void XFireClient::run() {
	client->connect(username,password,useproxy,proxyip,proxyport);
    client->addPacketListener(this);
  }

  void XFireClient::Status(string s) {
	  //da bei xfire statusmsg nur 100bytes länge unterstützt werden, wird gecutted
	  if(!client->gotBudduyList)
		  return;

	  s = s.substr(0, 100);

	  SendStatusMessagePacket *packet = new SendStatusMessagePacket();

	  if(myClient->useutf8)
		  packet->awaymsg = s.c_str();
	  else
		  packet->awaymsg = mir_utf8encode(s.c_str());

	  client->send( packet );
	  delete packet;
  }

  void XFireClient::receivedPacket(XFirePacket *packet) {
	  XFirePacketContent *content = packet->getContent();

	  switch(content->getPacketId())
	  {
		  /*case XFIRE_RECVBUDDYCHANGEDNICK:
		  {
			  RecvBuddyChangedNick *changednick = (RecvBuddyChangedNick*)content;
			  if(changednick) {
				handlingBuddys((BuddyListEntry*)changednick->entry,0,NULL);
			  }
			  break;
		  }*/
		  //Konfigpacket empfangen
		  case XFIRE_RECVPREFSPACKET:
		  {
			  //Konfigarray leeren
			  memset(&xfireconfig,0,sizeof(xfire_prefitem)*XFIRE_RECVPREFSPACKET_MAXCONFIGS);
			  RecvPrefsPacket *config = (RecvPrefsPacket*)content;
			  //konfigs in array speichern
			  if(config!=NULL)
			  {
				  //ins preferenes array sichern
				  for(int i=0;i<XFIRE_RECVPREFSPACKET_MAXCONFIGS;i++)
				  {
					  xfireconfig[i]=config->config[i];
				  }
				  //datenbank einträge durchführen
				  for(int i=0;i<XFIRE_RECVPREFSPACKET_SUPPORTEDONFIGS;i++)
				  {
					  char temp=1;
					  if(xfireconfig[xfireconfigitems[i].xfireconfigid].wasset==1)
					  {
						  temp=0;
					  }
					  db_set_b(NULL,protocolname,xfireconfigitems[i].dbentry,temp);
				  }
			  }
			  break;
		  }
		  case XFIRE_FOUNDBUDDYS_ID:
		  {
			  PROTOSEARCHRESULT psr;
			  ZeroMemory(&psr, sizeof(psr));
			  psr.cbSize = sizeof(psr);

			  XFireFoundBuddys *fb = (XFireFoundBuddys*)content;
			  for(uint i = 0 ; i < fb->usernames->size() ; i++) {
				  if((char*)fb->usernames->at(i).c_str()!=NULL)
					psr.nick = (char*)fb->usernames->at(i).c_str();
				  if((char*)fb->fname->at(i).c_str()!=NULL)
					  psr.firstName = (char*)fb->fname->at(i).c_str();
				  if((char*)fb->lname->at(i).c_str()!=NULL)
					  psr.lastName = (char*)fb->lname->at(i).c_str();
				  ProtoBroadcastAck(protocolname, NULL, ACKTYPE_SEARCH, ACKRESULT_DATA, (HANDLE) 1, (LPARAM) & psr);
			  }

			  ProtoBroadcastAck(protocolname, NULL, ACKTYPE_SEARCH, ACKRESULT_SUCCESS, (HANDLE) 1, 0);
			  break;
		  }
		  case XFIRE_BUDDYINFO:
		  {
			  BuddyInfoPacket *buddyinfo = (BuddyInfoPacket*)content;
			  BuddyListEntry *entry = client->getBuddyList()->getBuddyById( buddyinfo->userid );

			  //wenn die uid die gleiche wie die eigene ist, dann avatar auch selbst zuweisen
			  if(buddyinfo->userid==this->myuid) {
				  ProcessBuddyInfo(buddyinfo,NULL,"myxfireavatar");
			  }

			  if(entry)
				ProcessBuddyInfo(buddyinfo,entry->hcontact,(char*)entry->username.c_str());

			  break;
		  }
		  case XFIRE_CLANINVITATION_ID:
		  {
			  ClanInvitationPacket *claninv = (ClanInvitationPacket*)content;
			  for(int i=0;i<claninv->numberOfInv;i++)
			  {
				  char msg[XFIRE_MAX_STATIC_STRING_LEN];
				  sprintf(msg,Translate("%s (Nickname: %s) has invited you to join the %s clan. Message: %s%sPlease go to the XFireclan-Site to accept the Invitation."),claninv->invitefromusername[i].c_str(),
																								claninv->invitefrom[i].c_str(),
																								claninv->clanname[i].c_str(),
																								claninv->invitemsg[i].c_str(),"\n");
				  MSGBOX(msg);
			  }
			  break;
		  }
		  case XFIRE_GAMEINFO_ID:
		  {
			  GameInfoPacket *gameinfo = (GameInfoPacket*)content;
			  for(uint i = 0 ; i < gameinfo->sids->size() ; i++) {
				  BuddyListEntry *entry = client->getBuddyList()->getBuddyBySid( gameinfo->sids->at(i) );
				  if(entry){
					entry->gameinfo = gameinfo->gameinfo->at(i);
					handlingBuddys(entry,0,NULL);
				  }
			  }
			  break;
		  }
		  case XFIRE_RECVREMOVEBUDDYPACKET:
		  {
				RecvRemoveBuddyPacket *remove = (RecvRemoveBuddyPacket*)content;
				CallService( MS_DB_CONTACT_DELETE, (WPARAM) remove->handle, 1 );
				break;
		  }
		  case XFIRE_BUDDYS_NAMES_ID:
		  {
				//status nachricht nach der buddylist senden
			    client->gotBudduyList=TRUE;
				if(sendonrecieve)
				{
					if(myClient!=NULL)
					{
						if(myClient->client->connected)
						{
							//
							if (bpStatus == ID_STATUS_AWAY)
								myClient->Status(statusmessage[1]);
							else
								myClient->Status(statusmessage[0]);
						}
					}
					sendonrecieve=FALSE;
				}
				sendonrecieve=FALSE;

/*			  	GetBuddyInfo buddyinfo;

				vector<BuddyListEntry*> *entries = client->getBuddyList()->getEntries();
				for(uint i = 0 ; i < entries->size() ; i ++) {
					BuddyListEntry *entry = entries->at(i);
					handlingBuddys(entry,0,NULL);
				}*/
				break;
		  }
		 /* case XFIRE_CLAN_BUDDYS_NAMES_ID:
		  {
				vector<BuddyListEntry*> *entries = client->getBuddyList()->getEntriesClan();

				char temp[255];
				char * dummy;
				ClanBuddyListNamesPacket *clan = (ClanBuddyListNamesPacket*)content;
				sprintf(temp,"Clan_%d",clan->clanid);

				DBVARIANT dbv;
				if(!db_get(NULL,protocolname,temp,&dbv))
				{
					dummy=dbv.pszVal;
				}
				else
					dummy=NULL;

				for(uint i = 0 ; i < entries->size() ; i ++) {
					BuddyListEntry *entry = entries->at(i);
					if(entry->clanid==clan->clanid) {
						handlingBuddys(entry,clan->clanid,dummy);
					}
				}
				break;
		  }*/
		  case XFIRE_FRIENDS_BUDDYS_NAMES_ID:
		  {
				for(uint i = 0 ; i < ((FriendsBuddyListNamesPacket*)content)->userids->size() ; i++) {
					BuddyListEntry *entry = client->getBuddyList()->getBuddyById( ((FriendsBuddyListNamesPacket*)content)->userids->at(i) );
					if(entry) {
						char fofname[128]=LPGEN("Friends of Friends Playing");
						DBVARIANT dbv;
						//gruppennamen überladen
						if(!db_get(NULL,protocolname,"overload_fofgroupname",&dbv))
						{
							strcpy_s(fofname,128,dbv.pszVal);
							db_free(&dbv);
						}
						CreateGroup(Translate(fofname),"fofgroup");
						HANDLE hc=handlingBuddys(entry,-1,Translate(fofname));
						if(hc)
						{
							CheckAvatar(entry);
							db_set_b(hc,protocolname,"friendoffriend",1);
						}
					}
				}
				break;
		  }
		  /*case XFIRE_BUDDYS_ONLINE_ID:
		  {
			    for(uint i = 0 ; i < ((BuddyListOnlinePacket*)content)->userids->size() ; i++) {
					BuddyListEntry *entry = client->getBuddyList()->getBuddyById( ((BuddyListOnlinePacket*)content)->userids->at(i) );
					if(entry){
						handlingBuddys(entry,0,NULL);
					}
				}
				break;
		  }*/
		  /*case XFIRE_RECV_STATUSMESSAGE_PACKET_ID:
		  {
			  for(uint i=0;i<((RecvStatusMessagePacket*)content)->sids->size();i++)
			  {
				  BuddyListEntry *entry = this->client->getBuddyList()->getBuddyBySid( ((RecvStatusMessagePacket*)content)->sids->at(i) );
				  if(entry) //crashbug entfernt
					setBuddyStatusMsg(entry); //auf eine funktion reduziert, verringert cpuauslastung und beseitigt das
															 //das problem der fehlenden statusmsg
				  //handlingBuddys(entry,0,NULL);
			  }
			  break;
		  }*/
		  case XFIRE_BUDDYS_GAMES_ID:
		  {
			  vector<char *> *sids=NULL; //dieses array dient zu zwischensicherung von unbekannten sids
			  for(uint i=0;i<((BuddyListGamesPacket*)content)->sids->size();i++)
			  {
				  BuddyListEntry *entry = this->client->getBuddyList()->getBuddyBySid( ((BuddyListGamesPacket*)content)->sids->at(i) );
				  if(entry!=NULL)
				  {
					  //wir haben einen unbekannten user
					  if(entry->username.length()==0)
					  {
						  //sid array ist noch nicht init
						  if(sids==NULL)
						  {
							  sids = new vector<char *>;
						  }
						  //kopie der sid anlegen
						  char *sid = new char[16];
						  memcpy(sid,((BuddyListGamesPacket*)content)->sids->at(i),16);
						  //ab ins array damit
						  sids->push_back(sid);
					  }
					  else
					  {
						  if(entry->game == 0 && entry->hcontact != 0 && db_get_b(entry->hcontact,protocolname,"friendoffriend",0)==1)
							  db_set_w(entry->hcontact,protocolname,"Status",ID_STATUS_OFFLINE);
						  else
							  handlingBuddys(entry,0,NULL);
					  }
				  }
			  }
			  //sid anfragen nur senden, wenn das sids array init wurde
			  if(sids)
			  {
				  SendSidPacket sp;
				  sp.sids=sids;
				  client->send( &sp );
				  delete sids;
			  }
			  break;
		  }
		  case XFIRE_BUDDYS_GAMES2_ID:
		  {
			  for(uint i=0;i<((BuddyListGames2Packet*)content)->sids->size();i++)
			  {
				  BuddyListEntry *entry = this->client->getBuddyList()->getBuddyBySid( ((BuddyListGames2Packet*)content)->sids->at(i) );
				  if(entry!=NULL) handlingBuddys(entry,0,NULL);
			  }
			  break;
		  }
		  case XFIRE_PACKET_INVITE_REQUEST_PACKET: //friend request
		  {
			  InviteRequestPacket *invite = (InviteRequestPacket*)content;

			  //nur nich blockierte buddy's durchlassen
			  if(!db_get_b(NULL,"XFireBlock",(char*)invite->name.c_str(),0))
			  {
				  XFireContact xfire_newc;
				  xfire_newc.username=(char*)invite->name.c_str();
				  xfire_newc.nick=(char*)invite->nick.c_str();
				  xfire_newc.id=0;

				  HANDLE handle=CList_AddContact(xfire_newc,TRUE,TRUE,0);

				  if(handle) {  // invite nachricht mitsenden
	    			  string str = (char*)invite->msg.c_str();

					  PROTORECVEVENT pre;
					  pre.flags = 0;
					  pre.timestamp = time(NULL);
					  pre.szMessage = (char*)mir_utf8decode((char*)str.c_str(),NULL);
					  //invite nachricht konnte nicht zugewiesen werden?!?!?!
					  if(!pre.szMessage)
							pre.szMessage=(char*)str.c_str();
					  pre.lParam = 0;
					  ProtoChainRecvMsg(handle, &pre);
				  }
			  }
			  else
			  {
				  	SendDenyInvitationPacket deny;
					deny.name = invite->name;
					client->send( &deny );
			  }
			  break;
		  }
		case XFIRE_CLAN_PACKET:
		{
			char temp[100];
			XFireClanPacket *clan = (XFireClanPacket*)content;

			for(int i=0;i<clan->count;i++)
			{
				sprintf(temp,"Clan_%d",clan->clanid[i]);
				db_set_s(NULL, protocolname, temp, (char*)clan->name[i].c_str());

				sprintf(temp,"ClanUrl_%d",clan->clanid[i]);
				db_set_s(NULL, protocolname, temp, (char*)clan->url[i].c_str());

				if(!db_get_b(NULL,protocolname,"noclangroups",0)) {
					CreateGroup((char*)clan->name[i].c_str(),"mainclangroup");
				}
			}
			break;
		}
		case XFIRE_LOGIN_FAILED_ID:
			MSGBOXE(Translate("Login failed."));
			SetStatus(ID_STATUS_OFFLINE,NULL);
			break;
		case XFIRE_LOGIN_SUCCESS_ID: //login war erfolgreich
		{
			LoginSuccessPacket *login = (LoginSuccessPacket*)content;
			char * temp = mir_utf8decode((char*)login->nick.c_str(),NULL);
			//nick speichern
			db_set_s(NULL,protocolname,"Nick",temp);
			//uid speichern
			db_set_dw(NULL,protocolname,"myuid",login->myuid);
			this->myuid=login->myuid;
			//avatar auslesen
			GetBuddyInfo* buddyinfo=new GetBuddyInfo();
			buddyinfo->userid=login->myuid;
			mir_forkthread(SetAvatar2,(LPVOID)buddyinfo);
			break;
		}

		case XFIRE_RECV_OLDVERSION_PACKET_ID:
		{
			RecvOldVersionPacket *version = (RecvOldVersionPacket*)content;
			char temp[255];

			if((unsigned int)client->protocolVersion<(unsigned int)version->newversion)
			{
				db_set_b(NULL,protocolname,"protover",version->newversion);
				//recprotoverchg
				if(db_get_w(NULL,protocolname,"recprotoverchg",0)==0)
				{
					sprintf_s(temp,255,Translate("The protocol version is too old. Changed current version from %d to %d. You can reconnect now."),client->protocolVersion,version->newversion);
					MSGBOXE(temp);
				}
				else
				{
					SetStatus(ID_STATUS_RECONNECT,NULL);
					return;
				}
			}
			else
			{
				sprintf_s(temp,255,Translate("The protocol version is too old. Cannot detect a new version number."));
				MSGBOXE(temp);
				SetStatus(ID_STATUS_OFFLINE,NULL);
			}
			break;
		}

		case XFIRE_OTHER_LOGIN:
			MSGBOXE(Translate("Someone loged in with your account.disconnect."));
			SetStatus(ID_STATUS_OFFLINE,NULL);
			break;

		//ne nachricht für mich, juhu
		case XFIRE_MESSAGE_ID: {
			string str;

			if( (( MessagePacket*)content)->getMessageType() == 0){
				BuddyListEntry *entry = client->getBuddyList()->getBuddyBySid( ((MessagePacket*)content)->getSid() );
				if(entry!=NULL)
				{
					str=((MessagePacket*)content)->getMessage();

					PROTORECVEVENT pre = { 0 };
					pre.timestamp = time(NULL);
					if (this->useutf8) {
						pre.szMessage = (char*)str.c_str();
						pre.flags = PREF_UTF;
					}
					else pre.szMessage = (char*)mir_utf8decode((char*)str.c_str(),NULL);

					CallService(MS_PROTO_CONTACTISTYPING,(WPARAM)entry->hcontact,PROTOTYPE_CONTACTTYPING_OFF);
					ProtoChainRecvMsg(entry->hcontact, &pre);
				}
			}
			else if( (( MessagePacket*)content)->getMessageType() == 3) {
				BuddyListEntry *entry = client->getBuddyList()->getBuddyBySid( ((MessagePacket*)content)->getSid() );
				if(entry!=NULL)
					CallService(MS_PROTO_CONTACTISTYPING,(WPARAM)entry->hcontact,5);
			}

			break;
		}

	    //refresh buddy's
	  /*  if(content->getPacketId()==XFIRE_RECV_STATUSMESSAGE_PACKET_ID||
			content->getPacketId()==XFIRE_BUDDYS_GAMES_ID||
			content->getPacketId()==XFIRE_BUDDYS_GAMES2_ID)
        CallService(MS_CLIST_FRAMES_UPDATEFRAME, (WPARAM)-1, (LPARAM)FU_TBREDRAW | FU_FMREDRAW);*/
	  }

	  //
  }

//=====================================================

extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD)
{
	return &pluginInfoEx;
}

//=====================================================
// Unloads plugin
//=====================================================

extern "C" __declspec(dllexport) int  Unload(void)
{
	//urlprefix raushaun
	if(ServiceExists(MS_ASSOCMGR_ADDNEWURLTYPE))
		CallService(MS_ASSOCMGR_REMOVEURLTYPE, 0, (LPARAM)"xfire:");

	//gamedetetion das dead signal geben
	SetEvent(hGameDetection);

#ifndef NO_PTHREAD
	pthread_cancel (gamedetection);
	pthread_win32_process_detach_np ();
#endif

	DeleteCriticalSection(&modeMsgsMutex);
	DeleteCriticalSection(&connectingMutex);
	DeleteCriticalSection(&avatarMutex);

	Gdiplus::GdiplusShutdown(gdiplusToken);

	return 0;
}

void __stdcall XFireLog( const char* fmt, ... )
{
	va_list vararg;
	va_start( vararg, fmt );
	char* str = ( char* )alloca( 32000 );
	mir_vsnprintf( str, 32000, fmt, vararg );
	va_end( vararg );

	CallService( MS_NETLIB_LOG, ( WPARAM )hNetlib, ( LPARAM )str );
}

//=====================================================
// WINAPI DllMain
//=====================================================

BOOL WINAPI DllMain(HINSTANCE hinst,DWORD fdwReason,LPVOID lpvReserved)
{
	hinstance = hinst;
	//AtlAxWinInit();
	return TRUE;
}

//suche nach ini und danach starte gamedetection thread
void StartIniUpdateAndDetection(LPVOID dummy)
{
	EnterCriticalSection(&connectingMutex);

	//ini/ico updater, nur wenn aktiv
	if(db_get_b(NULL,protocolname,"autoiniupdate",0))
		UpdateMyXFireIni(NULL);
	if(db_get_b(NULL,protocolname,"autoicodllupdate",0))
		UpdateMyIcons(NULL);

#ifndef NO_PTHREAD
	void* (*func)(void*) = &inigamedetectiont;
	pthread_create( &gamedetection, NULL, func , NULL);
#else
	mir_forkthread(inigamedetectiont,NULL);
#endif

	LeaveCriticalSection(&connectingMutex);
}

INT_PTR UrlCall(WPARAM wparam,LPARAM lparam) {
	//lparam!=0?
	if(lparam) {
		//nach dem doppelpunkt suchen
		char*type=strchr((char*)lparam,':');
		//gefunden, dann anch fragezeichen suchen
		if(type)
		{
			type++;
			char*q=strchr(type,'?');
			//gefunden? dann urltype ausschneiden
			if(q)
			{
				//abschneiden
				*q=0;
				//ein addfriend url request?
				if(strcmp("add_friend",type)==0)
				{
					q++;
					//nach = suchen
					char*g=strchr(q,'=');
					//gefunden? dann abschneiden
					if(g)
					{
						*g=0;
						g++;
						//user parameter?
						if(strcmp("user",q)==0)
						{
							//tempbuffer für die frage and en user
							char temp[100];

							if(strlen(g)>25) //zugroße abschneiden
								*(g+25)=0;

							sprintf_s(temp,100,Translate("Do you really want to add %s to your friend list?"),g);
							//Nutzer vorher fragen, ob er wirklich user xyz adden möchte
							if(MessageBoxA(NULL,temp,"Miranda XFire Protocol Plugin",MB_YESNO|MB_ICONQUESTION)==IDYES)
							{
								if(myClient!=NULL)
								{
									if(myClient->client->connected)
									{
										InviteBuddyPacket invite;
										invite.addInviteName(g, Translate("Add me to your friends list."));
										myClient->client->send(&invite);
									}
									else
										MSGBOXE(Translate("XFire is not connected."));
								}
								else
									MSGBOXE(Translate("XFire is not connected."));
							}
						}
					}
				}
			}
		}

	}
	return 0;
}

//wenn alle module geladen sind
static int OnSystemModulesLoaded(WPARAM wParam,LPARAM lParam)
{
	char servicefunction[100];

	/*NETLIB***********************************/
	NETLIBUSER nlu;
	ZeroMemory(&nlu, sizeof(nlu));
    nlu.cbSize = sizeof(nlu);
    nlu.flags = NUF_OUTGOING | NUF_HTTPCONNS;
    nlu.szSettingsModule = protocolname;
    nlu.szDescriptiveName = "XFire server connection";
    hNetlib = (HANDLE) CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM) & nlu);
	/*NETLIB***********************************/

	HookEvent(ME_USERINFO_INITIALISE, OnDetailsInit);
	HookEvent(ME_DB_CONTACT_DELETED, ContactDeleted);

	//hook das queryplugin
	HookEvent("GameServerQuery/doneQuery" , doneQuery);

	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_SETAWAYMSG);
	CreateServiceFunction(servicefunction, SetAwayMsg);

	/*NETLIBUSER nlu;
	ZeroMemory(&nlu, sizeof(nlu));
    nlu.cbSize = sizeof(nlu);
    nlu.flags = NUF_NOHTTPSOPTION;
    nlu.szSettingsModule = protocolname;
    nlu.szDescriptiveName = "XFire Gamedetectionthread";
    hNetlibUser = (HANDLE) CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM) & nlu);*/


	// Variables support
	if (ServiceExists(MS_VARS_REGISTERTOKEN))
	{
		TOKENREGISTER tr = {0};
		tr.cbSize = sizeof(TOKENREGISTER);
		tr.memType = TR_MEM_MIRANDA;
		tr.flags = TRF_FREEMEM | TRF_PARSEFUNC | TRF_FIELD;

		tr.tszTokenString = _T("xfiregame");
		tr.parseFunction = Varxfiregame;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("Current Game");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

		tr.tszTokenString = _T("myxfiregame");
		tr.parseFunction = Varmyxfiregame;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("My Current Game");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

		tr.tszTokenString = _T("xfireserverip");
		tr.parseFunction = Varxfireserverip;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("ServerIP");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

		tr.tszTokenString = _T("myxfireserverip");
		tr.parseFunction = Varmyxfireserverip;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("My Current ServerIP");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

		tr.tszTokenString = _T("xfirevoice");
		tr.parseFunction = Varxfirevoice;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("Voice");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

		tr.tszTokenString = _T("myxfirevoice");
		tr.parseFunction = Varmyxfirevoice;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("My Current Voice");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

		tr.tszTokenString = _T("xfirevoiceip");
		tr.parseFunction = Varxfirevoiceip;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("Voice ServerIP");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

		tr.tszTokenString = _T("myxfirevoiceip");
		tr.parseFunction = Varmyxfirevoiceip;
		tr.szHelpText = LPGEN("XFire")"\t"LPGEN("My Voice ServerIP");
		CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr);

	}

	//File Association Manager support
	if(ServiceExists(MS_ASSOCMGR_ADDNEWURLTYPE))
	{
		AssocMgr_AddNewUrlType("xfire:",Translate("Xfire Link Protocol"),hinstance,IDI_TM,XFIRE_URLCALL,0);
	}

	//sound einfügen
	SkinAddNewSoundEx("xfirebstartgame",protocolname,LPGEN("Buddy start a game"));

	//hook für mbot einfügen, nur wenn mbot option aktiv
	if(db_get_b(NULL,protocolname,"mbotsupport",0))
		HookEvent(XFIRE_INGAMESTATUSHOOK, mBotNotify);

	//init der extraicons wenn service vorhanden
	/*if(ServiceExists(MS_EXTRAICON_REGISTER))
	{
		extraiconGAME=ExtraIcon_Register("Game Icon","Xfire game icons.","XFIRE_main",RebuildIcons,ApplyIcons);
		extraiconGAME=ExtraIcon_Register("Voice Icon","Xfire voice icons.","XFIRE_main");
	}*/

	//initialisiere teamspeak und co detection
	voicechat.initVoicechat();

	mir_forkthread(StartIniUpdateAndDetection,NULL);

	return 0;
}

//=====================================================
// Called when plugin is loaded into Miranda
//=====================================================

/*placebo funktionen*/
/*PROTO_INTERFACE* xfireProtoInit( const char* pszProtoName, const TCHAR* tszUserName )
{
	Xfire_m8 m8=new Xfire_m8();
	return m8;
}
/*placebo funktionen*/
/*static int xfireProtoUninit( void* ppro )
{
	return 0;
}

*/

int ExtraListRebuild(WPARAM wparam, LPARAM lparam)
{
	//für alle gameicons ein neues handle setzen
	return xgamelist.iconmngr.resetIconHandles();
}

int ExtraImageApply(WPARAM wparam, LPARAM lparam)
{
	HANDLE hContact=(HANDLE)wparam;
	// TODO: maybe need to fix extra icons
	char *szProto = GetContactProto(hContact);
	if ( szProto != NULL && !lstrcmpiA( szProto, protocolname ) && db_get_w(hContact, protocolname, "Status", ID_STATUS_OFFLINE)!=ID_STATUS_OFFLINE) {
		int gameid=db_get_w(hContact, protocolname, "GameId", 0);
		int gameid2=db_get_w(hContact, protocolname, "VoiceId", 0);

		if(gameid!=0)
		{
			SetIcon(hContact,xgamelist.iconmngr.getGameIconHandle(gameid));
		}
		if(gameid2!=0)
		{
			SetIcon(hContact,xgamelist.iconmngr.getGameIconHandle(gameid2),2);
		}
	}
	return 0;
}



extern "C" __declspec(dllexport) int  Load(void)
{
	mir_getLP(&pluginInfoEx);

	InitializeCriticalSection(&modeMsgsMutex);
	InitializeCriticalSection(&connectingMutex);
	InitializeCriticalSection(&avatarMutex);

	Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

	//void* init = GetProcAddress(LoadLibrary("atl"),"AtlAxWinInit"); _asm call init;

	//keine protoversion in der db, dann wohl der erste start von xfire
	if(db_get_b(NULL,protocolname,"protover",0)==0)
	{
		db_set_b(NULL,protocolname,"protover",0x84);
		db_set_w(NULL,protocolname,"avatarloadlatency",1000);
		db_set_b(NULL,protocolname,"gameico",0);
		db_set_b(NULL,protocolname,"voiceico",1);
		db_set_b(NULL,protocolname,"specialavatarload",1);
		db_set_b(NULL,protocolname,"xfiresitegameico",1);
		db_set_b(NULL,protocolname,"recprotoverchg",1);

		if(MessageBoxA(NULL,Translate("It seems that is the first time you use this plugin. Do you want to automatically download the latest available xfire_games.ini and icons.dll?\r\nWithout the ini xfire can't detect any games on your computer."),"Miranda XFire Protocol Plugin",MB_YESNO|MB_ICONQUESTION)==IDYES)
		{
			db_set_b(NULL,protocolname,"autoiniupdate",1);
			db_set_b(NULL,protocolname,"autoicodllupdate",1);
		}
	}


	XDEBUGS("-----------------------------------------------------\n");

	//statusmessages setzen
	strcpy(statusmessage[0],"");
	strcpy(statusmessage[1],"(AFK) Away from Keyboard");
	
	char servicefunction[100];
	
	HookEvent(ME_OPT_INITIALISE, OptInit);
	HookEvent(ME_SYSTEM_MODULESLOADED, OnSystemModulesLoaded);

	PROTOCOLDESCRIPTOR pd = { PROTOCOLDESCRIPTOR_V3_SIZE };
	pd.szName = protocolname;
	pd.type = PROTOTYPE_PROTOCOL;
	CallService(MS_PROTO_REGISTERMODULE,0,(LPARAM)&pd);


	hLogEvent=CreateHookableEvent("XFireProtocol/Log");

	CList_MakeAllOffline();
	
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_GETCAPS);
	CreateServiceFunction(servicefunction, GetCaps);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_GETNAME);
	CreateServiceFunction(servicefunction, GetName);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_LOADICON);
	CreateServiceFunction(servicefunction, TMLoadIcon);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_SETSTATUS);
	CreateServiceFunction(servicefunction, SetStatus);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_GETSTATUS);
	CreateServiceFunction(servicefunction, GetStatus);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PSS_ADDED);
	CreateServiceFunction(servicefunction, AddtoList);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_ADDTOLIST);
	CreateServiceFunction(servicefunction, SearchAddtoList);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_GETAVATARINFO);
	CreateServiceFunction(servicefunction, GetAvatarInfo);
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_GETMYAVATAR);
	CreateServiceFunction(servicefunction, GetMyAvatar);

	HookEvent(ME_CLIST_EXTRA_IMAGE_APPLY, ExtraImageApply);
	HookEvent(ME_CLIST_EXTRA_LIST_REBUILD, ExtraListRebuild);

	//erstell eine hook für andere plugins damit diese nachprüfen können, ab wann jemand ingame ist oer nicht
	hookgamestart = CreateHookableEvent(XFIRE_INGAMESTATUSHOOK);

	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PS_BASICSEARCH);
	CreateServiceFunction(servicefunction, BasicSearch);

	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PSS_MESSAGE);
	CreateServiceFunction( servicefunction, SendMessage );

	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PSS_USERISTYPING);
	CreateServiceFunction( servicefunction, UserIsTyping );

	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PSR_MESSAGE);
	CreateServiceFunction( servicefunction, RecvMessage );

	strcpy(servicefunction, XFIRE_URLCALL);
	CreateServiceFunction( servicefunction, UrlCall );

	strcpy(servicefunction, protocolname);
	strcat(servicefunction, PSS_GETAWAYMSG);
	CreateServiceFunction( servicefunction, GetAwayMsg );

	strcpy(servicefunction, XFIRE_SET_NICK);
	CreateServiceFunction( servicefunction, SetNickName );

	strcpy(servicefunction, XFIRE_SEND_PREFS);
	CreateServiceFunction( servicefunction, SendPrefs );

	//für mtipper, damit man das statusico übertragen kann
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "/GetXStatusIcon");
	CreateServiceFunction( servicefunction, GetXStatusIcon );

	char AvatarsFolder[MAX_PATH]= "";
	char CurProfileF[MAX_PATH] = "";
	char CurProfile[MAX_PATH] = "";
	CallService(MS_DB_GETPROFILEPATH, (WPARAM) MAX_PATH, (LPARAM)AvatarsFolder);
	strcat(AvatarsFolder, "\\");
	CallService(MS_DB_GETPROFILENAME, (WPARAM) MAX_PATH, (LPARAM)CurProfileF);

	int i;
	for (i = MAX_PATH; 5; i--){
		if (CurProfileF[i] == 't' && CurProfileF[i-3] == '.'){
			i = i-3;
			break;
		}
	}
	memcpy(CurProfile, CurProfileF, i);
	strcat(AvatarsFolder, CurProfile);
	strcat(AvatarsFolder, "\\");
	strcat(AvatarsFolder, "XFire");

	XFireWorkingFolder = FoldersRegisterCustomPath(protocolname, "Working Folder", AvatarsFolder);
	if ( !(XFireIconFolder = FoldersRegisterCustomPath(protocolname, "Game Icon Folder", AvatarsFolder)))
		CreateDirectory(AvatarsFolder, NULL);

	strcat(AvatarsFolder, "\\Avatars");
	if ( !(XFireAvatarFolder = FoldersRegisterCustomPath(protocolname, "Avatars", AvatarsFolder)))
		CreateDirectory(AvatarsFolder,NULL);

	//erweiterte Kontextmenüpunkte
	CLISTMENUITEM mi = { sizeof(mi) };
	mi.pszPopupName = protocolname;

	//gotoprofilemenüpunkt
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "GotoProfile");
	CreateServiceFunction(servicefunction,GotoProfile);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.pszContactOwner=protocolname;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.ptszName = LPGENT("&XFire Online Profile");
	Menu_AddContactMenuItem(&mi);

	//gotoxfireclansitemenüpunkt
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "GotoXFireClanSite");
	CreateServiceFunction(servicefunction,GotoXFireClanSite);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.pszContactOwner=protocolname;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.ptszName = LPGENT("XFire &Clan Site");
	gotoclansite=Menu_AddContactMenuItem(&mi);

	//kopiermenüpunkt
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "GetIPPort");
	CreateServiceFunction(servicefunction,GetIPPort);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("C&opy Server Address and Port");
	copyipport=Menu_AddContactMenuItem(&mi);

	//kopiermenüpunkt
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "VoiceIPPort");
	CreateServiceFunction(servicefunction,GetVIPPort);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("Cop&y Voice Server Address and Port");
	vipport=Menu_AddContactMenuItem(&mi);

	//joinmenüpunkt
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "JoinGame");
	CreateServiceFunction(servicefunction,JoinGame);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("Join &Game ...");
	joingame=Menu_AddContactMenuItem(&mi);

	//joinmenüpunkt
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "StartThisGame");
	CreateServiceFunction(servicefunction,StartThisGame);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("Play this Game ...");
	startthisgame=Menu_AddContactMenuItem(&mi);

	//remove friend
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "RemoveFriend");
	CreateServiceFunction(servicefunction,RemoveFriend);
	mi.pszService = servicefunction;
	mi.position = 2000070000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("Remove F&riend ...");
	removefriend=Menu_AddContactMenuItem(&mi);

	//block user
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "BlockFriend");
	CreateServiceFunction(servicefunction,BlockFriend);
	mi.pszService = servicefunction;
	mi.position = 2000070000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("Block U&ser ...");
	blockfriend=Menu_AddContactMenuItem(&mi);

	//my fire profile
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "GotoProfile2");
	CreateServiceFunction(servicefunction,GotoProfile2);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("&My XFire Online Profile");
	Menu_AddMainMenuItem(&mi);

	//my activity protocol
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "GotoProfileAct");
	CreateServiceFunction(servicefunction,GotoProfileAct);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("&Activity Report");
	Menu_AddMainMenuItem(&mi);

	//rescan my games
	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "ReScanMyGames");
	CreateServiceFunction(servicefunction,ReScanMyGames);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("&Rescan my Games ...");
	Menu_AddMainMenuItem(&mi);

	strcpy(servicefunction, protocolname);
	strcat(servicefunction, "SetNick");
	CreateServiceFunction(servicefunction,SetNickDlg);
	mi.pszService = servicefunction;
	mi.position = 500090000;
	mi.hIcon = LoadIcon(hinstance,MAKEINTRESOURCE(ID_OP));
	mi.pszContactOwner=protocolname;
	mi.ptszName = LPGENT("Set &Nickname");
	Menu_AddMainMenuItem(&mi);

	HookEvent( ME_CLIST_PREBUILDCONTACTMENU, RebuildContactMenu );

	//lade GetExtendedUdpTable Funktion
	HMODULE hmod=LoadLibraryA("IpHlpApi.dll");
	_GetExtendedUdpTable=(pGetExtendedUdpTable)GetProcAddress(hmod,"GetExtendedUdpTable");
	if(_GetExtendedUdpTable==NULL&&db_get_b(NULL,protocolname,"ipportdetec",0))
	{
		//MessageBoxA(0,"GetExtendedUdpTable not found. ServerIP/Port detection feature will be disabled.","Miranda XFire Protocol Plugin",MB_OK|MB_ICONINFORMATION);
		db_set_b(NULL,protocolname,"ipportdetec",0);
		XFireLog("Wasn't able to get GetExtendedUdpTable function");
	}

	Icon_Register(hinstance, LPGENT("Protocols/XFire"), &icon, 1);

	hExtraIcon1 = ExtraIcon_Register("xfire_game", LPGEN("XFire game icon"), "", ExtraListRebuild, ExtraImageApply);
	hExtraIcon2 = ExtraIcon_Register("xfire_voice", LPGEN("XFire voice icon"), "", ExtraListRebuild, ExtraImageApply);
	return 0;
}

//funktion liefert für xstatusid den passenden ico zurück, für tipper zb notwendig
INT_PTR GetXStatusIcon(WPARAM wParam, LPARAM lParam) {
	if(lParam == LR_SHARED)
	{
		if(wParam>1)
			return (int)xgamelist.iconmngr.getGameIconFromId(wParam-2); //icocache[(int)wParam-2].hicon;
	}
	else
	{
		if(wParam>1)
			return (int)CopyIcon((HICON)xgamelist.iconmngr.getGameIconFromId(wParam-2)/*icocache[(int)wParam-2].hicon*/);
	}

	return 0;
}

INT_PTR RecvMessage(WPARAM wParam, LPARAM lParam)
{
	CCSDATA *ccs = ( CCSDATA* )lParam;
    db_unset(ccs->hContact, "CList", "Hidden");

	char *szProto = GetContactProto(ccs->hContact);
	if ( szProto != NULL && !lstrcmpiA( szProto, protocolname ))
		return CallService( MS_PROTO_RECVMSG, wParam, lParam );

	return 1;
}

static void SetMeAFK( LPVOID param )
{
	if(bpStatus==ID_STATUS_ONLINE)
	{
		SetStatus(ID_STATUS_AWAY,(LPARAM)param);
	}
}

static void SetStatusLate( LPVOID param )
{
	Sleep(1000);
	if(bpStatus==ID_STATUS_OFFLINE)
	{
		SetStatus((WPARAM)param,0);
	}
}

static void SendAck( LPVOID param )
{
	ProtoBroadcastAck(protocolname, param, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, (HANDLE) 1, 0);
}

static void SendBadAck( LPVOID param )
{
	ProtoBroadcastAck(protocolname, param, ACKTYPE_MESSAGE, ACKRESULT_FAILED, (HANDLE) 0, LPARAM(Translate("XFire does not support offline messaging!")));
}

static INT_PTR UserIsTyping(WPARAM wParam, LPARAM lParam)
{
	HANDLE hContact = ( HANDLE )wParam;
    DBVARIANT dbv;

	if(lParam==PROTOTYPE_SELFTYPING_ON)
	{
		if(db_get_b(NULL,protocolname,"sendtyping",1)==1)
		{
			if(myClient!=NULL)
				if(myClient->client->connected)
					if(!db_get_s(hContact, protocolname, "Username",&dbv))
					{
						SendTypingPacket typing;
						typing.init(myClient->client, dbv.pszVal);
						myClient->client->send( &typing );
						db_free(&dbv);
					}
		}
	}
	else if(lParam==PROTOTYPE_SELFTYPING_OFF)
	{
	}

	return 0;
}

INT_PTR SendMessage(WPARAM wParam, LPARAM lParam)
{
    CCSDATA *ccs = (CCSDATA *) lParam;
	PROTORECVEVENT* pre = (PROTORECVEVENT*)ccs->lParam;
	ACKDATA * ack = (ACKDATA*) lParam;
    DBVARIANT dbv;
	int sended=0;

	db_get_s(ccs->hContact, protocolname, "Username",&dbv);
	if(myClient!=NULL)
		if(myClient->client->connected&&db_get_w(ccs->hContact, protocolname, "Status", -1)!=ID_STATUS_OFFLINE)
		{
			/*if(myClient->useutf8)
				myClient->sendmsg(dbv.pszVal, ( char* )ccs->lParam);
			else*/
				myClient->sendmsg(dbv.pszVal, mir_utf8encode(( char* )ccs->lParam));

			mir_forkthread(SendAck,ccs->hContact);
			sended=1;
		}
		else
		{
			mir_forkthread(SendBadAck,ccs->hContact);
		}
	db_free(&dbv);

    return sended;
}

//=======================================================
//GetCaps
//=======================================================

INT_PTR GetCaps(WPARAM wParam,LPARAM lParam)
{
	if(wParam==PFLAGNUM_1)
		return PF1_BASICSEARCH|PF1_MODEMSG|PF1_IM;
	else if(wParam==PFLAGNUM_2)
		return PF2_ONLINE|PF2_SHORTAWAY; // add the possible statuses here.
	else if(wParam==PFLAGNUM_3)
		return PF2_ONLINE|(db_get_b(NULL,protocolname,"nocustomaway",0)==1?0:PF2_SHORTAWAY);
	else if(wParam==PFLAGNUM_4)
		return PF4_SUPPORTTYPING|PF4_AVATARS;
	else if(wParam==PFLAG_UNIQUEIDTEXT)
		return (INT_PTR)Translate("Username");
	else if(wParam==PFLAG_UNIQUEIDSETTING)
		return (INT_PTR)"Username";
	else if(wParam==PFLAG_MAXLENOFMESSAGE)
		return 3996; //255;
	return 0;
}

//=======================================================
//GetName (tray icon)
//=======================================================
INT_PTR GetName(WPARAM wParam,LPARAM lParam)
{
	lstrcpyn((char*)lParam,"XFire",wParam);
	return 0;
}

//=======================================================
//TMLoadIcon
//=======================================================
INT_PTR TMLoadIcon(WPARAM wParam,LPARAM lParam)
{
	if(LOWORD( wParam ) == PLI_PROTOCOL) {
		if(wParam & PLIF_ICOLIB)
			return (int)Skin_GetIcon("XFIRE_main");
		return (int)CopyIcon( Skin_GetIcon("XFIRE_main"));
	}
	return NULL;
}


static void ConnectingThread(LPVOID params)
{
	WPARAM wParam=(WPARAM)params;

	EnterCriticalSection(&connectingMutex);

	if(myClient!=NULL&&myClient->client!=NULL)
		myClient->run();
	else
	{
		EnterCriticalSection(&connectingMutex);
		return;
	}

	if(myClient->client->connected)
	{
		sendonrecieve=TRUE;
	}
	else
	{
		if(db_get_w(NULL,protocolname,"noconnectfailedbox",0)==0) MSGBOXE(Translate("Unable to connect to XFire."));
		wParam =ID_STATUS_OFFLINE;
	}

	int oldStatus;
	oldStatus = bpStatus;
	bpStatus = wParam;

	ProtoBroadcastAck(protocolname,NULL,ACKTYPE_STATUS,ACKRESULT_SUCCESS,(HANDLE)oldStatus,wParam);

	LeaveCriticalSection(&connectingMutex);
}

//=======================================================
//SetStatus
//=======================================================
INT_PTR SetStatus(WPARAM wParam,LPARAM lParam)
{
	int oldStatus;

	oldStatus = bpStatus;

	if(bpStatus==ID_STATUS_CONNECTING)
		return 0;

	if(wParam!=ID_STATUS_ONLINE&&wParam!=ID_STATUS_OFFLINE&&wParam!=ID_STATUS_AWAY&&wParam!=ID_STATUS_RECONNECT)
		if(db_get_b(NULL,protocolname,"oninsteadafk",0)==0)
			wParam=ID_STATUS_AWAY; //protokoll auf away schalten
		else
			wParam=ID_STATUS_ONLINE; //protokoll auf online schalten

	if (
		(wParam == ID_STATUS_ONLINE && bpStatus!=ID_STATUS_ONLINE) || // offline --> online
		(wParam == ID_STATUS_AWAY && bpStatus==ID_STATUS_OFFLINE) // offline --> away
		)
	{
		if(bpStatus == ID_STATUS_AWAY) // away --> online
		{
			myClient->Status(statusmessage[0]);
		}
		else
		{
			// the status has been changed to online (maybe run some more code)
			DBVARIANT dbv;
			DBVARIANT dbv2;

			if(db_get(NULL,protocolname,"login",&dbv))
			{
				MSGBOXE(Translate("No Loginname is set!"));
				wParam=ID_STATUS_OFFLINE;
			}
			else if(db_get(NULL,protocolname,"password",&dbv2))
			{
				MSGBOXE(Translate("No Password is set!"));
				wParam=ID_STATUS_OFFLINE;
			}
			else
			{
				CallService(MS_DB_CRYPT_DECODESTRING,strlen(dbv2.pszVal)+1,(LPARAM)dbv2.pszVal);

				if(myClient!=NULL)
					delete myClient;

				//alter proxycode, entfernt da über netlib die proxysache geregelt wird
				/* if(db_get_b(NULL, protocolname, "useproxy" ,0))
				{
					//verbindung über proxy
					DBVARIANT dbv3;
					DBVARIANT dbv4;
					if(!db_get(NULL,protocolname,"proxyip",&dbv3))
					{
						if(!db_get(NULL,protocolname,"proxyport",&dbv4))
						{
							myClient = new XFireClient(dbv.pszVal,dbv2.pszVal,db_get_b(NULL,protocolname,"protover",0),1,dbv3.pszVal,atoi(dbv4.pszVal));
							db_free(&dbv4);
						}
						db_free(&dbv3);
					}
				}
				else */
					myClient = new XFireClient(dbv.pszVal,dbv2.pszVal,db_get_b(NULL,protocolname,"protover",0));

				//prüfe ob utf8 option aktiv, dann schlater auf true
				if(db_get_b(NULL,protocolname,"useutf8",0))
				{
					myClient->useutf8=TRUE;
				}


				//verbindung als thread
				bpStatus = ID_STATUS_CONNECTING;
				ProtoBroadcastAck(protocolname,NULL,ACKTYPE_STATUS,ACKRESULT_SUCCESS,(HANDLE)oldStatus,ID_STATUS_CONNECTING);

				mir_forkthread(ConnectingThread,(LPVOID)wParam);
				//alte verb
				/*
				myClient->run();

				if(myClient->client->connected)
				{
					sendonrecieve=TRUE;
				}
				else
				{
					MSGBOXE(Translate("Unable to connect to XFire."));
					wParam =ID_STATUS_OFFLINE;
				}
				*/
				//für die vars
				db_unset(NULL,protocolname,"currentgamename");
				db_unset(NULL,protocolname,"currentvoicename");
				db_unset(NULL,protocolname,"VServerIP");
				db_unset(NULL,protocolname,"ServerIP");

				db_free(&dbv);
				db_free(&dbv2);
				return 0;
			}
		}
	}
	else if (wParam == ID_STATUS_AWAY && bpStatus!=ID_STATUS_AWAY)
	{
		if(bpStatus == ID_STATUS_OFFLINE) // nix
		{
		}
		else if(myClient!=NULL&&myClient->client->connected) // online --> afk
		{
			//setze bei aktivem nocustomaway die alte awaystatusmsg zurück, bugfix
			if(db_get_b(NULL,protocolname,"nocustomaway",0))
				strcpy_s(statusmessage[1],1024,"(AFK) Away from Keyboard");

			myClient->Status(statusmessage[1]);
		}
	}
	else if ((wParam == ID_STATUS_OFFLINE || wParam == ID_STATUS_RECONNECT) && bpStatus!=ID_STATUS_OFFLINE) // * --> offline
	{
		SetEvent(hConnectionClose);

		// the status has been changed to offline (maybe run some more code)
		if(myClient!=NULL)
			if(myClient->client->connected)
				myClient->client->disconnect();
		CList_MakeAllOffline();

		//teamspeak/ventrilo pid sowie gamepid auf NULL setzen, damit bei einem reconnect die neuerkannt werden
		pid=NULL;
		ts2pid=NULL;
		db_set_w(NULL,protocolname,"currentgame",0);
		db_set_w(NULL,protocolname,"currentvoice",0);
		db_unset(NULL,protocolname, "VServerIP");
		db_unset(NULL,protocolname, "ServerIP");

		if(wParam == ID_STATUS_RECONNECT)
		{
			mir_forkthread(SetStatusLate,(LPVOID)oldStatus);
			wParam = ID_STATUS_OFFLINE;
		}
	}
	else
	{
		// the status has been changed to unknown  (maybe run some more code)
	}
	//broadcast the message
	bpStatus = wParam;
	ProtoBroadcastAck(protocolname,NULL,ACKTYPE_STATUS,ACKRESULT_SUCCESS,(HANDLE)oldStatus,wParam);


	return 0;
}

//=======================================================
//GetStatus
//=======================================================
INT_PTR GetStatus(WPARAM wParam,LPARAM lParam)
{
	if (bpStatus == ID_STATUS_ONLINE)
		return ID_STATUS_ONLINE;
	else if (bpStatus == ID_STATUS_AWAY)
		return ID_STATUS_AWAY;
	else if (bpStatus == ID_STATUS_CONNECTING)
		return ID_STATUS_CONNECTING;
	else
		return ID_STATUS_OFFLINE;
}

HANDLE CList_AddContact(XFireContact xfc, bool InList, bool SetOnline,int clan)
{
	HANDLE hContact;

	if (xfc.username == NULL)
		return 0;

	// here we create a new one since no one is to be found
	hContact = (HANDLE) CallService( MS_DB_CONTACT_ADD, 0, 0);
	if ( hContact ) {
		CallService( MS_PROTO_ADDTOCONTACT, (WPARAM) hContact, (LPARAM)protocolname );

		if ( InList )
			db_unset(hContact, "CList", "NotOnList");
		else
			db_set_b(hContact, "CList", "NotOnList", 1);
		db_unset(hContact, "CList", "Hidden");

		if(strlen(xfc.nick)>0)
		{
			if(myClient->useutf8)
				db_set_utf(hContact, protocolname, "Nick", xfc.nick);
			else
				db_set_s(hContact, protocolname, "Nick", mir_utf8decode(( char* )xfc.nick,NULL));
		}
		else if(strlen(xfc.username)>0)
			db_set_s(hContact, protocolname, "Nick", xfc.username);

		db_set_s(hContact, protocolname, "Username", xfc.username);

		//db_set_s(hContact, protocolname, "Screenname", xfc.nick);
		db_set_dw(hContact, protocolname, "UserId", xfc.id);

		if(clan>0)
			db_set_dw(hContact, protocolname, "Clan", clan);

		db_set_w(hContact, protocolname, "Status", SetOnline ? ID_STATUS_ONLINE:ID_STATUS_OFFLINE);

		if(db_get_b(NULL,protocolname,"noavatars",-1)==0)
		{
			if(!db_get_b(NULL,protocolname,"specialavatarload",0))
			{
				XFire_SetAvatar* xsa=new XFire_SetAvatar;
				xsa->hContact=hContact;
				xsa->username=new char[strlen(xfc.username)+1];
				strcpy(xsa->username,xfc.username);
				mir_forkthread(SetAvatar,(LPVOID)xsa);
			}
			else
			{
				/*
				   scheinbar unterpricht xfire bei zu agressiven nachfragen der buddyinfos die verbindung , deshalb erstmal auskommentiert
				   getestet mit clanbuddy's >270 members

				   mit hilfe der buddyinfos kann man den avatar laden und screenshot infos etc bekommt man auch
				*/
				GetBuddyInfo* buddyinfo=new GetBuddyInfo();
				buddyinfo->userid=xfc.id;
				mir_forkthread(SetAvatar2,(LPVOID)buddyinfo);
			}


		}

		if (xfc.id==0) {
			db_set_b( hContact, "CList", "NotOnList", 1 );
			db_set_b( hContact, "CList", "Hidden", 1 );
		}

		return hContact;
	}
	return false;
}

BOOL IsXFireContact(HANDLE hContact)
{
	char *szProto = GetContactProto(hContact);
	if (szProto != NULL && !lstrcmpiA(szProto, protocolname))
		return TRUE;

	return FALSE;
}

HANDLE CList_FindContact (int uid)
{
	for (HANDLE hContact = db_find_first(); hContact; hContact = db_find_next(hContact)) {
		char *szProto = GetContactProto(hContact);
		if ( szProto != NULL && !lstrcmpiA( szProto, protocolname )) {
			if ( db_get_dw(hContact, protocolname, "UserId",-1)==uid)
				return hContact;
		}
	}
	return 0;
}

void CList_MakeAllOffline()
{
	vector<HANDLE> fhandles;
	for (HANDLE hContact = db_find_first(); hContact; hContact = db_find_next(hContact)) {
		char *szProto = GetContactProto(hContact);
		if ( szProto != NULL && !lstrcmpiA( szProto, protocolname )) {
			//freunde von freunden in eine seperate liste setzen
			//nur wenn das nicht abgestellt wurde
			if(db_get_b(hContact,protocolname,"friendoffriend",0)==1&&
				db_get_b(NULL,protocolname,"fofdbremove",0)==1)
			{
				fhandles.push_back(hContact);
			}

			db_unset(hContact, "CList", "StatusMsg");
			db_unset(hContact, protocolname, "ServerIP");
			db_unset(hContact, protocolname, "Port");
			db_unset(hContact, protocolname, "ServerName");
			db_unset(hContact, protocolname, "GameType");
			db_unset(hContact, protocolname, "Map");
			db_unset(hContact, protocolname, "Players");
			db_unset(hContact, protocolname, "Passworded");

			db_unset(hContact, protocolname, "XStatusMsg");
			db_unset(hContact, protocolname, "XStatusId");
			db_unset(hContact, protocolname, "XStatusName");

			if(db_get_b(NULL,protocolname,"noavatars",-1)==1)
			{
				db_unset(hContact, "ContactPhoto", "File");
				db_unset(hContact, "ContactPhoto", "RFile");
				db_unset(hContact, "ContactPhoto", "Backup");
				db_unset(hContact, "ContactPhoto", "Format");
				db_unset(hContact, "ContactPhoto", "ImageHash");
				db_unset(hContact, "ContactPhoto", "XFireAvatarId");
				db_unset(hContact, "ContactPhoto", "XFireAvatarMode");
			}
			else
			{
				//prüf ob der avatar noch existiert
				DBVARIANT dbv;
				if(!db_get_s(hContact, "ContactPhoto", "File",&dbv))
				{
					FILE*f=fopen(dbv.pszVal,"r");
					if(f==NULL)
					{
						db_unset(hContact, "ContactPhoto", "File");
						db_unset(hContact, "ContactPhoto", "RFile");
						db_unset(hContact, "ContactPhoto", "Backup");
						db_unset(hContact, "ContactPhoto", "Format");
						db_unset(hContact, "ContactPhoto", "ImageHash");
						db_unset(hContact, "ContactPhoto", "XFireAvatarId");
						db_unset(hContact, "ContactPhoto", "XFireAvatarMode");
					}
					else
					{
						fclose(f);
					}
					db_free(&dbv);
				}
			}
			db_set_w(hContact,protocolname,"Status",ID_STATUS_OFFLINE);
		}
	}

	//alle gefundenen handles lsöchen
	for(uint i=0;i<fhandles.size();i++)
		CallService( MS_DB_CONTACT_DELETE, (WPARAM) fhandles.at(i), 0);
}

void SetIcon(HANDLE hcontact,HANDLE hicon,int ctype)
{
	ExtraIcon_SetIcon((ctype == 1) ? hExtraIcon1 : hExtraIcon2, hcontact, hicon);
}

void SetAvatar2(LPVOID lparam) {
	static int lasttime=0;
	int sleep=db_get_w(NULL,protocolname,"avatarloadlatency",1000);
	lasttime+=sleep;

	if(mySleep(lasttime,hConnectionClose))
	{
		delete lparam;
		lasttime-=sleep;
		return;
	}

	GetBuddyInfo* buddyinfo=(GetBuddyInfo*)lparam;
	if(myClient!=NULL)
		if(myClient->client->connected)
				myClient->client->send( buddyinfo );

	delete lparam;
	lasttime-=sleep;
}

void SetAvatar(LPVOID lparam)
//void SetAvatar(HANDLE hContact, char* username)
{
	//EnterCriticalSection(&avatarMutex);
	//WaitForSingleObject(hMutex, INFINITE);
	static int lasttime=0;
	int sleep=db_get_w(NULL,protocolname,"avatarloadlatency",250);

	if(bpStatus==ID_STATUS_OFFLINE)
		return;

	lasttime+=sleep;
	//Sleep(lasttime);
	if(mySleep(lasttime,hConnectionClose))
	{
		delete lparam;
		lasttime-=sleep;
		return;
	}

	if(bpStatus==ID_STATUS_OFFLINE)
		return;

	XFireAvatar av;

	XFire_SetAvatar* xsa=(XFire_SetAvatar*)lparam;

	if(xsa->hContact==NULL)
		return;

		if(GetAvatar(xsa->username,&av))
		{
			PROTO_AVATAR_INFORMATION AI;
			AI.cbSize = sizeof(AI);
			AI.format = av.type;
			AI.hContact = xsa->hContact;
			lstrcpy(AI.filename,av.file);
			ProtoBroadcastAck(protocolname, xsa->hContact, ACKTYPE_AVATAR, ACKRESULT_SUCCESS,(HANDLE) &AI, 0);
		}

	delete(xsa);
	//ReleaseMutex(hMutex);

	lasttime-=sleep;
}

BOOL GetAvatar(char* username,XFireAvatar* av)
{
	BOOL status=FALSE;

	if(av==NULL||username==NULL)
		return FALSE;

	char address[256]="http://www.xfire.com/profile/";
	strcat_s(address,256,username);
	strcat_s(address,256,"/");

	//netlib request
	NETLIBHTTPREQUEST nlhr={0},*nlhrReply;
	nlhr.cbSize		= sizeof(nlhr);
	nlhr.requestType= REQUEST_GET;
	nlhr.flags		= NLHRF_NODUMP|NLHRF_GENERATEHOST|NLHRF_SMARTAUTHHEADER;
	nlhr.szUrl		= address;

	nlhrReply=(NETLIBHTTPREQUEST*)CallService(MS_NETLIB_HTTPTRANSACTION,(WPARAM)hNetlib,(LPARAM)&nlhr);

	if(nlhrReply) {
		//nicht auf dem server
		if (nlhrReply->resultCode != 200) {
			CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0,(LPARAM)nlhrReply);
			return FALSE;
		}
		//keine daten für mich
		else if (nlhrReply->dataLength < 1 || nlhrReply->pData == NULL)
		{
			CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0,(LPARAM)nlhrReply);
			return FALSE;
		}
		else
		{
			//fwrite(nlhrReply->pData,nlhrReply->dataLength,1,f);

			//id wo angefangen wird, die adresse "rauszuschneiden"
			char avatarid[]="m_user_avatar_img_wrapper";
			char* pointer_av=avatarid;
			//ende des datenbuffers
			char* deathend=nlhrReply->pData+nlhrReply->dataLength;
			char* pointer=nlhrReply->pData;
			//status ob gefunden oder nich
			BOOL found=FALSE;

			while(pointer<deathend&&*pointer_av!=0)
			{
				if(*pointer_av==*pointer)
				{
					pointer_av++;
					if(pointer_av-avatarid>4)
						found=TRUE;
				}
				else
					pointer_av=avatarid;

				pointer++;
			}
			//was gefunden, nun das bild raustrennen
			if(*pointer_av==0)
			{
				char * pos = NULL;
				pos=strchr(pointer,'/');
				pos-=5;
				pointer=pos;

				pos=strchr(pointer,' ');
				if(pos)
				{
					pos--;
					*pos=0;

					//analysieren, welchent typ das bild hat
					pos=strrchr(pointer,'.');
					if(pos)
					{
						char filename[512];
						strcpy(filename, XFireGetFoldersPath ("Avatar"));
						strcat(filename, username);

						pos++;
						//gif?!?!
						if(*pos=='g'&&
							*(pos+1)=='i'&&
							*(pos+2)=='f')
						{
							av->type=PA_FORMAT_GIF;
							strcat(filename,".gif");
						}
						else//dann kanns nur jpg sein
						{
							av->type=PA_FORMAT_JPEG;
							strcat(filename,".jpg");
						}

						//verusch das bild runterladen
						if(GetWWWContent2(pointer,filename,FALSE))
						{
							strcpy_s(av->file,256,filename); //setzte dateinamen
							status=TRUE; //avatarladen hat geklappt, cool :)
						}
					}
				}
			}
		}
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0,(LPARAM)nlhrReply);
	}

	return status;
}

static INT_PTR GetIPPort(WPARAM wParam,LPARAM lParam)
{
	char temp[XFIRE_MAX_STATIC_STRING_LEN];
    HGLOBAL clipbuffer;
	char* buffer;

	if(db_get_w((HANDLE)wParam, protocolname, "Port", -1)==0)
		return 0;

	DBVARIANT dbv;
	if(db_get_s((HANDLE)wParam, protocolname, "ServerIP",&dbv))
		return 0;

	sprintf(temp,"%s:%d",dbv.pszVal,db_get_w((HANDLE)wParam, protocolname, "Port", -1));

	db_free(&dbv);

	if(OpenClipboard(NULL))
	{
		EmptyClipboard();

		clipbuffer = GlobalAlloc(GMEM_DDESHARE, strlen(temp)+1);
		buffer = (char*)GlobalLock(clipbuffer);
		strcpy(buffer, LPCSTR(temp));
		GlobalUnlock(clipbuffer);

		SetClipboardData(CF_TEXT, clipbuffer);
		CloseClipboard();
	}

	return 0;
}

static INT_PTR GetVIPPort(WPARAM wParam,LPARAM lParam)
{
	char temp[XFIRE_MAX_STATIC_STRING_LEN];
    HGLOBAL clipbuffer;
	char* buffer;

	if(db_get_w((HANDLE)wParam, protocolname, "VPort", -1)==0)
		return 0;

	DBVARIANT dbv;
	if(db_get_s((HANDLE)wParam, protocolname, "VServerIP",&dbv))
		return 0;

	sprintf(temp,"%s:%d",dbv.pszVal,db_get_w((HANDLE)wParam, protocolname, "VPort", -1));

	db_free(&dbv);

	if(OpenClipboard(NULL))
	{
		EmptyClipboard();

		clipbuffer = GlobalAlloc(GMEM_DDESHARE, strlen(temp)+1);
		buffer = (char*)GlobalLock(clipbuffer);
		strcpy(buffer, LPCSTR(temp));
		GlobalUnlock(clipbuffer);

		SetClipboardData(CF_TEXT, clipbuffer);
		CloseClipboard();
	}

	return 0;
}

static INT_PTR GotoProfile(WPARAM wParam,LPARAM lParam)
{
	DBVARIANT dbv;
	char temp[64]="";

	if(db_get_s((HANDLE)wParam, protocolname, "Username",&dbv))
		return 0;

	strcpy(temp,"http://xfire.com/profile/");
	strcat_s(temp,64,dbv.pszVal);
	db_free(&dbv);

	CallService( MS_UTILS_OPENURL, 1, (LPARAM)temp );

	return 0;
}

static INT_PTR GotoXFireClanSite(WPARAM wParam,LPARAM lParam) {
	DBVARIANT dbv;
	char temp[64]="";

	int clanid=db_get_dw((HANDLE)wParam, protocolname, "Clan",-1);
	sprintf(temp,"ClanUrl_%d",clanid);

	if(db_get_s(NULL, protocolname, temp,&dbv))
		return 0;

	strcpy(temp,"http://xfire.com/clans/");
	strcat_s(temp,64,dbv.pszVal);
	db_free(&dbv);

	CallService( MS_UTILS_OPENURL, 1, (LPARAM)temp );

	return 0;
}

static INT_PTR GotoProfile2(WPARAM wParam,LPARAM lParam)
{
	DBVARIANT dbv;
	char temp[64]="";

	if(db_get_s(NULL, protocolname, "login",&dbv))
		return 0;

	strcpy(temp,"http://xfire.com/profile/");
	strcat_s(temp,64,dbv.pszVal);
	db_free(&dbv);

	CallService( MS_UTILS_OPENURL, 1, (LPARAM)temp );

						//prefrences pakcet senden
					//XFirePrefPacket *packet2 = new XFirePrefPacket();
					//myClient->client->send( packet2 );
					//delete(packet2);

	return 0;
}

static INT_PTR GotoProfileAct(WPARAM wParam,LPARAM lParam)
{
	DBVARIANT dbv;
	char temp[64]="";

	if(db_get_s(NULL, protocolname, "login",&dbv))
		return 0;

	strcpy(temp,"http://www.xfire.com/?username=");
	strcat_s(temp,64,dbv.pszVal);
	db_free(&dbv);

	CallService( MS_UTILS_OPENURL, 1, (LPARAM)temp );

						//prefrences pakcet senden
					//XFirePrefPacket *packet2 = new XFirePrefPacket();
					//myClient->client->send( packet2 );
					//delete(packet2);

	return 0;
}

int RebuildContactMenu( WPARAM wParam, LPARAM lParam )
{
	HANDLE hContact = (HANDLE)wParam;
	bool bEnabled = true, bEnabled2 = true;

	DBVARIANT dbv;
	if (db_get_s(hContact, protocolname, "ServerIP", &dbv))
		bEnabled = false;
	else
		db_free(&dbv);
	Menu_ShowItem(copyipport, bEnabled);

	//kopieren von voice port und ip nur erlauben, wenn verfügbar
	bEnabled = true;
	if(db_get_s(hContact, protocolname, "VServerIP", &dbv))
		bEnabled = false;
	else
		db_free(&dbv);
	Menu_ShowItem(vipport, bEnabled);

	//clansite nur bei clanmembern anbieten
	Menu_ShowItem(gotoclansite, db_get_dw(hContact, protocolname, "Clan",0) != 0);

	//NotOnList
	Menu_ShowItem(blockfriend, db_get_dw(hContact, "CList", "NotOnList",0) != 0);

	//speichere gameid ab
	int gameid = db_get_w(hContact, protocolname, "GameId",0);
	//spiel in xfirespieliste?
	bEnabled = bEnabled2 = true;
	if(!xgamelist.Gameinlist(gameid)) {
		//nein, dann start und join auf unsichbar schalten
		bEnabled = bEnabled2 = false;
	}
	else {
		//gameobject holen
		Xfire_game* game=xgamelist.getGamebyGameid(gameid);
		//hat das spiel netzwerkparameter?
		if(game) {
			if(game->networkparams) {
				//is beim buddy ein port hinterlegt, also spielt er im internet?
				if( !db_get_dw(hContact, protocolname, "Port",0)) {
					//nein, dann join button auch ausblenden
					bEnabled = false;
				}
			}
			else bEnabled = false;
		}
		else bEnabled = false;
	}

	Menu_ShowItem(joingame, bEnabled);
	Menu_ShowItem(startthisgame, bEnabled2);

	//remove freind nur bei noramlen buddies
	Menu_ShowItem(removefriend, db_get_b(hContact, protocolname, "friendoffriend",0) != 1);
	return 0;
}

//wird beim miranda start ausgeführt, lädt spiele und startet gamedetection
#ifndef NO_PTHREAD
void *inigamedetectiont(void *ptr)
#else
void inigamedetectiont(LPVOID lParam)
#endif
{
	Scan4Games(NULL);
#ifndef NO_PTHREAD
	return gamedetectiont(ptr);
#else
	gamedetectiont(NULL);
#endif

}

void SetXFireGameStatusMsg(Xfire_game* game)
{
	char inipath[XFIRE_MAX_STATIC_STRING_LEN]="";
	static char statusmsg[100]="";

	//kein gameobject, dann abbrechen
	if(!game) return;

	if(!game->statusmsg)
	{
		xgamelist.getIniValue(game->id,"XUSERStatusMsg",statusmsg,100);
	}
	else
	{
		strcpy_s(statusmsg,100,game->statusmsg);
	}

	if(statusmsg[0]!=0)
		if(myClient!=NULL)
			if(myClient->client->connected)
				myClient->Status(statusmsg);

}

#ifndef NO_PTHREAD
void *gamedetectiont(void *ptr)
#else
void gamedetectiont(LPVOID lparam)
#endif
{
	DWORD ec; //exitcode der processid
	int ts2port=0;
	int vid=0;
	char ts2ip[4]={0,0,0,0};
	char temp[200];
	Xfire_game* currentgame=NULL;
	BOOL disabledsound=FALSE;
	BOOL disabledpopups=FALSE;

	//vaiable zum spielzeit messen
	time_t t1;


	if(db_get_b(NULL,protocolname,"nogamedetect",0))
#ifndef NO_PTHREAD
		return ptr;
#else
		return;
#endif

	DWORD lowpids=db_get_b(NULL,protocolname,"skiplowpid",100);

	//XFireLog("XFire Gamedetectionthread started ...","");

	while(1)
	{
		//Sleep(12000);
		//XFireLog("12 Sek warten ...","");
		if(mySleep(12000,hGameDetection))
		{
#ifndef NO_PTHREAD
			return ptr;
#else
			return;
#endif
		}

#ifndef NO_PTHREAD
		pthread_testcancel();
#else
		if(Miranda_Terminated())
			return;
#endif

		if(myClient!=NULL)
			if(!myClient->client->connected)
			{
				//XFireLog("PID und TSPID resett ...","");
				ts2pid=pid=0;
				//voicechat internen status zurücksetzen
				voicechat.resetCurrentvoicestatus();
			}
			/*
			else*/
			{
				//erstmal nach TS2 suchen
				//XFireLog("Teamspeak detection ...","");
				if(db_get_b(NULL,protocolname,"ts2detection",0))
				{
					SendGameStatus2Packet *packet = new SendGameStatus2Packet();
					if(voicechat.checkVoicechat(packet)) {
						if(myClient!=NULL)
						{
							XFireLog("Send voicechat infos ...");
							myClient->client->send( packet );
						}
					}
					delete packet;

					//nach ts3 mapfile suchen
					//HANDLE hMapObject = OpenFileMappingA(FILE_MAP_READ, FALSE, "$ts3info4xfire$");
					//if (hMapObject) {
					//}
					//wenn remote feature aktiviert, darüber ip erkennen
					/*if(db_get_b(NULL,protocolname,"ts2useremote",0))
					{
						//ipholen
						SendGameStatus2Packet *packet = new SendGameStatus2Packet();
						if(TSSetupPacket(packet,&ts2pid,&ts2port))
						{
							db_set_w(NULL,protocolname,"currentvoice",packet->gameid);

							if(packet->ip[3]!=0)
							{
								sprintf(temp,"%d.%d.%d.%d:%d",(unsigned char)packet->ip[3],(unsigned char)packet->ip[2],(unsigned char)packet->ip[1],(unsigned char)packet->ip[0],packet->port);
								db_set_s(NULL, protocolname, "VServerIP", temp);
								db_set_s(NULL, protocolname, "currentvoicename", "Teamspeak");
							}
							else
							{
								db_unset(NULL,protocolname, "VServerIP");
								db_unset(NULL,protocolname, "currentvoicename");
							}

							if(myClient!=NULL)
								myClient->client->send( packet );
						}
						delete packet;

					}
					else
					{
						if(!ts2pid)
						{
							if(FindTeamSpeak(&ts2pid,&vid))
							{
								//gefunden, serverdaten scannen
								SendGameStatus2Packet *packet = new SendGameStatus2Packet();
								if(myClient!=NULL)
									if(GetServerIPPort2(ts2pid,myClient->client->localaddr,myClient->client->llocaladdr,&packet->ip[3],&packet->ip[2],&packet->ip[1],&packet->ip[0],&packet->port))
									{
										if(packet->port!=0)
										{
											packet->gameid=vid;

											if(vid==32)
												db_set_s(NULL, protocolname, "currentvoicename", "Teamspeak");
											else if(vid==33)
												db_set_s(NULL, protocolname, "currentvoicename", "Ventrilo");
											else if(vid==34)
												db_set_s(NULL, protocolname, "currentvoicename", "Mumble");

											db_set_w(NULL,protocolname,"currentvoice",vid);

											sprintf(temp,"%d.%d.%d.%d:%d",(unsigned char)packet->ip[3],(unsigned char)packet->ip[2],(unsigned char)packet->ip[1],(unsigned char)packet->ip[0],packet->port);
											db_set_s(NULL, protocolname, "VServerIP", temp);

											if(myClient!=NULL)
												myClient->client->send( packet );
										}
									}
								delete packet;
							}
						}
						else
						{
							//HANDLE op=OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, ts2pid);
							//if(op!=NULL) GetExitCodeProcess(op,&ec);

							//if(ec!=STILL_ACTIVE) //nicht mehr offen
							if (GetProcessVersion(ts2pid) == 0)
							{
								SendGameStatus2Packet *packet = new SendGameStatus2Packet();
								packet->gameid=0;
								db_set_w(NULL,protocolname,"currentvoice",0);
								db_unset(NULL,protocolname, "VServerIP");
								db_unset(NULL,protocolname, "currentvoicename");

								if(myClient!=NULL)
									myClient->client->send( packet );
								ts2pid=0;
								delete packet;
							}
							else
							{
								SendGameStatus2Packet *packet = new SendGameStatus2Packet();
								if(myClient!=NULL)
									if(GetServerIPPort2(ts2pid,myClient->client->localaddr,myClient->client->llocaladdr,&packet->ip[3],&packet->ip[2],&packet->ip[1],&packet->ip[0],&packet->port))
									{
										if(packet->port!=0)
										{
											packet->gameid=vid;
											db_set_w(NULL,protocolname,"currentvoice",vid);

											sprintf(temp,"%d.%d.%d.%d:%d",(unsigned char)packet->ip[3],(unsigned char)packet->ip[2],(unsigned char)packet->ip[1],(unsigned char)packet->ip[0],packet->port);
											db_set_s(NULL, protocolname, "VServerIP", temp);

											if(myClient!=NULL)
												myClient->client->send( packet );
										}
									}
								delete packet;
							}
							//if(op!=NULL) CloseHandle(op);
						}
					}*/
				}

				if(currentgame!=NULL)
				{

					//XFireLog("XFire Gamedetection - Game still running ...","");

					//prüf ob das spiel noch offen
					ec=0;
					//HANDLE op=OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
					//if(op!=NULL) GetExitCodeProcess(op,&ec);

					//if(GetLastError()==5) //anwendung ist noch offen und der zugriff wird noch darauf blockiert
					//{
						//
					//}
					//else if(ec!=STILL_ACTIVE) //nicht mehr offen

					if (!xgamelist.isValidPid(pid))
					{
						//XFireLog("XFire Gamedetection - Game was closed ID: %i",currentgame);
						SendGameStatusPacket *packet = new SendGameStatusPacket();
						packet->gameid=0;
						if(db_get_b(NULL,protocolname,"sendgamestatus",1))
							if(myClient!=NULL)
								myClient->client->send( packet );

						//spielzeit messen
						time_t t2=time(NULL);
						time_t t3=t2-t1;
						tm * mytm=gmtime(&t3);

						//statusmsg von xfire zurücksetzen
						if(currentgame->setstatusmsg)
						{
							if(myClient!=NULL)
								if(myClient->client->connected)
									if(bpStatus==ID_STATUS_ONLINE)
										myClient->Status(statusmessage[0]);
									else if(bpStatus==ID_STATUS_AWAY)
										myClient->Status(statusmessage[1]);
						}

						sprintf(temp,Translate("Last game: %s playtime: %.2d:%.2d:%.2d"),currentgame->name,mytm->tm_hour,mytm->tm_min,mytm->tm_sec);
						db_set_s(NULL, protocolname, "LastGame", temp);

						if(currentgame->noicqstatus!=TRUE&&db_get_b(NULL,protocolname,"autosetstatusmsg",0))
							SetOldStatusMsg();

						db_set_w(NULL,protocolname,"currentgame",0);
						db_unset(NULL,protocolname,"currentgamename");

						//popup wieder aktivieren, menuservice funk aufrufen, nur wenn popups vorher abgestellt wurden
						if(disabledpopups)
							if(db_get_b(NULL,protocolname,"nopopups",0))
							{
								if(ServiceExists("PopUp/EnableDisableMenuCommand"))
								{
									CallService("PopUp/EnableDisableMenuCommand",NULL,NULL);
								}
								else if(ServiceExists("PopUp/ToggleEnabled"))
								{
									CallService("PopUp/ToggleEnabled",NULL,NULL);
								}
								disabledpopups=FALSE;
							}
						//sound wieder aktivieren, nur wenn es vorher abgestellt wurde
						if(disabledsound)
							if(db_get_b(NULL,protocolname,"nosoundev",0))
							{
								db_set_b(NULL,"Skin","UseSound",1);
								disabledsound=FALSE;
							}

						//bug beseitigt, wenn spiel beendet, alte ip entfernen
						db_unset(NULL,protocolname, "ServerIP");

						pid=NULL;
						currentgame=NULL;
						xgamelist.SetGameStatus(FALSE);

						NotifyEventHooks(hookgamestart,0,0);

						delete packet;
					}
					else //noch offen
					{
						//XFireLog("Spiel noch offen ...","");
						//nur nwspiele nach ip/port scannen
						if(db_get_b(NULL,protocolname,"ipportdetec",0))
							if(currentgame->networkparams!=NULL&&currentgame->send_gameid>0)
							{
								SendGameStatusPacket *packet = new SendGameStatusPacket();
								//verscueh serverip und port zu scannen

								XFireLog("IPPort detection ...","");
								if(GetServerIPPort(pid,myClient->client->localaddr,myClient->client->llocaladdr,&packet->ip[3],&packet->ip[2],&packet->ip[1],&packet->ip[0],&packet->port))
								{

									if(packet->ip[3]!=0)
									{
										sprintf(temp,"%d.%d.%d.%d:%d",(unsigned char)packet->ip[3],(unsigned char)packet->ip[2],(unsigned char)packet->ip[1],(unsigned char)packet->ip[0],packet->port);
										db_set_s(NULL, protocolname, "ServerIP", temp);
										XFireLog("Got IPPort: %s",temp);
									}
									else {
										db_unset(NULL,protocolname, "ServerIP");
										XFireLog("NO IPPort","");
									}

									packet->gameid=currentgame->send_gameid;
									if(db_get_b(NULL,protocolname,"sendgamestatus",1))
										if(myClient!=NULL)
											myClient->client->send( packet );

									if(currentgame->noicqstatus!=TRUE&&db_get_b(NULL,protocolname,"autosetstatusmsg",0))
										SetGameStatusMsg();
								} else {
									XFireLog("GetServerIPPort failed","");
								}
								delete packet;
							}
						//XFireLog("fertig ...","");
						//packet->=xf[currentgame].gameid2;
					}

					//if(op!=NULL) CloseHandle(op);
				}
				else
				{
					//XFireLog("nach spiel suchen ...","");
					//hardcoded game detection
					HANDLE hSnapShot = CreateToolhelp32Snapshot ( TH32CS_SNAPALL, 0);
					PROCESSENTRY32* processInfo = new PROCESSENTRY32;
					processInfo->dwSize = sizeof ( PROCESSENTRY32);

					XFireLog("XFire Gamedetection - Suche laufende Spiele ...");

					//gamelist blocken
					xgamelist.Block(TRUE);


					while ( Process32Next ( hSnapShot,processInfo ) != FALSE && currentgame==NULL)
					{
						//überspringe niedrige pids
						if(processInfo->th32ProcessID<lowpids)
							continue;

						Xfire_game* nextgame;
						while(xgamelist.getnextGame(&nextgame))
						{
							if(nextgame->checkpath(processInfo))
							{
								SendGameStatusPacket *packet = new SendGameStatusPacket() ;

								XFireLog("XFire Gamedetection - Spiel gefunden: %i",nextgame->id);

								if(myClient!=NULL)
									if(myClient->client->connected)
									{
										currentgame=nextgame;
										pid=processInfo->th32ProcessID;
										db_set_w(NULL,protocolname,"currentgame",currentgame->id);
										db_set_s(NULL,protocolname,"currentgamename",currentgame->name);
										packet->gameid=currentgame->send_gameid;
										t1=time(NULL);

										if(db_get_b(NULL,protocolname,"sendgamestatus",1))
										{
											XFireLog("XFire Gamedetection - Sendgame-ID: %i",currentgame->send_gameid);
											if(currentgame->send_gameid>0)
											{
												XFireLog("XFire Gamedetection - Setzte Status für XFire");
												myClient->client->send( packet );
											}
										}

										xgamelist.SetGameStatus(TRUE);

										//eventhook triggern
										NotifyEventHooks(hookgamestart,1,0);

										//statusmsg für xfire setzen
										if(currentgame->setstatusmsg)
										{
											SetXFireGameStatusMsg(currentgame);
										}

										if(currentgame->noicqstatus!=TRUE&&db_get_b(NULL,protocolname,"autosetstatusmsg",0))
										{
											BackupStatusMsg();
											SetGameStatusMsg();
										}
										//popup abschalten, menuservice funk aufrufen
										if(db_get_b(NULL,protocolname,"nopopups",0))
										{
											if(ServiceExists("PopUp/EnableDisableMenuCommand")&&db_get_b(NULL,"PopUp","ModuleIsEnabled",0)==1) /**/
											{
												disabledpopups=TRUE;
												CallService("PopUp/EnableDisableMenuCommand",NULL,NULL);
											}
											else if(ServiceExists("PopUp/ToggleEnabled")&&db_get_b(NULL,"YAPP","Enabled",0)==1)
											{
												disabledpopups=TRUE;
												CallService("PopUp/ToggleEnabled",NULL,NULL);
											}
										}
										//sound abschalten
										if(db_get_b(NULL,protocolname,"nosoundev",0)&&db_get_b(NULL,"Skin","UseSound",0)==1)
										{
											db_set_b(NULL,"Skin","UseSound",0);
											disabledsound=TRUE;
										}
									}

								delete packet;

								break;
							}
						}
					}
					CloseHandle ( hSnapShot);

					//gamelist unblocken
					xgamelist.Block(FALSE);
				}
			}
	}
}

static INT_PTR ReScanMyGames(WPARAM wParam,LPARAM lParam)
{
	db_unset(NULL, protocolname, "foundgames");

	mir_forkthread(Scan4Games,NULL);

	return 0;
}

static INT_PTR CustomGameSetup(WPARAM wParam,LPARAM lParam)
{
	//DialogBox(hinstance,MAKEINTRESOURCE(IDD_GAMELIST),NULL,DlgAddGameProc);
	return 0;
}

void setBuddyStatusMsg(BuddyListEntry *entry)
{	
	if (entry == NULL)
		return;

	if (IsContactMySelf(entry->username))
		return;
		
	if (entry->game)
	{
		ostringstream xstatus;
		DBVARIANT dbv;
		if (!db_get_s(entry->hcontact, protocolname, "RGame", &dbv))
		{
			xstatus << dbv.pszVal << " ";
			db_free(&dbv);
		}

		if (!db_get_b(NULL, protocolname, "noipportinstatus", 0))
		{
			if (!db_get_s(entry->hcontact, protocolname, "ServerName", &dbv))
			{
				xstatus << dbv.pszVal;
				db_free(&dbv);
			}
			else if (!db_get_s(entry->hcontact,protocolname, "ServerIP",&dbv))
			{
				xstatus << "(" << dbv.pszVal << ":" << db_get_w(entry->hcontact, protocolname, "Port", 0) << ")";
				db_free(&dbv);
			}
		}
		db_set_utf(entry->hcontact, protocolname, "XStatusMsg", xstatus.str().c_str());
	}
	else
	{		
		//db_set_b(entry->hcontact, protocolname, "XStatusId", 1);
		db_unset(entry->hcontact, protocolname, "XStatusId");
		db_unset(entry->hcontact, protocolname, "XStatusName");
		db_unset(entry->hcontact, protocolname, "XStatusMsg");
	}

	/*//statusmsg umwandeln
	char *statusmsg = mir_utf8decode((char*)entry->statusmsg.c_str(),NULL);
	if (statusmsg == NULL)
		statusmsg = (char*)entry->statusmsg.c_str();*/		

	string afk = entry->statusmsg.substr(0, 5);
	int status_id = (afk == "(AFK)" || afk == "(ABS)") ? ID_STATUS_AWAY : ID_STATUS_ONLINE;
	
	db_set_w(entry->hcontact, protocolname, "Status", status_id);
	
	if (!entry->statusmsg.empty())
		db_set_utf(entry->hcontact, "CList", "StatusMsg", entry->statusmsg.c_str());
	else
		db_unset(entry->hcontact, "CList", "StatusMsg");
}

/*void CheckAvatar(void *ventry)
{
	BuddyListEntry* entry=(BuddyListEntry*)ventry;
	DBVARIANT dbv;
	if(entry==NULL)
		return;
	if(db_get_b(NULL,protocolname,"noavatars",-1)==0)
	{
		if(db_get_b(entry->hcontact, "ContactPhoto", "Locked", -1)!=1)
		{
			if(!db_get_b(NULL,protocolname,"specialavatarload",0))
			{
				if(db_get(entry->hcontact,"ContactPhoto", "File",&dbv))
				{
					XFire_SetAvatar* xsa=new XFire_SetAvatar;
					xsa->hContact=entry->hcontact;
					xsa->username=new char[strlen(entry->username.c_str())+1];
					strcpy(xsa->username,entry->username.c_str());

					mir_forkthread(SetAvatar,(LPVOID)xsa);
				}
			}
			else
			{
				/*
				   scheinbar unterpricht xfire bei zu agressiven nachfragen der buddyinfos die verbindung , deshalb erstmal auskommentiert
				   getestet mit clanbuddy's >270 members

				   mit hilfe der buddyinfos kann man den avatar laden und screenshot infos etc bekommt man auch
				*/
/*				GetBuddyInfo* buddyinfo=new GetBuddyInfo();
				buddyinfo->userid=entry->userid;
				mir_forkthread(SetAvatar2,(LPVOID)buddyinfo);
			}
		}
	}
}*/

HANDLE handlingBuddys(BuddyListEntry *entry, int clan,char*group,BOOL dontscan)
{
	  HANDLE hContact;
	  string game;

	  if(entry==NULL)
		  return NULL;

	  //wenn der buddy ich selbst ist, dann ignorieren
	  if(IsContactMySelf(entry->username))
		return NULL;

		if(entry->hcontact==NULL)
		{
			entry->hcontact=CList_FindContact(entry->userid);
			if(entry->hcontact&&clan==-1)
			{
				db_set_w(entry->hcontact, protocolname, "Status", ID_STATUS_ONLINE);
				db_set_s(entry->hcontact, protocolname, "MirVer", "xfire");
			}
		}

		if(entry->hcontact==NULL)
		{
			XFireContact xfire_newc;
			xfire_newc.username=(char*)entry->username.c_str();
			xfire_newc.nick=(char*)entry->nick.c_str();
			xfire_newc.id=entry->userid;

			entry->hcontact=CList_AddContact(xfire_newc,TRUE,entry->isOnline()?TRUE:FALSE,clan);
		}


		hContact=entry->hcontact;

		if (hContact!=0)
		{
			if (!entry->nick.empty() && db_get_b(NULL, protocolname, "shownicks", 1)) {
				char*nick=NULL;

				if (myClient->useutf8)
					nick = ( char* )entry->nick.c_str();
				else
					nick = mir_utf8decode(( char* )entry->nick.c_str(),NULL);

				if(nick)
				{
					if(myClient->useutf8)
						db_set_utf(hContact, protocolname, "Nick", nick);
					else
						db_set_s(hContact, protocolname, "Nick", nick);
				}
				else
					db_set_s(hContact, protocolname, "Nick", entry->username.c_str());

				//db_set_utf(hContact, protocolname, "Nick", entry->nick.c_str());
				//db_set_utf(hContact, protocolname, "Nick", ( char* )entry->nick.c_str());
			} else
				db_set_s(hContact, protocolname, "Nick", entry->username.c_str());

			if(!entry->isOnline())
			{
				db_set_w(hContact, protocolname, "Status", ID_STATUS_OFFLINE);
				db_unset(hContact, protocolname, "XStatusMsg");
				db_unset(hContact, protocolname, "XStatusId");
				db_unset(hContact, protocolname, "XStatusName");
				db_unset(hContact, "CList", "StatusMsg");
				//db_set_utf(hContact, protocolname, "XStatusName", "");
				db_unset(hContact, protocolname, "ServerIP");
				db_unset(hContact, protocolname, "Port");
				db_unset(hContact, protocolname, "VServerIP");
				db_unset(hContact, protocolname, "VPort");
				db_unset(hContact, protocolname, "RVoice");
				db_unset(hContact, protocolname, "RGame");
				db_unset(hContact, protocolname, "GameId");
				db_unset(hContact, protocolname, "VoiceId");
				db_unset(hContact, protocolname, "GameInfo");
			}
			else if(entry->game>0||entry->game2>0)
			{
				char temp[XFIRE_MAX_STATIC_STRING_LEN]="";
				char gname[255]="";

				DummyXFireGame *gameob;

				if(strlen(entry->gameinfo.c_str())>0)
					db_set_s(hContact, protocolname, "GameInfo", entry->gameinfo.c_str());

				//beim voicechat foglendes machn
				if(entry->game2>0)
				{
					gameob=(DummyXFireGame*)entry->game2Obj; //obj wo ip und port sind auslesen

					xgamelist.getGamename(entry->game2,gname,255);

					db_set_s(hContact, protocolname, "RVoice", gname);

					if(gameob)
					{
						if((unsigned char)gameob->ip[3]!=0) // wenn ip, dann speichern
						{
							sprintf(temp,"%d.%d.%d.%d",(unsigned char)gameob->ip[3],(unsigned char)gameob->ip[2],(unsigned char)gameob->ip[1],(unsigned char)gameob->ip[0]);
							db_set_s(hContact, protocolname, "VServerIP", temp);
							db_set_w(hContact, protocolname, "VPort", (unsigned long)gameob->port);
						}
						else
						{
							db_unset(hContact, protocolname, "VServerIP");
							db_unset(hContact, protocolname, "VPort");
						}
					}

					db_set_w(hContact, protocolname, "VoiceId", entry->game2);

					SetIcon(hContact,xgamelist.iconmngr.getGameIconHandle(entry->game2),2);	//icon seperat setzen
				}
				else
				{
					db_unset(hContact, protocolname, "VServerIP");
					db_unset(hContact, protocolname, "VPort");
					db_unset(hContact, protocolname, "RVoice");
					db_unset(hContact, protocolname, "VoiceId");
					SetIcon(hContact,(HANDLE)-1,2);
				}

				//beim game folgendes machen
				if(entry->game>0)
				{
					HICON hicongame=xgamelist.iconmngr.getGameIcon(entry->game);

					xgamelist.getGamename(entry->game,gname,255);

					db_set_s(hContact, protocolname, "RGame", gname);

					//beinhaltet ip und port
					gameob=(DummyXFireGame*)entry->gameObj;

					//popup, wenn jemand was spielt
					if(db_get_b(NULL,protocolname,"gamepopup",0)==1) {
						char temp[256]="";

						sprintf(temp,Translate("%s is playing %s."),
							//ist ein nick gesetzt?
							(entry->nick.length()==0?
								//nein dann username
								entry->username.c_str():
								//klar, dann nick nehmen
								entry->nick.c_str())
							,gname);

						if(gameob)
						{
							if((unsigned char)gameob->ip[3]!=0)
							{
								sprintf(temp,Translate("%s is playing %s on server %d.%d.%d.%d:%d."),
									//ist ein nick gesetzt?
								(entry->nick.length()==0?
									//nein dann username
									entry->username.c_str():
									//klar, dann nick nehmen
									entry->nick.c_str())
									,gname,(unsigned char)gameob->ip[3],(unsigned char)gameob->ip[2],(unsigned char)gameob->ip[1],(unsigned char)gameob->ip[0],(unsigned long)gameob->port);
							}
						}

						/*
							POPUP-Filter
							Nur Popups anzeigen die noch nicht angezeigt wurden
						*/
						if(entry->lastpopup==NULL)
						{
							//größe des popupstrings
							int size=strlen(temp)+1;
							//popup darstellen
							displayPopup(NULL,temp,"Miranda XFire Protocol Plugin",0,hicongame);
							//letzten popup definieren
							entry->lastpopup=new char[size];
							//string kopieren
							strcpy_s(entry->lastpopup,size,temp);
						}
						else
						{
							if(strcmp(entry->lastpopup,temp)!=0)
							{
								delete[] entry->lastpopup;
								entry->lastpopup=NULL;

								//größe des popupstrings
								int size=strlen(temp)+1;
								//popup darstellen
								displayPopup(NULL,temp,"Miranda XFire Protocol Plugin",0,hicongame);
								//letzten popup definieren
								entry->lastpopup=new char[size];
								//string kopieren
								strcpy_s(entry->lastpopup,size,temp);
							}
						}
					}

					if(gameob)
					{
						if((unsigned char)gameob->ip[3]!=0)
						{
							//ip und port in kontakt speichern
							sprintf(temp,"%d.%d.%d.%d",(unsigned char)gameob->ip[3],(unsigned char)gameob->ip[2],(unsigned char)gameob->ip[1],(unsigned char)gameob->ip[0]);
							db_set_s(hContact, protocolname, "ServerIP", temp);
							db_set_w(hContact, protocolname, "Port", (unsigned long)gameob->port);

							//lass das query arbeiten
							if(dontscan==FALSE)
								if(ServiceExists("GameServerQuery/Query")&&db_get_b(NULL,protocolname,"gsqsupport",0))
								{
									GameServerQuery_query gsqq={0};
									gsqq.port=gameob->port;
									gsqq.xfiregameid=entry->game;
									strcpy(gsqq.ip,temp);
									CallService("GameServerQuery/Query" , (WPARAM) entry, (LPARAM)&gsqq);
								}
						}
						else
						{
							db_unset(hContact, protocolname, "ServerName");
							db_unset(hContact, protocolname, "ServerIP");
							db_unset(hContact, protocolname, "Port");
						}
					}

					SetIcon(hContact,xgamelist.iconmngr.getGameIconHandle(entry->game));

					//db_unset(hContact, "CList", "StatusMsg");
					db_set_w(hContact, protocolname, "Status", ID_STATUS_ONLINE);
					db_set_utf(hContact, protocolname, "XStatusName", Translate("Playing"));
					setBuddyStatusMsg(entry);
					db_set_b(hContact, protocolname, "XStatusId", xgamelist.iconmngr.getGameIconId(entry->game)+2);

					//buddy vorher ein spielgestartet, wenn nicht sound spielen?
					if(!db_get_w(hContact, protocolname, "GameId",0))
						SkinPlaySound("xfirebstartgame");

					db_set_w(hContact, protocolname, "GameId", entry->game);
				}
				else
				{
					SetIcon(hContact,(HANDLE)-1);
					db_unset(hContact, protocolname, "ServerIP");
					db_unset(hContact, protocolname, "Port");
					db_unset(hContact, protocolname, "XStatusMsg");
					db_unset(hContact, protocolname, "XStatusId");
					db_unset(hContact, protocolname, "XStatusName");
					db_unset(hContact, protocolname, "RGame");
					db_unset(hContact, protocolname, "GameId");
					setBuddyStatusMsg(entry);
				}
			}
			else if (!entry->statusmsg.empty())
			{
				setBuddyStatusMsg(entry);

				SetIcon(hContact,(HANDLE)-1);
				SetIcon(hContact,(HANDLE)-1,2);
				db_unset(hContact, protocolname, "ServerIP");
				db_unset(hContact, protocolname, "Port");
				db_unset(hContact, protocolname, "VServerIP");
				db_unset(hContact, protocolname, "VPort");
				db_unset(hContact, protocolname, "RVoice");
				db_unset(hContact, protocolname, "RGame");
				db_unset(hContact, protocolname, "GameId");
				db_unset(hContact, protocolname, "VoiceId");
			}
			else
			{
				if(db_get_w(entry->hcontact, protocolname, "Status", -1)==ID_STATUS_OFFLINE)
				{
					if(db_get_b(NULL, protocolname, "noclanavatars", 0)==1&&clan>0)
						;
					else
						if(myClient) myClient->CheckAvatar(entry);
				}

				SetIcon(hContact,(HANDLE)-1);
				SetIcon(hContact,(HANDLE)-1,2);
				db_set_w(hContact, protocolname, "Status", ID_STATUS_ONLINE);
				db_set_s(entry->hcontact, protocolname, "MirVer", "xfire");
				if(clan>0) db_set_dw(hContact, protocolname, "Clan", clan);
				//db_set_utf(hContact, "CList", "StatusMsg", "");
				db_unset(hContact, protocolname, "XStatusMsg");
				db_unset(hContact, protocolname, "XStatusId");
				db_unset(hContact, protocolname, "XStatusName");
				db_unset(hContact, "CList", "StatusMsg");
				db_unset(hContact, protocolname, "ServerIP");
				db_unset(hContact, protocolname, "Port");
				db_unset(hContact, protocolname, "VServerIP");
				db_unset(hContact, protocolname, "VPort");
				db_unset(hContact, protocolname, "RVoice");
				db_unset(hContact, protocolname, "RGame");
				db_unset(hContact, protocolname, "GameId");
				db_unset(hContact, protocolname, "VoiceId");
			}
		}
		if(group!=NULL)
		{
			if(!db_get_b(NULL,protocolname,"noclangroups",0))
			{
				if(clan>0)
				{
					int val=db_get_b(NULL,protocolname,"mainclangroup",0);

					if(	db_get_b(NULL,protocolname,"skipfriendsgroups",0)==0 ||
						(db_get_b(NULL,protocolname,"skipfriendsgroups",0)==1&&
					     db_get_b(entry->hcontact, protocolname, "isfriend", 0)==0)
						 )
					{
						if(val==0)
						{
							db_set_s(entry->hcontact, "CList", "Group", group);
						}
						else
						{
							char temp[256];
							DBVARIANT dbv;
							sprintf_s(temp,256,"%d",val-1);
							db_get_s(NULL,"CListGroups",temp,&dbv);
							if(dbv.pszVal!=NULL)
							{
								sprintf_s(temp,256,"%s\\%s",&dbv.pszVal[1],group);
								db_set_s(entry->hcontact, "CList", "Group", temp);
								db_free(&dbv);
							}
						}
					}
				}
				else if(clan==-1)//hauptgruppe für fof
				{
					int val=db_get_b(NULL,protocolname,"fofgroup",0);

					if(val==0)
					{
						db_set_s(entry->hcontact, "CList", "Group", group);
					}
					else
					{
						char temp[256];
						DBVARIANT dbv;
						sprintf_s(temp,256,"%d",val-1);
						db_get_s(NULL,"CListGroups",temp,&dbv);
						if(dbv.pszVal!=NULL)
						{
							sprintf_s(temp,256,"%s\\%s",&dbv.pszVal[1],group);
							db_set_s(entry->hcontact, "CList", "Group", temp);
							db_free(&dbv);
						}
					}
				}
			}
		}
		else
		{
			db_set_b(entry->hcontact, protocolname, "isfriend", 1);
		}

	return hContact;
}

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

    if (ccs->hContact)
    {
		DBVARIANT dbv2;
		if(!db_get(ccs->hContact,protocolname,"Username",&dbv2)) {

			if(myClient!=NULL)
				if(myClient->client->connected)
				{
					SendAcceptInvitationPacket accept;
					accept.name = dbv2.pszVal;
					myClient->client->send(&accept );
				}

			//temporären buddy entfernen, da eh ein neues packet kommt
			db_set_b(ccs->hContact, protocolname, "DontSendDenyPacket", 1);
			CallService(MS_DB_CONTACT_DELETE, (WPARAM) ccs->hContact, 0);
		}
	}
	return 0;
}


static void __cdecl AckBasicSearch(void * pszNick)
{
	if(pszNick!=NULL)
	{
		if(myClient!=NULL)
			if(myClient->client->connected)
			{
				SearchBuddy search;
				search.searchfor(( char* )pszNick);
				myClient->client->send(&search );
			}
	}
}

INT_PTR BasicSearch(WPARAM wParam,LPARAM lParam) {
	static char buf[50];
	if ( lParam ) {
		if(myClient!=NULL)
			if(myClient->client->connected)
			{
				lstrcpynA(buf, (const char *)lParam, 50);
				mir_forkthread(AckBasicSearch, &buf );
				return 1;
			}
	}

	return 0;
}



INT_PTR SearchAddtoList(WPARAM wParam,LPARAM lParam)
{
	PROTOSEARCHRESULT *psr = ( PROTOSEARCHRESULT* ) lParam;

	if ( psr->cbSize != sizeof( PROTOSEARCHRESULT ))
		return 0;

	if((int)wParam==0)
		if(myClient!=NULL)
			if(myClient->client->connected)
			{
				InviteBuddyPacket invite;
				invite.addInviteName( psr->nick, Translate("Add me to your friends list."));
				myClient->client->send(&invite );
			}

	return -1;
}


void CreateGroup(char*grpn,char*field) {
    DBVARIANT dbv;
	char* grp[255];

	int val=db_get_b(NULL,protocolname,field,0);

	if(val==0)
	{
		strcpy_s((char*)grp,255,grpn);//((char*)clan->name[i].c_str());
	}
	else
	{
		char temp[255];
		DBVARIANT dbv;
		sprintf_s(temp,255,"%d",val-1);
		db_get_s(NULL,"CListGroups",temp,&dbv);
		if(dbv.pszVal!=NULL)
		{
			sprintf_s((char*)grp,255,"%s\\%s",&dbv.pszVal[1],(char*)grpn);
			db_free(&dbv);
		}
		else //gruppe existiert nciht mehr, auf root alles legen
		{
			strcpy_s((char*)grp,255,grpn);
			db_set_b(NULL,protocolname,field,0);
		}
	}


	char group[255]="";
	char temp[10];
	int i=0;
	for (i = 0;; i++)
	{
		sprintf(temp,"%d",i);
		if (db_get_s(NULL, "CListGroups", temp, &dbv))
		{
			i--;
			break;
		}
		if (dbv.pszVal[0] != '\0' && !lstrcmp(dbv.pszVal + 1, (char*)grp))	{
			db_free(&dbv);
			return;
		}
		db_free(&dbv);
	}
	strcpy_s(group,255,"D");
	strcat_s(group,255,(char*)grp);
	group[0]= 1 | GROUPF_EXPANDED;
	sprintf(temp,"%d",i+1);
	db_set_s(NULL, "CListGroups", temp, group);
	CallServiceSync(MS_CLUI_GROUPADDED, i + 1, 0);
}


INT_PTR SetAwayMsg(WPARAM wParam, LPARAM lParam) {
	EnterCriticalSection(&modeMsgsMutex);
	if(( char* )lParam==NULL)
	{
		if(wParam==ID_STATUS_ONLINE)
		{
			strcpy(statusmessage[0],"");
		}
		else if((wParam!=ID_STATUS_ONLINE&&wParam!=ID_STATUS_OFFLINE)/*&&db_get_b(NULL,protocolname,"nocustomaway",0)==0*/)
		{
			strcpy(statusmessage[1],"(AFK) Away from Keyboard");
		}
	}
	else
	{
		if(wParam==ID_STATUS_ONLINE)
		{
			strcpy(statusmessage[0],( char* )lParam);
		}
		else if((wParam!=ID_STATUS_ONLINE&&wParam!=ID_STATUS_OFFLINE)&&db_get_b(NULL,protocolname,"nocustomaway",0)==0&&strlen(( char* )lParam)>0)
		{
			sprintf(statusmessage[1], "(AFK) %s", (char*)lParam);
			//strcpy(statusmessage[1],( char* )lParam);
		}
		else if(wParam!=ID_STATUS_ONLINE&&wParam!=ID_STATUS_OFFLINE)
		{
			strcpy(statusmessage[1],"(AFK) Away from Keyboard");
		}
	}

	if(myClient!=NULL)
	{
		if(myClient->client->connected)
		{
			if(bpStatus==ID_STATUS_ONLINE)
				myClient->Status(statusmessage[0]);
			else if(wParam!=ID_STATUS_ONLINE&&wParam!=ID_STATUS_OFFLINE)
				myClient->Status(statusmessage[1]);
		}
	}
	LeaveCriticalSection(&modeMsgsMutex);
	return 0;
}

static void SendAMAck( LPVOID param )
{
	DBVARIANT dbv;

	if(!db_get_utf((HANDLE)param, protocolname, "XStatusMsg",&dbv))
	{
		ProtoBroadcastAck(protocolname, (HANDLE)param, ACKTYPE_AWAYMSG, ACKRESULT_SUCCESS, (HANDLE) 1, LPARAM(dbv.pszVal));
	}
	else
		ProtoBroadcastAck(protocolname, (HANDLE)param, ACKTYPE_AWAYMSG, ACKRESULT_SUCCESS, (HANDLE) 1, LPARAM(""));
}

INT_PTR SetNickName(WPARAM newnick, LPARAM lparam)
{
	if(newnick==NULL)
	{
		return FALSE;
	}

	if(myClient!=NULL)
		if(myClient->client->connected)
		{
			myClient->setNick((char*)newnick);
			db_set_s(NULL,protocolname,"Nick",(char*)newnick);
			return TRUE;
		}
	return FALSE;
}

//sendet neue preferencen zu xfire
INT_PTR SendPrefs(WPARAM wparam, LPARAM lparam)
{
	if(myClient!=NULL)
		if(myClient->client->connected)
		{
			PrefsPacket prefs;
			for(int i=0;i<XFIRE_RECVPREFSPACKET_MAXCONFIGS;i++)
			{
				prefs.config[i]=xfireconfig[i];
			}
			myClient->client->send( &prefs );
			return TRUE;
		}
	return FALSE;
}


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

	mir_forkthread(SendAMAck,ccs->hContact);
	return 1;
}

int ContactDeleted(WPARAM wParam,LPARAM lParam)
{
	if(!db_get_b((HANDLE)wParam, protocolname, "DontSendDenyPacket", 0))
		if(db_get_b((HANDLE)wParam,"CList","NotOnList",0))
		{
			if(myClient!=NULL)
				if(myClient->client->connected)
				{
					DBVARIANT dbv2;
					if(!db_get((HANDLE)wParam,protocolname,"Username",&dbv2)) {
						SendDenyInvitationPacket deny;
						deny.name = dbv2.pszVal;
						myClient->client->send( &deny );
					}
				}
		}
		return 0;
}

INT_PTR StartGame(WPARAM wParam,LPARAM lParam,LPARAM fParam)
{
	//gamelist blocken
	xgamelist.Block(TRUE);

	Xfire_game*game=xgamelist.getGamebyGameid(fParam);

	//starte das spiel
	if(game)
		game->start_game();

	//gamelist blocken
	xgamelist.Block(FALSE);


	return 0;
}

INT_PTR RemoveFriend(WPARAM wParam,LPARAM lParam) {
	char temp[256];
	DBVARIANT dbv;

	if(!db_get_s((HANDLE)wParam, protocolname, "Username",&dbv))
	{
		sprintf(temp,Translate("Do you really want delete your friend %s?"),dbv.pszVal);
		if(MessageBoxA(NULL,temp,Translate("Confirm Delete"),MB_YESNO|MB_ICONQUESTION)==IDYES)
		{
			if(myClient!=NULL)
					{
						if(myClient->client->connected)
						{
							SendRemoveBuddyPacket removeBuddy;

							removeBuddy.userid=db_get_dw((HANDLE)wParam,protocolname,"UserId",0);

							if(removeBuddy.userid!=0)
							{
								myClient->client->send(&removeBuddy);
							}
					}
			}
		}
		db_free(&dbv);
	}
	return 0;
}

INT_PTR BlockFriend(WPARAM wParam,LPARAM lParam) {
	DBVARIANT dbv;

	if(!db_get_s((HANDLE)wParam, protocolname, "Username",&dbv))
	{
		if(MessageBoxA(NULL,Translate("Block this user from ever contacting you again?"),Translate("Block Confirmation"),MB_YESNO|MB_ICONQUESTION)==IDYES)
		{
			if(myClient!=NULL)
					{
						if(myClient->client->connected)
						{
							db_set_b(NULL,"XFireBlock",dbv.pszVal,1);

							SendDenyInvitationPacket deny;
							deny.name = dbv.pszVal;
							myClient->client->send( &deny );
						}
					}
		}
		CallService( MS_DB_CONTACT_DELETE, (WPARAM) wParam, 1 );
		db_free(&dbv);
	}
	return 0;
}

INT_PTR StartThisGame(WPARAM wParam,LPARAM lParam) {
	//gamelist blocken
	xgamelist.Block(TRUE);

	//hole die gameid des spiels
	int id=db_get_w((HANDLE)wParam, protocolname, "GameId",0);

	//hole passendes spielobjekt
	Xfire_game*game=xgamelist.getGamebyGameid(id);

	//starte das spiel
	if(game)
		game->start_game();

	//gamelist blocken
	xgamelist.Block(FALSE);

	return 0;
}

INT_PTR JoinGame(WPARAM wParam,LPARAM lParam) {
	//gamelist blocken
	xgamelist.Block(TRUE);

	//hole die gameid des spiels
	int id=db_get_w((HANDLE)wParam, protocolname, "GameId",0);

	//hole passendes spielobjekt
	Xfire_game*game=xgamelist.getGamebyGameid(id);

	//starte das spiel
	if(game)
	{
		DBVARIANT dbv; //dbv.pszVal
		int port=db_get_w((HANDLE)wParam, protocolname, "Port",0);
		if(!db_get_s((HANDLE)wParam, protocolname, "ServerIP",&dbv))
		{
			//starte spiel mit netzwerk parametern
			game->start_game(dbv.pszVal,port);
			db_free(&dbv);
		}
	}

	//gamelist unblocken
	xgamelist.Block(FALSE);


	return 0;
}


int doneQuery( WPARAM wParam, LPARAM lParam ) {
	char temp[256];
	BuddyListEntry* bud=(BuddyListEntry*)wParam;
	gServerstats* gameinfo = (gServerstats*)lParam;
	db_set_s(bud->hcontact, protocolname, "ServerName", gameinfo->name);
	db_set_s(bud->hcontact, protocolname, "GameType", gameinfo->gametype);
	db_set_s(bud->hcontact, protocolname, "Map", gameinfo->map);
	sprintf(temp,"(%d/%d)",gameinfo->players,gameinfo->maxplayers);
	db_set_s(bud->hcontact, protocolname, "Players", temp);
	db_set_b(bud->hcontact, protocolname, "Passworded", gameinfo->password);

	if(myClient!=NULL)
		handlingBuddys(bud,0,NULL,TRUE);

	return 0;
}

static INT_PTR SetNickDlg(WPARAM wParam,LPARAM lParam) {
	return ShowSetNick();
}


int IconLibChanged(WPARAM wParam, LPARAM lParam) {
	/*int x=0;
	char temp[255];
	for(int i=0;i<1024;i++)
	{
		if(icocache[i].hicon>0)
		{
			//ImageList_ReplaceIcon(hAdvancedStatusIcon,(int)icocache[i].handle,icocache[i].hicon);
			HANDLE before=icocache[i].handle;
			icocache[i].handle=(HANDLE)CallService(MS_CLIST_EXTRA_ADD_ICON, (WPARAM)icocache[i].hicon, 0);
			sprintf(temp,"before: %d after: %d",before,icocache[i].handle);
			MessageBoxA(NULL,temp,temp,0);
			DrawIcon(GetDC(NULL),x,0,(HICON)CallService(MS_SKIN2_GETICONBYHANDLE,0,(LPARAM)icocache[i].handle));
			x+=32;
		}
	}*/
	return 0;
}


INT_PTR GetAvatarInfo(WPARAM wParam, LPARAM lParam) {
	PROTO_AVATAR_INFORMATION* pai = (PROTO_AVATAR_INFORMATION*)lParam;

	if(db_get_b(NULL,protocolname,"noavatars",-1)!=0)
		return GAIR_NOAVATAR;

	pai->format=db_get_w(pai->hContact,"ContactPhoto","Format",0);
	if(pai->format==0)
		return GAIR_NOAVATAR;

	DBVARIANT dbv;
	if(!db_get(pai->hContact,"ContactPhoto","File",&dbv))
	{
		strcpy(pai->filename,dbv.pszVal);
		db_free(&dbv);
	}
	else
		return GAIR_NOAVATAR;

	return GAIR_SUCCESS;
}