File: main.cpp~

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

    This program is free software; you can redistribute it and/or modify        
    it under the terms of the GNU General Public License as published by        
    the Free Software Foundation; either version 2 of the License, or           
    (at your option) any later version.                                         
                                                                                
    This program is distributed in the hope that it will be useful,       
    but WITHOUT ANY WARRANTY; without even the implied warranty of              
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               
    GNU General Public License for more details.                
                                                                               
    You should have received a copy of the GNU General Public License           
    along with this program; if not, write to the Free Software                 
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA   
                                                                                
    Poul Sander
    Rævehjvej 36, V. 1111                                                    
    2800 Kgs. Lyngby
    DENMARK
    poul@poulsander.com 
    http://blockattack.sf.net     
*/

#define VERSION_NUMBER "version 1.3.1"

//If DEBUG is defined: AI info and FPS will be written to screen
//#define DEBUG

//If NETWORK id defined: enet will be used
#define NETWORK

//Macros to convert surfaces (for faster drawing)
#define CONVERT(n) tmp = SDL_DisplayFormat(n); SDL_FreeSurface(n); n = tmp
#define CONVERTA(n) tmp = SDL_DisplayFormatAlpha(n); SDL_FreeSurface(n); n = tmp

#include <iostream>
#include <stdlib.h>
#include <time.h>           //Used for srand()
#include <sstream>
#include <string>
#include "SDL.h"            //The SDL libary, used for most things
#include <SDL_mixer.h>      //Used for sound & music
#include <SDL_image.h>      //To load PNG images!
//#include "config.h"

//if SHAREDIR is not used we look in current directory
#ifndef SHAREDIR
#define SHAREDIR "./"
#endif

//enet things
#ifdef NETWORK
#include "enet/enet.h"
//#include "enet/list.h"
//#include "enet/protocol.h"
#endif
//enet things end

#include "SFont.h"          //Used to write on screen
#include "highscore.h"      //Stores highscores
#include "ReadKeyboard.h"   //Reads text from keyboard
#include "joypad.h"         //Used for joypads
#include "listFiles.h"	    //Used to show files on screen
#include "replay.h"			//Used for replays
#include <vector>

//Some definitions
//The game is divided in frames. FALLTIME means the blocks will fall one block every FRAMELENGTH*FALLTIME millisecond
#define FRAMELENGTH 50
#define HANGTIME 40
#define FALLTIME 20
//Don't change the following, they are fundamental and later some functions are hardcoded
#define BLOCKFALL 10000
#define BLOCKWAIT 100000
#define BLOCKHANG 1000
#define GARBAGE 1000000
#define CHAINPLACE 10000000
#define NUMBEROFCHAINS 100

//Animation lengths:
    #define READYTIME 500
    #define BOMBTIME 200
    #define CURSORTIME 200


using namespace std;	//remove it if you dare...
#ifdef SHAREDIR
char sharedir[] = SHAREDIR;
#endif

//All graphic in the game (as pointers):
SDL_Surface *background;    //Stores background
SDL_Surface *backgroundImage; //Stores the background image
int backgroundImageW, backgroundImageH; //size of background image
SDL_Surface *backBoard;     //Stores the background to the board
SDL_Surface *b1player;
SDL_Surface *b2players;
SDL_Surface *bVsMode;
SDL_Surface *bStageClear;
SDL_Surface *bPuzzle;
SDL_Surface *bNewGame;      //The New Game botton
SDL_Surface *bEndless;      //Endless button (sub to new)
SDL_Surface *bTimeTrial;    //Time trial button (sub to new)
SDL_Surface *bOptions;      //The Options botton
//new in 1.1.1
SDL_Surface *bConfigure;    //The configure button
SDL_Surface *bSelectPuzzle; //The Select Puzzle Button
SDL_Surface *bBack;         //The "Back" button
SDL_Surface *bForward;      //The "forward" button
//new in 1.1.1 end
//new in 1.1.2
SDL_Surface *iChainBack;
//new in 1.1.2 end (nota that iSmallFont has also been added)
//new in 1.2.0
SDL_Surface *bReplay;
SDL_Surface *bSave;
SDL_Surface *bLoad;
#ifdef NETWORK
SDL_Surface *bNetwork;
SDL_Surface *bConnect;
SDL_Surface *bHost;
#endif
//new in 1.2.0 end
SDL_Surface *bHighScore;    //The High Score botton
SDL_Surface *bExit;         //The Exit botton
SDL_Surface *blackLine;		//The seperator in stage clear
SDL_Surface *stageBobble;	//The bobble instage clear
SDL_Surface *screen;        //The whole screen;
SDL_Surface *iGameOver;     //The gameOver image
SDL_Surface *iWinner;		//the "winner" image
SDL_Surface *iDraw;			//the "draw" image
SDL_Surface *iLoser;		//the "loser" image
//Animations:
SDL_Surface *cursor[2];    //The animated cursor
SDL_Surface *bomb[2];       //Bomb then the bricks should blow
SDL_Surface *ready[2];      //Before the blocks fall
SDL_Surface *explosion[4];   //Then a block explodes
//Animations end
SDL_Surface *counter[3];    //Counts down from 3
SDL_Surface *bricks[7];     //The bricks, saved in an array of pointers
SDL_Surface *crossover;     //Cross the bricks that will be cleared soon
SDL_Surface *balls[7];      //The balls (the small ones that jump around)
SDL_Surface *iBlueFont;      //Contains the blue font used
SDL_Surface *iSmallFont;	//Small font used for the chain text 
SDL_Surface *topscoresBack;  //The backgound to the highscore list
SDL_Surface *optionsBack;
SDL_Surface *changeButtonsBack;
SDL_Surface *dialogBox;
//SDL_Surface *fileDialogBox;  //Manual entering of filename, new in 1.1.1, obsolute in 1.1.2
SDL_Surface *bOn;
SDL_Surface *bOff;
SDL_Surface *bChange;
SDL_Surface *b1024;
//SDL_Surface *b1280;
//SDL_Surface *b1400;
//SDL_Surface *b1600;
SDL_Surface *iLevelCheck;		//To the level select screen
SDL_Surface *iLevelCheckBox;
SDL_Surface *iCheckBoxArea;
SDL_Surface *boardBackBack;
SDL_Surface *garbageTL;			//the Garbage Blocks
SDL_Surface *garbageT;
SDL_Surface *garbageTR;
SDL_Surface *garbageR;
SDL_Surface *garbageBR;
SDL_Surface *garbageB;
SDL_Surface *garbageBL;
SDL_Surface *garbageL;
SDL_Surface *garbageFill;
SDL_Surface *garbageM;
SDL_Surface *garbageML;
SDL_Surface *garbageMR;
//new in 1.2.3 start
SDL_Surface *smiley[4];
SDL_Surface *garbageGM;
SDL_Surface *garbageGML;
SDL_Surface *garbageGMR;
//new in 1.2.3 end
SDL_Surface *mouse;				//The mouse cursor


SDL_Surface *tmp;				//a temporary surface to use DisplayFormat


SFont_Font *fBlueFont;      //Stores the blue font (SFont)
SFont_Font *fSmallFont;		//Stores the small font (SFont)

Mix_Music *bgMusic;         //backgroundMusic
Mix_Chunk *boing;           //boing sound when clearing
Mix_Chunk *timesUp;         //whistle when times up
Mix_Chunk *applause;        //Applause, then the player is good
Mix_Chunk *photoClick;      //clickSound
Mix_Chunk *heartBeat;		//heart beat
Mix_Chunk *typingChunk;          //When writing
Mix_Chunk *counterChunk;         //When counting down

Highscore theTopScoresEndless;      //Stores highscores for endless
Highscore theTopScoresTimeTrial;    //Stores highscores for timetrial

bool bMouseUp;              //true if the mouse(1) is unpressed
bool bMouseUp2;             //true if the mouse(2) is unpressed
bool bNewGameOpen;          //show sub menues
bool bOptionsOpen;          //Show OptionsMenu (Configure and Select Puzzle)
bool b1playerOpen;			//show submenu
bool b2playersOpen;			//show submenu
bool bReplayOpen;			//Show replay menu
#ifdef NETWORK
bool bNetworkOpen;			//Show the network menu
#endif
bool showHighscores;        //true if highscores is displayed
bool showEndless;           //if true show endless highscores else timetrial
bool showGame;              //the game is active don't show highscores/options
bool showOptions;           //true if options is open
bool bScreenLocked;			//Don't take input or allow any mouse interaction! Used for dialogbox and warningbox
bool showDialog;
//new in 1.3.1
bool NoSound;				//if true, absolutely no sound will be played, can be set from the commandline
					//prevents crash on systems without a soundcard
//end new 1.3.1
bool MusicEnabled;			//true if background music is enabled
bool SoundEnabled;			//true if sound effects is enabled
bool bFullscreen;			//true if game is running fullscreen
bool puzzleLoaded;          //true if the puzzle levels have been loaded
bool drawBalls;             //if true balls are drawed to the screen, this might lower framerate too much
bool standardBackground;

//Things for network play:
bool networkPlay;
bool networkActive;
Uint8 nrOfNetworkPlayers;  //Up to 4 players (inkl. self)
bool playerAlive[4];
//sockets here
#define SERVERPORT 41780
#define CLIENTPORT 41781

#ifdef NETWORK
char serverAddress[30];
#endif

                            //should be automatically disabled if framerate to low (isn't implemented and wont be soon/ever):
const int ballsFpsEnable = 30;     //If framerate higher -> enable balls
const int ballsFpsDisable = 10;    //If framerate lower -> disable balls

//other ball constants:
const double gravity = 200.8; //acceleration
const double startVelocityY = 50.0;
const double VelocityX = 50.0;
const int ballSize = 16;
const double minVelocity = 200.0; 

//global settings (reset everytime the game starts)
Uint8 player1Speed=0;
Uint8 player2Speed=0;
bool player1AI=false;		//Is AI enabled?
bool player2AI=false;		//Is AI enabled for player 2 (opponent in single player)
Uint8 player1AIlevel=3;		//What level is AI? 0 min, 6 max
Uint8 player2AIlevel=3;
const Uint8 AIlevels=7;		//7 possible levels: 0..6
Uint8 player1handicap=0;
Uint8 player2handicap=0;

unsigned long int currentTime;      //contains the current time, so we don't call SDL_GetTickets() too often...

int xsize;

//Stores the players names (way to long, but at least no buffer overflows (max length is 16 for display reasons))
char player1name[30];
char player2name[30];

//paths
string stageClearSavePath;
string puzzleSavePath;
string puzzleName;              //The filename of 

const int nrOfStageLevels = 50;		//number of stages in stage Clear
const int maxNrOfPuzzleStages = 50; //Maximum number of puzzle stages
vector<bool> stageCleared(nrOfStageLevels);		//vector that tells if a stage is cleared
vector<bool> puzzleCleared(maxNrOfPuzzleStages); //vector that tells if puzzle cleared
vector<int> nrOfMovesAllowed(maxNrOfPuzzleStages);  //Moves to clear
int puzzleLevels[maxNrOfPuzzleStages][6][12]; //Contains board layout;
int nrOfPuzzles;    //How many are there actually?

//Old mouse position:
int oldMousex, oldMousey;
//Old Stage Clear Buble
int oldBubleX, oldBubleY;

//bool doublebuf = false; //if true, screen is double buffered
char forceredraw; //If 1: always redraw, if 2: rarely redraw

bool singlePuzzle = false; //if true we are just in a little 300x600 window
int singlePuzzleNr = 0;
string singlePuzzleFile;

#if defined(DEBUG)
//frame counter (fps)
unsigned long int Frames, Ticks;
char FPS[10];
#endif

int lastNrOfPlayers; //1 if 1 player and 2 if vs. mode

//keySetup
int player1keys, player2keys;
bool mouseplay1=false;  //The mouse works on the play field
bool mouseplay2=false;  //Same for player2
bool joyplay1=false;    //Player one uses the joypad
bool joyplay2=false;    //Player two uses the joypad

  //Stores the controls
  struct control
  {
	  SDLKey up;
	  SDLKey down;
	  SDLKey left;
	  SDLKey right;
	  SDLKey change;
	  SDLKey push;
  };

  control keySettings[3];	//array to hold the controls

  void MakeBackground(int,int);

void closeAllMenus()
{
     bNewGameOpen=false;          //show sub menues
     bOptionsOpen=false;          //Show OptionsMenu (Configure and Select Puzzle)
     b1playerOpen=false;			//show submenu
     b2playersOpen=false;
     bReplayOpen = false;
#ifdef NETWORK
     bNetworkOpen = false;
#endif
     showOptions = false;
     showHighscores = false;
     
}

#ifdef WIN32
//Returns path to "my Documents" in windows:
string getMyDocumentsPath()
{
	TCHAR pszPath[MAX_PATH];
	if (SUCCEEDED(SHGetSpecialFolderPath(NULL, pszPath, CSIDL_PERSONAL, FALSE))) {
   	// pszPath is now the path that you want
#ifdef DEBUG
		cout << "MyDocuments Located: " << pszPath << endl;
#endif
		string theResult= pszPath;
		return theResult;	
	}
	else
	{
		cout << "Warning: My Documents not found!" << endl;
		string theResult ="";
		return theResult;
	}
}

#endif

//If we use the SHAREDIR we need:
#ifdef SHAREDIR
SDL_Surface * IMG_Load2(char* path) {

  char * tmp;
  SDL_Surface * ret=NULL; 
  tmp = (char*)malloc (sizeof(char)*(strlen(path)+strlen(sharedir)+2));
  strcpy(tmp, sharedir);
  strcat(tmp, "/");
  strcat(tmp, path);
#ifdef DEBUG  
printf("loading %s\n",tmp);
#endif
  if(!(ret = IMG_Load(tmp)))
    ret = IMG_Load(path);
  
  free(tmp);
  return ret;
}

Mix_Music * Mix_LoadMUS2(char* path) 
{
  char * tmp;
  Mix_Music * ret=NULL; 
  tmp = (char*)malloc (sizeof(char)*(strlen(path)+strlen(sharedir)+2));
  strcpy(tmp, sharedir);
  strcat(tmp, "/");
  strcat(tmp, path);
#ifdef DEBUG  
printf("loading %s\n",tmp);
#endif
  if(!(ret = Mix_LoadMUS(tmp)))
    ret = Mix_LoadMUS(path);
  
  free(tmp);
  return ret;
}

Mix_Chunk * Mix_LoadWAV2(char* path) 
{
  char * tmp;
  Mix_Chunk * ret=NULL; 
  tmp = (char*)malloc (sizeof(char)*(strlen(path)+strlen(sharedir)+2));
  strcpy(tmp, sharedir);
  strcat(tmp, "/");
  strcat(tmp, path);
#ifdef DEBUG  
printf("loading %s\n",tmp);
#endif
  if(!(ret = Mix_LoadWAV(tmp)))
    ret = Mix_LoadWAV(path);
  
  free(tmp);
  return ret;
}
#else
SDL_Surface * IMG_Load2(char* path)
{
	return IMG_Load(path);
}

Mix_Music * Mix_LoadMUS2(char* path)
{
	return Mix_LoadMUS(path);
}

Mix_Chunk * Mix_LoadWAV2(char* path)
{
	return Mix_LoadWAV(path);
}
#endif


