File: unitsync.cpp

package info (click to toggle)
spring 0.81.2.1%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 28,496 kB
  • ctags: 37,096
  • sloc: cpp: 238,659; ansic: 13,784; java: 12,175; awk: 3,428; python: 1,159; xml: 738; perl: 405; sh: 297; makefile: 267; pascal: 228; objc: 192
file content (2945 lines) | stat: -rw-r--r-- 71,749 bytes parent folder | download
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
#include "StdAfx.h"
#include "unitsync.h"
#include "unitsync_api.h"

#include <algorithm>
#include <string>
#include <vector>
#include <set>

// shared with spring:
#include "LuaInclude.h"
#include "FileSystem/ArchiveFactory.h"
#include "FileSystem/ArchiveScanner.h"
#include "FileSystem/FileHandler.h"
#include "FileSystem/VFSHandler.h"
#include "Game/GameVersion.h"
#include "Lua/LuaParser.h"
#include "Map/MapParser.h"
#include "Map/SMF/SmfMapFile.h"
#include "ConfigHandler.h"
#include "FileSystem/FileSystem.h"
#include "FileSystem/FileSystemHandler.h"
#include "Rendering/Textures/Bitmap.h"
#include "Sim/Misc/SideParser.h"
#include "ExternalAI/Interface/aidefines.h"
#include "ExternalAI/Interface/SSkirmishAILibrary.h"
#include "ExternalAI/LuaAIImplHandler.h"
#include "System/Exceptions.h"
#include "System/LogOutput.h"
#include "System/Util.h"
#include "System/exportdefines.h"
#include "System/Info.h"
#include "System/Option.h"


// unitsync only:
#include "LuaParserAPI.h"
#include "Syncer.h"

using std::string;

//////////////////////////
//////////////////////////

static CLogSubsystem LOG_UNITSYNC("unitsync", true);

//This means that the DLL can only support one instance. Don't think this should be a problem.
static CSyncer* syncer;

static bool logOutputInitialised=false;
// I'd rather not include globalstuff
#define SQUARE_SIZE 8


#ifdef WIN32
BOOL CALLING_CONV DllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved)
{
	return TRUE;
}
#endif


//////////////////////////
//////////////////////////

// function argument checking

static void CheckInit()
{
	if (!archiveScanner || !vfsHandler)
		throw std::logic_error("Unitsync not initialized. Call Init first.");
}

static void _CheckNull(void* condition, const char* name)
{
	if (!condition)
		throw std::invalid_argument("Argument " + string(name) + " may not be null.");
}

static void _CheckNullOrEmpty(const char* condition, const char* name)
{
	if (!condition || *condition == 0)
		throw std::invalid_argument("Argument " + string(name) + " may not be null or empty.");
}

static void _CheckBounds(int index, int size, const char* name)
{
	if (index < 0 || index >= size)
		throw std::out_of_range("Argument " + string(name) + " out of bounds. Index: " +
		                         IntToString(index) + " Array size: " + IntToString(size));
}

static void _CheckPositive(int value, const char* name)
{
	if (value <= 0)
		throw std::out_of_range("Argument " + string(name) + " must be positive.");
}

#define CheckNull(arg)         _CheckNull((arg), #arg)
#define CheckNullOrEmpty(arg)  _CheckNullOrEmpty((arg), #arg)
#define CheckBounds(arg, size) _CheckBounds((arg), (size), #arg)
#define CheckPositive(arg)     _CheckPositive((arg), #arg);

//////////////////////////
//////////////////////////

// error handling

static string lastError;

static void _SetLastError(string err)
{
	logOutput.Prints(LOG_UNITSYNC, "error: " + err);
	lastError = err;
}

#define SetLastError(str) \
	_SetLastError(string(__FUNCTION__) + ": " + (str))

#define UNITSYNC_CATCH_BLOCKS \
	catch (const std::exception& e) { \
		SetLastError(e.what()); \
	} \
	catch (...) { \
		SetLastError("an unknown exception was thrown"); \
	}

//////////////////////////
//////////////////////////

// Helper class for loading a map archive temporarily

class ScopedMapLoader {
	public:
		ScopedMapLoader(const string& mapName) : oldHandler(vfsHandler)
		{
			CFileHandler f("maps/" + mapName);
			if (f.FileExists()) {
				return;
			}

			vfsHandler = new CVFSHandler();
			vfsHandler->AddMapArchiveWithDeps(mapName, false);
		}

		~ScopedMapLoader()
		{
			if (vfsHandler != oldHandler) {
				delete vfsHandler;
				vfsHandler = oldHandler;
			}
		}

	private:
		CVFSHandler* oldHandler;
};

//////////////////////////
//////////////////////////

/** @addtogroup unitsync_api
	@{ */

/**
 * @brief Retrieve next error in queue of errors and removes this error from queue
 * @return An error message, or NULL if there are no more errors in the queue
 *
 * Use this method to get a (short) description of errors that occurred in any
 * other unitsync methods. Call this in a loop until it returns NULL to get all
 * errors.
 *
 * The error messages may be varying in detail etc.; nothing is guaranteed about
 * them, not even whether they have terminating newline or not.
 *
 * Example:
 *		@code
 *		const char* err;
 *		while ((err = GetNextError()) != NULL)
 *			printf("unitsync error: %s\n", err);
 *		@endcode
 */
EXPORT(const char*) GetNextError()
{
	try {
		// queue is only 1 element long now for simplicity :-)

		if (lastError.empty()) return NULL;

		string err = lastError;
		lastError.clear();
		return GetStr(err);
	}
	UNITSYNC_CATCH_BLOCKS;

	// Oops, can't even return errors anymore...
	// Returning anything but NULL might cause infinite loop in lobby client...
	//return __FUNCTION__ ": fatal error: an exception was thrown in GetNextError";
	return NULL;
}


/**
 * @brief Retrieve the version of Spring this unitsync was compiled with
 * @return The Spring/unitsync version string
 *
 * Returns a const char* string specifying the version of spring used to build this library with.
 * It was added to aid in lobby creation, where checks for updates to spring occur.
 */
EXPORT(const char*) GetSpringVersion()
{
	return GetStr(SpringVersion::Get());
}


static void _UnInit()
{
	lpClose();

	FileSystemHandler::Cleanup();

	if ( syncer )
	{
		SafeDelete(syncer);
		logOutput.Print(LOG_UNITSYNC, "deinitialized");
	}
}


/**
 * @brief Uninitialize the unitsync library
 *
 * also resets the config handler
 */
EXPORT(void) UnInit()
{
	try {
		_UnInit();
		ConfigHandler::Deallocate();
	}
	UNITSYNC_CATCH_BLOCKS;
}


/**
 * @brief Initialize the unitsync library
 * @return Zero on error; non-zero on success
 *
 * Call this function before calling any other function in unitsync.
 * In case unitsync was already initialized, it is uninitialized and then
 * reinitialized.
 *
 * Calling this function is currently the only way to clear the VFS of the
 * files which are mapped into it.  In other words, after using AddArchive() or
 * AddAllArchives() you have to call Init when you want to remove the archives
 * from the VFS and start with a clean state.
 *
 * The config handler won't be reset, it will however be initialised if it wasn't before (with SetSpringConfigFile())
 */
