summary refs log tree commit diff stats
path: root/vendor/tileson.hpp
blob: f8545ed67140374872469ba70c31e2a79f7e9c82 (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
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
///
/// T I L E S O N   V E R S I O N   1 . 3 . 0
/// ------------------------------------------------
/// BSD 2-Clause License
///
/// Copyright (c) 2020, Robin Berg Pettersen
/// All rights reserved.
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice, this
///    list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
///    this list of conditions and the following disclaimer in the documentation
///    and/or other materials provided with the distribution.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
/// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
/// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
/// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
/// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef TILESON_TILESON_H
#define TILESON_TILESON_H


/*** Start of inlined file: json11.hpp ***/
/*** Start of inlined file: json11.cpp ***/

/*** Start of inlined file: json11.hpp ***/
/* Copyright (c) 2013 Dropbox, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#pragma once

#include <string>
#include <vector>
#include <map>
#include <memory>
#include <initializer_list>

#define JSON11_IS_DEFINED

#ifdef _MSC_VER
#if _MSC_VER <= 1800 // VS 2013
		#ifndef noexcept
			#define noexcept throw()
		#endif

		#ifndef snprintf
			#define snprintf _snprintf_s
		#endif
	#endif
#endif

namespace json11 {

	enum JsonParse {
		STANDARD, COMMENTS
	};

	class JsonValue;

	class Json final {
		public:
			// Types
			enum Type {
				NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT
			};

			// Array and object typedefs
			typedef std::vector<Json> array;
			typedef std::map<std::string, Json> object;

			// Constructors for the various types of JSON value.
			inline Json() noexcept;                // NUL
			inline Json(std::nullptr_t) noexcept;  // NUL
			inline Json(double value);             // NUMBER
			inline Json(int value);                // NUMBER
			inline Json(bool value);               // BOOL
			inline Json(const std::string &value); // STRING
			inline Json(std::string &&value);      // STRING
			inline Json(const char * value);       // STRING
			inline Json(const array &values);      // ARRAY
			inline Json(array &&values);           // ARRAY
			inline Json(const object &values);     // OBJECT
			inline Json(object &&values);          // OBJECT

			// Implicit constructor: anything with a to_json() function.
			template <class T, class = decltype(&T::to_json)>
			inline Json(const T & t) : Json(t.to_json()) {}

			// Implicit constructor: map-like objects (std::map, std::unordered_map, etc)
			template <class M, typename std::enable_if<
					std::is_constructible<std::string, decltype(std::declval<M>().begin()->first)>::value
					&& std::is_constructible<Json, decltype(std::declval<M>().begin()->second)>::value,
					int>::type = 0>
			inline Json(const M & m) : Json(object(m.begin(), m.end())) {}

			// Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc)
			template <class V, typename std::enable_if<
					std::is_constructible<Json, decltype(*std::declval<V>().begin())>::value,
					int>::type = 0>
			inline Json(const V & v) : Json(array(v.begin(), v.end())) {}

			// This prevents Json(some_pointer) from accidentally producing a bool. Use
			// Json(bool(some_pointer)) if that behavior is desired.
			Json(void *) = delete;

			// Accessors
			inline Type type() const;

			inline bool is_null()   const { return type() == NUL; }
			inline bool is_number() const { return type() == NUMBER; }
			inline bool is_bool()   const { return type() == BOOL; }
			inline bool is_string() const { return type() == STRING; }
			inline bool is_array()  const { return type() == ARRAY; }
			inline bool is_object() const { return type() == OBJECT; }

			// Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not
			// distinguish between integer and non-integer numbers - number_value() and int_value()
			// can both be applied to a NUMBER-typed object.
			inline double number_value() const;
			inline int int_value() const;

			// Return the enclosed value if this is a boolean, false otherwise.
			inline bool bool_value() const;
			// Return the enclosed string if this is a string, "" otherwise.
			inline const std::string &string_value() const;
			// Return the enclosed std::vector if this is an array, or an empty vector otherwise.
			inline const array &array_items() const;
			// Return the enclosed std::map if this is an object, or an empty map otherwise.
			inline const object &object_items() const;

			// Return a reference to arr[i] if this is an array, Json() otherwise.
			inline const Json & operator[](size_t i) const;
			// Return a reference to obj[key] if this is an object, Json() otherwise.
			inline const Json & operator[](const std::string &key) const;

			// Serialize.
			inline void dump(std::string &out) const;
			inline std::string dump() const {
				std::string out;
				dump(out);
				return out;
			}

			// Parse. If parse fails, return Json() and assign an error message to err.
			static inline Json parse(const std::string & in,
							  std::string & err,
							  JsonParse strategy = JsonParse::STANDARD);
			static inline Json parse(const char * in,
							  std::string & err,
							  JsonParse strategy = JsonParse::STANDARD) {
				if (in) {
					return parse(std::string(in), err, strategy);
				} else {
					err = "null input";
					return nullptr;
				}
			}
			// Parse multiple objects, concatenated or separated by whitespace
			static inline std::vector<Json> parse_multi(
					const std::string & in,
					std::string::size_type & parser_stop_pos,
					std::string & err,
					JsonParse strategy = JsonParse::STANDARD);

			static inline std::vector<Json> parse_multi(
					const std::string & in,
					std::string & err,
					JsonParse strategy = JsonParse::STANDARD) {
				std::string::size_type parser_stop_pos;
				return parse_multi(in, parser_stop_pos, err, strategy);
			}

			inline bool operator== (const Json &rhs) const;
			inline bool operator<  (const Json &rhs) const;
			inline bool operator!= (const Json &rhs) const { return !(*this == rhs); }
			inline bool operator<= (const Json &rhs) const { return !(rhs < *this); }
			inline bool operator>  (const Json &rhs) const { return  (rhs < *this); }
			inline bool operator>= (const Json &rhs) const { return !(*this < rhs); }

			/* has_shape(types, err)
			 *
			 * Return true if this is a JSON object and, for each item in types, has a field of
			 * the given type. If not, return false and set err to a descriptive message.
			 */
			typedef std::initializer_list<std::pair<std::string, Type>> shape;
			inline bool has_shape(const shape & types, std::string & err) const;

		private:
			std::shared_ptr<JsonValue> m_ptr;
	};

// Internal class hierarchy - JsonValue objects are not exposed to users of this API.
	class JsonValue {
		protected:
			friend class Json;
			friend class JsonInt;
			friend class JsonDouble;
			virtual Json::Type type() const = 0;
			virtual bool equals(const JsonValue * other) const = 0;
			virtual bool less(const JsonValue * other) const = 0;
			virtual void dump(std::string &out) const = 0;
			virtual double number_value() const;
			virtual int int_value() const;
			virtual bool bool_value() const;
			virtual const std::string &string_value() const;
			virtual const Json::array &array_items() const;
			virtual const Json &operator[](size_t i) const;
			virtual const Json::object &object_items() const;
			virtual const Json &operator[](const std::string &key) const;
			virtual ~JsonValue() {}
	};

} // namespace json11

/*** End of inlined file: json11.hpp ***/

#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <limits>

namespace json11 {

	static const int max_depth = 200;

	using std::string;
	using std::vector;
	using std::map;
	using std::make_shared;
	using std::initializer_list;
	using std::move;

/* Helper for representing null - just a do-nothing struct, plus comparison
 * operators so the helpers in JsonValue work. We can't use nullptr_t because
 * it may not be orderable.
 */
	struct NullStruct {
		bool operator==(NullStruct) const { return true; }
		bool operator<(NullStruct) const { return false; }
	};

/* * * * * * * * * * * * * * * * * * * *
 * Serialization
 */

	static void dump(NullStruct, string &out) {
		out += "null";
	}

	static void dump(double value, string &out) {
		if (std::isfinite(value)) {
			char buf[32];
			snprintf(buf, sizeof buf, "%.17g", value);
			out += buf;
		} else {
			out += "null";
		}
	}

	static void dump(int value, string &out) {
		char buf[32];
		snprintf(buf, sizeof buf, "%d", value);
		out += buf;
	}

	static void dump(bool value, string &out) {
		out += value ? "true" : "false";
	}

	static void dump(const string &value, string &out) {
		out += '"';
		for (size_t i = 0; i < value.length(); i++) {
			const char ch = value[i];
			if (ch == '\\') {
				out += "\\\\";
			} else if (ch == '"') {
				out += "\\\"";
			} else if (ch == '\b') {
				out += "\\b";
			} else if (ch == '\f') {
				out += "\\f";
			} else if (ch == '\n') {
				out += "\\n";
			} else if (ch == '\r') {
				out += "\\r";
			} else if (ch == '\t') {
				out += "\\t";
			} else if (static_cast<uint8_t>(ch) <= 0x1f) {
				char buf[8];
				snprintf(buf, sizeof buf, "\\u%04x", ch);
				out += buf;
			} else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
					   && static_cast<uint8_t>(value[i+2]) == 0xa8) {
				out += "\\u2028";
				i += 2;
			} else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
					   && static_cast<uint8_t>(value[i+2]) == 0xa9) {
				out += "\\u2029";
				i += 2;
			} else {
				out += ch;
			}
		}
		out += '"';
	}

	static void dump(const Json::array &values, string &out) {
		bool first = true;
		out += "[";
		for (const auto &value : values) {
			if (!first)
				out += ", ";
			value.dump(out);
			first = false;
		}
		out += "]";
	}

	static void dump(const Json::object &values, string &out) {
		bool first = true;
		out += "{";
		for (const auto &kv : values) {
			if (!first)
				out += ", ";
			dump(kv.first, out);
			out += ": ";
			kv.second.dump(out);
			first = false;
		}
		out += "}";
	}

	void Json::dump(string &out) const {
		m_ptr->dump(out);
	}

/* * * * * * * * * * * * * * * * * * * *
 * Value wrappers
 */

	template <Json::Type tag, typename T>
	class Value : public JsonValue {
		protected:

			// Constructors
			explicit Value(const T &value) : m_value(value) {}
			explicit Value(T &&value)      : m_value(move(value)) {}

			// Get type tag
			Json::Type type() const override {
				return tag;
			}

			// Comparisons
			bool equals(const JsonValue * other) const override {
				return m_value == static_cast<const Value<tag, T> *>(other)->m_value;
			}
			bool less(const JsonValue * other) const override {
				return m_value < static_cast<const Value<tag, T> *>(other)->m_value;
			}

			const T m_value;
			void dump(string &out) const override { json11::dump(m_value, out); }
	};

	class JsonDouble final : public Value<Json::NUMBER, double> {
			double number_value() const override { return m_value; }
			int int_value() const override { return static_cast<int>(m_value); }
			bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
			bool less(const JsonValue * other)   const override { return m_value <  other->number_value(); }
		public:
			explicit JsonDouble(double value) : Value(value) {}
	};

	class JsonInt final : public Value<Json::NUMBER, int> {
			double number_value() const override { return m_value; }
			int int_value() const override { return m_value; }
			bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
			bool less(const JsonValue * other)   const override { return m_value <  other->number_value(); }
		public:
			explicit JsonInt(int value) : Value(value) {}
	};

	class JsonBoolean final : public Value<Json::BOOL, bool> {
			bool bool_value() const override { return m_value; }
		public:
			explicit JsonBoolean(bool value) : Value(value) {}
	};

	class JsonString final : public Value<Json::STRING, string> {
			const string &string_value() const override { return m_value; }
		public:
			explicit JsonString(const string &value) : Value(value) {}
			explicit JsonString(string &&value)      : Value(move(value)) {}
	};

	class JsonArray final : public Value<Json::ARRAY, Json::array> {
			const Json::array &array_items() const override { return m_value; }
			const Json & operator[](size_t i) const override;
		public:
			explicit JsonArray(const Json::array &value) : Value(value) {}
			explicit JsonArray(Json::array &&value)      : Value(move(value)) {}
	};

	class JsonObject final : public Value<Json::OBJECT, Json::object> {
			const Json::object &object_items() const override { return m_value; }
			const Json & operator[](const string &key) const override;
		public:
			explicit JsonObject(const Json::object &value) : Value(value) {}
			explicit JsonObject(Json::object &&value)      : Value(move(value)) {}
	};

	class JsonNull final : public Value<Json::NUL, NullStruct> {
		public:
			JsonNull() : Value({}) {}
	};

/* * * * * * * * * * * * * * * * * * * *
 * Static globals - static-init-safe
 */
	struct Statics {
		const std::shared_ptr<JsonValue> null = make_shared<JsonNull>();
		const std::shared_ptr<JsonValue> t = make_shared<JsonBoolean>(true);
		const std::shared_ptr<JsonValue> f = make_shared<JsonBoolean>(false);
		const string empty_string;
		const vector<Json> empty_vector;
		const map<string, Json> empty_map;
		Statics() {}
	};

	static const Statics & statics() {
		static const Statics s {};
		return s;
	}

	static const Json & static_null() {
		// This has to be separate, not in Statics, because Json() accesses statics().null.
		static const Json json_null;
		return json_null;
	}

/* * * * * * * * * * * * * * * * * * * *
 * Constructors
 */

	Json::Json() noexcept                  : m_ptr(statics().null) {}
	Json::Json(std::nullptr_t) noexcept    : m_ptr(statics().null) {}
	Json::Json(double value)               : m_ptr(make_shared<JsonDouble>(value)) {}
	Json::Json(int value)                  : m_ptr(make_shared<JsonInt>(value)) {}
	Json::Json(bool value)                 : m_ptr(value ? statics().t : statics().f) {}
	Json::Json(const string &value)        : m_ptr(make_shared<JsonString>(value)) {}
	Json::Json(string &&value)             : m_ptr(make_shared<JsonString>(move(value))) {}
	Json::Json(const char * value)         : m_ptr(make_shared<JsonString>(value)) {}
	Json::Json(const Json::array &values)  : m_ptr(make_shared<JsonArray>(values)) {}
	Json::Json(Json::array &&values)       : m_ptr(make_shared<JsonArray>(move(values))) {}
	Json::Json(const Json::object &values) : m_ptr(make_shared<JsonObject>(values)) {}
	Json::Json(Json::object &&values)      : m_ptr(make_shared<JsonObject>(move(values))) {}

/* * * * * * * * * * * * * * * * * * * *
 * Accessors
 */

	inline Json::Type Json::type()                           const { return m_ptr->type();         }
	inline double Json::number_value()                       const { return m_ptr->number_value(); }
	inline int Json::int_value()                             const { return m_ptr->int_value();    }
	inline bool Json::bool_value()                           const { return m_ptr->bool_value();   }
	inline const string & Json::string_value()               const { return m_ptr->string_value(); }
	inline const vector<Json> & Json::array_items()          const { return m_ptr->array_items();  }
	inline const map<string, Json> & Json::object_items()    const { return m_ptr->object_items(); }
	inline const Json & Json::operator[] (size_t i)          const { return (*m_ptr)[i];           }
	inline const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key];         }

	inline double                    JsonValue::number_value()              const { return 0; }
	inline int                       JsonValue::int_value()                 const { return 0; }
	inline bool                      JsonValue::bool_value()                const { return false; }
	inline const string &            JsonValue::string_value()              const { return statics().empty_string; }
	inline const vector<Json> &      JsonValue::array_items()               const { return statics().empty_vector; }
	inline const map<string, Json> & JsonValue::object_items()              const { return statics().empty_map; }
	inline const Json &              JsonValue::operator[] (size_t)         const { return static_null(); }
	inline const Json &              JsonValue::operator[] (const string &) const { return static_null(); }

	inline const Json & JsonObject::operator[] (const string &key) const {
		auto iter = m_value.find(key);
		return (iter == m_value.end()) ? static_null() : iter->second;
	}
	inline const Json & JsonArray::operator[] (size_t i) const {
		if (i >= m_value.size()) return static_null();
		else return m_value[i];
	}

/* * * * * * * * * * * * * * * * * * * *
 * Comparison
 */

	bool Json::operator== (const Json &other) const {
		if (m_ptr == other.m_ptr)
			return true;
		if (m_ptr->type() != other.m_ptr->type())
			return false;

		return m_ptr->equals(other.m_ptr.get());
	}

	bool Json::operator< (const Json &other) const {
		if (m_ptr == other.m_ptr)
			return false;
		if (m_ptr->type() != other.m_ptr->type())
			return m_ptr->type() < other.m_ptr->type();

		return m_ptr->less(other.m_ptr.get());
	}

/* * * * * * * * * * * * * * * * * * * *
 * Parsing
 */

/* esc(c)
 *
 * Format char c suitable for printing in an error message.
 */
	static inline string esc(char c) {
		char buf[12];
		if (static_cast<uint8_t>(c) >= 0x20 && static_cast<uint8_t>(c) <= 0x7f) {
			snprintf(buf, sizeof buf, "'%c' (%d)", c, c);
		} else {
			snprintf(buf, sizeof buf, "(%d)", c);
		}
		return string(buf);
	}

	static inline bool in_range(long x, long lower, long upper) {
		return (x >= lower && x <= upper);
	}

	namespace {
/* JsonParser
 *
 * Object that tracks all state of an in-progress parse.
 */
		struct JsonParser final {

			/* State
			 */
			const string &str;
			size_t i;
			string &err;
			bool failed;
			const JsonParse strategy;

			/* fail(msg, err_ret = Json())
			 *
			 * Mark this parse as failed.
			 */
			Json fail(string &&msg) {
				return fail(move(msg), Json());
			}

			template <typename T>
			T fail(string &&msg, const T err_ret) {
				if (!failed)
					err = std::move(msg);
				failed = true;
				return err_ret;
			}

			/* consume_whitespace()
			 *
			 * Advance until the current character is non-whitespace.
			 */
			void consume_whitespace() {
				while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t')
					i++;
			}

			/* consume_comment()
			 *
			 * Advance comments (c-style inline and multiline).
			 */
			bool consume_comment() {
				bool comment_found = false;
				if (str[i] == '/') {
					i++;
					if (i == str.size())
						return fail("unexpected end of input after start of comment", false);
					if (str[i] == '/') { // inline comment
						i++;
						// advance until next line, or end of input
						while (i < str.size() && str[i] != '\n') {
							i++;
						}
						comment_found = true;
					}
					else if (str[i] == '*') { // multiline comment
						i++;
						if (i > str.size()-2)
							return fail("unexpected end of input inside multi-line comment", false);
						// advance until closing tokens
						while (!(str[i] == '*' && str[i+1] == '/')) {
							i++;
							if (i > str.size()-2)
								return fail(
										"unexpected end of input inside multi-line comment", false);
						}
						i += 2;
						comment_found = true;
					}
					else
						return fail("malformed comment", false);
				}
				return comment_found;
			}

			/* consume_garbage()
			 *
			 * Advance until the current character is non-whitespace and non-comment.
			 */
			void consume_garbage() {
				consume_whitespace();
				if(strategy == JsonParse::COMMENTS) {
					bool comment_found = false;
					do {
						comment_found = consume_comment();
						if (failed) return;
						consume_whitespace();
					}
					while(comment_found);
				}
			}

			/* get_next_token()
			 *
			 * Return the next non-whitespace character. If the end of the input is reached,
			 * flag an error and return 0.
			 */
			char get_next_token() {
				consume_garbage();
				if (failed) return static_cast<char>(0);
				if (i == str.size())
					return fail("unexpected end of input", static_cast<char>(0));

				return str[i++];
			}

			/* encode_utf8(pt, out)
			 *
			 * Encode pt as UTF-8 and add it to out.
			 */
			void encode_utf8(long pt, string & out) {
				if (pt < 0)
					return;

				if (pt < 0x80) {
					out += static_cast<char>(pt);
				} else if (pt < 0x800) {
					out += static_cast<char>((pt >> 6) | 0xC0);
					out += static_cast<char>((pt & 0x3F) | 0x80);
				} else if (pt < 0x10000) {
					out += static_cast<char>((pt >> 12) | 0xE0);
					out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
					out += static_cast<char>((pt & 0x3F) | 0x80);
				} else {
					out += static_cast<char>((pt >> 18) | 0xF0);
					out += static_cast<char>(((pt >> 12) & 0x3F) | 0x80);
					out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
					out += static_cast<char>((pt & 0x3F) | 0x80);
				}
			}

			/* parse_string()
			 *
			 * Parse a string, starting at the current position.
			 */
			string parse_string() {
				string out;
				long last_escaped_codepoint = -1;
				while (true) {
					if (i == str.size())
						return fail("unexpected end of input in string", "");

					char ch = str[i++];

					if (ch == '"') {
						encode_utf8(last_escaped_codepoint, out);
						return out;
					}

					if (in_range(ch, 0, 0x1f))
						return fail("unescaped " + esc(ch) + " in string", "");

					// The usual case: non-escaped characters
					if (ch != '\\') {
						encode_utf8(last_escaped_codepoint, out);
						last_escaped_codepoint = -1;
						out += ch;
						continue;
					}

					// Handle escapes
					if (i == str.size())
						return fail("unexpected end of input in string", "");

					ch = str[i++];

					if (ch == 'u') {
						// Extract 4-byte escape sequence
						string esc = str.substr(i, 4);
						// Explicitly check length of the substring. The following loop
						// relies on std::string returning the terminating NUL when
						// accessing str[length]. Checking here reduces brittleness.
						if (esc.length() < 4) {
							return fail("bad \\u escape: " + esc, "");
						}
						for (size_t j = 0; j < 4; j++) {
							if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F')
								&& !in_range(esc[j], '0', '9'))
								return fail("bad \\u escape: " + esc, "");
						}

						long codepoint = strtol(esc.data(), nullptr, 16);

						// JSON specifies that characters outside the BMP shall be encoded as a pair
						// of 4-hex-digit \u escapes encoding their surrogate pair components. Check
						// whether we're in the middle of such a beast: the previous codepoint was an
						// escaped lead (high) surrogate, and this is a trail (low) surrogate.
						if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF)
							&& in_range(codepoint, 0xDC00, 0xDFFF)) {
							// Reassemble the two surrogate pairs into one astral-plane character, per
							// the UTF-16 algorithm.
							encode_utf8((((last_escaped_codepoint - 0xD800) << 10)
										 | (codepoint - 0xDC00)) + 0x10000, out);
							last_escaped_codepoint = -1;
						} else {
							encode_utf8(last_escaped_codepoint, out);
							last_escaped_codepoint = codepoint;
						}

						i += 4;
						continue;
					}

					encode_utf8(last_escaped_codepoint, out);
					last_escaped_codepoint = -1;

					if (ch == 'b') {
						out += '\b';
					} else if (ch == 'f') {
						out += '\f';
					} else if (ch == 'n') {
						out += '\n';
					} else if (ch == 'r') {
						out += '\r';
					} else if (ch == 't') {
						out += '\t';
					} else if (ch == '"' || ch == '\\' || ch == '/') {
						out += ch;
					} else {
						return fail("invalid escape character " + esc(ch), "");
					}
				}
			}

			/* parse_number()
			 *
			 * Parse a double.
			 */
			Json parse_number() {
				size_t start_pos = i;

				if (str[i] == '-')
					i++;

				// Integer part
				if (str[i] == '0') {
					i++;
					if (in_range(str[i], '0', '9'))
						return fail("leading 0s not permitted in numbers");
				} else if (in_range(str[i], '1', '9')) {
					i++;
					while (in_range(str[i], '0', '9'))
						i++;
				} else {
					return fail("invalid " + esc(str[i]) + " in number");
				}

				if (str[i] != '.' && str[i] != 'e' && str[i] != 'E'
					&& (i - start_pos) <= static_cast<size_t>(std::numeric_limits<int>::digits10)) {
					return std::atoi(str.c_str() + start_pos);
				}

				// Decimal part
				if (str[i] == '.') {
					i++;
					if (!in_range(str[i], '0', '9'))
						return fail("at least one digit required in fractional part");

					while (in_range(str[i], '0', '9'))
						i++;
				}

				// Exponent part
				if (str[i] == 'e' || str[i] == 'E') {
					i++;

					if (str[i] == '+' || str[i] == '-')
						i++;

					if (!in_range(str[i], '0', '9'))
						return fail("at least one digit required in exponent");

					while (in_range(str[i], '0', '9'))
						i++;
				}

				return std::strtod(str.c_str() + start_pos, nullptr);
			}

			/* expect(str, res)
			 *
			 * Expect that 'str' starts at the character that was just read. If it does, advance
			 * the input and return res. If not, flag an error.
			 */
			Json expect(const string &expected, Json res) {
				assert(i != 0);
				i--;
				if (str.compare(i, expected.length(), expected) == 0) {
					i += expected.length();
					return res;
				} else {
					return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length()));
				}
			}

			/* parse_json()
			 *
			 * Parse a JSON object.
			 */
			Json parse_json(int depth) {
				if (depth > max_depth) {
					return fail("exceeded maximum nesting depth");
				}

				char ch = get_next_token();
				if (failed)
					return Json();

				if (ch == '-' || (ch >= '0' && ch <= '9')) {
					i--;
					return parse_number();
				}

				if (ch == 't')
					return expect("true", true);

				if (ch == 'f')
					return expect("false", false);

				if (ch == 'n')
					return expect("null", Json());

				if (ch == '"')
					return parse_string();

				if (ch == '{') {
					map<string, Json> data;
					ch = get_next_token();
					if (ch == '}')
						return data;

					while (1) {
						if (ch != '"')
							return fail("expected '\"' in object, got " + esc(ch));

						string key = parse_string();
						if (failed)
							return Json();

						ch = get_next_token();
						if (ch != ':')
							return fail("expected ':' in object, got " + esc(ch));

						data[std::move(key)] = parse_json(depth + 1);
						if (failed)
							return Json();

						ch = get_next_token();
						if (ch == '}')
							break;
						if (ch != ',')
							return fail("expected ',' in object, got " + esc(ch));

						ch = get_next_token();
					}
					return data;
				}

				if (ch == '[') {
					vector<Json> data;
					ch = get_next_token();
					if (ch == ']')
						return data;

					while (1) {
						i--;
						data.push_back(parse_json(depth + 1));
						if (failed)
							return Json();

						ch = get_next_token();
						if (ch == ']')
							break;
						if (ch != ',')
							return fail("expected ',' in list, got " + esc(ch));

						ch = get_next_token();
						(void)ch;
					}
					return data;
				}

				return fail("expected value, got " + esc(ch));
			}
		};
	}//namespace {

	Json Json::parse(const string &in, string &err, JsonParse strategy) {
		JsonParser parser { in, 0, err, false, strategy };
		Json result = parser.parse_json(0);

		// Check for any trailing garbage
		parser.consume_garbage();
		if (parser.failed)
			return Json();
		if (parser.i != in.size() &&
			((parser.i + 1) != in.size() && in[parser.i] != 0)) //RBP: If there is only 1 character diff, it is probably just a terminating zero from a memory read.
		{
			return parser.fail("unexpected trailing " + esc(in[parser.i]));
		}
		return result;
	}