//Load all image files to memory
int InitImages()
{
    if (!((backgroundImage = IMG_Load2("gfx/background.png"))
    && (background = IMG_Load2("gfx/blackBackGround.png")) 
    && (bNewGame = IMG_Load2("gfx/bNewGame.png"))
	&& (b1player = IMG_Load2("gfx/bOnePlayer.png"))
	&& (b2players = IMG_Load2("gfx/bTwoPlayers.png"))
	&& (bVsMode = IMG_Load2("gfx/bVsGame.png"))
	&& (bPuzzle = IMG_Load2("gfx/bPuzzle.png"))
	&& (bStageClear = IMG_Load2("gfx/bStageClear.png"))
    && (bTimeTrial = IMG_Load2("gfx/bTimeTrial.png"))
    && (bEndless = IMG_Load2("gfx/bEndless.png"))
    && (bOptions = IMG_Load2("gfx/bOptions.png"))
    && (bConfigure = IMG_Load2("gfx/bConfigure.png"))
    && (bSelectPuzzle = IMG_Load2("gfx/bSelectPuzzle.png"))
    && (bHighScore = IMG_Load2("gfx/bHighScore.png"))
    && (bExit = IMG_Load2("gfx/bExit.png"))
    && (bBack = IMG_Load2("gfx/bBack.png"))
    && (bForward = IMG_Load2("gfx/bForward.png"))
	&& (bReplay = IMG_Load2("gfx/bReplays.png"))
	&& (bSave = IMG_Load2("gfx/bSave.png"))
	&& (bLoad = IMG_Load2("gfx/bLoad.png"))
#ifdef NETWORK
	&& (bNetwork = IMG_Load2("gfx/bNetwork.png"))
	&& (bHost = IMG_Load2("gfx/bHost.png"))
	&& (bConnect = IMG_Load2("gfx/bConnect.png"))
#endif
	&& (blackLine = IMG_Load2("gfx/blackLine.png"))
	&& (stageBobble = IMG_Load2("gfx/iStageClearLimit.png"))
    && (bricks[0] = IMG_Load2("gfx/blue.png"))
    && (bricks[1] = IMG_Load2("gfx/green.png"))
    && (bricks[2] = IMG_Load2("gfx/purple.png"))
    && (bricks[3] = IMG_Load2("gfx/red.png"))
    && (bricks[4] = IMG_Load2("gfx/turkish.png"))
    && (bricks[5] = IMG_Load2("gfx/yellow.png"))
    && (bricks[6] = IMG_Load2("gfx/grey.png"))
    && (crossover = IMG_Load2("gfx/crossover.png"))
    && (balls[0] = IMG_Load2("gfx/balls/ballBlue.png"))
    && (balls[1] = IMG_Load2("gfx/balls/ballGreen.png"))
    && (balls[2] = IMG_Load2("gfx/balls/ballPurple.png"))
    && (balls[3] = IMG_Load2("gfx/balls/ballRed.png"))
    && (balls[4] = IMG_Load2("gfx/balls/ballTurkish.png"))
    && (balls[5] = IMG_Load2("gfx/balls/ballYellow.png"))
    && (balls[6] = IMG_Load2("gfx/balls/ballGray.png"))
    && (cursor[0] = IMG_Load2("gfx/animations/cursor/1.png"))
    && (cursor[1] = IMG_Load2("gfx/animations/cursor/2.png"))
    && (bomb[0] = IMG_Load2("gfx/animations/bomb/bomb_1.png"))
    && (bomb[1] = IMG_Load2("gfx/animations/bomb/bomb_2.png"))
    && (ready[0] = IMG_Load2("gfx/animations/ready/ready_1.png"))
    && (ready[1] = IMG_Load2("gfx/animations/ready/ready_2.png"))
    && (explosion[0] = IMG_Load2("gfx/animations/explosion/0.png"))
    && (explosion[1] = IMG_Load2("gfx/animations/explosion/1.png"))
    && (explosion[2] = IMG_Load2("gfx/animations/explosion/2.png"))
    && (explosion[3] = IMG_Load2("gfx/animations/explosion/3.png"))
    && (counter[0] = IMG_Load2("gfx/counter/1.png"))
    && (counter[1] = IMG_Load2("gfx/counter/2.png"))
    && (counter[2] = IMG_Load2("gfx/counter/3.png"))
    && (backBoard = IMG_Load2("gfx/BackBoard.png")) //not used, we just test if it exists :)
    && (iGameOver = IMG_Load2("gfx/iGameOver.png"))
	&& (iWinner = IMG_Load2("gfx/iWinner.png"))
	&& (iDraw = IMG_Load2("gfx/iDraw.png"))
	&& (iLoser = IMG_Load2("gfx/iLoser.png"))
	&& (iChainBack = IMG_Load2("gfx/chainFrame.png"))
    //&& (iBlueFont = IMG_Load2("gfx/24P_Copperplate_Blue.png"))
    && (iBlueFont = IMG_Load2("gfx/24P_Arial_Blue.png"))
    && (iSmallFont = IMG_Load2("gfx/14P_Arial_Angle_Red.png"))
    && (topscoresBack = IMG_Load2("gfx/topscores.png"))
	&& (optionsBack = IMG_Load2("gfx/options.png"))
	&& (bOn = IMG_Load2("gfx/bOn.png"))
	&& (bOff = IMG_Load2("gfx/bOff.png"))
	&& (bChange = IMG_Load2("gfx/bChange.png"))
	&& (b1024 = IMG_Load2("gfx/b1024.png"))
	//&& (b1280 = IMG_Load2("gfx/b1280.png"))
	//&& (b1400 = IMG_Load2("gfx/b1400.png"))
	//&& (b1600 = IMG_Load2("gfx/b1600.png"))
	&& (dialogBox = IMG_Load2("gfx/dialogbox.png"))
//	&& (fileDialogBox = IMG_Load2("gfx/fileDialogbox.png"))
	&& (iLevelCheck = IMG_Load2("gfx/iLevelCheck.png"))
	&& (iLevelCheckBox = IMG_Load2("gfx/iLevelCheckBox.png"))
	&& (iCheckBoxArea = IMG_Load2("gfx/iCheckBoxArea.png"))
	&& (boardBackBack = IMG_Load2("gfx/boardBackBack.png"))
	&& (changeButtonsBack = IMG_Load2("gfx/changeButtonsBack.png"))
	&& (garbageTL = IMG_Load2("gfx/garbage/garbageTL.png"))
	&& (garbageT = IMG_Load2("gfx/garbage/garbageT.png"))
	&& (garbageTR = IMG_Load2("gfx/garbage/garbageTR.png"))
	&& (garbageR = IMG_Load2("gfx/garbage/garbageR.png"))
	&& (garbageBR = IMG_Load2("gfx/garbage/garbageBR.png"))
	&& (garbageB = IMG_Load2("gfx/garbage/garbageB.png"))
	&& (garbageBL = IMG_Load2("gfx/garbage/garbageBL.png"))
	&& (garbageL = IMG_Load2("gfx/garbage/garbageL.png"))
	&& (garbageFill = IMG_Load2("gfx/garbage/garbageFill.png"))
	&& (garbageML = IMG_Load2("gfx/garbage/garbageML.png"))
	&& (garbageM = IMG_Load2("gfx/garbage/garbageM.png"))
	&& (garbageMR = IMG_Load2("gfx/garbage/garbageMR.png"))
	&& (garbageGM = IMG_Load2("gfx/garbage/garbageGM.png"))
	&& (garbageGML = IMG_Load2("gfx/garbage/garbageGML.png"))
	&& (garbageGMR = IMG_Load2("gfx/garbage/garbageGMR.png"))
	&& (smiley[0] = IMG_Load2("gfx/smileys/0.png"))
	&& (smiley[1] = IMG_Load2("gfx/smileys/1.png"))
	&& (smiley[2] = IMG_Load2("gfx/smileys/2.png"))
	&& (smiley[3] = IMG_Load2("gfx/smileys/3.png"))
	&& (mouse = IMG_Load2("gfx/mouse.png"))
	))
    //if there was a problem ie. "File not found"
    {
        cout << "Error loading image file: " << SDL_GetError() << endl;
        exit(1);
    }
    

    //Prepare for fast blittering!
	CONVERT(background);
	CONVERT(bNewGame);
	CONVERT(backgroundImage);
	CONVERT(b1player);
	CONVERT(b2players);
	CONVERT(bVsMode);
	CONVERT(bPuzzle);
	CONVERT(bStageClear);
    CONVERT(bTimeTrial);
    CONVERT(bEndless);
    CONVERT(bOptions);
    CONVERTA(bConfigure);
    CONVERTA(bSelectPuzzle);
    CONVERTA(bReplay);
    CONVERTA(bSave);
    CONVERTA(bLoad);
#ifdef NETWORK
    CONVERTA(bNetwork);
    CONVERTA(bHost);
    CONVERTA(bConnect);
#endif
    CONVERT(bHighScore);
	CONVERTA(boardBackBack);
	CONVERT(backBoard);
	CONVERT(blackLine);
	CONVERTA(changeButtonsBack);
    CONVERTA(cursor[0]);
	CONVERTA(cursor[1]);
	CONVERTA(counter[0]);
	CONVERTA(counter[1]);
	CONVERTA(counter[2]);
	CONVERTA(topscoresBack);
	CONVERTA(optionsBack);
	CONVERT(bExit);
	CONVERT(bOn);
	CONVERT(bOff);
	CONVERT(bChange);
	CONVERT(b1024);
	CONVERTA(dialogBox);
//	CONVERTA(fileDialogBox);
    CONVERTA(iLevelCheck);
	CONVERT(iLevelCheckBox);
	CONVERTA(iCheckBoxArea);
	for(int i = 0;i<4;i++)
	{
        CONVERTA(explosion[i]);
    }
	for(int i = 0; i<7; i++)
	{
        CONVERTA(bricks[i]);
        CONVERTA(balls[i]);
	}
	CONVERTA(crossover);
	CONVERTA(garbageTL);
	CONVERTA(garbageT);
	CONVERTA(garbageTR);
	CONVERTA(garbageR);
	CONVERTA(garbageBR);
	CONVERTA(garbageB);
	CONVERTA(garbageBL);
	CONVERTA(garbageL);
	CONVERTA(garbageFill);
	CONVERTA(garbageML);
	CONVERTA(garbageMR);
	CONVERTA(garbageM);
	CONVERTA(garbageGML);
	CONVERTA(garbageGMR);
	CONVERTA(garbageGM);
	CONVERTA(smiley[0]);
	CONVERTA(smiley[1]);
	CONVERTA(smiley[2]);
	CONVERTA(smiley[3]);
	CONVERTA(iWinner);
	CONVERTA(iDraw);
	CONVERTA(iLoser);
	CONVERTA(iChainBack);
	CONVERTA(iBlueFont);
	CONVERTA(iSmallFont);
	CONVERTA(iGameOver);
	CONVERTA(mouse);
	CONVERTA(stageBobble);
	
	/*
	SDL_SetColorKey(topscoresBack, SDL_SRCCOLORKEY, 
                    SDL_MapRGB(topscoresBack->format, 0, 255, 0));
    SDL_SetColorKey(optionsBack, SDL_SRCCOLORKEY, 
                    SDL_MapRGB(optionsBack->format, 0, 255, 0));
	*/

    //Here comes the fonts:
    fBlueFont = SFont_InitFont(iBlueFont);
	fSmallFont = SFont_InitFont(iSmallFont);

//Loads the sound if sound present
if(!NoSound)
{
    //And here the music:
    bgMusic = Mix_LoadMUS2("music/bgMusic.ogg");
	//the music... we just hope it exists, else the user won't hear anything
    //Same goes for the sounds
    boing = Mix_LoadWAV2("sound/pop.ogg");
    timesUp = Mix_LoadWAV2("sound/whistleblow.ogg");
    applause = Mix_LoadWAV2("sound/applause.ogg");
    photoClick = Mix_LoadWAV2("sound/cameraclick.ogg");
	heartBeat = Mix_LoadWAV2("sound/heartbeat3.ogg");
	typingChunk = Mix_LoadWAV2("sound/typing.ogg");
	counterChunk = Mix_LoadWAV2("sound/counter.ogg");
} //All sound has been loaded or not
    return 0;
} //InitImages()


//Unload images and fonts and sounds
void UnloadImages()
{
    //Fonts and Sounds needs to be freed
    SFont_FreeFont(fBlueFont);
    SFont_FreeFont(fSmallFont);
if(!NoSound) //Only unload then it has been loaded!
{
    Mix_FreeMusic(bgMusic);
    Mix_FreeChunk(boing);
    Mix_FreeChunk(timesUp);
    Mix_FreeChunk(applause);
    Mix_FreeChunk(photoClick);
	Mix_FreeChunk(heartBeat);
	Mix_FreeChunk(counterChunk);
	Mix_FreeChunk(typingChunk);
}
    //Free surfaces:
        //I think this will crash, at least it happend to me...
    /*SDL_FreeSurface(backgroundImage);
    SDL_FreeSurface(background); 
    SDL_FreeSurface(bNewGame);
	SDL_FreeSurface(b1player);
	SDL_FreeSurface(b2players);
	SDL_FreeSurface(bVsMode);
	SDL_FreeSurface(bPuzzle);
	SDL_FreeSurface(bStageClear);
    SDL_FreeSurface(bTimeTrial);
    SDL_FreeSurface(bEndless);
    SDL_FreeSurface(bOptions);
    SDL_FreeSurface(bConfigure);
    SDL_FreeSurface(bSelectPuzzle);
    SDL_FreeSurface(bHighScore);
    SDL_FreeSurface(bReplay);
    SDL_FreeSurface(bSave);
    SDL_FreeSurface(bLoad);
#ifdef NETWORK
    SDL_FreeSurface(bNetwork);
    SDL_FreeSurface(bHost);
    SDL_FreeSurface(bConnect);
#endif
    SDL_FreeSurface(bExit);
	SDL_FreeSurface(blackLine);
	SDL_FreeSurface(stageBobble);
    SDL_FreeSurface(bricks[0]);
    SDL_FreeSurface(bricks[1]);
    SDL_FreeSurface(bricks[2]);
    SDL_FreeSurface(bricks[3]);
    SDL_FreeSurface(bricks[4]);
    SDL_FreeSurface(bricks[5]);
    SDL_FreeSurface(bricks[6]);
    SDL_FreeSurface(crossover);
    SDL_FreeSurface(balls[0]);
    SDL_FreeSurface(balls[1]);
    SDL_FreeSurface(balls[2]);
    SDL_FreeSurface(balls[3]);
    SDL_FreeSurface(balls[4]);
    SDL_FreeSurface(balls[5]);
    SDL_FreeSurface(balls[6]);
    SDL_FreeSurface(cursor[0]);
    SDL_FreeSurface(cursor[1]);
    SDL_FreeSurface(backBoard); //not used, we just test if it exists :)
    SDL_FreeSurface(iGameOver);
	SDL_FreeSurface(iWinner);
	SDL_FreeSurface(iDraw);
	SDL_FreeSurface(iLoser);
	SDL_FreeSurface(iChainBack);
    SDL_FreeSurface(iBlueFont);
    SDL_FreeSurface(iSmallFont);
    SDL_FreeSurface(topscoresBack);
	SDL_FreeSurface(optionsBack);
	SDL_FreeSurface(bOn);
	SDL_FreeSurface(bOff);
	SDL_FreeSurface(bChange);
	SDL_FreeSurface(b1024);
	SDL_FreeSurface(b1280);
	SDL_FreeSurface(b1400);
	SDL_FreeSurface(b1600);
	SDL_FreeSurface(dialogBox);
	SDL_FreeSurface(fileDialogBox);
    SDL_FreeSurface(iLevelCheck);
	SDL_FreeSurface(iLevelCheckBox);
	SDL_FreeSurface(iCheckBoxArea);
	SDL_FreeSurface(boardBackBack);
	SDL_FreeSurface(changeButtonsBack);
	SDL_FreeSurface(garbageTL);
	SDL_FreeSurface(garbageT);
	SDL_FreeSurface(garbageTR);
	SDL_FreeSurface(garbageR);
	SDL_FreeSurface(garbageBR);
	SDL_FreeSurface(garbageB);
	SDL_FreeSurface(garbageBL);
	SDL_FreeSurface(garbageL);
	SDL_FreeSurface(garbageFill);
	SDL_FreeSurface(garbageML);
	SDL_FreeSurface(garbageM);
	SDL_FreeSurface(garbageMR);
	SDL_FreeSurface(garbageGML);
	SDL_FreeSurface(garbageGM);
	SDL_FreeSurface(garbageGMR);
	SDL_FreeSurface(smiley[0]);
	SDL_FreeSurface(smiley[1]);
	SDL_FreeSurface(smiley[2]);
	SDL_FreeSurface(smiley[3]);
	SDL_FreeSurface(mouse); 
    */
}    

//Function to convert numbers to string
string itoa(int num)
{
    stringstream converter;
    converter << num;
    return converter.str();
}

/*Loads all the puzzle levels*/
int LoadPuzzleStages()
{
    //if(puzzleLoaded)
    //    return 1;
#ifdef __unix__
    string filename0 = (string)getenv("HOME")+(string)"/.gamesaves/blockattack/puzzles/";
    filename0 = filename0+puzzleName;
    if(singlePuzzle)
	filename0 = singlePuzzleFile;
#endif //__unix__
#ifdef SHAREDIR
    string filename = (string)SHAREDIR+(string)"/res/";
    filename = filename+puzzleName;
#else
    string filename = "res/"+puzzleName;
#endif
#ifdef __unix__
    ifstream inFile(filename0.c_str());
    if(!inFile)
	inFile.open(filename.c_str());
#else
     ifstream inFile(filename.c_str());
#endif
    inFile >> nrOfPuzzles;
    if(nrOfPuzzles>maxNrOfPuzzleStages)
        nrOfPuzzles=maxNrOfPuzzleStages;
    for(int k=0; (k<nrOfPuzzles)&&(!inFile.eof()); k++)
    {
        inFile >> nrOfMovesAllowed[k];
        for(int i=11;i>=0;i--)
            for(int j=0;j<6;j++)
            {
                inFile >> puzzleLevels[k][j][i];
            }
    }
    puzzleLoaded = true;
    return 0;
}

/*Draws a image from on a given Surface. Takes source image, destination surface and coordinates*/
inline void DrawIMG(SDL_Surface *img, SDL_Surface *target, int x, int y)
{
  SDL_Rect dest;
  dest.x = x;
  dest.y = y;
  SDL_BlitSurface(img, NULL, target, &dest);
}

/*Draws a part of an image on a surface of choice*/
void DrawIMG(SDL_Surface *img, SDL_Surface * target, int x, int y, int w, int h, int x2, int y2)
{
  SDL_Rect dest;
  dest.x = x;
  dest.y = y;
  SDL_Rect dest2;
  dest2.x = x2;
  dest2.y = y2;
  dest2.w = w;
  dest2.h = h;
  SDL_BlitSurface(img, &dest2, target, &dest);
}

//The small things that are faaling when you clear something
class aBall
{
    private:
        double x;
        double y;
        double velocityY;
        double velocityX;
        int color;
        unsigned long int lastTime;
    public:
               
        aBall()
        {}       
               
        //constructor:
        aBall(int X, int Y, bool right, int coulor)
        {
            double tal = 1.0;
            velocityY = -tal*startVelocityY;
            lastTime = currentTime;
            x = (double)X;
            y = (double)Y;
            color = coulor;
            if(right)
               velocityX = tal*VelocityX;
            else
               velocityX = -tal*VelocityX;
        }  //constructor  
        
        //Deconstructor
        ~aBall()
        {
        }   //Deconstructor
        
        void update()
        {
            double timePassed = (((double)(currentTime-lastTime))/1000.0);  //time passed in seconds
            x = x+timePassed*velocityX;
            y = y+timePassed*velocityY;
            velocityY = velocityY + gravity*timePassed;
            if(y<1.0)
            velocityY=10.0;
            if((velocityY>minVelocity) && (y>(double)(768-ballSize)) && (y<768.0))
            {
                velocityY = -0.70*velocityY;
                y = 768.0-ballSize;
            }    
            lastTime = currentTime;
        }    
        
        int getX()
        {
            return (int)x;
        }    
        
        int getY()
        {
            return (int)y;
        }  
        
        int getColor()
        {
            return color;
        }      
};  //aBall

const int maxNumberOfBalls = 100;

class ballManeger
{
    public:
        aBall ballArray[maxNumberOfBalls];
        bool ballUsed[maxNumberOfBalls];
        //The old ball information is also saved so balls can be deleted!
        aBall oldBallArray[maxNumberOfBalls];
        bool oldBallUsed[maxNumberOfBalls];
        
    ballManeger()
    {
        for(int i=0; i<maxNumberOfBalls; i++)
        {
                ballUsed[i] = false;
                oldBallUsed[i] = false;
        }
    }    
    
    int addBall(int x, int y,bool right,int color)
    {
        //cout << "Tries to add a ball" << endl;
        int ballNumber = 0;
        while((ballUsed[ballNumber])&&(ballNumber<maxNumberOfBalls))
        ballNumber++;
        if(ballNumber==maxNumberOfBalls)
        return -1;
        currentTime = SDL_GetTicks();
        ballArray[ballNumber] = aBall(x,y,right,color);
        ballUsed[ballNumber] = true;
        //cout << "Ball added" << endl;
        return 1;
    }  //addBall  
    
    void update()
    {
        currentTime = SDL_GetTicks();
        for(int i = 0; i<maxNumberOfBalls; i++)
        {
            
            if(ballUsed[i])
            {
               oldBallUsed[i] = true;
               oldBallArray[i] = ballArray[i];
               ballArray[i].update();
               if(ballArray[i].getY()>800)
               {
                   ballArray[i].~aBall();
                   ballUsed[i] = false;
                   //cout << "Ball removed" << endl;
               }    
            }    
            else
            {
                oldBallUsed[i] = false;
            }
        }    
    } //update
    
          
}; //theBallManeger

ballManeger theBallManeger;

//a explosions, non moving
class anExplosion
{
    private:
        int x;
        int y;
        Uint8 frameNumber;
        #define frameLength 80 
        //How long an image in an animation should be showed
        #define maxFrame 4 
        //How many images there are in the animation
        unsigned long int placeTime; //Then the explosion occored
    public:
               
        anExplosion()
        {}       
               
        //constructor:
        anExplosion(int X, int Y)
        {
            placeTime = currentTime;
            x = X;
            y = Y;
            frameNumber=0;
        }  //constructor  
        
        //Deconstructor
        ~anExplosion()
        {
        }   //Deconstructor
        
        //true if animation has played and object should be removed from the screen
        bool removeMe()
        {
            frameNumber = (currentTime-placeTime)/frameLength;
            return (!(frameNumber<maxFrame));
        }
        
        int getX()
        {
            return (int)x;
        }    
        
        int getY()
        {
            return (int)y;
        }  
        
        int getFrame()
        {
            return frameNumber;
        }      
};  //nExplosion

class explosionManeger
{
    public:
        anExplosion explosionArray[maxNumberOfBalls];
        bool explosionUsed[maxNumberOfBalls];
        //The old explosion information is also saved so explosions can be deleted!
        anExplosion oldExplosionArray[maxNumberOfBalls];
        bool oldExplosionUsed[maxNumberOfBalls];
        
    explosionManeger()
    {
        for(int i=0; i<maxNumberOfBalls; i++)
        {
                explosionUsed[i] = false;
                oldExplosionUsed[i] = false;
        }
    }    
    
    int addExplosion(int x, int y)
    {
        //cout << "Tries to add an explosion" << endl;
        int explosionNumber = 0;
        while((explosionUsed[explosionNumber])&&(explosionNumber<maxNumberOfBalls))
        explosionNumber++;
        if(explosionNumber==maxNumberOfBalls)
        return -1;
        currentTime = SDL_GetTicks();
        explosionArray[explosionNumber] = anExplosion(x,y);
        explosionUsed[explosionNumber] = true;
        //cout << "Explosion added" << endl;
        return 1;
    }  //addBall  
    
    void update()
    {
        currentTime = SDL_GetTicks();
        for(int i = 0; i<maxNumberOfBalls; i++)
        {
            
            if(explosionUsed[i])
            {
               oldExplosionUsed[i] = true;
               oldExplosionArray[i] = explosionArray[i];
               if(explosionArray[i].removeMe())
               {
                   explosionArray[i].~anExplosion();
                   explosionUsed[i] = false;
                   //cout << "Explosion removed" << endl;
               }    
            }    
            else
            {
                oldExplosionUsed[i] = false;
            }
        }    
    } //update
    
          
}; //explosionManeger

explosionManeger theExplosionManeger;

//text pop-up
class textMessage
{
    private:
        int x;
        int y;
        char textt[10];
        unsigned long int time;
        unsigned long int placeTime; //Then the text was placed
    public:
               
