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

#include "Game.h"
#include "Timer.h"
#include "LoadMenu.h"
#include "System.h"
#include "Camera.h"
#include "Aircraft.h"
#include "GameGui.h"
#include "EndAnimation.h"
#include "Sfx.h"
#include "Pad.h"
#include "Message.h"

/* *************************************
 *  Defines
 * *************************************/

#define GAME_MAX_RUNWAYS 16
#define GAME_MAX_AIRCRAFT_PER_TILE 4
#define FLIGHT_DATA_INVALID_IDX 0xFF

#define MIN_MAP_COLUMNS 8
#define MAX_MAP_COLUMNS 32

#define LEVEL_HEADER_SIZE 64
#define COLUMNS_PER_TILESET 4
#define ROWS_PER_TILESET COLUMNS_PER_TILESET
#define LEVEL_MAGIC_NUMBER_SIZE 3
#define LEVEL_MAGIC_NUMBER_STRING "ATC"
#define LEVEL_TITLE_SIZE 24
#define TILE_MIRROR_FLAG (0x80)

#define GAME_INVALID_TILE_SELECTION ( (uint16_t)0xFFFF )

#define GAME_MINIMUM_PARKING_SPAWN_TIME (2 * TIMER_PRESCALER_1_SECOND) // 2 seconds

/* **************************************
 *  Structs and enums                   *
 * *************************************/

typedef struct t_rwyentrydata
{
    DIRECTION Direction;
    uint16_t rwyEntryTile;
    int8_t rwyStep;
    uint16_t rwyHeader;
}TYPE_RWY_ENTRY_DATA;

typedef struct t_GameLevelBuffer_UVData
{
    short u;
    short v;
}TYPE_TILE_UV_DATA;

enum
{
    MOUSE_W = 8,
    MOUSE_H = 8,
    MOUSE_X = (X_SCREEN_RESOLUTION >> 1),
    MOUSE_Y = (Y_SCREEN_RESOLUTION >> 1),
    MOUSE_X_2PLAYER = (X_SCREEN_RESOLUTION >> 2),
    MOUSE_Y_2PLAYER = (Y_SCREEN_RESOLUTION >> 1)
};

enum
{
    LOST_FLIGHT_PENALTY = 4000,
    SCORE_REWARD_TAXIING = 200,
    SCORE_REWARD_FINAL = 400,
    SCORE_REWARD_UNLOADING = 300,
    SCORE_REWARD_TAKEOFF = 200,
    SCORE_REWARD_FINISH_FLIGHT = 1000
};

enum
{
    UNBOARDING_KEY_SEQUENCE_EASY = 4,
    UNBOARDING_KEY_SEQUENCE_MEDIUM = 6,
    UNBOARDING_KEY_SEQUENCE_HARD = GAME_MAX_SEQUENCE_KEYS,
    UNBOARDING_PASSENGERS_PER_SEQUENCE = 100
};

enum
{
    TILE_GRASS,
    TILE_ASPHALT_WITH_BORDERS,
    TILE_WATER,
    TILE_ASPHALT,

    TILE_RWY_MID,
    TILE_RWY_START_1,
    TILE_RWY_START_2,
    TILE_PARKING,

    TILE_PARKING_2,
    TILE_TAXIWAY_INTERSECT_GRASS,
    TILE_TAXIWAY_GRASS,
    TILE_TAXIWAY_CORNER_GRASS,

    TILE_HALF_WATER_1,
    TILE_HALF_WATER_2,
    TILE_RWY_HOLDING_POINT,
    TILE_RWY_HOLDING_POINT_2,

    TILE_RWY_EXIT,
    TILE_TAXIWAY_CORNER_GRASS_2,
    TILE_TAXIWAY_4WAY_CROSSING,
    TILE_RWY_EXIT_2,

    LAST_TILE_TILESET1 = TILE_RWY_EXIT_2,

    TILE_UNUSED_1,
    TILE_TAXIWAY_CORNER_GRASS_3,

    FIRST_TILE_TILESET2 = TILE_UNUSED_1,
    LAST_TILE_TILESET2 = TILE_TAXIWAY_CORNER_GRASS_3
};

enum
{
    SOUND_M1_INDEX,
    SOUND_W1_INDEX,

    MAX_RADIO_CHATTER_SOUNDS
}RADIO_CHATTER_VOICE_NUMBERS;

/* *************************************
 *  Local Prototypes
 * *************************************/