// Documented in json11.hpp
	vector<Json> Json::parse_multi(const string &in,
								   std::string::size_type &parser_stop_pos,
								   string &err,
								   JsonParse strategy) {
		JsonParser parser { in, 0, err, false, strategy };
		parser_stop_pos = 0;
		vector<Json> json_vec;
		while (parser.i != in.size() && !parser.failed) {
			json_vec.push_back(parser.parse_json(0));
			if (parser.failed)
				break;

			// Check for another object
			parser.consume_garbage();
			if (parser.failed)
				break;
			parser_stop_pos = parser.i;
		}
		return json_vec;
	}

/* * * * * * * * * * * * * * * * * * * *
 * Shape-checking
 */

	bool Json::has_shape(const shape & types, string & err) const {
		if (!is_object()) {
			err = "expected JSON object, got " + dump();
			return false;
		}

		const auto& obj_items = object_items();
		for (auto & item : types) {
			const auto it = obj_items.find(item.first);
			if (it == obj_items.cend() || it->second.type() != item.second) {
				err = "bad type for " + item.first + " in " + dump();
				return false;
			}
		}

		return true;
	}

} // namespace json11

/*** End of inlined file: json11.cpp ***/

/*** End of inlined file: json11.hpp ***/


/*** Start of inlined file: tileson_parser.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_TILESON_PARSER_HPP
#define TILESON_TILESON_PARSER_HPP

//RBP: FS-namespace is defined in tileson_parser now!
#if _MSC_VER && !__INTEL_COMPILER
	#include <filesystem>
	namespace fs = std::filesystem;
#elif __MINGW64__
	#if __MINGW64_VERSION_MAJOR > 6
		#include <filesystem>
		namespace fs = std::filesystem;
	#else
		#include <experimental/filesystem>
		namespace fs = std::experimental::filesystem;
	#endif
#elif __clang__
	#if __clang_major__ < 8
		#include <experimental/filesystem>
		namespace fs = std::experimental::filesystem;
	#else
		#include <filesystem>
		namespace fs = std::filesystem;
	#endif
#else //Linux
	#if __GNUC__ < 8 //GCC major version less than 8
		#include <experimental/filesystem>
		namespace fs = std::experimental::filesystem;
	#else
		#include <filesystem>
		namespace fs = std::filesystem;
	#endif
#endif

#include <fstream>
#include <sstream>
#include <memory>


/*** Start of inlined file: Tools.hpp ***/
//
// Created by robin on 31.07.2020.
//

#ifndef TILESON_TOOLS_HPP
#define TILESON_TOOLS_HPP

#include <cstdint>
#include <vector>
#include <string_view>
namespace tson
{
	class Tools
	{

		public:
			Tools() = delete;
			~Tools() = delete;
			inline static std::vector<uint8_t> Base64DecodedStringToBytes(std::string_view str);
			inline static std::vector<uint32_t> BytesToUnsignedInts(const std::vector<uint8_t> &bytes);
			//inline static std::vector<int> BytesToInts(const std::vector<uint8_t> &bytes);
	};

	/*!
	 * When you have decoded a Base64 string, you'll get a string representing bytes. This function turns them into actual bytes.
	 * @param str
	 * @return
	 */
	std::vector<uint8_t> Tools::Base64DecodedStringToBytes(std::string_view str)
	{
		std::vector<uint8_t> bytes;
		for(size_t i = 0; i < str.size(); ++i)
		{
			uint8_t u8 = static_cast<uint8_t>(str[i]);
			bytes.push_back(u8);
		}
		return bytes;
	}

	/*!
	 * Converts bytes into unsigned int values. The bytes are converted in the Little Endian byte order to fit Tiled's specs.
	 * @param bytes A vector of bytes.
	 * @return Bytes converted to unsigned ints
	 */
	std::vector<uint32_t> Tools::BytesToUnsignedInts(const std::vector<uint8_t> &bytes)
	{
		std::vector<uint32_t> uints;
		std::vector<uint8_t> toConvert;
		//uint32_t size8 = (compressed[55] << 24) | (compressed[56] << 16) | (compressed[57] << 8) | compressed[58]; //Should be 66000

		for(size_t i = 0; i < bytes.size(); ++i)
		{
			toConvert.push_back(bytes[i]);
			if(toConvert.size() == 4)
			{
				uint32_t u32 = (toConvert[3] << 24) | (toConvert[2] << 16) | (toConvert[1] << 8) | toConvert[0];
				uints.push_back(u32);
				toConvert.clear();
			}
		}

		return uints;
	}

	/*!
	 * While the Tiled specification uses unsigned ints for their tiles, Tileson uses regular ints.
	 * This may be changed in the future, but should in reality never really become an issue.
	 *
	 * Update 2020-11-09: This will cause problems when tiles has flip flags!
	 *
	 * int differences:
	 * int max:  2147483647
	 * uint max: 4294967295
	 *
	 * @param bytes A vector of bytes.
	 * @return Bytes converted to ints
	 */
	/*std::vector<int> Tools::BytesToInts(const std::vector<uint8_t> &bytes)
	{
		std::vector<int> ints;
		std::vector<uint8_t> toConvert;
		//uint32_t size8 = (compressed[55] << 24) | (compressed[56] << 16) | (compressed[57] << 8) | compressed[58]; //Should be 66000

		for(size_t i = 0; i < bytes.size(); ++i)
		{
			toConvert.push_back(bytes[i]);
			if(toConvert.size() == 4)
			{
				uint32_t u32 = (toConvert[3] << 24) | (toConvert[2] << 16) | (toConvert[1] << 8) | toConvert[0];
				ints.push_back(u32);
				toConvert.clear();
			}
		}

		return ints;
	}*/
}

#endif //TILESON_TOOLS_HPP

/*** End of inlined file: Tools.hpp ***/


/*** Start of inlined file: Base64Decompressor.hpp ***/
//
// Created by robin on 29.07.2020.
// The Base64 decoding logic is heavily based on: https://github.com/ReneNyffenegger/cpp-base64
//

#ifndef TILESON_BASE64DECOMPRESSOR_HPP
#define TILESON_BASE64DECOMPRESSOR_HPP


/*** Start of inlined file: IDecompressor.hpp ***/
//
// Created by robin on 29.07.2020.
//

#ifndef TILESON_IDECOMPRESSOR_HPP
#define TILESON_IDECOMPRESSOR_HPP

#include <string_view>

namespace tson
{
	template <class TIn, class TOut>
	class IDecompressor
	{
		public:
			/*!
			 * If the name matches with 'compression' or 'encoding' the decompress() function will
			 * be called automatically for the actual Layer. Encoding-related matching is handled first!
			 *
			 * Known values:
			 *
			 * compression: zlib, gzip, zstd (since Tiled 1.3) or empty (default) (tilelayer only).
			 * encoding: csv (default) or base64 (tilelayer only).
			 *
			 * @return
			 */
			[[nodiscard]] virtual const std::string &name() const = 0;

			/*!
			 * Used primarily for Tiled related decompression.
			 * @param input Input data
			 * @return Decompressed data
			 */
			virtual TOut decompress(const TIn &input) = 0;

			/*!
			 * Used for whole file decompression. Not related to Tiled
			 * @param path
			 * @return
			 */
			virtual TOut decompressFile(const fs::path &path) = 0;

			/*!
			 * Used for whole file decompression. Not related to Tiled
			 * @param path
			 * @return
			 */
			virtual TOut decompress(const void *data, size_t size) = 0;
	};
}

#endif //TILESON_IDECOMPRESSOR_HPP

/*** End of inlined file: IDecompressor.hpp ***/

#include <string>

namespace tson
{
	class Base64Decompressor : public IDecompressor<std::string_view, std::string>
	{
		public:
			[[nodiscard]] inline const std::string &name() const override;

			inline std::string decompress(const std::string_view &s) override;

			inline std::string decompressFile(const fs::path &path) override;
			inline std::string decompress(const void *data, size_t size) override;

		private:
			inline unsigned int pos_of_char(const unsigned char chr);
			inline static const std::string NAME = "base64";
	};

	const std::string &Base64Decompressor::name() const
	{
		return NAME;
	}

	std::string Base64Decompressor::decompress(const std::string_view &s)
	{

		size_t length_of_string = s.length();
		if (!length_of_string) return std::string("");

		size_t in_len = length_of_string;
		size_t pos = 0;

		//
		// The approximate length (bytes) of the decoded string might be one ore
		// two bytes smaller, depending on the amount of trailing equal signs
		// in the encoded string. This approximation is needed to reserve
		// enough space in the string to be returned.
		//
		size_t approx_length_of_decoded_string = length_of_string / 4 * 3;
		std::string ret;
		ret.reserve(approx_length_of_decoded_string);

		while (pos < in_len) {

			unsigned int pos_of_char_1 = pos_of_char(s[pos+1] );

			ret.push_back(static_cast<std::string::value_type>( ( (pos_of_char(s[pos+0]) ) << 2 ) + ( (pos_of_char_1 & 0x30 ) >> 4)));

			if (s[pos+2] != '=' && s[pos+2] != '.') { // accept URL-safe base 64 strings, too, so check for '.' also.

				unsigned int pos_of_char_2 = pos_of_char(s[pos+2] );
				ret.push_back(static_cast<std::string::value_type>( (( pos_of_char_1 & 0x0f) << 4) + (( pos_of_char_2 & 0x3c) >> 2)));

				if (s[pos+3] != '=' && s[pos+3] != '.') {
					ret.push_back(static_cast<std::string::value_type>( ( (pos_of_char_2 & 0x03 ) << 6 ) + pos_of_char(s[pos+3])   ));
				}
			}

			pos += 4;
		}

		return ret;
	}

	unsigned int Base64Decompressor::pos_of_char(const unsigned char chr)
	{
		//
		// Return the position of chr within base64_encode()
		//

		if      (chr >= 'A' && chr <= 'Z') return chr - 'A';
		else if (chr >= 'a' && chr <= 'z') return chr - 'a' + ('Z' - 'A')               + 1;
		else if (chr >= '0' && chr <= '9') return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2;
		else if (chr == '+' || chr == '-') return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters (
		else if (chr == '/' || chr == '_') return 63; // Ditto for '/' and '_'

		throw "If input is correct, this line should never be reached.";
	}

	/*!
	 * UNUSED! Does nothing
	 * @param path
	 * @return
	 */
	std::string Base64Decompressor::decompressFile(const fs::path &path)
	{
		return std::string();
	}

	/*!
	 * UNUSED! Does nothing
	 * @param path
	 * @return
	 */
	std::string Base64Decompressor::decompress(const void *data, size_t size)
	{
		return std::string();
	}
}

#endif //TILESON_BASE64DECOMPRESSOR_HPP

/*** End of inlined file: Base64Decompressor.hpp ***/


/*** Start of inlined file: Lzma.hpp ***/
//
// Created by robin on 16.01.2021.
//
//#include "../../extras/pocketlzma.hpp"
#ifdef POCKETLZMA_POCKETLZMA_H

#ifndef TILESON_LZMA_HPP
#define TILESON_LZMA_HPP

namespace tson
{
	class Lzma : public IDecompressor<std::vector<uint8_t>, std::vector<uint8_t>>
	{
		public:
			inline const std::string &name() const override
			{
				return NAME;
			}

			inline std::vector<uint8_t> decompress(const std::vector<uint8_t> &input) override
			{
				std::vector<uint8_t> out;

				plz::PocketLzma p;
				plz::StatusCode status = p.decompress(input, out);

				if(status != plz::StatusCode::Ok)
					return std::vector<uint8_t>();

				return out;
			}

			inline std::vector<uint8_t> decompressFile(const fs::path &path) override
			{
				std::vector<uint8_t> in;
				std::vector<uint8_t> out;

				plz::PocketLzma p;
				plz::FileStatus fileStatus = plz::File::FromFile(path.u8string(), in);
				if(fileStatus.status() != plz::FileStatus::Code::Ok)
					return std::vector<uint8_t>();

				plz::StatusCode status = p.decompress(in, out);

				if(status != plz::StatusCode::Ok)
					return std::vector<uint8_t>();

				return out;
			}

			inline std::vector<uint8_t> decompress(const void *data, size_t size) override
			{
				std::vector<uint8_t> out;

				plz::PocketLzma p;
				plz::StatusCode status = p.decompress((uint8_t*) data, size, out);

				if(status != plz::StatusCode::Ok)
					return std::vector<uint8_t>();

				return out;
			}

		private:
			inline static const std::string NAME {"lzma"};
	};
}

#endif //TILESON_LZMA_HPP

#endif
/*** End of inlined file: Lzma.hpp ***/


/*** Start of inlined file: DecompressorContainer.hpp ***/
//
// Created by robin on 30.07.2020.
//

#ifndef TILESON_DECOMPRESSORCONTAINER_HPP
#define TILESON_DECOMPRESSORCONTAINER_HPP

#include <memory>
#include <vector>
#include <string_view>
#include <functional>
namespace tson
{
	class DecompressorContainer
	{
		public:
			inline DecompressorContainer() = default;
			template <typename T, typename... Args>
			inline void add(Args &&... args);
			inline void remove(std::string_view name);
			inline bool contains(std::string_view name) const;
			inline bool empty() const;
			inline size_t size() const;
			inline void clear();

			inline IDecompressor<std::string_view, std::string> *get(std::string_view name);
		private:
			//Key: name,
			std::vector<std::unique_ptr<IDecompressor<std::string_view, std::string>>> m_decompressors;
	};

	template<typename T, typename... Args>
	void DecompressorContainer::add(Args &&... args)
	{
		m_decompressors.emplace_back(new T(args...));
	}

	/*!
	 *
	 * @param name The name of the decompressor to check whether exists.
	 * @return Whether a decompressor with the given name exists or not.
	 */
	bool DecompressorContainer::contains(std::string_view name) const
	{
		auto iter = std::find_if(m_decompressors.begin(), m_decompressors.end(), [&](const auto &item)
		{
			return item->name() == name;
		});

		return iter != m_decompressors.end();
	}

	/*!
	 * Removed an element with the given name.
	 * @param name The name of the decompressor
	 */
	void DecompressorContainer::remove(std::string_view name)
	{
		auto iter = std::remove_if(m_decompressors.begin(), m_decompressors.end(), [&](const auto &item)
		{
			return item->name() == name;
		});
		m_decompressors.erase(iter);
	}

	size_t DecompressorContainer::size() const
	{
		return m_decompressors.size();
	}

	/*!
	 *
	 * @param name The name of the container
	 * @return An ICompressor pointer if it exists. nullptr otherwise.
	 */
	IDecompressor<std::string_view, std::string> *DecompressorContainer::get(std::string_view name)
	{
		auto iter = std::find_if(m_decompressors.begin(), m_decompressors.end(), [&](const auto &item)
		{
			return item->name() == name;
		});

		return (iter != m_decompressors.end()) ? iter->get() : nullptr;
	}

	/*!
	 * Check if container is empty
	 * @return Whether or not the container is empty
	 */
	bool DecompressorContainer::empty() const
	{
		return m_decompressors.empty();
	}

	/*!
	 * Clears all IDecompressor elements in the container
	 */
	void DecompressorContainer::clear()
	{
		m_decompressors.clear();
	}
}
#endif //TILESON_DECOMPRESSORCONTAINER_HPP

/*** End of inlined file: DecompressorContainer.hpp ***/


/*** Start of inlined file: MemoryStream.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_MEMORYSTREAM_HPP
#define TILESON_MEMORYSTREAM_HPP


/*** Start of inlined file: MemoryBuffer.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_MEMORYBUFFER_HPP
#define TILESON_MEMORYBUFFER_HPP

#include <iostream>

namespace tson
{
	class MemoryBuffer : public std::basic_streambuf<char> {
		public:
			MemoryBuffer(const uint8_t *p, size_t l) {
				setg((char*)p, (char*)p, (char*)p + l);
			}
	};
}

#endif //TILESON_MEMORYBUFFER_HPP

/*** End of inlined file: MemoryBuffer.hpp ***/

namespace tson
{
	class MemoryStream : public std::istream {
		public:
			MemoryStream(const uint8_t *p, size_t l) :
					std::istream(&m_buffer),
					m_buffer(p, l) {
				rdbuf(&m_buffer);
			}

		private:
			MemoryBuffer m_buffer;
	};
}

#endif //TILESON_MEMORYSTREAM_HPP

/*** End of inlined file: MemoryStream.hpp ***/


/*** Start of inlined file: Map.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_MAP_HPP
#define TILESON_MAP_HPP


/*** Start of inlined file: Color.hpp ***/
//
// Created by robin on 09.08.2019.
//

#ifndef TILESON_COLOR_HPP
#define TILESON_COLOR_HPP

#include <type_traits>
#include <cstdint>
#include <string>

namespace tson
{

	template<typename T>
	class Color
	{

		public:
			/*!
			 * Parses color from Tiled's own color format, which is #aarrggbb in hex format or optionally #rrggbb.
			 * @param color Color in "#rrggbbaa" hex format.
			 * @example "#ffaa07ff" and "#aa07ff". In cases where alpha is not a value, it is set to 255.
			*/
			inline explicit Color(const std::string &color)
			{
				parseHexString(color);
			}
			inline Color(T red, T green, T blue, T alpha);
			inline Color() { r = g = b = 0; a = 255; }

			inline bool operator==(const Color &rhs) const;
			inline bool operator==(const std::string &rhs) const;
			inline bool operator!=(const Color &rhs) const;

			inline Color<float> asFloat();
			inline Color<uint8_t> asInt();

			/*! Red */
			T r;
			/*! Green */
			T g;
			/*! Blue */
			T b;
			/*! Alpha */
			T a;

		private:
			void parseHexString(const std::string &color)
			{
				if constexpr (std::is_same<T, float>::value)
				{
					if (color.size() == 9)
					{
						a = (float) std::stoi(color.substr(1, 2), nullptr, 16) / 255;
						r = (float) std::stoi(color.substr(3, 2), nullptr, 16) / 255;
						g = (float) std::stoi(color.substr(5, 2), nullptr, 16) / 255;
						b = (float) std::stoi(color.substr(7, 2), nullptr, 16) / 255;
					}
					else if (color.size() == 7)
					{
						r = (float) std::stoi(color.substr(1, 2), nullptr, 16) / 255;
						g = (float) std::stoi(color.substr(3, 2), nullptr, 16) / 255;
						b = (float) std::stoi(color.substr(5, 2), nullptr, 16) / 255;
						a = 1.f;
					}
				}
				else
				{
					if (color.size() == 9)
					{
						a = std::stoi(color.substr(1, 2), nullptr, 16);
						r = std::stoi(color.substr(3, 2), nullptr, 16);
						g = std::stoi(color.substr(5, 2), nullptr, 16);
						b = std::stoi(color.substr(7, 2), nullptr, 16);
					}
					else if (color.size() == 7)
					{
						r = std::stoi(color.substr(1, 2), nullptr, 16);
						g = std::stoi(color.substr(3, 2), nullptr, 16);
						b = std::stoi(color.substr(5, 2), nullptr, 16);
						a = 255;
					}
				}
			}

	};

	typedef Color<uint8_t> Colori;
	typedef Color<float> Colorf;

	/*!
	 * Gets the Color as a float. Only useful if the template related to the current color is NOT float
	 * @tparam T The template type
	 * @return If the T type is float, the value will be returned as a copy of itself. Else: All values will be divided by 255
	 * before returning.
	 */
	template<typename T>
	tson::Colorf Color<T>::asFloat()
	{
		if constexpr (std::is_same<T, float>::value)
			*this;
		else
			return tson::Colorf((float) r / 255, (float) g / 255, (float) b / 255, (float) a / 255);
	}

	/*!
	 * Gets the Color as an 32-bit variable, where each channel is 8-bit.
	 * Only useful if the template related to the current color is NOT already 8-bit int
	 * @tparam T The template type
	 * @return If the T type is float, the value of each channel will be multiplied by 255. Else: The value will be returned as a copy of itself.
	 */
	template<typename T>
	tson::Colori Color<T>::asInt()
	{
		if constexpr (std::is_same<T, float>::value)
			return tson::Colori((float) r * 255, (float) g * 255, (float) b * 255, (float) a * 255);
		else
			*this;
	}

	/*!
	 * Create a new color in rgba (red, green, blue, alpha) format
	 * @tparam T the template type for each channel. Usually uint8_t (8-bit int) or float.
	 * @param red Red channel
	 * @param green Green channel
	 * @param blue Blue channel
	 * @param alpha Alpha channel
	 */
	template<typename T>
	Color<T>::Color(T red, T green, T blue, T alpha)
	{
		r = red;
		g = green;
		b = blue;
		a = alpha;
	}

	template<typename T>
	bool Color<T>::operator==(const std::string &rhs) const {
		Color other {rhs};
		return *this == other;
	}

	template<typename T>
	bool Color<T>::operator==(const Color &rhs) const
	{
		return r == rhs.r &&
			   g == rhs.g &&
			   b == rhs.b &&
			   a == rhs.a;
	}

	template<typename T>
	bool Color<T>::operator!=(const Color &rhs) const
	{
		return !(rhs == *this);
	}

}

#endif //TILESON_COLOR_HPP

/*** End of inlined file: Color.hpp ***/


/*** Start of inlined file: Vector2.hpp ***/
//
// Created by robin on 31.07.2019.
//

#ifndef TILESON_VECTOR2_HPP
#define TILESON_VECTOR2_HPP

namespace tson
{
	template<typename T>
	class Vector2
	{

		public:
			inline Vector2(T xPos, T yPos);
			inline Vector2() { x = y = 0; }

			inline bool operator==(const Vector2 &rhs) const;
			inline bool operator!=(const Vector2 &rhs) const;

			T x;
			T y;
	};

	/*!
	 *
	 * @tparam T template type
	 * @param xPos x-position
	 * @param yPos y-position
	 */
	template<typename T>
	Vector2<T>::Vector2(T xPos, T yPos)
	{
		x = xPos;
		y = yPos;
	}

	template<typename T>
	bool Vector2<T>::operator==(const Vector2 &rhs) const
	{
		return x == rhs.x &&
			   y == rhs.y;
	}

	template<typename T>
	bool Vector2<T>::operator!=(const Vector2 &rhs) const
	{
		return !(rhs == *this);
	}

	typedef Vector2<int> Vector2i;
	typedef Vector2<float> Vector2f;
}

#endif //TILESON_VECTOR2_HPP

/*** End of inlined file: Vector2.hpp ***/

//#include "../external/json.hpp"

/*** Start of inlined file: IJson.hpp ***/
//
// Created by robin on 06.01.2021.
//

#ifndef TILESON_IJSON_HPP
#define TILESON_IJSON_HPP

namespace tson
{
	class IJson
	{
		public:

			virtual IJson& operator[](std::string_view key) = 0;
			virtual IJson &at(std::string_view key) = 0;
			virtual IJson &at(size_t pos) = 0;
			/*!
			 * If current json object is an array, this will get all elements of it!
			 * @return An array
			 */
			[[nodiscard]] virtual std::vector<std::unique_ptr<IJson>> array() = 0;
			[[nodiscard]] virtual std::vector<std::unique_ptr<IJson>> &array(std::string_view key) = 0;
			/*!
			 * Get the size of an object. This will be equal to the number of
			 * variables an object contains.
			 * @return
			 */
			[[nodiscard]] virtual size_t size() const = 0;
			[[nodiscard]] virtual bool parse(const fs::path &path) = 0;
			[[nodiscard]] virtual bool parse(const void *data, size_t size) = 0;

			template <typename T>
			[[nodiscard]] T get(std::string_view key);
			template <typename T>
			[[nodiscard]] T get();
			[[nodiscard]] virtual size_t count(std::string_view key) const = 0;
			[[nodiscard]] virtual bool any(std::string_view key) const = 0;
			[[nodiscard]] virtual bool isArray() const = 0;
			[[nodiscard]] virtual bool isObject() const = 0;
			[[nodiscard]] virtual bool isNull() const = 0;

		protected:
			[[nodiscard]] virtual int32_t getInt32(std::string_view key) = 0;
			[[nodiscard]] virtual uint32_t getUInt32(std::string_view key) = 0;
			[[nodiscard]] virtual int64_t getInt64(std::string_view key) = 0;
			[[nodiscard]] virtual uint64_t getUInt64(std::string_view key) = 0;
			[[nodiscard]] virtual double getDouble(std::string_view key) = 0;
			[[nodiscard]] virtual float getFloat(std::string_view key) = 0;
			[[nodiscard]] virtual std::string getString(std::string_view key) = 0;
			[[nodiscard]] virtual bool getBool(std::string_view key) = 0;

			[[nodiscard]] virtual int32_t getInt32() = 0;
			[[nodiscard]] virtual uint32_t getUInt32() = 0;
			[[nodiscard]] virtual int64_t getInt64() = 0;
			[[nodiscard]] virtual uint64_t getUInt64() = 0;
			[[nodiscard]] virtual double getDouble() = 0;
			[[nodiscard]] virtual float getFloat() = 0;
			[[nodiscard]] virtual std::string getString() = 0;
			[[nodiscard]] virtual bool getBool() = 0;
	};