        textMessage()
        {}       
               
        //constructor:
        textMessage(int X, int Y,const char* Text,unsigned int Time)
        {
        	//cout << "Running constructor" << endl;
            placeTime = currentTime;
            x = X;
            y = Y;
            strncpy(textt,Text,10);
            textt[9]=0;
            time = Time;
            //cout << "Constructor runned" << endl;
        }  //constructor  
        
        //true if the text has expired
        bool removeMe()
        {
            return currentTime-placeTime>time;
        }
        
        int getX()
        {
            //cout << "Gets X" << endl;
            return x;
        }    
        
        int getY()
        {
            //cout << "Gets Y" << endl;
            return y;
        }  
        
        char* getText()
        {
            //cout << "Gets text" << endl;
            return textt;
        }      
};  //text popup

class textManeger
{
    public:
        textMessage textArray[maxNumberOfBalls];
        bool textUsed[maxNumberOfBalls];
        //The old text information is also saved so text can be deleted!
        textMessage oldTextArray[maxNumberOfBalls];
        bool oldTextUsed[maxNumberOfBalls];
        
    textManeger()
    {
        for(int i=0; i<maxNumberOfBalls; i++)
        {
                textUsed[i] = false;
                oldTextUsed[i] = false;
        }
    }    
    
    int addText(int x, int y,string Text,unsigned int Time)
    {
        //cout << "Tries to add text" << endl;
        int textNumber = 0;
        while((textNumber<maxNumberOfBalls)&&((textUsed[textNumber])||(oldTextUsed[textNumber])))
        textNumber++;
        if(textNumber==maxNumberOfBalls)
        return -1;
        //cout << "adding to: " << textNumber << ":" << textUsed[textNumber] << ":" << &textArray[textNumber] << endl;
        currentTime = SDL_GetTicks();
        //if(&textArray[textNumber]!=NULL)
        //*textArray[textNumber]=0;	
        textArray[textNumber] = textMessage(x,y,Text.c_str(),Time);
        textUsed[textNumber] = true;
        //cout << "Text added" << endl;
        return 1;
    }  //addText  
    
    void update()
    {
        //cout << "Running update" << endl;
        currentTime = SDL_GetTicks();
        for(int i = 0; i<maxNumberOfBalls; i++)
        {
            
            if(textUsed[i])
            {
               if(!oldTextUsed[i])
               {
                    oldTextUsed[i] = true;
                    oldTextArray[i] = textMessage(textArray[i]);
               } 
               if(textArray[i].removeMe())
               {
                   textArray[i].~textMessage();
                   textUsed[i] = false;
               }    
            }    
            else
            if(oldTextUsed[i])
            {
                oldTextUsed[i] = false;
                oldTextArray[i].~textMessage();
            }
        }    
    } //update
    
          
}; //textManeger

textManeger theTextManeger;

//Here comes the Block Game object
#include "BlockGame.hpp"

//writeScreenShot saves the screen as a bmp file, it uses the time to get a unique filename
void writeScreenShot()
{
     cout << "Saving screenshot" << endl;
    int rightNow = (int)time(NULL);
#if defined(__unix__)
	char buf[514];
	sprintf( buf, "%s/.gamesaves/blockattack/screenshots/screenshot%i.bmp", getenv("HOME"), rightNow );
#else
	char buf[MAX_PATH];
	sprintf( buf, "%s\\My Games\\blockattack\\screenshots\\screenshot%i.bmp", (getMyDocumentsPath()).c_str(), rightNow );
#endif	
	SDL_SaveBMP( screen, buf );
	if(!NoSound)	
	if(SoundEnabled)Mix_PlayChannel(1,photoClick,0);
}    

//Draws the highscores
inline void DrawHighscores(int x, int y)
{
    DrawIMG(topscoresBack,screen,x,y);
    if(showEndless) SFont_Write(screen,fBlueFont,x+100,y+100,"Endless:");
    else SFont_Write(screen,fBlueFont,x+100,y+100,"Time Trial:");
    for(int i =0;i<10;i++)
    {
        char playerScore[32];
		char playerName[32];
        if(showEndless) sprintf(playerScore, "%i", theTopScoresEndless.getScoreNumber(i));
        else sprintf(playerScore, "%i", theTopScoresTimeTrial.getScoreNumber(i));
		if(showEndless) strcpy(playerName,theTopScoresEndless.getScoreName(i));
        else strcpy(playerName,theTopScoresTimeTrial.getScoreName(i));
        SFont_Write(screen,fBlueFont,x+420,y+150+i*35,playerScore);
		SFont_Write(screen,fBlueFont,x+60,y+150+i*35,playerName);
    }    
}   

char keyname[11];

//Function to return the name of a key, to be displayed...
char* getKeyName(SDLKey key)
{
	
	char charToPut = '\0';
	switch(key)
	{
	case SDLK_a:	charToPut = 'A'; break;
	case SDLK_b:	charToPut = 'B'; break;
	case SDLK_c:	charToPut = 'C'; break;
	case SDLK_d:	charToPut = 'D'; break;
	case SDLK_e:	charToPut = 'E'; break;
	case SDLK_f:	charToPut = 'F'; break;
	case SDLK_g:	charToPut = 'G'; break;
	case SDLK_h:	charToPut = 'H'; break;
	case SDLK_i:	charToPut = 'I'; break;
	case SDLK_j:	charToPut = 'J'; break;
	case SDLK_k:	charToPut = 'K'; break;
	case SDLK_l:	charToPut = 'L'; break;
	case SDLK_m:	charToPut = 'M'; break;
	case SDLK_n:	charToPut = 'N'; break;
	case SDLK_o:	charToPut = 'O'; break;
	case SDLK_p:	charToPut = 'P'; break;
	case SDLK_q:	charToPut = 'Q'; break;
	case SDLK_r:	charToPut = 'R'; break;
	case SDLK_s:	charToPut = 'S'; break;
	case SDLK_t:	charToPut = 'T'; break;
	case SDLK_u:	charToPut = 'U'; break;
	case SDLK_v:	charToPut = 'V'; break;
	case SDLK_w:	charToPut = 'W'; break;
	case SDLK_x:	charToPut = 'X'; break;
	case SDLK_y:	charToPut = 'Y'; break;
	case SDLK_z:	charToPut = 'Z'; break;
	case SDLK_0:	charToPut = '0'; break;
	case SDLK_1:	charToPut = '1'; break;
	case SDLK_2:	charToPut = '2'; break;
	case SDLK_3:	charToPut = '3'; break;
	case SDLK_4:	charToPut = '4'; break;
	case SDLK_5:	charToPut = '5'; break;
	case SDLK_6:	charToPut = '6'; break;
	case SDLK_7:	charToPut = '7'; break;
	case SDLK_8:	charToPut = '8'; break;
	case SDLK_9:	charToPut = '9'; break;
	case SDLK_KP0:	sprintf(keyname,"NP_0"); break;
	case SDLK_KP1:	sprintf(keyname,"NP_1"); break;
	case SDLK_KP2:	sprintf(keyname,"NP_2"); break;
	case SDLK_KP3:	sprintf(keyname,"NP_3"); break;
	case SDLK_KP4:	sprintf(keyname,"NP_4"); break;
	case SDLK_KP5:	sprintf(keyname,"NP_5"); break;
	case SDLK_KP6:	sprintf(keyname,"NP_6"); break;
	case SDLK_KP7:	sprintf(keyname,"NP_7"); break;
	case SDLK_KP8:	sprintf(keyname,"NP_8"); break;
	case SDLK_KP9:	sprintf(keyname,"NP_9"); break;
	case SDLK_BACKSPACE:	sprintf(keyname,"Backspace"); break;
	case SDLK_TAB:			sprintf(keyname,"Tab"); break;
	case SDLK_CLEAR:	sprintf(keyname,"Clear"); break;
	case SDLK_RETURN:	sprintf(keyname,"Return"); break;
	case SDLK_PAUSE:	sprintf(keyname,"Pause"); break;
	case SDLK_SPACE:	sprintf(keyname,"Space"); break;
	case SDLK_EXCLAIM:	charToPut = '!'; break;
	case SDLK_QUOTEDBL:	sprintf(keyname,"QuoteDBL"); break;
	case SDLK_HASH:	charToPut = '#'; break;
	case SDLK_DOLLAR:	sprintf(keyname,"$"); break;
	case SDLK_ASTERISK:	sprintf(keyname,"Asterisk"); break;
	case SDLK_PLUS:	sprintf(keyname,"Plus"); break;
	case SDLK_COMMA:	sprintf(keyname,"Comma"); break;
	case SDLK_MINUS:	sprintf(keyname,"Minus"); break;
	case SDLK_PERIOD:	sprintf(keyname,"Period"); break;
	case SDLK_SLASH:	charToPut ='/'; break;
	case SDLK_COLON:	sprintf(keyname,"Colon"); break;
	case SDLK_SEMICOLON:	sprintf(keyname,"SemiColon"); break;
	case SDLK_LESS:	charToPut = '<'; break;
	case SDLK_EQUALS:	sprintf(keyname,"Equals"); break;
	case SDLK_DELETE:	sprintf(keyname,"Delete"); break;
	case SDLK_KP_PERIOD:	sprintf(keyname,"NPperiod"); break;
	case SDLK_KP_DIVIDE:	sprintf(keyname,"NPdivide"); break;
	case SDLK_KP_MULTIPLY:	sprintf(keyname,"NPmultiply"); break;
	case SDLK_KP_MINUS:	sprintf(keyname,"NPminus"); break;
	case SDLK_KP_PLUS:	sprintf(keyname,"NPplus"); break;
	case SDLK_KP_ENTER:	sprintf(keyname,"NP_Enter"); break;
	case SDLK_KP_EQUALS:	sprintf(keyname,"NP="); break;
	case SDLK_UP:	sprintf(keyname,"UP"); break;
	case SDLK_DOWN:	sprintf(keyname,"DOWN"); break;
	case SDLK_RIGHT:	sprintf(keyname,"RIGHT"); break;
	case SDLK_LEFT:	sprintf(keyname,"LEFT"); break;
	case SDLK_INSERT:	sprintf(keyname,"Insert"); break;
	case SDLK_HOME:	sprintf(keyname,"Home"); break;
	case SDLK_END:	sprintf(keyname,"End"); break;
	case SDLK_PAGEUP:	sprintf(keyname,"PageUp"); break;
	case SDLK_PAGEDOWN:	sprintf(keyname,"PageDown"); break;
	case SDLK_NUMLOCK:	sprintf(keyname,"NumLock"); break;
	case SDLK_CAPSLOCK:	sprintf(keyname,"CapsLock"); break;
	case SDLK_SCROLLOCK:	sprintf(keyname,"ScrolLock"); break;
	case SDLK_RSHIFT:	sprintf(keyname,"Rshift"); break;
	case SDLK_LSHIFT:	sprintf(keyname,"Lshift"); break;
	case SDLK_RCTRL:	sprintf(keyname,"Rctrl"); break;
	case SDLK_LCTRL:	sprintf(keyname,"Lctrl"); break;
	case SDLK_RALT:	sprintf(keyname,"Ralt"); break;
	case SDLK_LALT:	sprintf(keyname,"Lalt"); break;
	case SDLK_RMETA:	sprintf(keyname,"Rmeta"); break;
	case SDLK_LMETA:	sprintf(keyname,"Lmeta"); break;
	case SDLK_LSUPER:	sprintf(keyname,"Lwin"); break;
	case SDLK_RSUPER:	sprintf(keyname,"Rwin"); break;
	case SDLK_MODE:	sprintf(keyname,"Mode"); break;
	case SDLK_HELP:	sprintf(keyname,"Help"); break;
	default:
        sprintf(keyname,"Unknown"); break;
	}
	if(charToPut != '\0')
		sprintf(keyname,"%c",charToPut);
	return &keyname[0];
}

void MakeBackground(int xsize,int ysize,BlockGame &theGame, BlockGame &theGame2);

int OpenControlsBox(int x, int y, int player)
{
	int mousex, mousey;
	Uint8 *keys;
	bool done =false;
	char *keyname;
	MakeBackground(1024,768);
	while(!done)
	{
		SDL_Delay(10);
		DrawIMG(background, screen, 0, 0);
		DrawIMG(changeButtonsBack,screen,x,y);
		if(player == 0)
			SFont_Write(screen,fBlueFont,x+40,y+2,"Player 1 keys");
		else
			SFont_Write(screen,fBlueFont,x+40,y+2,"Player 2 keys");
		SFont_Write(screen,fBlueFont,x+6,y+50,"Up");
		keyname = getKeyName(keySettings[player].up);
		SFont_Write(screen,fBlueFont,x+200,y+50,keyname);
		SFont_Write(screen,fBlueFont,x+6,y+100,"Down");
		keyname = getKeyName(keySettings[player].down);
		SFont_Write(screen,fBlueFont,x+200,y+100,keyname);
		SFont_Write(screen,fBlueFont,x+6,y+150,"Left");
		keyname = getKeyName(keySettings[player].left);
		SFont_Write(screen,fBlueFont,x+200,y+150,keyname);
		SFont_Write(screen,fBlueFont,x+6,y+200,"Right");
		keyname = getKeyName(keySettings[player].right);
		SFont_Write(screen,fBlueFont,x+200,y+200,keyname);
		SFont_Write(screen,fBlueFont,x+6,y+250,"Push");
		keyname = getKeyName(keySettings[player].push);
		SFont_Write(screen,fBlueFont,x+200,y+250,keyname);
		SFont_Write(screen,fBlueFont,x+6,y+300,"Change");
		keyname = getKeyName(keySettings[player].change);
		SFont_Write(screen,fBlueFont,x+200,y+300,keyname);
		//Ask for mouse play
		SFont_Write(screen,fBlueFont,x+6,y+350,"Mouse play?");
		DrawIMG(iLevelCheckBox,screen,x+220,y+350);
		if(((player==0)&&(mouseplay1))||((player==2)&&(mouseplay2)))
		  DrawIMG(iLevelCheck,screen,x+220,y+350); //iLevelCheck witdh is 42
		//Ask for joypad play
		SFont_Write(screen,fBlueFont,x+300,y+350,"Joypad?");
		DrawIMG(iLevelCheckBox,screen,x+460,y+350);
		if(((player==0)&&(joyplay1))||((player==2)&&(joyplay2)))
		  DrawIMG(iLevelCheck,screen,x+460,y+350); //iLevelCheck witdh is 42
		for(int i=1; i<7; i++)
		DrawIMG(bChange,screen,x+420,y+50*i);
		SDL_Event event;

		while(SDL_PollEvent(&event))
		{
			if ( event.type == SDL_QUIT )  {done = true;}

			if(event.type == SDL_KEYDOWN)
			{
				if (event.key.keysym.sym == SDLK_ESCAPE) 
					done = true;
			}
		}	//PollEvent

		keys = SDL_GetKeyState(NULL);

		SDL_GetMouseState(&mousex,&mousey);    

		// If the mouse button is released, make bMouseUp equal true
		if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
		{
			bMouseUp=true;
		}
  
		if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
		{
			bMouseUp = false;

			if((mousex>(420+x)) && (mousex<(540+x)) && (mousey>(50+y)) && (mousey<(90+y)))
			{
				//up
				bool finnish = false;
				while(!finnish)
				 while ( SDL_PollEvent(&event) )
				 {
				  if(event.type == SDL_KEYDOWN)
				  {
					 if(event.key.keysym.sym != SDLK_ESCAPE)
						 keySettings[player].up = event.key.keysym.sym;
					 finnish = true;
				  }
				 }
			} //up
			if((mousex>(420+x)) && (mousex<(540+x)) && (mousey>(100+y)) && (mousey<(140+y)))
			{
				//down
				bool finnish = false;
				while(!finnish)
				 while ( SDL_PollEvent(&event) )
				 {
				  if(event.type == SDL_KEYDOWN)
				  {
					 if(event.key.keysym.sym != SDLK_ESCAPE)
						 keySettings[player].down = event.key.keysym.sym;
					 finnish = true;
				  }
				 }
			} //down
			if((mousex>(420+x)) && (mousex<(540+x)) && (mousey>(150+y)) && (mousey<(190+y)))
			{
				//left
				bool finnish = false;
				while(!finnish)
				 while ( SDL_PollEvent(&event) )
				 {
				  if(event.type == SDL_KEYDOWN)
				  {
					 if(event.key.keysym.sym != SDLK_ESCAPE)
						 keySettings[player].left = event.key.keysym.sym;
					 finnish = true;
				  }
				 }
			} //left
			if((mousex>(420+x)) && (mousex<(540+x)) && (mousey>(200+y)) && (mousey<(240+y)))
			{
				//right
				bool finnish = false;
				while(!finnish)
				 while ( SDL_PollEvent(&event) )
				 {
				  if(event.type == SDL_KEYDOWN)
				  {
					 if(event.key.keysym.sym != SDLK_ESCAPE)
						 keySettings[player].right = event.key.keysym.sym;
					 finnish = true;
				  }
				 }
			} //right
			if((mousex>(420+x)) && (mousex<(540+x)) && (mousey>(250+y)) && (mousey<(290+y)))
			{
				//push
				bool finnish = false;
				while(!finnish)
				 while ( SDL_PollEvent(&event) )
				 {
				  if(event.type == SDL_KEYDOWN)
				  {
					 if(event.key.keysym.sym != SDLK_ESCAPE)
						 keySettings[player].push = event.key.keysym.sym;
					 finnish = true;
				  }
				 }
			} //push
			if((mousex>(420+x)) && (mousex<(540+x)) && (mousey>(300+y)) && (mousey<(340+y)))
			{
				//change
				bool finnish = false;
				while(!finnish)
				 while ( SDL_PollEvent(&event) )
				 {
				  if(event.type == SDL_KEYDOWN)
				  {
					 if(event.key.keysym.sym != SDLK_ESCAPE)
						 keySettings[player].change = event.key.keysym.sym;
					 finnish = true;
				  }
				 }
			} //change
			//mouseplay:
            if((mousex>(220+x)) && (mousex<(262+x)) && (mousey>(350+y)) && (mousey<(392+y)))
			{
                if (player==0)
                {
                    mouseplay1 = !mouseplay1;
                }
                else
                {
                    mouseplay2 = !mouseplay2;
                }
            }
            //Joyplay:
            if((mousex>(460+x)) && (mousex<(502+x)) && (mousey>(350+y)) && (mousey<(392+y)))
			{
                if (player==0)
                {
                    joyplay1 = !joyplay1;
                }
                else
                {
                    joyplay2 = !joyplay2;
                }
            }
		}	//get mouse state

		DrawIMG(mouse,screen,mousex,mousey);
		SDL_Flip(screen);
	}	//while !done
	DrawIMG(background, screen, 0, 0);
	return 0;
}


//Dialogbox
bool OpenDialogbox(int x, int y, char *name)
{
	bool done = false;     //We are done!
	bool accept = false;   //New name is accepted! (not Cancelled)
    bool repeating = false; //The key is being held (BACKSPACE)
    const int repeatDelay = 200;    //Repeating
	unsigned long time = 0;
	ReadKeyboard rk = ReadKeyboard(name);
	Uint8* keys;
	string strHolder;
	MakeBackground(1024,768);
	DrawIMG(background,screen,0,0);
	while(!done)
	{
	DrawIMG(dialogBox,screen,x,y);
	SFont_Write(screen,fBlueFont,x+40,y+72,rk.GetString());
	strHolder = rk.GetString();
	//cout << "hej\n" << (int)rk.CharsBeforeCursor() << endl;
	strHolder.erase((int)rk.CharsBeforeCursor());
	
	if(((SDL_GetTicks()/600)%2)==1)
	SFont_Write(screen,fBlueFont,x+40+SFont_TextWidth(fBlueFont,strHolder.c_str()),y+69,"|");

	SDL_Event event;
    
    while ( SDL_PollEvent(&event) )
    {
      if ( event.type == SDL_QUIT )  {  done = true; accept = false; }

      if ( event.type == SDL_KEYDOWN )
      {
		if ( (event.key.keysym.sym == SDLK_RETURN)||(event.key.keysym.sym == SDLK_KP_ENTER) ) { done = true; accept = true;}
		else 
		if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { done = true; accept = false;}
		else if(!(event.key.keysym.sym == SDLK_BACKSPACE)){if((rk.ReadKey(event.key.keysym.sym))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0);}
		else if((event.key.keysym.sym == SDLK_BACKSPACE)&&(!repeating)){if((rk.ReadKey(event.key.keysym.sym))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0); repeating = true; time=SDL_GetTicks();}
	  }

	}	//while(event)

    if(SDL_GetTicks()>(time+repeatDelay))
	  {
           time = SDL_GetTicks();
           keys = SDL_GetKeyState(NULL);
	       if( (keys[SDLK_BACKSPACE])&&(repeating) )
           {if((rk.ReadKey(SDLK_BACKSPACE))&&(SoundEnabled)&&(!NoSound))Mix_PlayChannel(1,typingChunk,0);}
           else
           repeating = false;
       }

	SDL_Flip(screen); //Update screen
	}	//while(!done)
	strcpy(name,rk.GetString());
	bScreenLocked = false;
	showDialog = false;
	return accept;
}