EXPORT(int) Init(bool isServer, int id)
{
	try {
		if (!logOutputInitialised)
			logOutput.SetFileName("unitsync.log");
		if (!configHandler)
			ConfigHandler::Instantiate(); // use the default config file
		FileSystemHandler::Initialize(false);

		if (!logOutputInitialised)
		{
			logOutput.Initialize();
			logOutputInitialised = true;
		}
		logOutput.Print(LOG_UNITSYNC, "loaded, %s\n", SpringVersion::GetFull().c_str());

		_UnInit();

		std::vector<string> filesToCheck;
		filesToCheck.push_back("base/springcontent.sdz");
		filesToCheck.push_back("base/maphelper.sdz");
		filesToCheck.push_back("base/spring/bitmaps.sdz");
		filesToCheck.push_back("base/cursors.sdz");

		for (std::vector<string>::const_iterator it = filesToCheck.begin(); it != filesToCheck.end(); ++it) {
			CFileHandler f(*it, SPRING_VFS_RAW);
			if (!f.FileExists()) {
				throw content_error("Required base file '" + *it + "' does not exist.");
			}
		}

		syncer = new CSyncer();
		logOutput.Print(LOG_UNITSYNC, "initialized, %s\n", SpringVersion::GetFull().c_str());
		logOutput.Print(LOG_UNITSYNC, "%s\n", isServer ? "hosting" : "joining");
		return 1;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Get the main data directory that's used by unitsync and Spring
 * @return NULL on error; the data directory path on success
 *
 * This is the data directory which is used to write logs, screenshots, demos, etc.
 */
EXPORT(const char*) GetWritableDataDirectory()
{
	try {
		CheckInit();
		return GetStr(FileSystemHandler::GetInstance().GetWriteDir());
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}

// TODO (when needed): GetDataDirectoryCount(), GetDataDirectory(int index)


/**
 * @brief Process another unit and return how many are left to process
 * @return The number of unprocessed units to be handled
 *
 * Call this function repeatedly until it returns 0 before calling any other
 * function related to units.
 *
 * Because of risk for infinite loops, this function can not return any error code.
 * It is advised to poll GetNextError() after calling this function.
 *
 * Before any units are available, you'll first need to map a mod's archives
 * into the VFS using AddArchive() or AddAllArchives().
 */
EXPORT(int) ProcessUnits()
{
	try {
		logOutput.Print(LOG_UNITSYNC, "syncer: process units\n");
		return syncer->ProcessUnits();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Identical to ProcessUnits(), neither generates checksum anymore
 * @see ProcessUnits
 */
EXPORT(int) ProcessUnitsNoChecksum()
{
	return ProcessUnits();
}


/**
 * @brief Get the number of units
 * @return Zero on error; the number of units available on success
 *
 * Will return the number of units. Remember to call ProcessUnits() beforehand
 * until it returns 0.  As ProcessUnits() is called the number of processed
 * units goes up, and so will the value returned by this function.
 *
 * Example:
 *		@code
 *		while (ProcessUnits() != 0) {}
 *		int unit_number = GetUnitCount();
 *		@endcode
 */
EXPORT(int) GetUnitCount()
{
	try {
		logOutput.Print(LOG_UNITSYNC, "syncer: get unit count\n");
		return syncer->GetUnitCount();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Get the units internal mod name
 * @param unit The units id number
 * @return The units internal modname or NULL on error
 *
 * This function returns the units internal mod name. For example it would
 * return 'armck' and not 'Arm Construction kbot'.
 */
EXPORT(const char*) GetUnitName(int unit)
{
	try {
		logOutput.Print(LOG_UNITSYNC, "syncer: get unit %d name\n", unit);
		string tmp = syncer->GetUnitName(unit);
		return GetStr(tmp);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Get the units human readable name
 * @param unit The units id number
 * @return The units human readable name or NULL on error
 *
 * This function returns the units human name. For example it would return
 * 'Arm Construction kbot' and not 'armck'.
 */
EXPORT(const char*) GetFullUnitName(int unit)
{
	try {
		logOutput.Print(LOG_UNITSYNC, "syncer: get full unit %d name\n", unit);
		string tmp = syncer->GetFullUnitName(unit);
		return GetStr(tmp);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}

//////////////////////////
//////////////////////////

/**
 * @brief Adds an archive to the VFS (Virtual File System)
 *
 * After this, the contents of the archive are available to other unitsync functions,
 * for example: ProcessUnits(), OpenFileVFS(), ReadFileVFS(), FileSizeVFS(), etc.
 *
 * Don't forget to call RemoveAllArchives() before proceeding with other archives.
 */
EXPORT(void) AddArchive(const char* name)
{
	try {
		CheckInit();
		CheckNullOrEmpty(name);

		logOutput.Print(LOG_UNITSYNC, "adding archive: %s\n", name);
		vfsHandler->AddArchive(name, false);
	}
	UNITSYNC_CATCH_BLOCKS;
}


/**
 * @brief Adds an achive and all it's dependencies to the VFS
 * @see AddArchive
 */
EXPORT(void) AddAllArchives(const char* root)
{
	try {
		CheckInit();
		CheckNullOrEmpty(root);

		vector<string> ars = archiveScanner->GetArchives(root);
		for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) {
			logOutput.Print(LOG_UNITSYNC, "adding archive: %s\n", i->c_str());
			vfsHandler->AddArchive(*i, false);
		}
	}
	UNITSYNC_CATCH_BLOCKS;
}

/**
 * @brief Removes all archives from the VFS (Virtual File System)
 *
 * After this, the contents of the archives are not available to other unitsync functions anymore,
 * for example: ProcessUnits(), OpenFileVFS(), ReadFileVFS(), FileSizeVFS(), etc.
 *
 * In a lobby client, this may be used instead of Init() when switching mod archive.
 */
EXPORT(void) RemoveAllArchives()
{
	try {
		CheckInit();

		logOutput.Print(LOG_UNITSYNC, "removing all archives\n");
		SafeDelete(vfsHandler);
		SafeDelete(syncer);
		vfsHandler = new CVFSHandler();
		syncer = new CSyncer();
	}
	UNITSYNC_CATCH_BLOCKS;
}

/**
 * @brief Get checksum of an archive
 * @return Zero on error; the checksum on success
 *
 * This checksum depends only on the contents from the archive itself, and not
 * on the contents from dependencies of this archive (if any).
 */
EXPORT(unsigned int) GetArchiveChecksum(const char* arname)
{
	try {
		CheckInit();
		CheckNullOrEmpty(arname);

		logOutput.Print(LOG_UNITSYNC, "archive checksum: %s\n", arname);
		return archiveScanner->GetArchiveChecksum(arname);
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Gets the real path to the archive
 * @return NULL on error; a path to the archive on success
 */
EXPORT(const char*) GetArchivePath(const char* arname)
{
	try {
		CheckInit();
		CheckNullOrEmpty(arname);

		logOutput.Print(LOG_UNITSYNC, "archive path: %s\n", arname);
		return GetStr(archiveScanner->GetArchivePath(arname));
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


// Updated on every call to GetMapCount
static vector<string> mapNames;


/**
 * @brief Get the number of maps available
 * @return Zero on error; the number of maps available on success
 *
 * Call this before any of the map functions which take a map index as parameter.
 * This function actually performs a relatively costly enumeration of all maps,
 * so you should resist from calling it repeatedly in a loop.  Rather use:
 *		@code
 *		int map_count = GetMapCount();
 *		for (int index = 0; index < map_count; ++index) {
 *			printf("map name: %s\n", GetMapName(index));
 *		}
 *		@endcode
 * Then:
 *		@code
 *		for (int index = 0; index < GetMapCount(); ++index) { ... }
 *		@endcode
 */
EXPORT(int) GetMapCount()
{
	try {
		CheckInit();

		//vector<string> files = CFileHandler::FindFiles("{maps/*.smf,maps/*.sm3}");
		vector<string> files = CFileHandler::FindFiles("maps/", "{*.smf,*.sm3}");
		vector<string> ars = archiveScanner->GetMaps();

		mapNames.clear();
		for (vector<string>::iterator i = files.begin(); i != files.end(); ++i) {
			string mn = *i;
			mn = mn.substr(mn.find_last_of('/') + 1);
			mapNames.push_back(mn);
		}
		for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i)
			mapNames.push_back(*i);
		sort(mapNames.begin(), mapNames.end());

		return mapNames.size();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Get the name of a map
 * @return NULL on error; the name of the map (e.g. "SmallDivide.smf") on success
 */
EXPORT(const char*) GetMapName(int index)
{
	try {
		CheckInit();
		CheckBounds(index, mapNames.size());

		return GetStr(mapNames[index]);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


static void safe_strzcpy(char* dst, std::string src, size_t max)
{
	if (src.length() > max-1) {
		src = src.substr(0, max-1);
	}
	strcpy(dst, src.c_str());
}


static int _GetMapInfoEx(const char* name, MapInfo* outInfo, int version)
{
	CheckInit();
	CheckNullOrEmpty(name);
	CheckNull(outInfo);

	logOutput.Print(LOG_UNITSYNC, "get map info: %s", name);

	const string mapName = name;
	ScopedMapLoader mapLoader(mapName);

	string err("");

	MapParser mapParser(mapName);
	if (!mapParser.IsValid()) {
		err = mapParser.GetErrorLog();
	}
	const LuaTable mapTable = mapParser.GetRoot();

	// Retrieve the map header as well
	if (err.empty()) {
		const string extension = mapName.substr(mapName.length() - 3);
		if (extension == "smf") {
			try {
				CSmfMapFile file(name);
				const SMFHeader& mh = file.GetHeader();

				outInfo->width  = mh.mapx * SQUARE_SIZE;
				outInfo->height = mh.mapy * SQUARE_SIZE;
			}
			catch (content_error&) {
				outInfo->width  = -1;
			}
		}
		else {
			int w = mapTable.GetInt("gameAreaW", 0);
			int h = mapTable.GetInt("gameAreaW", 1);

			outInfo->width  = w * SQUARE_SIZE;
			outInfo->height = h * SQUARE_SIZE;
		}

		// Make sure we found stuff in both the smd and the header
		if (outInfo->width <= 0) {
			err = "Bad map width";
		}
		else if (outInfo->height <= 0) {
			err = "Bad map height";
		}
	}

	// If the map didn't parse, say so now
	if (!err.empty()) {
		SetLastError(err);
		safe_strzcpy(outInfo->description, err, 255);

		// Fill in stuff so tasclient won't crash
		outInfo->posCount = 0;
		if (version >= 1) {
			outInfo->author[0] = 0;
		}
		return 0;
	}

	const string desc = mapTable.GetString("description", "");
	safe_strzcpy(outInfo->description, desc, 255);

	outInfo->tidalStrength   = mapTable.GetInt("tidalstrength", 0);
	outInfo->gravity         = mapTable.GetInt("gravity", 0);
	outInfo->extractorRadius = mapTable.GetInt("extractorradius", 0);
	outInfo->maxMetal        = mapTable.GetFloat("maxmetal", 0.0f);

	if (version >= 1) {
		const string author = mapTable.GetString("author", "");
		safe_strzcpy(outInfo->author, author, 200);
	}

	const LuaTable atmoTable = mapTable.SubTable("atmosphere");
	outInfo->minWind = atmoTable.GetInt("minWind", 0);
	outInfo->maxWind = atmoTable.GetInt("maxWind", 0);

	// Find the start positions
	int curTeam;
	for (curTeam = 0; curTeam < 16; ++curTeam) {
		float3 pos(-1.0f, -1.0f, -1.0f); // defaults
		if (!mapParser.GetStartPos(curTeam, pos)) {
			break; // position could not be parsed
		}
		outInfo->positions[curTeam].x = pos.x;
		outInfo->positions[curTeam].z = pos.z;
		logOutput.Print(LOG_UNITSYNC, "  startpos: %.0f, %.0f", pos.x, pos.z);
	}

	outInfo->posCount = curTeam;

	return 1;
}


/**
 * @brief Retrieve map info
 * @param name name of the map, e.g. "SmallDivide.smf"
 * @param outInfo pointer to structure which is filled with map info
 * @param version this determines which fields of the MapInfo structure are filled
 * @return Zero on error; non-zero on success
 *
 * If version >= 1, then the author field is filled.
 *
 * Important: the description and author fields must point to a valid, and sufficiently long buffer
 * to store their contents.  Description is max 255 chars, and author is max 200 chars. (including
 * terminating zero byte).
 *
 * If an error occurs (return value 0), the description is set to an error message.
 * However, using GetNextError() is the recommended way to get the error message.
 *
 * Example:
 *		@code
 *		char description[255];
 *		char author[200];
 *		MapInfo mi;
 *		mi.description = description;
 *		mi.author = author;
 *		if (GetMapInfoEx("somemap.smf", &mi, 1)) {
 *			//now mi is contains map data
 *		} else {
 *			//handle the error
 *		}
 *		@endcode
 */
EXPORT(int) GetMapInfoEx(const char* name, MapInfo* outInfo, int version)
{
	try {
		return _GetMapInfoEx(name, outInfo, version);
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Retrieve map info, equivalent to GetMapInfoEx(name, outInfo, 0)
 * @param name name of the map, e.g. "SmallDivide.smf"
 * @param outInfo pointer to structure which is filled with map info
 * @return Zero on error; non-zero on success
 * @see GetMapInfoEx
 */
EXPORT(int) GetMapInfo(const char* name, MapInfo* outInfo)
{
	try {
		return _GetMapInfoEx(name, outInfo, 0);
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}



/**
 * @brief return the map's minimum height
 * @param name name of the map, e.g. "SmallDivide.smf"
 *
 * Together with maxHeight, this determines the
 * range of the map's height values in-game. The
 * conversion formula for any raw 16-bit height
 * datum <code>h</code> is
 *
 *    <code>minHeight + (h * (maxHeight - minHeight) / 65536.0f)</code>
 */
EXPORT(float) GetMapMinHeight(const char* name) {
	try {
		ScopedMapLoader loader(name);
		CSmfMapFile file(name);
		MapParser parser(name);

		const SMFHeader& header = file.GetHeader();
		const LuaTable rootTable = parser.GetRoot();
		const LuaTable smfTable = rootTable.SubTable("smf");

		if (smfTable.KeyExists("minHeight")) {
			// override the header's minHeight value
			return (smfTable.GetFloat("minHeight", 0.0f));
		} else {
			return (header.minHeight);
		}
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0.0f;
}

/**
 * @brief return the map's maximum height
 * @param name name of the map, e.g. "SmallDivide.smf"
 *
 * Together with minHeight, this determines the
 * range of the map's height values in-game. See
 * GetMapMinHeight() for the conversion formula.
 */
EXPORT(float) GetMapMaxHeight(const char* name) {
	try {
		ScopedMapLoader loader(name);
		CSmfMapFile file(name);
		MapParser parser(name);

		const SMFHeader& header = file.GetHeader();
		const LuaTable rootTable = parser.GetRoot();
		const LuaTable smfTable = rootTable.SubTable("smf");

		if (smfTable.KeyExists("maxHeight")) {
			// override the header's maxHeight value
			return (smfTable.GetFloat("maxHeight", 0.0f));
		} else {
			return (header.maxHeight);
		}
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0.0f;
}




static vector<string> mapArchives;


/**
 * @brief Retrieves the number of archives a map requires
 * @param mapName name of the map, e.g. "SmallDivide.smf"
 * @return Zero on error; the number of archives on success
 *
 * Must be called before GetMapArchiveName()
 */
EXPORT(int) GetMapArchiveCount(const char* mapName)
{
	try {
		CheckInit();
		CheckNullOrEmpty(mapName);

		mapArchives = archiveScanner->GetArchivesForMap(mapName);
		return mapArchives.size();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Retrieves an archive a map requires
 * @param index the index of the archive
 * @return NULL on error; the name of the archive on success
 */
EXPORT(const char*) GetMapArchiveName(int index)
{
	try {
		CheckInit();
		CheckBounds(index, mapArchives.size());

		return GetStr(mapArchives[index]);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Get map checksum given a map index
 * @param index the index of the map
 * @return Zero on error; the checksum on success
 *
 * This checksum depends on Spring internals, and as such should not be expected
 * to remain stable between releases.
 *
 * (It is ment to check sync between clients in lobby, for example.)
 */
EXPORT(unsigned int) GetMapChecksum(int index)
{
	try {
		CheckInit();
		CheckBounds(index, mapNames.size());

		return archiveScanner->GetMapChecksum(mapNames[index]);
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Get map checksum given a map name
 * @param mapName name of the map, e.g. "SmallDivide.smf"
 * @return Zero on error; the checksum on success
 * @see GetMapChecksum
 */
EXPORT(unsigned int) GetMapChecksumFromName(const char* mapName)
{
	try {
		CheckInit();

		return archiveScanner->GetMapChecksum(mapName);
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


#define RM	0x0000F800
#define GM  0x000007E0
#define BM  0x0000001F

#define RED_RGB565(x) ((x&RM)>>11)
#define GREEN_RGB565(x) ((x&GM)>>5)
#define BLUE_RGB565(x) (x&BM)
#define PACKRGB(r, g, b) (((r<<11)&RM) | ((g << 5)&GM) | (b&BM) )

// Used to return the image
static char* imgbuf[1024*1024*2];

static void* GetMinimapSM3(string mapName, int miplevel)
{
	MapParser mapParser(mapName);
	const string minimapFile = mapParser.GetRoot().GetString("minimap", "");

	if (minimapFile.empty()) {
		memset(imgbuf,0,sizeof(imgbuf));
		return imgbuf;
	}

	CBitmap bm;
	if (!bm.Load(minimapFile)) {
		memset(imgbuf,0,sizeof(imgbuf));
		return imgbuf;
	}

	if (1024 >> miplevel != bm.xsize || 1024 >> miplevel != bm.ysize)
		bm = bm.CreateRescaled (1024 >> miplevel, 1024 >> miplevel);

	unsigned short *dst = (unsigned short*)imgbuf;
	unsigned char *src = bm.mem;
	for (int y=0;y<bm.ysize;y++)
		for (int x=0;x<bm.xsize;x++)
		{
			*dst = 0;

			*dst |= ((src[0]>>3) << 11) & RM;
			*dst |= ((src[1]>>2) << 5) & GM;
			*dst |= (src[2]>>3) & BM;

			dst ++;
			src += 4;
		}

	return imgbuf;
}

static void* GetMinimapSMF(string mapName, int miplevel)
{
	CSmfMapFile in(mapName);
	std::vector<uint8_t> buffer;
	const int mipsize = in.ReadMinimap(buffer, miplevel);

	// Do stuff
	void* ret = (void*)imgbuf;
	unsigned short* colors = (unsigned short*)ret;

	unsigned char* temp = &buffer[0];

	const int numblocks = buffer.size()/8;
	for ( int i = 0; i < numblocks; i++ ) {
		unsigned short color0 = (*(unsigned short*)&temp[0]);
		unsigned short color1 = (*(unsigned short*)&temp[2]);
		unsigned int bits = (*(unsigned int*)&temp[4]);

		for ( int a = 0; a < 4; a++ ) {
			for ( int b = 0; b < 4; b++ ) {
				int x = 4*(i % ((mipsize+3)/4))+b;
				int y = 4*(i / ((mipsize+3)/4))+a;
				unsigned char code = bits & 0x3;
				bits >>= 2;

				if ( color0 > color1 ) {
					if ( code == 0 ) {
						colors[y*mipsize+x] = color0;
					}
					else if ( code == 1 ) {
						colors[y*mipsize+x] = color1;
					}
					else if ( code == 2 ) {
						colors[y*mipsize+x] = PACKRGB((2*RED_RGB565(color0)+RED_RGB565(color1))/3, (2*GREEN_RGB565(color0)+GREEN_RGB565(color1))/3, (2*BLUE_RGB565(color0)+BLUE_RGB565(color1))/3);
					}
					else {
						colors[y*mipsize+x] = PACKRGB((2*RED_RGB565(color1)+RED_RGB565(color0))/3, (2*GREEN_RGB565(color1)+GREEN_RGB565(color0))/3, (2*BLUE_RGB565(color1)+BLUE_RGB565(color0))/3);
					}
				}
				else {
					if ( code == 0 ) {
						colors[y*mipsize+x] = color0;
					}
					else if ( code == 1 ) {
						colors[y*mipsize+x] = color1;
					}
					else if ( code == 2 ) {
						colors[y*mipsize+x] = PACKRGB((RED_RGB565(color0)+RED_RGB565(color1))/2, (GREEN_RGB565(color0)+GREEN_RGB565(color1))/2, (BLUE_RGB565(color0)+BLUE_RGB565(color1))/2);
					}
					else {
						colors[y*mipsize+x] = 0;
					}
				}
			}
		}
		temp += 8;
	}
	return (void*)ret;
}

/**
 * @brief Retrieves a minimap image for a map.
 * @param filename The name of the map, including extension.
 * @param miplevel Which miplevel of the minimap to extract from the file.
 * Set miplevel to 0 to get the largest, 1024x1024 minimap. Each increment
 * divides the width and height by 2. The maximum miplevel is 8, resulting in a
 * 4x4 image.
 * @return A pointer to a static memory area containing the minimap as a 16 bit
 * packed RGB-565 (MSB to LSB: 5 bits red, 6 bits green, 5 bits blue) linear
 * bitmap on success; NULL on error.
 *
 * An example usage would be GetMinimap("SmallDivide.smf", 2).
 * This would return a 16 bit packed RGB-565 256x256 (= 1024/2^2) bitmap.
 */
EXPORT(void*) GetMinimap(const char* filename, int miplevel)
{
	try {
		CheckInit();
		CheckNullOrEmpty(filename);

		if (miplevel < 0 || miplevel > 8)
			throw std::out_of_range("Miplevel must be between 0 and 8 (inclusive) in GetMinimap.");

		const string mapName = filename;
		ScopedMapLoader mapLoader(mapName);

		const string extension = mapName.substr(mapName.length() - 3);

		void* ret = NULL;

		if (extension == "smf") {
			ret = GetMinimapSMF(mapName, miplevel);
		} else if (extension == "sm3") {
			ret = GetMinimapSM3(mapName, miplevel);
		}

		return ret;
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves dimensions of infomap for a map.
 * @param filename The name of the map, including extension.
 * @param name     Of which infomap to retrieve the dimensions.
 * @param width    This is set to the width of the infomap, or 0 on error.
 * @param height   This is set to the height of the infomap, or 0 on error.
 * @return Non-zero when the infomap was found with a non-zero size; zero on error.
 * @see GetInfoMap
 */
EXPORT(int) GetInfoMapSize(const char* filename, const char* name, int* width, int* height)
{
	try {
		CheckInit();
		CheckNullOrEmpty(filename);
		CheckNullOrEmpty(name);
		CheckNull(width);
		CheckNull(height);

		ScopedMapLoader mapLoader(filename);
		CSmfMapFile file(filename);
		MapBitmapInfo bmInfo = file.GetInfoMapSize(name);

		*width = bmInfo.width;
		*height = bmInfo.height;

		return bmInfo.width > 0;
	}
	UNITSYNC_CATCH_BLOCKS;

	if (width)  *width  = 0;
	if (height) *height = 0;

	return 0;
}


/**
 * @brief Retrieves infomap data of a map.
 * @param filename The name of the map, including extension.
 * @param name     Which infomap to extract from the file.
 * @param data     Pointer to memory location with enough room to hold the infomap data.
 * @param typeHint One of bm_grayscale_8 (or 1) and bm_grayscale_16 (or 2).
 * @return Non-zero if the infomap was successfully extracted (and optionally
 * converted), or zero on error (map wasn't found, infomap wasn't found, or
 * typeHint could not be honoured.)
 *
 * This function extracts an infomap from a map. This can currently be one of:
 * "height", "metal", "grass", "type". The heightmap is natively in 16 bits per
 * pixel, the others are in 8 bits pixel. Using typeHint one can give a hint to
 * this function to convert from one format to another. Currently only the
 * conversion from 16 bpp to 8 bpp is implemented.
 */
EXPORT(int) GetInfoMap(const char* filename, const char* name, void* data, int typeHint)
{
	try {
		CheckInit();
		CheckNullOrEmpty(filename);
		CheckNullOrEmpty(name);
		CheckNull(data);

		string n = name;
		ScopedMapLoader mapLoader(filename);
		CSmfMapFile file(filename);
		int actualType = (n == "height" ? bm_grayscale_16 : bm_grayscale_8);

		if (actualType == typeHint) {
			return file.ReadInfoMap(n, data);
		}
		else if (actualType == bm_grayscale_16 && typeHint == bm_grayscale_8) {
			// convert from 16 bits per pixel to 8 bits per pixel
			MapBitmapInfo bmInfo = file.GetInfoMapSize(name);
			const int size = bmInfo.width * bmInfo.height;
			if (size <= 0) return 0;

			unsigned short* temp = new unsigned short[size];
			if (!file.ReadInfoMap(n, temp)) {
				delete[] temp;
				return 0;
			}

			const unsigned short* inp = temp;
			const unsigned short* inp_end = temp + size;
			unsigned char* outp = (unsigned char*) data;
			for (; inp < inp_end; ++inp, ++outp) {
				*outp = *inp >> 8;
			}
			delete[] temp;
			return 1;
		}
		else if (actualType == bm_grayscale_8 && typeHint == bm_grayscale_16) {
			throw content_error("converting from 8 bits per pixel to 16 bits per pixel is unsupported");
		}
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


//////////////////////////
//////////////////////////

vector<CArchiveScanner::ModData> modData;


/**
 * @brief Retrieves the number of mods available
 * @return int Zero on error; The number of mods available on success
 * @see GetMapCount
 */
EXPORT(int) GetPrimaryModCount()
{
	try {
		CheckInit();

		modData = archiveScanner->GetPrimaryMods();
		return modData.size();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Retrieves the name of this mod
 * @param index The mods index/id
 * @return NULL on error; The mods name on success
 *
 * Returns the name of the mod usually found in modinfo.tdf.
 * Be sure you've made a call to GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModName(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		string x = modData[index].name;
		return GetStr(x);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves the shortened name of this mod
 * @param index The mods index/id
 * @return NULL on error; The mods abbrieviated name on success
 *
 * Returns the shortened name of the mod usually found in modinfo.tdf.
 * Be sure you've made a call GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModShortName(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		string x = modData[index].shortName;
		return GetStr(x);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves the version string of this mod
 * @param index The mods index/id
 * @return NULL on error; The mods version string on success
 *
 * Returns value of the mutator tag for the specified mod usually found in modinfo.tdf.
 * Be sure you've made a call to GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModVersion(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		string x = modData[index].version;
		return GetStr(x);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves the mutator name of this mod
 * @param index The mods index/id
 * @return NULL on error; The mods mutator name on success
 *
 * Returns value of the mutator tag for the specified mod usually found in modinfo.tdf.
 * Be sure you've made a call to GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModMutator(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		string x = modData[index].mutator;
		return GetStr(x);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves the game name of this mod
 * @param index The mods index/id
 * @return NULL on error; The mods game name on success
 *
 * Returns the name of the game this mod belongs to usually found in modinfo.tdf.
 * Be sure you've made a call to GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModGame(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		string x = modData[index].game;
		return GetStr(x);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves the short game name of this mod
 * @param index The mods index/id
 * @return NULL on error; The mods abbrieviated game name on success
 *
 * Returns the abbrieviated name of the game this mod belongs to usually found in modinfo.tdf.
 * Be sure you've made a call to GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModShortGame(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		string x = modData[index].shortGame;
		return GetStr(x);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves the description of this mod
 * @param index The mods index/id
 * @return NULL on error; The mods description on success
 *
 * Returns a description for the specified mod usually found in modinfo.tdf.
 * Be sure you've made a call to GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModDescription(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		string x = modData[index].description;
		return GetStr(x);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieves the mod's first/primary archive
 * @param index The mods index/id
 * @return NULL on error; The mods primary archive on success
 *
 * Returns the name of the primary archive of the mod.
 * Be sure you've made a call to GetPrimaryModCount() prior to using this.
 */
EXPORT(const char*) GetPrimaryModArchive(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		return GetStr(modData[index].dependencies[0]);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


vector<string> primaryArchives;

/**
 * @brief Retrieves the number of archives a mod requires
 * @param index The index of the mod
 * @return Zero on error; the number of archives this mod depends on otherwise
 *
 * This is used to get the entire list of archives that a mod requires.
 * Call GetPrimaryModArchiveCount() with selected mod first to get number of
 * archives, and then use GetPrimaryModArchiveList() for 0 to count-1 to get the
 * name of each archive.  In code:
 *		@code
 *		int count = GetPrimaryModArchiveCount(mod_index);
 *		for (int arnr = 0; arnr < count; ++arnr) {
 *			printf("primary mod archive: %s\n", GetPrimaryModArchiveList(arnr));
 *		}
 *		@endcode
 */
EXPORT(int) GetPrimaryModArchiveCount(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		primaryArchives = archiveScanner->GetArchives(modData[index].dependencies[0]);
		return primaryArchives.size();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Retrieves the name of the current mod's archive.
 * @param archiveNr The archive's index/id.
 * @return NULL on error; the name of the archive on success
 * @see GetPrimaryModArchiveCount
 */
EXPORT(const char*) GetPrimaryModArchiveList(int archiveNr)
{
	try {
		CheckInit();
		CheckBounds(archiveNr, primaryArchives.size());

		logOutput.Print(LOG_UNITSYNC, "primary mod archive list: %s\n", primaryArchives[archiveNr].c_str());
		return GetStr(primaryArchives[archiveNr]);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief The reverse of GetPrimaryModName()
 * @param name The name of the mod
 * @return -1 if the mod can not be found; the index of the mod otherwise
 */
EXPORT(int) GetPrimaryModIndex(const char* name)
{
	try {
		CheckInit();

		string n(name);
		for (unsigned i = 0; i < modData.size(); ++i) {
			if (modData[i].name == n)
				return i;
		}
	}
	UNITSYNC_CATCH_BLOCKS;

	// if it returns -1, make sure you call GetPrimaryModCount before GetPrimaryModIndex.
	return -1;
}


/**
 * @brief Get checksum of mod
 * @param index The mods index/id
 * @return Zero on error; the checksum on success.
 * @see GetMapChecksum
 */
EXPORT(unsigned int) GetPrimaryModChecksum(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modData.size());

		return archiveScanner->GetModChecksum(GetPrimaryModArchive(index));
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Get checksum of mod given the mod's name
 * @param name The name of the mod
 * @return Zero on error; the checksum on success.
 * @see GetMapChecksum
 */
EXPORT(unsigned int) GetPrimaryModChecksumFromName(const char* name)
{
	try {
		CheckInit();

		return archiveScanner->GetModChecksum(archiveScanner->ModNameToModArchive(name));
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


//////////////////////////
//////////////////////////

/**
 * @brief Retrieve the number of available sides
 * @return Zero on error; the number of sides on success
 *
 * This function parses the mod's side data, and returns the number of sides
 * available. Be sure to map the mod into the VFS using AddArchive() or
 * AddAllArchives() prior to using this function.
 */
EXPORT(int) GetSideCount()
{
	try {
		CheckInit();

		if (!sideParser.Load()) {
			throw content_error("failed: " + sideParser.GetErrorLog());
		}
		return sideParser.GetCount();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Retrieve a side's name
 * @return NULL on error; the side's name on success
 *
 * Be sure you've made a call to GetSideCount() prior to using this.
 */
EXPORT(const char*) GetSideName(int side)
{
	try {
		CheckInit();
		CheckBounds(side, sideParser.GetCount());

		// the full case name  (not the lowered version)
		return GetStr(sideParser.GetCaseName(side));
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve a side's default starting unit
 * @return NULL on error; the side's starting unit name on success
 *
 * Be sure you've made a call to GetSideCount() prior to using this.
 */
EXPORT(const char*) GetSideStartUnit(int side)
{
	try {
		CheckInit();
		CheckBounds(side, sideParser.GetCount());

		return GetStr(sideParser.GetStartUnit(side));
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


//////////////////////////
//////////////////////////


static std::vector<Option> options;
static std::set<std::string> optionsSet;

static void ParseOptions(const string& fileName,
                         const string& fileModes,
                         const string& accessModes,
                         const string& mapName = "")
{
	parseOptions(options, fileName, fileModes, accessModes, mapName,
			&optionsSet, &LOG_UNITSYNC);
}


static void CheckOptionIndex(int optIndex)
{
	CheckInit();
	CheckBounds(optIndex, options.size());
}

static void CheckOptionType(int optIndex, int type)
{
	CheckOptionIndex(optIndex);

	if (options[optIndex].typeCode != type)
		throw std::invalid_argument("wrong option type");
}


/**
 * @brief Retrieve the number of map options available
 * @param name the name of the map
 * @return Zero on error; the number of map options available on success
 */
EXPORT(int) GetMapOptionCount(const char* name)
{
	try {
		CheckInit();
		CheckNullOrEmpty(name);

		ScopedMapLoader mapLoader(name);

		options.clear();
		optionsSet.clear();

		ParseOptions("MapOptions.lua", SPRING_VFS_MAP, SPRING_VFS_MAP, name);

		optionsSet.clear();

		return options.size();
	}
	UNITSYNC_CATCH_BLOCKS;

	options.clear();
	optionsSet.clear();

	return 0;
}


/**
 * @brief Retrieve the number of mod options available
 * @return Zero on error; the number of mod options available on success
 *
 * Be sure to map the mod into the VFS using AddArchive() or AddAllArchives()
 * prior to using this function.
 */
EXPORT(int) GetModOptionCount()
{
	try {
		CheckInit();

		options.clear();
		optionsSet.clear();

		// EngineOptions must be read first, so accidentally "overloading" engine
		// options with mod options with identical names is not possible.
		// Both files are now optional
		try {
			ParseOptions("EngineOptions.lua", SPRING_VFS_MOD_BASE, SPRING_VFS_MOD_BASE);
		}
		UNITSYNC_CATCH_BLOCKS;
		try {
			ParseOptions("ModOptions.lua", SPRING_VFS_MOD, SPRING_VFS_MOD);
		}
		UNITSYNC_CATCH_BLOCKS;

		optionsSet.clear();

		return options.size();
	}
	UNITSYNC_CATCH_BLOCKS;

	// Failed to load engineoptions
	options.clear();
	optionsSet.clear();

	return 0;
}

EXPORT(int) GetCustomOptionCount(const char* filename)
{
	try {
		CheckInit();

		options.clear();
		optionsSet.clear();

		try {
			ParseOptions(filename, SPRING_VFS_ZIP, SPRING_VFS_ZIP);
		}
		UNITSYNC_CATCH_BLOCKS;

		optionsSet.clear();

		return options.size();
	}
	UNITSYNC_CATCH_BLOCKS;

	// Failed to load custom options file
	options.clear();
	optionsSet.clear();

	return 0;
}

//////////////////////////
//////////////////////////

static std::vector< std::vector<InfoItem> > luaAIInfos;

static void GetLuaAIInfo()
{
	luaAIInfos = luaAIImplHandler.LoadInfos();
}


/**
 * @brief Retrieve the number of LUA AIs available
 * @return Zero on error; the number of LUA AIs otherwise
 *
 * Usually LUA AIs are shipped inside a mod, so be sure to map the mod into
 * the VFS using AddArchive() or AddAllArchives() prior to using this function.
 */
static int GetNumberOfLuaAIs()
{
	try {
		CheckInit();

		GetLuaAIInfo();
		return luaAIInfos.size();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


//////////////////////////
//////////////////////////



// Updated on every call to GetSkirmishAICount
static vector<std::string> skirmishAIDataDirs;

EXPORT(int) GetSkirmishAICount() {

	try {
		CheckInit();

		skirmishAIDataDirs.clear();

		std::vector<std::string> dataDirs_tmp =
				filesystem.FindDirsInDirectSubDirs(SKIRMISH_AI_DATA_DIR);

		// filter out dirs not containing an AIInfo.lua file
		std::vector<std::string>::const_iterator i;
		for (i = dataDirs_tmp.begin(); i != dataDirs_tmp.end(); ++i) {
			const std::string& possibleDataDir = *i;
			vector<std::string> infoFile = CFileHandler::FindFiles(
					possibleDataDir, "AIInfo.lua");
			if (infoFile.size() > 0) {
				skirmishAIDataDirs.push_back(possibleDataDir);
			}
		}

		sort(skirmishAIDataDirs.begin(), skirmishAIDataDirs.end());

		int luaAIs = GetNumberOfLuaAIs();

//logOutput.Print(LOG_UNITSYNC, "GetSkirmishAICount: luaAIs: %i / skirmishAIs: %u", luaAIs, skirmishAIDataDirs.size());
		return skirmishAIDataDirs.size() + luaAIs;
	}
	UNITSYNC_CATCH_BLOCKS;

	return 0;
}


static std::vector<InfoItem> info;
static std::set<std::string> infoSet;

static void ParseInfo(const std::string& fileName,
                      const std::string& fileModes,
                      const std::string& accessModes)
{
	parseInfo(info, fileName, fileModes, accessModes, &infoSet, &LOG_UNITSYNC);
}

static void CheckSkirmishAIIndex(int aiIndex)
{
	CheckInit();
	int numSkirmishAIs = skirmishAIDataDirs.size() + luaAIInfos.size();
	CheckBounds(aiIndex, numSkirmishAIs);
}

static bool IsLuaAIIndex(int aiIndex) {
	return (((unsigned int) aiIndex) >= skirmishAIDataDirs.size());
}

static int ToPureLuaAIIndex(int aiIndex) {
	return (aiIndex - skirmishAIDataDirs.size());
}

static int loadedLuaAIIndex = -1;

EXPORT(int) GetSkirmishAIInfoCount(int aiIndex) {

	try {
		CheckSkirmishAIIndex(aiIndex);

		if (IsLuaAIIndex(aiIndex)) {
			loadedLuaAIIndex = aiIndex;
			return luaAIInfos[ToPureLuaAIIndex(loadedLuaAIIndex)].size();
		} else {
			loadedLuaAIIndex = -1;

			info.clear();
			infoSet.clear();

			ParseInfo(skirmishAIDataDirs[aiIndex] + "/AIInfo.lua",
					SPRING_VFS_RAW, SPRING_VFS_RAW);

			infoSet.clear();

			return (int)info.size();
		}
	}
	UNITSYNC_CATCH_BLOCKS;

	info.clear();

	return 0;
}

static void CheckSkirmishAIInfoIndex(int infoIndex)
{
	CheckInit();
	if (loadedLuaAIIndex >= 0) {
		CheckBounds(infoIndex, luaAIInfos[ToPureLuaAIIndex(loadedLuaAIIndex)].size());
	} else {
		CheckBounds(infoIndex, info.size());
	}
}

EXPORT(const char*) GetInfoKey(int infoIndex) {

	try {
		CheckSkirmishAIInfoIndex(infoIndex);
		if (loadedLuaAIIndex >= 0) {
			return GetStr(luaAIInfos[ToPureLuaAIIndex(loadedLuaAIIndex)][infoIndex].key);
		} else {
			return GetStr(info[infoIndex].key);
		}
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}
EXPORT(const char*) GetInfoValue(int infoIndex) {

	try {
		CheckSkirmishAIInfoIndex(infoIndex);
		if (loadedLuaAIIndex >= 0) {
			return GetStr(luaAIInfos[ToPureLuaAIIndex(loadedLuaAIIndex)][infoIndex].value);
		} else {
			return GetStr(info[infoIndex].value);
		}
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}
EXPORT(const char*) GetInfoDescription(int infoIndex) {

	try {
		CheckSkirmishAIInfoIndex(infoIndex);
		if (loadedLuaAIIndex >= 0) {
			return GetStr(luaAIInfos[ToPureLuaAIIndex(loadedLuaAIIndex)][infoIndex].desc);
		} else {
			return GetStr(info[infoIndex].desc);
		}
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}

EXPORT(int) GetSkirmishAIOptionCount(int aiIndex) {

	try {
		CheckSkirmishAIIndex(aiIndex);

		if (IsLuaAIIndex(aiIndex)) {
			// lua AIs do not have options
			return 0;
		} else {
			options.clear();
			optionsSet.clear();

			ParseOptions(skirmishAIDataDirs[aiIndex] + "/AIOptions.lua",
					SPRING_VFS_RAW, SPRING_VFS_RAW);

			optionsSet.clear();

			GetLuaAIInfo();

			return options.size();
		}
	}
	UNITSYNC_CATCH_BLOCKS;

	options.clear();
	optionsSet.clear();

	return 0;
}


// Common Options Parameters

/**
 * @brief Retrieve an option's key
 * @param optIndex option index/id
 * @return NULL on error; the option's key on success
 *
 * The key of an option is the name it should be given in the start script's
 * MODOPTIONS or MAPOPTIONS section.
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionKey(int optIndex)
{
	try {
		CheckOptionIndex(optIndex);
		return GetStr(options[optIndex].key);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an option's scope
 * @param optIndex option index/id
 * @return NULL on error; the option's scope on success
 *
 * Will be either "global" (default), "player", "team" or "allyteam"
 */
EXPORT(const char*) GetOptionScope(int optIndex)
{
	try {
		CheckOptionIndex(optIndex);
		return GetStr(options[optIndex].scope);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}

/**
 * @brief Retrieve an option's name
 * @param optIndex option index/id
 * @return NULL on error; the option's user visible name on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionName(int optIndex)
{
	try {
		CheckOptionIndex(optIndex);
		return GetStr(options[optIndex].name);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an option's section
 * @param optIndex option index/id
 * @return NULL on error; the option's section name on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionSection(int optIndex)
{
	try {
		CheckOptionIndex(optIndex);
		return GetStr(options[optIndex].section);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an option's style
 * @param optIndex option index/id
 * @return NULL on error; the option's style on success
 *
 * The format of an option style string is currently undecided.
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionStyle(int optIndex)
{
	try {
		CheckOptionIndex(optIndex);
		return GetStr(options[optIndex].style);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an option's description
 * @param optIndex option index/id
 * @return NULL on error; the option's description on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionDesc(int optIndex)
{
	try {
		CheckOptionIndex(optIndex);
		return GetStr(options[optIndex].desc);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an option's type
 * @param optIndex option index/id
 * @return opt_error on error; the option's type on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(int) GetOptionType(int optIndex)
{
	try {
		CheckOptionIndex(optIndex);
		return options[optIndex].typeCode;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


// Bool Options

/**
 * @brief Retrieve an opt_bool option's default value
 * @param optIndex option index/id
 * @return Zero on error; the option's default value (0 or 1) on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(int) GetOptionBoolDef(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_bool);
		return options[optIndex].boolDef ? 1 : 0;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


// Number Options

/**
 * @brief Retrieve an opt_number option's default value
 * @param optIndex option index/id
 * @return Zero on error; the option's default value on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(float) GetOptionNumberDef(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_number);
		return options[optIndex].numberDef;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0.0f;
}


/**
 * @brief Retrieve an opt_number option's minimum value
 * @param optIndex option index/id
 * @return -1.0e30 on error; the option's minimum value on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(float) GetOptionNumberMin(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_number);
		return options[optIndex].numberMin;
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1.0e30f; // FIXME ?
}


/**
 * @brief Retrieve an opt_number option's maximum value
 * @param optIndex option index/id
 * @return +1.0e30 on error; the option's maximum value on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(float) GetOptionNumberMax(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_number);
		return options[optIndex].numberMax;
	}
	UNITSYNC_CATCH_BLOCKS;
	return +1.0e30f; // FIXME ?
}


/**
 * @brief Retrieve an opt_number option's step value
 * @param optIndex option index/id
 * @return Zero on error; the option's step value on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(float) GetOptionNumberStep(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_number);
		return options[optIndex].numberStep;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0.0f;
}


// String Options

/**
 * @brief Retrieve an opt_string option's default value
 * @param optIndex option index/id
 * @return NULL on error; the option's default value on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionStringDef(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_string);
		return GetStr(options[optIndex].stringDef);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an opt_string option's maximum length
 * @param optIndex option index/id
 * @return Zero on error; the option's maximum length on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(int) GetOptionStringMaxLen(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_string);
		return options[optIndex].stringMaxLen;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


// List Options

/**
 * @brief Retrieve an opt_list option's number of available items
 * @param optIndex option index/id
 * @return Zero on error; the option's number of available items on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(int) GetOptionListCount(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_list);
		return options[optIndex].list.size();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Retrieve an opt_list option's default value
 * @param optIndex option index/id
 * @return NULL on error; the option's default value (list item key) on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionListDef(int optIndex)
{
	try {
		CheckOptionType(optIndex, opt_list);
		return GetStr(options[optIndex].listDef);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an opt_list option item's key
 * @param optIndex option index/id
 * @param itemIndex list item index/id
 * @return NULL on error; the option item's key (list item key) on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionListItemKey(int optIndex, int itemIndex)
{
	try {
		CheckOptionType(optIndex, opt_list);
		const vector<OptionListItem>& list = options[optIndex].list;
		CheckBounds(itemIndex, list.size());
		return GetStr(list[itemIndex].key);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an opt_list option item's name
 * @param optIndex option index/id
 * @param itemIndex list item index/id
 * @return NULL on error; the option item's name on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionListItemName(int optIndex, int itemIndex)
{
	try {
		CheckOptionType(optIndex, opt_list);
		const vector<OptionListItem>& list = options[optIndex].list;
		CheckBounds(itemIndex, list.size());
		return GetStr(list[itemIndex].name);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


/**
 * @brief Retrieve an opt_list option item's description
 * @param optIndex option index/id
 * @param itemIndex list item index/id
 * @return NULL on error; the option item's description on success
 *
 * Be sure you've made a call to either GetMapOptionCount()
 * or GetModOptionCount() prior to using this.
 */
EXPORT(const char*) GetOptionListItemDesc(int optIndex, int itemIndex)
{
	try {
		CheckOptionType(optIndex, opt_list);
		const vector<OptionListItem>& list = options[optIndex].list;
		CheckBounds(itemIndex, list.size());
		return GetStr(list[itemIndex].desc);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


//////////////////////////
//////////////////////////

static vector<string> modValidMaps;


static int LuaGetMapList(lua_State* L)
{
	lua_newtable(L);
	const int mapCount = GetMapCount();
	for (int i = 0; i < mapCount; i++) {
		lua_pushnumber(L, i + 1);
		lua_pushstring(L, GetMapName(i));
		lua_rawset(L, -3);
	}
	return 1;
}


static void LuaPushNamedString(lua_State* L,
                              const string& key, const string& value)
{
	lua_pushstring(L, key.c_str());
	lua_pushstring(L, value.c_str());
	lua_rawset(L, -3);
}


static void LuaPushNamedNumber(lua_State* L, const string& key, float value)
{
	lua_pushstring(L, key.c_str());
	lua_pushnumber(L, value);
	lua_rawset(L, -3);
}


static int LuaGetMapInfo(lua_State* L)
{
	const string mapName = luaL_checkstring(L, 1);

	MapInfo mi;
	char auth[256];
	char desc[256];
	mi.author = auth;
 	mi.author[0] = 0;
	mi.description = desc;
	mi.description[0] = 0;

	if (!GetMapInfoEx(mapName.c_str(), &mi, 1)) {
		logOutput.Print(LOG_UNITSYNC, "LuaGetMapInfo: _GetMapInfoEx(\"%s\") failed", mapName.c_str());
		return 0;
	}

	lua_newtable(L);

	LuaPushNamedString(L, "author", mi.author);
	LuaPushNamedString(L, "desc",   mi.description);

	LuaPushNamedNumber(L, "tidal",   mi.tidalStrength);
	LuaPushNamedNumber(L, "gravity", mi.gravity);
	LuaPushNamedNumber(L, "metal",   mi.maxMetal);
	LuaPushNamedNumber(L, "windMin", mi.minWind);
	LuaPushNamedNumber(L, "windMax", mi.maxWind);
	LuaPushNamedNumber(L, "mapX",    mi.width);
	LuaPushNamedNumber(L, "mapY",    mi.height);
	LuaPushNamedNumber(L, "extractorRadius", mi.extractorRadius);

	lua_pushstring(L, "startPos");
	lua_newtable(L);
	for (int i = 0; i < mi.posCount; i++) {
		lua_pushnumber(L, i + 1);
		lua_newtable(L);
		LuaPushNamedNumber(L, "x", mi.positions[i].x);
		LuaPushNamedNumber(L, "z", mi.positions[i].z);
		lua_rawset(L, -3);
	}
	lua_rawset(L, -3);

	return 1;
}


/**
 * @brief Retrieve the number of valid maps for the current mod
 * @return 0 on error; the number of valid maps on success
 *
 * A return value of 0 means that any map can be selected.
 * Be sure to map the mod into the VFS using AddArchive() or AddAllArchives()
 * prior to using this function.
 */
EXPORT(int) GetModValidMapCount()
{
	try {
		CheckInit();

		modValidMaps.clear();

		LuaParser luaParser("ValidMaps.lua", SPRING_VFS_MOD, SPRING_VFS_MOD);
		luaParser.GetTable("Spring");
		luaParser.AddFunc("GetMapList", LuaGetMapList);
		luaParser.AddFunc("GetMapInfo", LuaGetMapInfo);
		luaParser.EndTable();
		if (!luaParser.Execute()) {
			throw content_error("luaParser.Execute() failed: " + luaParser.GetErrorLog());
		}

		const LuaTable root = luaParser.GetRoot();
		if (!root.IsValid()) {
			throw content_error("root table invalid");
		}

		for (int index = 1; root.KeyExists(index); index++) {
			const string map = root.GetString(index, "");
			if (!map.empty()) {
				modValidMaps.push_back(map);
			}
		}

		return modValidMaps.size();
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Retrieve the name of a map valid for the current mod
 * @return NULL on error; the name of the map on success
 *
 * Map names should be complete  (including the .smf or .sm3 extension.)
 * Be sure you've made a call to GetModValidMapCount() prior to using this.
 */
EXPORT(const char*) GetModValidMap(int index)
{
	try {
		CheckInit();
		CheckBounds(index, modValidMaps.size());
		return GetStr(modValidMaps[index]);
	}
	UNITSYNC_CATCH_BLOCKS;
	return NULL;
}


//////////////////////////
//////////////////////////

static map<int, CFileHandler*> openFiles;
static int nextFile = 0;
static vector<string> curFindFiles;

static void CheckFileHandle(int handle)
{
	CheckInit();

	if (openFiles.find(handle) == openFiles.end())
		throw content_error("Unregistered handle. Pass a handle returned by OpenFileVFS.");
}


/**
 * @brief Open a file from the VFS
 * @param name the name of the file
 * @return Zero on error; a non-zero file handle on success.
 *
 * The returned file handle is needed for subsequent calls to CloseFileVFS(),
 * ReadFileVFS() and FileSizeVFS().
 *
 * Map the wanted archives into the VFS with AddArchive() or AddAllArchives()
 * before using this function.
 */
EXPORT(int) OpenFileVFS(const char* name)
{
	try {
		CheckInit();
		CheckNullOrEmpty(name);

		logOutput.Print(LOG_UNITSYNC, "openfilevfs: %s\n", name);

		CFileHandler* fh = new CFileHandler(name);
		if (!fh->FileExists()) {
			delete fh;
			throw content_error("File '" + string(name) + "' does not exist");
		}

		nextFile++;
		openFiles[nextFile] = fh;

		return nextFile;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Close a file in the VFS
 * @param handle the file handle as returned by OpenFileVFS()
 */
EXPORT(void) CloseFileVFS(int handle)
{
	try {
		CheckFileHandle(handle);

		logOutput.Print(LOG_UNITSYNC, "closefilevfs: %d\n", handle);
		delete openFiles[handle];
		openFiles.erase(handle);
	}
	UNITSYNC_CATCH_BLOCKS;
}

/**
 * @brief Read some data from a file in the VFS
 * @param handle the file handle as returned by OpenFileVFS()
 * @param buf output buffer, must be at least length bytes
 * @param length how many bytes to read from the file
 * @return -1 on error; the number of bytes read on success
 * (if this is less than length you reached the end of the file.)
 */
EXPORT(int) ReadFileVFS(int handle, void* buf, int length)
{
	try {
		CheckFileHandle(handle);
		CheckNull(buf);
		CheckPositive(length);

		logOutput.Print(LOG_UNITSYNC, "readfilevfs: %d\n", handle);
		CFileHandler* fh = openFiles[handle];
		return fh->Read(buf, length);
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1;
}


/**
 * @brief Retrieve size of a file in the VFS
 * @param handle the file handle as returned by OpenFileVFS()
 * @return -1 on error; the size of the file on success
 */
EXPORT(int) FileSizeVFS(int handle)
{
	try {
		CheckFileHandle(handle);

		logOutput.Print(LOG_UNITSYNC, "filesizevfs: %d\n", handle);
		CFileHandler* fh = openFiles[handle];
		return fh->FileSize();
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1;
}

/**
 * Does not currently support more than one call at a time.
 * (a new call to initfind destroys data from previous ones)
 * pass the returned handle to findfiles to get the results
 */
EXPORT(int) InitFindVFS(const char* pattern)
{
	try {
		CheckInit();
		CheckNullOrEmpty(pattern);

		string path = filesystem.GetDirectory(pattern);
		string patt = filesystem.GetFilename(pattern);
		logOutput.Print(LOG_UNITSYNC, "initfindvfs: %s\n", pattern);
		curFindFiles = CFileHandler::FindFiles(path, patt);
		return 0;
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1;
}

/**
 * Does not currently support more than one call at a time.
 * (a new call to initfind destroys data from previous ones)
 * pass the returned handle to findfiles to get the results
 */
EXPORT(int) InitDirListVFS(const char* path, const char* pattern, const char* modes)
{
	try {
		CheckInit();

		if (path    == NULL) { path = "";              }
		if (modes   == NULL) { modes = SPRING_VFS_ALL; }
		if (pattern == NULL) { pattern = "*";          }
		logOutput.Print(LOG_UNITSYNC, "InitDirListVFS: '%s' '%s' '%s'\n", path, pattern, modes);
		curFindFiles = CFileHandler::DirList(path, pattern, modes);
		return 0;
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1;
}

/**
 * Does not currently support more than one call at a time.
 * (a new call to initfind destroys data from previous ones)
 * pass the returned handle to findfiles to get the results
 */
EXPORT(int) InitSubDirsVFS(const char* path, const char* pattern, const char* modes)
{
	try {
		CheckInit();
		if (path    == NULL) { path = "";              }
		if (modes   == NULL) { modes = SPRING_VFS_ALL; }
		if (pattern == NULL) { pattern = "*";          }
		logOutput.Print(LOG_UNITSYNC, "InitSubDirsVFS: '%s' '%s' '%s'\n", path, pattern, modes);
		curFindFiles = CFileHandler::SubDirs(path, pattern, modes);
		return 0;
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1;
}

// On first call, pass handle from initfind. pass the return value of this function on subsequent calls
// until 0 is returned. size should be set to max namebuffer size on call
EXPORT(int) FindFilesVFS(int handle, char* nameBuf, int size)
{
	try {
		CheckInit();
		CheckNull(nameBuf);
		CheckPositive(size);

		logOutput.Print(LOG_UNITSYNC, "findfilesvfs: %d\n", handle);
		if ((unsigned)handle >= curFindFiles.size())
			return 0;
		safe_strzcpy(nameBuf, curFindFiles[handle], size);
		return handle + 1;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


//////////////////////////
//////////////////////////

static map<int, CArchiveBase*> openArchives;
static int nextArchive = 0;


static void CheckArchiveHandle(int handle)
{
	CheckInit();

	if (openArchives.find(handle) == openArchives.end())
		throw content_error("Unregistered handle. Pass a handle returned by OpenArchive.");
}


/**
 * @brief Open an archive
 * @param name the name of the archive (*.sdz, *.sd7, ...)
 * @return Zero on error; a non-zero archive handle on success.
 * @sa OpenArchiveType
 */
EXPORT(int) OpenArchive(const char* name)
{
	try {
		CheckInit();
		CheckNullOrEmpty(name);

		CArchiveBase* a = CArchiveFactory::OpenArchive(name);

		if (!a) {
			throw content_error("Archive '" + string(name) + "' could not be opened");
		}

		nextArchive++;
		openArchives[nextArchive] = a;
		return nextArchive;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Open an archive
 * @param name the name of the archive (*.sd7, *.sdz, *.sdd, *.ccx, *.hpi, *.ufo, *.gp3, *.gp4, *.swx)
 * @param type the type of the archive (sd7, 7z, sdz, zip, sdd, dir, ccx, hpi, ufo, gp3, gp4, swx)
 * @return Zero on error; a non-zero archive handle on success.
 * @sa OpenArchive
 *
 * The list of supported types and recognized extensions may change at any time.
 * (But this list will always be the same as the file types recognized by the engine.)
 *
 * This function is pointless, because OpenArchive() does the same and automatically
 * detects the file type based on it's extension.  Who added it anyway?
 */
EXPORT(int) OpenArchiveType(const char* name, const char* type)
{
	try {
		CheckInit();
		CheckNullOrEmpty(name);
		CheckNullOrEmpty(type);

		CArchiveBase* a = CArchiveFactory::OpenArchive(name, type);

		if (!a) {
			throw content_error("Archive '" + string(name) + "' could not be opened");
		}

		nextArchive++;
		openArchives[nextArchive] = a;
		return nextArchive;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Close an archive in the VFS
 * @param archive the archive handle as returned by OpenArchive()
 */
EXPORT(void) CloseArchive(int archive)
{
	try {
		CheckArchiveHandle(archive);

		delete openArchives[archive];
		openArchives.erase(archive);
	}
	UNITSYNC_CATCH_BLOCKS;
}


EXPORT(int) FindFilesArchive(int archive, int cur, char* nameBuf, int* size)
{
	try {
		CheckArchiveHandle(archive);
		CheckNull(nameBuf);
		CheckNull(size);

		CArchiveBase* a = openArchives[archive];

		logOutput.Print(LOG_UNITSYNC, "findfilesarchive: %d\n", archive);

		string name;
		int s;

		int ret = a->FindFiles(cur, &name, &s);
		strcpy(nameBuf, name.c_str()); // FIXME: oops, buffer overflow
		*size = s;
		return ret;
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Open an archive member
 * @param archive the archive handle as returned by OpenArchive()
 * @param name the name of the file
 * @return Zero on error; a non-zero file handle on success.
 *
 * The returned file handle is needed for subsequent calls to ReadArchiveFile(),
 * CloseArchiveFile() and SizeArchiveFile().
 */
EXPORT(int) OpenArchiveFile(int archive, const char* name)
{
	try {
		CheckArchiveHandle(archive);
		CheckNullOrEmpty(name);

		CArchiveBase* a = openArchives[archive];
		return a->OpenFile(name);
	}
	UNITSYNC_CATCH_BLOCKS;
	return 0;
}


/**
 * @brief Read some data from an archive member
 * @param archive the archive handle as returned by OpenArchive()
 * @param handle the file handle as returned by OpenArchiveFile()
 * @param buffer output buffer, must be at least numBytes bytes
 * @param numBytes how many bytes to read from the file
 * @return -1 on error; the number of bytes read on success
 * (if this is less than numBytes you reached the end of the file.)
 */
EXPORT(int) ReadArchiveFile(int archive, int handle, void* buffer, int numBytes)
{
	try {
		CheckArchiveHandle(archive);
		CheckNull(buffer);
		CheckPositive(numBytes);

		CArchiveBase* a = openArchives[archive];
		return a->ReadFile(handle, buffer, numBytes);
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1;
}


/**
 * @brief Close an archive member
 * @param archive the archive handle as returned by OpenArchive()
 * @param handle the file handle as returned by OpenArchiveFile()
 */
EXPORT(void) CloseArchiveFile(int archive, int handle)
{
	try {
		CheckArchiveHandle(archive);

		CArchiveBase* a = openArchives[archive];
		a->CloseFile(handle);
	}
	UNITSYNC_CATCH_BLOCKS;
}


/**
 * @brief Retrieve size of an archive member
 * @param archive the archive handle as returned by OpenArchive()
 * @param handle the file handle as returned by OpenArchiveFile()
 * @return -1 on error; the size of the file on success
 */
EXPORT(int) SizeArchiveFile(int archive, int handle)
{
	try {
		CheckArchiveHandle(archive);

		CArchiveBase* a = openArchives[archive];
		return a->FileSize(handle);
	}
	UNITSYNC_CATCH_BLOCKS;
	return -1;
}

//////////////////////////
//////////////////////////

char strBuf[STRBUF_SIZE];

//Just returning str.c_str() does not work
const char *GetStr(string str)
{
	//static char strBuf[STRBUF_SIZE];

	if (str.length() + 1 > STRBUF_SIZE) {
		sprintf(strBuf, "Increase STRBUF_SIZE (needs %d bytes)", str.length() + 1);
	}
	else {
		strcpy(strBuf, str.c_str());
	}

	return strBuf;
}

void PrintLoadMsg(const char* text)
{
}


//////////////////////////
//////////////////////////

EXPORT(void) SetSpringConfigFile(const char* filenameAsAbsolutePath)
{
	ConfigHandler::Instantiate(filenameAsAbsolutePath);
}

EXPORT(const char*) GetSpringConfigFile()
{
	return GetStr(configHandler->GetConfigFile());
}

static void CheckConfigHandler()
{
	if (!configHandler)
		throw std::logic_error("Unitsync config handler not initialized, check config source.");
}


/**
 * @brief get string from Spring configuration
 * @param name name of key to get
 * @param defValue default string value to use if key is not found, may not be NULL
 * @return string value
 */
EXPORT(const char*) GetSpringConfigString(const char* name, const char* defValue)
{
	try {
		CheckConfigHandler();
		string res = configHandler->GetString(name, defValue);
		return GetStr(res);
	}
	UNITSYNC_CATCH_BLOCKS;
	return defValue;
}

/**
 * @brief get integer from Spring configuration
 * @param name name of key to get
 * @param defValue default integer value to use if key is not found
 * @return integer value
 */
EXPORT(int) GetSpringConfigInt(const char* name, const int defValue)
{
	try {
		CheckConfigHandler();
		return configHandler->Get(name, defValue);
	}
	UNITSYNC_CATCH_BLOCKS;
	return defValue;
}

/**
 * @brief get float from Spring configuration
 * @param name name of key to get
 * @param defValue default float value to use if key is not found
 * @return float value
 */
EXPORT(float) GetSpringConfigFloat(const char* name, const float defValue)
{
	try {
		CheckConfigHandler();
		return configHandler->Get(name, defValue);
	}
	UNITSYNC_CATCH_BLOCKS;
	return defValue;
}

/**
 * @brief set string in Spring configuration
 * @param name name of key to set
 * @param value string value to set
 */
EXPORT(void) SetSpringConfigString(const char* name, const char* value)
{
	try {
		CheckConfigHandler();
		configHandler->SetString( name, value );
	}
	UNITSYNC_CATCH_BLOCKS;
}

/**
 * @brief set integer in Spring configuration
 * @param name name of key to set
 * @param value integer value to set
 */
EXPORT(void) SetSpringConfigInt(const char* name, const int value)
{
	try {
		CheckConfigHandler();
		configHandler->Set(name, value);
	}
	UNITSYNC_CATCH_BLOCKS;
}

/**
 * @brief set float in Spring configuration
 * @param name name of key to set
 * @param value float value to set
 */
EXPORT(void) SetSpringConfigFloat(const char* name, const float value)
{
	try {
		CheckConfigHandler();
		configHandler->Set(name, value);
	}
	UNITSYNC_CATCH_BLOCKS;
}

/** @} */

//////////////////////////
//////////////////////////

// Helper class for popping up a MessageBox only once

class CMessageOnce
{
	private:
		bool alreadyDone;

	public:
		CMessageOnce() : alreadyDone(false) {}
		void operator() (const string& msg)
		{
			if (alreadyDone) return;
			alreadyDone = true;
			logOutput.Print(LOG_UNITSYNC, "Message from DLL: %s\n", msg.c_str());
#ifdef WIN32
			MessageBox(NULL, msg.c_str(), "Message from DLL", MB_OK);
#endif
		}
};

#define DEPRECATED \
	static CMessageOnce msg; \
	msg(string(__FUNCTION__) + ": deprecated unitsync function called, please update your lobby client"); \
	SetLastError("deprecated unitsync function called")