	template<typename T>
	T IJson::get(std::string_view key)
	{
		if constexpr (std::is_same<T, double>::value)
			return getDouble(key);
		if constexpr (std::is_same<T, float>::value)
			return getFloat(key);
		else if constexpr (std::is_same<T, int32_t>::value)
			return getInt32(key);
		else if constexpr (std::is_same<T, uint32_t>::value)
			return getUInt32(key);
		else if constexpr (std::is_same<T, int64_t>::value)
			return getInt64(key);
		else if constexpr (std::is_same<T, uint64_t>::value)
			return getUInt64(key);
		else if constexpr (std::is_same<T, std::string>::value)
			return getString(key);
		else if constexpr (std::is_same<T, bool>::value)
			return getBool(key);
		else
			return nullptr;
	}

	template<typename T>
	T IJson::get()
	{
		if constexpr (std::is_same<T, double>::value)
			return getDouble();
		if constexpr (std::is_same<T, float>::value)
			return getFloat();
		else if constexpr (std::is_same<T, int32_t>::value)
			return getInt32();
		else if constexpr (std::is_same<T, uint32_t>::value)
			return getUInt32();
		else if constexpr (std::is_same<T, int64_t>::value)
			return getInt64();
		else if constexpr (std::is_same<T, uint64_t>::value)
			return getUInt64();
		else if constexpr (std::is_same<T, std::string>::value)
			return getString();
		else if constexpr (std::is_same<T, bool>::value)
			return getBool();
		else
			return nullptr;
	}

}

#endif //TILESON_IJSON_HPP

/*** End of inlined file: IJson.hpp ***/



/*** Start of inlined file: NlohmannJson.hpp ***/
//
// Created by robin on 08.01.2021.
//

#ifdef INCLUDE_NLOHMANN_JSON_HPP_

#ifndef TILESON_NLOHMANNJSON_HPP
#define TILESON_NLOHMANNJSON_HPP

namespace tson
{
	class NlohmannJson : public tson::IJson
	{
		public:
			inline NlohmannJson() = default;

			IJson &operator[](std::string_view key) override
			{
				if(m_arrayCache.count(key.data()) == 0)
					m_arrayCache[key.data()] = std::make_unique<NlohmannJson>(&m_json->operator[](key.data()));//.front());

				return *m_arrayCache[key.data()].get();
			}

			inline explicit NlohmannJson(nlohmann::json *json) : m_json {json}
			{

			}

			inline IJson& at(std::string_view key) override
			{
				if(m_arrayCache.count(key.data()) == 0)
					m_arrayCache[key.data()] = std::make_unique<NlohmannJson>(&m_json->operator[](key.data()));//.front());

				return *m_arrayCache[key.data()].get();
			}

			inline IJson& at(size_t pos) override
			{
				if(m_arrayPosCache.count(pos) == 0)
					m_arrayPosCache[pos] = std::make_unique<NlohmannJson>(&m_json->at(pos));

				return *m_arrayPosCache[pos];
			}

			std::vector<std::unique_ptr<IJson>> array() override
			{
				std::vector<std::unique_ptr<IJson>> vec;
				for(auto &item : *m_json)
				{
					nlohmann::json *ptr = &item;
					vec.emplace_back(std::make_unique<NlohmannJson>(ptr));
				}

				return vec;
			}

			inline std::vector<std::unique_ptr<IJson>> &array(std::string_view key) override
			{
				if(m_arrayListDataCache.count(key.data()) == 0)
				{
					if (m_json->count(key.data()) > 0 && m_json->operator[](key.data()).is_array())
					{
						std::for_each(m_json->operator[](key.data()).begin(), m_json->operator[](key.data()).end(), [&](nlohmann::json &item)
						{
							nlohmann::json *ptr = &item;
							m_arrayListDataCache[key.data()].emplace_back(std::make_unique<NlohmannJson>(ptr));
						});
					}
				}

				return m_arrayListDataCache[key.data()];
			}

			[[nodiscard]] inline size_t size() const override
			{
				return m_json->size();
			}

			inline bool parse(const fs::path &path) override
			{
				clearCache();
				m_data = nullptr;
				m_json = nullptr;
				if (fs::exists(path) && fs::is_regular_file(path))
				{
					m_data = std::make_unique<nlohmann::json>();
					std::ifstream i(path.u8string());
					try
					{
						i >> *m_data;
						m_json = m_data.get();
					}
					catch (const nlohmann::json::parse_error &error)
					{
						std::string message = "Parse error: ";
						message += std::string(error.what());
						message += std::string("\n");
						std::cerr << message;
						return false;
					}
					return true;
				}
				return false;
			}

			inline bool parse(const void *data, size_t size) override
			{
				clearCache();
				m_json = nullptr;
				m_data = std::make_unique<nlohmann::json>();
				tson::MemoryStream mem{(uint8_t *) data, size};
				try
				{
					mem >> *m_data;
					m_json = m_data.get();
				}
				catch (const nlohmann::json::parse_error &error)
				{
					std::string message = "Parse error: ";
					message += std::string(error.what());
					message += std::string("\n");
					std::cerr << message;
					return false;
				}
				return true;
			}

			[[nodiscard]] inline size_t count(std::string_view key) const override
			{
				return m_json->count(key);
			}

			[[nodiscard]] inline bool any(std::string_view key) const override
			{
				return count(key) > 0;
			}

			[[nodiscard]] inline bool isArray() const override
			{
				return m_json->is_array();
			}

			[[nodiscard]] inline bool isObject() const override
			{
				return m_json->is_object();
			}

			[[nodiscard]] inline bool isNull() const override
			{
				return m_json->is_null();
			}

		protected:
			[[nodiscard]] inline int32_t getInt32(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<int32_t>();
			}

			[[nodiscard]] inline uint32_t getUInt32(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<uint32_t>();
			}

			[[nodiscard]] inline int64_t getInt64(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<int64_t>();
			}

			[[nodiscard]] inline uint64_t getUInt64(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<uint64_t>();
			}

			[[nodiscard]] inline double getDouble(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<double>();
			}

			[[nodiscard]] inline std::string getString(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<std::string>();
			}

			[[nodiscard]] inline bool getBool(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<bool>();
			}

			[[nodiscard]] float getFloat(std::string_view key) override
			{
				return m_json->operator[](key.data()).get<float>();
			}

			[[nodiscard]] inline int32_t getInt32() override
			{
				return m_json->get<int32_t>();
			}

			[[nodiscard]] inline uint32_t getUInt32() override
			{
				return m_json->get<uint32_t>();
			}

			[[nodiscard]] inline int64_t getInt64() override
			{
				return m_json->get<int64_t>();
			}

			[[nodiscard]] inline uint64_t getUInt64() override
			{
				return m_json->get<uint64_t>();
			}

			[[nodiscard]] inline double getDouble() override
			{
				return m_json->get<double>();
			}

			[[nodiscard]] inline std::string getString() override
			{
				return m_json->get<std::string>();
			}

			[[nodiscard]] inline bool getBool() override
			{
				return m_json->get<bool>();
			}

			[[nodiscard]] float getFloat() override
			{
				return m_json->get<float>();
			}

		private:
			inline void clearCache()
			{
				m_arrayCache.clear();
				m_arrayPosCache.clear();
				m_arrayListDataCache.clear();
			}

			nlohmann::json *m_json = nullptr;
			std::unique_ptr<nlohmann::json> m_data = nullptr; //Only used if this is the owner json!

			//Cache!
			std::map<std::string, std::unique_ptr<IJson>> m_arrayCache;
			std::map<size_t, std::unique_ptr<IJson>> m_arrayPosCache;
			std::map<std::string, std::vector<std::unique_ptr<IJson>>> m_arrayListDataCache;

	};
}
#endif //TILESON_NLOHMANNJSON_HPP

#endif //INCLUDE_NLOHMANN_JSON_HPP_
/*** End of inlined file: NlohmannJson.hpp ***/


/*** Start of inlined file: PicoJson.hpp ***/
//
// Created by robin on 11.01.2021.
//

#ifdef picojson_h
#ifndef TILESON_PICOJSON_HPP
#define TILESON_PICOJSON_HPP

namespace tson
{
	class PicoJson : public tson::IJson
	{
		public:
			inline PicoJson() = default;

			IJson &operator[](std::string_view key) override
			{
				if(m_arrayCache.count(key.data()) == 0)
				{
					if(m_json->is<picojson::object>())
					{
						picojson::object &o = m_json->get<picojson::object>();
						m_arrayCache[key.data()] = std::make_unique<PicoJson>(&o[key.data()]);
					}
				}

				return *m_arrayCache[key.data()].get();
			}

			inline explicit PicoJson(picojson::value *json) : m_json {json}
			{

			}

			inline IJson& at(std::string_view key) override
			{
				if(m_arrayCache.count(key.data()) == 0)
				{
					if(m_json->is<picojson::object>())
					{
						picojson::object &o = m_json->get<picojson::object>();
						m_arrayCache[key.data()] = std::make_unique<PicoJson>(&o[key.data()]);
					}
				}
				return *m_arrayCache[key.data()].get();
			}

			inline IJson& at(size_t pos) override
			{
				if(m_arrayPosCache.count(pos) == 0)
				{
					picojson::array &a = m_json->get<picojson::array>();
					m_arrayPosCache[pos] = std::make_unique<PicoJson>(&a.at(pos));
				}

				return *m_arrayPosCache[pos];
			}

			std::vector<std::unique_ptr<IJson>> array() override
			{
				std::vector<std::unique_ptr<IJson>> vec;
				if(m_json->is<picojson::array>())
				{
					picojson::array &a = m_json->get<picojson::array>();
					for (auto &item : a)
					{
						picojson::value *ptr = &item;
						vec.emplace_back(std::make_unique<PicoJson>(ptr));
					}
				}

				return vec;
			}

			inline std::vector<std::unique_ptr<IJson>> &array(std::string_view key) override
			{
				if(m_arrayListDataCache.count(key.data()) == 0)
				{
					if(count(key.data()) > 0)
					{
						if (isObject())
						{
							picojson::object &obj = m_json->get<picojson::object>();
							picojson::value &v = obj.at(key.data());
							bool isArray = v.is<picojson::array>();
							if (isArray)
							{
								picojson::array &a = v.get<picojson::array>();

								std::for_each(a.begin(), a.end(), [&](picojson::value &item)
								{
									picojson::value *ptr = &item;
									m_arrayListDataCache[key.data()].emplace_back(std::make_unique<PicoJson>(ptr));
								});
							}
						}
					}
				}

				return m_arrayListDataCache[key.data()];
			}

			[[nodiscard]] inline size_t size() const override
			{
				if (m_json->is<picojson::object>())
				{
					picojson::object obj = m_json->get<picojson::object>();
					return obj.size();
				}
				return 0;
			}

			inline bool parse(const fs::path &path) override
			{
				clearCache();
				m_data = nullptr;
				m_json = nullptr;
				if (fs::exists(path) && fs::is_regular_file(path))
				{
					m_data = std::make_unique<picojson::value>();
					std::ifstream i(path.u8string());
					try
					{
						std::string error = picojson::parse(*m_data, i);
						if(!error.empty())
						{
							std::cerr << "PicoJson parse error: " << error << "\n";
							return false;
						}
						//i >> *m_data;
						m_json = m_data.get();
					}
					catch (const std::exception &error)
					{
						std::string message = "Parse error: ";
						message += std::string(error.what());
						message += std::string("\n");
						std::cerr << message;
						return false;
					}
					return true;
				}
				return false;
			}

			inline bool parse(const void *data, size_t size) override
			{
				clearCache();
				m_json = nullptr;
				m_data = std::make_unique<picojson::value>();
				tson::MemoryStream mem{(uint8_t *) data, size};
				try
				{
					std::string error = picojson::parse(*m_data, mem);
					if(!error.empty())
					{
						std::cerr << "PicoJson parse error: " << error << "\n";
						return false;
					}
					//mem >> *m_data;
					m_json = m_data.get();
				}
				catch (const std::exception &error)
				{
					std::string message = "Parse error: ";
					message += std::string(error.what());
					message += std::string("\n");
					std::cerr << message;
					return false;
				}
				return true;
			}

			[[nodiscard]] inline size_t count(std::string_view key) const override
			{
				if (isObject())
				{
					picojson::object obj = m_json->get<picojson::object>();
					return obj.count(key.data());
				}

				return m_json->contains(key.data()) ? 1 : 0;
			}

			[[nodiscard]] inline bool any(std::string_view key) const override
			{
				return count(key) > 0;
			}

			[[nodiscard]] inline bool isArray() const override
			{
				return m_json->is<picojson::array>();
			}

			[[nodiscard]] inline bool isObject() const override
			{
				return m_json->is<picojson::object>();
			}

			[[nodiscard]] inline bool isNull() const override
			{
				return m_json->is<picojson::null>();
			}

		protected:
			[[nodiscard]] inline int32_t getInt32(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return static_cast<int32_t>(getDouble(key));
			}

			[[nodiscard]] inline uint32_t getUInt32(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return static_cast<uint32_t>(getDouble(key));
			}

			[[nodiscard]] inline int64_t getInt64(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return static_cast<int64_t>(getDouble(key));
			}

			[[nodiscard]] inline uint64_t getUInt64(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return static_cast<uint64_t>(getDouble(key));
			}

			[[nodiscard]] inline double getDouble(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return obj[key.data()].get<double>();
			}

			[[nodiscard]] inline std::string getString(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return obj[key.data()].get<std::string>();
			}

			[[nodiscard]] inline bool getBool(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return obj[key.data()].get<bool>();
			}

			[[nodiscard]] float getFloat(std::string_view key) override
			{
				picojson::object obj = m_json->get<picojson::object>();
				return static_cast<float>(getDouble(key));
			}

			[[nodiscard]] inline int32_t getInt32() override
			{
				return static_cast<int32_t>(getDouble());
			}

			[[nodiscard]] inline uint32_t getUInt32() override
			{
				return static_cast<uint32_t>(getDouble());
			}

			[[nodiscard]] inline int64_t getInt64() override
			{
				return static_cast<int64_t>(getDouble());
			}

			[[nodiscard]] inline uint64_t getUInt64() override
			{
				return static_cast<uint64_t>(getDouble());
			}

			[[nodiscard]] inline double getDouble() override
			{
				return m_json->get<double>();
			}

			[[nodiscard]] inline std::string getString() override
			{
				return m_json->get<std::string>();
			}

			[[nodiscard]] inline bool getBool() override
			{
				return m_json->get<bool>();
			}

			[[nodiscard]] float getFloat() override
			{
				return static_cast<float>(getDouble());
			}

		private:
			inline void clearCache()
			{
				m_arrayCache.clear();
				m_arrayPosCache.clear();
				m_arrayListDataCache.clear();
			}

			picojson::value *m_json = nullptr;
			std::unique_ptr<picojson::value> m_data = nullptr; //Only used if this is the owner json!

			//Cache!
			std::map<std::string, std::unique_ptr<IJson>> m_arrayCache;
			std::map<size_t, std::unique_ptr<IJson>> m_arrayPosCache;
			std::map<std::string, std::vector<std::unique_ptr<IJson>>> m_arrayListDataCache;

	};
}
#endif //TILESON_PICOJSON_HPP
#endif

/*** End of inlined file: PicoJson.hpp ***/

//#include "../json/Gason.hpp" //Unsupported

/*** Start of inlined file: Json11.hpp ***/
//
// Created by robin on 16.01.2021.
//

#ifndef TILESON_JSON11_HPP
#define TILESON_JSON11_HPP

namespace tson
{
	class Json11 : public tson::IJson
	{
		public:
			inline Json11() = default;

			IJson &operator[](std::string_view key) override
			{
				if(m_arrayCache.count(key.data()) == 0)
				{
					if(m_json->is_object())
					{
						m_arrayCache[key.data()] = std::make_unique<Json11>(m_json->operator[](key.data()));
					}
				}

				return *m_arrayCache[key.data()].get();
			}

			inline explicit Json11(const json11::Json &json) : m_json {&json}
			{

			}

			inline IJson& at(std::string_view key) override
			{
				if(m_arrayCache.count(key.data()) == 0)
				{
					if(m_json->is_object())
					{
						m_arrayCache[key.data()] = std::make_unique<Json11>(m_json->operator[](key.data()));
					}
				}
				return *m_arrayCache[key.data()].get();
			}

			inline IJson& at(size_t pos) override
			{
				if(m_arrayPosCache.count(pos) == 0)
				{
					const std::vector<json11::Json> &a = m_json->array_items();
					m_arrayPosCache[pos] = std::make_unique<Json11>(a.at(pos));
				}

				return *m_arrayPosCache[pos];
			}

			std::vector<std::unique_ptr<IJson>> array() override
			{
				std::vector<std::unique_ptr<IJson>> vec;
				if(m_json->is_array())
				{
					for (const json11::Json &item : m_json->array_items())
					{
						vec.emplace_back(std::make_unique<Json11>(item));
					}
				}

				return vec;
			}

			inline std::vector<std::unique_ptr<IJson>> &array(std::string_view key) override
			{
				if(m_arrayListDataCache.count(key.data()) == 0)
				{
					if(count(key.data()) > 0)
					{
						if(isObject())
						{
							const json11::Json &v = m_json->operator[](key.data());
							if(v.is_array())
							{
								for (const json11::Json &item : v.array_items())
								{
									m_arrayListDataCache[key.data()].emplace_back(std::make_unique<Json11>(item));
								}
							}
						}
					}
				}

				return m_arrayListDataCache[key.data()];
			}

			[[nodiscard]] inline size_t size() const override
			{
				if(m_json->is_object())
					return m_json->object_items().size();
				else if(m_json->is_array())
					return m_json->array_items().size();

				return 0;
			}

			inline bool parse(const fs::path &path) override
			{
				clearCache();
				m_data = nullptr;
				m_json = nullptr;
				if (fs::exists(path) && fs::is_regular_file(path))
				{
					std::ifstream file(path.u8string());
					std::string str;

					file.seekg(0, std::ios::end);
					str.reserve(file.tellg());
					file.seekg(0, std::ios::beg);

					str.assign((std::istreambuf_iterator<char>(file)),
							   std::istreambuf_iterator<char>());

					m_data = std::make_unique<json11::Json>();

					try
					{
						std::string strError;
						*m_data = json11::Json::parse(str, strError);
						if(!strError.empty())
						{
							std::cerr << strError << "\n";
							return false;
						}
						m_json = m_data.get();
					}
					catch (const std::exception &error)
					{
						std::string message = "Json11 parse error: ";
						message += std::string(error.what());
						message += std::string("\n");
						std::cerr << message;
						return false;
					}
					return true;
				}
				return false;
			}

			inline bool parse(const void *data, size_t size) override
			{
				clearCache();
				m_json = nullptr;
				std::string str;

				str.reserve(size);

				tson::MemoryStream mem{(uint8_t *) data, size};

				str.assign((std::istreambuf_iterator<char>(mem)),
						   std::istreambuf_iterator<char>());

				m_data = std::make_unique<json11::Json>();

				try
				{
					std::string strError;

					*m_data = json11::Json::parse(str, strError);
					if(!strError.empty())
					{
						std::cout << strError << "\n";
						return false;
					}
					m_json = m_data.get();
				}
				catch (const std::exception &error)
				{
					std::string message = "Json11 parse error: ";
					message += std::string(error.what());
					message += std::string("\n");
					std::cerr << message;
					return false;
				}
				return true;
			}

			[[nodiscard]] inline size_t count(std::string_view key) const override
			{
				if (isObject())
				{
					//const json11::Json &j = m_json->operator[](key.data());
					//size_t s1 = j.object_items().size();
					return m_json->object_items().count(key.data());
				}

				return 0;
			}

			[[nodiscard]] inline bool any(std::string_view key) const override
			{
				return count(key) > 0;
			}

			[[nodiscard]] inline bool isArray() const override
			{
				return m_json->is_array();
			}

			[[nodiscard]] inline bool isObject() const override
			{
				return m_json->is_object();
			}

			[[nodiscard]] inline bool isNull() const override
			{
				return m_json->is_null();
			}

		protected:
			[[nodiscard]] inline int32_t getInt32(std::string_view key) override
			{
				return static_cast<int32_t>(getDouble(key));
			}

			[[nodiscard]] inline uint32_t getUInt32(std::string_view key) override
			{
				return static_cast<uint32_t>(getDouble(key));
			}

			[[nodiscard]] inline int64_t getInt64(std::string_view key) override
			{
				return static_cast<int64_t>(getDouble(key));
			}

			[[nodiscard]] inline uint64_t getUInt64(std::string_view key) override
			{
				return static_cast<uint64_t>(getDouble(key));
			}

			[[nodiscard]] inline double getDouble(std::string_view key) override
			{
				return m_json->operator[](key.data()).number_value();
			}

			[[nodiscard]] inline std::string getString(std::string_view key) override
			{
				return m_json->operator[](key.data()).string_value(); // .get<std::string>();
			}

			[[nodiscard]] inline bool getBool(std::string_view key) override
			{
				return m_json->operator[](key.data()).bool_value();
			}

			[[nodiscard]] float getFloat(std::string_view key) override
			{
				return static_cast<float>(getDouble(key));
			}

			[[nodiscard]] inline int32_t getInt32() override
			{
				return static_cast<int32_t>(getDouble());
			}

			[[nodiscard]] inline uint32_t getUInt32() override
			{
				return static_cast<uint32_t>(getDouble());
			}

			[[nodiscard]] inline int64_t getInt64() override
			{
				return static_cast<int64_t>(getDouble());
			}

			[[nodiscard]] inline uint64_t getUInt64() override
			{
				return static_cast<uint64_t>(getDouble());
			}

			[[nodiscard]] inline double getDouble() override
			{
				return m_json->number_value();
			}

			[[nodiscard]] inline std::string getString() override
			{
				return m_json->string_value();
			}

			[[nodiscard]] inline bool getBool() override
			{
				return m_json->bool_value();
			}

			[[nodiscard]] float getFloat() override
			{
				return static_cast<float>(getDouble());
			}

		private:

			inline void clearCache()
			{
				m_arrayCache.clear();
				m_arrayPosCache.clear();
				m_arrayListDataCache.clear();
			}

			//Owner values
			char *m_endptr;
			std::unique_ptr<json11::Json> m_data = nullptr; //Only used if this is the owner json!

			const json11::Json *m_json = nullptr;

			//Cache!
			std::map<std::string, std::unique_ptr<IJson>> m_arrayCache;
			std::map<size_t, std::unique_ptr<IJson>> m_arrayPosCache;
			std::map<std::string, std::vector<std::unique_ptr<IJson>>> m_arrayListDataCache;

	};
}

#endif //TILESON_JSON11_HPP

/*** End of inlined file: Json11.hpp ***/



/*** Start of inlined file: Layer.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_LAYER_HPP
#define TILESON_LAYER_HPP

#include <set>
//#include "../external/json.hpp"


/*** Start of inlined file: Chunk.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_CHUNK_HPP
#define TILESON_CHUNK_HPP

//#include "../external/json.hpp"

namespace tson
{
	class Chunk
	{
		public:
			inline Chunk() = default;
			inline explicit Chunk(IJson &json);
			inline bool parse(IJson &json);

			[[nodiscard]] inline const std::vector<int> &getData() const;
			[[nodiscard]] inline const std::string &getBase64Data() const;
			[[nodiscard]] inline const Vector2i &getSize() const;
			[[nodiscard]] inline const Vector2i &getPosition() const;

		private:
			std::vector<int> m_data;        /*! 'data' (when uint array): Array of unsigned int (GIDs) or base64-encoded data. tilelayer only. */
			std::string      m_base64Data;  /*! 'data' (when string): Array of unsigned int (GIDs) or base64-encoded data. */
			tson::Vector2i   m_size;        /*!  x='width' (in tiles) and y='height' (in tiles): */
			tson::Vector2i   m_position;    /*! 'x' and 'y' position in tiles */
	};
}

#endif //TILESON_CHUNK_HPP

/*!
 * Parses 'chunk' data from Tiled json and stores the values in this class
 * @param json json-data
 */
tson::Chunk::Chunk(IJson &json)
{
	parse(json);
}

/*!
 * Parses 'chunk' data from Tiled json and stores the values in this class
 * @param json json-data
 * @return true if all mandatory fields was found. false otherwise.
 */
bool tson::Chunk::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("width") > 0 && json.count("height") > 0)
		m_size = {json["width"].get<int>(), json["height"].get<int>()}; else allFound = false;
	if(json.count("x") > 0 && json.count("y") > 0)
		m_position = {json["x"].get<int>(), json["y"].get<int>()}; else allFound = false;

	//Handle DATA (Optional)
	if(json.count("data") > 0)
	{
		if(json["data"].isArray())
		{
			auto &data = json.array("data");
			std::for_each(data.begin(), data.end(), [&](std::unique_ptr<IJson> &item) { m_data.push_back(item->get<int>()); });
		}
		else
			m_base64Data = json["data"].get<std::string>();
	}

	return allFound;
}

/*!
 * 'data' (when uint array): Array of unsigned int (GIDs) or base64-encoded data. tilelayer only.
 * @return list of tile ids
 */
const std::vector<int> &tson::Chunk::getData() const
{
	return m_data;
}

/*!
 * 'data' (when string): Array of unsigned int (GIDs) or base64-encoded data.
 * @return base64 string
 */
const std::string &tson::Chunk::getBase64Data() const
{
	return m_base64Data;
}

/*!
 * x='width' (in tiles) and y='height' (in tiles).
 * @return Size (x and y), containing the values from the fields 'width' and 'height' in Tiled
 */
const tson::Vector2i &tson::Chunk::getSize() const
{
	return m_size;
}