//Open a puzzle file
bool OpenFileDialogbox(int x, int y, char *name)
{
	bool done = false;	//We are done!
	int mousex, mousey;
	ListFiles lf = ListFiles();
#ifdef SHAREDIR	
	string folder = (string)SHAREDIR+(string)"/res";
	cout << "Looking in " << folder << endl;
	lf.setDictory(folder.c_str());
#else
	lf.setDictory("./res");
#endif
#ifdef __unix__
	string homeFolder = (string)getenv("HOME")+(string)"/.gamesaves/blockattack/puzzles";
	lf.setDictory2(homeFolder.c_str());
#endif
	Uint8* keys;
	string strHolder;
	MakeBackground(1024,768);
	DrawIMG(background,screen,0,0);
	DrawIMG(bForward,background,x+460,y+420);
	DrawIMG(bBack,background,x+20,y+420);
	while(!done)
	{
		DrawIMG(background,screen,0,0);
		const int nrOfFiles = 10;
		DrawIMG(changeButtonsBack,screen,x,y);
		for(int i=0;i<nrOfFiles;i++)
		{
			SFont_Write(screen,fBlueFont,x+10,y+10+36*i,lf.getFileName(i).c_str());
		}

		SDL_Event event;
    
    		while ( SDL_PollEvent(&event) )
    		{
      			if ( event.type == SDL_QUIT )  {  done = true; }

      			if ( event.type == SDL_KEYDOWN )
			{
				if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { done = true;}

				if ( (event.key.keysym.sym == SDLK_RIGHT) ) { lf.forward(); }

				if ( (event.key.keysym.sym == SDLK_LEFT) ) { lf.back(); }
			}

		} //while(event)
		
		SDL_GetMouseState(&mousex,&mousey);    

		// If the mouse button is released, make bMouseUp equal true
		if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
		{
			bMouseUp=true;
		}
  
		if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
		{
			bMouseUp = false;

			//The Forward Button:
			if( (mousex>x+460) && (mousex<x+460+120) && (mousey>y+420) && (mousey<y+420+40) )
			{
				lf.forward();
			}

			//The back button:
			if( (mousex>x+20) && (mousex<x+20+120) && (mousey>y+420) && (mousey<y+420+40) )
			{
				lf.back();
			}

			for(int i=0;i<10;i++)
			{
				if( (mousex>x+10) && (mousex<x+480) && (mousey>y+10+i*36) && (mousey<y+10+i*36+32) )
				{
					if(lf.fileExists(i))
					{
						strncpy(name,lf.getFileName(i).c_str(),28); //Problems occurs then larger than 28 (maybe 29)
						done=true; //The user have, clicked the purpose of this function is now complete
					}
				}
			}
		}
	
		DrawIMG(mouse,screen,mousex,mousey);
		SDL_Flip(screen); //Update screen
	}
}

//Open a saved replay
bool OpenReplayDialogbox(int x, int y, char *name)
{
	bool done = false;	//We are done!
	int mousex, mousey;
	ListFiles lf = ListFiles();
	cout << "Ready to set directory!" << endl;
	#ifdef __unix__
		string dictory = (string)getenv("HOME")+(string)"/.gamesaves/blockattack/replays";
	#elif WIN32
		string dictory = getMyDocumentsPath()+(string)"/My Games/blockattack/replays";
	#else
		string dictory = "./replays";
	#endif
	lf.setDictory(dictory);
	cout << "Directory sat" << endl;
	Uint8* keys;
	string strHolder;
	MakeBackground(1024,768);
	DrawIMG(background,screen,0,0);
	DrawIMG(bForward,background,x+460,y+420);
	DrawIMG(bBack,background,x+20,y+420);
	while(!done)
	{
		DrawIMG(background,screen,0,0);
		const int nrOfFiles = 10;
		DrawIMG(changeButtonsBack,screen,x,y);
		for(int i=0;i<nrOfFiles;i++)
		{
			SFont_Write(screen,fBlueFont,x+10,y+10+36*i,lf.getFileName(i).c_str());
		}

		SDL_Event event;
    
    		while ( SDL_PollEvent(&event) )
    		{
      			if ( event.type == SDL_QUIT )  {  done = true; return false;}

      			if ( event.type == SDL_KEYDOWN )
			{
				if ( (event.key.keysym.sym == SDLK_ESCAPE) ) { done = true; return false;}

				if ( (event.key.keysym.sym == SDLK_RIGHT) ) { lf.forward(); }

				if ( (event.key.keysym.sym == SDLK_LEFT) ) { lf.back(); }
			}

		} //while(event)
		
		SDL_GetMouseState(&mousex,&mousey);    

		// If the mouse button is released, make bMouseUp equal true
		if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
		{
			bMouseUp=true;
		}
  
		if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
		{
			bMouseUp = false;

			//The Forward Button:
			if( (mousex>x+460) && (mousex<x+460+120) && (mousey>y+420) && (mousey<y+420+40) )
			{
				lf.forward();
			}

			//The back button:
			if( (mousex>x+20) && (mousex<x+20+120) && (mousey>y+420) && (mousey<y+420+40) )
			{
				lf.back();
			}

			for(int i=0;i<10;i++)
			{
				if( (mousex>x+10) && (mousex<x+480) && (mousey>y+10+i*36) && (mousey<y+10+i*36+32) )
				{
					if(lf.fileExists(i))
					{
						strncpy(name,lf.getFileName(i).c_str(),28); //Problems occurs then larger than 28 (maybe 29)
						done=true; //The user have, clicked the purpose of this function is now complete
						return true;
					}
				}
			}
		}
	
		DrawIMG(mouse,screen,mousex,mousey);
		SDL_Flip(screen); //Update screen
	}
}


//draws options:
inline void DrawOptions(int x, int y)
{
	if(MusicEnabled) DrawIMG(bOn,optionsBack,400,120);
	else DrawIMG(bOff,optionsBack,400,120);
	if(SoundEnabled) DrawIMG(bOn,optionsBack,400,170);
	else DrawIMG(bOff,optionsBack,400,170);
	if(bFullscreen) DrawIMG(bOn,optionsBack,400,220);
	else DrawIMG(bOff,optionsBack,400,220);	
	DrawIMG(bChange,optionsBack,230,435);
	DrawIMG(bChange,optionsBack,410,435);
	DrawIMG(bChange,optionsBack,230,500);
	DrawIMG(bChange,optionsBack,410,500);
	DrawIMG(optionsBack,screen,x,y);
}  //drawOptions

//Draws the balls and explosions
void DrawBalls()
{
    for(int i = 0; i< maxNumberOfBalls; i++)
    {
        if(theBallManeger.ballUsed[i])
        {
            DrawIMG(balls[theBallManeger.ballArray[i].getColor()],screen,theBallManeger.ballArray[i].getX(),theBallManeger.ballArray[i].getY());
        } //if used    
        if(theExplosionManeger.explosionUsed[i])
        {
            DrawIMG(explosion[theExplosionManeger.explosionArray[i].getFrame()],screen,theExplosionManeger.explosionArray[i].getX(),theExplosionManeger.explosionArray[i].getY());
        }
        if(theTextManeger.textUsed[i])
        {
        	//cout << "Printing text: " << theTextManeger.textArray[i].getText() << endl;
            int x = theTextManeger.textArray[i].getX()-SFont_TextWidth(fSmallFont,theTextManeger.textArray[i].getText())/2;
            int y = theTextManeger.textArray[i].getY()-SFont_TextHeight(fSmallFont)/2;
            DrawIMG(iChainBack,screen,x,y);
            SFont_Write(screen,fSmallFont,x+(25-SFont_TextWidth(fSmallFont,theTextManeger.textArray[i].getText()))/2,y+(25-SFont_TextHeight(fSmallFont))/2,theTextManeger.textArray[i].getText());
        }
    } //for    
}    //DrawBalls

//Removes the old balls
void UndrawBalls()
{
    for(int i = 0; i< maxNumberOfBalls; i++)
    {
        if(theBallManeger.oldBallUsed[i])
        {
            DrawIMG(background,screen,theBallManeger.oldBallArray[i].getX(),theBallManeger.oldBallArray[i].getY(),ballSize,ballSize,theBallManeger.oldBallArray[i].getX(),theBallManeger.oldBallArray[i].getY());
        } //if used    
        if(theExplosionManeger.oldExplosionUsed[i])
        {
            DrawIMG(background,screen,theExplosionManeger.oldExplosionArray[i].getX(),theExplosionManeger.oldExplosionArray[i].getY(),70,120,theExplosionManeger.oldExplosionArray[i].getX(),theExplosionManeger.oldExplosionArray[i].getY());
        }
        if(theTextManeger.oldTextUsed[i])
        {
            int x = theTextManeger.oldTextArray[i].getX()-SFont_TextWidth(fSmallFont,theTextManeger.oldTextArray[i].getText())/2;
            int y = theTextManeger.oldTextArray[i].getY()-SFont_TextHeight(fSmallFont)/2;
            DrawIMG(background,screen,x,y,25,25,x,y);
        }
    } //for    
}   //UndrawBalls

//draws everything
void DrawEverything(int xsize, int ysize,BlockGame &theGame, BlockGame &theGame2)
{
  SDL_ShowCursor(SDL_DISABLE);
  //draw background:
  if(forceredraw != 1)
  {
  
        UndrawBalls();
        DrawIMG(background,screen,oldMousex,oldMousey,32,32,oldMousex,oldMousey);
        DrawIMG(background,screen,oldBubleX,oldBubleY,140,50,oldBubleX,oldBubleY);

  
  DrawIMG(background,screen,350,200,120,200,350,200);
  DrawIMG(background,screen,830,200,120,200,830,200);
  DrawIMG(background,screen,800,0,140,50,800,0);
  
  DrawIMG(background,screen,50,60,300,50,50,60);
  DrawIMG(background,screen,510,60,300,50,510,60);
  }
  else
  DrawIMG(background,screen,0,0);
  //draw bottons (should be moves and drawn directly to background once)
if(!networkActive) //We don't show the menu while running server or connected to a server
{
  //Here we draw the menu
  DrawIMG(bNewGame, screen, 0, 0);
  DrawIMG(bOptions, screen, 120,0);
  DrawIMG(bHighScore, screen, 2*120,0);
  DrawIMG(bReplay,screen,3*120,0);
}
else
{ //If network is active
  DrawIMG(bBack, screen, 0, 0); //Display a disconnect button
}
  DrawIMG(bExit, screen, xsize-120,ysize-120);
  //DrawIMG(boardBackBack,screen,theGame.topx-60,theGame.topy-68);
  DrawIMG(theGame.sBoard,screen,theGame.topx,theGame.topy);
  string strHolder;
  strHolder = itoa(theGame.score+theGame.handicap);
  SFont_Write(screen,fBlueFont,theGame.topx+310,theGame.topy+100,strHolder.c_str());
  if(theGame.AI_Enabled)
  	SFont_Write(screen,fBlueFont,theGame.topx+10,theGame.topy-40,"CPU");
  else
  if(!singlePuzzle)
  	SFont_Write(screen,fBlueFont,theGame.topx+10,theGame.topy-40,player1name);
  if(theGame.timetrial)
  {
      int tid = (int)SDL_GetTicks()-theGame.gameStartedAt;
      int minutes;
      int seconds;
      if(tid>=0)
      {
        minutes = (2*60*1000-(abs((int)SDL_GetTicks()-theGame.gameStartedAt)))/60/1000;
        seconds = ((2*60*1000-(abs((int)SDL_GetTicks()-theGame.gameStartedAt)))%(60*1000))/1000;
      }
      else
      {
            minutes = ((abs((int)SDL_GetTicks()-theGame.gameStartedAt)))/60/1000;
            seconds = (((abs((int)SDL_GetTicks()-theGame.gameStartedAt)))%(60*1000))/1000;
        }
      if(theGame.bGameOver) minutes=0;
      if(theGame.bGameOver) seconds=0;
      if(seconds>9) 
      strHolder = itoa(minutes)+":"+itoa(seconds);
      else strHolder = itoa(minutes)+":0"+itoa(seconds);
  	  if((SoundEnabled)&&(!NoSound)&&(tid>0)&&(seconds<5)&&(minutes == 0)&&(seconds>1)&&(!(Mix_Playing(6)))) Mix_PlayChannel(6,heartBeat,0);
	  SFont_Write(screen,fBlueFont,theGame.topx+310,theGame.topy+150,strHolder.c_str());
  }    
  else
  {
      int minutes = ((abs((int)SDL_GetTicks()-theGame.gameStartedAt)))/60/1000;
      int seconds = (((abs((int)SDL_GetTicks()-theGame.gameStartedAt)))%(60*1000))/1000;
      if(theGame.bGameOver) minutes=(theGame.gameEndedAfter/1000/60)%100;
      if(theGame.bGameOver) seconds=(theGame.gameEndedAfter/1000)%60;
      if(seconds>9) 
      	strHolder = itoa(minutes)+":"+itoa(seconds);
      else 
      	strHolder = itoa(minutes)+":0"+itoa(seconds);
      SFont_Write(screen,fBlueFont,theGame.topx+310,theGame.topy+150,strHolder.c_str());
  }    
  strHolder = itoa(theGame.chain);
  SFont_Write(screen,fBlueFont,theGame.topx+310,theGame.topy+200,strHolder.c_str());
  //drawspeedLevel:
  strHolder = itoa(theGame.speedLevel);
  SFont_Write(screen,fBlueFont,theGame.topx+310,theGame.topy+250,strHolder.c_str());
  if((theGame.stageClear) &&(theGame.topy+700+50*(theGame.stageClearLimit-theGame.linesCleared)-theGame.pixels-1<600+theGame.topy)) 
  {
    oldBubleX = theGame.topx+280;
    oldBubleY = theGame.topy+650+50*(theGame.stageClearLimit-theGame.linesCleared)-theGame.pixels-1;
    DrawIMG(stageBobble,screen,theGame.topx+280,theGame.topy+650+50*(theGame.stageClearLimit-theGame.linesCleared)-theGame.pixels-1);
  }
  //player1 finnish, player2 start
  //DrawIMG(boardBackBack,screen,theGame2.topx-60,theGame2.topy-68);
  DrawIMG(theGame2.sBoard,screen,theGame2.topx,theGame2.topy);
  strHolder = itoa(theGame2.score+theGame2.handicap);
  SFont_Write(screen,fBlueFont,theGame2.topx+310,theGame2.topy+100,strHolder.c_str());
  if(theGame2.AI_Enabled)
  	SFont_Write(screen,fBlueFont,theGame2.topx+10,theGame2.topy-40,"CPU");
  else
  SFont_Write(screen,fBlueFont,theGame2.topx+10,theGame2.topy-40,theGame2.name);
  if(theGame2.timetrial)
  {
      int tid = (int)SDL_GetTicks()-theGame2.gameStartedAt;
      int minutes; 
      int seconds; 
      if(tid>=0)
      {
        minutes = (2*60*1000-(abs((int)SDL_GetTicks()-theGame2.gameStartedAt)))/60/1000;
        seconds = ((2*60*1000-(abs((int)SDL_GetTicks()-theGame2.gameStartedAt)))%(60*1000))/1000;
      }
      else
      {
            minutes = ((abs((int)SDL_GetTicks()-theGame2.gameStartedAt)))/60/1000;
            seconds = (((abs((int)SDL_GetTicks()-theGame2.gameStartedAt)))%(60*1000))/1000;
        }
      if(theGame2.bGameOver) minutes=0;
      if(theGame2.bGameOver) seconds=0;
      if(seconds>9) 
        strHolder = itoa(minutes)+":"+itoa(seconds);
      else 
        strHolder = itoa(minutes)+":0"+itoa(seconds);
	  if((SoundEnabled)&&(!NoSound)&&(tid>0)&&(seconds<5)&&(minutes == 0)&&(seconds>1)&&(!(Mix_Playing(6)))) Mix_PlayChannel(6,heartBeat,0);
      SFont_Write(screen,fBlueFont,theGame2.topx+310,theGame2.topy+150,strHolder.c_str());
  }    
  else
  {
      int minutes = (abs((int)SDL_GetTicks()-theGame2.gameStartedAt))/60/1000;
      int seconds = (abs((int)SDL_GetTicks()-theGame2.gameStartedAt)%(60*1000))/1000;
      if(theGame2.bGameOver) minutes=(theGame2.gameEndedAfter/1000/60)%100;
      if(theGame2.bGameOver) seconds=(theGame2.gameEndedAfter/1000)%60;
      if(seconds>9) 
        strHolder = itoa(minutes)+":"+itoa(seconds);
      else 
        strHolder = itoa(minutes)+":0"+itoa(seconds);
      SFont_Write(screen,fBlueFont,theGame2.topx+310,theGame2.topy+150,strHolder.c_str());
  }    
  strHolder = itoa(theGame2.chain);
  SFont_Write(screen,fBlueFont,theGame2.topx+310,theGame2.topy+200,strHolder.c_str());
  strHolder = itoa(theGame2.speedLevel);
  SFont_Write(screen,fBlueFont,theGame2.topx+310,theGame2.topy+250,strHolder.c_str());

  //player2 finnish
 
  if(bNewGameOpen)
  {
      DrawIMG(b1player,screen,0,40);
      DrawIMG(b2players,screen,0,80);
#ifdef NETWORK
	  DrawIMG(bNetwork,screen,0,120);
#endif
	  if(b1playerOpen)
	  {
		  DrawIMG(bEndless,screen,120,40);
		  DrawIMG(bTimeTrial,screen,120,80);
		  DrawIMG(bStageClear,screen,120,120);
		  DrawIMG(bPuzzle,screen,120,160);
		  DrawIMG(bVsMode,screen,120,200);
	  }
	  else
	  if(b2playersOpen)
	  {
		  DrawIMG(bTimeTrial,screen,120,80);
		  DrawIMG(bVsMode,screen,120,120);
	  }
#ifdef NETWORK
	  else
	  if(bNetworkOpen)
	  {
	  	  DrawIMG(bHost,screen,120,120);
	  	  DrawIMG(bConnect,screen,120,160);
	  }
#endif
  }   
  if(bOptionsOpen)
  {
      DrawIMG(bConfigure,screen,120,40);
      DrawIMG(bSelectPuzzle,screen,120,80);
      DrawIMG(bVsMode,screen,120,120);
  } 
  if(bReplayOpen)
  {
  	DrawIMG(bSave,screen,360,40);
  	DrawIMG(bLoad,screen,360,80);
  }
  if(showHighscores) DrawHighscores(100,100);
  if(showOptions) DrawOptions(100,100);

  DrawBalls();
	
#if defined(DEBUG)
  Frames++;
	if(SDL_GetTicks() >= Ticks + 1000)
	{
		if(Frames > 999) Frames=999;
		sprintf(FPS, "%i fps", Frames);
		Frames = 0;
		Ticks = SDL_GetTicks();
	}

	SFont_Write(screen,fBlueFont,800,4,FPS);
#endif
 
  //SDL_Flip(screen); //Update screen, now called outside DrawEvrything, bacause the mouse needs to be painted
  
}