static void GameInit(const TYPE_GAME_CONFIGURATION* const pGameCfg);
static void GameInitTileUVTable(void);
static bool GameExit(void);
static void GameLoadLevel(const char* path);
static bool GamePause(void);
static void GameFinished(const uint8_t i);
static void GameEmergencyMode(void);
static void GameCalculations(void);
static void GamePlayerHandler(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GamePlayerAddWaypoint(TYPE_PLAYER* const ptrPlayer);
static void GamePlayerAddWaypoint_Ex(TYPE_PLAYER* const ptrPlayer, uint16_t tile);
static void GameGraphics(void);
static void GameRenderTerrainPrecalculations(TYPE_PLAYER* const ptrPlayer, const TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameRenderTerrain(TYPE_PLAYER* const ptrPlayer);
static void GameClock(void);
static void GameClockFlights(const uint8_t i);
static void GameAircraftState(const uint8_t i);
static void GameActiveAircraft(const uint8_t i);
static void GameStateShowAircraft(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameSelectAircraftFromList(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameStateSelectRunway(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameStateSelectTaxiwayRunway(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameStateSelectTaxiwayParking(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameStateLockTarget(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static TYPE_ISOMETRIC_POS GameSelectAircraft(TYPE_PLAYER* const ptrPlayer);
static void GameSelectAircraftWaypoint(TYPE_PLAYER* const ptrPlayer);
static void GameGetRunwayArray(void);
static void GameGetSelectedRunwayArray(uint16_t rwyHeader, uint16_t* rwyArray, size_t sz);
static void GameAssignRunwaytoAircraft(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static bool GamePathToTile(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameDrawMouse(TYPE_PLAYER* const ptrPlayer);
static void GameStateUnboarding(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameGenerateUnboardingSequence(TYPE_PLAYER* const ptrPlayer);
static void GameCreateTakeoffWaypoints(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData, uint8_t aircraftIdx);
static void GameGetRunwayEntryTile(uint8_t aircraftIdx, TYPE_RWY_ENTRY_DATA* ptrRwyEntry);
static void GameActiveAircraftList(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData);
static void GameRemainingAircraft(const uint8_t i);
static void GameMinimumSpawnTimeout(void);
static void GameRenderBuildingAircraft(TYPE_PLAYER* const ptrPlayer);
static void GameGetAircraftTilemap(const uint8_t i);
static bool GameWaypointCheckExisting(TYPE_PLAYER* const ptrPlayer, uint16_t temp_tile);
static void GameDrawBackground(TYPE_PLAYER* const ptrPlayer);
static DIRECTION GameGetRunwayDirection(uint16_t rwyHeader);
static DIRECTION GameGetParkingDirection(uint16_t parkingTile);

/* *************************************
 *  Global Variables
 * *************************************/

bool GameStartupFlag;
uint32_t GameScore;

/* *************************************
 *  Local Variables
 * *************************************/

// Sprites
static GsSprite GameTilesetSpr;
static GsSprite GameTileset2Spr;
static GsSprite GamePlaneSpr;
static GsSprite GameMouseSpr;
static GsSprite GameBuildingSpr;

static uint16_t GameRwy[GAME_MAX_RUNWAYS];
static TYPE_FLIGHT_DATA FlightData;
static uint16_t GameUsedRwy[GAME_MAX_RUNWAYS];
static uint16_t GameSelectedTile;
static TYPE_TIMER* GameSpawnMinTime;
static bool spawnMinTimeFlag;
static bool aircraftCreated;
static bool GameAircraftCollisionFlag;
static uint8_t GameAircraftCollisionIdx;
static uint8_t GameAircraftTilemap[GAME_MAX_MAP_SIZE][GAME_MAX_AIRCRAFT_PER_TILE];

static TYPE_TILE_UV_DATA GameLevelBuffer_UVData[GAME_MAX_MAP_SIZE];

// Radio chatter
static SsVag ApproachSnds[MAX_RADIO_CHATTER_SOUNDS];
static SsVag TowerFinalSnds[MAX_RADIO_CHATTER_SOUNDS];

// Takeoff sounds
static SsVag TakeoffSnd;

// Beep sounds (taxiway/parking accept)
static SsVag BeepSnd;

// Instances for player-specific data
static TYPE_PLAYER PlayerData[MAX_PLAYERS] =
{
    [PLAYER_ONE] =
    {
        .PadKeyPressed_Callback = &PadOneKeyPressed,
        .PadKeyReleased_Callback = &PadOneKeyReleased,
        .PadKeySinglePress_Callback = &PadOneKeySinglePress,
        .PadDirectionKeyPressed_Callback = &PadOneDirectionKeyPressed,
        .PadLastKeySinglePressed_Callback = &PadOneGetLastKeySinglePressed
    },

    [PLAYER_TWO] =
    {
        .PadKeyPressed_Callback = &PadTwoKeyPressed,
        .PadKeyReleased_Callback = &PadTwoKeyReleased,
        .PadDirectionKeyPressed_Callback = &PadTwoDirectionKeyPressed,
        .PadKeySinglePress_Callback = &PadTwoKeySinglePress,
        .PadLastKeySinglePressed_Callback = &PadTwoGetLastKeySinglePressed
    }

};

static void* GamePltDest[] = {(TYPE_FLIGHT_DATA*)&FlightData    };

static uint16_t levelBuffer[GAME_MAX_MAP_SIZE];

static uint8_t GameLevelColumns;
static uint16_t GameLevelSize;

static char GameLevelTitle[LEVEL_TITLE_SIZE];

//Game local time
static uint8_t GameHour;
static uint8_t GameMinutes;

//Local flag for two-player game mode. Obtained from Menu
static bool twoPlayers;

// Determines whether game has finished or not.
bool levelFinished;

/* ***************************************************************************************
 *
 * @name: void Game(TYPE_GAME_CONFIGURATION* pGameCfg)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Game main loop. Called by "Menu" module.
 *
 * @remarks:
 *
 * ***************************************************************************************/
void Game(const TYPE_GAME_CONFIGURATION* const pGameCfg)
{
    twoPlayers = pGameCfg->TwoPlayers;
    GameInit(pGameCfg);

    while (1)
    {
        if (GameExit())
        {
            break;
        }

        GameEmergencyMode();

        GameCalculations();

        GameGraphics();

        if (GameStartupFlag)
        {
            GameStartupFlag = false;
        }
    }

    GfxDisableSplitScreen();

    EndAnimation();
}

/* ***************************************************************************************
 *
 * @name: bool GameExit(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Evaluates special conditions which end current game and return to main menu.
 *
 * @returns:
 *  True if game has to be exitted, false otherwise.
 *
 * ***************************************************************************************/
static bool GameExit(void)
{
    if (levelFinished)
    {
        // Exit game on level finished.
        if (GameGuiFinishedDialog(&PlayerData[PLAYER_ONE]))
        {
            return true;
        }
    }

    if (GamePause())
    {
        // Exit game if player desires to exit.
        return true;
    }

    if (GameAircraftCollisionFlag)
    {
        GameGuiAircraftCollision(&PlayerData[PLAYER_ONE]);
        return true;
    }

    return false;
}

/* ***************************************************************************************
 *
 * @name: bool GamePause(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  When PAD_START is pressed, it draws a rectangle on top of the screen and the game halts.
 *
 * @remarks:
 *
 * ***************************************************************************************/
static bool GamePause(void)
{
    uint8_t i;

    if (GameStartupFlag)
    {
        return false;
    }

    for (i = 0 ; i < MAX_PLAYERS ; i++)
    {
        const TYPE_PLAYER* const ptrPlayer = &PlayerData[i];

        // Run player-specific functions for each player
        if (ptrPlayer->Active)
        {
            //Serial_printf("Released callback = 0x%08X\n", ptrPlayer->PadKeySinglePress_Callback);
            if (ptrPlayer->PadKeySinglePress_Callback(PAD_START))
            {
                Serial_printf("Player %d set pause_flag to true!\n",i);

                // Blocking function:
                //  * Returns true if player pointed to by ptrPlayer wants to exit game
                //  * Returns false if player pointed to by ptrPlayer wants to resume game
                return GameGuiPauseDialog(ptrPlayer);
            }
        }
    }

    return false;
}

/* ***************************************************************************************
 *
 * @name: void GameInit(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Game basic parameters initialization.
 *
 * @remarks:
 *  Tilesets and buildings are only loaded on first game. Then, only PLT is loaded.
 *
 * ***************************************************************************************/
void GameInit(const TYPE_GAME_CONFIGURATION* const pGameCfg)
{
    static const char* const GameFileList[] =
    {
        "DATA\\SPRITES\\TILESET1.TIM",
        "DATA\\SPRITES\\TILESET2.TIM",
        "DATA\\SPRITES\\GAMEPLN.TIM",
        "DATA\\SPRITES\\PLNBLUE.CLT",
        "DATA\\SPRITES\\MOUSE.TIM",
        "DATA\\SPRITES\\BLDNGS1.TIM",
        "DATA\\SOUNDS\\RCPW1A1.VAG",
        "DATA\\SOUNDS\\RCPM1A1.VAG",
        "DATA\\SOUNDS\\RCTM1F1.VAG",
        "DATA\\SOUNDS\\TAKEOFF1.VAG",
        "DATA\\SOUNDS\\BEEP.VAG"
    };

    static void* GameFileDest[] =
    {
        &GameTilesetSpr,
        &GameTileset2Spr,
        &GamePlaneSpr,
        NULL, // CLT files must use NULL pointers
        &GameMouseSpr,
        &GameBuildingSpr,
        &ApproachSnds[SOUND_M1_INDEX],
        &ApproachSnds[SOUND_W1_INDEX],
        &TowerFinalSnds[SOUND_M1_INDEX],
        &TakeoffSnd,
        &BeepSnd
    };

    uint8_t i;
    static bool loaded;

    GameStartupFlag = true;

    // Has to be initialized before loading *.PLT files inside LoadMenu().
    MessageInit();

    if (loaded == false)
    {
        loaded = true;

        LOAD_FILES(GameFileList, GameFileDest);

        GameSpawnMinTime = TimerCreate(GAME_MINIMUM_PARKING_SPAWN_TIME, false, GameMinimumSpawnTimeout);
    }

    LoadMenu(   &pGameCfg->PLTPath,
                GamePltDest,
                sizeof (char),
                ARRAY_SIZE(GamePltDest));

    GameLoadLevel(pGameCfg->LVLPath);

    GameGuiInit();

    memset(GameRwy, 0, GAME_MAX_RUNWAYS * sizeof (uint16_t) );

    memset(GameUsedRwy, 0, GAME_MAX_RUNWAYS * sizeof (uint16_t) );

    PlayerData[PLAYER_ONE].Active = true;
    PlayerData[PLAYER_ONE].FlightDataPage = 0;
    PlayerData[PLAYER_ONE].UnboardingSequenceIdx = 0;

    PlayerData[PLAYER_ONE].ShowAircraftData = false;
    PlayerData[PLAYER_ONE].SelectRunway = false;
    PlayerData[PLAYER_ONE].SelectTaxiwayRunway = false;
    PlayerData[PLAYER_ONE].SelectTaxiwayParking = false;
    PlayerData[PLAYER_ONE].InvalidPath = false;
    PlayerData[PLAYER_ONE].LockTarget = false;
    PlayerData[PLAYER_ONE].Unboarding = false;

    memset(PlayerData[PLAYER_ONE].UnboardingSequence, 0, GAME_MAX_SEQUENCE_KEYS * sizeof (unsigned short) );
    memset(PlayerData[PLAYER_ONE].TileData, 0, GAME_MAX_MAP_SIZE * sizeof (TYPE_TILE_DATA));

    PlayerData[PLAYER_TWO].Active = twoPlayers? true : false;

    if (PlayerData[PLAYER_TWO].Active)
    {
        PlayerData[PLAYER_TWO].FlightDataPage = 0;
        PlayerData[PLAYER_TWO].UnboardingSequenceIdx = 0;

        PlayerData[PLAYER_TWO].ShowAircraftData = false;
        PlayerData[PLAYER_TWO].SelectRunway = false;
        PlayerData[PLAYER_TWO].SelectTaxiwayRunway = false;
        PlayerData[PLAYER_TWO].SelectTaxiwayParking = false;
        PlayerData[PLAYER_TWO].InvalidPath = false;
        PlayerData[PLAYER_TWO].LockTarget = false;
        PlayerData[PLAYER_TWO].Unboarding = false;

        memset(PlayerData[PLAYER_TWO].UnboardingSequence, 0, GAME_MAX_SEQUENCE_KEYS * sizeof (unsigned short) );
        memset(PlayerData[PLAYER_TWO].TileData, 0, GAME_MAX_MAP_SIZE * sizeof (TYPE_TILE_DATA));

        // On 2-player mode, one player controls departure flights and
        // other player controls arrival flights.
        PlayerData[PLAYER_ONE].FlightDirection = DEPARTURE;
        PlayerData[PLAYER_TWO].FlightDirection = ARRIVAL;
    }
    else
    {
        PlayerData[PLAYER_ONE].FlightDirection = DEPARTURE | ARRIVAL;
    }

    for (i = 0; i < MAX_PLAYERS ; i++)
    {
        CameraInit(&PlayerData[i]);
        PlayerData[i].ShowAircraftData = false;
        PlayerData[i].SelectRunway = false;
        PlayerData[i].SelectTaxiwayRunway = false;
        PlayerData[i].LockTarget = false;
        PlayerData[i].SelectedAircraft = 0;
        PlayerData[i].FlightDataPage = 0;
        memset(&PlayerData[i].Waypoints, 0, sizeof (uint16_t) * PLAYER_MAX_WAYPOINTS);
        PlayerData[i].WaypointIdx = 0;
        PlayerData[i].LastWaypointIdx = 0;
        PlayerData[i].RemainingAircraft = 0;
    }

    aircraftCreated = false;
    GameAircraftCollisionFlag = false;
    GameAircraftCollisionIdx = 0;

    if (GameTwoPlayersActive())
    {
        GameMouseSpr.x = MOUSE_X_2PLAYER;
        GameMouseSpr.y = MOUSE_Y_2PLAYER;
    }
    else
    {
        GameMouseSpr.x = MOUSE_X;
        GameMouseSpr.y = MOUSE_Y;
    }

    GameMouseSpr.w = MOUSE_W;
    GameMouseSpr.h = MOUSE_H;
    GameMouseSpr.attribute = COLORMODE(COLORMODE_16BPP);
    GameMouseSpr.r = NORMAL_LUMINANCE;
    GameMouseSpr.g = NORMAL_LUMINANCE;
    GameMouseSpr.b = NORMAL_LUMINANCE;

    spawnMinTimeFlag = false;

    GameScore = 0;

    GameGetRunwayArray();

    GameSelectedTile = 0;

    levelFinished = false;

    GameInitTileUVTable();

    AircraftInit();

    LoadMenuEnd();

    GfxSetGlobalLuminance(0);

    {
        const uint32_t track = SystemRand(GAMEPLAY_FIRST_TRACK, GAMEPLAY_LAST_TRACK);

        SfxPlayTrack(track);
    }
}

/* ***************************************************************************************
 *
 * @name: void GameEmergencyMode(void)
 *
 * @author: Xavier Del Campo
 *
 *
 * @brief:
 *  Draws a blue rectangle on top of the screen whenever one of the two active controllers
 *  (e.g.: pad1 on single player mode, pad1 || pad2 on two player mode) is disconnected.
 *
 * @remarks:
 *  See PSX_PollPad(), defined on psx.h, and Pad module for further information.
 *
 * ***************************************************************************************/
void GameEmergencyMode(void)
{
    uint8_t i;
    uint8_t disconnected_players = 0x00;
    static bool (*const PadXConnected[MAX_PLAYERS])(void) =
    {
        [PLAYER_ONE] = &PadOneConnected,
        [PLAYER_TWO] = &PadTwoConnected
    };

    enum
    {
        PAD_DISCONNECTED_TEXT_X = 48,
        PAD_DISCONNECTED_TEXT_Y = 48,
        PAD_DISCONNECTED_TEXT_Y_OFFSET_BITSHIFT = 5
    };

    do
    {
        bool enabled = false;

        if (SystemGetEmergencyMode())
        {
            enum
            {
                ERROR_RECT_X = 32,
                ERROR_RECT_W = X_SCREEN_RESOLUTION - (ERROR_RECT_X << 1),

                ERROR_RECT_Y = 16,
                ERROR_RECT_H = Y_SCREEN_RESOLUTION - (ERROR_RECT_Y << 1),

                ERROR_RECT_R = 0,
                ERROR_RECT_G = 32,
                ERROR_RECT_B = NORMAL_LUMINANCE
            };

            static const GsRectangle errorRct =
            {
                .x = ERROR_RECT_X,
                .w = ERROR_RECT_W,
                .y = ERROR_RECT_Y,
                .h = ERROR_RECT_H,
                .r = ERROR_RECT_R,
                .g = ERROR_RECT_G,
                .b = ERROR_RECT_B
            };

            // One of the pads has been disconnected during gameplay
            // Show an error screen until it is disconnected again.

            GsSortCls(0,0,0);
            GsSortRectangle((GsRectangle*)&errorRct);

            for (i = 0; i < MAX_PLAYERS; i++)
            {
                if (disconnected_players & (1 << i) )
                {
                    FontPrintText(  &SmallFont,
                                    PAD_DISCONNECTED_TEXT_X,
                                    PAD_DISCONNECTED_TEXT_Y + (i << PAD_DISCONNECTED_TEXT_Y_OFFSET_BITSHIFT),
                                    "Pad %s disconnected", i? "right" : "left"    );
                }
            }

            GfxDrawScene_Slow();
        }

        for (i = 0; i < MAX_PLAYERS; i++)
        {
            TYPE_PLAYER* const ptrPlayer = &PlayerData[i];

            if (ptrPlayer->Active)
            {
                if (PadXConnected[i]() == false)
                {
                    enabled = true;
                    disconnected_players |= 1 << i;
                }
                else
                {
                    disconnected_players &= ~(1 << i);
                }
            }
        }

        SystemSetEmergencyMode(enabled);

    } while (SystemGetEmergencyMode());
}

/* ***************************************************************************************
 *
 * @name: void GameGetAircraftTilemap(uint8_t i)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint8_t i:
 *      Index for FlightData table.
 *
 * @brief:
 *  On each cycle, it creates a 2-dimensional array relating aircraft indexes against
 *  tile numbers.
 *
 * @remarks:
 *
 * ***************************************************************************************/
static void GameGetAircraftTilemap(const uint8_t i)
{
    if (i == 0)
    {
        memset(GameAircraftTilemap, FLIGHT_DATA_INVALID_IDX, sizeof (GameAircraftTilemap) );
    }

    if (FlightData.State[i] != STATE_IDLE)
    {
        const uint16_t tileNr = AircraftGetTileFromFlightDataIndex(i);

        uint8_t j;

        for (j = 0; j < GAME_MAX_AIRCRAFT_PER_TILE; j++)
        {
            if (GameAircraftTilemap[tileNr][j] == FLIGHT_DATA_INVALID_IDX)
            {
                break;
            }
        }

        GameAircraftTilemap[tileNr][j] = i;
    }
}

/* ***************************************************************************************
 *
 * @name: void GameCalculations(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  First half of game execution. Executed when GPU is still drawing previous frame.
 *  Calculates all new states and values.
 *
 * @remarks:
 *  Since the GPU takes a long time to draw a frame, GameCalculations() should be used
 *  for all CPU-intensive tasks.
 *
 * ***************************************************************************************/
void GameCalculations(void)
{
    uint8_t i;

    GameClock();

    // Set level finished flag. It will
    // reset if at least one flight is still pending.
    levelFinished = true;

    for (i = 0; i < FlightData.nAircraft; i++)
    {
        GameFinished(i);
        GameClockFlights(i);
        GameAircraftState(i);
        GameActiveAircraft(i);
        GameRemainingAircraft(i);
        GameGetAircraftTilemap(i);
    }

    MessageHandler();
    AircraftHandler();
    GameGuiCalculateSlowScore();

    for (i = 0 ; i < MAX_PLAYERS ; i++)
    {
        // Run player-specific functions for each player
        if (PlayerData[i].Active)
        {
            GamePlayerHandler(&PlayerData[i], &FlightData);
        }
    }
}

/* ***************************************************************************************
 *
 * @name: void GamePlayerHandler(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Calls all routines attached to a player.
 *
 * @remarks:
 *
 * ***************************************************************************************/
void GamePlayerHandler(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    ptrPlayer->SelectedTile = 0;    // Reset selected tile if no states
                                    // which use this are currently active.
    ptrPlayer->InvalidPath = false; // Do the same thing for "InvalidPath".

    // Recalculate ptrPlayer->SelectedAircraft. In case new aircraft appear, we may be pointing
    // to a incorrect instance.
    GameActiveAircraftList(ptrPlayer, ptrFlightData);

    if (GameAircraftCollisionFlag)
    {
        TYPE_ISOMETRIC_POS IsoPos = AircraftGetIsoPos(GameAircraftCollisionIdx);
        CameraMoveToIsoPos(ptrPlayer, IsoPos);
    }

    if (System1SecondTick())
    {
        GameGuiCalculateNextAircraftTime(ptrPlayer, ptrFlightData);
    }

    GameStateUnboarding(ptrPlayer, ptrFlightData);
    GameStateLockTarget(ptrPlayer, ptrFlightData);
    GameStateSelectRunway(ptrPlayer, ptrFlightData);
    GameStateSelectTaxiwayRunway(ptrPlayer, ptrFlightData);
    GameStateSelectTaxiwayParking(ptrPlayer, ptrFlightData);
    GameStateShowAircraft(ptrPlayer, ptrFlightData);
    CameraHandler(ptrPlayer);
    GameRenderTerrainPrecalculations(ptrPlayer, ptrFlightData);
    GameGuiActiveAircraftPage(ptrPlayer, ptrFlightData);
    GameSelectAircraftFromList(ptrPlayer, ptrFlightData);
}

/* *******************************************************************
 *
 * @name: void GameClock(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Handles game clock later rendered on GameGui.
 *
 * @remarks:
 *
 * *******************************************************************/

void GameClock(void)
{
    if (System1SecondTick())
    {
        if (++GameMinutes >= 60)
        {
            GameMinutes = 0;

            if (++GameHour >= 24)
            {
                GameHour = 0;
            }
        }
    }
}

/* *******************************************************************
 *
 * @name: void GameClockFlights(uint8_t i)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint8_t i:
 *      Index for FlightData table.
 *
 * @brief:
 *  Handles hours/minutes values for all active aircraft.
 *
 * @remarks:
 *
 * *******************************************************************/

static void GameClockFlights(const uint8_t i)
{
    if (System1SecondTick())
    {
        if (FlightData.State[i] != STATE_IDLE)
        {
            if (FlightData.RemainingTime[i] != 0)
            {
                FlightData.RemainingTime[i]--;
            }
        }
        else
        {
            if ((FlightData.Minutes[i] == 0)
                        &&
                FlightData.Hours[i])
            {
                FlightData.Minutes[i] = 60;
                FlightData.Hours[i]--;
            }

            if (FlightData.Minutes[i])
            {
                FlightData.Minutes[i]--;
            }
        }
    }
}

/* *******************************************************************
 *
 * @name: void GameGraphics(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Second half of game execution. Once GameCalculations() has ended,
 *  states and new values have been calculated and all primitives are
 *  rendered depending on the obtained results.
 *
 * @remarks:
 *  It is advisable to keep CPU usage here, as once this function is
 *  entered, GPU is waiting for primitive data. Always try to move
 *  CPU-intensive operations to GameCalculations().
 *
 * *******************************************************************/

void GameGraphics(void)
{
    uint8_t i;
    bool split_screen = false;

    // Caution: blocking function!
    MessageRender();

    if (twoPlayers)
    {
        split_screen = true;
    }

    if (GfxGetGlobalLuminance() < NORMAL_LUMINANCE)
    {
        // Fading from black effect on startup.
        GfxIncreaseGlobalLuminance(1);
    }

    for (i = 0; i < MAX_PLAYERS ; i++)
    {
        TYPE_PLAYER* const ptrPlayer = &PlayerData[i];

        if (ptrPlayer->Active)
        {
            if (split_screen)
            {
                GfxSetSplitScreen(i);
            }

            // Draw half split screen for each player
            // only if 2-player mode is active. Else, render
            // the whole screen as usual.

            // Render background first.

            GameDrawBackground(ptrPlayer);

            // Then ground tiles must be rendered.

            GameRenderTerrain(ptrPlayer);

            // Ground tiles are now rendered. Now, depending on building/aircraft
            // positions, determine in what order they should be rendered.

            GameRenderBuildingAircraft(ptrPlayer);

            GameGuiAircraftList(ptrPlayer, &FlightData);

            GameGuiShowPassengersLeft(ptrPlayer);

            GameDrawMouse(ptrPlayer);

            GameGuiDrawUnboardingSequence(ptrPlayer);

            if (split_screen)
            {
                //~ GfxDrawScene_NoSwap();
                //~ while (GsIsDrawing());
            }
        }
    }

    // Avoid changing drawing environment twice on 1-player mode
    // as it doesn't make any sense.
    if (split_screen)
    {
        GfxDisableSplitScreen();
    }

    // Draw common elements for both players (messages, clock...)

    GameGuiBubble(&FlightData);

    GameGuiClock(GameHour,GameMinutes);

    GameGuiShowScore();

    if (split_screen)
    {
        //~ GfxDrawScene_NoSwap();
    }

    GfxDrawScene();
}

/* *******************************************************************
 *
 * @name: void GameDrawBackground(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Draws the background used for main gameplay.
 *
 * @remarks:
 *  Must be called before rendering anything else on screen!
 *
 * *******************************************************************/

void GameDrawBackground(TYPE_PLAYER* const ptrPlayer)
{
    enum
    {
        BG_POLY4_R0 = 0,
        BG_POLY4_G0 = 0,
        BG_POLY4_B0 = 16,

        BG_POLY4_R1 = 0,
        BG_POLY4_G1 = 0,
        BG_POLY4_B1 = 16,

        BG_POLY4_R2 = 0,
        BG_POLY4_G2 = 0,
        BG_POLY4_B2 = 80,

        BG_POLY4_R3 = 0,
        BG_POLY4_G3 = 0,
        BG_POLY4_B3 = 80
    };

    static const GsGPoly4 BgPoly4 =
    {
        .x[0] = 0,
        .x[1] = X_SCREEN_RESOLUTION,
        .x[2] = 0,
        .x[3] = X_SCREEN_RESOLUTION,

        .y[0] = 0,
        .y[1] = 0,
        .y[2] = Y_SCREEN_RESOLUTION,
        .y[3] = Y_SCREEN_RESOLUTION,

        .r[0] = BG_POLY4_R0,
        .g[0] = BG_POLY4_G0,
        .b[0] = BG_POLY4_B0,

        .r[1] = BG_POLY4_R1,
        .g[1] = BG_POLY4_G1,
        .b[1] = BG_POLY4_B1,

        .r[2] = BG_POLY4_R2,
        .g[2] = BG_POLY4_G2,
        .b[2] = BG_POLY4_B2,

        .r[3] = BG_POLY4_R3,
        .g[3] = BG_POLY4_G3,
        .b[3] = BG_POLY4_B3
    };

    GsSortGPoly4((GsGPoly4*)&BgPoly4);
}

/* *******************************************************************
 *
 * @name: void GameRenderBuildingAircraft(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to player data structure.
 *
 * @brief:
 *  Determines rendering order depending on building/aircraft
 *  isometric position data.
 *
 * @remarks:
 *
 * *******************************************************************/

void GameRenderBuildingAircraft(TYPE_PLAYER* const ptrPlayer)
{
    enum
    {
        BUILDING_NONE,
        BUILDING_HANGAR,
        BUILDING_ILS,
        BUILDING_ATC_TOWER,
        BUILDING_ATC_LOC,
        BUILDING_TERMINAL,
        BUILDING_TERMINAL_2,
        BUILDING_GATE,

        LAST_BUILDING = BUILDING_GATE,
        MAX_BUILDING_ID
    };

    enum
    {
        BUILDING_ATC_LOC_OFFSET_X = TILE_SIZE >> 1,
        BUILDING_ATC_LOC_OFFSET_Y = TILE_SIZE >> 1,

        BUILDING_ILS_OFFSET_X = 0,
        BUILDING_ILS_OFFSET_Y = 0,

        BUILDING_GATE_OFFSET_X = (TILE_SIZE >> 1) - 4,
        BUILDING_GATE_OFFSET_Y = 0,

        BUILDING_HANGAR_OFFSET_X = 4,
        BUILDING_HANGAR_OFFSET_Y = TILE_SIZE >> 1,

        BUILDING_TERMINAL_OFFSET_X = 0,
        BUILDING_TERMINAL_OFFSET_Y = TILE_SIZE >> 1,

        BUILDING_TERMINAL_2_OFFSET_X = BUILDING_TERMINAL_OFFSET_X,
        BUILDING_TERMINAL_2_OFFSET_Y = BUILDING_TERMINAL_OFFSET_Y,

        BUILDING_ATC_TOWER_OFFSET_X = TILE_SIZE >> 2,
        BUILDING_ATC_TOWER_OFFSET_Y = TILE_SIZE >> 1,
    };

    enum
    {
        BUILDING_ILS_U = 34,
        BUILDING_ILS_V = 0,
        BUILDING_ILS_W = 24,
        BUILDING_ILS_H = 34,

        BUILDING_GATE_U = 0,
        BUILDING_GATE_V = 70,
        BUILDING_GATE_W = 28,
        BUILDING_GATE_H = 25,

        BUILDING_HANGAR_U = 0,
        BUILDING_HANGAR_V = 0,
        BUILDING_HANGAR_W = 34,
        BUILDING_HANGAR_H = 28,

        BUILDING_TERMINAL_U = 0,
        BUILDING_TERMINAL_V = 34,
        BUILDING_TERMINAL_W = 51,
        BUILDING_TERMINAL_H = 36,

        BUILDING_TERMINAL_2_U = 51,
        BUILDING_TERMINAL_2_V = BUILDING_TERMINAL_V,
        BUILDING_TERMINAL_2_W = BUILDING_TERMINAL_W,
        BUILDING_TERMINAL_2_H = BUILDING_TERMINAL_H,

        BUILDING_ATC_TOWER_U = 58,
        BUILDING_ATC_TOWER_V = 0,
        BUILDING_ATC_TOWER_W = 29,
        BUILDING_ATC_TOWER_H = 34,

        BUILDING_ATC_LOC_U = 87,
        BUILDING_ATC_LOC_V = 0,
        BUILDING_ATC_LOC_W = 10,
        BUILDING_ATC_LOC_H = 34
    };

    enum
    {
        BUILDING_ILS_ORIGIN_X = 10,
        BUILDING_ILS_ORIGIN_Y = 22,

        BUILDING_GATE_ORIGIN_X = 20,
        BUILDING_GATE_ORIGIN_Y = 8,

        BUILDING_TERMINAL_ORIGIN_X = 20,
        BUILDING_TERMINAL_ORIGIN_Y = 11,

        BUILDING_TERMINAL_2_ORIGIN_X = BUILDING_TERMINAL_ORIGIN_X,
        BUILDING_TERMINAL_2_ORIGIN_Y = BUILDING_TERMINAL_ORIGIN_Y,

        BUILDING_HANGAR_ORIGIN_X = 16,
        BUILDING_HANGAR_ORIGIN_Y = 12,

        BUILDING_ATC_TOWER_ORIGIN_X = 12,
        BUILDING_ATC_TOWER_ORIGIN_Y = 20,

        BUILDING_ATC_LOC_ORIGIN_X = 6,
        BUILDING_ATC_LOC_ORIGIN_Y = 32
    };

    static const struct
    {
        TYPE_ISOMETRIC_POS IsoPos;  // Offset inside tile
        short orig_x;               // Coordinate X origin inside building sprite
        short orig_y;               // Coordinate Y origin inside building sprite
        short w;                    // Building width
        short h;                    // Building height
        short u;                    // Building X offset inside texture page
        short v;                    // Building Y offset inside texture page
    } GameBuildingData[MAX_BUILDING_ID] =
    {
        [BUILDING_GATE] =
        {
            .IsoPos.x = BUILDING_GATE_OFFSET_X,
            .IsoPos.y = BUILDING_GATE_OFFSET_Y,
            .orig_x = BUILDING_GATE_ORIGIN_X,
            .orig_y = BUILDING_GATE_ORIGIN_Y,
            .u = BUILDING_GATE_U,
            .v = BUILDING_GATE_V,
            .w = BUILDING_GATE_W,
            .h = BUILDING_GATE_H,
            // z coordinate set to 0 by default.
        },

        [BUILDING_ATC_LOC] =
        {
            .IsoPos.x = BUILDING_ATC_LOC_OFFSET_X,
            .IsoPos.y = BUILDING_ATC_LOC_OFFSET_Y,
            .orig_x = BUILDING_ATC_LOC_ORIGIN_X,
            .orig_y = BUILDING_ATC_LOC_ORIGIN_Y,
            .u = BUILDING_ATC_LOC_U,
            .v = BUILDING_ATC_LOC_V,
            .w = BUILDING_ATC_LOC_W,
            .h = BUILDING_ATC_LOC_H,
            // z coordinate set to 0 by default.
        },

        [BUILDING_ILS] =
        {
            .IsoPos.x = BUILDING_ILS_OFFSET_X,
            .IsoPos.y = BUILDING_ILS_OFFSET_Y,
            // z coordinate set to 0 by default.
            .orig_x = BUILDING_ILS_ORIGIN_X,
            .orig_y = BUILDING_ILS_ORIGIN_Y,
            .u = BUILDING_ILS_U,
            .v = BUILDING_ILS_V,
            .w = BUILDING_ILS_W,
            .h = BUILDING_ILS_H,
        },

        [BUILDING_HANGAR] =
        {
            // BUILDING_HANGAR coordinates inside tile.
            .IsoPos.x = BUILDING_HANGAR_OFFSET_X,
            .IsoPos.y = BUILDING_HANGAR_OFFSET_Y,
            // z coordinate set to 0 by default.
            .orig_x = BUILDING_HANGAR_ORIGIN_X,
            .orig_y = BUILDING_HANGAR_ORIGIN_Y,
            .u = BUILDING_HANGAR_U,
            .v = BUILDING_HANGAR_V,
            .w = BUILDING_HANGAR_W,
            .h = BUILDING_HANGAR_H,
        },

        [BUILDING_TERMINAL] =
        {
            // BUILDING_TERMINAL coordinates inside tile.
            .IsoPos.x = BUILDING_TERMINAL_OFFSET_X,
            .IsoPos.y = BUILDING_TERMINAL_OFFSET_Y,
            // z coordinate set to 0 by default.
            .orig_x = BUILDING_TERMINAL_ORIGIN_X,
            .orig_y = BUILDING_TERMINAL_ORIGIN_Y,
            .u = BUILDING_TERMINAL_U,
            .v = BUILDING_TERMINAL_V,
            .w = BUILDING_TERMINAL_W,
            .h = BUILDING_TERMINAL_H,
        },

        [BUILDING_TERMINAL_2] =
        {
            // BUILDING_TERMINAL_2 coordinates inside tile.
            .IsoPos.x = BUILDING_TERMINAL_2_OFFSET_X,
            .IsoPos.y = BUILDING_TERMINAL_2_OFFSET_Y,
            // z coordinate set to 0 by default.
            .orig_x = BUILDING_TERMINAL_2_ORIGIN_X,
            .orig_y = BUILDING_TERMINAL_2_ORIGIN_Y,
            .u = BUILDING_TERMINAL_2_U,
            .v = BUILDING_TERMINAL_2_V,
            .w = BUILDING_TERMINAL_2_W,
            .h = BUILDING_TERMINAL_2_H,
        },

        [BUILDING_ATC_TOWER] =
        {
            // BUILDING_ATC_TOWER coordinates inside tile.
            .IsoPos.x = BUILDING_ATC_TOWER_OFFSET_X,
            .IsoPos.y = BUILDING_ATC_TOWER_OFFSET_Y,
            // z coordinate set to 0 by default.
            .orig_x = BUILDING_ATC_TOWER_ORIGIN_X,
            .orig_y = BUILDING_ATC_TOWER_ORIGIN_Y,
            .u = BUILDING_ATC_TOWER_U,
            .v = BUILDING_ATC_TOWER_V,
            .w = BUILDING_ATC_TOWER_W,
            .h = BUILDING_ATC_TOWER_H,
        },

        [BUILDING_GATE] =
        {
            // BUILDING_GATE coordinates inside tile.
            .IsoPos.x = BUILDING_GATE_OFFSET_X,
            .IsoPos.y = BUILDING_GATE_OFFSET_Y,
            // z coordinate set to 0 by default.
            .orig_x = BUILDING_GATE_ORIGIN_X,
            .orig_y = BUILDING_GATE_ORIGIN_Y,
            .u = BUILDING_GATE_U,
            .v = BUILDING_GATE_V,
            .w = BUILDING_GATE_W,
            .h = BUILDING_GATE_H,
        },
    };

    uint16_t tileNr;
    uint8_t rows = 0;
    uint8_t columns = 0;

    for (tileNr = 0; tileNr < GameLevelSize; tileNr++)
    {
        // Building data is stored in levelBuffer MSB. LSB is dedicated to tile data.
        uint8_t CurrentBuilding = (uint8_t)(levelBuffer[tileNr] >> 8);
        uint8_t j;
        uint8_t k;
        uint8_t AircraftRenderOrder[GAME_MAX_AIRCRAFT_PER_TILE];
        short Aircraft_Y_Data[GAME_MAX_AIRCRAFT_PER_TILE];

        memset(AircraftRenderOrder, FLIGHT_DATA_INVALID_IDX, sizeof (AircraftRenderOrder) );

        for (j = 0; j < GAME_MAX_AIRCRAFT_PER_TILE; j++)
        {
            // Fill with 0x7FFF (maximum 16-bit positive value).
            Aircraft_Y_Data[j] = 0x7FFF;
        }

        for (j = 0; j < GAME_MAX_AIRCRAFT_PER_TILE; j++)
        {
            uint8_t AircraftIdx = GameAircraftTilemap[tileNr][j];

            TYPE_ISOMETRIC_POS aircraftIsoPos = AircraftGetIsoPos(AircraftIdx);

            if (AircraftIdx == FLIGHT_DATA_INVALID_IDX)
            {
                // No more aircraft on this tile.
                break;
            }

            //DEBUG_PRINT_VAR(aircraftIsoPos.y);

            for (k = 0; k < GAME_MAX_AIRCRAFT_PER_TILE; k++)
            {
                if (aircraftIsoPos.y < Aircraft_Y_Data[k])
                {
                    uint8_t idx;

                    for (idx = k; idx < (GAME_MAX_AIRCRAFT_PER_TILE - 1); idx++)
                    {
                        // Move previous Y values to the right.
                        Aircraft_Y_Data[idx + 1] = Aircraft_Y_Data[idx];
                        AircraftRenderOrder[idx + 1] = AircraftRenderOrder[idx];
                    }

                    Aircraft_Y_Data[k] = aircraftIsoPos.y;
                    AircraftRenderOrder[k] = AircraftIdx;

                    break;
                }
            }
        }

        if (CurrentBuilding == BUILDING_NONE)
        {
            for (k = 0; k < GAME_MAX_AIRCRAFT_PER_TILE; k++)
            {
                AircraftRender(ptrPlayer, AircraftRenderOrder[k]);
            }
        }
        else
        {
            // Determine rendering order depending on Y value.
            short x_bldg_offset = GameBuildingData[CurrentBuilding].IsoPos.x;
            short y_bldg_offset = GameBuildingData[CurrentBuilding].IsoPos.y;
            short z_bldg_offset = GameBuildingData[CurrentBuilding].IsoPos.z;
            short orig_u = GameBuildingSpr.u;
            short orig_v = GameBuildingSpr.v;

            TYPE_ISOMETRIC_POS buildingIsoPos =
            {
                .x = (columns << (TILE_SIZE_BIT_SHIFT)) + x_bldg_offset,
                .y = (rows << (TILE_SIZE_BIT_SHIFT)) + y_bldg_offset,
                .z = z_bldg_offset
            };

            // Isometric -> Cartesian conversion
            TYPE_CARTESIAN_POS buildingCartPos = GfxIsometricToCartesian(&buildingIsoPos);
            bool buildingDrawn = false;

            // Define new coordinates for building.
            GameBuildingSpr.x = buildingCartPos.x - GameBuildingData[CurrentBuilding].orig_x;
            GameBuildingSpr.y = buildingCartPos.y - GameBuildingData[CurrentBuilding].orig_y;

            GameBuildingSpr.u = orig_u + GameBuildingData[CurrentBuilding].u;
            GameBuildingSpr.v = orig_v + GameBuildingData[CurrentBuilding].v;
            GameBuildingSpr.w = GameBuildingData[CurrentBuilding].w;
            GameBuildingSpr.h = GameBuildingData[CurrentBuilding].h;

            CameraApplyCoordinatesToSprite(ptrPlayer, &GameBuildingSpr);

            for (k = 0; k < GAME_MAX_AIRCRAFT_PER_TILE; k++)
            {
                if (AircraftRenderOrder[k] == FLIGHT_DATA_INVALID_IDX)
                {
                    if (buildingDrawn == false)
                    {
                        GfxSortSprite(&GameBuildingSpr);

                        GameBuildingSpr.u = orig_u;
                        GameBuildingSpr.v = orig_v;

                        buildingDrawn = true;
                    }

                    break;
                }

                if (Aircraft_Y_Data[k] < buildingIsoPos.y)
                {
                    AircraftRender(ptrPlayer, AircraftRenderOrder[k]);
                }
                else
                {
                    if (buildingDrawn == false)
                    {
                        GfxSortSprite(&GameBuildingSpr);

                        GameBuildingSpr.u = orig_u;
                        GameBuildingSpr.v = orig_v;

                        buildingDrawn = true;
                    }

                    AircraftRender(ptrPlayer, AircraftRenderOrder[k]);
                }
            }
        }

        if (columns < (GameLevelColumns - 1) )
        {
            columns++;
        }
        else
        {
            rows++;
            columns = 0;
        }
    }
}

/* *******************************************************************
 *
 * @name: void GameLoadLevel(void)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Loads and parses *.LVL data.
 *
 *
 * @remarks:
 *  Filepath for *.LVL is given by GameLevelList[0]. Do NOT ever move
 *  it from there to avoid problems!
 *
 * *******************************************************************/

static void GameLoadLevel(const char* path)
{
    uint8_t i = 0;
    uint8_t* ptrBuffer;
    char LevelHeader[LEVEL_MAGIC_NUMBER_SIZE + 1];

    /* TODO - Very important */
    // Map contents (that means, without header) should be copied to levelBuffer
    // Header treatment (magic number, map size, map title...) should be done
    // using System's file buffer.

    if (SystemLoadFile((char*)path) == false)
    {
        return;
    }

    ptrBuffer = SystemGetBufferAddress();

    //SystemLoadFileToBuffer(GameLevelList[0],levelBuffer,GAME_MAX_MAP_SIZE);

    memset(LevelHeader,0, LEVEL_MAGIC_NUMBER_SIZE + 1);

    memcpy(LevelHeader,ptrBuffer,LEVEL_MAGIC_NUMBER_SIZE);

    LevelHeader[LEVEL_MAGIC_NUMBER_SIZE] = '\0';

    Serial_printf("Level header: %s\n",LevelHeader);

    if (strncmp(LevelHeader,LEVEL_MAGIC_NUMBER_STRING,LEVEL_MAGIC_NUMBER_SIZE) != 0)
    {
        Serial_printf("Invalid level header! Read \"%s\" instead of " LEVEL_MAGIC_NUMBER_STRING "\n", LevelHeader);
        return;
    }

    i += LEVEL_MAGIC_NUMBER_SIZE;

    GameLevelColumns = ptrBuffer[i++];

    Serial_printf("Level size: %d\n",GameLevelColumns);

    if (    (GameLevelColumns < MIN_MAP_COLUMNS)
                ||
            (GameLevelColumns > MAX_MAP_COLUMNS)    )
    {
        Serial_printf("Invalid map size! Value: %d\n",GameLevelColumns);
        return;
    }

    GameLevelSize = GameLevelColumns * GameLevelColumns;

    memset(GameLevelTitle,0,LEVEL_TITLE_SIZE);

    memcpy(GameLevelTitle,&ptrBuffer[i],LEVEL_TITLE_SIZE);

    Serial_printf("Game level title: %s\n",GameLevelTitle);

    i += LEVEL_TITLE_SIZE;

    memset(levelBuffer, 0, GAME_MAX_MAP_SIZE);

    i = LEVEL_HEADER_SIZE;

    {
        size_t j;
        size_t k;

        for (j = LEVEL_HEADER_SIZE, k = 0; k < GameLevelSize; j += sizeof (uint16_t), k++)
        {
            levelBuffer[k] = ptrBuffer[j + 1];
            levelBuffer[k] |= (ptrBuffer[j] << 8);
        }
    }
}

/* ******************************************************************************************
 *
 * @name: void GameAircraftState(uint8_t i)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint8_t i:
 *      Index for FlightData table.
 *
 * @brief:
 *  It determines what state should be applied to aircraft when spawn timer expires.
 *
 * @remarks:
 *  This is where TYPE_FLIGHT_DATA is transferred to TYPE_AIRCRAFT on departure.
 *
 * ******************************************************************************************/

static void GameAircraftState(const uint8_t i)
{
    if (FlightData.Finished[i] == false)
    {
        if ((FlightData.Hours[i] == 0)
                    &&
            (FlightData.Minutes[i] == 0)
                    &&
            (FlightData.State[i] == STATE_IDLE)
                    &&
            (FlightData.RemainingTime[i] != 0))
        {
            Serial_printf("Aircraft %d should now start...\n", i);
            if (spawnMinTimeFlag == false)
            {
                if ((FlightData.FlightDirection[i] == DEPARTURE)
                                    &&
                     FlightData.Parking[i])
                {
                    uint8_t j;
                    bool bParkingBusy = false;

                    for (j = 0; j < FlightData.nAircraft; j++)
                    {
                        if (AircraftFromFlightDataIndex(j)->State != STATE_IDLE)
                        {
                            const uint16_t* const targets = AircraftGetTargets(j);

                            if (targets != NULL)
                            {
                                const uint16_t tile = AircraftGetTileFromFlightDataIndex(j);

                                if (tile == FlightData.Parking[i])
                                {
                                    bParkingBusy = true;
                                }
                                else if (SystemContains_u16(FlightData.Parking[i], targets, AIRCRAFT_MAX_TARGETS))
                                {
                                    bParkingBusy = true;
                                }
                            }
                        }
                    }

                    if (bParkingBusy == false)
                    {
                        uint16_t target[2] = {0};
                        // Arrays are copied to AircraftAddNew, so we create a first and only
                        // target which is the parking tile itself, and the second element
                        // is just the NULL character.
                        // Not an ideal solution, but the best one currently available.

                        FlightData.State[i] = STATE_PARKED;

                        aircraftCreated = true;

                        // Create notification request for incoming aircraft
                        GameGuiBubbleShow();

                        target[0] = FlightData.Parking[i];

                        if (AircraftAddNew(&FlightData, i, target, GameGetParkingDirection(levelBuffer[target[0]])) == false)
                        {
                            Serial_printf("Exceeded maximum aircraft number!\n");
                            return;
                        }
                    }
                }
                else if (FlightData.FlightDirection[i] == ARRIVAL)
                {
                    const uint32_t idx = SystemRand(SOUND_M1_INDEX, ARRAY_SIZE(ApproachSnds));

                    FlightData.State[i] = STATE_APPROACH;
                    aircraftCreated = true;

                    // Play chatter sound.
                    SfxPlaySound(&ApproachSnds[idx]);

                    // Create notification request for incoming aircraft
                    GameGuiBubbleShow();
                }
            }
        }
        else if ( (FlightData.State[i] != STATE_IDLE)
                            &&
                  (FlightData.RemainingTime[i] == 0))
        {
            // Player(s) lost a flight!
            GameRemoveFlight(i, false);
        }
    }
}

static void GameInitTileUVTable(void)
{
    uint16_t i;

    memset(GameLevelBuffer_UVData, 0, sizeof (GameLevelBuffer_UVData));

    for (i = 0 ; i < GameLevelSize; i++)
    {
        uint8_t CurrentTile = (uint8_t)(levelBuffer[i] & 0x007F);   // Remove building data
                                                                    // and mirror flag.

        if (CurrentTile >= FIRST_TILE_TILESET2)
        {
            CurrentTile -= FIRST_TILE_TILESET2;
        }

        GameLevelBuffer_UVData[i].u = (short)(CurrentTile % COLUMNS_PER_TILESET) << TILE_SIZE_BIT_SHIFT;
        GameLevelBuffer_UVData[i].v = (short)(CurrentTile / COLUMNS_PER_TILESET) * TILE_SIZE_H;
    }
}

/* ******************************************************************************************
 *
 * @name: void GameRenderTerrainPrecalculations(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Reads current player states, precalculates RGB/XY/visibilty data and saves it into
 *  lookup tables which will be then used on GameRenderTerrain().
 *
 * @remarks:
 *  Tiles are usually rendered with normal RGB values unless parking/runway is busy
 *  or ptrPlayer->InvalidPath.
 *
 * ******************************************************************************************/
static void GameRenderTerrainPrecalculations(TYPE_PLAYER* const ptrPlayer, const TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint16_t i;
    uint8_t rows = 0;
    uint8_t columns = 0;
    unsigned char rwy_sine = SystemGetSineValue();
    bool used_rwy = SystemContains_u16(ptrPlayer->RwyArray[0], GameUsedRwy, GAME_MAX_RUNWAYS);

    for (i = 0 ; i < GameLevelSize; i++)
    {
        TYPE_ISOMETRIC_POS tileIsoPos;

        // levelBuffer bits explanation:
        // X X X X  X X X X     X X X X     X X X X
        // | | | |  | | | |     | | | |     | | | |
        // | | | |  | | | |     | | | |     | | | V
        // | | | |  | | | |     | | | |     | | V Tile, bit 0
        // | | | |  | | | |     | | | |     | V Tile, bit 1
        // | | | |  | | | |     | | | |     V Tile, bit 2
        // | | | |  | | | |     | | | V     Tile, bit 3
        // | | | |  | | | |     | | V Tile, bit 4
        // | | | |  | | | |     | V Tile, bit 5
        // | | | |  | | | |     V Tile, bit 6
        // | | | |  | | | |     Tile mirror flag
        // | | | |  | | | V
        // | | | |  | | V Building, bit 0
        // | | | |  | V Building, bit 1
        // | | | |  V Building, bit 2
        // | | | V  Building, bit 3
        // | | V Building, bit 4
        // | V Building, bit 5
        // V Building, bit 6
        // Building, bit 7
        uint8_t CurrentTile = (uint8_t)(levelBuffer[i] & 0x007F);   // Remove building data
                                                                    // and mirror flag.

        // Isometric -> Cartesian conversion
        tileIsoPos.x = columns << (TILE_SIZE_BIT_SHIFT);
        tileIsoPos.y = rows << (TILE_SIZE_BIT_SHIFT);
        tileIsoPos.z = 0;

        TYPE_TILE_DATA* const tileData = &ptrPlayer->TileData[i];

        tileData->CartPos = GfxIsometricToCartesian(&tileIsoPos);

        if (columns < (GameLevelColumns - 1) )
        {
            columns++;
        }
        else
        {
            rows++;
            columns = 0;
        }

        // Set coordinate origin to left upper corner.
        tileData->CartPos.x -= TILE_SIZE >> 1;

        CameraApplyCoordinatesToCartesianPos(ptrPlayer, &tileData->CartPos);

        if (GfxIsInsideScreenArea(  tileData->CartPos.x,
                                    tileData->CartPos.y,
                                    TILE_SIZE,
                                    TILE_SIZE_H ))
        {
            tileData->ShowTile = true;

            tileData->r = NORMAL_LUMINANCE;
            tileData->g = NORMAL_LUMINANCE;
            tileData->b = NORMAL_LUMINANCE;

            if (i != 0)
            {
                if (ptrPlayer->SelectRunway)
                {
                    if (SystemContains_u16(i, ptrPlayer->RwyArray, GAME_MAX_RWY_LENGTH))
                    {
                        if (used_rwy)
                        {
                            tileData->r = rwy_sine;
                            tileData->b = NORMAL_LUMINANCE >> 2;
                            tileData->g = NORMAL_LUMINANCE >> 2;
                        }
                        else
                        {
                            tileData->r = NORMAL_LUMINANCE >> 2;
                            tileData->g = NORMAL_LUMINANCE >> 2;
                            tileData->b = rwy_sine;
                        }
                    }
                }
                else if (   (ptrPlayer->SelectTaxiwayParking)
                                                ||
                            (ptrPlayer->SelectTaxiwayRunway)   )
                {
                    if ((   (SystemContains_u16(i, ptrPlayer->Waypoints, ptrPlayer->WaypointIdx))
                                        ||
                            (i == ptrPlayer->SelectedTile)  )
                                        &&
                            (ptrPlayer->SelectedTile != GAME_INVALID_TILE_SELECTION)    )
                    {
                        if (ptrPlayer->InvalidPath)
                        {
                            tileData->r = rwy_sine;
                            tileData->b = NORMAL_LUMINANCE >> 2;
                            tileData->g = NORMAL_LUMINANCE >> 2;
                        }
                        else
                        {
                            tileData->r = NORMAL_LUMINANCE >> 2;
                            tileData->g = NORMAL_LUMINANCE >> 2;
                            tileData->b = rwy_sine;
                        }
                    }
                    else if (   (ptrPlayer->SelectTaxiwayRunway)
                                            &&
                                (   (CurrentTile == TILE_RWY_HOLDING_POINT)
                                            ||
                                    (CurrentTile == TILE_RWY_HOLDING_POINT_2)   )   )
                    {
                        tileData->r = NORMAL_LUMINANCE >> 2;
                        tileData->g = rwy_sine;
                        tileData->b = NORMAL_LUMINANCE >> 2;
                    }
                    else if (   (ptrPlayer->SelectTaxiwayParking)
                                            &&
                                (   (CurrentTile == TILE_PARKING)
                                            ||
                                    (CurrentTile == TILE_PARKING_2) )   )
                    {
                        bool parkingBusy = false;

                        uint8_t aircraftIndex;

                        for (aircraftIndex = 0; aircraftIndex < GAME_MAX_AIRCRAFT; aircraftIndex++)
                        {
                            const TYPE_AIRCRAFT_DATA* const ptrAircraft = AircraftFromFlightDataIndex(aircraftIndex);

                            if (ptrAircraft->State == STATE_PARKED)
                            {
                                const uint16_t tile = AircraftGetTileFromFlightDataIndex(aircraftIndex);

                                if (i == tile)
                                {
                                    parkingBusy = true;
                                    break;
                                }
                            }
                        }

                        if (parkingBusy)
                        {
                            tileData->r = rwy_sine;
                            tileData->g = NORMAL_LUMINANCE >> 2;
                            tileData->b = NORMAL_LUMINANCE >> 2;
                        }
                        else
                        {
                            tileData->r = NORMAL_LUMINANCE >> 2;
                            tileData->g = rwy_sine;
                            tileData->b = NORMAL_LUMINANCE >> 2;
                        }
                    }
                }
                else if (ptrPlayer->ShowAircraftData)
                {
                    const uint8_t aircraftIndex = ptrPlayer->FlightDataSelectedAircraft;

                    switch (ptrFlightData->State[aircraftIndex])
                    {
                        case STATE_TAXIING:
                            // Fall through.
                        case STATE_USER_STOPPED:
                            // Fall through.
                        case STATE_AUTO_STOPPED:
                            // Fall through.
                        {
                            const uint16_t* const targets = AircraftGetTargets(aircraftIndex);

                            if (targets != NULL)
                            {
                                if (SystemContains_u16(i, targets, AIRCRAFT_MAX_TARGETS))
                                {
                                    if (SystemIndexOf_U16(i, targets, AIRCRAFT_MAX_TARGETS) >=
                                        AircraftGetTargetIdx(aircraftIndex))
                                    {
                                        tileData->r = NORMAL_LUMINANCE >> 2;
                                        tileData->g = NORMAL_LUMINANCE >> 2;
                                        tileData->b = rwy_sine;
                                    }
                                }
                            }
                        }
                        break;

                        default:
                        break;
                    }
                }
            }
        }
    }
}

/* ******************************************************************************************
 *
 * @name: void GameRenderTerrain(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *
 * @brief:
 *  Draws all tiles depending on levelBuffer configuration.
 *
 * @remarks:
 *  Tiles are usually rendered with normal RGB values unless parking/runway is busy
 *  or ptrPlayer->InvalidPath.
 *
 * ******************************************************************************************/
void GameRenderTerrain(TYPE_PLAYER* const ptrPlayer)
{
    uint16_t i;

    for (i = 0 ; i < GameLevelSize; i++)
    {
        if (ptrPlayer->TileData[i].ShowTile)
        {
            bool flip_id;
            GsSprite* ptrTileset;
            uint8_t aux_id;
            uint8_t CurrentTile = (uint8_t)(levelBuffer[i] & 0x00FF);

            // Flipped tiles have bit 7 set.
            if (CurrentTile & TILE_MIRROR_FLAG)
            {
                flip_id = true;
                aux_id = CurrentTile;
                CurrentTile &= ~(TILE_MIRROR_FLAG);
            }
            else
            {
                flip_id = false;
            }

            if (CurrentTile <= LAST_TILE_TILESET1)
            {
                // Draw using GameTilesetSpr
                ptrTileset = &GameTilesetSpr;
            }
            else if (   (CurrentTile > LAST_TILE_TILESET1)
                            &&
                        (CurrentTile <= LAST_TILE_TILESET2) )
            {
                // Draw using GameTileset2Spr
                ptrTileset = &GameTileset2Spr;
            }
            else
            {
                ptrTileset = NULL;
                continue;
            }

            // Apply {X, Y} data from precalculated lookup tables.
            ptrTileset->x = ptrPlayer->TileData[i].CartPos.x;
            ptrTileset->y = ptrPlayer->TileData[i].CartPos.y;

            // Apply RGB data from precalculated lookup tables.
            ptrTileset->r = ptrPlayer->TileData[i].r;
            ptrTileset->g = ptrPlayer->TileData[i].g;
            ptrTileset->b = ptrPlayer->TileData[i].b;

            if (flip_id)
            {
                ptrTileset->attribute |= H_FLIP;
            }

            ptrTileset->w = TILE_SIZE;
            ptrTileset->h = TILE_SIZE_H;

            ptrTileset->u = GameLevelBuffer_UVData[i].u;
            ptrTileset->v = GameLevelBuffer_UVData[i].v;

            ptrTileset->mx = ptrTileset->u + (TILE_SIZE >> 1);
            ptrTileset->my = ptrTileset->v + (TILE_SIZE_H >> 1);

            if (flip_id)
            {
                flip_id = false;
                CurrentTile = aux_id;
            }

            GfxSortSprite(ptrTileset);

            if (ptrTileset->attribute & H_FLIP)
            {
                ptrTileset->attribute &= ~(H_FLIP);
            }
        }
    }
}

/* *******************************************************************
 *
 * @name: void GameSetTime(uint8_t hour, uint8_t minutes)
 *
 * @author: Xavier Del Campo
 *
 * @brief:
 *  Reportedly, it sets game time to specified hour and minutes.
 *
 *
 * @remarks:
 *  To be used on GameInit() after PLT file parsing.
 *
 * *******************************************************************/
void GameSetTime(uint8_t hour, uint8_t minutes)
{
    GameHour = hour;
    GameMinutes = minutes;
}

/* *******************************************************************
 *
 * @name: void GameActiveAircraft(uint8_t i)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint8_t i:
 *      Index from FlightData array.
 *
 * @brief:
 *  On each game cycle, FlightData.ActiveAircraft is set to 0 and
 *  number of active aircraft is recalculated.
 *
 * @remarks:
 *  Called ciclically from GameCalculations(). This function is
 *  executed GAME_MAX_AIRCRAFT times on each cycle.
 *
 * *******************************************************************/
static void GameActiveAircraft(const uint8_t i)
{
    // Reset iterator when i == 0.

    if (i == 0)
    {
        FlightData.ActiveAircraft = 0;
    }

    if (FlightData.State[i] != STATE_IDLE)
    {
        FlightData.ActiveAircraft++;
    }
}

/* ******************************************************************************************
 *
 * @name: void GameStateShowAircraft(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Handles ptrPlayer->ShowAircraftData state.
 *
 *
 * @remarks:
 *  Called ciclically from GamePlayerHandler().
 *
 * ******************************************************************************************/

static void GameStateShowAircraft(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    if (ptrPlayer->ShowAircraftData)
    {
        if (ptrPlayer->PadKeySinglePress_Callback(PAD_TRIANGLE))
        {
            ptrPlayer->ShowAircraftData = false;
        }
    }

    if (ptrPlayer->PadKeySinglePress_Callback(PAD_CIRCLE))
    {
        if (GameGuiShowAircraftDataSpecialConditions(ptrPlayer) == false)
        {
            //Invert ptrPlayer->ShowAircraftData value
            ptrPlayer->ShowAircraftData = ptrPlayer->ShowAircraftData ? false : true;
        }
    }
}

/* ******************************************************************************************
 *
 * @name: void GameStateLockTarget(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Handles ptrPlayer->LockTarget state.
 *
 *
 * @remarks:
 *  Called ciclically from GamePlayerHandler().
 *
 ******************************************************************************************/

static void GameStateLockTarget(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint8_t AircraftIdx = ptrPlayer->FlightDataSelectedAircraft;

    if (ptrPlayer->LockTarget)
    {
        if ((ptrPlayer->LockedAircraft != FLIGHT_DATA_INVALID_IDX)
                            &&
            (ptrPlayer->LockedAircraft <= ptrPlayer->FlightDataSelectedAircraft))
        {
            CameraMoveToIsoPos(ptrPlayer, AircraftGetIsoPos(ptrPlayer->LockedAircraft) );
        }
    }

    if (ptrPlayer->ShowAircraftData)
    {
        if ( (ptrFlightData->State[AircraftIdx] != STATE_IDLE)
                                        &&
            (ptrFlightData->State[AircraftIdx] != STATE_APPROACH) )
        {
            ptrPlayer->LockTarget = true;
            ptrPlayer->LockedAircraft = AircraftIdx;
        }
    }
    else
    {
        ptrPlayer->LockTarget = false;
        ptrPlayer->LockedAircraft = FLIGHT_DATA_INVALID_IDX;
    }
}

/* ******************************************************************************************
 *
 * @name: void GameStateSelectTaxiwayRunway(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Handler for ptrPlayer->SelectTaxiwayRunway.
 *
 *
 * @remarks:
 *  Called ciclically from GamePlayerHandler().
 *
 * ******************************************************************************************/

static void GameStateSelectTaxiwayRunway(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint8_t i;
    uint16_t target_tile;

    /*Serial_printf("Camera is pointing to {%d,%d}\n",IsoPos.x, IsoPos.y);*/

    if (ptrPlayer->SelectTaxiwayRunway)
    {
        // Under this mode, always reset locking target.
        ptrPlayer->LockTarget = false;
        ptrPlayer->LockedAircraft = FLIGHT_DATA_INVALID_IDX;

        if (GamePathToTile(ptrPlayer, ptrFlightData) == false)
        {
            ptrPlayer->InvalidPath = true;
        }

        if (ptrPlayer->PadKeySinglePress_Callback(PAD_TRIANGLE))
        {
            // State exit.
            ptrPlayer->SelectTaxiwayRunway = false;
            // Clear waypoints array.
            memset(ptrPlayer->Waypoints, 0, sizeof (uint16_t) * PLAYER_MAX_WAYPOINTS);
            ptrPlayer->WaypointIdx = 0;
            ptrPlayer->LastWaypointIdx = 0;
        }
        else if (ptrPlayer->PadKeySinglePress_Callback(PAD_CROSS))
        {
            if (ptrPlayer->InvalidPath == false)
            {
                for (i = 0; i < PLAYER_MAX_WAYPOINTS; i++)
                {
                    if (ptrPlayer->Waypoints[i] == 0)
                    {
                        break;
                    }

                    ptrPlayer->LastWaypointIdx = i;
                }

                target_tile = levelBuffer[ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx]];

                SfxPlaySound(&BeepSnd);

                switch(target_tile)
                {
                    case TILE_RWY_HOLDING_POINT:
                        // Fall through
                    case TILE_RWY_HOLDING_POINT | TILE_MIRROR_FLAG:
                        // Fall through
                    case TILE_RWY_HOLDING_POINT_2:
                        // Fall through
                    case TILE_RWY_HOLDING_POINT_2 | TILE_MIRROR_FLAG:
                        AircraftFromFlightDataIndexAddTargets(ptrPlayer->FlightDataSelectedAircraft, ptrPlayer->Waypoints);
                        Serial_printf("Added these targets to aircraft %d:\n", ptrPlayer->FlightDataSelectedAircraft);

                        for (i = 0; i < PLAYER_MAX_WAYPOINTS; i++)
                        {
                            Serial_printf("%d ",ptrPlayer->Waypoints[i]);
                        }

                        Serial_printf("\n");

                        // Clear waypoints array.
                        memset(ptrPlayer->Waypoints, 0, sizeof (uint16_t) * PLAYER_MAX_WAYPOINTS);

                        // Reset state and auxiliar variables
                        ptrPlayer->WaypointIdx = 0;
                        ptrPlayer->LastWaypointIdx = 0;
                        ptrPlayer->LockedAircraft = FLIGHT_DATA_INVALID_IDX;
                        ptrPlayer->LockTarget = false;
                        ptrPlayer->SelectTaxiwayRunway = false;

                        ptrFlightData->State[ptrPlayer->FlightDataSelectedAircraft] = STATE_TAXIING;
                        GameScore += SCORE_REWARD_TAXIING;
                    break;

                    default:
                    break;
                }
            }
        }
    }
}

/* **************************************************************************************************
 *
 * @name: void GameStateSelectTaxiwayParking(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Handler for ptrPlayer->SelectTaxiwayParking.
 *
 * @remarks:
 *
 * **************************************************************************************************/
static void GameStateSelectTaxiwayParking(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint8_t i;
    uint16_t target_tile;

    if (ptrPlayer->SelectTaxiwayParking)
    {
        // Under this mode, always reset locking target.
        ptrPlayer->LockTarget = false;
        ptrPlayer->LockedAircraft = FLIGHT_DATA_INVALID_IDX;

        if (GamePathToTile(ptrPlayer, ptrFlightData) == false)
        {
            ptrPlayer->InvalidPath = true;
        }

        for (i = 0; i < GAME_MAX_AIRCRAFT; i++)
        {
            if (ptrPlayer->InvalidPath == false)
            {
                const TYPE_AIRCRAFT_DATA* const ptrAircraft = AircraftFromFlightDataIndex(i);

                if (ptrAircraft != NULL)
                {
                    if (ptrAircraft->State == STATE_PARKED)
                    {
                        const uint16_t tile = AircraftGetTileFromFlightDataIndex(i);

                        if (ptrPlayer->SelectedTile == tile)
                        {
                            ptrPlayer->InvalidPath = true;
                            break;
                        }
                    }
                }
            }
        }

        if (ptrPlayer->PadKeySinglePress_Callback(PAD_TRIANGLE))
        {
            // State exit.
            ptrPlayer->SelectTaxiwayParking = false;
            // Clear waypoints array.
            memset(ptrPlayer->Waypoints, 0, sizeof (uint16_t) * PLAYER_MAX_WAYPOINTS);
            ptrPlayer->WaypointIdx = 0;
            ptrPlayer->LastWaypointIdx = 0;
        }
        else if (ptrPlayer->PadKeySinglePress_Callback(PAD_CROSS))
        {
            if (ptrPlayer->InvalidPath == false)
            {
                for (i = 0; i < PLAYER_MAX_WAYPOINTS; i++)
                {
                    if (ptrPlayer->Waypoints[i] == 0)
                    {
                        break;
                    }

                    ptrPlayer->LastWaypointIdx = i;
                }

                target_tile = levelBuffer[ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx]] & ~(TILE_MIRROR_FLAG);

                SfxPlaySound(&BeepSnd);

                if (    (target_tile == TILE_PARKING)
                                ||
                        (target_tile == TILE_PARKING_2) )
                {
                    // TODO: Assign path to aircraft
                    AircraftFromFlightDataIndexAddTargets(ptrPlayer->FlightDataSelectedAircraft, ptrPlayer->Waypoints);

                    Serial_printf("Added these targets to aircraft %d:\n", ptrPlayer->FlightDataSelectedAircraft);

                    for (i = 0; i < PLAYER_MAX_WAYPOINTS; i++)
                    {
                        Serial_printf("%d ",ptrPlayer->Waypoints[i]);
                    }

                    Serial_printf("\n");

                    ptrPlayer->SelectTaxiwayParking = false;
                    // Clear waypoints array.
                    memset(ptrPlayer->Waypoints, 0, sizeof (uint16_t) * PLAYER_MAX_WAYPOINTS);
                    ptrPlayer->WaypointIdx = 0;
                    ptrPlayer->LastWaypointIdx = 0;

                    ptrFlightData->State[ptrPlayer->FlightDataSelectedAircraft] = STATE_TAXIING;
                    GameScore += SCORE_REWARD_TAXIING;
                }
                else
                {
                    Serial_printf("Tile %d cannot be used as end point.\n", target_tile);
                }
            }
        }
    }
}

/* **************************************************************************************************
 *
 * @name: void GameStateSelectRunway(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Handler for ptrPlayer->SelectRunway.
 *
 * @remarks:
 *
 * **************************************************************************************************/
static void GameStateSelectRunway(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint8_t i;
    TYPE_ISOMETRIC_POS IsoPos = {   GameGetXFromTile_short(GameRwy[ptrPlayer->SelectedRunway]),
                                    GameGetYFromTile_short(GameRwy[ptrPlayer->SelectedRunway]),
                                    0   };

    if (ptrPlayer->SelectRunway)
    {
        // Under this mode, always reset locking target.
        ptrPlayer->LockTarget = false;
        ptrPlayer->LockedAircraft = FLIGHT_DATA_INVALID_IDX;

        GameGetSelectedRunwayArray(GameRwy[ptrPlayer->SelectedRunway], ptrPlayer->RwyArray, sizeof (ptrPlayer->RwyArray));

        CameraMoveToIsoPos(ptrPlayer, IsoPos);

        if (ptrPlayer->PadKeySinglePress_Callback(PAD_TRIANGLE))
        {
            ptrPlayer->SelectRunway = false;
        }
        else if (ptrPlayer->PadKeySinglePress_Callback(PAD_CROSS))
        {
            bool success = false;

            if (SystemContains_u16(GameRwy[ptrPlayer->SelectedRunway], GameUsedRwy, GAME_MAX_RUNWAYS) == false)
            {
                ptrPlayer->SelectRunway = false;
                Serial_printf("Player selected runway %d!\n",GameRwy[ptrPlayer->SelectedRunway]);

                for (i = 0; i < GAME_MAX_RUNWAYS; i++)
                {
                    if (GameUsedRwy[i] == 0)
                    {
                        GameAssignRunwaytoAircraft(ptrPlayer, ptrFlightData);
                        success = true;
                        GameUsedRwy[i] = GameRwy[ptrPlayer->SelectedRunway];
                        break;
                    }
                }

                if (success == false)
                {
                    Serial_printf("No available runways!\n");
                }
            }
        }
        else if (ptrPlayer->PadKeySinglePress_Callback(PAD_LEFT))
        {
            if (ptrFlightData->State[ptrPlayer->FlightDataSelectedAircraft] == STATE_APPROACH)
            {
                if (ptrPlayer->SelectedRunway != 0)
                {
                    ptrPlayer->SelectedRunway--;
                }
            }
        }
        else if (ptrPlayer->PadKeySinglePress_Callback(PAD_RIGHT))
        {
            if (ptrFlightData->State[ptrPlayer->FlightDataSelectedAircraft] == STATE_APPROACH)
            {
                if (ptrPlayer->SelectedRunway < (GAME_MAX_RUNWAYS - 1))
                {
                    if (GameRwy[ptrPlayer->SelectedRunway + 1] != 0)
                    {
                        ptrPlayer->SelectedRunway++;
                    }
                }
            }
        }
    }
}

/* **************************************************************************************************
 *
 * @name: void GameGetRunwayArray(void)
 *
 * @author: Xavier Del Campo
 *
 *
 * @brief:
 *  On startup, an array of runway headers is created from levelBuffer once *.LVL is parsed.
 *
 * @remarks:
 *  Do not confuse GameRwy with GameRwyArray, which are used for completely different purposes.
 *
 * **************************************************************************************************/
void GameGetRunwayArray(void)
{
    uint16_t i;
    uint8_t j = 0;

    for (i = 0; i < GameLevelSize; i++)
    {
        uint8_t tileNr = levelBuffer[i] & ~TILE_MIRROR_FLAG;

        if (tileNr == TILE_RWY_START_1)
        {
            if (SystemContains_u16(i, levelBuffer, GAME_MAX_RUNWAYS) == false)
            {
                GameRwy[j++] = i;
            }
        }
    }

    Serial_printf("GameRwy = ");

    for (i = 0; i < GAME_MAX_RUNWAYS; i++)
    {
        if (GameRwy[i] == 0)
        {
            break;
        }

        Serial_printf("%d ", GameRwy[i]);
    }

    Serial_printf("\n");
}

/* **************************************************************************************************
 *
 * @name: void GameSelectAircraftFromList(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Actions for ptrPlayer->ShowAircraftData.
 *
 * @remarks:
 *
 * **************************************************************************************************/

static void GameSelectAircraftFromList(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint8_t AircraftIdx = ptrPlayer->FlightDataSelectedAircraft;
    FL_STATE aircraftState = ptrFlightData->State[AircraftIdx];

    if (ptrPlayer->ShowAircraftData)
    {
        if (ptrPlayer->PadKeySinglePress_Callback(PAD_CROSS))
        {
            if (ptrPlayer->ActiveAircraft != 0)
            {
                ptrPlayer->ShowAircraftData = false;

                switch(aircraftState)
                {
                    case STATE_APPROACH:
                        ptrPlayer->SelectRunway = true;
                    break;

                    case STATE_PARKED:
                        ptrPlayer->SelectTaxiwayRunway = true;
                        // Move camera to selected aircraft and add first waypoint.
                        GameSelectAircraftWaypoint(ptrPlayer);
                    break;

                    case STATE_LANDED:
                        ptrPlayer->SelectTaxiwayParking = true;
                        // Move camera to selected aircraft and add first waypoint.
                        GameSelectAircraftWaypoint(ptrPlayer);
                    break;

                    case STATE_UNBOARDING:
                        ptrPlayer->Unboarding = true;
                        // Move camera to selected aircraft.
                        GameSelectAircraft(ptrPlayer);
                        // Generate first unboarding key sequence
                        GameGenerateUnboardingSequence(ptrPlayer);
                    break;

                    case STATE_READY_FOR_TAKEOFF:
                        ptrFlightData->State[AircraftIdx] = STATE_TAKEOFF;
                        GameCreateTakeoffWaypoints(ptrPlayer, ptrFlightData, AircraftIdx);
                        SfxPlaySound(&TakeoffSnd);
                    break;

                    case STATE_HOLDING_RWY:
                    {
                        TYPE_RWY_ENTRY_DATA rwyEntryData = {0};
                        uint8_t i;

                        ptrPlayer->SelectRunway = true;
                        GameGetRunwayEntryTile(AircraftIdx, &rwyEntryData);

                        for (i = 0; GameRwy[i] != 0 && (i < (sizeof (GameRwy) / sizeof (GameRwy[0]))); i++)
                        {
                            if (GameRwy[i] == rwyEntryData.rwyHeader)
                            {
                                break;
                            }
                        }

                        ptrPlayer->SelectedRunway = i;
                    }
                    break;

                    default:
                        Serial_printf("Incompatible state %d!\n",aircraftState);
                        // States remain unchanged
                        ptrPlayer->SelectRunway = false;
                        ptrPlayer->SelectTaxiwayRunway = false;
                        ptrPlayer->ShowAircraftData = true;
                        ptrPlayer->Unboarding = false;
                    break;
                }
            }
        }
        else if (ptrPlayer->PadKeySinglePress_Callback(PAD_L1))
        {
            FL_STATE* const ptrAircraftState = &FlightData.State[ptrPlayer->FlightDataSelectedAircraft];

            switch (*ptrAircraftState)
            {
                case STATE_TAXIING:
                    *ptrAircraftState = STATE_USER_STOPPED;
                break;

                case STATE_USER_STOPPED:
                    // Fall through.
                case STATE_AUTO_STOPPED:
                    *ptrAircraftState = STATE_TAXIING;
                break;

                default:
                break;
            }
        }
    }
}

/* **************************************************************************************************
 *
 * @name: DIRECTION GameGetParkingDirection(uint16_t parkingTile)
 *
 * @author: Xavier Del Campo
 *
 * @return:
 *  Depending on tile number, parking direction is returned.
 *
 * **************************************************************************************************/
DIRECTION GameGetParkingDirection(uint16_t parkingTile)
{
    switch (parkingTile)
    {
        case TILE_PARKING:
        return DIR_WEST;

        case TILE_PARKING | TILE_MIRROR_FLAG:
        return DIR_NORTH;

        case TILE_PARKING_2:
        return DIR_EAST;

        case TILE_PARKING_2 | TILE_MIRROR_FLAG:
        return DIR_SOUTH;

        default:
        break;
    }

    return NO_DIRECTION;
}

/* **************************************************************************************************
 *
 * @name: DIRECTION GameGetRunwayDirection(uint16_t rwyHeader)
 *
 * @author: Xavier Del Campo
 *
 * @return:
 *  Depending on tile number, runway direction is returned.
 *
 * **************************************************************************************************/
DIRECTION GameGetRunwayDirection(uint16_t rwyHeader)
{
    switch(levelBuffer[rwyHeader])
    {
        case TILE_RWY_START_1:
            return DIR_EAST;

        case TILE_RWY_START_2:
            return DIR_WEST;

        case TILE_RWY_START_1 | TILE_MIRROR_FLAG:
            return DIR_SOUTH;

        case TILE_RWY_START_2 | TILE_MIRROR_FLAG:
            return DIR_NORTH;

        default:
            Serial_printf("Unknown direction for tile %d\n",rwyHeader);
            break;
    }

    return NO_DIRECTION;
}

/* **************************************************************************************************
 *
 * @name: void GameGetSelectedRunwayArray(uint16_t rwyHeader, uint16_t* rwyArray, size_t sz)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint16_t rwyHeader:
 *      Level tile number (located inside levelBuffer) pointing to runway header.
 *      Only TILE_RWY_START_1 and TILE_RWY_START_2 (with or without TILE_MIRROR_FLAG)
 *      can be used for runway headers!
 *
 *  uint16_t* rwyArray:
 *      Pointer to an array which will be filled with all the tiles belonging to a runway
 *      with header pointed to by rwyHeader.
 *
 *  size_t sz:
 *      Maximum size of the array.
 *
 * @brief:
 *  Fills rwyArray with all the tile numbers (included in levelBuffer) belonging to a
 *  runway with header pointed to by rwyHeader.
 *
 * @remarks:
 *
 * **************************************************************************************************/
void GameGetSelectedRunwayArray(uint16_t rwyHeader, uint16_t* rwyArray, size_t sz)
{
    static uint16_t last_tile = 0;
    static uint8_t i = 0;
    static DIRECTION dir;

    if (sz != (GAME_MAX_RWY_LENGTH * sizeof (uint16_t) ))
    {
        Serial_printf(  "GameGetSelectedRunwayArray: size %d is different"
                        " than expected (%d bytes). Returning...\n",
                        sz,
                        (GAME_MAX_RWY_LENGTH * sizeof (uint16_t) ) );
        return;
    }

    if (rwyHeader != 0)
    {
        // This function is called recursively.
        // Since 0 is not a valid value (it's not allowed to place
        // a runway header on first tile), it is used to determine
        // when to start creating the array.

        // Part one: determine runway direction and call the function again with rwyHeader == 0.

        memset(rwyArray, 0, sz);
        last_tile = rwyHeader;
        i = 0;

        dir = GameGetRunwayDirection(rwyHeader);

        if (dir == NO_DIRECTION)
        {
            Serial_printf("rwyHeader = %d returned NO_DIRECTION\n", rwyHeader);
            return;
        }
    }
    else
    {
        // Part two: append tiles to array until runway end is found.

        if (    (levelBuffer[last_tile] == TILE_RWY_START_1)
                            ||
                (levelBuffer[last_tile] == TILE_RWY_START_2)
                            ||
                (levelBuffer[last_tile] == (TILE_RWY_START_1 | TILE_MIRROR_FLAG) )
                            ||
                (levelBuffer[last_tile] == (TILE_RWY_START_2 | TILE_MIRROR_FLAG) )  )
        {
            // Runway end found
            rwyArray[i++] = last_tile;
            return;
        }
    }

    rwyArray[i++] = last_tile;

    switch(dir)
    {
        case DIR_EAST:
            last_tile++;
        break;

        case DIR_WEST:
            last_tile--;
        break;

        case DIR_NORTH:
            last_tile -= GameLevelColumns;
        break;

        case DIR_SOUTH:
            last_tile += GameLevelColumns;
        break;

        case NO_DIRECTION:
            // Fall through
        default:
            Serial_printf("Invalid runway direction.\n");
        return;
    }

    GameGetSelectedRunwayArray(0, rwyArray, sz);
}

/* **************************************************************************************************
 *
 * @name: void GameAssignRunwaytoAircraft(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Assigns a runway to an incoming aircraft (FlightDirection == ARRIVAL) depending on
 *  player selection.
 *
 * @remarks:
 *
 * **************************************************************************************************/

void GameAssignRunwaytoAircraft(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint16_t assignedRwy = GameRwy[ptrPlayer->SelectedRunway];
    uint8_t aircraftIndex = ptrPlayer->FlightDataSelectedAircraft;
    uint16_t rwyExit = 0;
    uint8_t i;
    uint16_t targets[AIRCRAFT_MAX_TARGETS] = {0};
    uint8_t rwyTiles[GAME_MAX_RWY_LENGTH] = {0};

    // Remember that ptrPlayer->SelectedAircraft contains an index to
    // be used with ptrFlightData.

    if (ptrFlightData->State[aircraftIndex] == STATE_APPROACH)
    {
        uint8_t j;
        bool firstEntryPointFound = false;
        uint16_t rwyArray[GAME_MAX_RWY_LENGTH];

        // TODO: Algorithm is not correct. If TILE_RWY_EXIT is placed further,
        // but returns a match earlier than other rwyExitTiles[], invalid targets
        // are returned to aircraft. We should check this before proceeding.
        static const uint8_t rwyExitTiles[] =
        {
            TILE_RWY_EXIT,
            TILE_RWY_EXIT | TILE_MIRROR_FLAG,
            TILE_RWY_EXIT_2,
            TILE_RWY_EXIT_2 | TILE_MIRROR_FLAG
        };

        ptrFlightData->State[aircraftIndex] = STATE_FINAL;
        GameScore += SCORE_REWARD_FINAL;

        GameGetSelectedRunwayArray(assignedRwy, rwyArray, sizeof (rwyArray));

        for (i = 0; i < GAME_MAX_RWY_LENGTH; i++)
        {
            rwyTiles[i] = levelBuffer[rwyArray[i]];
        }

        for (i = 0; (i < GAME_MAX_RWY_LENGTH) && (rwyExit == 0); i++)
        {
            for (j = 0; j < ARRAY_SIZE(rwyExitTiles); j++)
            {
                if (rwyTiles[i] == rwyExitTiles[j])
                {
                    if (firstEntryPointFound == false)
                    {
                        firstEntryPointFound = true;
                    }
                    else
                    {
                        rwyExit = rwyArray[i];
                    }

                    break;
                }
            }
        }

        if (rwyExit == 0)
        {
            Serial_printf("ERROR: Could not find TILE_RWY_EXIT or TILE_RWY_EXIT_2 for runway header %d.\n", assignedRwy);
            return;
        }

        // Create two new targets for the recently created aircraft.
        targets[0] = assignedRwy;
        targets[1] = rwyExit;

        if (AircraftAddNew( ptrFlightData,
                            aircraftIndex,
                            targets,
                            GameGetRunwayDirection(assignedRwy) ) == false)
        {
            Serial_printf("Exceeded maximum aircraft number!\n");
            return;
        }

        SfxPlaySound(&TowerFinalSnds[SystemRand(SOUND_M1_INDEX, MAX_RADIO_CHATTER_SOUNDS - 1)]);
    }
    else if (ptrFlightData->State[aircraftIndex] == STATE_HOLDING_RWY)
    {
        TYPE_RWY_ENTRY_DATA rwyEntryData = {0};

        GameGetRunwayEntryTile(aircraftIndex, &rwyEntryData);

        targets[0] = rwyEntryData.rwyEntryTile;
        targets[1] = targets[0] + rwyEntryData.rwyStep;

        AircraftAddTargets(AircraftFromFlightDataIndex(aircraftIndex), targets);

        ptrFlightData->State[aircraftIndex] = STATE_ENTERING_RWY;
    }
}

/* *******************************************************************
 *
 * @name: short GameGetXFromTile_short(uint16_t tile)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint16_t tile:
 *      Tile number from levelBuffer.
 *
 * @return:
 *  Returns relative X position (no fixed-point arithmetic) given
 *  a tile number from levelBuffer.
 *
 * @remarks:
 *
 * *******************************************************************/

short GameGetXFromTile_short(uint16_t tile)
{
    short retVal;

    tile %= GameLevelColumns;

    retVal = (tile << TILE_SIZE_BIT_SHIFT);

    // Always point to tile center
    retVal += TILE_SIZE >> 1;

    return retVal;
}

/* *******************************************************************
 *
 * @name: short GameGetYFromTile_short(uint16_t tile)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint16_t tile:
 *      Tile number from levelBuffer.
 *
 * @return:
 *  Returns relative Y position (no fixed-point arithmetic) given
 *  a tile number from levelBuffer.
 *
 * @remarks:
 *
 * *******************************************************************/

short GameGetYFromTile_short(uint16_t tile)
{
    short retVal;

    tile /= GameLevelColumns;

    retVal = (tile << TILE_SIZE_BIT_SHIFT);

    // Always point to tile center
    retVal += TILE_SIZE >> 1;

    return retVal;
}

/* *******************************************************************
 *
 * @name: fix16_t GameGetXFromTile(uint16_t tile)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint16_t tile:
 *      Tile number from levelBuffer.
 *
 * @return:
 *  Returns relative X position in 16.16 (fix16_t) fixed-point format
 *  given a tile number from levelBuffer.
 *
 * @remarks:
 *
 * *******************************************************************/

fix16_t GameGetXFromTile(uint16_t tile)
{
    return fix16_from_int(GameGetXFromTile_short(tile));
}

/* *******************************************************************
 *
 * @name: fix16_t GameGetYFromTile(uint16_t tile)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint16_t tile:
 *      Tile number from levelBuffer.
 *
 * @return:
 *  Returns relative Y position in 16.16 (fix16_t) fixed-point format
 *  given a tile number from levelBuffer.
 *
 * @remarks:
 *
 * *******************************************************************/

fix16_t GameGetYFromTile(uint16_t tile)
{
    return fix16_from_int(GameGetYFromTile_short(tile));
}

/* ****************************************************************************
 *
 * @name: FL_STATE GameTargetsReached(uint16_t firstTarget, uint8_t index)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint16_t firstTarget:
 *      First waypoint of TYPE_AIRCRAFT instance.
 *
 *  uint8_t index:
 *      Index of FlightData.
 *
 * @brief:
 *  Calculates new state for aircraft once all waypoints have been reached.
 *
 * @return:
 *  New state for aircraft once waypoints have been reached.
 *
 * @remarks:
 *
 * ****************************************************************************/

FL_STATE GameTargetsReached(uint16_t firstTarget, uint8_t index)
{
    FL_STATE retState = STATE_IDLE;
    uint8_t i;

    switch(FlightData.State[index])
    {
        case STATE_FINAL:
            FlightData.State[index] = STATE_LANDED;

            for (i = 0; i < GAME_MAX_RUNWAYS; i++)
            {
                if (GameUsedRwy[i] == firstTarget)
                {
                    GameUsedRwy[i] = 0;
                }
            }
        break;

        case STATE_TAXIING:
            if (FlightData.FlightDirection[index] == DEPARTURE)
            {
                FlightData.State[index] = STATE_HOLDING_RWY;
            }
            else if (FlightData.FlightDirection[index] == ARRIVAL)
            {
                FlightData.State[index] = STATE_UNBOARDING;
            }
        break;

        case STATE_TAKEOFF:
            FlightData.State[index] = STATE_CLIMBING;
        break;

        case STATE_ENTERING_RWY:
            FlightData.State[index] = STATE_READY_FOR_TAKEOFF;
        break;

        default:
        break;
    }

    return retState;
}

/* ****************************************************************************
 *
 * @name: uint16_t GameGetTileFromIsoPosition(TYPE_ISOMETRIC_POS* IsoPos)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_ISOMETRIC_POS* IsoPos:
 *      (x, y, z) position data.
 *
 * @brief:
 *  Calculates new state for aircraft once all waypoints have been reached.
 *
 * @return:
 *  Tile number to be used against levelBuffer.
 *
 * @remarks:
 *  GameLevelColumns is used to determine tile number.
 *
 * ****************************************************************************/

uint16_t GameGetTileFromIsoPosition(const TYPE_ISOMETRIC_POS* const IsoPos)
{
    uint16_t tile;

    if (IsoPos == NULL)
    {
        return 0;
    }

    if (    (IsoPos->x < 0) || (IsoPos->y < 0) )
    {
        return GAME_INVALID_TILE_SELECTION; // Invalid XYZ position
    }

    tile = IsoPos->x >> TILE_SIZE_BIT_SHIFT;
    tile += (IsoPos->y >> TILE_SIZE_BIT_SHIFT) * GameLevelColumns;

    /*Serial_printf("Returning tile %d from position {%d, %d, %d}\n",
            tile,
            IsoPos->x,
            IsoPos->y,
            IsoPos->z   );*/

    return tile;
}

/* ****************************************************************************
 *
 * @name: uint8_t GameGetLevelColumns(void)
 *
 * @author: Xavier Del Campo
 *
 * @return:
 *  GameLevelColumns. Used for other modules without declaring GameLevelColumns
 *  as a global variable.
 *
 * ****************************************************************************/

uint8_t GameGetLevelColumns(void)
{
    return GameLevelColumns;
}

/* ****************************************************************************
 *
 * @name: void GamePlayerAddWaypoint(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 * @brief:
 *  Wrapper for GamePlayerAddWaypoint_Ex().
 *
 * ****************************************************************************/

void GamePlayerAddWaypoint(TYPE_PLAYER* const ptrPlayer)
{
    GamePlayerAddWaypoint_Ex(ptrPlayer, ptrPlayer->SelectedTile);
}

/* ****************************************************************************
 *
 * @name: void GamePlayerAddWaypoint(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure.
 *
 *  uint16_t tile:
 *      Tile number from levelBuffer.
 *
 * @brief:
 *  It allows adding a tile number to ptrPlayer.
 *
 * @remark:
 *  To be used together with GamePathToTile().
 *
 * ****************************************************************************/

void GamePlayerAddWaypoint_Ex(TYPE_PLAYER* const ptrPlayer, uint16_t tile)
{
    // "_Ex" function allow selecting a certain tile, whereas the other one
    // is a particulare case of "_Ex" for tile = ptrPlayer->SelectedTIle.

    if (ptrPlayer->WaypointIdx >= PLAYER_MAX_WAYPOINTS)
    {
        Serial_printf("No available waypoints for this player!\n");
        return;
    }

    /*Serial_printf("Added tile %d to ptrPlayer->Waypoints[%d]\n",
            tile,
            ptrPlayer->WaypointIdx);*/

    ptrPlayer->Waypoints[ptrPlayer->WaypointIdx++] = tile;
}

/* **************************************************************************************
 *
 * @name: bool GameWaypointCheckExisting(TYPE_PLAYER* const ptrPlayer, uint16_t temp_tile)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure.
 *
 *  uint16_t tile:
 *      Tile number from levelBuffer.
 *
 * @brief:
 *  Checks if tile number temp_tile is already included on player's waypoint list.
 *
 * @return:
 *  True if waypoint is already included on waypoint list, false otherwise.
 *
 * **************************************************************************************/

bool GameWaypointCheckExisting(TYPE_PLAYER* const ptrPlayer, uint16_t temp_tile)
{
    if (SystemContains_u16(temp_tile, ptrPlayer->Waypoints, PLAYER_MAX_WAYPOINTS) == false)
    {
        /*for (i = 0; i < FlightData.nAircraft; i++)
        {
            if ( (ptrFlightData->State[i] != STATE_IDLE)
                            &&
                (AircraftMoving(i) == false)            )
            {
                if (temp_tile == AircraftGetTileFromFlightDataIndex(i))
                {
                    return false;   // Check pending!
                }
            }
        }*/

        GamePlayerAddWaypoint_Ex(ptrPlayer, temp_tile);

        return false;
    }

    // temp_tile is already included on ptrPlayer->Waypoints!
    return true;
}

/* ****************************************************************************************
 *
 * @name: bool GamePathToTile(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Given an input TYPE_PLAYER structure and a selected tile,
 *  it updates current Waypoints array with all tiles between two points.
 *  If one of these tiles do not belong to desired tiles (i.e.: grass,
 *  water, buildings...), then false is returned.
 *
 * @return:
 *  Returns false on invalid path or invalid tile number selected. True otherwise.
 *
 * ****************************************************************************************/

bool GamePathToTile(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    static const uint8_t AcceptedTiles[] =
    {
        TILE_ASPHALT_WITH_BORDERS,
        TILE_PARKING,
        TILE_RWY_MID,
        TILE_RWY_EXIT,
        TILE_RWY_EXIT_2,
        TILE_TAXIWAY_CORNER_GRASS,
        TILE_TAXIWAY_CORNER_GRASS_2,
        TILE_TAXIWAY_GRASS,
        TILE_TAXIWAY_INTERSECT_GRASS,
        TILE_TAXIWAY_4WAY_CROSSING,
        TILE_PARKING_2,
        TILE_RWY_HOLDING_POINT,
        TILE_RWY_HOLDING_POINT_2,
        TILE_TAXIWAY_CORNER_GRASS_3
    };

    uint8_t i;

    uint16_t x_diff;
    uint16_t y_diff;
    uint16_t temp_tile;

    const TYPE_ISOMETRIC_POS IsoPos = CameraGetIsoPos(ptrPlayer);

    ptrPlayer->SelectedTile = GameGetTileFromIsoPosition(&IsoPos);

    if (ptrPlayer->SelectedTile == GAME_INVALID_TILE_SELECTION)
    {
        return false;
    }

    for (i = (ptrPlayer->LastWaypointIdx + 1); i < PLAYER_MAX_WAYPOINTS; i++)
    {
        ptrPlayer->Waypoints[i] = 0;
    }

    ptrPlayer->WaypointIdx = ptrPlayer->LastWaypointIdx + 1;

    x_diff = abs((ptrPlayer->SelectedTile % GameLevelColumns) -
                 (ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx] % GameLevelColumns));

    y_diff = abs((ptrPlayer->SelectedTile / GameLevelColumns) -
                 (ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx] / GameLevelColumns));

    // At this point, we have to update current waypoints list.
    // ptrPlayer->Waypoints[ptrPlayer->WaypointIdx - 1] points to the last inserted point,
    // so now we have to determine how many points need to be created.

    temp_tile = ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx];

    if (x_diff >= y_diff)
    {
        while ( (x_diff--) > 0)
        {
            if ( (ptrPlayer->SelectedTile % GameLevelColumns) >
                (ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx] % GameLevelColumns)   )
            {
                temp_tile++;
            }
            else
            {
                temp_tile--;
            }

            if (GameWaypointCheckExisting(ptrPlayer, temp_tile))
            {
                return false;   // Tile is already included in the list of temporary tiles?
            }
        }

        while ( (y_diff--) > 0)
        {
            if ( (ptrPlayer->SelectedTile / GameLevelColumns) >
                (ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx] / GameLevelColumns)   )
            {
                temp_tile += GameLevelColumns;
            }
            else
            {
                temp_tile -= GameLevelColumns;
            }

            if (GameWaypointCheckExisting(ptrPlayer, temp_tile))
            {
                return false;   // Tile is already included in the list of temporary tiles?
            }
        }
    }
    else
    {
        while ( (y_diff--) > 0)
        {
            if ( (ptrPlayer->SelectedTile / GameLevelColumns) >
                (ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx] / GameLevelColumns)   )
            {
                temp_tile += GameLevelColumns;
            }
            else
            {
                temp_tile -= GameLevelColumns;
            }

            if (GameWaypointCheckExisting(ptrPlayer, temp_tile))
            {
                return false;   // Tile is already included in the list of temporary tiles?
            }
        }

        while ( (x_diff--) > 0)
        {
            if ( (ptrPlayer->SelectedTile % GameLevelColumns) >
                (ptrPlayer->Waypoints[ptrPlayer->LastWaypointIdx] % GameLevelColumns)   )
            {
                temp_tile++;
            }
            else
            {
                temp_tile--;
            }

            if (GameWaypointCheckExisting(ptrPlayer, temp_tile))
            {
                return false;   // Tile is already included in the list of temporary tiles?
            }
        }
    }

    // Now at this point, we have prepared our array.

    for (i = 0; i < PLAYER_MAX_WAYPOINTS; i++)
    {
        if (ptrPlayer->Waypoints[i] == 0)
        {
            // We have found empty waypoints. Exit loop
            break;
        }

        if (SystemContains_u8(  levelBuffer[ptrPlayer->Waypoints[i]],
                                AcceptedTiles,
                                sizeof (AcceptedTiles) ) == false)
        {
            // Now try again with mirrored tiles, just in case!
            static const uint8_t AcceptedMirroredTiles[] =
            {
                TILE_ASPHALT_WITH_BORDERS | TILE_MIRROR_FLAG,
                TILE_PARKING | TILE_MIRROR_FLAG,
                TILE_RWY_MID | TILE_MIRROR_FLAG,
                TILE_RWY_EXIT | TILE_MIRROR_FLAG,
                TILE_RWY_EXIT_2 | TILE_MIRROR_FLAG,
                TILE_TAXIWAY_CORNER_GRASS | TILE_MIRROR_FLAG,
                TILE_TAXIWAY_CORNER_GRASS_2 | TILE_MIRROR_FLAG,
                TILE_TAXIWAY_GRASS | TILE_MIRROR_FLAG,
                TILE_TAXIWAY_INTERSECT_GRASS | TILE_MIRROR_FLAG,
                TILE_TAXIWAY_4WAY_CROSSING | TILE_MIRROR_FLAG,
                TILE_PARKING_2 | TILE_MIRROR_FLAG,
                TILE_RWY_HOLDING_POINT | TILE_MIRROR_FLAG,
                TILE_RWY_HOLDING_POINT_2 | TILE_MIRROR_FLAG,
                TILE_TAXIWAY_CORNER_GRASS_3 | TILE_MIRROR_FLAG
            };

            if (SystemContains_u8(  levelBuffer[ptrPlayer->Waypoints[i]],
                                    AcceptedMirroredTiles,
                                    sizeof (AcceptedTiles) ) == false)
            {
                // Both cases have failed. Return from function.
                return false;
            }
        }
    }

    return true;
}

/* ****************************************************************************************
 *
 * @name: TYPE_ISOMETRIC_POS GameSelectAircraft(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 * @brief:
 *  Moves player camera position to selected aircraft.
 *
 * @return:
 *  Isometric position of selected aircraft.
 *
 * ****************************************************************************************/

static TYPE_ISOMETRIC_POS GameSelectAircraft(TYPE_PLAYER* const ptrPlayer)
{
    const uint8_t AircraftIdx = ptrPlayer->FlightDataSelectedAircraft;
    const TYPE_ISOMETRIC_POS IsoPos = AircraftGetIsoPos(AircraftIdx);

    CameraMoveToIsoPos(ptrPlayer, IsoPos);

    return IsoPos;
}

/* ********************************************************************************
 *
 * @name: void GameSelectAircraftWaypoint(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 * @brief:
 *  Moves player camera to selected aircraft and adds first waypoint.
 *
 * ********************************************************************************/

void GameSelectAircraftWaypoint(TYPE_PLAYER* const ptrPlayer)
{
    TYPE_ISOMETRIC_POS IsoPos = GameSelectAircraft(ptrPlayer);

    ptrPlayer->SelectedTile = GameGetTileFromIsoPosition(&IsoPos);

    GamePlayerAddWaypoint(ptrPlayer);
}

/* ********************************************************************************
 *
 * @name: bool GameTwoPlayersActive(void)
 *
 * @author: Xavier Del Campo
 *
 * @return:
 *  Returns if a second player is active. To be used with other modules without
 *  declaring twoPlayers as a global variable.
 *
 * ********************************************************************************/

bool GameTwoPlayersActive(void)
{
    return twoPlayers;
}

/* *****************************************************************
 *
 * @name: void GameDrawMouse(TYPE_PLAYER* const ptrPlayer)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 * @brief:
 *  Draws GameMouseSpr under determined player states.
 *
 * *****************************************************************/

static void GameDrawMouse(TYPE_PLAYER* const ptrPlayer)
{
    if ((ptrPlayer->SelectTaxiwayParking)
                        ||
        (ptrPlayer->SelectTaxiwayRunway)   )
    {
        GfxSortSprite(&GameMouseSpr);
    }
}

/* ********************************************************************************
 *
 * @name: FL_STATE GameGetFlightDataStateFromIdx(uint8_t FlightDataIdx)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  uint8_t FlightDataIdx:
 *      Index from FlightData.
 *
 * @return:
 *  Returns .State variable given offset from FlightData.
 *
 * ********************************************************************************/

FL_STATE GameGetFlightDataStateFromIdx(uint8_t FlightDataIdx)
{
    if (FlightDataIdx >= FlightData.nAircraft)
    {
        return STATE_IDLE; // Error: could cause buffer overrun
    }

    return FlightData.State[FlightDataIdx];
}

/* ********************************************************************************
 *
 * @name: uint32_t GameGetScore(void)
 *
 * @author: Xavier Del Campo
 *
 * @return:
 *  Returns game score to other modules.
 *
 * ********************************************************************************/

uint32_t GameGetScore(void)
{
    return GameScore;
}

/* *******************************************************************************************
 *
 * @name: void GameStateUnboarding(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Handler for StateUnboarding.
 *
 * *******************************************************************************************/

static void GameStateUnboarding(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    if (ptrPlayer->Unboarding)
    {
        if (ptrPlayer->PadKeySinglePress_Callback(PAD_CIRCLE))
        {
            ptrPlayer->Unboarding = false;
            ptrPlayer->UnboardingSequenceIdx = 0;   // Player will need to repeat sequence
                                                    // if he/she decides to leave without finishing
        }

        ptrPlayer->LockTarget = true;
        ptrPlayer->LockedAircraft = ptrPlayer->FlightDataSelectedAircraft;

        if (ptrPlayer->PadLastKeySinglePressed_Callback() == ptrPlayer->UnboardingSequence[ptrPlayer->UnboardingSequenceIdx])
        {
            if (++ptrPlayer->UnboardingSequenceIdx >= UNBOARDING_KEY_SEQUENCE_MEDIUM)
            {
                if (ptrFlightData->Passengers[ptrPlayer->FlightDataSelectedAircraft] > UNBOARDING_PASSENGERS_PER_SEQUENCE)
                {
                    // Player has entered correct sequence. Unboard UNBOARDING_PASSENGERS_PER_SEQUENCE passengers.

                    ptrFlightData->Passengers[ptrPlayer->FlightDataSelectedAircraft] -= UNBOARDING_PASSENGERS_PER_SEQUENCE;
                    GameScore += SCORE_REWARD_UNLOADING;

                    ptrPlayer->PassengersLeftSelectedAircraft = ptrFlightData->Passengers[ptrPlayer->FlightDataSelectedAircraft];

                    GameGenerateUnboardingSequence(ptrPlayer);
                }
                else
                {
                    // Flight has finished. Remove aircraft and set finished flag
                    ptrPlayer->Unboarding = false;
                    GameRemoveFlight(ptrPlayer->FlightDataSelectedAircraft, true);
                }

                ptrPlayer->UnboardingSequenceIdx = 0;
            }

            Serial_printf("ptrPlayer->UnboardingSequenceIdx = %d\n", ptrPlayer->UnboardingSequenceIdx);

            SfxPlaySound(&BeepSnd);
        }
        else if (ptrPlayer->PadLastKeySinglePressed_Callback() != 0)
        {
            ptrPlayer->UnboardingSequenceIdx = 0; // Player has committed a mistake while entering the sequence. Repeat it!
        }
    }
}

/* *******************************************************************************************
 *
 * @name: void GameStateUnboarding(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 * @brief:
 *  Modifies ptrPlayer->UnboardingSequence creating a random sequence of numbers
 *  using SystemRand().
 *
 * @todo:
 *  Maximum number of sequence keys should be adjusted according to difficulty.
 *
 * *******************************************************************************************/

static void GameGenerateUnboardingSequence(TYPE_PLAYER* const ptrPlayer)
{
    uint8_t i;
    unsigned short keyTable[] = { PAD_CROSS, PAD_SQUARE, PAD_TRIANGLE };

    memset(ptrPlayer->UnboardingSequence, 0, sizeof (ptrPlayer->UnboardingSequence) );

    ptrPlayer->UnboardingSequenceIdx = 0;

    Serial_printf("Key sequence generated: ");

    // Only medium level implemented. TODO: Implement other levels
    for (i = 0; i < UNBOARDING_KEY_SEQUENCE_MEDIUM; i++)
    {
        uint8_t randIdx = SystemRand(0, (sizeof (keyTable) / sizeof (keyTable[0])) - 1);

        ptrPlayer->UnboardingSequence[i] = keyTable[randIdx];

        Serial_printf("idx = %d, 0x%04X ", randIdx, ptrPlayer->UnboardingSequence[i]);
    }

    Serial_printf("\n");
}

/* *********************************************************************************************************************
 *
 * @name: void GameCreateTakeoffWaypoints(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData, uint8_t aircraftIdx)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 *  uint8_t aircraftIdx:
 *      Index from FlightData.
 *
 * @brief:
 *  Given input aircraft from FlightData, it automatically looks for selected runway and creates an array
 *  of waypoints to be then executed by corresponding TYPE_AIRCRAFT_DATA instance.
 *
 * *********************************************************************************************************************/

static void GameCreateTakeoffWaypoints(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData, uint8_t aircraftIdx)
{
    TYPE_AIRCRAFT_DATA* const ptrAircraft = AircraftFromFlightDataIndex(aircraftIdx);

    if (ptrAircraft != NULL)
    {
        // Look for aircraft direction by searching TILE_RWY_EXIT
        //uint16_t currentTile = AircraftGetTileFromFlightDataIndex(aircraftIdx);
        //uint8_t targetsIdx = 0;
        DIRECTION aircraftDir = AircraftGetDirection(ptrAircraft);
        int8_t rwyStep = 0;
        uint16_t currentTile = 0;
        uint16_t targets[AIRCRAFT_MAX_TARGETS] = {0};
        uint8_t i;

        switch(aircraftDir)
        {
            case DIR_EAST:
                rwyStep = 1;
            break;

            case DIR_WEST:
                rwyStep = -1;
            break;

            case DIR_NORTH:
                rwyStep = -GameLevelColumns;
            break;

            case DIR_SOUTH:
                rwyStep = GameLevelColumns;
            break;

            default:
            return;
        }

        DEBUG_PRINT_VAR(AircraftGetTileFromFlightDataIndex(aircraftIdx));

        for (currentTile = (AircraftGetTileFromFlightDataIndex(aircraftIdx) + rwyStep);
            ((levelBuffer[currentTile] & ~(TILE_MIRROR_FLAG)) != TILE_RWY_START_1)
                                &&
            ((levelBuffer[currentTile] & ~(TILE_MIRROR_FLAG)) != TILE_RWY_START_2);
            currentTile -= rwyStep  )
        {
            // Calculate new currentTile value until conditions are invalid.
        }

        for (i = 0; i < GAME_MAX_RUNWAYS; i++)
        {
            if (GameUsedRwy[i] == currentTile)
            {
                GameUsedRwy[i] = 0;
                break;
            }
        }

        for (   currentTile = (AircraftGetTileFromFlightDataIndex(aircraftIdx) + rwyStep);
                ((levelBuffer[currentTile] & ~(TILE_MIRROR_FLAG)) != TILE_RWY_EXIT)
                            &&
                ((levelBuffer[currentTile] & ~(TILE_MIRROR_FLAG)) != TILE_RWY_EXIT_2);
                currentTile += rwyStep  )
        {

        }

        targets[0] = currentTile;
        AircraftAddTargets(AircraftFromFlightDataIndex(aircraftIdx), targets);
    }
}

/* *******************************************************************************************
 *
 * @name: void GameGetRunwayEntryTile(uint8_t aircraftIdx, TYPE_RWY_ENTRY_DATA* ptrRwyEntry)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t aircraftIdx:
 *      Index from FlightData. Used to determine target tile.
 *
 *  TYPE_RWY_ENTRY_DATA* ptrRwyEntry:
 *      Instance to be filled with runway data.
 *
 * @brief:
 *  Fills a TYPE_RWY_ENTRY_DATA instance with information about runway.
 *
 * *******************************************************************************************/

static void GameGetRunwayEntryTile(uint8_t aircraftIdx, TYPE_RWY_ENTRY_DATA* ptrRwyEntry)
{
    // Look for aircraft direction by searching TILE_RWY_EXIT
    const uint16_t currentTile = AircraftGetTileFromFlightDataIndex(aircraftIdx);
    int16_t step = 0;
    uint16_t i;

    if ( (currentTile >= GameLevelColumns)
                        &&
        ( (currentTile + GameLevelColumns) < GameLevelSize) )
    {
        if (    ((levelBuffer[currentTile + 1] & ~(TILE_MIRROR_FLAG)) == TILE_RWY_EXIT)
                                ||
                ((levelBuffer[currentTile + 1] & ~(TILE_MIRROR_FLAG)) == TILE_RWY_EXIT_2)   )
        {
            ptrRwyEntry->Direction = DIR_EAST;
            ptrRwyEntry->rwyStep = GameLevelColumns;
            step = 1;
        }
        else if (   ((levelBuffer[currentTile - 1] & ~(TILE_MIRROR_FLAG) ) == TILE_RWY_EXIT)
                                    ||
                    ((levelBuffer[currentTile - 1] & ~(TILE_MIRROR_FLAG)) == TILE_RWY_EXIT_2)   )
        {
            ptrRwyEntry->Direction = DIR_WEST;
            ptrRwyEntry->rwyStep = GameLevelColumns;
            step = -1;
        }
        else if (   ((levelBuffer[currentTile + GameLevelColumns] & ~(TILE_MIRROR_FLAG)) == TILE_RWY_EXIT)
                                                ||
                    ((levelBuffer[currentTile + GameLevelColumns] & ~(TILE_MIRROR_FLAG)) == TILE_RWY_EXIT_2)    )
        {
            ptrRwyEntry->Direction = DIR_SOUTH;
            ptrRwyEntry->rwyStep = 1;
            step = GameLevelColumns;
        }
        else if (   ((levelBuffer[currentTile - GameLevelColumns] & ~(TILE_MIRROR_FLAG)) == TILE_RWY_EXIT)
                                                ||
                    ((levelBuffer[currentTile - GameLevelColumns] & ~(TILE_MIRROR_FLAG)) == TILE_RWY_EXIT_2)    )
        {
            ptrRwyEntry->Direction = DIR_NORTH;
            ptrRwyEntry->rwyStep = 1;
            step = -GameLevelColumns;
        }
        else
        {
            ptrRwyEntry->rwyEntryTile = 0;
            ptrRwyEntry->Direction = NO_DIRECTION;
            ptrRwyEntry->rwyStep = 0;
            return;
        }

        ptrRwyEntry->rwyEntryTile = currentTile + step;

        i = ptrRwyEntry->rwyEntryTile;

        while ( ((levelBuffer[i] & ~TILE_MIRROR_FLAG) != TILE_RWY_START_1)
                                &&
                ((levelBuffer[i] & ~TILE_MIRROR_FLAG) != TILE_RWY_START_2)
                                &&
                (i > ptrRwyEntry->rwyStep)
                                &&
                ((i - ptrRwyEntry->rwyStep) < GameLevelSize ) )
        {
            i -= ptrRwyEntry->rwyStep;
        }

        ptrRwyEntry->rwyHeader = i;
    }
    else
    {
        Serial_printf("GameGetRunwayEntryTile(): Invalid index for tile.\n");
    }
}

/* *******************************************************************************************
 *
 * @name: bool GameInsideLevelFromIsoPos(TYPE_ISOMETRIC_FIX16_POS* ptrIsoPos)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  TYPE_ISOMETRIC_FIX16_POS* ptrIsoPos:
 *      (x, y, z) coordinate data in an isometric system.
 *
 * @return:
 *  Returns true if a (x, y, z) coordinate is inside level coordinates. False otherwise.
 *
 * *******************************************************************************************/

bool GameInsideLevelFromIsoPos(TYPE_ISOMETRIC_FIX16_POS* ptrIsoPos)
{
    short x = (short)fix16_to_int(ptrIsoPos->x);
    short y = (short)fix16_to_int(ptrIsoPos->y);

    if (x < 0)
    {
        return false;
    }

    if (x > (GameLevelColumns << TILE_SIZE_BIT_SHIFT))
    {
        return false;
    }

    if (y < 0)
    {
        return false;
    }

    if (y > (GameLevelColumns << TILE_SIZE_BIT_SHIFT) )
    {
        return false;
    }

    return true;
}

/* *******************************************************************************************
 *
 * @name: void GameRemoveFlight(uint8_t idx, bool successful)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t idx:
 *      Index from FlightData.
 *
 *  bool successful:
 *      False if flight was lost on timeout, true otherwise.
 *
 * @brief:
 *  Actions to be performed when a flight ends, both successfully or not (lost flight).
 *
 * @remarks:
 *  GameScore is updated here depending on player actions.
 *
 * *******************************************************************************************/

void GameRemoveFlight(const uint8_t idx, const bool successful)
{
    uint8_t i;

    for (i = PLAYER_ONE; i < MAX_PLAYERS; i++)
    {
        TYPE_PLAYER* const ptrPlayer = &PlayerData[i];
        uint8_t j;

        if (ptrPlayer->Active == false)
        {
            continue;
        }

        if (idx >= FlightData.nAircraft)
        {
            Serial_printf("GameRemoveFlight: index %d exceeds max index %d!\n", idx, FlightData.nAircraft);
            return;
        }

        if ((FlightData.FlightDirection[idx] & ptrPlayer->FlightDirection) == 0)
        {
            continue;
        }

        for (j = 0; j < ptrPlayer->ActiveAircraft; j++)
        {
            if (ptrPlayer->ActiveAircraftList[j] == idx)
            {
                if (FlightData.State[idx] != STATE_IDLE)
                {
                    uint8_t k;

                    memset(ptrPlayer->UnboardingSequence, 0, GAME_MAX_SEQUENCE_KEYS);
                    ptrPlayer->UnboardingSequenceIdx = 0;

                    for (k = 0; k < GAME_MAX_RUNWAYS; k++)
                    {
                        const uint16_t* const targets = AircraftGetTargets(idx);
                        uint16_t rwyArray[GAME_MAX_RWY_LENGTH] = {0};

                        if (SystemContains_u16(GameUsedRwy[k], targets, AIRCRAFT_MAX_TARGETS))
                        {
                            GameUsedRwy[k] = 0;
                        }
                        else
                        {
                            // GameRwyArray is filled with runway tiles.
                            GameGetSelectedRunwayArray(GameUsedRwy[k], rwyArray, GAME_MAX_RWY_LENGTH * sizeof (uint16_t) );

                            if (SystemContains_u16(  AircraftGetTileFromFlightDataIndex(idx),
                                                    rwyArray,
                                                    sizeof (rwyArray) / sizeof (rwyArray[0]) ))
                            {
                                GameUsedRwy[k] = 0;
                            }
                        }
                    }

                    if (FlightData.State[idx] != STATE_APPROACH)
                    {
                        if (FlightData.State[idx] == STATE_UNBOARDING)
                        {
                            ptrPlayer->Unboarding = false;
                            ptrPlayer->LockTarget = false;
                            ptrPlayer->LockedAircraft = FLIGHT_DATA_INVALID_IDX;
                        }

                        if (AircraftRemove(idx) == false)
                        {
                            Serial_printf("Something went wrong when removing aircraft!\n");
                            return;
                        }
                    }
                    else
                    {
                        // STATE_APPROACH is the only state which is not linked to a TYPE_AIRCRAFT_DATA instance.
                    }

                    if (ptrPlayer->LockedAircraft == idx)
                    {
                        ptrPlayer->LockTarget = false;
                        ptrPlayer->LockedAircraft = FLIGHT_DATA_INVALID_IDX;
                    }

                    if (successful)
                    {
                        GameScore += SCORE_REWARD_FINISH_FLIGHT;

                        // Add punctuation
                        GameScore += FlightData.RemainingTime[idx] << 1;
                    }
                    else
                    {
                        GameScore = (GameScore < LOST_FLIGHT_PENALTY)? 0 : (GameScore - LOST_FLIGHT_PENALTY);
                    }

                    if (ptrPlayer->SelectedAircraft != 0)
                    {
                        if (ptrPlayer->SelectedAircraft >= j)
                        {
                            ptrPlayer->SelectedAircraft--;
                        }
                    }

                    FlightData.Passengers[idx] = 0;
                    FlightData.State[idx] = STATE_IDLE;
                    FlightData.Finished[idx] = true;

                    spawnMinTimeFlag = true;
                    TimerRestart(GameSpawnMinTime);

                    return;
                }
            }
        }

        // Usually called in PlayerHandler(), but now
        // force active aircraft list update.
        GameActiveAircraftList(ptrPlayer, &FlightData);
    }
}

/* *******************************************************************************************
 *
 * @name: void GameActiveAircraftList(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  TYPE_PLAYER* const ptrPlayer:
 *      Pointer to a player structure
 *
 *  TYPE_FLIGHT_DATA* const ptrFlightData:
 *      In the end, pointer to FlightData data table, which contains
 *      information about all available flights.
 *
 * @brief:
 *  Rebuilds flight data arrray for a specific player.
 *
 * *******************************************************************************************/

void GameActiveAircraftList(TYPE_PLAYER* const ptrPlayer, TYPE_FLIGHT_DATA* const ptrFlightData)
{
    uint8_t i;
    uint8_t j = 0;

    uint8_t currentFlightDataIdx;
    const uint8_t lastFlightDataIdx = ptrPlayer->ActiveAircraftList[ptrPlayer->SelectedAircraft];

    // Clear all pointers for aircraft data first.
    // Then, rebuild aircraft list for current player.
    memset(ptrPlayer->ActiveAircraftList, 0, GAME_MAX_AIRCRAFT);
    ptrPlayer->ActiveAircraft = 0;
    ptrPlayer->RemainingAircraft = 0;

    for (i = 0; i < FlightData.nAircraft; i++)
    {
        if ((ptrFlightData->State[i] != STATE_IDLE)
                            &&
            (ptrFlightData->FlightDirection[i] & ptrPlayer->FlightDirection) )
        {
            ptrPlayer->ActiveAircraftList[j++] = i;
            ptrPlayer->ActiveAircraft++;
        }
        else if (ptrFlightData->State[i] == STATE_IDLE)
        {
            ptrPlayer->RemainingAircraft++;
        }
    }

    currentFlightDataIdx = ptrPlayer->ActiveAircraftList[ptrPlayer->SelectedAircraft];

    if (aircraftCreated)
    {
        aircraftCreated = false;

        if (ptrPlayer->ActiveAircraft > 1)
        {
            if (currentFlightDataIdx != lastFlightDataIdx)
            {
                for (ptrPlayer->SelectedAircraft = 0; ptrPlayer->SelectedAircraft < FlightData.nAircraft; ptrPlayer->SelectedAircraft++)
                {
                    if (ptrPlayer->ActiveAircraftList[ptrPlayer->SelectedAircraft] == lastFlightDataIdx)
                    {
                        break;
                    }
                }
            }
        }
    }

    ptrPlayer->FlightDataSelectedAircraft = ptrPlayer->ActiveAircraftList[ptrPlayer->SelectedAircraft];
}

/* *******************************************************************************************
 *
 * @name: void GameRemainingAircraft(uint8_t i)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t i:
 *      Index from FlightData.
 *
 * @brief:
 *  Reportedly, it updates FlightData.nRemainingAircraft depending on game status.
 *
 * @remarks:
 *  This function is called nActiveAircraft times. See loop inside GameCalculations()
 *  for further reference.
 *
 * *******************************************************************************************/

static void GameRemainingAircraft(const uint8_t i)
{
    // Reset iterator when starting from first element.

    if (i == 0)
    {
        FlightData.nRemainingAircraft = FlightData.nAircraft;
    }

    if ((FlightData.State[i] != STATE_IDLE)
            ||
        FlightData.Finished[i])
    {
        FlightData.nRemainingAircraft--;
    }
}

/* *******************************************************************************************
 *
 * @name: void GameFinished(uint8_t i)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t i:
 *      Index from FlightData.
 *
 * @brief:
 *  Sets levelFinished if there are no more active aircraft.
 *
 * @remarks:
 *  This function is called nActiveAircraft times. See loop inside GameCalculations()
 *  for further reference.
 *
 * *******************************************************************************************/

static void GameFinished(const uint8_t i)
{
    if (FlightData.Finished[i] == false)
    {
        levelFinished = false;
    }
}

/* *******************************************************************************************
 *
 * @name: void GameMinimumSpawnTimeout(void)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t i:
 *      Index from FlightData.
 *
 * @brief:
 *  Callback automatically executed on GameSpawnMinTime expired. spawnMinTimeFlag is used
 *  to set a minimum time between flight ended and flight spawn.
 *
 * *******************************************************************************************/

void GameMinimumSpawnTimeout(void)
{
    spawnMinTimeFlag = false;
}

/* *******************************************************************************************
 *
 * @name: void GameAircraftCollision(uint8_t AircraftIdx)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t AircraftIdx:
 *      Index from FlightData.
 *
 * @brief:
 *  Sets GameAircraftCollisionFlag when two or more aircraft collide. This flag is then
 *  checked by Game().
 *
 * *******************************************************************************************/

void GameAircraftCollision(uint8_t AircraftIdx)
{
    GameAircraftCollisionFlag = true;
    GameAircraftCollisionIdx = AircraftIdx;
}

/* *******************************************************************************************
 *
 * @name: void GameAircraftCollision(uint8_t AircraftIdx)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t AircraftIdx:
 *      Index from FlightData.
 *
 * @brief:
 *  Event triggered by Aircraft when aircraft A is getting close to non-moving aircraft B
 *  and a security stop must be done in order to avoid collision.
 *
 * *******************************************************************************************/

void GameStopFlight(uint8_t AircraftIdx)
{
    FL_STATE* ptrState = &FlightData.State[AircraftIdx];

    if (*ptrState == STATE_TAXIING)
    {
        // Only allow auto stop under taxi
        *ptrState = STATE_AUTO_STOPPED;
    }
}

/* *******************************************************************************************
 *
 * @name: void GameAircraftCollision(uint8_t AircraftIdx)
 *
 * @author: Xavier Del Campo
 *
 * @param:
 *
 *  uint8_t AircraftIdx:
 *      Index from FlightData.
 *
 * @brief:
 *  Event triggered by Aircraft when aircraft A is no longer getting close to aircraft B, so
 *  that taxiing can be resumed.
 *
 * *******************************************************************************************/

void GameResumeFlightFromAutoStop(uint8_t AircraftIdx)
{
    FL_STATE* ptrState = &FlightData.State[AircraftIdx];

    if (*ptrState == STATE_AUTO_STOPPED)
    {
        // Only recovery to STATE_TAXIING is allowed.
        *ptrState = STATE_TAXIING;
    }
}