/*!
 * 'x' and 'y' position in tiles
 * @return Position in int
 */
const tson::Vector2i &tson::Chunk::getPosition() const
{
	return m_position;
}
/*** End of inlined file: Chunk.hpp ***/


/*** Start of inlined file: Object.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_OBJECT_HPP
#define TILESON_OBJECT_HPP

//#include "../external/json.hpp"


/*** Start of inlined file: PropertyCollection.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_PROPERTYCOLLECTION_HPP
#define TILESON_PROPERTYCOLLECTION_HPP


/*** Start of inlined file: Property.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_PROPERTY_HPP
#define TILESON_PROPERTY_HPP

//#include "../../TilesonConfig.h"

//#if USE_CPP17_FILESYSTEM

#include <any>
#include <string>

/*** Start of inlined file: Enums.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_ENUMS_HPP
#define TILESON_ENUMS_HPP
#include <cstdint>

/*** Start of inlined file: EnumBitflags.hpp ***/
//
// Created by robin on 08.11.2020.
//

#ifndef TILESON_ENUMBITFLAGS_HPP
#define TILESON_ENUMBITFLAGS_HPP

#include <type_traits>
#include <iostream>

namespace tson
{
	#define ENABLE_BITMASK_OPERATORS(x)  \
	template<>                           \
	struct EnableBitMaskOperators<x>     \
	{                                    \
		static const bool enable = true; \
	};

	template<typename Enum>
	struct EnableBitMaskOperators
	{
		static const bool enable = false;
	};

	template<typename Enum>
	typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
	operator |(Enum lhs, Enum rhs)
	{
		static_assert(std::is_enum<Enum>::value,
					  "template parameter is not an enum type");

		using underlying = typename std::underlying_type<Enum>::type;

		return static_cast<Enum> (
				static_cast<underlying>(lhs) |
				static_cast<underlying>(rhs)
		);
	}

	//Permissions operator &(Permissions lhs, Permissions rhs)
	template<typename Enum>
	typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
	operator &(Enum lhs, Enum rhs)
	{
		static_assert(std::is_enum<Enum>::value,
					  "template parameter is not an enum type");

		using underlying = typename std::underlying_type<Enum>::type;

		return static_cast<Enum> (
				static_cast<underlying>(lhs) &
				static_cast<underlying>(rhs)
		);
	}

	//Permissions operator ^(Permissions lhs, Permissions rhs)
	template<typename Enum>
	typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
	operator ^(Enum lhs, Enum rhs)
	{
		static_assert(std::is_enum<Enum>::value,
					  "template parameter is not an enum type");

		using underlying = typename std::underlying_type<Enum>::type;

		return static_cast<Enum> (
				static_cast<underlying>(lhs) ^
				static_cast<underlying>(rhs)
		);
	}

	//Permissions operator ~(Permissions rhs)
	template<typename Enum>
	typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
	operator ~(Enum rhs)
	{
		static_assert(std::is_enum<Enum>::value,
					  "template parameter is not an enum type");

		using underlying = typename std::underlying_type<Enum>::type;

		return static_cast<Enum> (
				~static_cast<underlying>(rhs)
		);
	}

	//Permissions& operator |=(Permissions &lhs, Permissions rhs)
	template<typename Enum>
	typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
	&operator |=(Enum &lhs, Enum rhs)
	{
		static_assert(std::is_enum<Enum>::value,
					  "template parameter is not an enum type");

		using underlying = typename std::underlying_type<Enum>::type;

		lhs = static_cast<Enum> (
				static_cast<underlying>(lhs) |
				static_cast<underlying>(rhs)
		);

		return lhs;
	}

	//Permissions& operator &=(Permissions &lhs, Permissions rhs)
	template<typename Enum>
	typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
	&operator &=(Enum &lhs, Enum rhs)
	{
		static_assert(std::is_enum<Enum>::value,
					  "template parameter is not an enum type");

		using underlying = typename std::underlying_type<Enum>::type;

		lhs = static_cast<Enum> (
				static_cast<underlying>(lhs) &
				static_cast<underlying>(rhs)
		);

		return lhs;
	}

	//Permissions& operator ^=(Permissions &lhs, Permissions rhs)
	template<typename Enum>
	typename std::enable_if<EnableBitMaskOperators<Enum>::enable, Enum>::type
	&operator ^=(Enum &lhs, Enum rhs)
	{
		static_assert(std::is_enum<Enum>::value,
					  "template parameter is not an enum type");

		using underlying = typename std::underlying_type<Enum>::type;

		lhs = static_cast<Enum> (
				static_cast<underlying>(lhs) ^
				static_cast<underlying>(rhs)
		);

		return lhs;
	}
}

#endif //TILESON_ENUMBITFLAGS_HPP

/*** End of inlined file: EnumBitflags.hpp ***/


namespace tson
{
	/*!
	 * Type used in Property.hpp
	 */
	enum class Type : uint8_t
	{
			Undefined = 0,
			Color = 1, /*! color */
			File = 2, /*! file */
			Int = 3, /*! int */
			Boolean = 4, /*! bool */
			Float = 5, /*! float */
			String = 6 /*! string */
	};

	/*!
	 * Layer.hpp - LayerType
	 * //'type': tilelayer, objectgroup, imagelayer or group
	 */
	enum class LayerType : uint8_t
	{
			Undefined = 0,
			TileLayer = 1,
			ObjectGroup = 2,
			ImageLayer = 3,
			Group = 4
	};

	/*!
	 * Map.hpp - ParseStatus
	 */
	enum class ParseStatus : uint8_t
	{
			OK = 0, //OK unless otherwise stated
			FileNotFound = 1,
			ParseError = 2,
			MissingData = 3,
			DecompressionError = 4
	};

	/*!
	 * Object.hpp - ObjectType
	 */
	enum class ObjectType : uint8_t
	{
			Undefined = 0,
			Object = 1,
			Ellipse = 2,
			Rectangle = 3,
			Point = 4,
			Polygon = 5,
			Polyline = 6,
			Text = 7,
			Template = 8
	};

	static constexpr uint32_t FLIPPED_HORIZONTALLY_FLAG = 0x80000000;
	static constexpr uint32_t FLIPPED_VERTICALLY_FLAG   = 0x40000000;
	static constexpr uint32_t FLIPPED_DIAGONALLY_FLAG   = 0x20000000;
	/*!
	 * Object.hpp - ObjectFlipFlags
	 */
	enum class TileFlipFlags : uint32_t
	{
			None = 0,
			Diagonally = FLIPPED_DIAGONALLY_FLAG,
			Vertically = FLIPPED_VERTICALLY_FLAG,
			Horizontally = FLIPPED_HORIZONTALLY_FLAG
	};

	/*!
	 * Tileset.hpp - ObjectAlignment
	 */
	enum class ObjectAlignment : uint8_t
	{
			Unspecified = 0,    //unspecified
			TopLeft = 1,        //topleft
			Top = 2,            //top
			TopRight = 3,       //topright
			Left = 4,           //left
			Center = 5,         //center
			Right = 6,          //right
			BottomLeft = 7,     //bottomleft
			Bottom = 8,         //bottom
			BottomRight = 9     //bottomright
	};

	ENABLE_BITMASK_OPERATORS(TileFlipFlags)
}

#endif //TILESON_ENUMS_HPP

/*** End of inlined file: Enums.hpp ***/


//#include "../external/json.hpp"

namespace tson
{
	class Property
	{
		public:

			//enum class Type : uint8_t
			//{
			//        Undefined = 0,
			//        Color = 1, /*! color */
			//        File = 2, /*! file */
			//        Int = 3, /*! int */
			//        Boolean = 4, /*! bool */
			//        Float = 5, /*! float */
			//        String = 6 /*! string */
			//};

			inline Property();
			inline Property(IJson &json);
			inline Property(std::string name, std::any value, Type type);

			inline void setValue(const std::any &value);
			inline void setStrValue(const std::string &value);
			inline void setName(const std::string &name);

			[[nodiscard]] inline const std::type_info& getValueType() const;
			inline std::string getValueTypeInfo();
			[[nodiscard]]inline const std::any &getValue() const;
			template <typename T>
			inline T getValue() const;
			[[nodiscard]] inline const std::string &getName() const;
			[[nodiscard]] inline Type getType() const;

		protected:
			inline void setTypeByString(const std::string &str);
			inline void setValueByType(IJson &json);

			Type m_type = Type::Undefined;
			std::string m_name;
			std::any m_value; //Using std::any to assign any type
	};

	template<typename T>
	T Property::getValue() const
	{
		bool isCorrectType = (m_value.type() == typeid(T));

		if(isCorrectType)
		{
			T value = std::any_cast<T>(m_value);
			return value;
		}
		else
		{
			static T defaultValue;
			return defaultValue;
		}
	}
}

tson::Property::Property() : m_name {"unnamed"}
{

}

tson::Property::Property(IJson &json)
{
	setTypeByString(json["type"].get<std::string>());
	setValueByType(json["value"]);
	m_name = json["name"].get<std::string>();
}

tson::Property::Property(std::string name, std::any value, Type type) : m_name { move(name) }, m_value { move(value) }, m_type {type}
{

}

void tson::Property::setValue(const std::any &value)
{
	m_value = value;
}

/*!
 * Sets the value specifically as string.
 * When not specified as std::string, the default is that the value will be set as char * when adding a value like "test"
 * This function is to make sure the value is added as string.
 * @param value
 */
void tson::Property::setStrValue(const std::string &value)
{
	m_value = value;
}

const std::any &tson::Property::getValue() const
{
	return m_value;
}

void tson::Property::setName(const std::string &name)
{
	m_name = name;
}

const std::string &tson::Property::getName() const
{
	return m_name;
}

/*!
 * Gets the value type as std::value_info.
 * This can easily be compared to types like this:
 * Check if int: getValueType() == typeid(int)
 * @return
 */

const std::type_info &tson::Property::getValueType() const
{
	return m_value.type();
}

/*!
 * Gets the value type as std::string
 * Examples of known types:
 * "i" = int
 * "f" = float
 * "b" = bool
 * @return
 */
std::string tson::Property::getValueTypeInfo()
{
	return m_value.type().name();
}

tson::Type tson::Property::getType() const
{
	return m_type;
}

void tson::Property::setTypeByString(const std::string &str)
{
	if(str == "color")
		m_type = tson::Type::Color;
	else if(str == "file")
		m_type = tson::Type::File;
	else if(str == "int")
		m_type = tson::Type::Int;
	else if(str == "bool")
		m_type = tson::Type::Boolean;
	else if(str == "float")
		m_type = tson::Type::Float;
	else if(str == "string")
		m_type = tson::Type::String;
	else
		m_type = tson::Type::Undefined;
}

void tson::Property::setValueByType(IJson &json)
{
	switch(m_type)
	{
		case Type::Color:
			m_value = Colori(json.get<std::string>());
			break;

		case Type::File:
			m_value = fs::path(json.get<std::string>());
			break;

		case Type::Int:
			m_value = json.get<int>();
			break;

		case Type::Boolean:
			m_value = json.get<bool>();
			break;

		case Type::Float:
			m_value = json.get<float>();
			break;

		case Type::String:
			setStrValue(json.get<std::string>());
			break;

		default:
			setStrValue(json.get<std::string>());
			break;

	}
}

#endif //TILESON_PROPERTY_HPP

/*** End of inlined file: Property.hpp ***/

//#include "../external/json.hpp"
#include <map>

namespace tson
{
	class PropertyCollection
	{
		public:
			inline PropertyCollection() = default;

			inline explicit PropertyCollection(std::string id);

			inline tson::Property * add(const tson::Property &property);
			inline tson::Property * add(IJson &json);
			inline tson::Property * add(const std::string &name, const std::any &value, tson::Type type);

			inline void remove(const std::string &name);

			inline void setValue(const std::string &name, const std::any &value);
			inline void setId(const std::string &id);

			inline bool hasProperty(const std::string &name);
			inline tson::Property * getProperty(const std::string &name);
			inline std::map<std::string, Property> &getProperties();
			inline std::vector<Property*> get();
			template <typename T>
			inline T getValue(const std::string &name);
			[[nodiscard]] inline const std::string &getId() const;
			[[nodiscard]] inline size_t getSize() const;

		protected:
			std::string m_id;
			std::map<std::string, tson::Property> m_properties;
	};
}

template<typename T>
T tson::PropertyCollection::getValue(const std::string &name)
{
	static T defaultT;
	return (m_properties.count(name) > 0) ? m_properties[name].getValue<T>() : defaultT;
}

tson::PropertyCollection::PropertyCollection(std::string id) : m_id {std::move(id)}
{

}

tson::Property *tson::PropertyCollection::add(const tson::Property &property)
{
	m_properties[property.getName()] = property;
	return &m_properties[property.getName()];
}

tson::Property *tson::PropertyCollection::add(IJson &json)
{
	tson::Property property = tson::Property(json);
	std::string name = property.getName();
	m_properties[name] = std::move(property);
	return &m_properties[name];
}

tson::Property *tson::PropertyCollection::add(const std::string &name, const std::any &value, tson::Type type)
{
	m_properties[name] = {name, value, type};
	return &m_properties[name];
}

void tson::PropertyCollection::remove(const std::string &name)
{
	m_properties.erase(name);
}

/*!
 * Sets a value IF the property already exists. Does nothing otherwise.
 * See add() for adding new properties
 * @param name
 * @param value
 */
void tson::PropertyCollection::setValue(const std::string &name, const std::any &value)
{
	if(m_properties.count(name) > 0)
		m_properties[name].setValue(value);
}

void tson::PropertyCollection::setId(const std::string &id)
{
	m_id = id;
}

bool tson::PropertyCollection::hasProperty(const std::string &name)
{
	return m_properties.count(name) > 0;
}

tson::Property *tson::PropertyCollection::getProperty(const std::string &name)
{
	return (m_properties.count(name) > 0) ? &m_properties[name] : nullptr;
}

std::map<std::string, tson::Property> &tson::PropertyCollection::getProperties()
{
	return m_properties;
}

/*!
 * Gets vector of pointers to all the existing properties
 * @return
 */
std::vector<tson::Property *> tson::PropertyCollection::get()
{
	std::vector<tson::Property *> props;
	for(auto &i : m_properties)
		props.emplace_back(&i.second);

	return props;
}

const std::string &tson::PropertyCollection::getId() const
{
	return m_id;
}

size_t tson::PropertyCollection::getSize() const
{
	return m_properties.size();
}

#endif //TILESON_PROPERTYCOLLECTION_HPP

/*** End of inlined file: PropertyCollection.hpp ***/


/*** Start of inlined file: Text.hpp ***/
//
// Created by robin on 05.08.2019.
//

#ifndef TILESON_TEXT_HPP
#define TILESON_TEXT_HPP

#include <string>

namespace tson
{
	class Text
	{
		public:
			inline Text() = default;
			/*!
			 *
			 * @param _text Text
			 * @param _wrap If the text is marked as wrapped
			 */
			inline Text(std::string _text, bool _wrap, tson::Colori _color) : text {std::move(_text)}, wrap {_wrap}, color {_color} {};
			//Just make it simple
			std::string text;
			tson::Colori color;
			bool wrap{};
	};
}

#endif //TILESON_TEXT_HPP

/*** End of inlined file: Text.hpp ***/

namespace tson
{
	class Object
	{
		public:
			//enum class Type : uint8_t
			//{
			//        Undefined = 0,
			//        Object = 1,
			//        Ellipse = 2,
			//        Rectangle = 3,
			//        Point = 4,
			//        Polygon = 5,
			//        Polyline = 6,
			//        Text = 7,
			//        Template = 8
			//};

			inline Object() = default;
			inline explicit Object(IJson &json);
			inline bool parse(IJson &json);

			[[nodiscard]] inline ObjectType getObjectType() const;
			[[nodiscard]] inline bool isEllipse() const;
			[[nodiscard]] inline uint32_t getGid() const;
			[[nodiscard]] inline const Vector2i &getSize() const;
			[[nodiscard]] inline int getId() const;
			[[nodiscard]] inline const std::string &getName() const;
			[[nodiscard]] inline bool isPoint() const;
			[[nodiscard]] inline float getRotation() const;
			[[nodiscard]] inline const std::string &getTemplate() const;
			[[nodiscard]] inline const std::string &getType() const;
			[[nodiscard]] inline bool isVisible() const;
			[[nodiscard]] inline const Vector2i &getPosition() const;

			[[nodiscard]] inline const std::vector<tson::Vector2i> &getPolygons() const;
			[[nodiscard]] inline const std::vector<tson::Vector2i> &getPolylines() const;
			[[nodiscard]] inline PropertyCollection &getProperties();
			[[nodiscard]] inline const Text &getText() const;

			template <typename T>
			inline T get(const std::string &name);
			inline tson::Property * getProp(const std::string &name);

			//v1.2.0-stuff
			[[nodiscard]] inline TileFlipFlags getFlipFlags() const;
			inline bool hasFlipFlags(TileFlipFlags flags);

		private:
			inline void setObjectTypeByJson(IJson &json);

			ObjectType                        m_objectType = ObjectType::Undefined;    /*! Says with object type this is */
			bool                              m_ellipse {};                            /*! 'ellipse': Used to mark an object as an ellipse */
			uint32_t                          m_gid {};                                /*! 'gid': GID, only if object comes from a Tilemap */
			tson::Vector2i                    m_size;                                  /*! x = 'width' (Width in pixels), y = 'height' (Height in pixels). Ignored if using a gid.)*/
			int                               m_id{};                                  /*! 'id': Incremental id - unique across all objects */
			std::string                       m_name;                                  /*! 'name':  String assigned to name field in editor*/
			bool                              m_point {};                              /*! 'point': Used to mark an object as a point */
			std::vector<tson::Vector2i>       m_polygon; 	                           /*! 'polygon': A list of x,y coordinates in pixels */
			std::vector<tson::Vector2i>       m_polyline; 	                           /*! 'polyline': A list of x,y coordinates in pixels */
			tson::PropertyCollection          m_properties; 	                       /*! 'properties': A list of properties (name, value, type). */
			float                             m_rotation {};                           /*! 'rotation': Angle in degrees clockwise */
			std::string                       m_template;                              /*! 'template': Reference to a template file, in case object is a template instance */
			tson::Text                        m_text; 	                               /*! first: 'text' second: 'wrap' */
			std::string                       m_type;                                  /*! 'type': String assigned to type field in editor */
			bool                              m_visible {};                            /*! 'visible': Whether object is shown in editor. */
			tson::Vector2i                    m_position;                              /*! 'x' and 'y': coordinate in pixels */

			//v1.2.0-stuff
			tson::TileFlipFlags               m_flipFlags = TileFlipFlags::None;       /*! Resolved using bit 32, 31 and 30 from gid */
	};

	/*!
	 * A shortcut for getting a property. Alternative to getProperties().getValue<T>("<name>")
	 * @tparam T The template value
	 * @param name Name of the property
	 * @return The actual value, if it exists. Otherwise: The default value of the type.
	 */
	template<typename T>
	T tson::Object::get(const std::string &name)
	{
		return m_properties.getValue<T>(name);
	}
}

/*!
 * Parses a json Tiled object
 * @param json
 */
tson::Object::Object(IJson &json)
{
	parse(json);
}

/*!
 * Parses a json Tiled object and autoamtically determines the object type based on the data presented.
 * Call getObjectType() to see what object type it is.
 * @param json
 * @return true if all mandatory fields was found. false otherwise.
 */
bool tson::Object::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("ellipse") > 0) m_ellipse = json["ellipse"].get<bool>(); //Optional
	if(json.count("gid") > 0)
	{
		uint32_t gid = json["gid"].get<uint32_t>(); //Optional
		if (gid & FLIPPED_HORIZONTALLY_FLAG) m_flipFlags |= TileFlipFlags::Horizontally;
		if (gid & FLIPPED_VERTICALLY_FLAG) m_flipFlags |= TileFlipFlags::Vertically;
		if (gid & FLIPPED_DIAGONALLY_FLAG) m_flipFlags |= TileFlipFlags::Diagonally;

		// Clear flags
		gid &= ~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG | FLIPPED_DIAGONALLY_FLAG);

		m_gid = gid;
	}
	if(json.count("id") > 0) m_id = json["id"].get<int>(); else allFound = false;
	if(json.count("name") > 0) m_name = json["name"].get<std::string>(); else allFound = false;
	if(json.count("point") > 0) m_point = json["point"].get<bool>(); //Optional
	if(json.count("rotation") > 0) m_rotation = json["rotation"].get<float>(); else allFound = false;
	if(json.count("template") > 0) m_template = json["template"].get<std::string>(); //Optional
	if(json.count("type") > 0) m_type = json["type"].get<std::string>(); else allFound = false;
	if(json.count("visible") > 0) m_visible = json["visible"].get<bool>(); else allFound = false;

	if(json.count("width") > 0 && json.count("height") > 0)
		m_size = {json["width"].get<int>(), json["height"].get<int>()}; else allFound = false;
	if(json.count("x") > 0 && json.count("y") > 0)
		m_position = {json["x"].get<int>(), json["y"].get<int>()}; else allFound = false;

	if(json.count("text") > 0)
	{
		bool hasColor = json["text"].count("color") > 0;
		tson::Color c = (hasColor) ? tson::Colori(json["text"]["color"].get<std::string>()) : tson::Colori();
		m_text = {json["text"]["text"].get<std::string>(), json["text"]["wrap"].get<bool>(), c}; //Optional
	}

	setObjectTypeByJson(json);

	if(m_objectType == ObjectType::Template)
		allFound = true; //Just accept anything with this type

	//More advanced data
	if(json.count("polygon") > 0 && json["polygon"].isArray())
	{
		auto &polygon = json.array("polygon");
		std::for_each(polygon.begin(), polygon.end(),[&](std::unique_ptr<IJson> &item)
		{
			IJson &j = *item;
			m_polygon.emplace_back(j["x"].get<int>(), j["y"].get<int>());
		});

	}

	if(json.count("polyline") > 0 && json["polyline"].isArray())
	{
		auto &polyline = json.array("polyline");
		std::for_each(polyline.begin(), polyline.end(),[&](std::unique_ptr<IJson> &item)
		{
			IJson &j = *item;
			m_polyline.emplace_back(j["x"].get<int>(), j["y"].get<int>());
		});
	}

	if(json.count("properties") > 0 && json["properties"].isArray())
	{
		auto &properties = json.array("properties");
		std::for_each(properties.begin(), properties.end(), [&](std::unique_ptr<IJson> &item)
		{
			m_properties.add(*item);
		});
	}

	return allFound;
}

/*!
 * Sets an object type based on json data.
 * @param json
 */
void tson::Object::setObjectTypeByJson(IJson &json)
{
	m_objectType = ObjectType::Undefined;
	if(m_ellipse)
		m_objectType = ObjectType::Ellipse;
	else if(m_point)
		m_objectType = ObjectType::Point;
	else if(json.count("polygon") > 0)
		m_objectType = ObjectType::Polygon;
	else if(json.count("polyline") > 0)
		m_objectType = ObjectType::Polyline;
	else if(json.count("text") > 0)
		m_objectType = ObjectType::Text;
	else if(json.count("gid") > 0)
		m_objectType = ObjectType::Object;
	else if(json.count("template") > 0)
		m_objectType = ObjectType::Template;
	else
		m_objectType = ObjectType::Rectangle;
}

/*!
 * Gets what type of object this is.
 * @return
 */

tson::ObjectType tson::Object::getObjectType() const
{
	return m_objectType;
}

/*!
 * 'ellipse': Used to mark an object as an ellipse
 * @return
 */
bool tson::Object::isEllipse() const
{
	return m_ellipse;
}

/*!
 * 'gid': GID, only if object comes from a Tilemap
 * @return
 */
uint32_t tson::Object::getGid() const
{
	return m_gid;
}

/*!
 * x = 'width' (Width in pixels), y = 'height' (Height in pixels). Ignored if using a gid.)
 * @return
 */
const tson::Vector2i &tson::Object::getSize() const
{
	return m_size;
}

/*!
 * 'id': Incremental id - unique across all objects
 * @return
 */
int tson::Object::getId() const
{
	return m_id;
}

/*!
 * 'name': String assigned to name field in editor
 * @return
 */
const std::string &tson::Object::getName() const
{
	return m_name;
}

/*!
 * 'point': Used to mark an object as a point
 * @return true if the object is of type point
 */
bool tson::Object::isPoint() const
{
	return m_point;
}

/*!
 * 'rotation': Angle in degrees clockwise
 * @return
 */
float tson::Object::getRotation() const
{
	return m_rotation;
}

/*!
 * 'template': Reference to a template file, in case object is a template instance
 * @return
 */
const std::string &tson::Object::getTemplate() const
{
	return m_template;
}

/*!
 * 'type': String assigned to type field in editor
 * @return
 */
const std::string &tson::Object::getType() const
{
	return m_type;
}

/*!
 * 'visible': Whether object is shown in editor.
 * @return
 */
bool tson::Object::isVisible() const
{
	return m_visible;
}

/*!
 * 'x' and 'y': coordinate in pixels
 * @return
 */
const tson::Vector2i &tson::Object::getPosition() const
{
	return m_position;
}

/*!
 * 'polygon': A list of x,y coordinates in pixels.
 * If this is a Polygon type, this function will return the points used to create it
 * @return
 */
const std::vector<tson::Vector2i> &tson::Object::getPolygons() const
{
	return m_polygon;
}

/*!
 * 'polyline': A list of x,y coordinates in pixels
 * If this is a Polyline type, this function will return the points used to create it
 * @return
 */
const std::vector<tson::Vector2i> &tson::Object::getPolylines() const
{
	return m_polyline;
}

/*!
 * 'properties': A list of properties (name, value, type).
 * @return
 */
tson::PropertyCollection &tson::Object::getProperties()
{
	return m_properties;
}

/*!
 * 'type': String assigned to type field in editor
 * @return
 */