//Generates the standard background
void MakeBackground(int xsize,int ysize)
{
    DrawIMG(backgroundImage,background,0,0);
    standardBackground = true;
}    

//Generates the background with red board backs
void MakeBackground(int xsize,int ysize,BlockGame &theGame, BlockGame &theGame2)
{
    DrawIMG(backgroundImage,background,0,0);
    DrawIMG(boardBackBack,background,theGame.topx-60,theGame.topy-68);
    DrawIMG(boardBackBack,background,theGame2.topx-60,theGame2.topy-68);
    standardBackground = false;
}    


//The function that allows the player to choose PuzzleLevel
int PuzzleLevelSelect()
{
    const int xplace = 200;
	const int yplace = 300;
	Uint8 *keys;
	int levelNr, mousex, mousey;
	bool levelSelected = false;
	bool tempBool;
	
	//Loads the levels, if they havn't been loaded:
    LoadPuzzleStages();
    
	//Keeps track of background;
    int nowTime=SDL_GetTicks();
  
    ifstream puzzleFile(puzzleSavePath.c_str(),ios::binary);
    MakeBackground(1024,768);
    if(puzzleFile)
    {
        for(int i=0;(i<nrOfPuzzles)&&(!puzzleFile.eof()); i++)
        {
            puzzleFile.read(reinterpret_cast<char*>(&tempBool),sizeof(bool));
            puzzleCleared[i] = tempBool;
        }
        puzzleFile.close();
    }
    else
    {
        tempBool = false;
        for(int i=0; i<nrOfPuzzles; i++)
            puzzleCleared[i] = tempBool;
    }  
    
    do
	{
		nowTime=SDL_GetTicks();

		
		DrawIMG(background, screen, 0, 0);
		DrawIMG(iCheckBoxArea,screen,xplace,yplace);
		SFont_Write(screen,fBlueFont,xplace+12,yplace+2,"Select Puzzle");
		//Now drow the fields you click in (and a V if clicked):
		for(int i = 0; i < nrOfPuzzles;i++)
		{
            DrawIMG(iLevelCheckBox,screen,xplace+10+(i%10)*50, yplace+60+(i/10)*50);
			if(puzzleCleared[i]==true) DrawIMG(iLevelCheck,screen,xplace+10+(i%10)*50, yplace+60+(i/10)*50);
		}
		
		SDL_Event event;
		while ( SDL_PollEvent(&event) )
		if ( event.type == SDL_KEYDOWN )
		{
			if ( event.key.keysym.sym == SDLK_ESCAPE ) {levelNr = -1; levelSelected = true;}
		}

		keys = SDL_GetKeyState(NULL);

		SDL_GetMouseState(&mousex,&mousey);    

		// If the mouse button is released, make bMouseUp equal true
		if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
		{
			bMouseUp=true;
		}
  
		if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
		{
			bMouseUp = false;

			int levelClicked = -1;
			int i;
			for(i = 0; (i<nrOfPuzzles/10)||((i<nrOfPuzzles/10+1)&&(nrOfPuzzles%10 != 0)); i++)
			if((60+i*50<mousey-yplace)&&(mousey-yplace<i*50+92))
				levelClicked = i*10;
			i++;
			if(levelClicked != -1)
			for(int j = 0; ((j<nrOfStageLevels%(i*10))&&(j<10)); j++)
			if((10+j*50<mousex-xplace)&&(mousex-xplace<j*50+42))
			{
				levelClicked +=j;
				levelSelected = true;
				levelNr = levelClicked;
			}
		}

		DrawIMG(mouse,screen,mousex,mousey);
		SDL_Flip(screen); //draws it all to the screen

	} while(!levelSelected);
	DrawIMG(background, screen, 0, 0);
	return levelNr;
}

//The function that allows the player to choose Level number
int StageLevelSelect()
{
	const int xplace = 200;
	const int yplace = 300;
	Uint8 *keys;
	int levelNr, mousex, mousey;
	bool levelSelected = false;
	bool tempBool;

  //Keeps track of background;
  //int nowTime=SDL_GetTicks();

  MakeBackground(1024,768);
  ifstream stageFile(stageClearSavePath.c_str(),ios::binary);
  if(stageFile)
  {
	  for(int i = 0; i<nrOfStageLevels; i++)
	  {
		  stageFile.read(reinterpret_cast<char*>(&tempBool),sizeof(bool));
		  stageCleared[i]=tempBool;
	  }
	  stageFile.close();
  }
  else
  {
	  for(int i=0; i<nrOfStageLevels; i++)
		  stageCleared[i]= false;
  }


	do
	{
		//nowTime=SDL_GetTicks();
		DrawIMG(background, screen, 0, 0);
		DrawIMG(iCheckBoxArea,screen,xplace,yplace);
		SFont_Write(screen,fBlueFont,xplace+12,yplace+2,"Stage Clear Level Select");
		for(int i = 0; i < nrOfStageLevels;i++)
		{
            DrawIMG(iLevelCheckBox,screen,xplace+10+(i%10)*50, yplace+60+(i/10)*50);
			if(stageCleared[i]==true) DrawIMG(iLevelCheck,screen,xplace+10+(i%10)*50, yplace+60+(i/10)*50);
		}
		
		SDL_Event event;
		while ( SDL_PollEvent(&event) )
		if ( event.type == SDL_KEYDOWN )
		{
			if ( event.key.keysym.sym == SDLK_ESCAPE ) {levelNr = -1; levelSelected = true;}
		}

		keys = SDL_GetKeyState(NULL);

		SDL_GetMouseState(&mousex,&mousey);    

		// If the mouse button is released, make bMouseUp equal true
		if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
		{
			bMouseUp=true;
		}
  
		if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
		{
			bMouseUp = false;

			int levelClicked = -1;
			int i;
			for(i = 0; (i<nrOfStageLevels/10)||((i<nrOfStageLevels/10+1)&&(nrOfStageLevels%10 != 0)); i++)
			if((60+i*50<mousey-yplace)&&(mousey-yplace<i*50+92))
				levelClicked = i*10;
			i++;
			if(levelClicked != -1)
			for(int j = 0; ((j<nrOfStageLevels%(i*10))&&(j<10)); j++)
			if((10+j*50<mousex-xplace)&&(mousex-xplace<j*50+42))
			{
				levelClicked +=j;
				levelSelected = true;
				levelNr = levelClicked;
			}
		}

		DrawIMG(mouse,screen,mousex,mousey);
		SDL_Flip(screen); //draws it all to the screen

	} while(!levelSelected);
	DrawIMG(background, screen, 0, 0);
	return levelNr;
}

//Ask user for what AI level he will compete agains, return the number. Number must be 0..AIlevels
int startSingleVs()
{
	//Where to place the windows
	const int xplace = 200;
	const int yplace = 100;
	Uint8 *keys;	//To take keyboard input
	int mousex, mousey;	//To allow mouse
	bool done = false;	//When are we done?
	
	MakeBackground(1024,768);
	DrawIMG(changeButtonsBack,background,xplace,yplace);
	SFont_Write(background,fBlueFont,xplace+10,yplace+10,"1 : Very Easy");
	SFont_Write(background,fBlueFont,xplace+10,yplace+40,"2 : Easy");
	SFont_Write(background,fBlueFont,xplace+10,yplace+70,"3 : Below Normal");
	SFont_Write(background,fBlueFont,xplace+10,yplace+100,"4 : Normal");
	SFont_Write(background,fBlueFont,xplace+10,yplace+130,"5 : Above Normal");
	SFont_Write(background,fBlueFont,xplace+10,yplace+160,"6 : Hard");
	SFont_Write(background,fBlueFont,xplace+10,yplace+190,"7 : Hardest");
	DrawIMG(background, screen, 0, 0);
	SDL_Flip(screen);
	do
	{
		
		SDL_Delay(10);
		SDL_Event event;
		while ( SDL_PollEvent(&event) )
		if ( event.type == SDL_KEYDOWN )
		{
			if ( event.key.keysym.sym == SDLK_ESCAPE ) { done = true;}
			if ( event.key.keysym.sym == SDLK_RETURN ) { done = true;}
			if ( event.key.keysym.sym == SDLK_KP_ENTER ) { done = true;}
			if ( event.key.keysym.sym == SDLK_1 ) { return 0;}
			if ( event.key.keysym.sym == SDLK_2 ) { return 1;}
			if ( event.key.keysym.sym == SDLK_3 ) { return 2;}
			if ( event.key.keysym.sym == SDLK_4 ) { return 3;}
			if ( event.key.keysym.sym == SDLK_5 ) { return 4;}
			if ( event.key.keysym.sym == SDLK_6 ) { return 5;}
			if ( event.key.keysym.sym == SDLK_7 ) { return 6;}
			if ( event.key.keysym.sym == SDLK_KP1 ) { return 0;}
			if ( event.key.keysym.sym == SDLK_KP2 ) { return 1;}
			if ( event.key.keysym.sym == SDLK_KP3 ) { return 2;}
			if ( event.key.keysym.sym == SDLK_KP4 ) { return 3;}
			if ( event.key.keysym.sym == SDLK_KP5 ) { return 4;}
			if ( event.key.keysym.sym == SDLK_KP6 ) { return 5;}
			if ( event.key.keysym.sym == SDLK_KP7 ) { return 6;}
			
		}
		
		// If the mouse button is released, make bMouseUp equal true
		if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
		{
			bMouseUp=true;
		}
  
		if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
		{
			bMouseUp = false;
            
            for(int i=0; i<7;i++)
               {
                    if((mousex>xplace+10)&&(mousex<xplace+410)&&(mousey>yplace+10+i*30)&&(mousey<yplace+38+i*30))
                       return i;
               }
		}
		
		SDL_GetMouseState(&mousex,&mousey); 
		DrawIMG(background, screen, 0, 0);
		DrawIMG(mouse,screen,mousex,mousey);
		SDL_Flip(screen); //draws it all to the screen
	}while(!done);
	
	
	return 3; //Returns normal
}

//The function that allows the player to choose Level number
void startVsMenu()
{
	const int xplace = 200;
	const int yplace = 100;
	Uint8 *keys;
	int mousex, mousey;
	bool done = false;
	
  //Keeps track of background;
  //int nowTime=SDL_GetTicks();

  MakeBackground(1024,768);
  SFont_Write(background,fBlueFont,360,650,"Press ESC to accept");
  DrawIMG(bBack,background,1024/2-120/2,600);
	do
	{
		//nowTime=SDL_GetTicks();
		DrawIMG(background, screen, 0, 0);
		DrawIMG(changeButtonsBack,screen,xplace,yplace);
		SFont_Write(screen,fBlueFont,xplace+50,yplace+20,"Player 1");
		SFont_Write(screen,fBlueFont,xplace+300+50,yplace+20,"Player 2");
		SFont_Write(screen,fBlueFont,xplace+50,yplace+70,"Speed:");
		SFont_Write(screen,fBlueFont,xplace+50+300,yplace+70,"Speed:");
        for(int i=0; i<5;i++)
		{
                char levelS[2]; //level string;
                levelS[0]='1'+i;
                levelS[1]=0;
                SFont_Write(screen,fBlueFont,xplace+50+i*40,yplace+110,levelS);
                DrawIMG(iLevelCheckBox,screen,xplace+50+i*40,yplace+150);
                if(player1Speed==i)
                   DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+150);
        }
        for(int i=0; i<5;i++)
		{
                char levelS[2]; //level string;
                levelS[0]='1'+i;
                levelS[1]=0;
                SFont_Write(screen,fBlueFont,xplace+300+50+i*40,yplace+110,levelS);
                DrawIMG(iLevelCheckBox,screen,xplace+300+50+i*40,yplace+150);
                if(player2Speed==i)
                   DrawIMG(iLevelCheck,screen,xplace+300+50+i*40,yplace+150);
        }
        SFont_Write(screen,fBlueFont,xplace+50,yplace+200,"AI: ");
        DrawIMG(iLevelCheckBox,screen,xplace+50+70,yplace+200);
        if(player1AI)
           DrawIMG(iLevelCheck,screen,xplace+50+70,yplace+200);
        SFont_Write(screen,fBlueFont,xplace+50,yplace+250,"TT Handicap: ");
        SFont_Write(screen,fBlueFont,xplace+50+300,yplace+200,"AI: ");
        DrawIMG(iLevelCheckBox,screen,xplace+50+70+300,yplace+200);
        if(player2AI)
           DrawIMG(iLevelCheck,screen,xplace+50+70+300,yplace+200);
        SFont_Write(screen,fBlueFont,xplace+50+300,yplace+250,"TT Handicap: ");
        for(int i=0; i<5;i++)
		{
                char levelS[2]; //level string;
                levelS[0]='1'+i;
                levelS[1]=0;
                SFont_Write(screen,fBlueFont,xplace+50+i*40,yplace+290,levelS);
                DrawIMG(iLevelCheckBox,screen,xplace+50+i*40,yplace+330);
                if(player1handicap==i)
                   DrawIMG(iLevelCheck,screen,xplace+50+i*40,yplace+330);
        }
        for(int i=0; i<5;i++)
		{
                char levelS[2]; //level string;
                levelS[0]='1'+i;
                levelS[1]=0;
                SFont_Write(screen,fBlueFont,xplace+50+i*40+300,yplace+290,levelS);
                DrawIMG(iLevelCheckBox,screen,xplace+50+i*40+300,yplace+330);
                if(player2handicap==i)
                   DrawIMG(iLevelCheck,screen,xplace+50+i*40+300,yplace+330);
        }
        		
		SDL_Event event;
		while ( SDL_PollEvent(&event) )
		if ( event.type == SDL_KEYDOWN )
		{
			if ( event.key.keysym.sym == SDLK_ESCAPE ) { done = true;}
			if ( event.key.keysym.sym == SDLK_RETURN ) { done = true;}
			if ( event.key.keysym.sym == SDLK_KP_ENTER ) { done = true;}
		}

		keys = SDL_GetKeyState(NULL);

		SDL_GetMouseState(&mousex,&mousey);    

		// If the mouse button is released, make bMouseUp equal true
		if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
		{
			bMouseUp=true;
		}
  
		if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
		{
			bMouseUp = false;
            
            if((mousex>xplace+50+70)&&(mousey>yplace+200)&&(mousex<xplace+50+70+30)&&(mousey<yplace+200+30))
               player1AI=!player1AI;
            if((mousex>xplace+50+70+300)&&(mousey>yplace+200)&&(mousex<xplace+50+70+30+300)&&(mousey<yplace+200+30))
               player2AI=!player2AI;
            for(int i=0; i<5;i++)
               {
                    if((mousex>xplace+50+i*40)&&(mousex<xplace+50+i*40+30)&&(mousey>yplace+150)&&(mousey<yplace+150+30))
                       player1Speed=i;
               }
            for(int i=0; i<5;i++)
               {
                    if((mousex>xplace+50+i*40+300)&&(mousex<xplace+50+i*40+30+300)&&(mousey>yplace+150)&&(mousey<yplace+150+30))
                       player2Speed=i;
               }    
            for(int i=0; i<5;i++)
               {
                    if((mousex>xplace+50+i*40)&&(mousex<xplace+50+i*40+30)&&(mousey>yplace+330)&&(mousey<yplace+330+30))
                       player1handicap=i;
               }
            for(int i=0; i<5;i++)
               {
                    if((mousex>xplace+50+i*40+300)&&(mousex<xplace+50+i*40+30+300)&&(mousey>yplace+330)&&(mousey<yplace+330+30))
                       player2handicap=i;
               }    
            if((mousex>1024/2-120/2)&&(mousex<1024/2+120/2)&&(mousey>600)&&(mousey<640))
               done = true;
		}

		DrawIMG(mouse,screen,mousex,mousey);
		SDL_Flip(screen); //draws it all to the screen
		SDL_Delay(10);

	} while(!done);
	DrawIMG(background, screen, 0, 0);
}

//This function will promt for the user to select another file for puzzle mode
void changePuzzleLevels()
{
     char theFileName[30];
     strcpy(theFileName,puzzleName.c_str());
     for(int i=puzzleName.length();i<30;i++)
        theFileName[i]=' ';
     theFileName[29]=0;
     if(OpenFileDialogbox(200,100,theFileName))
     {
        for(int i=28;((theFileName[i]==' ')&&(i>0));i--)
           theFileName[i]=0;
        puzzleName = theFileName;
        #if defined(__unix__)
        string home = getenv("HOME");
        puzzleSavePath = home+"/.gamesaves/blockattack/"+puzzleName+".save";
        #elif defined(_WIN32)
        string home = getenv("APPDATA");
        if(&home!=NULL)
        {
             puzzleSavePath = home+"/gamesaves/blockattack/"+puzzleName+".save";
        }
        else
        {
             puzzleSavePath = puzzleName+".save";    
        }
        #else
             puzzleSavePath = puzzleName+".save";
        #endif
     }
      
}

#ifdef NETWORK
//The network interface
class NetworkThing
{
	private:
	ENetAddress address;
    ENetHost * server;
	ENetHost * client;
    ENetPeer *peer;
    
	BlockGame *bgHome, *bgAway; //Pointers to the two games, so we can call the procedures
	bool weAreAServer, weAreAClient;
	bool weAreConnected;
	bool enemyIsReady;
	bool enemyHasStarted; //If we should have a ready button
	bool gameHasStarted; //If the player is GameOver it might just be because the game hasn't started yet... not if this is true!
	
	public:

	Uint32 theSeed;
	
	NetworkThing()
	{
		weAreAServer = false;
		weAreAClient = false;
		weAreConnected = false;
		enemyIsReady = false;
		enemyHasStarted = false;
		gameHasStarted = false; 
		if (enet_initialize () != 0)
    	{
        	fprintf (stderr, "An error occurred while initializing ENet.\n");
    	}
    	else
    	{
    		cout << "Network is working!" << endl;
    	}
    	atexit (enet_deinitialize);
	}
	
	//This function couses us to remove the connection to the other peer, plus destroying servers
	void ntDisconnect()
	{
		strcpy(bgAway->name,player2name);
		if(weAreConnected || weAreAClient || weAreAServer)
		{
			if(weAreAClient)
			{
				enet_peer_disconnect (peer);
				SDL_Delay(20);
				enet_host_destroy(client);
				weAreAClient = false;
				weAreConnected = false;
				enemyHasStarted = false;
			}
			else
			if(weAreAServer)
			{
				enet_host_destroy(server);
				weAreAServer = false;
				weAreConnected = false;
				enemyHasStarted = false;
			}
			//If the game is running then we disconnect, we are considered the looser!
			if((!bgHome->bGameOver)&&(!bgAway->bGameOver))
			{
				bgAway->setPlayerWon();
				bgHome->SetGameOver();
			}
			gameHasStarted = false;
		}
	};

	//Lets disconnect before we close...
	~NetworkThing()
	{
		cout << "Network system is going down" << endl;
		ntDisconnect();
	}
	
	void theGameHasStarted()
	{
		gameHasStarted = true;
	}

	//The NetworkThing needs to be able to call the models... here the pointers are set
	void setBGpointers(BlockGame *bg1, BlockGame *bg2)
	{
		bgHome = bg1;
		bgAway = bg2;
	}
	
	//Starts a server instance
	void startServer()
	{
		if(!weAreAServer)
		{
		ntDisconnect();
		
		/* Bind the server to the default localhost.     */
    	/* A specific host address can be specified by   */
    	/* enet_address_set_host (& address, "x.x.x.x"); */

    	address.host = ENET_HOST_ANY;
    	/* Bind the server to port SERVERPORT. */
    	address.port = SERVERPORT;

    	server = enet_host_create (& address /* the address to bind the server host to */, 
                                  1      /* allow up to 1 clients and/or outgoing connections */,
                                  0      /* assume any amount of incoming bandwidth */,
                                  0      /* assume any amount of outgoing bandwidth */);
    	if (server == NULL)
    	{
        	fprintf (stderr, 
                 "An error occurred while trying to create an ENet server host.\n");
     	
    	}
    	else
    	{
			weAreAServer = true;
			enemyIsReady = false;
			gameHasStarted = false;
			cout << "Server is listening on port " << SERVERPORT << endl;
		}
		}
	}
	