const tson::Text &tson::Object::getText() const
{
	return m_text;
}

/*!
 * Shortcut for getting a property object. Alternative to getProperties().getProperty("<name>");
 * @param name Name of the property
 * @return
 */
tson::Property *tson::Object::getProp(const std::string &name)
{
	if(m_properties.hasProperty(name))
		return m_properties.getProperty(name);
	return nullptr;
}

/*!
 * Get all flip flags
 * @return
 */
tson::TileFlipFlags tson::Object::getFlipFlags() const
{
	return m_flipFlags;
}

/*!
 *
 * @param flags Which flags to check for. Several flags can be checked at once using the bitwise or operator.
 * Example:
 * hasFlipFlags(TileFlipFlags::Vertically | TileFlipFlags::Horizontally)
 *
 * @return true if the flag(s) specified are set
 */
bool tson::Object::hasFlipFlags(TileFlipFlags flags)
{
	return ((m_flipFlags & flags) == flags) ? true : false;
}

#endif //TILESON_OBJECT_HPP

/*** End of inlined file: Object.hpp ***/


/*** Start of inlined file: TileObject.hpp ***/
//
// Created by robin on 26.07.2020.
//

#ifndef TILESON_TILEOBJECT_HPP
#define TILESON_TILEOBJECT_HPP


/*** Start of inlined file: Rect.hpp ***/
//
// Created by robin on 24.07.2020.
//

#ifndef TILESON_RECT_HPP
#define TILESON_RECT_HPP

namespace tson
{
	class Rect
	{
		public:

			inline Rect();
			inline Rect(int x_, int y_, int width_, int height_);

			inline bool operator==(const Rect &rhs) const;
			inline bool operator!=(const Rect &rhs) const;

			int x;
			int y;
			int width;
			int height;
	};

	Rect::Rect()
	{

	}

	Rect::Rect(int x_, int y_, int width_, int height_)
	{
		x = x_;
		y = y_;
		width = width_;
		height = height_;
	}

	bool Rect::operator==(const Rect &rhs) const
	{
		return x == rhs.x &&
			   y == rhs.y &&
			   width == rhs.width &&
			   height == rhs.height;
	}

	bool Rect::operator!=(const Rect &rhs) const
	{
		return !(rhs == *this);
	}
}

#endif //TILESON_RECT_HPP

/*** End of inlined file: Rect.hpp ***/

namespace tson
{
	class Tile;
	class TileObject
	{
		public:
			inline TileObject() = default;
			inline TileObject(const std::tuple<int, int> &posInTileUnits, tson::Tile *tile);

			inline void initialize(const std::tuple<int, int> &posInTileUnits, tson::Tile *tile); //Defined in tileson_forward.hpp

			inline Tile *getTile() const;
			inline const Vector2i &getPositionInTileUnits() const;
			inline const Vector2f &getPosition() const;
			inline const tson::Rect &getDrawingRect() const; //Defined in tileson_forward.hpp

		private:
			tson::Tile *m_tile;
			tson::Vector2i m_posInTileUnits;
			tson::Vector2f m_position;

	};

	TileObject::TileObject(const std::tuple<int, int> &posInTileUnits, tson::Tile *tile)
	{
		initialize(posInTileUnits, tile);
	}

	/*!
	 * Get a pointer to the related tile
	 * @return
	 */
	Tile *TileObject::getTile() const
	{
		return m_tile;
	}

	/*!
	 * Gets the position of the tile in tile units
	 * @return
	 */
	const Vector2i &TileObject::getPositionInTileUnits() const
	{
		return m_posInTileUnits;
	}

	/*!
	 * Gets the position of the tile in pixels.
	 * @return
	 */
	const Vector2f &TileObject::getPosition() const
	{
		return m_position;
	}
}

#endif //TILESON_TILEOBJECT_HPP

/*** End of inlined file: TileObject.hpp ***/


/*** Start of inlined file: FlaggedTile.hpp ***/
//
// Created by robin on 13.11.2020.
//

#ifndef TILESON_FLAGGEDTILE_HPP
#define TILESON_FLAGGEDTILE_HPP

namespace tson
{
	class FlaggedTile
	{

		public:
			FlaggedTile(size_t x_, size_t y_, uint32_t id_, uint32_t tileId_) : x {x_}, y {y_}, id {id_}, tileId {tileId_}
			{

			}
			size_t x;
			size_t y;
			/*! Full ID, including flag */
			uint32_t id;
			/*! ID of the flagged tile */
			uint32_t tileId;
	};
}
#endif //TILESON_FLAGGEDTILE_HPP

/*** End of inlined file: FlaggedTile.hpp ***/

namespace tson
{
	class Tile;
	class Map;

	class Layer
	{
		public:
			inline Layer() = default;
			inline Layer(IJson &json, tson::Map *map);
			inline bool parse(IJson &json, tson::Map *map);

			[[nodiscard]] inline const std::string &getCompression() const;
			[[nodiscard]] inline const std::vector<uint32_t> &getData() const;
			[[nodiscard]] inline const std::string &getBase64Data() const;
			[[nodiscard]] inline const std::string &getDrawOrder() const;
			[[nodiscard]] inline const std::string &getEncoding() const;
			[[nodiscard]] inline int getId() const;
			[[nodiscard]] inline const std::string &getImage() const;
			[[nodiscard]] inline const std::string &getName() const;
			[[nodiscard]] inline const Vector2f &getOffset() const;
			[[nodiscard]] inline float getOpacity() const;
			[[nodiscard]] inline const Vector2i &getSize() const;
			[[nodiscard]] inline const Colori &getTransparentcolor() const;

			[[nodiscard]] inline LayerType getType() const;

			[[nodiscard]] inline const std::string &getTypeStr() const;
			[[nodiscard]] inline bool isVisible() const;
			[[nodiscard]] inline int getX() const;
			[[nodiscard]] inline int getY() const;

			[[nodiscard]] inline std::vector<tson::Chunk> &getChunks();
			[[nodiscard]] inline std::vector<tson::Layer> &getLayers();
			[[nodiscard]] inline std::vector<tson::Object> &getObjects();
			[[nodiscard]] inline PropertyCollection &getProperties();

			inline tson::Object *getObj(int id);
			inline tson::Object *firstObj(const std::string &name);
			inline std::vector<tson::Object> getObjectsByName(const std::string &name);
			inline std::vector<tson::Object> getObjectsByType(tson::ObjectType type);

			template <typename T>
			inline T get(const std::string &name);
			inline tson::Property * getProp(const std::string &name);

			inline void assignTileMap(std::map<uint32_t, tson::Tile*> *tileMap);
			inline void createTileData(const Vector2i &mapSize, bool isInfiniteMap);

			[[nodiscard]] inline const std::map<std::tuple<int, int>, tson::Tile *> &getTileData() const;
			inline tson::Tile * getTileData(int x, int y);

			//v1.2.0-stuff
			[[nodiscard]] inline const Colori &getTintColor() const;
			[[nodiscard]] inline tson::Map *getMap() const;

			[[nodiscard]] inline const std::map<std::tuple<int, int>, tson::TileObject> &getTileObjects() const;
			inline tson::TileObject * getTileObject(int x, int y);
			[[nodiscard]] inline const std::set<uint32_t> &getUniqueFlaggedTiles() const;
			inline void resolveFlaggedTiles();

		private:
			inline void setTypeByString();

			std::vector<tson::Chunk>                       m_chunks; 	                      /*! 'chunks': Array of chunks (optional). tilelayer only. */
			std::string                                    m_compression;                     /*! 'compression': zlib, gzip or empty (default). tilelayer only. */
			std::vector<uint32_t>                          m_data;                            /*! 'data' (when uint array): Array of unsigned int (GIDs) or base64-encoded
																							   *   data. tilelayer only. */
			std::string                                    m_base64Data;                      /*! 'data' (when string):     Array of unsigned int (GIDs) or base64-encoded
																							   *   data. tilelayer only. */
			std::string                                    m_drawOrder;                       /*! 'draworder': topdown (default) or index. objectgroup only. */
			std::string                                    m_encoding;                        /*! 'encoding': csv (default) or base64. tilelayer only. */
			int                                            m_id{};                            /*! 'id': Incremental id - unique across all layers */
			std::string                                    m_image;                           /*! 'image': Image used by this layer. imagelayer only. */
			std::vector<tson::Layer>                       m_layers; 	                      /*! 'layers': Array of layers. group on */
			std::string                                    m_name;                            /*! 'name': Name assigned to this layer */
			std::vector<tson::Object>                      m_objects;                         /*! 'objects': Array of objects. objectgroup only. */
			tson::Vector2f                                 m_offset;                          /*! 'offsetx' and 'offsety': Horizontal and Vertical layer offset in pixels
																							   *  (default: {0, 0}) */
			float                                          m_opacity{};                       /*! 'opacity': Value between 0 and 1 */
			tson::PropertyCollection                       m_properties; 	                  /*! 'properties': A list of properties (name, value, type). */
			tson::Vector2i                                 m_size;                            /*! x = 'width': (Column count. Same as map width for fixed-size maps.)
																								  y = 'height': Row count. Same as map height for fixed-size maps. */
			tson::Colori                                   m_transparentcolor;                /*! 'transparentcolor': Hex-formatted color (#RRGGBB) (optional, imagelayer only */
			std::string                                    m_typeStr;                         /*! 'type': tilelayer, objectgroup, imagelayer or group */
			LayerType                                      m_type {LayerType::Undefined};     /*! Layer type as enum*/
			bool                                           m_visible{};                       /*! 'visible': Whether layer is shown or hidden in editor */
			int                                            m_x{};                             /*! 'x': Horizontal layer offset in tiles. Always 0. */
			int                                            m_y{};                             /*! 'y': Vertical layer offset in tiles. Always 0. */

			std::map<uint32_t, tson::Tile*>                *m_tileMap;
			std::map<std::tuple<int, int>, tson::Tile*>    m_tileData;                        /*! Key: Tuple of x and y pos in tile units. */

			//v1.2.0-stuff
			tson::Colori                                        m_tintcolor;                  /*! 'tintcolor': Hex-formatted color (#RRGGBB or #AARRGGBB) that is multiplied with
																							   *        any graphics drawn by this layer or any child layers (optional). */
			inline void decompressData();                                                     /*! Defined in tileson_forward.hpp */
			inline void queueFlaggedTile(size_t x, size_t y, uint32_t id);                    /*! Queue a flagged tile */

			tson::Map *                                         m_map;                        /*! The map who owns this layer */
			std::map<std::tuple<int, int>, tson::TileObject>    m_tileObjects;
			std::set<uint32_t>                                  m_uniqueFlaggedTiles;
			std::vector<tson::FlaggedTile>                      m_flaggedTiles;

	};

	/*!
	 * A shortcut for getting a property. Alternative to getProperties().getValue<T>("<name>")
	 * @tparam T The template value
	 * @param name Name of the property
	 * @return The actual value, if it exists. Otherwise: The default value of the type.
	 */
	template<typename T>
	T Layer::get(const std::string &name)
	{
		return m_properties.getValue<T>(name);
	}
}

/*!
 * Parses a Tiled layer from json
 * @param json
 */
tson::Layer::Layer(IJson &json, tson::Map *map)
{
	parse(json, map);
}

void tson::Layer::queueFlaggedTile(size_t x, size_t y, uint32_t id)
{
	uint32_t tileId = id;
	tileId &= ~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG | FLIPPED_DIAGONALLY_FLAG);
	m_uniqueFlaggedTiles.insert(id);
	m_flaggedTiles.emplace_back(x, y, id, tileId);
}

/*!
 * Parses a Tiled layer from json
 * @param json
 * @return true if all mandatory fields was found. false otherwise.
 */
bool tson::Layer::parse(IJson &json, tson::Map *map)
{
	m_map = map;

	bool allFound = true;
	if(json.count("tintcolor") > 0) m_tintcolor = tson::Colori(json["tintcolor"].get<std::string>()); //Optional
	if(json.count("compression") > 0) m_compression = json["compression"].get<std::string>(); //Optional
	if(json.count("draworder") > 0) m_drawOrder = json["draworder"].get<std::string>(); //Optional
	if(json.count("encoding") > 0) m_encoding = json["encoding"].get<std::string>(); //Optional
	if(json.count("id") > 0) m_id = json["id"].get<int>(); //Optional
	if(json.count("image") > 0) m_image = json["image"].get<std::string>(); //Optional
	if(json.count("name") > 0) m_name = json["name"].get<std::string>(); else allFound = false;
	if(json.count("offsetx") > 0 && json.count("offsety") > 0)
		m_offset = {json["offsetx"].get<float>(), json["offsety"].get<float>()}; //Optional
	if(json.count("opacity") > 0) m_opacity = json["opacity"].get<float>(); else allFound = false;
	if(json.count("width") > 0 && json.count("height") > 0)
		m_size = {json["width"].get<int>(), json["height"].get<int>()}; //else allFound = false; - Not mandatory for all layers!
	if(json.count("transparentcolor") > 0) m_transparentcolor = tson::Colori(json["transparentcolor"].get<std::string>()); //Optional
	if(json.count("type") > 0) m_typeStr = json["type"].get<std::string>(); else allFound = false;
	if(json.count("visible") > 0) m_visible = json["visible"].get<bool>(); else allFound = false;
	if(json.count("x") > 0) m_x = json["x"].get<int>(); else allFound = false;
	if(json.count("y") > 0) m_y = json["y"].get<int>(); else allFound = false;

	//Handle DATA (Optional)
	if(json.count("data") > 0)
	{
		if(json["data"].isArray())
		{
			auto &array = json.array("data");
			std::for_each(array.begin(), array.end(), [&](std::unique_ptr<IJson> &item) { m_data.push_back(item->get<uint32_t>()); });
		}
		else
		{
			m_base64Data = json["data"].get<std::string>();
			decompressData();
		}
	}

	//More advanced data
	if(json.count("chunks") > 0 && json["chunks"].isArray())
	{
		auto &chunks = json.array("chunks");
		std::for_each(chunks.begin(), chunks.end(), [&](std::unique_ptr<IJson> &item) { m_chunks.emplace_back(*item); });
	}
	if(json.count("layers") > 0 && json["layers"].isArray())
	{
		auto &layers = json.array("layers");
		std::for_each(layers.begin(), layers.end(), [&](std::unique_ptr<IJson> &item) { m_layers.emplace_back(*item, m_map); });
	}
	if(json.count("objects") > 0 && json["objects"].isArray())
	{
		auto &objects = json.array("objects");
		std::for_each(objects.begin(), objects.end(), [&](std::unique_ptr<IJson> &item) { m_objects.emplace_back(*item); });
	}
	if(json.count("properties") > 0 && json["properties"].isArray())
	{
		auto &properties = json.array("properties");
		std::for_each(properties.begin(), properties.end(), [&](std::unique_ptr<IJson> &item) { m_properties.add(*item); });
	}

	setTypeByString();

	return allFound;
}

/*!
 * Copies all objects with a name that equals the parameter
 * @param name Name of the objects to return
 * @return All objects with a matching name
 */
std::vector<tson::Object> tson::Layer::getObjectsByName(const std::string &name)
{
	std::vector<tson::Object> found;

	std::copy_if(m_objects.begin(), m_objects.end(), std::back_inserter(found), [&](const tson::Object &item)
	{
		return item.getName() == name;
	});

	return found;
}

/*!
 * Copies all objects with a type that equals the parameter
 * @param type LayerType of the objects to return
 * @return All objects with a matching type
 */
std::vector<tson::Object> tson::Layer::getObjectsByType(tson::ObjectType type)
{
	std::vector<tson::Object> found;

	std::copy_if(m_objects.begin(), m_objects.end(), std::back_inserter(found), [&](const tson::Object &item)
	{
		return item.getObjectType() == type;
	});

	return found;
}

/*!
 * Returns the first object with the given name
 * @param name Name of the object to find.
 * @return A pointer to the object if found. nullptr otherwise.
 */
tson::Object *tson::Layer::firstObj(const std::string &name)
{
	auto result = std::find_if(m_objects.begin(), m_objects.end(), [&](const tson::Object &obj){return obj.getName() == name; });
	if(result == m_objects.end())
		return nullptr;

	return &result.operator*();
}

/*!
 * Get an object by ID
 * @param id Unique ID of the object
 * @return A pointer to the object if found. nullptr otherwise.
 */
tson::Object *tson::Layer::getObj(int id)
{
	auto result = std::find_if(m_objects.begin(), m_objects.end(), [&](const tson::Object &obj){return obj.getId() == id; });
	if(result == m_objects.end())
		return nullptr;

	return &result.operator*();
}

/*!
 * Set type by string
 * tilelayer, objectgroup, imagelayer or group
 */
void tson::Layer::setTypeByString()
{
	if(m_typeStr == "tilelayer") m_type = LayerType::TileLayer;
	else if(m_typeStr == "objectgroup") m_type = LayerType::ObjectGroup;
	else if(m_typeStr == "imagelayer") m_type = LayerType::ImageLayer;
	else if(m_typeStr == "group") m_type = LayerType::Group;
	else m_type = LayerType::Undefined;
}

/*!
 * 'compression': zlib, gzip or empty (default). tilelayer only.
 * @return
 */
const std::string &tson::Layer::getCompression() const
{
	return m_compression;
}

/*!
 * 'data' (when uint array): Array of unsigned int (GIDs) or base64-encoded data. tilelayer only.
 * @return
 */
const std::vector<uint32_t> &tson::Layer::getData() const
{
	return m_data;
}

/*!
 * 'data' (when string): Array of unsigned int (GIDs) or base64-encoded data. tilelayer only.
 * @return
 */
const std::string &tson::Layer::getBase64Data() const
{
	return m_base64Data;
}

/*!
 * 'draworder': topdown (default) or index. objectgroup only.
 * @return
 */
const std::string &tson::Layer::getDrawOrder() const
{
	return m_drawOrder;
}

/*!
 * 'encoding': csv (default) or base64. tilelayer only.
 * @return
 */
const std::string &tson::Layer::getEncoding() const
{
	return m_encoding;
}

/*!
 * 'id': Incremental id - unique across all layers
 * @return
 */
int tson::Layer::getId() const
{
	return m_id;
}

/*!
 * 'image': Image used by this layer. imagelayer only.
 * @return
 */
const std::string &tson::Layer::getImage() const
{
	return m_image;
}

/*!
 * 'name': Name assigned to this layer
 * @return
 */
const std::string &tson::Layer::getName() const
{
	return m_name;
}

/*!
 * 'offsetx' and 'offsety': Horizontal and Vertical layer offset in pixels (default: {0, 0})
 * @return
 */
const tson::Vector2f &tson::Layer::getOffset() const
{
	return m_offset;
}

/*!
 * 'opacity': Value between 0 and 1
 * @return
 */
float tson::Layer::getOpacity() const
{
	return m_opacity;
}

/*!
 * x = 'width': (Column count. Same as map width for fixed-size maps.)
 * y = 'height': Row count. Same as map height for fixed-size maps.
 * @return width and height as a single size
 */
const tson::Vector2i &tson::Layer::getSize() const
{
	return m_size;
}

/*!
 * 'transparentcolor': Color created from a hex color (#RRGGBB) (optional, imagelayer only)
 * @return color as color object with rgba channel.
 */
const tson::Colori &tson::Layer::getTransparentcolor() const
{
	return m_transparentcolor;
}

/*!
 * 'type': tilelayer, objectgroup, imagelayer or group
 * @return string with the object type
 */
const std::string &tson::Layer::getTypeStr() const
{
	return m_typeStr;
}

/*!
 * 'visible': Whether layer is shown or hidden in editor
 * @return
 */
bool tson::Layer::isVisible() const
{
	return m_visible;
}

/*!
 * 'x': Horizontal layer offset in tiles. Always 0.
 * @return x value (always 0 for layer)
 */
int tson::Layer::getX() const
{
	return m_x;
}

/*!
 * 'y': Horizontal layer offset in tiles. Always 0.
 * @return y value (always 0 for layer)
 */
int tson::Layer::getY() const
{
	return m_y;
}

/*!
 * 'chunks': Array of chunks (optional). tilelayer only.
 * @return
 */
std::vector<tson::Chunk> &tson::Layer::getChunks()
{
	return m_chunks;
}

/*!
 * 'layers': Array of layers. group on
 * @return
 */
std::vector<tson::Layer> &tson::Layer::getLayers()
{
	return m_layers;
}

/*!
 * 'objects': Array of objects. objectgroup only.
 * @return
 */
std::vector<tson::Object> &tson::Layer::getObjects()
{
	return m_objects;
}

/*!
 * 'properties': A list of properties (name, value, type).
 * @return
 */
tson::PropertyCollection &tson::Layer::getProperties()
{
	return m_properties;
}

/*!
 * Shortcut for getting a property object. Alternative to getProperties().getProperty("<name>");
 * @param name Name of the property
 * @return
 */
tson::Property *tson::Layer::getProp(const std::string &name)
{
	if(m_properties.hasProperty(name))
		return m_properties.getProperty(name);
	return nullptr;
}

/*!
 * Get layer type
 * @return Layer type as enum
 */
tson::LayerType tson::Layer::getType() const
{
	return m_type;
}

/*!
 * Assigns a tilemap of pointers to existing tiles.
 * @param tileMap The tilemap. key: tile id, value: pointer to Tile.
 */
void tson::Layer::assignTileMap(std::map<uint32_t, tson::Tile *> *tileMap)
{
	m_tileMap = tileMap;
}

/*!
 * Get tile data as some kind of map with x and y position with pointers to existing tiles.
 * Map only contains tiles that are not empty. x and y position is in tile units.
 *
 * Example of getting tile from the returned map:
 *
 * Tile *tile = tileData[{0, 4}];
 *
 * @return A map that represents the data returned from getData() in a 2D map with Tile pointers.
 */
const std::map<std::tuple<int, int>, tson::Tile *> &tson::Layer::getTileData() const
{
	return m_tileData;
}

/*!
 * A safe way to get tile data
 * Get tile data as some kind of map with x and y position with pointers to existing tiles.
 * Map only contains tiles that are not empty. x and y position is in tile units.
 *
 * Example of getting tile:
 * Tile *tile = layer->getTileData(0, 4)
 *
 * @param x X position in tile units
 * @param y Y position in tile units
 * @return pointer to tile, if it exists. nullptr otherwise.
 */
tson::Tile *tson::Layer::getTileData(int x, int y)
{
	return (m_tileData.count({x, y}) > 0) ? m_tileData[{x,y}] : nullptr;
}

/*!
 * Used for getting the tson::Map who is the parent of this Layer.
 * @return a pointer to the tson::Map where this layer is contained.
 */
tson::Map *tson::Layer::getMap() const
{
	return m_map;
}

/*!
 *
 * This is only supported for non-infinite maps!
 *
 * @param mapSize The size of the map
 * @param isInfiniteMap Whether or not the current map is infinte.
 */
void tson::Layer::createTileData(const Vector2i &mapSize, bool isInfiniteMap)
{
	size_t x = 0;
	size_t y = 0;
	if(!isInfiniteMap)
	{
		std::for_each(m_data.begin(), m_data.end(), [&](uint32_t tileId)
		{
			if (x == mapSize.x)
			{
				++y;
				x = 0;
			}

			if (tileId > 0 && m_tileMap->count(tileId) > 0)
			{
				m_tileData[{x, y}] = m_tileMap->at(tileId);
				m_tileObjects[{x, y}] = {{x, y}, m_tileData[{x, y}]};
			}
			else if(tileId > 0 && m_tileMap->count(tileId) == 0) //Tile with flip flags!
			{
				queueFlaggedTile(x, y, tileId);
			}
			x++;
		});

	}
}

const std::map<std::tuple<int, int>, tson::TileObject> &tson::Layer::getTileObjects() const
{
	return m_tileObjects;
}

tson::TileObject *tson::Layer::getTileObject(int x, int y)
{
	return (m_tileObjects.count({x, y}) > 0) ? &m_tileObjects[{x,y}] : nullptr;
}

const std::set<uint32_t> &tson::Layer::getUniqueFlaggedTiles() const
{
	return m_uniqueFlaggedTiles;
}

void tson::Layer::resolveFlaggedTiles()
{
	std::for_each(m_flaggedTiles.begin(), m_flaggedTiles.end(), [&](const tson::FlaggedTile &tile)
	{
		if (tile.id > 0 && m_tileMap->count(tile.id) > 0)
		{
			m_tileData[{tile.x, tile.y}] = m_tileMap->at(tile.id);
			m_tileObjects[{tile.x, tile.y}] = {{tile.x, tile.y}, m_tileData[{tile.x, tile.y}]};
		}
	});
}

/*!
 * 'tintcolor': Hex-formatted color (#RRGGBB or #AARRGGBB) that is multiplied with any graphics drawn by this layer or any child layers (optional).
 *
 * @return tintcolor
 */
const tson::Colori &tson::Layer::getTintColor() const
{
	return m_tintcolor;
}

#endif //TILESON_LAYER_HPP

/*** End of inlined file: Layer.hpp ***/


/*** Start of inlined file: Tileset.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_TILESET_HPP
#define TILESON_TILESET_HPP

//#include "../external/json.hpp"


/*** Start of inlined file: WangSet.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_WANGSET_HPP
#define TILESON_WANGSET_HPP

//#include "../external/json.hpp"

/*** Start of inlined file: WangColor.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_WANGCOLOR_HPP
#define TILESON_WANGCOLOR_HPP

//#include "../external/json.hpp"

namespace tson
{
	class WangColor
	{
		public:
			inline WangColor() = default;
			inline explicit WangColor(IJson &json);
			inline bool parse(IJson &json);

			[[nodiscard]] inline const Colori &getColor() const;
			[[nodiscard]] inline const std::string &getName() const;
			[[nodiscard]] inline float getProbability() const;
			[[nodiscard]] inline int getTile() const;

		private:
			tson::Colori      m_color;              /*! 'color': Hex-formatted color (#RRGGBB or #AARRGGBB) */
			std::string       m_name;               /*! 'name': Name of the Wang color */
			float             m_probability{};      /*! 'probability': Probability used when randomizing */
			int               m_tile{};             /*! 'tile': Local ID of tile representing the Wang color */
	};
}

tson::WangColor::WangColor(IJson &json)
{
	parse(json);
}

bool tson::WangColor::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("color") > 0) m_color = tson::Colori(json["color"].get<std::string>()); else allFound = false;
	if(json.count("name") > 0) m_name = json["name"].get<std::string>(); else allFound = false;
	if(json.count("probability") > 0) m_probability = json["probability"].get<float>(); else allFound = false;
	if(json.count("tile") > 0) m_tile = json["tile"].get<int>(); else allFound = false;

	return allFound;
}

/*!
 * 'color': Color object created from hex-formatted string (#RRGGBB or #AARRGGBB)
 * @return
 */
const tson::Colori &tson::WangColor::getColor() const
{
	return m_color;
}

/*!
 * 'name': Name of the Wang color
 * @return
 */
const std::string &tson::WangColor::getName() const
{
	return m_name;
}

/*!
 * 'probability': Probability used when randomizing
 * @return
 */
float tson::WangColor::getProbability() const
{
	return m_probability;
}

/*!
 * 'tile': Local ID of tile representing the Wang color
 * @return
 */
int tson::WangColor::getTile() const
{
	return m_tile;
}

#endif //TILESON_WANGCOLOR_HPP

/*** End of inlined file: WangColor.hpp ***/



/*** Start of inlined file: WangTile.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_WANGTILE_HPP
#define TILESON_WANGTILE_HPP

//#include "../external/json.hpp"

namespace tson
{
	class WangTile
	{
		public:
			inline WangTile() = default;
			inline explicit WangTile(IJson &json);
			inline bool parse(IJson &json);

			[[nodiscard]] inline bool hasDFlip() const;
			[[nodiscard]] inline bool hasHFlip() const;
			[[nodiscard]] inline int getTileid() const;
			[[nodiscard]] inline bool hasVFlip() const;

			[[nodiscard]] inline const std::vector<int> &getWangIds() const;

		private:
			bool                 m_dflip{};     /*! 'dflip': Tile is flipped diagonally */
			bool                 m_hflip{};     /*! 'hflip': Tile is flipped horizontally */
			int                  m_tileid{};    /*! 'tileid': Local ID of tile */
			bool                 m_vflip{};     /*! 'vflip': Tile is flipped vertically */
			std::vector<int>     m_wangId;      /*! 'wangid': Array of Wang color indexes (uchar[8])*/
	};
}

tson::WangTile::WangTile(IJson &json)
{
	parse(json);
}

/*!
 * Parses a wang tile from Tiled json.
 * @param json A Tiled json file
 * @return true if all mandatory fields were found. False otherwise.
 */
bool tson::WangTile::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("dflip") > 0) m_dflip = json["dflip"].get<bool>(); else allFound = false;
	if(json.count("hflip") > 0) m_hflip = json["hflip"].get<bool>(); else allFound = false;
	if(json.count("vflip") > 0) m_vflip = json["vflip"].get<bool>(); else allFound = false;
	if(json.count("tileid") > 0) m_tileid = json["tileid"].get<int>(); else allFound = false;

	if(json.count("wangid") > 0 && json["wangid"].isArray())
	{
		auto &wangid = json.array("wangid");
		std::for_each(wangid.begin(), wangid.end(), [&](std::unique_ptr<IJson> &item) { m_wangId.emplace_back(item->get<int>()); });
	}

	return allFound;
}

/*!
 * 'dflip': Tile is flipped diagonally
 * @return
 */
bool tson::WangTile::hasDFlip() const
{
	return m_dflip;
}

/*!
 * 'hflip': Tile is flipped horizontally
 * @return
 */
bool tson::WangTile::hasHFlip() const
{
	return m_hflip;
}

/*!
 * 'tileid': Local ID of tile
 * @return
 */
int tson::WangTile::getTileid() const
{
	return m_tileid;
}

/*!
 * 'vflip': Tile is flipped vertically
 * @return
 */
bool tson::WangTile::hasVFlip() const
{
	return m_vflip;
}

/*!
 * 'wangid': Array of Wang color indexes (uchar[8])
 * @return
 */
const std::vector<int> &tson::WangTile::getWangIds() const
{
	return m_wangId;
}

#endif //TILESON_WANGTILE_HPP

/*** End of inlined file: WangTile.hpp ***/

namespace tson
{
	class WangSet
	{
		public:
			inline WangSet() = default;
			inline explicit WangSet(IJson &json);
			inline bool parse(IJson &json);

			[[nodiscard]] inline const std::string &getName() const;
			[[nodiscard]] inline int getTile() const;

			[[nodiscard]] inline const std::vector<tson::WangTile> &getWangTiles() const;
			[[nodiscard]] inline const std::vector<tson::WangColor> &getCornerColors() const;
			[[nodiscard]] inline const std::vector<tson::WangColor> &getEdgeColors() const;

			inline PropertyCollection &getProperties();

			template <typename T>
			inline T get(const std::string &name);
			inline tson::Property * getProp(const std::string &name);

		private:
			std::string                  m_name;          /*! 'name': Name of the Wang set */
			int                          m_tile{};        /*! 'tile': Local ID of tile representing the Wang set */
			std::vector<tson::WangTile>  m_wangTiles;     /*! 'wangtiles': Array of Wang tiles */
			std::vector<tson::WangColor> m_cornerColors;  /*! 'cornercolors': Array of Wang colors */
			std::vector<tson::WangColor> m_edgeColors;    /*! 'edgecolors': Array of Wang colors */
			tson::PropertyCollection     m_properties; 	  /*! 'properties': A list of properties (name, value, type). */

	};

	/*!
	 * A shortcut for getting a property. Alternative to getProperties().getValue<T>("<name>")
	 * @tparam T The template value
	 * @param name Name of the property
	 * @return The actual value, if it exists. Otherwise: The default value of the type.
	 */
	template<typename T>
	T tson::WangSet::get(const std::string &name)
	{
		return m_properties.getValue<T>(name);
	}
}

tson::WangSet::WangSet(IJson &json)
{
	parse(json);
}

bool tson::WangSet::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("tile") > 0) m_tile = json["tile"].get<int>(); else allFound = false;
	if(json.count("name") > 0) m_name = json["name"].get<std::string>(); else allFound = false;

	//More advanced data
	if(json.count("wangtiles") > 0 && json["wangtiles"].isArray())
	{
		auto &wangtiles = json.array("wangtiles");
		std::for_each(wangtiles.begin(), wangtiles.end(), [&](std::unique_ptr<IJson> &item) { m_wangTiles.emplace_back(*item); });
	}
	if(json.count("cornercolors") > 0 && json["cornercolors"].isArray())
	{
		auto &cornercolors = json.array("cornercolors");
		std::for_each(cornercolors.begin(), cornercolors.end(), [&](std::unique_ptr<IJson> &item) { m_cornerColors.emplace_back(*item); });
	}
	if(json.count("edgecolors") > 0 && json["edgecolors"].isArray())
	{
		auto &edgecolors = json.array("edgecolors");
		std::for_each(edgecolors.begin(), edgecolors.end(), [&](std::unique_ptr<IJson> &item) { m_edgeColors.emplace_back(*item); });
	}
	if(json.count("properties") > 0 && json["properties"].isArray())
	{
		auto &properties = json.array("properties");
		std::for_each(properties.begin(), properties.end(), [&](std::unique_ptr<IJson> &item) { m_properties.add(*item); });
	}

	return allFound;
}

/*!
 * 'name': Name of the Wang set
 * @return
 */
const std::string &tson::WangSet::getName() const
{
	return m_name;
}

/*!
 * 'tile': Local ID of tile representing the Wang set
 * @return
 */
int tson::WangSet::getTile() const
{
	return m_tile;
}

/*!
 * 'wangtiles': Array of Wang tiles
 * @return
 */
const std::vector<tson::WangTile> &tson::WangSet::getWangTiles() const
{
	return m_wangTiles;
}

/*!
 * 'cornercolors': Array of Wang colors
 * @return
 */
const std::vector<tson::WangColor> &tson::WangSet::getCornerColors() const
{
	return m_cornerColors;
}

/*!
 * 'edgecolors': Array of Wang colors
 * @return
 */
const std::vector<tson::WangColor> &tson::WangSet::getEdgeColors() const
{
	return m_edgeColors;
}

/*!
 * 'properties': A list of properties (name, value, type).
 * @return
 */
tson::PropertyCollection &tson::WangSet::getProperties()
{
	return m_properties;
}

/*!
 * Shortcut for getting a property object. Alternative to getProperties().getProperty("<name>");
 * @param name Name of the property
 * @return
 */
tson::Property *tson::WangSet::getProp(const std::string &name)
{
	if(m_properties.hasProperty(name))
		return m_properties.getProperty(name);

	return nullptr;
}

#endif //TILESON_WANGSET_HPP

/*** End of inlined file: WangSet.hpp ***/


/*** Start of inlined file: Tile.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_TILE_HPP
#define TILESON_TILE_HPP

//#include "../external/json.hpp"


/*** Start of inlined file: Frame.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_FRAME_HPP
#define TILESON_FRAME_HPP

//#include "../external/json.hpp"

namespace tson
{
	class Frame
	{
		public:
			inline Frame() = default;
			inline Frame(int duration, int tileId);
			inline explicit Frame(IJson &json);

			inline bool parse(IJson &json);

			[[nodiscard]] inline int getDuration() const;
			[[nodiscard]] inline int getTileId() const;

		private:
			int m_duration {};  /*! 'duration': Frame duration in milliseconds */
			int m_tileId {};    /*! 'tileid': Local tile ID representing this frame */
	};
}

/*!
 *
 * @param duration duration in milliseconds
 * @param tileId TileId
 */
tson::Frame::Frame(int duration, int tileId) : m_duration {duration}, m_tileId {tileId}
{

}

/*!
 * Parses frame data from json
 * @param json
 */
tson::Frame::Frame(IJson &json)
{
	parse(json);
}

/*!
 * Parses frame data from json
 * @param json
 * @return true if all mandatory fields was found. false otherwise.
 */
bool tson::Frame::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("duration") > 0) m_duration = json["duration"].get<int>(); else allFound = false;
	if(json.count("tileid") > 0) m_tileId = json["tileid"].get<int>(); else allFound = false;

	return allFound;
}

/*!
 * 'duration': Frame duration in milliseconds
 * @return Duration in milliseconds
 */
int tson::Frame::getDuration() const
{
	return m_duration;
}

/*!
 * 'tileid': Local tile ID representing this frame
 * @return tile id
 */
int tson::Frame::getTileId() const
{
	return m_tileId;
}

#endif //TILESON_FRAME_HPP

/*** End of inlined file: Frame.hpp ***/

namespace tson
{
	class Tileset;

	class Tile
	{
		public:
			inline Tile() = default;
			inline Tile(IJson &json, tson::Tileset *tileset, tson::Map *map);
			inline Tile(uint32_t id, tson::Tileset *tileset, tson::Map *map);
			inline Tile(uint32_t id, tson::Map *map); //v1.2.0
			inline bool parse(IJson &json, tson::Tileset *tileset, tson::Map *map);
			inline bool parseId(IJson &json);

			[[nodiscard]] inline uint32_t getId() const;

			[[nodiscard]] inline const fs::path &getImage() const;

			[[nodiscard]] inline const Vector2i &getImageSize() const;
			[[nodiscard]] inline const std::string &getType() const;

			[[nodiscard]] inline const std::vector<tson::Frame> &getAnimation() const;
			[[nodiscard]] inline const Layer &getObjectgroup() const;
			[[nodiscard]] inline PropertyCollection &getProperties();
			[[nodiscard]] inline const std::vector<int> &getTerrain() const;

			template <typename T>
			inline T get(const std::string &name);
			inline tson::Property * getProp(const std::string &name);

			//v1.2.0-stuff
			inline void setProperties(const tson::PropertyCollection &properties);

			inline tson::Tileset * getTileset() const;
			inline tson::Map * getMap() const;
			inline const tson::Rect &getDrawingRect() const;
			inline const tson::Vector2f getPosition(const std::tuple<int, int> &tileDataPos);
			inline const tson::Vector2i getPositionInTileUnits(const std::tuple<int, int> &tileDataPos);
			inline const tson::Vector2i getTileSize() const;                       /*! Declared in tileson_forward.hpp */

			[[nodiscard]] inline TileFlipFlags getFlipFlags() const;
			inline bool hasFlipFlags(TileFlipFlags flags);
			[[nodiscard]] inline uint32_t getGid() const;

			inline void addTilesetAndPerformCalculations(tson::Tileset *tileset); //v1.2.0

		private:
			std::vector<tson::Frame>    m_animation; 	    /*! 'animation': Array of Frames */
			uint32_t                    m_id {};            /*! 'id': Local ID of the tile */

			fs::path                    m_image;            /*! 'image': Image representing this tile (optional)*/

			tson::Vector2i              m_imageSize;        /*! x = 'imagewidth' and y = 'imageheight': in pixels */
			tson::Layer                 m_objectgroup; 	 	/*! 'objectgroup': Layer with type objectgroup (optional) */
			tson::PropertyCollection    m_properties; 	    /*! 'properties': A list of properties (name, value, type). */
			std::vector<int>            m_terrain;          /*! 'terrain': Index of terrain for each corner of tile */
			std::string                 m_type;             /*! 'type': The type of the tile (optional) */

			//v1.2.0-stuff
			uint32_t                    m_gid {};                                    /*! id without flip flags */
			tson::Tileset *             m_tileset;                                   /*! A pointer to the tileset where this Tile comes from */
			tson::Map *                 m_map;                                       /*! A pointer to the map where this tile is contained */
			tson::Rect                  m_drawingRect;                               /*! A rect that shows which part of the tileset that is used for this tile */
			tson::TileFlipFlags         m_flipFlags = TileFlipFlags::None;           /*! Resolved using bit 32, 31 and 30 from gid */
			inline void performDataCalculations();                                   /*! Declared in tileson_forward.hpp - Calculate all the values used in the tile class. */
			inline void manageFlipFlagsByIdThenRemoveFlags(uint32_t &id);
			friend class Layer;
	};

	/*!
	 * A shortcut for getting a property. Alternative to getProperties().getValue<T>("<name>")
	 * @tparam T The template value
	 * @param name Name of the property
	 * @return The actual value, if it exists. Otherwise: The default value of the type.
	 */
	template<typename T>
	T tson::Tile::get(const std::string &name)
	{
		return m_properties.getValue<T>(name);
	}
}

tson::Tile::Tile(IJson &json, tson::Tileset *tileset, tson::Map *map)
{
	parse(json, tileset, map);
}

/*!
 * Used in cases where you have a tile without any property
 * @param id
 */
tson::Tile::Tile(uint32_t id, tson::Tileset *tileset, tson::Map *map) : m_id {id}, m_gid {id}
{
	m_tileset = tileset;
	m_map = map;
	manageFlipFlagsByIdThenRemoveFlags(m_gid);
	performDataCalculations();
}

/*!
 * Used in cases where you have a FLIP FLAGGED tile
 * @param id
 */
tson::Tile::Tile(uint32_t id, tson::Map *map) : m_id {id}, m_gid {id}
{
	m_map = map;
	manageFlipFlagsByIdThenRemoveFlags(m_gid);
}

/*!
 * For flip flagged tiles, tilesets must be resolved later.
 * @param tileset
 */
void tson::Tile::addTilesetAndPerformCalculations(tson::Tileset *tileset)
{
	m_tileset = tileset;
	performDataCalculations();
}

/*!
 * Parses a tile from a Tiled json. id on tile is store as id + 1 to match the references in data containers.
 * @param json
 * @return
 */
bool tson::Tile::parse(IJson &json, tson::Tileset *tileset, tson::Map *map)
{
	m_tileset = tileset;
	m_map = map;

	if(json.count("image") > 0) m_image = fs::path(json["image"].get<std::string>()); //Optional

	bool allFound = parseId(json);

	if(json.count("type") > 0) m_type = json["type"].get<std::string>(); //Optional
	if(json.count("objectgroup") > 0) m_objectgroup = tson::Layer(json["objectgroup"], m_map); //Optional

	if(json.count("imagewidth") > 0 && json.count("imageheight") > 0)
		m_imageSize = {json["imagewidth"].get<int>(), json["imageheight"].get<int>()}; //Optional

	//More advanced data
	if(json.count("animation") > 0 && json["animation"].isArray())
	{
		auto &animation = json.array("animation");
		std::for_each(animation.begin(), animation.end(), [&](std::unique_ptr<IJson> &item) { m_animation.emplace_back(*item); });
	}
	if(json.count("terrain") > 0 && json["terrain"].isArray())
	{
		auto &terrain = json.array("terrain");
		std::for_each(terrain.begin(), terrain.end(), [&](std::unique_ptr<IJson> &item) { m_terrain.emplace_back(item->get<int>()); });
	}

	if(json.count("properties") > 0 && json["properties"].isArray())
	{
		auto &properties = json.array("properties");
		std::for_each(properties.begin(), properties.end(), [&](std::unique_ptr<IJson> &item) { m_properties.add(*item); });
	}

	performDataCalculations();

	return allFound;
}

/*!
 * 'id': Local ID of the tile
 * @return
 */
uint32_t tson::Tile::getId() const
{
	return m_id;
}

/*!
 * 'image': Image representing this tile (optional)
 * @return
 */

const fs::path &tson::Tile::getImage() const { return m_image; }

/*!
 * x = 'imagewidth' and y = 'imageheight': in pixels
 * @return
 */
const tson::Vector2i &tson::Tile::getImageSize() const
{
	return m_imageSize;
}

/*!
 * 'type': The type of the tile (optional)
 * @return
 */
const std::string &tson::Tile::getType() const
{
	return m_type;
}

/*!
 * 'animation': Array of Frames
 * @return
 */
const std::vector<tson::Frame> &tson::Tile::getAnimation() const
{
	return m_animation;
}

/*!
 * 'objectgroup': Layer with type objectgroup (optional)
 * @return
 */
const tson::Layer &tson::Tile::getObjectgroup() const
{
	return m_objectgroup;
}

/*!
 * 'properties': A list of properties (name, value, type).
 * @return
 */
tson::PropertyCollection &tson::Tile::getProperties()
{
	return m_properties;
}

/*!
 * 'terrain': Index of terrain for each corner of tile
 * @return
 */
const std::vector<int> &tson::Tile::getTerrain() const
{
	return m_terrain;
}

/*!
 * Shortcut for getting a property object. Alternative to getProperties().getProperty("<name>");
 * @param name Name of the property
 * @return
 */
tson::Property *tson::Tile::getProp(const std::string &name)
{
	if(m_properties.hasProperty(name))
		return m_properties.getProperty(name);

	return nullptr;
}

/*!
 * Used for getting the tson::Tileset who is the parent of this Tile.
 * @return a pointer to the tson::Tileset where this tile is contained.
 */
tson::Tileset *tson::Tile::getTileset() const
{
	return m_tileset;
}

/*!
 * Used for getting the tson::Map who is the parent of this Tile.
 * @return a pointer to the tson::Map where this tile is contained.
 */
tson::Map *tson::Tile::getMap() const
{
	return m_map;
}

/*!
 * Get the information needed to draw the Tile based on its current tileset
 * @return a tson::Rect containing the information needed to draw the tile.
 */
const tson::Rect &tson::Tile::getDrawingRect() const
{
	return m_drawingRect;
}

/*!
 * Helper function.
 *
 * Get the position of the tile in tile units.
 * The size of each unit is determined by the tile size property of the map.
 * Example: If the tile size is 16x16 in the map, a tile unit of [2, 4] would be [32, 64] in pixels.
 * If you want the position in pixels: use getPosition() instead.
 *
 * @return Position of tile in tile units.
 */
const tson::Vector2i tson::Tile::getPositionInTileUnits(const std::tuple<int, int> &tileDataPos)
{
	return {std::get<0>(tileDataPos), std::get<1>(tileDataPos)};
}

void tson::Tile::manageFlipFlagsByIdThenRemoveFlags(uint32_t &id)
{
	if (id & FLIPPED_HORIZONTALLY_FLAG) m_flipFlags |= TileFlipFlags::Horizontally;
	if (id & FLIPPED_VERTICALLY_FLAG) m_flipFlags |= TileFlipFlags::Vertically;
	if (id & FLIPPED_DIAGONALLY_FLAG) m_flipFlags |= TileFlipFlags::Diagonally;

	id &= ~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG | FLIPPED_DIAGONALLY_FLAG);
}

tson::TileFlipFlags tson::Tile::getFlipFlags() const
{
	return m_flipFlags;
}

/*!
 *
 * @param flags Which flags to check for. Several flags can be checked at once using the bitwise or operator.
 * Example:
 * hasFlipFlags(TileFlipFlags::Vertically | TileFlipFlags::Horizontally)
 *
 * @return true if the flag(s) specified are set
 */
bool tson::Tile::hasFlipFlags(tson::TileFlipFlags flags)
{
	return ((m_flipFlags & flags) == flags) ? true : false;
}

uint32_t tson::Tile::getGid() const
{
	return m_gid;
}

void tson::Tile::setProperties(const tson::PropertyCollection &properties)
{
	m_properties = properties;
}

#endif //TILESON_TILE_HPP

/*** End of inlined file: Tile.hpp ***/


/*** Start of inlined file: Terrain.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_TERRAIN_HPP
#define TILESON_TERRAIN_HPP

//#include "../external/json.hpp"

namespace tson
{
	class Terrain
	{
		public:
			inline Terrain() = default;
			inline Terrain(std::string name, int tile);
			inline explicit Terrain(IJson &json);

			inline bool parse(IJson &json);

			[[nodiscard]] inline const std::string &getName() const;
			[[nodiscard]] inline int getTile() const;
			[[nodiscard]] inline PropertyCollection &getProperties();

			template <typename T>
			inline T get(const std::string &name);
			inline tson::Property * getProp(const std::string &name);

		private:
			std::string                 m_name;        /*! 'name': Name of terrain */
			int                         m_tile {};     /*! 'tile': Local ID of tile representing terrain */
			tson::PropertyCollection    m_properties;  /*! 'properties': A list of properties (name, value, type). */
	};

	/*!
	 * A shortcut for getting a property. Alternative to getProperties().getValue<T>("<name>")
	 * @tparam T The template value
	 * @param name Name of the property
	 * @return The actual value, if it exists. Otherwise: The default value of the type.
	 */
	template<typename T>
	T tson::Terrain::get(const std::string &name)
	{
		return m_properties.getValue<T>(name);
	}
}

tson::Terrain::Terrain(std::string name, int tile) : m_name {std::move(name)}, m_tile {tile}
{

}

tson::Terrain::Terrain(IJson &json)
{
	parse(json);
}

bool tson::Terrain::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("name") > 0) m_name = json["name"].get<std::string>(); else allFound = false;
	if(json.count("tile") > 0) m_tile = json["tile"].get<int>(); else allFound = false;

	if(json.count("properties") > 0 && json["properties"].isArray())
	{
		auto &properties = json.array("properties");
		std::for_each(properties.begin(), properties.end(), [&](std::unique_ptr<IJson> &item) { m_properties.add(*item); });
	}

	return allFound;
}

/*!
 * 'name': Name of terrain
 * @return
 */
const std::string &tson::Terrain::getName() const
{
	return m_name;
}

/*!
 * 'tile': Local ID of tile representing terrain
 * @return
 */
int tson::Terrain::getTile() const
{
	return m_tile;
}

/*!
 * 'properties': A list of properties (name, value, type). *Missing from the official Tiled documentation...*
 * @return
 */
tson::PropertyCollection &tson::Terrain::getProperties()
{
	return m_properties;
}

/*!
 * Shortcut for getting a property object. Alternative to getProperties().getProperty("<name>");
 * @param name Name of the property
 * @return
 */
tson::Property *tson::Terrain::getProp(const std::string &name)
{
	if(m_properties.hasProperty(name))
		return m_properties.getProperty(name);
	return nullptr;
}

#endif //TILESON_TERRAIN_HPP

/*** End of inlined file: Terrain.hpp ***/


/*** Start of inlined file: Grid.hpp ***/
//
// Created by robin on 22.03.2020.
//

#ifndef TILESON_GRID_HPP
#define TILESON_GRID_HPP

#include <string>
//#include "../external/json.hpp"

namespace tson
{
	class Grid
	{
		public:
			inline Grid() = default;
			inline explicit Grid(IJson &json);

			inline bool parse(IJson &json);

			[[nodiscard]] inline const std::string &getOrientation() const;
			[[nodiscard]] inline const Vector2i &getSize() const;

		private:
			std::string m_orientation; /*! 'orientation': Orientation of the grid for the tiles in this tileset (orthogonal or isometric) */
			tson::Vector2i m_size; /*! 'width' and 'height': Size. */
	};
}

/*!
 * Parses Tiled grid data from json
 * @param json
 */
tson::Grid::Grid(IJson &json)
{
	parse(json);
}

/*!
 * Parses Tiled grid data from json
 * @param json
 * @return true if all mandatory fields was found. false otherwise.
 */
bool tson::Grid::parse(IJson &json)
{
	bool allFound = true;

	if(json.count("orientation") > 0) m_orientation = json["orientation"].get<std::string>(); //Optional

	if(json.count("width") > 0 && json.count("height") > 0)
		m_size = {json["width"].get<int>(), json["height"].get<int>()}; else allFound = false;

	return allFound;
}

/*!
 * 'orientation': Orientation of the grid for the tiles in this tileset (orthogonal or isometric)
 * @return orientation as string
 */
const std::string &tson::Grid::getOrientation() const
{
	return m_orientation;
}