	void connectToServer(string server)
	{
		ENetAddress address;
    	ENetEvent event;
	
		enet_address_set_host (& address, server.c_str());
    	address.port = SERVERPORT;
	
		ntDisconnect();
		client = enet_host_create (NULL /* create a client host */,
                1 /* only allow 1 outgoing connection */,
                0 /* Unlimited downstream bandwidth */,
                0 /* Unlimted upstream bandwidth */);

    	if (client == NULL)
    	{
        	cout << "An error occurred while trying to create an ENet client host." << endl;
    	}
    	else
    	{
    		/* Initiate the connection, allocating the four channels 0 and 1 and 2 and 3. */
    		peer = enet_host_connect (client, & address, 4);    
    
    		if (peer == NULL)
    		{
       		     cout << "No available peers for initiating an ENet connection." << endl;
    		}
    		else
    		if (enet_host_service (client, & event, 2000) > 0 &&
        			event.type == ENET_EVENT_TYPE_CONNECT)
    		{
    			cout << "We are connected!" << endl;
				enemyIsReady = false;
				weAreAClient = true;
				weAreConnected = true;
				gameHasStarted = false;
			}
			else
			{
				cout << "Server didn't answer in time" << endl;
			}
		}
	}
	
	bool isConnected()
	{
		return (weAreConnected||weAreAServer);
	}
	
	bool isConnectedToPeer()
	{
		return weAreConnected;
	}

	//This function must be called in the game loop:
	void updateNetwork()
	{
		//Now we must send our own board:
		if(weAreConnected)
		{
		//cout << "Creating package" << endl;
    		boardPackage boardpack = bgHome->getPackage();
    		ENetPacket * packet = enet_packet_create (&boardpack, 
                                              sizeof(boardPackage), 
                                              0);
        	//Now lets send the package
		if(weAreAServer)
        		enet_host_broadcast (server, 0, packet);
        	else
        		if(weAreAClient)
        			enet_peer_send (peer, 0, packet);
        			//cout << "Package sent" << endl;

		//See if we are game over and in that case notify the other player
		if((gameHasStarted)&&(bgHome->bGameOver))
		{
			ENetPacket * packet = enet_packet_create("G",2,ENET_PACKET_FLAG_RELIABLE);
			if(weAreAServer)
        			enet_host_broadcast (server, 1, packet);
        		else
        			if(weAreAClient)
        				enet_peer_send (peer, 1, packet);
			gameHasStarted=false;
		}

		//Now lets see if we have something to throw at the opponent.
		Uint8 x,y,type;

		if(gameHasStarted)
		while(bgAway->popGarbage(&x,&y,&type))
		{ //if there are garbage to drop
			if(type==1)
			{
				x=255;
				y=255;
			}
			Uint16 g = ((Uint16)x)*256+(Uint16)y; //A 16-bit int containing everything
			ENetPacket * packet = enet_packet_create(&g,2,ENET_PACKET_FLAG_RELIABLE);
			if(weAreAServer)
        			enet_host_broadcast (server, 2, packet);
        		else
        			if(weAreAClient)
        				enet_peer_send (peer, 2, packet);
			cout << "We send a garbage block: " << (int)x << "," << (int)y << "==" << g << endl;
		}
		}
		ENetEvent event;
    
    	/* Wait up to 0 milliseconds for an event. */
    	while (((weAreAClient)&&(enet_host_service (client, & event, 0) > 0))||((weAreAServer)&&(enet_host_service (server, & event, 0) > 0)))
    	{
        	switch (event.type)
        	{
        	case ENET_EVENT_TYPE_CONNECT:
            	printf ("A new client connected from %x:%u.\n", 
                    event.peer -> address.host,
                    event.peer -> address.port);
				weAreConnected = true;
            	/* Store any relevant client information here. */
            	//event.peer -> data = "Client";
		{
			
			ENetPacket * namePacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE);
			//if(weAreAServer)
        			enet_host_broadcast (server, 3, namePacket);
			ENetPacket * answerPacket = enet_packet_create("version2",sizeof("version2"),ENET_PACKET_FLAG_RELIABLE);
        			enet_host_broadcast (server, 3, answerPacket);
			theSeed = time(0)/4;
			bgHome->putStartBlocks(theSeed); 
			ENetPacket * timePacket = enet_packet_create(&theSeed,sizeof(theSeed),ENET_PACKET_FLAG_RELIABLE);
				enet_host_broadcast (server, 3, timePacket);
			cout << "We send the seed: " << theSeed << endl;
		}
            	break;

        	case ENET_EVENT_TYPE_RECEIVE:
            	/*printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
                    event.packet -> dataLength,
                    event.packet -> data,
                    event.peer -> data,
                    event.channelID);*/
                 //cout << "Package recieved" << endl;
                if(event.channelID==0) //Unreliable (only boardPacks)
                {
                	boardPackage bpack;
                	//cout << "Package size: "<< event.packet->dataLength << " should be: " << sizeof(boardPackage) << endl;
                	memcpy(&bpack,(const char*)event.packet->data,sizeof(boardPackage));
                	bgAway->setBoard(bpack);
                }
		if(event.channelID==1) //reliable (used for GameOver notifications only!)
		{
			if((bgHome->bGameOver)&&(!bgHome->hasWonTheGame)&&(gameHasStarted))
			{
				bgHome->setDraw();
				bgAway->setDraw();
			}
			else
			{
				bgHome->setPlayerWon();
				bgAway->SetGameOver();
			}
			gameHasStarted=false;
		}

		if(event.channelID==2) //reliable (used for Garbage only!)
		{
			Uint16 g;
			memcpy(&g,event.packet->data,sizeof(Uint16));
			Uint8 x = (g/256);
			Uint8 y = (g%256);
			cout << "Recieved Garbage: " << (int)x << "," << (int)y << endl;
			if((x==255)&&(y==255))
				bgHome->CreateGreyGarbage();
			else
				bgHome->CreateGarbage(x,y);
		}

		if(event.channelID==3) //We have reacieved a name or a version number
		{
			if(event.packet->dataLength==sizeof(char[30])) //We have reveived a name
			{
				strcpy(bgAway->name,(const char*)event.packet->data);				
				cout << "The enemy name is: " << bgAway->name << " Length: " << sizeof(char[30])<< endl;
				if(weAreAClient) //We have just recieved the servers name and must send our own
				{
					ENetPacket * answerPacket = enet_packet_create(bgHome->name,sizeof(char[30]),ENET_PACKET_FLAG_RELIABLE);
        				enet_peer_send (peer, 3, answerPacket);
				}
			}
			else
			if(event.packet->dataLength==sizeof("2")) //We have recieved aversion number
			{
				if(0!=strcmp((const char*)event.packet->data,"version2"))
				{
					cout << "Incompatible version: " << event.packet->data << "!=" << "version2" << endl;
					ntDisconnect();
				}
				if(weAreAClient) //We will send our version number
				{
					ENetPacket * answerPacket = enet_packet_create("version2",sizeof("version2"),ENET_PACKET_FLAG_RELIABLE);
        				enet_peer_send (peer, 3, answerPacket);
				}
			}
			else
			if(event.packet->dataLength==sizeof(Uint32)) //We have recieved a seed
			{
				memcpy(&theSeed,event.packet->data,sizeof(Uint32));
				bgHome->putStartBlocks(theSeed); 
				cout << "We recieved a seed: " << theSeed << endl;
			}
		}

            	/* Clean up the packet now that we're done using it. */
            	enet_packet_destroy (event.packet);
            
            	break;
           
        	case ENET_EVENT_TYPE_DISCONNECT:
            	printf ("%s disconected.\n", event.peer -> data);

            	/* Reset the peer's client information. */

            	event.peer -> data = NULL;
            	//weAreConnected = false;
            	if((!bgHome->bGameOver)&&(!bgAway->bGameOver))
		{
			bgHome->setPlayerWon();
			bgAway->SetGameOver();
		}

		ntDisconnect(); //When we will disconnect!
		
        	}
    	}
    	
    	
	}
}; //NetworkThing
#endif

//The main function, quite big... too big
int main(int argc, char *argv[])
{
    //We first create the folder there we will save (only on UNIX systems)
    //we call the external command "mkdir"... the user might have renamed this, but we hope he hasn't
  #if defined(__unix__)
  //system("mkdir -p ~/.gamesaves");
  //system("mkdir -p ~/.gamesaves/blockattack");
  system("mkdir -p ~/.gamesaves/blockattack/screenshots");
  system("mkdir -p ~/.gamesaves/blockattack/replays");
  system("mkdir -p ~/.gamesaves/blockattack/puzzles");
  #elif defined(_WIN32)
  //Now for Windows NT/2k/xp/2k3 etc.
  string tempA = getMyDocumentsPath()+"\\My Games";
  CreateDirectory(tempA.c_str(),NULL);//system(tempA.c_str());
  tempA = getMyDocumentsPath()+"\\My Games\\blockattack";
  CreateDirectory(tempA.c_str(),NULL);//system(tempA.c_str());
  tempA = getMyDocumentsPath()+"\\My Games\\blockattack\\replays";
  CreateDirectory(tempA.c_str(),NULL);//system(tempA.c_str()); 
  tempA = getMyDocumentsPath()+"\\My Games\\blockattack\\screenshots";
  CreateDirectory(tempA.c_str(),NULL);//system(tempA.c_str()); 
  #endif
	bool highPriority = false;	//if true the game will take most resources, but increase framerate.
	bFullscreen = false;
  if(argc > 1)
  {
  int argumentNr = 1;
  forceredraw = 2;
  while(argc>argumentNr)
  {
	  char helpString[] = "--help";
	  char priorityString[] = "-priority";
	  char forceRedrawString[] = "-forceredraw";
	  char forcepartdrawString[] = "-forcepartdraw";
	char singlePuzzleString[] = "-SP";
	char noSoundAtAll[] = "-nosound";
	  if(!(strncmp(argv[argumentNr],helpString,6)))
	  {
		  cout << "Block Attack Help" << endl << "--help Display this message" << 
          endl << "-priority  Starts game in high priority" << endl <<
          "-forceredraw  Redraw the whole screen every frame, prevents garbage" << endl <<
          "-forcepartdraw  Only draw what is changed, sometimes cause garbage" << endl <<
	  "-nosound  No sound will be played at all, and sound hardware want be loaded (use this if game crashes because of sound)" << endl;
#ifdef WIN32
		  system("Pause");
#endif
		  return 0;
	  }
	  if(!(strncmp(argv[argumentNr],priorityString,9)))
	  {
		  cout << "Priority mode" << endl;
			highPriority = true;
	  }
	  if(!(strncmp(argv[argumentNr],forceRedrawString,12)))
	  {
            forceredraw = 1;
        }
      if(!(strncmp(argv[argumentNr],forcepartdrawString,14)))
	  {
            forceredraw = 2;
        }
	if(!(strncmp(argv[argumentNr],singlePuzzleString,3)))
	{
	  singlePuzzle = true; //We will just have one puzzle
	  if(argv[argumentNr+1][1]!=0)
		singlePuzzleNr = (argv[argumentNr+1][1]-'0')+(argv[argumentNr+1][0]-'0')*10;
	  else
		singlePuzzleNr = (argv[argumentNr+1][0]-'0');
	  singlePuzzleFile = argv[argumentNr+2];
	  argumentNr+=2;
	cout << "SinglePuzzleMode, File: " << singlePuzzleFile << " and Level: " << singlePuzzleNr << endl;
	}
	if(!(strncmp(argv[argumentNr],noSoundAtAll,8)))
	{
            NoSound = true;
        }
	  argumentNr++;
  }   //while		  
  }   //if

  SoundEnabled = true;
  MusicEnabled = true;
  xsize = 1024;     //screen size x
  int ysize = 768;      //screen size y
  int mousex, mousey;   //Mouse coordinates
  showHighscores = false;
  showEndless = true;
  showOptions = false;
  b1playerOpen = false;
  b2playersOpen = false;
  bReplayOpen = false;
  bScreenLocked = false;
  bool twoPlayers = false;	//true if two players splitscreen
  bool vsMode = false;
  theTopScoresEndless = Highscore(1);
  theTopScoresTimeTrial = Highscore(2);
  drawBalls = true;
  puzzleLoaded = false;
	bool weWhereConnected = false;
  
  //Things used for repeating keystrokes:
    bool repeatingP1N = false; //The key is being held
    bool repeatingP1S = false; //The key is being held
    bool repeatingP1W = false; //The key is being held
    bool repeatingP1E = false; //The key is being held
    bool repeatingP2N = false; //The key is being held
    bool repeatingP2S = false; //The key is being held
    bool repeatingP2W = false; //The key is being held
    bool repeatingP2E = false; //The key is being held
    const int startRepeat = 200;
    const int repeatDelay = 100;    //Repeating
	unsigned long timeHeldP1N = 0;
	unsigned long timeHeldP1S = 0;
	unsigned long timeHeldP1E = 0;
	unsigned long timeHeldP1W = 0;
	unsigned long timeHeldP2N = 0;
	unsigned long timeHeldP2S = 0;
	unsigned long timeHeldP2E = 0;
	unsigned long timeHeldP2W = 0;
    unsigned long timesRepeatedP1N = 0;
	unsigned long timesRepeatedP1S = 0;
	unsigned long timesRepeatedP1E = 0;
	unsigned long timesRepeatedP1W = 0;
    unsigned long timesRepeatedP2N = 0;
	unsigned long timesRepeatedP2S = 0;
	unsigned long timesRepeatedP2E = 0;
	unsigned long timesRepeatedP2W = 0;
  
  theBallManeger = ballManeger();
  theExplosionManeger = explosionManeger();

//We now set the paths were we are saving, we are using the keyword __unix__ . I hope that all UNIX systems has a home folder
  #if defined(__unix__)
  string home = getenv("HOME");
  string optionsPath = home+"/.gamesaves/blockattack/options.dat";
  #elif defined(_WIN32)
  string home = getMyDocumentsPath();
  string optionsPath;
  if(&home!=NULL) //Null if no APPDATA dir exists (win 9x)
    optionsPath = home+"/My Games/blockattack/options.dat";
  else
    optionsPath = "options.dat";
  #else
  string optionsPath = "options.dat";
  #endif
  
  #if defined(__unix__)
  stageClearSavePath = home+"/.gamesaves/blockattack/stageClear.SCsave";
  puzzleSavePath = home+"/.gamesaves/blockattack/puzzle.levels.save";
  #elif defined(_WIN32)
  if(&home!=NULL)
  {
    stageClearSavePath = home+"/My Games/blockattack/stageClear.SCsave";
    puzzleSavePath = home+"/My Games/blockattack/puzzle.levels.save";
  }
  else
  {
    stageClearSavePath = "stageClear.SCsave";
    puzzleSavePath = "puzzle.levels.save";    
  }
  #else
  stageClearSavePath = "stageClear.SCsave";
  puzzleSavePath = "puzzle.levels.save";
  #endif
  puzzleName="puzzle.levels";
  
  Uint8 *keys;
  
  //Init SDL
  if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
  {
    cout << "Unable to init SDL: " << SDL_GetError() << endl;
    exit(1);
  }
  atexit(SDL_Quit);		//quits SDL when the game stops for some reason (like you hit exit or Esc)
  
  Joypad_init();    //Prepare the joysticks
  
  Joypad joypad1 = Joypad();    //Creates a joypad
  Joypad joypad2 = Joypad();    //Creates a joypad
  
  theTextManeger = textManeger();
  
  //Open Audio
  if(!NoSound) //If sound has not been disabled, then load the sound system
  if(Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0)
  {
    cout << "Warning: Couldn't set 44100 Hz 16-bit audio - Reason: " << SDL_GetError() << endl
    << "Sound will be disabled!" << endl;
    NoSound = true; //Tries to stop all sound from playing/loading
  }
  
  SDL_WM_SetCaption("Block Attack - Rise of the Blocks", NULL); //Sets title line
  //Now sets the icon:
  SDL_Surface *icon = IMG_Load2("gfx/icon.png");
  SDL_WM_SetIcon(icon,NULL);
  SDL_FreeSurface(icon);
  
  //Copyright notice:
  cout << "Block Attack - Rise of the Blocks (" << VERSION_NUMBER << ")" << endl << "http://blockattack.sf.net" << endl << "Copyright 2004-2006 Poul Sander" << endl <<
          "A SDL based game (see www.libsdl.org)" << endl;
  #if defined(_WIN32)
    cout << "Windows build" << endl;
    #elif defined(__linux__)
    cout << "Linux build" <<  endl;
    #elif defined(__unix__)
    cout << "Unix build" <<  endl;
    #else
    cout << "Alternative build" << endl;
    #endif        
  cout << "-------------------------------------------" << endl;

  keySettings[0].up= SDLK_UP;
  keySettings[0].down = SDLK_DOWN;
  keySettings[0].left = SDLK_LEFT;
  keySettings[0].right = SDLK_RIGHT;
  keySettings[0].change = SDLK_KP_ENTER;
  keySettings[0].push = SDLK_KP0;

  keySettings[2].up= SDLK_w;
  keySettings[2].down = SDLK_s;
  keySettings[2].left = SDLK_a;
  keySettings[2].right = SDLK_d;
  keySettings[2].change = SDLK_LCTRL;
  keySettings[2].push = SDLK_LSHIFT;

  player1keys=0;
  player2keys=2;

  strcpy(player1name, "Player 1                    \0");
  strcpy(player2name, "Player 2                    \0");

#ifdef NETWORK
  strcpy(serverAddress, "192.168.0.2                 \0");
#endif
  
  //Reads options from file:
  ifstream optionsFile(optionsPath.c_str(), ios::binary);
  if(optionsFile)
  {
	  //reads data: xsize,ysize,fullescreen, player1keys, player2keys, MusicEnabled, SoundEnabled,player1name,player2name
	  optionsFile.read(reinterpret_cast<char*>(&xsize), sizeof(int));
	  optionsFile.read(reinterpret_cast<char*>(&ysize), sizeof(int));
	  optionsFile.read(reinterpret_cast<char*>(&bFullscreen), sizeof(bool));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[0].up), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[0].down), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[0].left), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[0].right), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[0].change), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[0].push), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[2].up), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[2].down), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[2].left), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[2].right), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[2].change), sizeof(SDLKey));
	  optionsFile.read(reinterpret_cast<char*>(&keySettings[2].push), sizeof(SDLKey));	  
	  optionsFile.read(reinterpret_cast<char*>(&MusicEnabled), sizeof(bool));
	  optionsFile.read(reinterpret_cast<char*>(&SoundEnabled), sizeof(bool));
	  optionsFile.read(player1name, 30*sizeof(char));
	  optionsFile.read(player2name, 30*sizeof(char));
	  //mouseplay?
	  if(!optionsFile.eof())
	  {
         optionsFile.read(reinterpret_cast<char*>(&mouseplay1), sizeof(bool));
         optionsFile.read(reinterpret_cast<char*>(&mouseplay2), sizeof(bool));
         optionsFile.read(reinterpret_cast<char*>(&joyplay1),sizeof(bool));
         optionsFile.read(reinterpret_cast<char*>(&joyplay2),sizeof(bool));
      }
	  optionsFile.close();
	  cout << "Data loaded from options file" << endl;
  }
  else
  {
	  cout << "Unable to load options file, using default values" << endl;
  }

xsize = 1024;
ysize = 768;
if(singlePuzzle)
{
	xsize=300;
	ysize=600;
}
  //Open video
  if((bFullscreen)&&(!singlePuzzle)) screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_FULLSCREEN|SDL_ANYFORMAT);
  else screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_ANYFORMAT);
  
  if ( screen == NULL )
  {
    cout << "Unable to set " << xsize << "x" << ysize << " video: " << SDL_GetError() << endl;
    exit(1);
  }

  //Loading all images into memory
  InitImages();

  cout << "Images loaded" << endl;


  BlockGame theGame = BlockGame(50,100);			//creates game objects
  BlockGame theGame2 = BlockGame(xsize-500,100);