/*!
 * 'width' and 'height': Size.
 * @return size as int
 */
const tson::Vector2i &tson::Grid::getSize() const
{
	return m_size;
}

#endif //TILESON_GRID_HPP

/*** End of inlined file: Grid.hpp ***/

#include <functional>

namespace tson
{
	class Map;
	class Tileset
	{
		public:
			inline Tileset() = default;
			inline explicit Tileset(IJson &json, tson::Map *map);
			inline bool parse(IJson &json, tson::Map *map);

			[[nodiscard]] inline int getColumns() const;
			[[nodiscard]] inline int getFirstgid() const;

			[[nodiscard]] inline const fs::path &getImagePath() const;
			[[nodiscard]] inline const fs::path &getImage() const;

			[[nodiscard]] inline const Vector2i &getImageSize() const;
			[[nodiscard]] inline int getMargin() const;
			[[nodiscard]] inline const std::string &getName() const;
			[[nodiscard]] inline int getSpacing() const;
			[[nodiscard]] inline int getTileCount() const;
			[[nodiscard]] inline const Vector2i &getTileSize() const;
			[[nodiscard]] inline const Colori &getTransparentColor() const;

			[[nodiscard]] inline const std::string &getType() const;
			[[nodiscard]] inline std::vector<tson::Tile> &getTiles();
			[[nodiscard]] inline const std::vector<tson::WangSet> &getWangsets() const;
			[[nodiscard]] inline PropertyCollection &getProperties();
			[[nodiscard]] inline const std::vector<tson::Terrain> &getTerrains() const;
			[[nodiscard]] inline const Vector2i &getTileOffset() const;
			[[nodiscard]] inline const Grid &getGrid() const;

			inline tson::Tile * getTile(int id);
			inline tson::Terrain * getTerrain(const std::string &name);

			template <typename T>
			inline T get(const std::string &name);
			inline tson::Property * getProp(const std::string &name);

			//v1.2.0-stuff
			[[nodiscard]] inline tson::Map *getMap() const;
			[[nodiscard]] inline ObjectAlignment getObjectAlignment() const;

			inline static tson::ObjectAlignment StringToAlignment(std::string_view str);

		private:
			inline void generateMissingTiles();

			int                           m_columns {};       /*! 'columns': The number of tile columns in the tileset */
			int                           m_firstgid {};      /*! 'firstgid': GID corresponding to the first tile in the set */

			fs::path                      m_image;            /*! 'image': Image used for tiles in this set */

			tson::Vector2i                m_imageSize;        /*! x = 'imagewidth' and y = 'imageheight': in pixels */
			int                           m_margin {};        /*! 'margin': Buffer between image edge and first tile (pixels)*/
			std::string                   m_name;             /*! 'name': Name given to this tileset */
			int                           m_spacing {};       /*! 'spacing': Spacing between adjacent tiles in image (pixels)*/
			int                           m_tileCount {};     /*! 'tilecount': The number of tiles in this tileset */
			tson::Vector2i                m_tileSize;         /*! x = 'tilewidth' and y = 'tileheight': Maximum size of tiles in this set */
			tson::Colori                  m_transparentColor; /*! 'transparentcolor': Hex-formatted color (#RRGGBB) (optional) */
			std::string                   m_type;             /*! 'type': tileset (for tileset files, since 1.0) */

			std::vector<tson::Tile>       m_tiles;            /*! 'tiles': Array of Tiles (optional) */
			std::vector<tson::WangSet>    m_wangsets;         /*! 'wangsets':Array of Wang sets (since 1.1.5) */
			tson::PropertyCollection      m_properties; 	  /*! 'properties': A list of properties (name, value, type). */

			std::vector<tson::Terrain>    m_terrains;         /*! 'terrains': Array of Terrains (optional) */
			tson::Vector2i                m_tileOffset;       /*! 'x' and 'y': See <tileoffset> (optional) */
			tson::Grid                    m_grid;             /*! 'grid': This element is only used in case of isometric orientation, and determines
																   how tile overlays for terrain and collision information are rendered. */

			//v1.2.0-stuff
			tson::ObjectAlignment         m_objectAlignment{tson::ObjectAlignment::Unspecified};  /*! 'objectalignment': Alignment to use for tile objects. Tiled 1.4.*/
			tson::Map *                   m_map;              /*! The map who owns this tileset */
	};

	/*!
	 * A shortcut for getting a property. Alternative to getProperties().getValue<T>("<name>")
	 * @tparam T The template value
	 * @param name Name of the property
	 * @return The actual value, if it exists. Otherwise: The default value of the type.
	 */
	template<typename T>
	T tson::Tileset::get(const std::string &name)
	{
		return m_properties.getValue<T>(name);
	}
}

tson::Tileset::Tileset(IJson &json, tson::Map *map)
{
	parse(json, map);
}

bool tson::Tileset::parse(IJson &json, tson::Map *map)
{
	m_map = map;
	bool allFound = true;

	if(json.count("columns") > 0) m_columns = json["columns"].get<int>(); else allFound = false;
	if(json.count("firstgid") > 0) m_firstgid = json["firstgid"].get<int>(); else allFound = false;

	if(json.count("image") > 0) m_image = fs::path(json["image"].get<std::string>()); else allFound = false;

	if(json.count("margin") > 0) m_margin = json["margin"].get<int>(); else allFound = false;
	if(json.count("name") > 0) m_name = json["name"].get<std::string>(); else allFound = false;
	if(json.count("spacing") > 0) m_spacing = json["spacing"].get<int>(); else allFound = false;
	if(json.count("tilecount") > 0) m_tileCount = json["tilecount"].get<int>(); else allFound = false;
	if(json.count("transparentcolor") > 0) m_transparentColor = tson::Colori(json["transparentcolor"].get<std::string>()); //Optional
	if(json.count("type") > 0) m_type = json["type"].get<std::string>();
	if(json.count("grid") > 0) m_grid = tson::Grid(json["grid"]);

	if(json.count("imagewidth") > 0 && json.count("imageheight") > 0)
		m_imageSize = {json["imagewidth"].get<int>(), json["imageheight"].get<int>()}; else allFound = false;
	if(json.count("tilewidth") > 0 && json.count("tileheight") > 0)
		m_tileSize = {json["tilewidth"].get<int>(), json["tileheight"].get<int>()}; else allFound = false;
	if(json.count("tileoffset") > 0)
		m_tileOffset = {json["tileoffset"]["x"].get<int>(), json["tileoffset"]["y"].get<int>()};

	//More advanced data
	if(json.count("wangsets") > 0 && json["wangsets"].isArray())
	{
		auto &wangsets = json.array("wangsets");
		std::for_each(wangsets.begin(), wangsets.end(), [&](std::unique_ptr<IJson> &item) { m_wangsets.emplace_back(*item); });
	}
	if(json.count("tiles") > 0 && json["tiles"].isArray())
	{
		auto &tiles = json.array("tiles");
		std::for_each(tiles.begin(), tiles.end(), [&](std::unique_ptr<IJson> &item) { m_tiles.emplace_back(*item, this, m_map); });
	}
	if(json.count("terrains") > 0 && json["terrains"].isArray())
	{
		auto &terrains = json.array("terrains");
		std::for_each(terrains.begin(), terrains.end(), [&](std::unique_ptr<IJson> &item) { m_terrains.emplace_back(*item); });
	}

	if(json.count("properties") > 0 && json["properties"].isArray())
	{
		auto &properties = json.array("properties");
		std::for_each(properties.begin(), properties.end(), [&](std::unique_ptr<IJson> &item) { m_properties.add(*item); });
	}

	if(json.count("objectalignment") > 0)
	{
		std::string alignment = json["objectalignment"].get<std::string>();
		m_objectAlignment = StringToAlignment(alignment);
	}

	generateMissingTiles();

	return allFound;
}

/*!
 * 'columns': The number of tile columns in the tileset
 * @return
 */
int tson::Tileset::getColumns() const
{
	return m_columns;
}

/*!
 * 'firstgid': GID corresponding to the first tile in the set
 * @return
 */
int tson::Tileset::getFirstgid() const
{
	return m_firstgid;
}

/*!
 * 'image': Image used for tiles in this set
 * @return
 */

const fs::path &tson::Tileset::getImagePath() const { return m_image; }

/*!
 * x = 'imagewidth' and y = 'imageheight': in pixels
 * @return
 */
const tson::Vector2i &tson::Tileset::getImageSize() const
{
	return m_imageSize;
}

/*!
 * 'margin': Buffer between image edge and first tile (pixels)
 * @return
 */
int tson::Tileset::getMargin() const
{
	return m_margin;
}

/*!
 * 'name': Name given to this tileset
 * @return
 */
const std::string &tson::Tileset::getName() const
{
	return m_name;
}

/*!
 * 'spacing': Spacing between adjacent tiles in image (pixels)
 * @return
 */
int tson::Tileset::getSpacing() const
{
	return m_spacing;
}

/*!
 * 'tilecount': The number of tiles in this tileset
 * @return
 */
int tson::Tileset::getTileCount() const
{
	return m_tileCount;
}

/*!
 * x = 'tilewidth' and y = 'tileheight': Maximum size of tiles in this set
 * @return
 */
const tson::Vector2i &tson::Tileset::getTileSize() const
{
	return m_tileSize;
}

/*!
 * 'transparentcolor': Color object created by hex-formatted color (#RRGGBB) (optional)
 * @return
 */
const tson::Colori &tson::Tileset::getTransparentColor() const
{
	return m_transparentColor;
}

/*!
 * 'type': tileset (for tileset files, since 1.0)
 * @return
 */
const std::string &tson::Tileset::getType() const
{
	return m_type;
}

/*!
 * 'image': Image used for tiles in this set
 * @return
 */

const fs::path &tson::Tileset::getImage() const { return m_image; }

/*!
 * 'tiles': Array of Tiles (optional)
 * @return
 */
std::vector<tson::Tile> &tson::Tileset::getTiles()
{
	return m_tiles;
}

/*!
 * 'wangsets':Array of Wang sets (since Tiled 1.1.5)
 * @return
 */
const std::vector<tson::WangSet> &tson::Tileset::getWangsets() const
{
	return m_wangsets;
}

/*!
 * 'properties': A list of properties (name, value, type).
 * @return
 */
tson::PropertyCollection &tson::Tileset::getProperties()
{
	return m_properties;
}

/*!
 * 'terrains': Array of Terrains (optional)
 * @return
 */
const std::vector<tson::Terrain> &tson::Tileset::getTerrains() const
{
	return m_terrains;
}

/*!
 * 'x' and 'y': See <tileoffset> (optional)
 * @return
 */
const tson::Vector2i &tson::Tileset::getTileOffset() const
{
	return m_tileOffset;
}

/*!
 * 'grid': This element is only used in case of isometric orientation, and determines
 * how tile overlays for terrain and collision information are rendered.
 * @return
 */
const tson::Grid &tson::Tileset::getGrid() const
{
	return m_grid;
}

/*!
 * Gets a tile by ID (Tiled ID + 1)
 * @param id The ID of the tile stored in Tiled map + 1. Example: If ID was stored in Tiled map as 0, the corresponding value in Tileson is 1.
 * This is to make sure the IDs of tiles matches their references in containers.
 * @return A pointer to the Tile if found. nullptr otherwise.
 */
tson::Tile *tson::Tileset::getTile(int id)
{
	auto result = std::find_if(m_tiles.begin(), m_tiles.end(), [&](const tson::Tile & item) { return item.getId() == id;});
	if(result == m_tiles.end())
		return nullptr;

	return &result.operator*();
}

/*!
 * Get an existing Terrain object by name
 * @param name
 * @return A pointer to the Terrain if found. nullptr otherwise.
 */
tson::Terrain *tson::Tileset::getTerrain(const std::string &name)
{
	auto result = std::find_if(m_terrains.begin(), m_terrains.end(), [&](const tson::Terrain & item) { return item.getName() == name;});
	if(result == m_terrains.end())
		return nullptr;

	return &result.operator*();
}

/*!
 * Shortcut for getting a property object. Alternative to getProperties().getProperty("<name>");
 * @param name Name of the property
 * @return
 */
tson::Property *tson::Tileset::getProp(const std::string &name)
{
	if(m_properties.hasProperty(name))
		return m_properties.getProperty(name);

	return nullptr;
}

/*!
 * Tiled only has tiles with a property stored in the map. This function makes sure even the ones with no properties will exist.
 */
void tson::Tileset::generateMissingTiles()
{
	std::vector<uint32_t> tileIds;
	for(auto &tile : m_tiles)
		tileIds.push_back(tile.getId());

	for(uint32_t i = m_firstgid; i < m_firstgid + m_tileCount; ++i)
	{
		if(std::count(tileIds.begin(), tileIds.end(), i) == 0)
		{
			m_tiles.emplace_back(Tile(i, this, m_map));
		}
	}
}

/*!
 * Used for getting the tson::Map who is the parent of this Tileset.
 * @return a pointer to the tson::Map where this tileset is contained.
 */
tson::Map *tson::Tileset::getMap() const
{
	return m_map;
}

/*!
 *
 * @param str The string you want to convert
 * @return Alignment enum based on the string from the input.
 */
tson::ObjectAlignment tson::Tileset::StringToAlignment(std::string_view str)
{
	if(str == "unspecified") return tson::ObjectAlignment::Unspecified;
	else if(str == "topleft") return tson::ObjectAlignment::TopLeft;
	else if(str == "top") return tson::ObjectAlignment::Top;
	else if(str == "topright") return tson::ObjectAlignment::TopRight;
	else if(str == "left") return tson::ObjectAlignment::Left;
	else if(str == "center") return tson::ObjectAlignment::Center;
	else if(str == "right") return tson::ObjectAlignment::Right;
	else if(str == "bottomleft") return tson::ObjectAlignment::BottomLeft;
	else if(str == "bottom") return tson::ObjectAlignment::Bottom;
	else if(str == "bottomright") return tson::ObjectAlignment::BottomRight;
	else
		return tson::ObjectAlignment::Unspecified;
}

tson::ObjectAlignment tson::Tileset::getObjectAlignment() const
{
	return m_objectAlignment;
}

#endif //TILESON_TILESET_HPP
/*** End of inlined file: Tileset.hpp ***/

namespace tson
{
	class Map
	{
		public:
			inline Map() = default;
			inline Map(ParseStatus status, std::string description);
			inline explicit Map(IJson &json, tson::DecompressorContainer *decompressors);
			inline bool parse(IJson &json, tson::DecompressorContainer *decompressors);

			[[nodiscard]] inline const Colori &getBackgroundColor() const;
			[[nodiscard]] inline const Vector2i &getSize() const;
			[[nodiscard]] inline int getHexsideLength() const;
			[[nodiscard]] inline bool isInfinite() const;
			[[nodiscard]] inline int getNextLayerId() const;
			[[nodiscard]] inline int getNextObjectId() const;
			[[nodiscard]] inline const std::string &getOrientation() const;
			[[nodiscard]] inline const std::string &getRenderOrder() const;
			[[nodiscard]] inline const std::string &getStaggerAxis() const;
			[[nodiscard]] inline const std::string &getStaggerIndex() const;
			[[nodiscard]] inline const std::string &getTiledVersion() const;
			[[nodiscard]] inline const Vector2i &getTileSize() const;
			[[nodiscard]] inline const std::string &getType() const;
			[[nodiscard]] inline int getVersion() const;

			[[nodiscard]] inline std::vector<tson::Layer> &getLayers();
			[[nodiscard]] inline PropertyCollection &getProperties();
			[[nodiscard]] inline std::vector<tson::Tileset> &getTilesets();

			[[nodiscard]] inline ParseStatus getStatus() const;
			[[nodiscard]] inline const std::string &getStatusMessage() const;
			[[nodiscard]] inline const std::map<uint32_t, tson::Tile *> &getTileMap() const;

			inline Layer * getLayer(const std::string &name);
			inline Tileset * getTileset(const std::string &name);

			template <typename T>
			inline T get(const std::string &name);
			inline tson::Property * getProp(const std::string &name);

			//v1.2.0
			[[nodiscard]] inline int getCompressionLevel() const;
			inline DecompressorContainer *getDecompressors();
			inline Tileset * getTilesetByGid(uint32_t gid);

		private:
			inline void createTilesetData(IJson &json);
			inline void processData();

			Colori                                 m_backgroundColor;   /*! 'backgroundcolor': Hex-formatted color (#RRGGBB or #AARRGGBB) (optional)*/;
			Vector2i                               m_size;              /*! 'width' and 'height' of a Tiled map */
			int                                    m_hexsideLength {};  /*! 'hexsidelength': Length of the side of a hex tile in pixels */
			bool                                   m_isInfinite {};     /*! 'infinite': Whether the map has infinite dimensions*/
			std::vector<tson::Layer>               m_layers; 	        /*! 'layers': Array of layers. group on */
			int                                    m_nextLayerId {};    /*! 'nextlayerid': Auto-increments for each layer */
			int                                    m_nextObjectId {};   /*! 'nextobjectid': Auto-increments for each placed object */
			std::string                            m_orientation;       /*! 'orientation': orthogonal, isometric, staggered or hexagonal */
			tson::PropertyCollection               m_properties; 	    /*! 'properties': A list of properties (name, value, type). */
			std::string                            m_renderOrder;       /*! 'renderorder': Rendering direction (orthogonal maps only) */
			std::string                            m_staggerAxis;       /*! 'staggeraxis': x or y (staggered / hexagonal maps only) */
			std::string                            m_staggerIndex;      /*! 'staggerindex': odd or even (staggered / hexagonal maps only) */
			std::string                            m_tiledVersion;      /*! 'tiledversion': The Tiled version used to save the file */
			Vector2i                               m_tileSize;          /*! 'tilewidth': and 'tileheight' of a map */
			std::vector<tson::Tileset>             m_tilesets;          /*! 'tilesets': Array of Tilesets */
			std::string                            m_type;              /*! 'type': map (since 1.0) */
			int                                    m_version{};         /*! 'version': The JSON format version*/

			ParseStatus                            m_status {ParseStatus::OK};
			std::string                            m_statusMessage {"OK"};

			std::map<uint32_t, tson::Tile*>        m_tileMap;           /*! key: Tile ID. Value: Pointer to Tile*/

			//v1.2.0
			int                                    m_compressionLevel {-1};  /*! 'compressionlevel': The compression level to use for tile layer
																			  *     data (defaults to -1, which means to use the algorithm default)
																			  *     Introduced in Tiled 1.3*/
			tson::DecompressorContainer *          m_decompressors;
			std::map<uint32_t, tson::Tile>         m_flaggedTileMap;    /*! key: Tile ID. Value: Tile*/
	};

	/*!
	 * A shortcut for getting a property. Alternative to getProperties().getValue<T>("<name>")
	 * @tparam T The template value
	 * @param name Name of the property
	 * @return The actual value, if it exists. Otherwise: The default value of the type.
	 */
	template<typename T>
	T tson::Map::get(const std::string &name)
	{
		return m_properties.getValue<T>(name);
	}
}

/*!
 * When errors have happened before the map starts parsing, just keep the statuses
 * @param status The status
 * @param description Description of the status
 */
tson::Map::Map(tson::ParseStatus status, std::string description) : m_status {status}, m_statusMessage { std::move(description) }
{

}

/*!
 * Parses a json of a Tiled map.
 * @param json A json object with the format of Map
 * @return true if all mandatory fields was found. false otherwise.
 */
tson::Map::Map(IJson &json, tson::DecompressorContainer *decompressors)
{
	parse(json, decompressors);
}

/*!
 * Parses a json of a Tiled map.
 * @param json A json object with the format of Map
 * @return true if all mandatory fields was found. false otherwise.
 */
bool tson::Map::parse(IJson &json, tson::DecompressorContainer *decompressors)
{
	m_decompressors = decompressors;

	bool allFound = true;
	if(json.count("compressionlevel") > 0)
		m_compressionLevel = json["compressionlevel"].get<int>(); //Tiled 1.3 - Optional

	if(json.count("backgroundcolor") > 0) m_backgroundColor = Colori(json["backgroundcolor"].get<std::string>()); //Optional
	if(json.count("width") > 0 && json.count("height") > 0 )
		m_size = {json["width"].get<int>(), json["height"].get<int>()}; else allFound = false;
	if(json.count("hexsidelength") > 0) m_hexsideLength = json["hexsidelength"].get<int>();         //Optional
	if(json.count("infinite") > 0) m_isInfinite = json["infinite"].get<bool>();                     //Optional
	if(json.count("nextlayerid") > 0) m_nextLayerId = json["nextlayerid"].get<int>();               //Optional
	if(json.count("nextobjectid") > 0) m_nextObjectId = json["nextobjectid"].get<int>(); else allFound = false;
	if(json.count("orientation") > 0) m_orientation = json["orientation"].get<std::string>(); else allFound = false;
	if(json.count("renderorder") > 0) m_renderOrder = json["renderorder"].get<std::string>();       //Optional
	if(json.count("staggeraxis") > 0) m_staggerAxis = json["staggeraxis"].get<std::string>();       //Optional
	if(json.count("staggerindex") > 0) m_staggerIndex = json["staggerindex"].get<std::string>();    //Optional
	if(json.count("tiledversion") > 0) m_tiledVersion = json["tiledversion"].get<std::string>(); else allFound = false;
	if(json.count("tilewidth") > 0 && json.count("tileheight") > 0 )
		m_tileSize = {json["tilewidth"].get<int>(), json["tileheight"].get<int>()}; else allFound = false;
	if(json.count("type") > 0) m_type = json["type"].get<std::string>();                            //Optional
	if(json.count("version") > 0) m_version = json["version"].get<int>(); else allFound = false;

	//More advanced data
	if(json.count("layers") > 0 && json["layers"].isArray())
	{
		auto &array = json.array("layers");
		std::for_each(array.begin(), array.end(), [&](std::unique_ptr<IJson> &item)
		{
			m_layers.emplace_back(*item, this);
		});
	}

	if(json.count("properties") > 0 && json["properties"].isArray())
	{
		auto &array = json.array("properties");
		std::for_each(array.begin(), array.end(), [&](std::unique_ptr<IJson> &item)
		{
			m_properties.add(*item);
		});
	}
	createTilesetData(json);
	processData();

	return allFound;
}

/*!
 * Tileset data must be created in two steps to prevent malformed tson::Tileset pointers inside tson::Tile
 */
void tson::Map::createTilesetData(IJson &json)
{
	if(json.count("tilesets") > 0 && json["tilesets"].isArray())
	{
		//First created tileset objects
		auto &tilesets = json.array("tilesets");
		std::for_each(tilesets.begin(), tilesets.end(), [&](std::unique_ptr<IJson> &item)
		{
			m_tilesets.emplace_back();
		});

		int i = 0;
		//Then do the parsing
		std::for_each(tilesets.begin(), tilesets.end(), [&](std::unique_ptr<IJson> &item)
		{
			m_tilesets[i].parse(*item, this);
			++i;
		});
	}
}

/*!
 * Processes the parsed data and uses the data to create helpful objects, like tile maps.
 */
void tson::Map::processData()
{
	m_tileMap.clear();
	for(auto &tileset : m_tilesets)
	{
		std::for_each(tileset.getTiles().begin(), tileset.getTiles().end(), [&](tson::Tile &tile) { m_tileMap[tile.getGid()] = &tile; });
	}
	std::for_each(m_layers.begin(), m_layers.end(), [&](tson::Layer &layer)
	{
		layer.assignTileMap(&m_tileMap);
		layer.createTileData(m_size, m_isInfinite);
		const std::set<uint32_t> &flaggedTiles = layer.getUniqueFlaggedTiles();
		for(uint32_t ftile : flaggedTiles)
		{
			tson::Tile tile {ftile, layer.getMap()};
			if(m_tileMap.count(tile.getGid()))
			{
				tson::Tile *originalTile = m_tileMap[tile.getGid()];
				tile.addTilesetAndPerformCalculations(originalTile->getTileset());
				tile.setProperties(originalTile->getProperties());
				m_flaggedTileMap[ftile] = tile;
				m_tileMap[ftile] = &m_flaggedTileMap[ftile];
			}
		}
		layer.resolveFlaggedTiles();
	});
}

/*!
 * 'backgroundcolor': Color created from a hex-formatted color string (#RRGGBB or #AARRGGBB) (optional)
 * @return string as color
 */
const tson::Colori &tson::Map::getBackgroundColor() const
{
	return m_backgroundColor;
}

/*!
 * 'width' and 'height' of a Tiled map
 * @return
 */
const tson::Vector2<int> &tson::Map::getSize() const
{
	return m_size;
}

/*!
 * 'hexsidelength': Length of the side of a hex tile in pixels
 * @return
 */
int tson::Map::getHexsideLength() const
{
	return m_hexsideLength;
}

/*!
 * 'infinite': Whether the map has infinite dimensions
 * @return
 */
bool tson::Map::isInfinite() const
{
	return m_isInfinite;
}

/*!
 * 'nextlayerid': Auto-increments for each layer
 * @return
 */
int tson::Map::getNextLayerId() const
{
	return m_nextLayerId;
}

/*!
 * 'nextobjectid': Auto-increments for each placed object
 * @return
 */
int tson::Map::getNextObjectId() const
{
	return m_nextObjectId;
}

/*!
 * 'orientation': orthogonal, isometric, staggered or hexagonal
 * @return
 */
const std::string &tson::Map::getOrientation() const
{
	return m_orientation;
}

/*!
 * 'renderorder': Rendering direction (orthogonal maps only)
 * @return
 */
const std::string &tson::Map::getRenderOrder() const
{
	return m_renderOrder;
}

/*!
 * 'staggeraxis': x or y (staggered / hexagonal maps only)
 * @return
 */
const std::string &tson::Map::getStaggerAxis() const
{
	return m_staggerAxis;
}

/*!
 * 'staggerindex': odd or even (staggered / hexagonal maps only)
 * @return
 */