if(singlePuzzle)
{
  theGame.topy=0;
  theGame.topx=0;
  theGame2.topy=10000;
  theGame2.topx=10000;
}
  theGame.DoPaintJob();			//Makes sure what there is something to paint
  theGame2.DoPaintJob();
  theGame.SetGameOver();		//sets the game over in the beginning
  theGame2.SetGameOver(); 


    //Takes names from file instead
  strcpy(theGame.name, player1name);
  strcpy(theGame2.name, player2name);

  //Keeps track of background;
  int nowTime=SDL_GetTicks();
 

#ifdef NETWORK
	NetworkThing nt = NetworkThing();
	nt.setBGpointers(&theGame,&theGame2);
#endif

if(singlePuzzle)
{
  LoadPuzzleStages();
  theGame.NewPuzzleGame(singlePuzzleNr,0,0); 
  showGame = true; 
  vsMode = true;
} 
  //Draws everything to screen
  MakeBackground(xsize,ysize,theGame,theGame2);
  DrawIMG(background, screen, 0, 0);
  DrawEverything(xsize,ysize,theGame,theGame2);
  SDL_Flip(screen);
  
  //game loop
  int done = 0;
  cout << "Starting game loop" << endl;
  while(done == 0)
  {
    if(!(highPriority)) SDL_Delay(10);
    
    if(standardBackground)
    {
        MakeBackground(xsize,ysize,theGame,theGame2);
        DrawIMG(background, screen, 0, 0);
    }
          
    //updates the balls and explosions:
    theBallManeger.update();
    theExplosionManeger.update();
    theTextManeger.update();
     
#ifdef NETWORK
	if(nt.isConnected())
	{
    		nt.updateNetwork();
		networkActive = true;
		if(!nt.isConnectedToPeer())
			DrawIMG(background, screen, 0, 0);
	}
	else
		networkActive = false;
	if(nt.isConnectedToPeer())
	{
		networkPlay=true;
		if(!weWhereConnected) //We have just connected
		{
			theGame.NewVsGame(50,100,&theGame2); 
			theGame.putStartBlocks(nt.theSeed);
			theGame2.playNetwork(xsize-500,100); 
			nt.theGameHasStarted();
			DrawIMG(background, screen, 0, 0);
		}
		weWhereConnected = true;
	}
	else
	{
		networkPlay=false;
		weWhereConnected = false;
	}
#endif
        
	if(!bScreenLocked)
	{
    SDL_Event event;
    
    while ( SDL_PollEvent(&event) )
    {
      if ( event.type == SDL_QUIT )  {  done = 1;  }

      if ( event.type == SDL_KEYDOWN )
      {
	  if ( event.key.keysym.sym == SDLK_ESCAPE ) 
          { 
                if(showHighscores)
                {
                    showHighscores = false;
                }
                else 
                    if(showOptions)
                    {
                        showOptions = false;
                    } 
                    else 
                        done=1; 
            DrawIMG(background, screen, 0, 0);
            
        }
        //player1:
		if ( event.key.keysym.sym == keySettings[player1keys].up ) { theGame.MoveCursor('N'); repeatingP1N=true; timeHeldP1N=SDL_GetTicks(); timesRepeatedP1N=0;}
        if ( event.key.keysym.sym == keySettings[player1keys].down ) { theGame.MoveCursor('S'); repeatingP1S=true; timeHeldP1S=SDL_GetTicks(); timesRepeatedP1S=0;}
        if ( (event.key.keysym.sym == keySettings[player1keys].left) && (showGame) ) { theGame.MoveCursor('W'); repeatingP1W=true; timeHeldP1W=SDL_GetTicks(); timesRepeatedP1W=0;}
        if ( (event.key.keysym.sym == keySettings[player1keys].right) && (showGame) ) { theGame.MoveCursor('E'); repeatingP1E=true; timeHeldP1E=SDL_GetTicks(); timesRepeatedP1E=0;}
		if ( event.key.keysym.sym == keySettings[player1keys].push ) { theGame.PushLine(); }
        if ( event.key.keysym.sym == keySettings[player1keys].change ) { theGame.SwitchAtCursor();}
		//player2:
		if ( event.key.keysym.sym == keySettings[player2keys].up ) { theGame2.MoveCursor('N'); repeatingP2N=true; timeHeldP2N=SDL_GetTicks(); timesRepeatedP2N=0;}
        if ( event.key.keysym.sym == keySettings[player2keys].down ) { theGame2.MoveCursor('S'); repeatingP2S=true; timeHeldP2S=SDL_GetTicks(); timesRepeatedP2S=0;}
        if ( (event.key.keysym.sym == keySettings[player2keys].left) && (showGame) ) { theGame2.MoveCursor('W'); repeatingP2W=true; timeHeldP2W=SDL_GetTicks(); timesRepeatedP2W=0;}
        if ( (event.key.keysym.sym == keySettings[player2keys].right) && (showGame) ) { theGame2.MoveCursor('E'); repeatingP2E=true; timeHeldP2E=SDL_GetTicks(); timesRepeatedP2E=0;}
		if ( event.key.keysym.sym == keySettings[player2keys].push ) { theGame2.PushLine(); }
        if ( event.key.keysym.sym == keySettings[player2keys].change ) { theGame2.SwitchAtCursor();}
        //common:
if(!singlePuzzle)
{
		if ( ((event.key.keysym.sym == SDLK_LEFT)||(event.key.keysym.sym == SDLK_RIGHT)) && (showHighscores) ) {showEndless = !showEndless;}
        
        if ( event.key.keysym.sym == SDLK_F2 ) {if((!showHighscores)&&(!showOptions)&&(!networkActive)){theGame.NewGame(50,100); theGame.timetrial = false; theGame.putStartBlocks(); closeAllMenus(); twoPlayers =false; theGame2.SetGameOver(); showGame = true; vsMode = false;}}
        if ( event.key.keysym.sym == SDLK_F3 ) {if((!showHighscores)&&(!showOptions)&&(!networkActive)){theGame.NewGame(50,100); theGame.timetrial = true; theGame.putStartBlocks(); closeAllMenus(); twoPlayers =false; theGame2.SetGameOver(); showGame = true; vsMode = false;}}
		if ( event.key.keysym.sym == SDLK_F5 ) 
        {
            if((!showHighscores)&&(!showOptions)&&(!networkActive))
            { 
                int myLevel = StageLevelSelect(); 
                theGame.NewStageGame(myLevel,50,100); 
                MakeBackground(xsize,ysize,theGame,theGame2); 
                DrawIMG(background, screen, 0, 0); 	
                closeAllMenus();
                twoPlayers =false; 
                theGame2.SetGameOver(); 
                showGame = true; 
                vsMode = false;
            }
        }
		if ( event.key.keysym.sym == SDLK_F6 ) 
		{
			if((!showHighscores)&&(!showOptions)&&(!networkActive))
			{
				theGame.NewVsGame(50,100,&theGame2); 
				theGame2.NewVsGame(xsize-500,100,&theGame); 
                closeAllMenus();
				vsMode = true;
				theGame.setGameSpeed(player1Speed);
				theGame2.setGameSpeed(player2Speed);
				theGame.setHandicap(player1handicap);
				theGame2.setHandicap(player2handicap);
				theGame.AI_Enabled = player1AI;
				theGame2.AI_Enabled = player2AI;
				theGame.setAIlevel(player1AIlevel);
				theGame2.setAIlevel(player2AIlevel);
				int theTime = time(0);
				theGame.putStartBlocks(theTime);
				theGame2.putStartBlocks(theTime);
				twoPlayers = true;
			}
		}
		if ( event.key.keysym.sym == SDLK_F4 ) 
		{
			if((!showHighscores)&&(!showOptions)&&(!networkActive))
			{
				theGame.NewGame(50,100); 
				theGame2.NewGame(xsize-500,100); 
				theGame.timetrial = true;
				theGame2.timetrial = true;
				int theTime = time(0);
				theGame.putStartBlocks(theTime);
				theGame2.putStartBlocks(theTime);
				closeAllMenus();
				twoPlayers = true;
				theGame.setGameSpeed(player1Speed);
				theGame2.setGameSpeed(player2Speed);
				theGame.setHandicap(player1handicap);
				theGame2.setHandicap(player2handicap);
				theGame.AI_Enabled = player1AI;
				theGame2.AI_Enabled = player2AI;
				theGame.setAIlevel(player1AIlevel);
				theGame2.setAIlevel(player2AIlevel);
			} 
		}
		if ( event.key.keysym.sym == SDLK_F7 ) 
        {
            if((!showHighscores)&&(!showOptions)&&(!networkActive))
            {
                int myLevel = PuzzleLevelSelect(); 
                theGame.NewPuzzleGame(myLevel,50,100); 
                MakeBackground(xsize,ysize,theGame,theGame2); 
                DrawIMG(background, screen, 0, 0); 	
                closeAllMenus(); 
                twoPlayers = false; 
                theGame2.SetGameOver(); 
                showGame = true; 
                vsMode = true;
            }
        }
        if ( event.key.keysym.sym == SDLK_F8 ) 
        {
            if((!showGame)&&(!showOptions)&&(!networkActive)) 
            if(!showHighscores)
            {
                closeAllMenus();
                showHighscores = true; 
                MakeBackground(xsize,ysize,theGame,theGame2); 
                DrawIMG(background, screen, 0, 0); 	
                closeAllMenus(); 
                theGame2.SetGameOver();
            } 
            else 
            {
                showEndless = !showEndless;
            }
        }
        if ( event.key.keysym.sym == SDLK_F9 ) {writeScreenShot();}
        if ( event.key.keysym.sym == SDLK_F11 ) {
                /*This is the test place, place function to test here*/
            
            	theGame.CreateGreyGarbage();
                
           } //F11
} 
       if ( event.key.keysym.sym == SDLK_F12 ) {done=1;}
      }
    } //while event PollEvent - read keys

/**********************************************************************
**************************** Repeating start **************************
repeatingP2E=true; timeHeldP2E=SDL_GetTicks(); timesRepeatedP2E=0;
keySettings[player2keys].right
keys = SDL_GetKeyState(NULL);
(this is just info so we don't need to look too long back)
**********************************************************************/

keys = SDL_GetKeyState(NULL);
//Also the joysticks:
//Repeating not implemented

//Player 1 start
       if(!(keys[keySettings[player1keys].up]))
       repeatingP1N=false;
       while((repeatingP1N)&&(keys[keySettings[player1keys].up])&&(SDL_GetTicks()>timeHeldP1N+timesRepeatedP1N*repeatDelay+startRepeat))
	   {
	       theGame.MoveCursor('N');
	       timesRepeatedP1N++;
       }

       if(!(keys[keySettings[player1keys].down]))
       repeatingP1S=false;
       while((repeatingP1S)&&(keys[keySettings[player1keys].down])&&(SDL_GetTicks()>timeHeldP1S+timesRepeatedP1S*repeatDelay+startRepeat))
	   {
	       theGame.MoveCursor('S');
	       timesRepeatedP1S++;
       }

       if(!(keys[keySettings[player1keys].left]))
       repeatingP1W=false;
       while((repeatingP1W)&&(keys[keySettings[player1keys].left])&&(SDL_GetTicks()>timeHeldP1W+timesRepeatedP1W*repeatDelay+startRepeat))
	   {
           timesRepeatedP1W++;
	       theGame.MoveCursor('W');
       }

       if(!(keys[keySettings[player1keys].right]))
       repeatingP1E=false;
       while((repeatingP1E)&&(keys[keySettings[player1keys].right])&&(SDL_GetTicks()>timeHeldP1E+timesRepeatedP1E*repeatDelay+startRepeat))
	   {
           timesRepeatedP1E++;
	       theGame.MoveCursor('E');
       }
       
//Player 1 end

//Player 2 start
       if(!(keys[keySettings[player2keys].up]))
       repeatingP2N=false;
       while((repeatingP2N)&&(keys[keySettings[player2keys].up])&&(SDL_GetTicks()>timeHeldP2N+timesRepeatedP2N*repeatDelay+startRepeat))
	   {
	       theGame2.MoveCursor('N');
	       timesRepeatedP2N++;
       }

       if(!(keys[keySettings[player2keys].down]))
       repeatingP2S=false;
       while((repeatingP2S)&&(keys[keySettings[player2keys].down])&&(SDL_GetTicks()>timeHeldP2S+timesRepeatedP2S*repeatDelay+startRepeat))
	   {
	       theGame2.MoveCursor('S');
	       timesRepeatedP2S++;
       }

       if(!(keys[keySettings[player2keys].left]))
       repeatingP2W=false;
       while((repeatingP2W)&&(keys[keySettings[player2keys].left])&&(SDL_GetTicks()>timeHeldP2W+timesRepeatedP2W*repeatDelay+startRepeat))
	   {
	       theGame2.MoveCursor('W');
	       timesRepeatedP2W++;
       }

       if(!(keys[keySettings[player2keys].right]))
       repeatingP2E=false;
       while((repeatingP2E)&&(keys[keySettings[player2keys].right])&&(SDL_GetTicks()>timeHeldP2E+timesRepeatedP2E*repeatDelay+startRepeat))
	   {
	       theGame2.MoveCursor('E');
	       timesRepeatedP2E++;
       }
       
//Player 2 end

/**********************************************************************
**************************** Repeating end ****************************
**********************************************************************/

/**********************************************************************
***************************** Joypad start ****************************
**********************************************************************/

    if(joyplay1||joyplay2)
    {
    if(joypad1.working)
        if(joyplay1)
        {
            joypad1.update();
            if(joypad1.up)
                {theGame.MoveCursor('N'); repeatingP1N=true; timeHeldP1N=SDL_GetTicks(); timesRepeatedP1N=0;}
            if(joypad1.down)
                {theGame.MoveCursor('S'); repeatingP1S=true; timeHeldP1S=SDL_GetTicks(); timesRepeatedP1S=0;}
            if(joypad1.left)
                {theGame.MoveCursor('W'); repeatingP1W=true; timeHeldP1W=SDL_GetTicks(); timesRepeatedP1W=0;}
            if(joypad1.right)
                {theGame.MoveCursor('E'); repeatingP1E=true; timeHeldP1E=SDL_GetTicks(); timesRepeatedP1E=0;}
            if(joypad1.but1)
                theGame.SwitchAtCursor();
            if(joypad1.but2)
                theGame.PushLine();
        }
        else
        {
            joypad1.update();
            if(joypad1.up)
                {theGame2.MoveCursor('N'); repeatingP2N=true; timeHeldP2N=SDL_GetTicks(); timesRepeatedP2N=0;}
            if(joypad1.down)
                {theGame2.MoveCursor('S'); repeatingP2S=true; timeHeldP2S=SDL_GetTicks(); timesRepeatedP2S=0;}
            if(joypad1.left)
                {theGame2.MoveCursor('W'); repeatingP2W=true; timeHeldP2W=SDL_GetTicks(); timesRepeatedP2W=0;}
            if(joypad1.right)
                {theGame2.MoveCursor('E'); repeatingP2E=true; timeHeldP2E=SDL_GetTicks(); timesRepeatedP2E=0;}
            if(joypad1.but1)
                theGame2.SwitchAtCursor();
            if(joypad1.but2)
                theGame2.PushLine();
        }
    if(joypad2.working)
        if(!joyplay2)
        {
            joypad2.update();
            if(joypad2.up)
                {theGame.MoveCursor('N'); repeatingP1N=true; timeHeldP1N=SDL_GetTicks(); timesRepeatedP1N=0;}
            if(joypad2.down)
                {theGame.MoveCursor('S'); repeatingP1S=true; timeHeldP1S=SDL_GetTicks(); timesRepeatedP1S=0;}
            if(joypad2.left)
                {theGame.MoveCursor('W'); repeatingP1W=true; timeHeldP1W=SDL_GetTicks(); timesRepeatedP1W=0;}
            if(joypad2.right)
                {theGame.MoveCursor('E'); repeatingP1E=true; timeHeldP1E=SDL_GetTicks(); timesRepeatedP1E=0;}
            if(joypad2.but1)
                theGame.SwitchAtCursor();
            if(joypad2.but2)
                theGame.PushLine();
        }
        else
        {
            joypad2.update();
            if(joypad2.up)
                {theGame2.MoveCursor('N'); repeatingP2N=true; timeHeldP2N=SDL_GetTicks(); timesRepeatedP2N=0;}
            if(joypad2.down)
                {theGame2.MoveCursor('S'); repeatingP2S=true; timeHeldP2S=SDL_GetTicks(); timesRepeatedP2S=0;}
            if(joypad2.left)
                {theGame2.MoveCursor('W'); repeatingP2W=true; timeHeldP2W=SDL_GetTicks(); timesRepeatedP2W=0;}
            if(joypad2.right)
                {theGame2.MoveCursor('E'); repeatingP2E=true; timeHeldP2E=SDL_GetTicks(); timesRepeatedP2E=0;}
            if(joypad2.but1)
                theGame2.SwitchAtCursor();
            if(joypad2.but2)
                theGame2.PushLine();
        }
    }

/**********************************************************************
***************************** Joypad end ******************************
**********************************************************************/


    keys = SDL_GetKeyState(NULL);
  
  SDL_GetMouseState(&mousex,&mousey);    

  /********************************************************************
  **************** Here comes mouse play ******************************
  ********************************************************************/
  
    if(mouseplay1) //player 1
    if((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600))
    {
        int yLine, xLine;
        yLine = ((100+600)-(mousey-100+theGame.pixels))/50;
        xLine = (mousex-50+25)/50;
        yLine-=2;
        xLine-=1;
        if((yLine>10)&&(theGame.TowerHeight<12))
            yLine=10;
        if(((theGame.pixels==50)||(theGame.pixels==0)) && (yLine>11))
            yLine=11;
        if(yLine<0)
            yLine=0;
        if(xLine<0)
            xLine=0;
        if(xLine>4)
            xLine=4;
        theGame.cursorx=xLine;
        theGame.cursory=yLine;
    }
    
    if(mouseplay2) //player 2
    if((mousex > xsize-500)&&(mousey>100)&&(mousex<xsize-500+300)&&(mousey<100+600))
    {
        int yLine, xLine;
        yLine = ((100+600)-(mousey-100+theGame2.pixels))/50;
        xLine = (mousex-(xsize-500)+25)/50;
        yLine-=2;
        xLine-=1;
        if((yLine>10)&&(theGame2.TowerHeight<12))
            yLine=10;
        if(((theGame2.pixels==50)||(theGame2.pixels==0)) && (yLine>11))
            yLine=11;
        if(yLine<0)
            yLine=0;
        if(xLine<0)
            xLine=0;
        if(xLine>4)
            xLine=4;
        theGame2.cursorx=xLine;
        theGame2.cursory=yLine;
    }
  
  /********************************************************************
  **************** Here ends mouse play *******************************
  ********************************************************************/

  // If the mouse button is released, make bMouseUp equal true
  if(!SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1))
  {
    bMouseUp=true;
  }
  
  // If the mouse button 2 is released, make bMouseUp2 equal true
  if((SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(3))!=SDL_BUTTON(3))
  {
    bMouseUp2=true;
  }

if(!singlePuzzle)
{
  //read mouse events
  if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1) && bMouseUp)
  {
    bMouseUp = false;
    DrawIMG(background, screen, 0, 0);
    if((0<mousex) && (mousex<120) && (0<mousey) && (mousey<40) &&(!networkActive) )
    {
        //New game clicked
        bool state = (!bNewGameOpen);
        closeAllMenus();
        bNewGameOpen = state; //theGame.NewGame(50,100);
        showOptions = false;
        showHighscores = false;
    }
    else
#ifdef NETWORK
    if((0<mousex) && (mousex<120) && (0<mousey) && (mousey<40) &&(networkActive))
    {
	//Disconnect clicked!
	cout << "Disconnect clicked!" << endl;
	nt.ntDisconnect();
    }
    else
#endif
	if((0<mousex) && (mousex<120) && (40<mousey) && (mousey<80) && (bNewGameOpen) &&(!networkActive))
    {
		//1player
        b1playerOpen = (!b1playerOpen);
		b2playersOpen = false;
#ifdef NETWORK
		bNetworkOpen = false;
#endif
    }
	else
	if((0<mousex) && (mousex<120) && (80<mousey) && (mousey<120) && (bNewGameOpen) &&(!networkActive))
    {
		//2player
        b2playersOpen = (!b2playersOpen);
		b1playerOpen = false;
#ifdef NETWORK
		bNetworkOpen = false;
#endif
    }
#ifdef NETWORK
	else
    if((0<mousex) && (mousex<120) && (120<mousey) && (mousey<160) && (bNewGameOpen) &&(!networkActive))
    {
        //Network
        b1playerOpen = false;
		b2playersOpen = false;
		bNetworkOpen = (!bNetworkOpen);
    }
#endif
    else
    if((120<mousex) && (mousex<240) && (40<mousey) && (mousey<80) && (b1playerOpen) &&(!networkActive))
    {
        //1 player - endless
        theGame.NewGame(50,100);
        theGame.putStartBlocks();
        bNewGameOpen = false;
		b1playerOpen = false;
        twoPlayers =false; theGame2.SetGameOver(); showGame = true;
    }
    else
    if((120<mousex) && (mousex<240) && (80<mousey) && (mousey<120) && (b1playerOpen) &&(!networkActive) )
    {
        //1 player - time trial
        theGame.NewGame(50,100); theGame.timetrial=true;
        theGame.putStartBlocks();
        bNewGameOpen = false;
		b1playerOpen = false;
		twoPlayers =false; theGame2.SetGameOver(); showGame = true;
    }
	else
    if((120<mousex) && (mousex<240) && (120<mousey) && (mousey<160) && (b1playerOpen)&&(!networkActive) )
    {
        //1 player - stage clear
        bNewGameOpen = false;
		b1playerOpen = false;
		int myLevel = StageLevelSelect(); 
		theGame.NewStageGame(myLevel,50,100); 
		MakeBackground(xsize,ysize,theGame,theGame2); 
        DrawIMG(background, screen, 0, 0); 	
		twoPlayers =false; theGame2.SetGameOver(); showGame = true;
		vsMode = false;
    }
    	else
    if((120<mousex) && (mousex<240) && (160<mousey) && (mousey<200) && (b1playerOpen))
    {
        //1 player - puzzle
        bNewGameOpen = false;
		b1playerOpen = false;
		int myLevel = PuzzleLevelSelect(); 
		theGame.NewPuzzleGame(myLevel,50,100); 
		MakeBackground(xsize,ysize,theGame,theGame2);
		DrawIMG(background, screen, 0, 0);
		twoPlayers =false; theGame2.SetGameOver(); showGame = true;
		vsMode = false;
    }
	else
	if((120<mousex) && (mousex<240) && (200<mousey) && (mousey<240) && (b1playerOpen))
    {
        //1 player - Vs mode
        bNewGameOpen = false;
		b1playerOpen = false;
		int theAIlevel = startSingleVs(); 
		theGame.NewVsGame(50,100,&theGame2); 
		theGame2.NewVsGame(xsize-500,100,&theGame); 
		MakeBackground(xsize,ysize,theGame,theGame2);
		DrawIMG(background, screen, 0, 0);
		twoPlayers = true; //Single player, but AI plays 
		showGame = true;
		vsMode = true;
		theGame2.AI_Enabled=true; //Of course we need an AI
		theGame2.setAIlevel((Uint8)theAIlevel);
		int theTime = time(0);
		theGame.putStartBlocks(theTime);
		theGame2.putStartBlocks(theTime);
    }
	else
    if((120<mousex) && (mousex<240) && (80<mousey) && (mousey<120) && (b2playersOpen))
    {
        //2 player - time trial
        theGame.NewGame(50,100); theGame.timetrial=true;
        bNewGameOpen = false;
		b2playersOpen = false;
		theGame.NewGame(50,100); 
		theGame2.NewGame(xsize-500,100); 
		theGame.timetrial = true;
		theGame2.timetrial = true;
		int theTime = time(0);
				theGame.putStartBlocks(theTime);
				theGame2.putStartBlocks(theTime);
		theGame.setGameSpeed(player1Speed);
		theGame2.setGameSpeed(player2Speed);
		theGame.setHandicap(player1handicap);
		theGame2.setHandicap(player2handicap);
		theGame.AI_Enabled = player1AI;
		theGame2.AI_Enabled = player2AI;
		theGame.setAIlevel(player1AIlevel);
		theGame2.setAIlevel(player2AIlevel);
		twoPlayers = true;
    }
    else
	if((120<mousex) && (mousex<240) && (120<mousey) && (mousey<160) && (b2playersOpen))
    {
        //2 player - VsMode
		theGame.NewVsGame(50,100,&theGame2); 
		theGame2.NewVsGame(xsize-500,100,&theGame); 
		bNewGameOpen = false;
		vsMode = true;
		twoPlayers = true;
		b2playersOpen = false;
		theGame.setGameSpeed(player1Speed);
		theGame2.setGameSpeed(player2Speed);
		theGame.setHandicap(player1handicap);
		theGame2.setHandicap(player2handicap);
		theGame.AI_Enabled = player1AI;
		theGame2.AI_Enabled = player2AI;
		theGame.setAIlevel(player1AIlevel);
		theGame2.setAIlevel(player2AIlevel);
		int theTime = time(0);
		theGame.putStartBlocks(theTime);
		theGame2.putStartBlocks(theTime);
    }
#ifdef NETWORK
	else
	if((120<mousex) && (mousex<240) && (120<mousey) && (mousey<160) && (bNetworkOpen))
	{
		//Host
		cout << "Host" << endl;
		closeAllMenus();
		theGame.SetGameOver();
		theGame2.SetGameOver();
		nt.startServer();
	}
	else
	if((120<mousex) && (mousex<240) && (160<mousey) && (mousey<200) && (bNetworkOpen))
	{
		//Connect
		cout << "Connect" << endl;
		closeAllMenus();
		theGame.SetGameOver();
		theGame2.SetGameOver();
		if(OpenDialogbox(200,100,serverAddress))
		{
			char buf[30];
			memcpy(buf,serverAddress,30);
			nt.connectToServer(strtok(buf," "));
		}
		while ( SDL_PollEvent(&event) ); //If the user have pressed ESC or the like
	}
#endif
	else
    if((120<mousex) && (mousex<2*120) && (0<mousey) && (mousey<40) &&(!networkActive))
    {
		//options button clicked
		if(bOptionsOpen)
		{
            closeAllMenus();
        }
        else
        {
            closeAllMenus();
		    bOptionsOpen = true;
            DrawIMG(background, screen, 0, 0);
        }
    }
    else
    if((120<mousex) && (mousex<2*120) && (40<mousey) && (mousey<80) && (bOptionsOpen) )
    {
		//Configure button clicked
		closeAllMenus();
        if(!showOptions) { showOptions = true; showHighscores = false; }
		else showOptions = false;
        DrawIMG(background, screen, 0, 0);
    }
    else
    if((120<mousex) && (mousex<2*120) && (80<mousey) && (mousey<120) && (bOptionsOpen) )
    {
		//Configure button clicked
		closeAllMenus();
        changePuzzleLevels();
    }
    else
    if((120<mousex) && (mousex<2*120) && (120<mousey) && (mousey<160) && (bOptionsOpen) )
    {
		//vsMode button clicked
		closeAllMenus();
        startVsMenu();
    }
    else
    if((120*2<mousex) && (mousex<3*120) && (0<mousey) && (mousey<40) &&(!networkActive))
    {
		//highscore button clicked
        bool state = showHighscores;
        closeAllMenus();
        if(!state) {showHighscores = true; showOptions = false;}
        DrawIMG(background, screen, 0, 0);
    }
    else
    if((360<mousex) && (mousex<4*120) && (0<mousey) && (mousey<40) &&(!networkActive))
    {
        //Replay clicked!
        bool state = (!bReplayOpen);
        closeAllMenus();
        bReplayOpen = state; //theGame.NewGame(50,100);
        showOptions = false;
        showHighscores = false;
    }
	else
	if((360<mousex) && (mousex<4*120) && (40<mousey) && (mousey<80) &&(bReplayOpen))
    {
        //Replay->Save clicked!
        //cout << "Replay->Save clicked" << endl;
        char buf[30];
        for(int i=0;i<29;i++)buf[i]=' ';
        buf[30]=0;
        OpenDialogbox(200,100,buf);
        for(int i=28;buf[i]==' ';i--)
            		buf[i]=0;
        #ifdef __unix__
        	string saveHere = (string)getenv("HOME")+(string)"/.gamesaves/blockattack/replays/"+(string)buf;
        #elif WIN32
        	string saveHere = home+(string)"/My Games/blockattack/replays/"+(string)buf;
        #else
        	string saveHere = (string)"./replays"+(string)buf;
        #endif
        ofstream replayFileOut;
  		replayFileOut.open(saveHere.c_str(),ios::binary|ios::trunc);
  		if(replayFileOut)
  		{
				//writes data: xsize,ysize,fullescreen, player1keys, player2keys, MusicEnabled, SoundEnabled,player1name,player2name
    		//	optionsFileOut.write(reinterpret_cast<char*>(&xsize),sizeof(int));
		Uint8 version = 1;
		replayFileOut.write(reinterpret_cast<char*>(&version),sizeof(Uint8));
        	if(lastNrOfPlayers>0)
        		replayFileOut.write(reinterpret_cast<char*>(&theGame.theReplay),sizeof(Replay));
        	if(lastNrOfPlayers>1)
        		replayFileOut.write(reinterpret_cast<char*>(&theGame2.theReplay),sizeof(Replay));
        	replayFileOut.close();
        }
        closeAllMenus();
    }
	else
    if((360<mousex) && (mousex<4*120) && (80<mousey) && (mousey<120)&&(bReplayOpen))
    {
        //Replay->Load clicked!
        //cout << "Replay->Load clicked" << endl;
        
        char buf[30];
        for(int i=0;i<29;i++)buf[i]=' ';
        buf[30]=0;
            if(OpenReplayDialogbox(50,100,buf))
            {
            	//cout << "Good way" << endl;
            	for(int i=28;buf[i]==' ';i--)
            		buf[i]=0;
            	#ifdef __unix__
                	string loadThis = (string)getenv("HOME")+(string)"/.gamesaves/blockattack/replays/"+(string)buf;
             	#elif WIN32
             		string loadThis = home+(string)"/My Games/blockattack/replays/"+(string)buf;
             	#else
             		string loadThis = (string)"./replays/"+(string)buf;
             	#endif
             	ifstream replayFileIn;
        		replayFileIn.open(loadThis.c_str(),ios::binary);
        		bool play2 = false;
        		if(replayFileIn)
        		{
        			Uint8 version = 0;
				replayFileIn.read(reinterpret_cast<char*>(&version),sizeof(Uint8));
				if(version==1)
				{
					replayFileIn.read(reinterpret_cast<char*>(&theGame.theReplay), sizeof(Replay));
        				if(!replayFileIn.eof())
        				{
        					cout << "2 players" << endl;
        					if(replayFileIn.read(reinterpret_cast<char*>(&theGame2.theReplay), sizeof(Replay)))
        						play2 = true; //If we can actually read a player 2
        				}
				}
        			replayFileIn.close();
        			theGame.playReplay(50,100);
        			if(play2)
        			theGame2.playReplay(xsize-500,100);
        			else
        			theGame2.SetGameOver();
        		}
        	}
        closeAllMenus();
    }
	else
    if((xsize-120<mousex) && (xsize-20>mousex) && (ysize-120<mousey) && (ysize-20>mousey))
    {
        //Exit clicked
        done=1;
    }
	else
	if((showOptions) && (mousex>500) && (mousex<560) && (mousey>220) && (mousey<260))
	{
		MusicEnabled = !MusicEnabled;
		if(!MusicEnabled) Mix_FadeOutMusic(500);
	}
	if((showOptions) && (mousex>500) && (mousex<560) && (mousey>270) && (mousey<310))
	{
		SoundEnabled = !SoundEnabled;
	}
	if((showOptions) && (mousex>500) && (mousex<560) && (mousey>320) && (mousey<360))
	{
		//Fullscreen
		bFullscreen = !bFullscreen;
		#if defined(WIN32)
		if(bFullscreen) screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_FULLSCREEN|SDL_ANYFORMAT);
                        else screen=SDL_SetVideoMode(xsize,ysize,32,SDL_SWSURFACE|SDL_ANYFORMAT);
        DrawIMG(background, screen, 0, 0);
		#else
		SDL_WM_ToggleFullScreen(screen); //Will only work in Linux
		#endif
        SDL_ShowCursor(SDL_DISABLE);
	}
	
	if((showOptions) && (mousex>330) && (mousex<470) && (mousey>535) && (mousey<585))
	{
		//change name
		bScreenLocked = true;
		showDialog = true;
		if(OpenDialogbox(200,100,player1name))
		strcpy(theGame.name, player1name);
		else
		strcpy(player1name,theGame.name);
		bScreenLocked = false;
		showDialog = false;
		MakeBackground(xsize,ysize,theGame,theGame2);
		DrawIMG(background, screen, 0, 0);
	}
	if((showOptions) && (mousex>330) && (mousex<470) && (mousey>600) && (mousey<640))
	{
		//change name
		bScreenLocked = true;
		showDialog = true;
		if(OpenDialogbox(200,100,player2name))
		strcpy(theGame2.name, player2name);
		else
		strcpy(player2name,theGame2.name);
		bScreenLocked = false;
		showDialog = false;
		MakeBackground(xsize,ysize,theGame,theGame2);
		DrawIMG(background, screen, 0, 0);
	}
	if((showOptions) && (mousex>510) && (mousex<630) && (mousey>535) && (mousey<585))
	{
		//changeControls
		OpenControlsBox(200,100,0);
		MakeBackground(xsize,ysize,theGame,theGame2);
		DrawIMG(background, screen, 0, 0);
	}
	if((showOptions) && (mousex>510) && (mousex<630) && (mousey>600) && (mousey<640))
	{
		//changeControls
		OpenControlsBox(200,100,2);
		MakeBackground(xsize,ysize,theGame,theGame2);
		DrawIMG(background, screen, 0, 0);
	}
	if((showHighscores)&&(((mousex>150)&&(mousex<173))||((mousex>628)&&(mousex<650)))&&(mousey<652)&&(mousey>630))
	{
        //small arrors on Highscore board clicked!
        showEndless = !showEndless;
        DrawIMG(background, screen, 0, 0);
    }

  /********************************************************************
  **************** Here comes mouse play ******************************
  ********************************************************************/
  if((!showOptions)&&(!showHighscores))
  {
    if(mouseplay1) //player 1
    if((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600))
    {
        theGame.SwitchAtCursor();
    }
    if(mouseplay2) //player 2
    if((mousex > xsize-500)&&(mousey>100)&&(mousex<xsize-500+300)&&(mousey<100+600))
    {
        theGame2.SwitchAtCursor();
    }
  } 
    /********************************************************************
    **************** Here ends mouse play *******************************
    ********************************************************************/
    
    //cout << "Mouse x: " << mousex << ", mouse y: " << mousey << endl;
  }
  
  //Mouse button 2:
    if((SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(3))==SDL_BUTTON(3) && bMouseUp2)
    {
        bMouseUp2=false; //The button is pressed
        /********************************************************************
        **************** Here comes mouse play ******************************
        ********************************************************************/
        if((!showOptions)&&(!showHighscores))
        {
            if(mouseplay1) //player 1
            if((mousex > 50)&&(mousey>100)&&(mousex<50+300)&&(mousey<100+600))
            {
                theGame.PushLine();
            }
            if(mouseplay2) //player 2
            if((mousex > xsize-500)&&(mousey>100)&&(mousex<xsize-500+300)&&(mousey<100+600))
            {
                theGame2.PushLine();
            }
        }  
        /********************************************************************
        **************** Here ends mouse play *******************************
        ********************************************************************/
    }
} //if !singlePuzzle
else
{
   
}
  } //if !bScreenBocked;

  
  //Sees if music is stopped and if music is enabled
  if((!NoSound)&&(!Mix_PlayingMusic())&&(MusicEnabled))
    {
      // then starts playing it.
      Mix_PlayMusic(bgMusic, 0); //music loop
    }
  
  //Updates the objects
  theGame.Update();
  theGame2.Update();

 //see if anyone has won (two players only)
  if(!networkPlay)
  if(twoPlayers)
  {
  	  lastNrOfPlayers = 2;
	  if((theGame.bGameOver) && (theGame2.bGameOver))
	  {
		  if(theGame.score+theGame.handicap>theGame2.score+theGame2.handicap)
			  theGame.setPlayerWon();
		  else
		    if(theGame.score+theGame.handicap<theGame2.score+theGame2.handicap)
			  theGame2.setPlayerWon();
			else {theGame.setDraw(); theGame2.setDraw();}
		  twoPlayers = false;
	  }
	  if((theGame.bGameOver) && (!theGame2.bGameOver))
	  {
		  theGame2.setPlayerWon();
		  twoPlayers = false;
	  }
	  if((!theGame.bGameOver) && (theGame2.bGameOver))
	  {
		  theGame.setPlayerWon();
		  twoPlayers = false;
	  }
  }

  //Once evrything has been checked, update graphics
  DrawEverything(xsize,ysize,theGame, theGame2);
  SDL_GetMouseState(&mousex,&mousey);
  //Remember mouse placement
  oldMousex = mousex;
  oldMousey = mousey;
  //Draw the mouse: 
  DrawIMG(mouse,screen,mousex,mousey);
  SDL_Flip(screen);
  } //game loop
  
  

  //Saves options
  ofstream optionsFileOut;
  optionsFileOut.open(optionsPath.c_str(),ios::binary|ios::trunc);
  if(optionsFileOut)
  {
	//writes data: xsize,ysize,fullescreen, player1keys, player2keys, MusicEnabled, SoundEnabled,player1name,player2name
    optionsFileOut.write(reinterpret_cast<char*>(&xsize),sizeof(int));
	optionsFileOut.write(reinterpret_cast<char*>(&ysize),sizeof(int));
	optionsFileOut.write(reinterpret_cast<char*>(&bFullscreen),sizeof(bool));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[0].up), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[0].down), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[0].left), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[0].right), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[0].change), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[0].push), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[2].up), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[2].down), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[2].left), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[2].right), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[2].change), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&keySettings[2].push), sizeof(SDLKey));
	optionsFileOut.write(reinterpret_cast<char*>(&MusicEnabled),sizeof(bool));
	optionsFileOut.write(reinterpret_cast<char*>(&SoundEnabled),sizeof(bool));
	optionsFileOut.write(player1name,30*sizeof(char));
	optionsFileOut.write(player2name,30*sizeof(char));
	optionsFileOut.write(reinterpret_cast<char*>(&mouseplay1),sizeof(bool));
	optionsFileOut.write(reinterpret_cast<char*>(&mouseplay2),sizeof(bool));
	optionsFileOut.write(reinterpret_cast<char*>(&joyplay1),sizeof(bool));
	optionsFileOut.write(reinterpret_cast<char*>(&joyplay2),sizeof(bool));
	optionsFileOut.close();
	cout << "options written to file" << endl;
  }
  else
  {
	  cout << "Failed to write options" << endl;
  }


  //Frees memory from music and fonts
  //This is done after writing of options since it's often crashes the program :(
  UnloadImages(); 

  //calculate uptime:
  int hours, mins, secs, time;
  time = SDL_GetTicks();
  hours = time/(1000*60*60);
  time = time % (1000*60*60);
  mins = time/(1000*60);
  time = time % (1000*60);
  secs = time/1000;
  
  cout << "Block Attack - Rise of the Blocks ran for: " << hours << " hours " << mins << " mins and " << secs << " secs" << endl;         
          	
  return 0;
}