const std::string &tson::Map::getStaggerIndex() const
{
	return m_staggerIndex;
}

/*!
 * 'tiledversion': The Tiled version used to save the file
 * @return
 */
const std::string &tson::Map::getTiledVersion() const
{
	return m_tiledVersion;
}

/*!
 * 'tilewidth': and 'tileheight' of a map
 * @return
 */
const tson::Vector2<int> &tson::Map::getTileSize() const
{
	return m_tileSize;
}

/*!
 * 'type': map (since 1.0)
 * @return
 */
const std::string &tson::Map::getType() const
{
	return m_type;
}

/*!
 * 'version': The JSON format version
 * @return
 */
int tson::Map::getVersion() const
{
	return m_version;
}

/*!
 * 'layers': Array of layers. group on
 * @return
 */
std::vector<tson::Layer> &tson::Map::getLayers()
{
	return m_layers;
}

/*!
 * 'properties': A list of properties (name, value, type).
 * @return
 */
tson::PropertyCollection &tson::Map::getProperties()
{
	return m_properties;
}

/*!
 * 'tilesets': Array of Tilesets
 * @return
 */
std::vector<tson::Tileset> &tson::Map::getTilesets()
{
	return m_tilesets;
}

tson::Layer *tson::Map::getLayer(const std::string &name)
{
	auto result = std::find_if(m_layers.begin(), m_layers.end(), [&](const tson::Layer &item) { return item.getName() == name; });
	if(result == m_layers.end())
		return nullptr;

	return &result.operator*();
}

/*!
 * Gets a tileset by name
 *
 * @param name Name of the tileset
 * @return tileset with the matching name
 */
tson::Tileset *tson::Map::getTileset(const std::string &name)
{
	auto result = std::find_if(m_tilesets.begin(), m_tilesets.end(), [&](const tson::Tileset &item) {return item.getName() == name; });
	if(result == m_tilesets.end())
		return nullptr;

	return &result.operator*();
}

/*!
 * Gets a tileset by gid (graphical ID of a tile). These are always unique, no matter how many tilesets you have
 *
 * @param gid Graphical ID of a tile
 * @return tileset related to the actual gid
 */
tson::Tileset *tson::Map::getTilesetByGid(uint32_t gid)
{
	auto result = std::find_if(m_tilesets.begin(), m_tilesets.end(), [&](const tson::Tileset &tileset)
	{
		int firstId = tileset.getFirstgid(); //First tile id of the tileset
		int lastId = (firstId + tileset.getTileCount()) - 1;

		return (gid >= firstId && gid <= lastId);
	});
	if(result == m_tilesets.end())
		return nullptr;

	return &result.operator*();
}

/*!
 * Shortcut for getting a property object. Alternative to getProperties().getProperty("<name>");
 * @param name Name of the property
 * @return
 */
tson::Property *tson::Map::getProp(const std::string &name)
{
	if(m_properties.hasProperty(name))
		return m_properties.getProperty(name);
	return nullptr;
}

tson::ParseStatus tson::Map::getStatus() const
{
	return m_status;
}

const std::string &tson::Map::getStatusMessage() const
{
	return m_statusMessage;
}

/*!
 * Get a tile map with pointers to every existing tile.
 * @return
 */
const std::map<uint32_t, tson::Tile *> &tson::Map::getTileMap() const
{
	return m_tileMap;
}

tson::DecompressorContainer *tson::Map::getDecompressors()
{
	return m_decompressors;
}

/*!
 * 'compressionlevel': The compression level to use for tile layer data (defaults to -1, which means to use the algorithm default)
 *
 * @return The compression level
 */
int tson::Map::getCompressionLevel() const
{
	return m_compressionLevel;
}

#endif //TILESON_MAP_HPP

/*** End of inlined file: Map.hpp ***/


/*** Start of inlined file: Project.hpp ***/
//
// Created by robin on 01.08.2020.
//

#ifndef TILESON_PROJECT_HPP
#define TILESON_PROJECT_HPP

#include <fstream>
#include <sstream>
#include <memory>

/*** Start of inlined file: World.hpp ***/
//
// Created by robin on 01.08.2020.
//

#ifndef TILESON_WORLD_HPP
#define TILESON_WORLD_HPP


/*** Start of inlined file: WorldMapData.hpp ***/
//
// Created by robin on 01.08.2020.
//

#ifndef TILESON_WORLDMAPDATA_HPP
#define TILESON_WORLDMAPDATA_HPP

namespace tson
{
	class WorldMapData
	{
		public:
			inline WorldMapData(const fs::path &folder_, IJson &json);
			inline void parse(const fs::path &folder_, IJson &json);
			//inline WorldMapData(fs::path folder_, std::string fileName_) : folder {std::move(folder_)}, fileName {fileName_}
			//{
			//    path = folder / fileName;
			//}

			fs::path folder;
			fs::path path;
			std::string fileName;
			tson::Vector2i size;
			tson::Vector2i position;
	};

	WorldMapData::WorldMapData(const fs::path &folder_, IJson &json)
	{
		parse(folder_, json);
	}

	void WorldMapData::parse(const fs::path &folder_, IJson &json)
	{
		folder = folder_;
		if(json.count("fileName") > 0) fileName = json["fileName"].get<std::string>();
		if(json.count("height") > 0) size = {json["width"].get<int>(), json["height"].get<int>()};
		if(json.count("x") > 0) position = {json["x"].get<int>(), json["y"].get<int>()};

		path = (!fileName.empty()) ? folder / fileName : folder;
	}
}

#endif //TILESON_WORLDMAPDATA_HPP
/*** End of inlined file: WorldMapData.hpp ***/

#include <memory>
namespace tson
{
	class Tileson;
	class World
	{
		public:
			#ifdef JSON11_IS_DEFINED
			inline explicit World(std::unique_ptr<tson::IJson> jsonParser = std::make_unique<tson::Json11>()) : m_json {std::move(jsonParser)}
			{
			}

			inline explicit World(const fs::path &path, std::unique_ptr<tson::IJson> jsonParser = std::make_unique<tson::Json11>());
			#else
			inline explicit World(std::unique_ptr<tson::IJson> jsonParser) : m_json {std::move(jsonParser)}
			{
			}

			inline explicit World(const fs::path &path, std::unique_ptr<tson::IJson> jsonParser);
			#endif
			inline bool parse(const fs::path &path);
			inline int loadMaps(tson::Tileson *parser); //tileson_forward.hpp
			inline bool contains(std::string_view filename);
			inline const WorldMapData *get(std::string_view filename) const;

			[[nodiscard]] inline const fs::path &getPath() const;
			[[nodiscard]] inline const fs::path &getFolder() const;
			[[nodiscard]] inline const std::vector<WorldMapData> &getMapData() const;
			[[nodiscard]] inline bool onlyShowAdjacentMaps() const;
			[[nodiscard]] inline const std::string &getType() const;
			[[nodiscard]] inline const std::vector<std::unique_ptr<tson::Map>> &getMaps() const;

		private:
			inline void parseJson(IJson &json);

			std::unique_ptr<IJson> m_json = nullptr;
			fs::path m_path;
			fs::path m_folder;
			std::vector<WorldMapData> m_mapData;
			std::vector<std::unique_ptr<tson::Map>> m_maps;
			bool m_onlyShowAdjacentMaps;
			std::string m_type;
	};

	World::World(const fs::path &path, std::unique_ptr<tson::IJson> jsonParser) : m_json {std::move(jsonParser)}
	{
		parse(path);
	}

	bool World::parse(const fs::path &path)
	{
		m_path = path;
		m_folder = m_path.parent_path();

		if(!m_json->parse(path))
			return false;

		parseJson(*m_json);
		return true;
	}

	const fs::path &World::getPath() const
	{
		return m_path;
	}

	const std::vector<WorldMapData> &World::getMapData() const
	{
		return m_mapData;
	}

	bool World::onlyShowAdjacentMaps() const
	{
		return m_onlyShowAdjacentMaps;
	}

	const std::string &World::getType() const
	{
		return m_type;
	}

	void World::parseJson(IJson &json)
	{
		if(json.count("onlyShowAdjacentMaps") > 0) m_onlyShowAdjacentMaps = json["onlyShowAdjacentMaps"].get<bool>();
		if(json.count("type") > 0) m_type = json["type"].get<std::string>();

		if(json["maps"].isArray())
		{
			auto &maps = json.array("maps");
			std::for_each(maps.begin(), maps.end(), [&](std::unique_ptr<IJson> &item) { m_mapData.emplace_back(m_folder, *item); });
		}
	}

	const fs::path &World::getFolder() const
	{
		return m_folder;
	}

	/*!
	 * Check if there is WorldMapData in the world that contains the current filename.
	 * Filename = <file>.<extension>
	 * @param filename
	 * @return
	 */
	bool World::contains(std::string_view filename)
	{
		//Note: might be moved to std::ranges from C++20.
		return std::any_of(m_mapData.begin(), m_mapData.end(), [&](const auto &item) { return item.fileName == filename; });
	}

	/*!
	 * Get a map by its filename
	 * @param filename Filename (including extension) - (example: file.json)
	 * @return pointer to WorldMapData or nullptr if not exists
	 */
	const WorldMapData * World::get(std::string_view filename) const
	{
		auto iter = std::find_if(m_mapData.begin(), m_mapData.end(), [&](const auto &item) { return item.fileName == filename; });
		return (iter == m_mapData.end()) ? nullptr : iter.operator->();
	}

	/*!
	 * Get all maps that have been loaded by loadMaps().
	 * NOTE: This is untested, and was a last second addition to Tileson 1.2.0, as I had forgot about the loadMaps() functionality (also untested)
	 * If you find anything malfunctioning - please report.
	 * @return All maps loaded by loadMaps()
	 */
	const std::vector<std::unique_ptr<tson::Map>> &World::getMaps() const
	{
		return m_maps;
	}

}

#endif //TILESON_WORLD_HPP
/*** End of inlined file: World.hpp ***/



/*** Start of inlined file: ProjectFolder.hpp ***/
//
// Created by robin on 01.08.2020.
//

#ifndef TILESON_PROJECTFOLDER_HPP
#define TILESON_PROJECTFOLDER_HPP

namespace tson
{
	class ProjectFolder
	{
		public:
			inline ProjectFolder(const fs::path &path);

			inline const fs::path &getPath() const;
			inline bool hasWorldFile() const;
			inline const std::vector<ProjectFolder> &getSubFolders() const;
			inline const std::vector<fs::path> &getFiles() const;
			inline const World &getWorld() const;

		private:
			inline void loadData();
			fs::path                    m_path;
			bool                        m_hasWorldFile;
			tson::World                 m_world;
			std::vector<ProjectFolder>  m_subFolders;
			std::vector<fs::path>       m_files;

	};

	ProjectFolder::ProjectFolder(const fs::path &path) : m_path {path}
	{
		loadData();
	}

	void ProjectFolder::loadData()
	{
		m_hasWorldFile = false;
		m_subFolders.clear();
		m_files.clear();
		//Search and see if there is a World file .world file
		fs::path worldPath;
		for (const auto & entry : fs::directory_iterator(m_path))
		{
			if(fs::is_regular_file(entry.path()))
			{
				if(entry.path().extension() == ".world")
				{
					m_hasWorldFile = true;
					worldPath = entry.path();
				}
			}
		}

		if(m_hasWorldFile)
			m_world.parse(worldPath);

		for (const auto & entry : fs::directory_iterator(m_path))
		{
			if (fs::is_directory(entry.path()))
				m_subFolders.emplace_back(entry.path());//.loadData(); - loadData() is called in the constructor, so don't call again.
			else if (fs::is_regular_file(entry.path()))
			{
				if(m_hasWorldFile && m_world.contains(entry.path().filename().u8string()))
					m_files.emplace_back(entry.path());
				else if(!m_hasWorldFile)
					m_files.emplace_back(entry.path());
			}
		}

	}

	const fs::path &ProjectFolder::getPath() const
	{
		return m_path;
	}

	bool ProjectFolder::hasWorldFile() const
	{
		return m_hasWorldFile;
	}

	const std::vector<ProjectFolder> &ProjectFolder::getSubFolders() const
	{
		return m_subFolders;
	}

	const std::vector<fs::path> &ProjectFolder::getFiles() const
	{
		return m_files;
	}

	/*!
	 * Only gives useful data if hasWorldFile() is true!
	 * @return
	 */
	const World &ProjectFolder::getWorld() const
	{
		return m_world;
	}
}

#endif //TILESON_PROJECTFOLDER_HPP
/*** End of inlined file: ProjectFolder.hpp ***/


/*** Start of inlined file: ProjectData.hpp ***/
//
// Created by robin on 01.08.2020.
//

#ifndef TILESON_PROJECTDATA_HPP
#define TILESON_PROJECTDATA_HPP

namespace tson
{
	class ProjectData
	{
		public:
			ProjectData() = default;
			std::string automappingRulesFile;
			std::vector<std::string> commands;
			std::string extensionsPath;
			std::vector<std::string> folders;
			std::string objectTypesFile;

			//Tileson specific
			fs::path basePath;
			std::vector<tson::ProjectFolder> folderPaths;
	};
}

#endif //TILESON_PROJECTDATA_HPP
/*** End of inlined file: ProjectData.hpp ***/

namespace tson
{
	class Project
	{
		public:
			#ifdef JSON11_IS_DEFINED
			inline explicit Project(std::unique_ptr<tson::IJson> jsonParser = std::make_unique<tson::Json11>()) : m_json {std::move(jsonParser)}
			{

			}
			inline explicit Project(const fs::path &path, std::unique_ptr<tson::IJson> jsonParser = std::make_unique<tson::Json11>());
			#else
			inline explicit Project(std::unique_ptr<tson::IJson> jsonParser) : m_json {std::move(jsonParser)}
			{

			}
			inline explicit Project(const fs::path &path, std::unique_ptr<tson::IJson> jsonParser);
			#endif
			inline bool parse(const fs::path &path);

			[[nodiscard]] inline const ProjectData &getData() const;
			[[nodiscard]] inline const fs::path &getPath() const;
			[[nodiscard]] inline const std::vector<ProjectFolder> &getFolders() const;

		private:
			inline void parseJson(IJson &json);
			fs::path m_path;
			std::vector<ProjectFolder> m_folders;
			ProjectData m_data;
			std::unique_ptr<IJson> m_json = nullptr;
	};

	Project::Project(const fs::path &path, std::unique_ptr<tson::IJson> jsonParser) : m_json {std::move(jsonParser)}
	{
		parse(path);
	}

	bool Project::parse(const fs::path &path)
	{
		m_path = path;
		std::ifstream i(m_path.u8string());

		try
		{
			if(!m_json->parse(path))
				return false;
		}
		catch(const std::exception &error)
		{
			std::string message = "Parse error: ";
			message += std::string(error.what());
			message += std::string("\n");
			return false;
		}
		parseJson(*m_json);
		return true;
	}

	const ProjectData &Project::getData() const
	{
		return m_data;
	}

	void Project::parseJson(IJson &json)
	{
		m_data.basePath = m_path.parent_path(); //The directory of the project file

		if(json.count("automappingRulesFile") > 0) m_data.automappingRulesFile = json["automappingRulesFile"].get<std::string>();
		if(json.count("commands") > 0)
		{
			m_data.commands.clear();
			auto &commands = json.array("commands");
			std::for_each(commands.begin(), commands.end(), [&](std::unique_ptr<IJson> &item)
			{
				m_data.commands.emplace_back(item->get<std::string>());
			});
		}
		if(json.count("extensionsPath") > 0) m_data.extensionsPath = json["extensionsPath"].get<std::string>();
		if(json.count("folders") > 0)
		{
			m_data.folders.clear();
			m_data.folderPaths.clear();
			auto &folders = json.array("folders");
			std::for_each(folders.begin(), folders.end(), [&](std::unique_ptr<IJson> &item)
			{
				std::string folder = item->get<std::string>();
				m_data.folders.emplace_back(folder);
				m_data.folderPaths.emplace_back(m_data.basePath / folder);
				m_folders.emplace_back(m_data.basePath / folder);
			});
		}
		if(json.count("objectTypesFile") > 0) m_data.objectTypesFile = json["objectTypesFile"].get<std::string>();

	}

	const fs::path &Project::getPath() const
	{
		return m_path;
	}

	const std::vector<ProjectFolder> &Project::getFolders() const
	{
		return m_folders;
	}

}

#endif //TILESON_PROJECT_HPP

/*** End of inlined file: Project.hpp ***/

namespace tson
{
	class Tileson
	{
		public:
			#ifdef JSON11_IS_DEFINED
			inline explicit Tileson(std::unique_ptr<tson::IJson> jsonParser = std::make_unique<tson::Json11>(), bool includeBase64Decoder = true);
			#else
			inline explicit Tileson(std::unique_ptr<tson::IJson> jsonParser, bool includeBase64Decoder = true);
			#endif

			inline std::unique_ptr<tson::Map> parse(const fs::path &path, std::unique_ptr<IDecompressor<std::vector<uint8_t>, std::vector<uint8_t>>> decompressor = nullptr);
			inline std::unique_ptr<tson::Map> parse(const void * data, size_t size, std::unique_ptr<IDecompressor<std::vector<uint8_t>, std::vector<uint8_t>>> decompressor = nullptr);
			inline tson::DecompressorContainer *decompressors();

		private:
			inline std::unique_ptr<tson::Map> parseJson();
			std::unique_ptr<tson::IJson> m_json;
			tson::DecompressorContainer m_decompressors;
	};
}

/*!
 *
 * @param includeBase64Decoder Includes the base64-decoder from "Base64Decompressor.hpp" if true.
 * Otherwise no other decompressors/decoders than whatever the user itself have added will be used.
 */
tson::Tileson::Tileson(std::unique_ptr<tson::IJson> jsonParser, bool includeBase64Decoder) : m_json {std::move(jsonParser)}
{
	if(includeBase64Decoder)
		m_decompressors.add<Base64Decompressor>();
}

/*!
 * Parses Tiled json map data by file
 * @param path path to file
 * @return parsed data as Map
 */
std::unique_ptr<tson::Map> tson::Tileson::parse(const fs::path &path, std::unique_ptr<IDecompressor<std::vector<uint8_t>, std::vector<uint8_t>>> decompressor)
{

	bool result = false;

	if(decompressor != nullptr)
	{
		std::vector<uint8_t> decompressed = decompressor->decompressFile(path);
		result = (decompressed.empty()) ? false : true;
		if(!result)
			return std::make_unique<tson::Map>(tson::ParseStatus::DecompressionError, "Error during decompression");
		result = m_json->parse(&decompressed[0], decompressed.size());
		if(result)
			return std::move(parseJson());
	}
	else if(m_json->parse(path))
	{
		return std::move(parseJson());
	}

	std::string msg = "File not found: ";
	msg += std::string(path.u8string());
	return std::make_unique<tson::Map>(tson::ParseStatus::FileNotFound, msg);
}

/*!
 * Parses Tiled json map data by memory
 * @param data The data to parse
 * @param size The size of the data to parse
 * @return parsed data as Map
 */
std::unique_ptr<tson::Map> tson::Tileson::parse(const void *data, size_t size, std::unique_ptr<IDecompressor<std::vector<uint8_t>, std::vector<uint8_t>>> decompressor)
{
	bool result = false;

	if(decompressor != nullptr)
	{
		std::vector<uint8_t> decompressed = decompressor->decompress(data, size);
		result = (decompressed.empty()) ? false : true;
		if(!result)
			return std::make_unique<tson::Map>(tson::ParseStatus::DecompressionError, "Error during decompression");
		result = m_json->parse(&decompressed[0], decompressed.size());
	}
	else
		result = m_json->parse(data, size);

	if(!result)
		return std::make_unique<tson::Map>(tson::ParseStatus::ParseError, "Memory error");

	return std::move(parseJson());
}

/*!
 * Common parsing functionality for doing the json parsing
 * @param json Tiled json to parse
 * @return parsed data as Map
 */
std::unique_ptr<tson::Map> tson::Tileson::parseJson()
{
	std::unique_ptr<tson::Map> map = std::make_unique<tson::Map>();

	if(map->parse(*m_json, &m_decompressors))
		return std::move(map);

	return std::make_unique<tson::Map> (tson::ParseStatus::MissingData, "Missing map data...");
}

/*!
 * Gets the decompressor container used when something is either encoded or compressed (regardless: IDecompressor is used as base).
 * These are used specifically for tile layers, and are connected by checking the name of the IDecompressor. If the name of a decompressor
 * matches with an encoding or a compression, its decompress() function will be used.
 *
 * @return The container including all decompressors.
 */
tson::DecompressorContainer *tson::Tileson::decompressors()
{
	return &m_decompressors;
}

#endif //TILESON_TILESON_PARSER_HPP

/*** End of inlined file: tileson_parser.hpp ***/


/*** Start of inlined file: tileson_forward.hpp ***/
//
// Created by robin on 25.07.2020.
//

#ifndef TILESON_TILESON_FORWARD_HPP
#define TILESON_TILESON_FORWARD_HPP
/*!
 * T I L E S O N   F O R W A R D   D E C L A R A T I O N S
 * -------------------------------------------------------
 *
 * Due to cross-references we have forward declarations that cannot be resolved during the
 * implementation, thus the implementations must be done later when the class definition itself is known.
 *
 * All those forward declarations can be found below.
 */

// T i l e . h p p
// ---------------------

/*!
 * Really just a shortcut to retrieve the tile size from the map.
 * @return TileSize based on the map property for tile size.
 */
const tson::Vector2i tson::Tile::getTileSize() const
{
	if(m_map != nullptr)
		return m_map->getTileSize();
	else
		return {0,0};
}

bool tson::Tile::parseId(IJson &json)
{
	if(json.count("id") > 0)
	{
		m_id = json["id"].get<uint32_t>() + 1;
		if (m_tileset != nullptr)
			m_gid = m_tileset->getFirstgid() + m_id - 1;
		else
			m_gid = m_id;
		manageFlipFlagsByIdThenRemoveFlags(m_gid);
		return true;
	}
	return false;
}

/*!
 * Uses tson::Tileset and tson::Map data to calculate related values for tson::Tile.
 * Added in v1.2.0
 */
void tson::Tile::performDataCalculations()
{
	if(m_tileset == nullptr || m_map == nullptr)
		return;

	int firstId = m_tileset->getFirstgid(); //First tile id of the tileset
	int columns = m_tileset->getColumns();
	int rows = m_tileset->getTileCount() / columns;
	int lastId = (m_tileset->getFirstgid() + m_tileset->getTileCount()) - 1;

	if (getGid() >= firstId && getGid() <= lastId)
	{
		int baseTilePosition = ((int)getGid() - firstId);

		int tileModX = (baseTilePosition % columns);
		int currentRow = (baseTilePosition / columns);
		int offsetX = (tileModX != 0) ? ((tileModX) * m_map->getTileSize().x) : (0 * m_map->getTileSize().x);
		int offsetY =  (currentRow < rows-1) ? (currentRow * m_map->getTileSize().y) : ((rows-1) * m_map->getTileSize().y);

		m_drawingRect = { offsetX, offsetY, m_map->getTileSize().x, m_map->getTileSize().y };
	}
	else
		m_drawingRect = {0, 0, 0, 0};
}

/*!
 * Get the position of the tile in pixels based on the tile data position from the current layer.
 * @return The position of the tile in Pixels
 */
const tson::Vector2f tson::Tile::getPosition(const std::tuple<int, int> &tileDataPos)
{
	return {((float) std::get<0>(tileDataPos)) * m_drawingRect.width, ((float) std::get<1>(tileDataPos)) * m_drawingRect.height};
}

// T i l e O b j e c t . h p p
// ---------------------

/*!
 * In cases where the empty constructor is called, this must be called manually
 * for this class to make sense
 * @param posInTileUnits
 * @param tile
 */
void tson::TileObject::initialize(const std::tuple<int, int> &posInTileUnits, tson::Tile *tile)
{
	m_tile = tile;
	m_posInTileUnits = tile->getPositionInTileUnits(posInTileUnits);
	m_position = tile->getPosition(posInTileUnits);
}

const tson::Rect &tson::TileObject::getDrawingRect() const
{
	return m_tile->getDrawingRect();
}

// L a y e r . h p p
// -------------------

/*!
 * Decompresses data if there are matching decompressors
 */
void tson::Layer::decompressData()
{

	tson::DecompressorContainer *container = m_map->getDecompressors();
	if(container->empty())
		return;

	if(m_encoding.empty() && m_compression.empty())
		return;

	std::string data = m_base64Data;
	bool hasBeenDecoded = false;
	if(!m_encoding.empty() && container->contains(m_encoding))
	{
		data = container->get(m_encoding)->decompress(data);
		hasBeenDecoded = true;
	}

	if(!m_compression.empty() && container->contains(m_compression))
	{
		data = container->get(m_compression)->decompress(data);
	}

	if(hasBeenDecoded)
	{
		std::vector<uint8_t> bytes = tson::Tools::Base64DecodedStringToBytes(data);
		m_data = tson::Tools::BytesToUnsignedInts(bytes);
	}
}

// W o r l d . h p p
// ------------------

/*!
 * Loads the actual maps based on the world data.
 * @param parser A Tileson object used for parsing the maps of the world.
 * @return How many maps who were parsed. Remember to call getStatus() for the actual map to find out if everything went okay.
 */

int tson::World::loadMaps(tson::Tileson *parser)
{
	m_maps.clear();
	std::for_each(m_mapData.begin(), m_mapData.end(), [&](const tson::WorldMapData &data)
	{
		if(fs::exists(data.path))
		{
			std::unique_ptr<tson::Map> map = parser->parse(data.path);
			m_maps.push_back(std::move(map));
		}
	});

	return m_maps.size();
}

#endif //TILESON_TILESON_FORWARD_HPP

/*** End of inlined file: tileson_forward.hpp ***/

#endif //TILESON_TILESON_H