Files @ r3355:881cb92af87e
Branch filter:

Location: cpp/openttd-patchpack/source/newgrf.c

celestar
(svn r4150) -Feature: Merged elrails into trunk. Thanks to Tron for lots of code and proofreading, thanks to peter1138 for another lot of code and ideas.
   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
/* $Id$ */

#include "stdafx.h"

#include <stdarg.h>

#include "openttd.h"
#include "debug.h"
#include "gfx.h"
#include "fileio.h"
#include "functions.h"
#include "engine.h"
#include "spritecache.h"
#include "station.h"
#include "sprite.h"
#include "newgrf.h"
#include "variables.h"
#include "bridge.h"
#include "economy.h"
#include "newgrf_engine.h"

/* TTDPatch extended GRF format codec
 * (c) Petr Baudis 2004 (GPL'd)
 * Changes by Florian octo Forster are (c) by the OpenTTD development team.
 *
 * Contains portions of documentation by TTDPatch team.
 * Thanks especially to Josef Drexler for the documentation as well as a lot
 * of help at #tycoon. Also thanks to Michael Blunck for is GRF files which
 * served as subject to the initial testing of this codec. */


uint16 _custom_sprites_base;
static int _skip_sprites; // XXX
static uint _file_index; // XXX
extern int _traininfo_vehicle_pitch;

static GRFFile *_cur_grffile;
GRFFile *_first_grffile;
static int _cur_spriteid;
static int _cur_stage;
static int nfo_line;

/* 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */
static uint32 _ttdpatch_flags[8];


typedef enum grfspec_feature {
	GSF_TRAIN,
	GSF_ROAD,
	GSF_SHIP,
	GSF_AIRCRAFT,
	GSF_STATION,
	GSF_CANAL,
	GSF_BRIDGE,
	GSF_TOWNHOUSE,
	GSF_GLOBALVAR,
} grfspec_feature;


typedef void (*SpecialSpriteHandler)(byte *buf, int len);

static const int _vehcounts[4] = {
	/* GSF_TRAIN */    NUM_TRAIN_ENGINES,
	/* GSF_ROAD */     NUM_ROAD_ENGINES,
	/* GSF_SHIP */     NUM_SHIP_ENGINES,
	/* GSF_AIRCRAFT */ NUM_AIRCRAFT_ENGINES
};

static const int _vehshifts[4] = {
	/* GSF_TRAIN */    0,
	/* GSF_ROAD */     ROAD_ENGINES_INDEX,
	/* GSF_SHIP */     SHIP_ENGINES_INDEX,
	/* GSF_AIRCRAFT */ AIRCRAFT_ENGINES_INDEX,
};

static uint16 cargo_allowed[TOTAL_NUM_ENGINES];
static uint16 cargo_disallowed[TOTAL_NUM_ENGINES];

/* Debugging messages policy:
 *
 * These should be the severities used for direct DEBUG() calls
 * (there is room for exceptions, but you have to have a good cause):
 *
 * 0..2 - dedicated to grfmsg()
 * 3
 * 4
 * 5
 * 6 - action handler entry reporting - one per action
 * 7 - basic action progress reporting - in loops, only single one allowed
 * 8 - more detailed progress reporting - less important stuff, in deep loops etc
 * 9 - extremely detailed progress reporting - detailed reports inside of deep loops and so
 */


typedef enum grfmsg_severity {
	GMS_NOTICE,
	GMS_WARN,
	GMS_ERROR,
	GMS_FATAL,
} grfmsg_severity;

static void CDECL grfmsg(grfmsg_severity severity, const char *str, ...)
{
	static const char* const severitystr[] = {
		"Notice",
		"Warning",
		"Error",
		"Fatal"
	};
	int export_severity = 0;
	char buf[1024];
	va_list va;

	va_start(va, str);
	vsnprintf(buf, sizeof(buf), str, va);
	va_end(va);

	export_severity = 2 - (severity == GMS_FATAL ? 2 : severity);
	DEBUG(grf, export_severity) ("[%s:%d][%s] %s", _cur_grffile->filename, nfo_line, severitystr[severity], buf);
}


#define check_length(real, wanted, where) \
do { \
	if (real < wanted) { \
		grfmsg(GMS_ERROR, "%s: Invalid special sprite length %d (expected %d)!", \
		       where, real, wanted); \
		return; \
	} \
} while (0)


static inline byte grf_load_byte(byte **buf)
{
	return *(*buf)++;
}

static uint16 grf_load_word(byte **buf)
{
	uint16 val;
	byte *p = *buf;
	val = p[0];
	val |= p[1] << 8;
	*buf = p + 2;
	return val;
}

static uint16 grf_load_extended(byte** buf)
{
	uint16 val;
	val = grf_load_byte(buf);
	if (val == 0xFF) val = grf_load_word(buf);
	return val;
}

static uint32 grf_load_dword(byte **buf)
{
	uint32 val;
	byte *p = *buf;
	val = p[0];
	val |= p[1] << 8;
	val |= p[2] << 16;
	val |= p[3] << 24;
	*buf = p + 4;
	return val;
}


static GRFFile *GetFileByGRFID(uint32 grfid)
{
	GRFFile *file;

	for (file = _first_grffile; file != NULL; file = file->next) {
		if (file->grfid == grfid) break;
	}
	return file;
}

static GRFFile *GetFileByFilename(const char *filename)
{
	GRFFile *file;

	for (file = _first_grffile; file != NULL; file = file->next) {
		if (strcmp(file->filename, filename) == 0) break;
	}
	return file;
}


typedef bool (*VCI_Handler)(uint engine, int numinfo, int prop, byte **buf, int len);

#define FOR_EACH_OBJECT for (i = 0; i < numinfo; i++)

static void dewagonize(int condition, int engine)
{
	EngineInfo *ei = &_engine_info[engine];
	RailVehicleInfo *rvi = &_rail_vehicle_info[engine];

	if (condition != 0) {
		ei->unk2 &= ~0x80;
		rvi->flags &= ~2;
	} else {
		ei->unk2 |= 0x80;
		rvi->flags |= 2;
	}
}

static bool RailVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
{
	EngineInfo *ei = &_engine_info[engine];
	RailVehicleInfo *rvi = &_rail_vehicle_info[engine];
	byte *buf = *bufp;
	int i;
	bool ret = false;

	switch (prop) {
		case 0x05: /* Track type */
			FOR_EACH_OBJECT {
				uint8 tracktype = grf_load_byte(&buf);

				switch (tracktype) {
					case 0: ei[i].railtype = RAILTYPE_RAIL; break;
					case 1: ei[i].railtype = RAILTYPE_MONO; break;
					case 2: ei[i].railtype = RAILTYPE_MAGLEV; break;
					default:
						grfmsg(GMS_WARN, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring.", tracktype);
						break;
				}
			}
			break;

		case 0x08: /* AI passenger service */
			/* TODO */
			FOR_EACH_OBJECT grf_load_byte(&buf);
			ret = true;
			break;

		case 0x09: /* Speed */
			FOR_EACH_OBJECT {
				uint16 speed = grf_load_word(&buf);
				if (speed == 0xFFFF) speed = 0;

				rvi[i].max_speed = speed;
			}
			break;

		case 0x0B: /* Power */
			FOR_EACH_OBJECT {
				uint16 power = grf_load_word(&buf);

				if (rvi[i].flags & RVI_MULTIHEAD) power /= 2;

				rvi[i].power = power;
				dewagonize(power, engine + i);
			}
			break;

		case 0x0D: /* Running cost factor */
			FOR_EACH_OBJECT {
				uint8 runcostfact = grf_load_byte(&buf);

				if (rvi[i].flags & RVI_MULTIHEAD) runcostfact /= 2;

				rvi[i].running_cost_base = runcostfact;
			}
			break;

		case 0x0E: /* Running cost base */
			FOR_EACH_OBJECT {
				uint32 base = grf_load_dword(&buf);

				switch (base) {
					case 0x4C30: rvi[i].running_cost_class = 0; break;
					case 0x4C36: rvi[i].running_cost_class = 1; break;
					case 0x4C3C: rvi[i].running_cost_class = 2; break;
				}
			}
			break;

		case 0x12: /* Sprite ID */
			FOR_EACH_OBJECT {
				uint8 spriteid = grf_load_byte(&buf);

				/* TTD sprite IDs point to a location in a 16bit array, but we use it
				 * as an array index, so we need it to be half the original value. */
				if (spriteid < 0xFD) spriteid >>= 1;

				rvi[i].image_index = spriteid;
			}
			break;

		case 0x13: /* Dual-headed */
			FOR_EACH_OBJECT {
				uint8 dual = grf_load_byte(&buf);

				if (dual != 0) {
					if (!(rvi[i].flags & RVI_MULTIHEAD)) {
						// adjust power and running cost if needed
						rvi[i].power /= 2;
						rvi[i].running_cost_base /= 2;
					}
					rvi[i].flags |= RVI_MULTIHEAD;
				} else {
					if (rvi[i].flags & RVI_MULTIHEAD) {
						// adjust power and running cost if needed
						rvi[i].power *= 2;
						rvi[i].running_cost_base *= 2;
					}
					rvi[i].flags &= ~RVI_MULTIHEAD;
				}
			}
			break;

		case 0x14: /* Cargo capacity */
			FOR_EACH_OBJECT rvi[i].capacity = grf_load_byte(&buf);
			break;

		case 0x15: /* Cargo type */
			FOR_EACH_OBJECT {
				uint8 ctype = grf_load_byte(&buf);

				if (ctype < NUM_CARGO) {
					rvi[i].cargo_type = ctype;
				} else {
					grfmsg(GMS_NOTICE, "RailVehicleChangeInfo: Invalid cargo type %d, ignoring.", ctype);
				}
			}
			break;

		case 0x16: /* Weight */
			FOR_EACH_OBJECT SB(rvi[i].weight, 0, 8, grf_load_byte(&buf));
			break;

		case 0x17: /* Cost factor */
			FOR_EACH_OBJECT rvi[i].base_cost = grf_load_byte(&buf);
			break;

		case 0x18: /* AI rank */
			FOR_EACH_OBJECT rvi[i].ai_rank = grf_load_byte(&buf);
			break;

		case 0x19: /* Engine traction type */
			/* What do the individual numbers mean?
			 * 0x00 .. 0x07: Steam
			 * 0x08 .. 0x27: Diesel
			 * 0x28 .. 0x31: Electric
			 * 0x32 .. 0x37: Monorail
			 * 0x38 .. 0x41: Maglev
			 */
			FOR_EACH_OBJECT {
				uint8 traction = grf_load_byte(&buf);
				int engclass;

				if (traction <= 0x07) {
					engclass = 0;
				} else if (traction <= 0x27) {
					engclass = 1;
				} else if (traction <= 0x31) {
					engclass = 2;
					ei[i].railtype = RAILTYPE_ELECTRIC;
				} else if (traction <= 0x41) {
					engclass = 2;
				} else {
					break;
				}

				rvi[i].engclass = engclass;
			}
			break;

		case 0x1A: /* Alter purchase list sort order */
			FOR_EACH_OBJECT {
				EngineID pos = grf_load_byte(&buf);

				if (pos < NUM_TRAIN_ENGINES) {
					AlterRailVehListOrder(engine + i, pos);
				} else {
					grfmsg(GMS_NOTICE, "RailVehicleChangeInfo: Invalid train engine ID %d, ignoring.", pos);
				}
			}
			break;

		case 0x1B: /* Powered wagons power bonus */
			FOR_EACH_OBJECT rvi[i].pow_wag_power = grf_load_word(&buf);
			break;

		case 0x1D: /* Refit cargo */
			FOR_EACH_OBJECT ei[i].refit_mask = grf_load_dword(&buf);
			break;

		case 0x1E: /* Callback */
			FOR_EACH_OBJECT rvi[i].callbackmask = grf_load_byte(&buf);
			break;

		case 0x21: /* Shorter vehicle */
			FOR_EACH_OBJECT rvi[i].shorten_factor = grf_load_byte(&buf);
			break;

		case 0x22: /* Visual effect */
			// see note in engine.h about rvi->visual_effect
			FOR_EACH_OBJECT rvi[i].visual_effect = grf_load_byte(&buf);
			break;

		case 0x23: /* Powered wagons weight bonus */
			FOR_EACH_OBJECT rvi[i].pow_wag_weight = grf_load_byte(&buf);
			break;

		case 0x24: /* High byte of vehicle weight */
			FOR_EACH_OBJECT {
				byte weight = grf_load_byte(&buf);

				if (weight > 4) {
					grfmsg(GMS_NOTICE, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring.", weight << 8);
				} else {
					SB(rvi[i].weight, 8, 8, weight);
				}
			}
			break;

		case 0x27: /* Miscellaneous flags */
			FOR_EACH_OBJECT ei[i].misc_flags = grf_load_byte(&buf);
			break;

		case 0x28: /* Cargo classes allowed */
			FOR_EACH_OBJECT cargo_allowed[engine + i] = grf_load_word(&buf);
			break;

		case 0x29: /* Cargo classes disallowed */
			FOR_EACH_OBJECT cargo_disallowed[engine + i] = grf_load_word(&buf);
			break;

		/* TODO */
		/* Fall-through for unimplemented one byte long properties. */
		case 0x1C: /* Refit cost */
		case 0x1F: /* Tractive effort */
		case 0x20: /* Air drag */
		case 0x25: /* User-defined bit mask to set when checking veh. var. 42 */
		case 0x26: /* Retire vehicle early */
			/* TODO */
			FOR_EACH_OBJECT grf_load_byte(&buf);
			ret = true;
			break;

		default:
			ret = true;
			break;
	}
	*bufp = buf;
	return ret;
}

static bool RoadVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
{
	EngineInfo *ei = &_engine_info[ROAD_ENGINES_INDEX + engine];
	RoadVehicleInfo *rvi = &_road_vehicle_info[engine];
	byte *buf = *bufp;
	int i;
	bool ret = false;

	switch (prop) {
		case 0x08: /* Speed */
			FOR_EACH_OBJECT rvi[i].max_speed = grf_load_byte(&buf); // ?? units
			break;

		case 0x09: /* Running cost factor */
			FOR_EACH_OBJECT rvi[i].running_cost = grf_load_byte(&buf);
			break;

		case 0x0A: /* Running cost base */
			/* TODO: I have no idea. --pasky */
			FOR_EACH_OBJECT grf_load_dword(&buf);
			ret = true;
			break;

		case 0x0E: /* Sprite ID */
			FOR_EACH_OBJECT {
				uint8 spriteid = grf_load_byte(&buf);

				// cars have different custom id in the GRF file
				if (spriteid == 0xFF) spriteid = 0xFD;

				if (spriteid < 0xFD) spriteid >>= 1;

				rvi[i].image_index = spriteid;
			}
			break;

		case 0x0F: /* Cargo capacity */
			FOR_EACH_OBJECT rvi[i].capacity = grf_load_byte(&buf);
			break;

		case 0x10: /* Cargo type */
			FOR_EACH_OBJECT {
				uint8 cargo = grf_load_byte(&buf);

				if (cargo < NUM_CARGO) {
					rvi[i].cargo_type = cargo;
				} else {
					grfmsg(GMS_NOTICE, "RoadVehicleChangeInfo: Invalid cargo type %d, ignoring.", cargo);
				}
			}
			break;

		case 0x11: /* Cost factor */
			FOR_EACH_OBJECT rvi[i].base_cost = grf_load_byte(&buf); // ?? is it base_cost?
			break;

		case 0x12: /* SFX */
			FOR_EACH_OBJECT rvi[i].sfx = grf_load_byte(&buf);
			break;

		case 0x13: /* Power in 10hp */
		case 0x14: /* Weight in 1/4 tons */
		case 0x15: /* Speed in mph*0.8 */
			/* TODO: Support for road vehicles realistic power
			 * computations (called rvpower in TTDPatch) is just
			 * missing in OTTD yet. --pasky */
			FOR_EACH_OBJECT grf_load_byte(&buf);
			ret = true;
			break;

		case 0x16: /* Cargos available for refitting */
			FOR_EACH_OBJECT ei[i].refit_mask = grf_load_dword(&buf);
			break;

		case 0x17: /* Callback mask */
			FOR_EACH_OBJECT rvi[i].callbackmask = grf_load_byte(&buf);
			break;

		case 0x1C: /* Miscellaneous flags */
			FOR_EACH_OBJECT ei[i].misc_flags = grf_load_byte(&buf);
			break;

		case 0x1D: /* Cargo classes allowed */
			FOR_EACH_OBJECT cargo_allowed[ROAD_ENGINES_INDEX + engine + i] = grf_load_word(&buf);
			break;

		case 0x1E: /* Cargo classes disallowed */
			FOR_EACH_OBJECT cargo_disallowed[ROAD_ENGINES_INDEX + engine + i] = grf_load_word(&buf);
			break;

		case 0x18: /* Tractive effort */
		case 0x19: /* Air drag */
		case 0x1A: /* Refit cost */
		case 0x1B: /* Retire vehicle early */
			/* TODO */
			FOR_EACH_OBJECT grf_load_byte(&buf);
			ret = true;
			break;

		default:
			ret = true;
			break;
	}

	*bufp = buf;
	return ret;
}

static bool ShipVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
{
	EngineInfo *ei = &_engine_info[SHIP_ENGINES_INDEX + engine];
	ShipVehicleInfo *svi = &_ship_vehicle_info[engine];
	byte *buf = *bufp;
	int i;
	bool ret = false;

	//printf("e %x prop %x?\n", engine, prop);
	switch (prop) {
		case 0x08: /* Sprite ID */
			FOR_EACH_OBJECT {
				uint8 spriteid = grf_load_byte(&buf);

				// ships have different custom id in the GRF file
				if (spriteid == 0xFF) spriteid = 0xFD;

				if (spriteid < 0xFD) spriteid >>= 1;

				svi[i].image_index = spriteid;
			}
			break;

		case 0x09: /* Refittable */
			FOR_EACH_OBJECT svi[i].refittable = grf_load_byte(&buf);
			break;

		case 0x0A: /* Cost factor */
			FOR_EACH_OBJECT svi[i].base_cost = grf_load_byte(&buf); // ?? is it base_cost?
			break;

		case 0x0B: /* Speed */
			FOR_EACH_OBJECT svi[i].max_speed = grf_load_byte(&buf); // ?? units
			break;

		case 0x0C: /* Cargo type */
			FOR_EACH_OBJECT {
				uint8 cargo = grf_load_byte(&buf);

				// XXX: Need to consult this with patchman yet.
#if 0
				// Documentation claims this is already the
				// per-landscape cargo type id, but newships.grf
				// assume otherwise.
				cargo = local_cargo_id_ctype[cargo];
#endif
				if (cargo < NUM_CARGO) {
					svi[i].cargo_type = cargo;
				} else {
					grfmsg(GMS_NOTICE, "ShipVehicleChangeInfo: Invalid cargo type %d, ignoring.", cargo);
				}
			}
			break;

		case 0x0D: /* Cargo capacity */
			FOR_EACH_OBJECT svi[i].capacity = grf_load_word(&buf);
			break;

		case 0x0F: /* Running cost factor */
			FOR_EACH_OBJECT svi[i].running_cost = grf_load_byte(&buf);
			break;

		case 0x10: /* SFX */
			FOR_EACH_OBJECT svi[i].sfx = grf_load_byte(&buf);
			break;

		case 0x11: /* Cargos available for refitting */
			FOR_EACH_OBJECT ei[i].refit_mask = grf_load_dword(&buf);
			break;

		case 0x12: /* Callback mask */
			FOR_EACH_OBJECT svi[i].callbackmask = grf_load_byte(&buf);
			break;

		case 0x17: /* Miscellaneous flags */
			FOR_EACH_OBJECT ei[i].misc_flags = grf_load_byte(&buf);
			break;

		case 0x18: /* Cargo classes allowed */
			FOR_EACH_OBJECT cargo_allowed[SHIP_ENGINES_INDEX + engine + i] = grf_load_word(&buf);
			break;

		case 0x19: /* Cargo classes disallowed */
			FOR_EACH_OBJECT cargo_disallowed[SHIP_ENGINES_INDEX + engine + i] = grf_load_word(&buf);
			break;

		case 0x13: /* Refit cost */
		case 0x14: /* Ocean speed fraction */
		case 0x15: /* Canal speed fraction */
		case 0x16: /* Retire vehicle early */
			/* TODO */
			FOR_EACH_OBJECT grf_load_byte(&buf);
			ret = true;
			break;

		default:
			ret = true;
			break;
	}

	*bufp = buf;
	return ret;
}

static bool AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
{
	EngineInfo *ei = &_engine_info[AIRCRAFT_ENGINES_INDEX + engine];
	AircraftVehicleInfo *avi = &_aircraft_vehicle_info[engine];
	byte *buf = *bufp;
	int i;
	bool ret = false;

	//printf("e %x prop %x?\n", engine, prop);
	switch (prop) {
		case 0x08: /* Sprite ID */
			FOR_EACH_OBJECT {
				uint8 spriteid = grf_load_byte(&buf);

				// aircraft have different custom id in the GRF file
				if (spriteid == 0xFF) spriteid = 0xFD;

				if (spriteid < 0xFD) spriteid >>= 1;

				avi[i].image_index = spriteid;
			}
			break;

		case 0x09: /* Helicopter */
			FOR_EACH_OBJECT SB(avi[i].subtype, 0, 1, (grf_load_byte(&buf) != 0 ? 1 : 0));
			break;

		case 0x0A: /* Large */
			FOR_EACH_OBJECT SB(avi[i].subtype, 1, 1, (grf_load_byte(&buf) != 0 ? 1 : 0));
			break;

		case 0x0B: /* Cost factor */
			FOR_EACH_OBJECT avi[i].base_cost = grf_load_byte(&buf); // ?? is it base_cost?
			break;

		case 0x0C: /* Speed */
			FOR_EACH_OBJECT avi[i].max_speed = grf_load_byte(&buf); // ?? units
			break;

		case 0x0D: /* Acceleration */
			FOR_EACH_OBJECT avi[i].acceleration = grf_load_byte(&buf);
			break;

		case 0x0E: /* Running cost factor */
			FOR_EACH_OBJECT avi[i].running_cost = grf_load_byte(&buf);
			break;

		case 0x0F: /* Passenger capacity */
			FOR_EACH_OBJECT avi[i].passenger_capacity = grf_load_word(&buf);
			break;

		case 0x11: /* Mail capacity */
			FOR_EACH_OBJECT avi[i].mail_capacity = grf_load_byte(&buf);
			break;

		case 0x12: /* SFX */
			FOR_EACH_OBJECT avi[i].sfx = grf_load_byte(&buf);
			break;

		case 0x13: /* Cargos available for refitting */
			FOR_EACH_OBJECT ei[i].refit_mask = grf_load_dword(&buf);
			break;

		case 0x14: /* Callback mask */
			FOR_EACH_OBJECT avi[i].callbackmask = grf_load_byte(&buf);
			break;

		case 0x17: /* Miscellaneous flags */
			FOR_EACH_OBJECT ei[i].misc_flags = grf_load_byte(&buf);
			break;

		case 0x18: /* Cargo classes allowed */
			FOR_EACH_OBJECT cargo_allowed[AIRCRAFT_ENGINES_INDEX + engine + i] = grf_load_word(&buf);
			break;

		case 0x19: /* Cargo classes disallowed */
			FOR_EACH_OBJECT cargo_disallowed[AIRCRAFT_ENGINES_INDEX + engine + i] = grf_load_word(&buf);
			break;

		case 0x15: /* Refit cost */
		case 0x16: /* Retire vehicle early */
			/* TODO */
			FOR_EACH_OBJECT grf_load_byte(&buf);
			ret = true;
			break;

		default:
			ret = true;
			break;
	}

	*bufp = buf;
	return ret;
}

static bool StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int len)
{
	byte *buf = *bufp;
	int i;
	int ret = 0;

	/* This is one single huge TODO. It doesn't handle anything more than
	 * just waypoints for now. */

	//printf("sci %d %d [0x%02x]\n", stid, numinfo, prop);
	switch (prop) {
		case 0x08:
		{	/* Class ID */
			FOR_EACH_OBJECT {
				StationSpec *stat = &_cur_grffile->stations[stid + i];
				uint32 classid;

				/* classid, for a change, is always little-endian */
				classid = *(buf++) << 24;
				classid |= *(buf++) << 16;
				classid |= *(buf++) << 8;
				classid |= *(buf++);

				stat->sclass = AllocateStationClass(classid);
			}
			break;
		}
		case 0x09:
		{	/* Define sprite layout */
			FOR_EACH_OBJECT {
				StationSpec *stat = &_cur_grffile->stations[stid + i];
				int t;

				stat->tiles = grf_load_extended(&buf);
				stat->renderdata = calloc(stat->tiles, sizeof(*stat->renderdata));
				for (t = 0; t < stat->tiles; t++) {
					DrawTileSprites *dts = &stat->renderdata[t];
					int seq_count = 0;
					PalSpriteID ground_sprite;

					ground_sprite = grf_load_dword(&buf);
					if (ground_sprite == 0) {
						static const DrawTileSeqStruct empty = {0x80, 0, 0, 0, 0, 0, 0};
						dts->seq = &empty;
						continue;
					}

					if (HASBIT(ground_sprite, 31)) {
						// Bit 31 indicates that we should use a custom sprite.
						dts->ground_sprite = GB(ground_sprite, 0, 15) - 0x42D;
						dts->ground_sprite += _cur_grffile->first_spriteset;
					} else {
						dts->ground_sprite = ground_sprite;
					}

					dts->seq = NULL;
					while (buf < *bufp + len) {
						DrawTileSeqStruct *dtss;

						// no relative bounding box support
						dts->seq = realloc((void*)dts->seq, ++seq_count * sizeof(DrawTileSeqStruct));
						dtss = (DrawTileSeqStruct*) &dts->seq[seq_count - 1];

						dtss->delta_x = grf_load_byte(&buf);
						if ((byte) dtss->delta_x == 0x80) break;
						dtss->delta_y = grf_load_byte(&buf);
						dtss->delta_z = grf_load_byte(&buf);
						dtss->width = grf_load_byte(&buf);
						dtss->height = grf_load_byte(&buf);
						dtss->unk = grf_load_byte(&buf);
						dtss->image = grf_load_dword(&buf) - 0x42d;
					}
				}
			}
			break;
		}
		case 0x0a:
		{	/* Copy sprite layout */
			FOR_EACH_OBJECT {
				StationSpec *stat = &_cur_grffile->stations[stid + i];
				byte srcid = grf_load_byte(&buf);
				const StationSpec *srcstat = &_cur_grffile->stations[srcid];
				int t;

				stat->tiles = srcstat->tiles;
				stat->renderdata = calloc(stat->tiles, sizeof(*stat->renderdata));
				for (t = 0; t < stat->tiles; t++) {
					DrawTileSprites *dts = &stat->renderdata[t];
					const DrawTileSprites *sdts = &srcstat->renderdata[t];
					DrawTileSeqStruct const *sdtss = sdts->seq;
					int seq_count = 0;

					dts->ground_sprite = sdts->ground_sprite;
					if (!dts->ground_sprite) {
						static const DrawTileSeqStruct empty = {0x80, 0, 0, 0, 0, 0, 0};
						dts->seq = &empty;
						continue;
					}

					dts->seq = NULL;
					while (1) {
						DrawTileSeqStruct *dtss;

						// no relative bounding box support
						dts->seq = realloc((void*)dts->seq, ++seq_count * sizeof(DrawTileSeqStruct));
						dtss = (DrawTileSeqStruct*) &dts->seq[seq_count - 1];
						*dtss = *sdtss;
						if ((byte) dtss->delta_x == 0x80) break;
						sdtss++;
					}
				}
			}
			break;
		}
		case 0x0b:
		{	/* Callback */
			/* TODO */
			FOR_EACH_OBJECT {
				grf_load_byte(&buf);
			}
			ret = 1;
			break;
		}
		case 0x0C:
		{	/* Platforms number */
			FOR_EACH_OBJECT {
				StationSpec *stat = &_cur_grffile->stations[stid + i];

				stat->allowed_platforms = ~grf_load_byte(&buf);
			}
			break;
		}
		case 0x0D:
		{	/* Platforms length */
			FOR_EACH_OBJECT {
				StationSpec *stat = &_cur_grffile->stations[stid + i];

				stat->allowed_lengths = ~grf_load_byte(&buf);
			}
			break;
		}
		case 0x0e:
		{	/* Define custom layout */
			FOR_EACH_OBJECT {
				StationSpec *stat = &_cur_grffile->stations[stid + i];

				while (buf < *bufp + len) {
					byte length = grf_load_byte(&buf);
					byte number = grf_load_byte(&buf);
					StationLayout layout;
					int l, p;

					if (length == 0 || number == 0) break;

					//debug("l %d > %d ?", length, stat->lengths);
					if (length > stat->lengths) {
						stat->platforms = realloc(stat->platforms, length);
						memset(stat->platforms + stat->lengths, 0, length - stat->lengths);

						stat->layouts = realloc(stat->layouts, length * sizeof(*stat->layouts));
						memset(stat->layouts + stat->lengths, 0,
						       (length - stat->lengths) * sizeof(*stat->layouts));

						stat->lengths = length;
					}
					l = length - 1; // index is zero-based

					//debug("p %d > %d ?", number, stat->platforms[l]);
					if (number > stat->platforms[l]) {
						stat->layouts[l] = realloc(stat->layouts[l],
						                               number * sizeof(**stat->layouts));
						// We expect NULL being 0 here, but C99 guarantees that.
						memset(stat->layouts[l] + stat->platforms[l], 0,
						       (number - stat->platforms[l]) * sizeof(**stat->layouts));

						stat->platforms[l] = number;
					}

					p = 0;
					layout = malloc(length * number);
					for (l = 0; l < length; l++) {
						for (p = 0; p < number; p++) {
							layout[l * number + p] = grf_load_byte(&buf);
						}
					}

					l--;
					p--;
					assert(p >= 0);
					free(stat->layouts[l][p]);
					stat->layouts[l][p] = layout;
				}
			}
			break;
		}
		case 0x0f:
		{	/* Copy custom layout */
			/* TODO */
			FOR_EACH_OBJECT {
				grf_load_byte(&buf);
			}
			ret = 1;
			break;
		}
		case 0x10:
		{	/* Little/lots cargo threshold */
			/* TODO */
			FOR_EACH_OBJECT {
				grf_load_word(&buf);
			}
			ret = 1;
			break;
		}
		case 0x11:
		{	/* Pylon placement */
			/* TODO; makes sense only for electrified tracks */
			FOR_EACH_OBJECT {
				grf_load_word(&buf);
			}
			ret = 1;
			break;
		}
		case 0x12:
		{	/* Cargo types for random triggers */
			/* TODO */
			FOR_EACH_OBJECT {
				grf_load_dword(&buf);
			}
			ret = 1;
			break;
		}
		default:
			ret = 1;
			break;
	}

	*bufp = buf;
	return ret;
}

static bool BridgeChangeInfo(uint brid, int numinfo, int prop, byte **bufp, int len)
{
	byte *buf = *bufp;
	int i;
	int ret = 0;

	switch (prop) {
		case 0x08: /* Year of availability */
			FOR_EACH_OBJECT _bridge[brid + i].avail_year = grf_load_byte(&buf);
			break;

		case 0x09: /* Minimum length */
			FOR_EACH_OBJECT _bridge[brid + i].min_length = grf_load_byte(&buf);
			break;

		case 0x0A: /* Maximum length */
			FOR_EACH_OBJECT _bridge[brid + i].max_length = grf_load_byte(&buf);
			break;

		case 0x0B: /* Cost factor */
			FOR_EACH_OBJECT _bridge[brid + i].price = grf_load_byte(&buf);
			break;

		case 0x0C: /* Maximum speed */
			FOR_EACH_OBJECT _bridge[brid + i].speed = grf_load_word(&buf);
			break;

		case 0x0D: /* Bridge sprite tables */
			FOR_EACH_OBJECT {
				Bridge *bridge = &_bridge[brid + i];
				byte tableid = grf_load_byte(&buf);
				byte numtables = grf_load_byte(&buf);
				byte table, sprite;

				if (bridge->sprite_table == NULL) {
					/* Allocate memory for sprite table pointers and set to NULL */
					bridge->sprite_table = malloc(7 * sizeof(*bridge->sprite_table));
					for (table = 0; table < 7; table++)
						bridge->sprite_table[table] = NULL;
				}

				for (table = tableid; table < tableid + numtables; table++) {
					if (table < 7) {
						if (bridge->sprite_table[table] == NULL) {
							bridge->sprite_table[table] = malloc(32 * sizeof(**bridge->sprite_table));
						}

						for (sprite = 0; sprite < 32; sprite++)
							bridge->sprite_table[table][sprite] = grf_load_dword(&buf);
					} else {
						grfmsg(GMS_WARN, "BridgeChangeInfo: Table %d >= 7, skipping.", table);
						// Skip past invalid data.
						for (sprite = 0; sprite < 32; sprite++)
							grf_load_dword(&buf);
					}
				}
			}
			break;

		case 0x0E: /* Flags; bit 0 - disable far pillars */
			FOR_EACH_OBJECT _bridge[brid + i].flags = grf_load_byte(&buf);
			break;

		default:
			ret = 1;
	}

	*bufp = buf;
	return ret;
}

static bool GlobalVarChangeInfo(uint gvid, int numinfo, int prop, byte **bufp, int len)
{
	byte *buf = *bufp;
	int i;
	bool ret = false;

	switch (prop) {
		case 0x08: { /* Cost base factor */
			FOR_EACH_OBJECT {
				byte factor = grf_load_byte(&buf);
				uint price = gvid + i;

				if (price < NUM_PRICES) {
					SetPriceBaseMultiplier(price, factor);
				} else {
					grfmsg(GMS_WARN, "GlobalVarChangeInfo: Price %d out of range, ignoring.", price);
				}
			}
		} break;
		default:
			ret = true;
	}
	*bufp = buf;
	return ret;
}

/* Action 0x00 */
static void VehicleChangeInfo(byte *buf, int len)
{
	byte *bufend = buf + len;
	int i;

	/* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
	 *
	 * B feature       0, 1, 2 or 3 for trains, road vehicles, ships or planes
	 *                 4 for defining new train station sets
	 * B num-props     how many properties to change per vehicle/station
	 * B num-info      how many vehicles/stations to change
	 * B id            ID of first vehicle/station to change, if num-info is
	 *                 greater than one, this one and the following
	 *                 vehicles/stations will be changed
	 * B property      what property to change, depends on the feature
	 * V new-info      new bytes of info (variable size; depends on properties) */
	/* TODO: Bridges, town houses. */

	static const VCI_Handler handler[] = {
		/* GSF_TRAIN */    RailVehicleChangeInfo,
		/* GSF_ROAD */     RoadVehicleChangeInfo,
		/* GSF_SHIP */     ShipVehicleChangeInfo,
		/* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
		/* GSF_STATION */  StationChangeInfo,
		/* GSF_CANAL */    NULL,
		/* GSF_BRIDGE */   BridgeChangeInfo,
		/* GSF_TOWNHOUSE */NULL,
		/* GSF_GLOBALVAR */GlobalVarChangeInfo,
	};

	uint8 feature;
	uint8 numprops;
	uint8 numinfo;
	byte engine;
	EngineInfo *ei = NULL;

	if (len == 1) {
		DEBUG(grf, 8) ("Silently ignoring one-byte special sprite 0x00.");
		return;
	}

	check_length(len, 6, "VehicleChangeInfo");
	feature = buf[1];
	numprops = buf[2];
	numinfo = buf[3];
	engine = buf[4];

	DEBUG(grf, 6) ("VehicleChangeInfo: Feature %d, %d properties, to apply to %d+%d",
	               feature, numprops, engine, numinfo);

	if (feature >= lengthof(handler) || handler[feature] == NULL) {
		grfmsg(GMS_WARN, "VehicleChangeInfo: Unsupported feature %d, skipping.", feature);
		return;
	}

	if (feature <= GSF_AIRCRAFT) {
		if (engine + numinfo > _vehcounts[feature]) {
			grfmsg(GMS_ERROR, "VehicleChangeInfo: Last engine ID %d out of bounds (max %d), skipping.", engine + numinfo, _vehcounts[feature]);
			return;
		}
		ei = &_engine_info[engine + _vehshifts[feature]];
	}

	buf += 5;

	while (numprops-- && buf < bufend) {
		uint8 prop = grf_load_byte(&buf);
		bool ignoring = false;

		switch (feature) {
			case GSF_TRAIN:
			case GSF_ROAD:
			case GSF_SHIP:
			case GSF_AIRCRAFT:
				/* Common properties for vehicles */
				switch (prop) {
					case 0x00: /* Introduction date */
						FOR_EACH_OBJECT ei[i].base_intro = grf_load_word(&buf);
						break;

					case 0x02: /* Decay speed */
						FOR_EACH_OBJECT SB(ei[i].unk2, 0, 7, grf_load_byte(&buf) & 0x7F);
						break;

					case 0x03: /* Vehicle life */
						FOR_EACH_OBJECT ei[i].lifelength = grf_load_byte(&buf);
						break;

					case 0x04: /* Model life */
						FOR_EACH_OBJECT ei[i].base_life = grf_load_byte(&buf);
						break;

					case 0x06: /* Climates available */
						FOR_EACH_OBJECT ei[i].climates = grf_load_byte(&buf);
						break;

					case 0x07: /* Loading speed */
						/* TODO */
						/* Hyronymus explained me what does
						 * this mean and insists on having a
						 * credit ;-). --pasky */
						/* TODO: This needs to be supported by
						 * LoadUnloadVehicle() first. */
						FOR_EACH_OBJECT grf_load_byte(&buf);
						ignoring = true;
						break;

					default:
						if (handler[feature](engine, numinfo, prop, &buf, bufend - buf))
							ignoring = true;
						break;
				}
				break;

			default:
				if (handler[feature](engine, numinfo, prop, &buf, bufend - buf))
					ignoring = true;
				break;
		}

		if (ignoring)
			grfmsg(GMS_NOTICE, "VehicleChangeInfo: Ignoring property %x (not implemented).", prop);
	}
}

#undef FOR_EACH_OBJECT

/**
 * Creates a spritegroup representing a callback result
 * @param value The value that was used to represent this callback result
 * @return A spritegroup representing that callback result
 */
static SpriteGroup* NewCallBackResultSpriteGroup(uint16 value)
{
	SpriteGroup *group = calloc(1, sizeof(*group));

	group->type = SGT_CALLBACK;

	// Old style callback results have the highest byte 0xFF so signify it is a callback result
	// New style ones only have the highest bit set (allows 15-bit results, instead of just 8)
	if ((value >> 8) == 0xFF) {
		value &= ~0xFF00;
	} else {
		value &= ~0x8000;
	}

	group->g.callback.result = value;

	return group;
}

/**
 * Creates a spritegroup representing a sprite number result.
 * @param value The sprite number.
 * @param sprites The number of sprites per set.
 * @return A spritegroup representing the sprite number result.
 */
static SpriteGroup* NewResultSpriteGroup(uint16 value, byte sprites)
{
	SpriteGroup *group = calloc(1, sizeof(*group));
	group->type = SGT_RESULT;
	group->g.result.result = value;
	group->g.result.sprites = sprites;
	return group;
}

/* Action 0x01 */
static void NewSpriteSet(byte *buf, int len)
{
	/* <01> <feature> <num-sets> <num-ent>
	 *
	 * B feature       feature to define sprites for
	 *                 0, 1, 2, 3: veh-type, 4: train stations
	 * B num-sets      number of sprite sets
	 * E num-ent       how many entries per sprite set
	 *                 For vehicles, this is the number of different
	 *                         vehicle directions in each sprite set
	 *                         Set num-dirs=8, unless your sprites are symmetric.
	 *                         In that case, use num-dirs=4.
	 *                 For stations, must be 12 (hex) for the eighteen
	 *                         different sprites that make up a station */
	/* TODO: No stations support. */
	uint8 feature;
	uint num_sets;
	uint num_ents;
	uint i;

	check_length(len, 4, "NewSpriteSet");
	buf++;
	feature  = grf_load_byte(&buf);
	num_sets = grf_load_byte(&buf);
	num_ents = grf_load_extended(&buf);

	_cur_grffile->spriteset_start = _cur_spriteid;
	_cur_grffile->spriteset_feature = feature;
	_cur_grffile->spriteset_numsets = num_sets;
	_cur_grffile->spriteset_numents = num_ents;

	DEBUG(grf, 7) (
		"New sprite set at %d of type %d, "
		"consisting of %d sets with %d views each (total %d)",
		_cur_spriteid, feature, num_sets, num_ents, num_sets * num_ents
	);

	for (i = 0; i < num_sets * num_ents; i++) {
		LoadNextSprite(_cur_spriteid++, _file_index);
		nfo_line++;
	}
}

/* Action 0x02 */
static void NewSpriteGroup(byte *buf, int len)
{
	byte *bufend = buf + len;

	/* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
	 *
	 * B feature       see action 1
	 * B set-id        ID of this particular definition
	 * B type/num-entries
	 *                 if 80 or greater, this is a randomized or variational
	 *                 list definition, see below
	 *                 otherwise it specifies a number of entries, the exact
	 *                 meaning depends on the feature
	 * V feature-specific-data (huge mess, don't even look it up --pasky) */
	/* TODO: No 0x80-types (ugh). */
	/* TODO: Also, empty sprites aren't handled for now. Need to investigate
	 * the "opacity" rules for these, that is which sprite to fall back to
	 * when. --pasky */
	uint8 feature;
	uint8 setid;
	/* XXX: For stations, these two are "little cargo" and "lotsa cargo" sets. */
	uint8 numloaded;
	uint8 numloading;
	SpriteGroup *group;
	RealSpriteGroup *rg;
	byte *loaded_ptr;
	byte *loading_ptr;
	int i;

	check_length(len, 5, "NewSpriteGroup");
	feature = buf[1];
	setid = buf[2];
	numloaded = buf[3];
	numloading = buf[4];

	if (setid >= _cur_grffile->spritegroups_count) {
		// Allocate memory for new sprite group references.
		_cur_grffile->spritegroups = realloc(_cur_grffile->spritegroups, (setid + 1) * sizeof(*_cur_grffile->spritegroups));
		// Initialise new space to NULL
		for (; _cur_grffile->spritegroups_count < (setid + 1); _cur_grffile->spritegroups_count++)
			_cur_grffile->spritegroups[_cur_grffile->spritegroups_count] = NULL;
	}

	if (numloaded == 0x81 || numloaded == 0x82) {
		DeterministicSpriteGroup *dg;
		uint16 groupid;
		int i;

		// Ok, this is gonna get a little wild, so hold your breath...

		/* This stuff is getting actually evaluated in
		 * EvalDeterministicSpriteGroup(). */

		buf += 4; len -= 4;
		check_length(len, 6, "NewSpriteGroup 0x81/0x82");

		group = calloc(1, sizeof(*group));
		group->type = SGT_DETERMINISTIC;
		dg = &group->g.determ;

		/* XXX: We don't free() anything, assuming that if there was
		 * some action here before, it got associated by action 3.
		 * We should perhaps keep some refcount? --pasky */

		dg->var_scope = numloaded == 0x82 ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
		dg->variable = grf_load_byte(&buf);
		/* Variables 0x60 - 0x7F include an extra parameter */
		if (IS_BYTE_INSIDE(dg->variable, 0x60, 0x80))
			dg->parameter = grf_load_byte(&buf);

		dg->shift_num = grf_load_byte(&buf);
		dg->and_mask = grf_load_byte(&buf);
		dg->operation = dg->shift_num >> 6; /* w00t */
		dg->shift_num &= 0x3F;
		if (dg->operation != DSG_OP_NONE) {
			dg->add_val = grf_load_byte(&buf);
			dg->divmod_val = grf_load_byte(&buf);
		}

		/* (groupid & 0x8000) means this is callback result. */

		dg->num_ranges = grf_load_byte(&buf);
		dg->ranges = calloc(dg->num_ranges, sizeof(*dg->ranges));
		for (i = 0; i < dg->num_ranges; i++) {
			groupid = grf_load_word(&buf);
			if (HASBIT(groupid, 15)) {
				dg->ranges[i].group = NewCallBackResultSpriteGroup(groupid);
				dg->ranges[i].group->ref_count++;
			} else if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
				grfmsg(GMS_WARN, "NewSpriteGroup(%02x:0x%x): Groupid %04x does not exist, leaving empty.", setid, numloaded, groupid);
				dg->ranges[i].group = NULL;
			} else {
				dg->ranges[i].group = _cur_grffile->spritegroups[groupid];
				dg->ranges[i].group->ref_count++;
			}

			dg->ranges[i].low = grf_load_byte(&buf);
			dg->ranges[i].high = grf_load_byte(&buf);
		}

		groupid = grf_load_word(&buf);
		if (HASBIT(groupid, 15)) {
			dg->default_group = NewCallBackResultSpriteGroup(groupid);
			dg->default_group->ref_count++;
		} else if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
			grfmsg(GMS_WARN, "NewSpriteGroup(%02x:0x%x): Groupid %04x does not exist, leaving empty.", setid, numloaded, groupid);
			dg->default_group = NULL;
		} else {
			dg->default_group = _cur_grffile->spritegroups[groupid];
		dg->default_group->ref_count++;
		}

		if (_cur_grffile->spritegroups[setid] != NULL)
			UnloadSpriteGroup(&_cur_grffile->spritegroups[setid]);
		_cur_grffile->spritegroups[setid] = group;
		group->ref_count++;
		return;

	} else if (numloaded == 0x80 || numloaded == 0x83) {
		RandomizedSpriteGroup *rg;
		int i;

		/* This stuff is getting actually evaluated in
		 * EvalRandomizedSpriteGroup(). */

		buf += 4;
		len -= 4;
		check_length(len, 6, "NewSpriteGroup 0x80/0x83");

		group = calloc(1, sizeof(*group));
		group->type = SGT_RANDOMIZED;
		rg = &group->g.random;

		/* XXX: We don't free() anything, assuming that if there was
		 * some action here before, it got associated by action 3.
		 * We should perhaps keep some refcount? --pasky */

		rg->var_scope = numloaded == 0x83 ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;

		rg->triggers = grf_load_byte(&buf);
		rg->cmp_mode = rg->triggers & 0x80;
		rg->triggers &= 0x7F;

		rg->lowest_randbit = grf_load_byte(&buf);
		rg->num_groups = grf_load_byte(&buf);

		rg->groups = calloc(rg->num_groups, sizeof(*rg->groups));
		for (i = 0; i < rg->num_groups; i++) {
			uint16 groupid = grf_load_word(&buf);

			if (HASBIT(groupid, 15)) {
				rg->groups[i] = NewCallBackResultSpriteGroup(groupid);
				rg->groups[i]->ref_count++;
			} else if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
				grfmsg(GMS_WARN, "NewSpriteGroup(%02x:0x%x): Groupid %04x does not exist, leaving empty.", setid, numloaded, groupid);
				rg->groups[i] = NULL;
			} else {
				rg->groups[i] = _cur_grffile->spritegroups[groupid];
				rg->groups[i]->ref_count++;
			}
		}

		if (_cur_grffile->spritegroups[setid] != NULL)
			UnloadSpriteGroup(&_cur_grffile->spritegroups[setid]);
		_cur_grffile->spritegroups[setid] = group;
		group->ref_count++;
		return;
	}

	if (!_cur_grffile->spriteset_start) {
		grfmsg(GMS_ERROR, "NewSpriteGroup: No sprite set to work on! Skipping.");
		return;
	}

	if (_cur_grffile->spriteset_feature != feature) {
		grfmsg(GMS_ERROR, "NewSpriteGroup: Group feature %x doesn't match set feature %x! Playing it risky and trying to use it anyway.", feature, _cur_grffile->spriteset_feature);
		// return; // XXX: we can't because of MB's newstats.grf --pasky
	}

	check_length(bufend - buf, 5, "NewSpriteGroup");
	buf += 5;
	check_length(bufend - buf, 2 * numloaded, "NewSpriteGroup");
	loaded_ptr = buf;
	loading_ptr = buf + 2 * numloaded;

	if (_cur_grffile->first_spriteset == 0)
		_cur_grffile->first_spriteset = _cur_grffile->spriteset_start;

	if (numloaded > 16) {
		grfmsg(GMS_WARN, "NewSpriteGroup: More than 16 sprites in group %x, skipping the rest.", setid);
		numloaded = 16;
	}
	if (numloading > 16) {
		grfmsg(GMS_WARN, "NewSpriteGroup: More than 16 sprites in group %x, skipping the rest.", setid);
		numloading = 16;
	}

	group = calloc(1, sizeof(*group));
	group->type = SGT_REAL;
	rg = &group->g.real;

	rg->sprites_per_set = _cur_grffile->spriteset_numents;
	rg->loaded_count  = numloaded;
	rg->loading_count = numloading;

	DEBUG(grf, 6) ("NewSpriteGroup: New SpriteGroup 0x%02hhx, %u views, %u loaded, %u loading, sprites %u - %u",
			setid, rg->sprites_per_set, rg->loaded_count, rg->loading_count,
			_cur_grffile->spriteset_start - _cur_grffile->sprite_offset,
			_cur_grffile->spriteset_start + (_cur_grffile->spriteset_numents * (numloaded + numloading)) - _cur_grffile->sprite_offset);

	for (i = 0; i < numloaded; i++) {
		uint16 spriteset_id = grf_load_word(&loaded_ptr);
		if (HASBIT(spriteset_id, 15)) {
			rg->loaded[i] = NewCallBackResultSpriteGroup(spriteset_id);
		} else {
			rg->loaded[i] = NewResultSpriteGroup(_cur_grffile->spriteset_start + spriteset_id * _cur_grffile->spriteset_numents, rg->sprites_per_set);
		}
		rg->loaded[i]->ref_count++;
		DEBUG(grf, 8) ("NewSpriteGroup: + rg->loaded[%i]  = %u (subset %u)", i, rg->loaded[i]->g.result.result, spriteset_id);
	}

	for (i = 0; i < numloading; i++) {
		uint16 spriteset_id = grf_load_word(&loading_ptr);
		if (HASBIT(spriteset_id, 15)) {
			rg->loading[i] = NewCallBackResultSpriteGroup(spriteset_id);
		} else {
			rg->loading[i] = NewResultSpriteGroup(_cur_grffile->spriteset_start + spriteset_id * _cur_grffile->spriteset_numents, rg->sprites_per_set);
		}
		rg->loading[i]->ref_count++;
		DEBUG(grf, 8) ("NewSpriteGroup: + rg->loading[%i] = %u (subset %u)", i, rg->loading[i]->g.result.result, spriteset_id);
	}

	if (_cur_grffile->spritegroups[setid] != NULL)
		UnloadSpriteGroup(&_cur_grffile->spritegroups[setid]);
	_cur_grffile->spritegroups[setid] = group;
	group->ref_count++;
}

/* Action 0x03 */
static void NewVehicle_SpriteGroupMapping(byte *buf, int len)
{
	/* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
	 * id-list	:= [<id>] [id-list]
	 * cargo-list	:= <cargo-type> <cid> [cargo-list]
	 *
	 * B feature       see action 0
	 * B n-id          bits 0-6: how many IDs this definition applies to
	 *                 bit 7: if set, this is a wagon override definition (see below)
	 * B ids           the IDs for which this definition applies
	 * B num-cid       number of cargo IDs (sprite group IDs) in this definition
	 *                 can be zero, in that case the def-cid is used always
	 * B cargo-type    type of this cargo type (e.g. mail=2, wood=7, see below)
	 * W cid           cargo ID (sprite group ID) for this type of cargo
	 * W def-cid       default cargo ID (sprite group ID) */
	/* TODO: Bridges, town houses. */
	/* TODO: Multiple cargo support could be useful even for trains/cars -
	 * cargo id 0xff is used for showing images in the build train list. */

	static byte *last_engines;
	static int last_engines_count;
	uint8 feature;
	uint8 idcount;
	bool wagover;
	uint8 cidcount;
	int c, i;

	check_length(len, 7, "VehicleMapSpriteGroup");
	feature = buf[1];
	idcount = buf[2] & 0x7F;
	wagover = (buf[2] & 0x80) == 0x80;
	check_length(len, 3 + idcount, "VehicleMapSpriteGroup");
	cidcount = buf[3 + idcount];
	check_length(len, 4 + idcount + cidcount * 3, "VehicleMapSpriteGroup");

	DEBUG(grf, 6) ("VehicleMapSpriteGroup: Feature %d, %d ids, %d cids, wagon override %d.",
			feature, idcount, cidcount, wagover);

	if (feature > GSF_STATION) {
		grfmsg(GMS_WARN, "VehicleMapSpriteGroup: Unsupported feature %d, skipping.", feature);
		return;
	}


	if (feature == GSF_STATION) {
		// We do things differently for stations.

		for (i = 0; i < idcount; i++) {
			uint8 stid = buf[3 + i];
			StationSpec *stat = &_cur_grffile->stations[stid];
			byte *bp = &buf[4 + idcount];

			for (c = 0; c < cidcount; c++) {
				uint8 ctype = grf_load_byte(&bp);
				uint16 groupid = grf_load_word(&bp);

				if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
					grfmsg(GMS_WARN, "VehicleMapSpriteGroup: Spriteset %x out of range %x or empty, skipping.",
					       groupid, _cur_grffile->spritegroups_count);
					return;
				}

				if (ctype != 0xFF) {
					/* TODO: No support for any other cargo. */
					continue;
				}

				stat->spritegroup[1] = _cur_grffile->spritegroups[groupid];
				stat->spritegroup[1]->ref_count++;
			}
		}

		{
			byte *bp = buf + 4 + idcount + cidcount * 3;
			uint16 groupid = grf_load_word(&bp);

			if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
				grfmsg(GMS_WARN, "VehicleMapSpriteGroup: Spriteset %x out of range %x or empty, skipping.",
				       groupid, _cur_grffile->spritegroups_count);
				return;
			}

			for (i = 0; i < idcount; i++) {
				uint8 stid = buf[3 + i];
				StationSpec *stat = &_cur_grffile->stations[stid];

				stat->spritegroup[0] = _cur_grffile->spritegroups[groupid];
				stat->spritegroup[0]->ref_count++;
				stat->grfid = _cur_grffile->grfid;
				stat->localidx = stid;
				SetCustomStation(stat);
			}
		}
		return;
	}


	/* If ``n-id'' (or ``idcount'') is zero, this is a ``feature
	 * callback''. I have no idea how this works, so we will ignore it for
	 * now.  --octo */
	if (idcount == 0) {
		grfmsg(GMS_NOTICE, "NewMapping: Feature callbacks not implemented yet.");
		return;
	}

	// FIXME: Tropicset contains things like:
	// 03 00 01 19 01 00 00 00 00 - this is missing one 00 at the end,
	// what should we exactly do with that? --pasky

	if (!_cur_grffile->spriteset_start || !_cur_grffile->spritegroups) {
		grfmsg(GMS_WARN, "VehicleMapSpriteGroup: No sprite set to work on! Skipping.");
		return;
	}

	if (!wagover && last_engines_count != idcount) {
		last_engines = realloc(last_engines, idcount);
		last_engines_count = idcount;
	}

	if (wagover) {
		if (last_engines_count == 0) {
			grfmsg(GMS_ERROR, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with.");
			return;
		}
		DEBUG(grf, 6) ("VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons.",
				last_engines_count, idcount);
	}


	for (i = 0; i < idcount; i++) {
		uint8 engine_id = buf[3 + i];
		uint8 engine = engine_id + _vehshifts[feature];
		byte *bp = &buf[4 + idcount];

		if (engine_id > _vehcounts[feature]) {
			grfmsg(GMS_ERROR, "Id %u for feature %x is out of bounds.",
					engine_id, feature);
			return;
		}

		DEBUG(grf, 7) ("VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);

		for (c = 0; c < cidcount; c++) {
			uint8 ctype = grf_load_byte(&bp);
			uint16 groupid = grf_load_word(&bp);

			DEBUG(grf, 8) ("VehicleMapSpriteGroup: * [%d] Cargo type %x, group id %x", c, ctype, groupid);

			if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
				grfmsg(GMS_WARN, "VehicleMapSpriteGroup: Spriteset %x out of range %x or empty, skipping.", groupid, _cur_grffile->spritegroups_count);
				return;
			}

			if (ctype == GC_INVALID) ctype = GC_PURCHASE;

			if (wagover) {
				// TODO: No multiple cargo types per vehicle yet. --pasky
				SetWagonOverrideSprites(engine, _cur_grffile->spritegroups[groupid], last_engines, last_engines_count);
			} else {
				SetCustomEngineSprites(engine, ctype, _cur_grffile->spritegroups[groupid]);
				last_engines[i] = engine;
			}
		}
	}

	{
		byte *bp = buf + 4 + idcount + cidcount * 3;
		uint16 groupid = grf_load_word(&bp);

		DEBUG(grf, 8) ("-- Default group id %x", groupid);

		for (i = 0; i < idcount; i++) {
			uint8 engine = buf[3 + i] + _vehshifts[feature];

			// Don't tell me you don't love duplicated code!
			if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
				grfmsg(GMS_WARN, "VehicleMapSpriteGroup: Spriteset %x out of range %x or empty, skipping.", groupid, _cur_grffile->spritegroups_count);
				return;
			}

			if (wagover) {
				// TODO: No multiple cargo types per vehicle yet. --pasky
				SetWagonOverrideSprites(engine, _cur_grffile->spritegroups[groupid], last_engines, last_engines_count);
			} else {
				SetCustomEngineSprites(engine, GC_DEFAULT, _cur_grffile->spritegroups[groupid]);
				last_engines[i] = engine;
			}
		}
	}
}

/* Action 0x04 */
static void VehicleNewName(byte *buf, int len)
{
	/* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
	 *
	 * B veh-type      see action 0
	 * B language-id   language ID with bit 7 cleared (see below)
	 * B num-veh       number of vehicles which are getting a new name
	 * B/W offset      number of the first vehicle that gets a new name
	 * S data          new texts, each of them zero-terminated, after
	 *                 which the next name begins. */
	/* TODO: No support for changing non-vehicle text. Perhaps we shouldn't
	 * implement it at all, but it could be useful for some "modpacks"
	 * (completely new scenarios changing all graphics and logically also
	 * factory names etc). We should then also support all languages (by
	 * name), not only the original four ones. --pasky */
	/* TODO: Support for custom station class/type names. */

	uint8 feature;
	uint8 lang;
	uint8 num;
	uint16 id;
	uint16 endid;
	const char* name;

	check_length(len, 6, "VehicleNewName");
	buf++;
	feature  = grf_load_byte(&buf);
	lang     = grf_load_byte(&buf);
	num      = grf_load_byte(&buf);
	id       = (lang & 0x80) ? grf_load_word(&buf) : grf_load_byte(&buf);

	if (feature > 3) {
		DEBUG(grf, 7) ("VehicleNewName: Unsupported feature %d, skipping", feature);
		return;
	}

	id      += _vehshifts[feature];
	endid    = id + num;

	DEBUG(grf, 6) ("VehicleNewName: About to rename engines %d..%d (feature %d) in language 0x%x.",
	               id, endid, feature, lang);

	if (lang & 0x80) {
		grfmsg(GMS_WARN, "VehicleNewName: No support for changing in-game texts. Skipping.");
		return;
	}

	if (!(lang & 3)) {
		/* XXX: If non-English name, silently skip it. */
		DEBUG(grf, 7) ("VehicleNewName: Skipping non-English name.");
		return;
	}

	name = (const char*)buf;
	len -= (lang & 0x80) ? 6 : 5;
	for (; id < endid && len > 0; id++) {
		size_t ofs = strlen(name) + 1;

		if (ofs < 128) {
			DEBUG(grf, 8) ("VehicleNewName: %d <- %s", id, name);
			SetCustomEngineName(id, name);
		} else {
			DEBUG(grf, 7) ("VehicleNewName: Too long a name (%d)", ofs);
		}
		name += ofs;
		len -= ofs;
	}
}

/* Action 0x05 */
static void GraphicsNew(byte *buf, int len)
{
	/* <05> <graphics-type> <num-sprites> <other data...>
	 *
	 * B graphics-type What set of graphics the sprites define.
	 * E num-sprites   How many sprites are in this set?
	 * V other data    Graphics type specific data.  Currently unused. */
	/* TODO */

	uint8 type;
	uint16 num;

	check_length(len, 2, "GraphicsNew");
	buf++;
	type = grf_load_byte(&buf);
	num  = grf_load_extended(&buf);

	grfmsg(GMS_NOTICE, "GraphicsNew: Custom graphics (type %x) sprite block of length %d (unimplemented, ignoring).\n",
	       type, num);
}

/* Action 0x06 */
static void CfgApply(byte *buf, int len)
{
	/* <06> <param-num> <param-size> <offset> ... <FF>
	 *
	 * B param-num     Number of parameter to substitute (First = "zero")
	 *                 Ignored if that parameter was not specified in newgrf.cfg
	 * B param-size    How many bytes to replace.  If larger than 4, the
	 *                 bytes of the following parameter are used.  In that
	 *                 case, nothing is applied unless *all* parameters
	 *                 were specified.
	 * B offset        Offset into data from beginning of next sprite
	 *                 to place where parameter is to be stored. */
	/* TODO */
	grfmsg(GMS_NOTICE, "CfgApply: Ignoring (not implemented).\n");
}

/* Action 0x07 */
/* Action 0x09 */
static void SkipIf(byte *buf, int len)
{
	/* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
	 *
	 * B param-num
	 * B param-size
	 * B condition-type
	 * V value
	 * B num-sprites */
	/* TODO: More params. More condition types. */
	uint8 param;
	uint8 paramsize;
	uint8 condtype;
	uint8 numsprites;
	uint32 param_val = 0;
	uint32 cond_val = 0;
	bool result;

	check_length(len, 6, "SkipIf");
	param = buf[1];
	paramsize = buf[2];
	condtype = buf[3];

	if (condtype < 2) {
		/* Always 1 for bit tests, the given value should be ignored. */
		paramsize = 1;
	}

	buf += 4;
	switch (paramsize) {
		case 4: cond_val = grf_load_dword(&buf); break;
		case 2: cond_val = grf_load_word(&buf);  break;
		case 1: cond_val = grf_load_byte(&buf);  break;
		default: break;
	}

	switch (param) {
		case 0x83:    /* current climate, 0=temp, 1=arctic, 2=trop, 3=toyland */
			param_val = _opt.landscape;
			break;
		case 0x84:    /* .grf loading stage, 0=initialization, 1=activation */
			param_val = _cur_stage;
			break;
		case 0x85:    /* TTDPatch flags, only for bit tests */
			param_val = _ttdpatch_flags[cond_val / 0x20];
			cond_val %= 0x20;
			break;
		case 0x86:    /* road traffic side, bit 4 clear=left, set=right */
			param_val = _opt.road_side << 4;
			break;
		case 0x88: {  /* see if specified GRFID is active */
			param_val = (GetFileByGRFID(cond_val) != NULL);
		}	break;

		case 0x8B: { /* TTDPatch version */
			uint major    = 2;
			uint minor    = 0;
			uint revision = 10; // special case: 2.0.1 is 2.0.10
			uint build    = 49;
			param_val = (major << 24) | (minor << 20) | (revision << 16) | (build * 10);
			break;
		}

		case 0x8D:    /* TTD Version, 00=DOS, 01=Windows */
			param_val = !_use_dos_palette;
			break;
		case 0x8E:
			param_val = _traininfo_vehicle_pitch;
			break;
		case 0x9D:    /* TTD Platform, 00=TTDPatch, 01=OpenTTD */
			param_val = 1;
			break;
		/* TODO */
		case 0x8F:    /* Track type cost multipliers */
		default:
			if (param < 0x80) {
				/* Parameter. */
				param_val = _cur_grffile->param[param];
			} else {
				/* In-game variable. */
				grfmsg(GMS_WARN, "Unsupported in-game variable 0x%02X. Ignoring test.", param);
				return;
			}
	}

	DEBUG(grf, 7) ("Test condtype %d, param %x, condval %x", condtype, param_val, cond_val);
	switch (condtype) {
		case 0: result = !!(param_val & (1 << cond_val));
			break;
		case 1: result = !(param_val & (1 << cond_val));
			break;
		/* TODO: For the following, make it to work with paramsize>1. */
		case 2: result = (param_val == cond_val);
			break;
		case 3: result = (param_val != cond_val);
			break;
		case 4: result = (param_val < cond_val);
			break;
		case 5: result = (param_val > cond_val);
			break;
		case 6: result = !!param_val; /* GRFID is active (only for param-num=88) */
			break;
		case 7: result = !param_val; /* GRFID is not active (only for param-num=88) */
			break;
		default:
			grfmsg(GMS_WARN, "Unsupported test %d. Ignoring.", condtype);
			return;
	}

	if (!result) {
		grfmsg(GMS_NOTICE, "Not skipping sprites, test was false.");
		return;
	}

	numsprites = grf_load_byte(&buf);
	grfmsg(GMS_NOTICE, "Skipping %d sprites, test was true.", numsprites);
	_skip_sprites = numsprites;
	if (_skip_sprites == 0) {
		/* Zero means there are no sprites to skip, so
		 * we use -1 to indicate that all further
		 * sprites should be skipped. */
		_skip_sprites = -1;
	}
}

static void GRFInfo(byte *buf, int len)
{
	/* <08> <version> <grf-id> <name> <info>
	 *
	 * B version       newgrf version, currently 06
	 * 4*B grf-id      globally unique ID of this .grf file
	 * S name          name of this .grf set
	 * S info          string describing the set, and e.g. author and copyright */
	/* TODO: Check version. (We should have own versioning done somehow.) */
	uint8 version;
	uint32 grfid;
	const char *name;
	const char *info;

	check_length(len, 8, "GRFInfo");
	version = buf[1];
	/* this is de facto big endian - grf_load_dword() unsuitable */
	grfid = buf[2] << 24 | buf[3] << 16 | buf[4] << 8 | buf[5];
	name = (const char*)(buf + 6);
	info = name + strlen(name) + 1;

	_cur_grffile->grfid = grfid;
	_cur_grffile->flags |= 0x0001; /* set active flag */

	DEBUG(grf, 1) ("[%s] Loaded GRFv%d set %08lx - %s:\n%s",
	               _cur_grffile->filename, version, grfid, name, info);
}

static void SpriteReplace(byte *buf, int len)
{
	/* <0A> <num-sets> <set1> [<set2> ...]
	 * <set>: <num-sprites> <first-sprite>
	 *
	 * B num-sets      How many sets of sprites to replace.
	 * Each set:
	 * B num-sprites   How many sprites are in this set
	 * W first-sprite  First sprite number to replace */
	uint8 num_sets;
	uint i;

	buf++; /* skip action byte */
	num_sets = grf_load_byte(&buf);

	for (i = 0; i < num_sets; i++) {
		uint8 num_sprites = grf_load_byte(&buf);
		uint16 first_sprite = grf_load_word(&buf);
		uint j;

		grfmsg(GMS_NOTICE,
			"SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
			i, num_sprites, first_sprite
		);

		for (j = 0; j < num_sprites; j++) {
			LoadNextSprite(first_sprite + j, _file_index); // XXX
			nfo_line++;
		}
	}
}

static void GRFError(byte *buf, int len)
{
	/* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
	 *
	 * B severity      00: notice, contine loading grf file
	 *                 01: warning, continue loading grf file
	 *                 02: error, but continue loading grf file, and attempt
	 *                     loading grf again when loading or starting next game
	 *                 03: error, abort loading and prevent loading again in
	 *                     the future (only when restarting the patch)
	 * B language-id   see action 4, use 1F for built-in error messages
	 * B message-id    message to show, see below
	 * S message       for custom messages (message-id FF), text of the message
	 *                 not present for built-in messages.
	 * V data          additional data for built-in (or custom) messages
	 * B parnum        see action 6, only used with built-in message 03 */
	/* TODO: For now we just show the message, sometimes incomplete and never translated. */

	static const char * const msgstr[4] = {
		"Requires at least pseudo-TTDPatch version %s.",
		"This file is for %s version of TTD.",
		"Designed to be used with %s.",
		"Invalid parameter %s.",
	};
	uint8 severity;
	uint8 msgid;

	check_length(len, 6, "GRFError");
	severity = buf[1];
	msgid = buf[3];

	// Undocumented TTDPatch feature.
	if ((severity & 0x80) == 0 && _cur_stage == 0)
		return;
	severity &= 0x7F;

	if (msgid == 0xFF) {
		grfmsg(severity, "%s", buf+4);
	} else {
		grfmsg(severity, msgstr[msgid], buf+4);
	}
}

static void GRFComment(byte *buf, int len)
{
	/* <0C> [<ignored...>]
	 *
	 * V ignored       Anything following the 0C is ignored */
}

/* Action 0x0D */
static void ParamSet(byte *buf, int len)
{
	/* <0D> <target> <operation> <source1> <source2> [<data>]
	 *
	 * B target        parameter number where result is stored
	 * B operation     operation to perform, see below
	 * B source1       first source operand
	 * B source2       second source operand
	 * D data          data to use in the calculation, not necessary
	 *                 if both source1 and source2 refer to actual parameters
	 *
	 * Operations
	 * 00      Set parameter equal to source1
	 * 01      Addition, source1 + source2
	 * 02      Subtraction, source1 - source2
	 * 03      Unsigned multiplication, source1 * source2 (both unsigned)
	 * 04      Signed multiplication, source1 * source2 (both signed)
	 * 05      Unsigned bit shift, source1 by source2 (source2 taken to be a
	 *         signed quantity; left shift if positive and right shift if
	 *         negative, source1 is unsigned)
	 * 06      Signed bit shift, source1 by source2
	 *         (source2 like in 05, and source1 as well)
	 */

	byte target;
	byte oper;
	uint32 src1;
	uint32 src2;
	uint32 data = 0;
	uint32 res;

	check_length(len, 5, "ParamSet");
	buf++;
	target = grf_load_byte(&buf);
	oper = grf_load_byte(&buf);
	src1 = grf_load_byte(&buf);
	src2 = grf_load_byte(&buf);

	if (len >= 8) data = grf_load_dword(&buf);

	/* You can add 80 to the operation to make it apply only if the target
	 * is not defined yet.  In this respect, a parameter is taken to be
	 * defined if any of the following applies:
	 * - it has been set to any value in the newgrf(w).cfg parameter list
	 * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
	 *   an earlier action D */
	if (oper & 0x80) {
		if (_cur_grffile->param_end < target)
			oper &= 0x7F;
		else
			return;
	}

	/* The source1 and source2 operands refer to the grf parameter number
	 * like in action 6 and 7.  In addition, they can refer to the special
	 * variables available in action 7, or they can be FF to use the value
	 * of <data>.  If referring to parameters that are undefined, a value
	 * of 0 is used instead.  */
	if (src1 == 0xFF) {
		src1 = data;
	} else {
		src1 = _cur_grffile->param_end >= src1 ? _cur_grffile->param[src1] : 0;
	}

	if (src2 == 0xFF) {
		src2 = data;
	} else {
		src2 = _cur_grffile->param_end >= src2 ? _cur_grffile->param[src2] : 0;
	}

	/* TODO: You can access the parameters of another GRF file by using
	 * source2=FE, source1=the other GRF's parameter number and data=GRF
	 * ID.  This is only valid with operation 00 (set).  If the GRF ID
	 * cannot be found, a value of 0 is used for the parameter value
	 * instead. */

	switch (oper) {
		case 0x00:
			res = src1;
			break;

		case 0x01:
			res = src1 + src2;
			break;

		case 0x02:
			res = src1 - src2;
			break;

		case 0x03:
			res = src1 * src2;
			break;

		case 0x04:
			res = (int32)src1 * (int32)src2;
			break;

		case 0x05:
			if ((int32)src2 < 0)
				res = src1 >> -(int32)src2;
			else
				res = src1 << src2;
			break;

		case 0x06:
			if ((int32)src2 < 0)
				res = (int32)src1 >> -(int32)src2;
			else
				res = (int32)src1 << src2;
			break;

		case 0x07: /* Bitwise AND */
			res = src1 & src2;
			break;

		case 0x08: /* Bitwise OR */
			res = src1 | src2;
			break;

		case 0x09: /* Unsigned division */
			if (src2 == 0) {
				res = src1;
			} else {
				res = src1 / src2;
			}
			break;

		case 0x0A: /* Signed divison */
			if (src2 == 0) {
				res = src1;
			} else {
				res = (int32)src1 / (int32)src2;
			}
			break;

		case 0x0B: /* Unsigned modulo */
			if (src2 == 0) {
				res = src1;
			} else {
				res = src1 % src2;
			}
			break;

		case 0x0C: /* Signed modulo */
			if (src2 == 0) {
				res = src1;
			} else {
				res = (int32)src1 % (int32)src2;
			}
			break;

		default:
			grfmsg(GMS_ERROR, "ParamSet: Unknown operation %d, skipping.", oper);
			return;
	}

	switch (target) {
		case 0x8E: // Y-Offset for train sprites
			_traininfo_vehicle_pitch = res;
			break;

		// TODO implement
		case 0x8F: // Rail track type cost factors
		case 0x93: // Tile refresh offset to left
		case 0x94: // Tile refresh offset to right
		case 0x95: // Tile refresh offset upwards
		case 0x96: // Tile refresh offset downwards
		case 0x97: // Snow line height
		case 0x99: // Global ID offset
			DEBUG(grf, 7) ("ParamSet: Skipping unimplemented target 0x%02X", target);
			break;

		default:
			if (target < 0x80) {
				_cur_grffile->param[target] = res;
				if (target + 1U > _cur_grffile->param_end) _cur_grffile->param_end = target + 1;
			} else {
				DEBUG(grf, 7) ("ParamSet: Skipping unknown target 0x%02X", target);
			}
			break;
	}
}

static void GRFInhibit(byte *buf, int len)
{
	/* <0E> <num> <grfids...>
	 *
	 * B num           Number of GRFIDs that follow
	 * D grfids        GRFIDs of the files to deactivate */

	byte num;
	int i;

	check_length(len, 1, "GRFInhibit");
	buf++, len--;
	num = grf_load_byte(&buf); len--;
	check_length(len, 4 * num, "GRFInhibit");

	for (i = 0; i < num; i++) {
		uint32 grfid = grf_load_dword(&buf);
		GRFFile *file = GetFileByGRFID(grfid);

		/* Unset activation flag */
		if (file != NULL) {
			grfmsg(GMS_NOTICE, "GRFInhibit: Deactivating file ``%s''", file->filename);
			file->flags &= 0xFFFE;
		}
	}
}


static void InitializeGRFSpecial(void)
{
	/* FIXME: We should rather reflect reality in _ttdpatch_flags[]. */

	_ttdpatch_flags[0] = (_patches.always_small_airport ? (1 << 0x0C) : 0)  /* keepsmallairport */
	                   | (1 << 0x0E)  /* largestations */
	                   | (_patches.longbridges ? (1 << 0x0F) : 0)           /* longbridges */
	                   | (1 << 0x12)  /* presignals */
	                   | (1 << 0x13)  /* extpresignals */
	                   | (_patches.never_expire_vehicles ? (1 << 0x16) : 0) /* enginespersist */
	                   | (1 << 0x1B); /* multihead */
	_ttdpatch_flags[1] = (_patches.mammoth_trains ? (1 << 0x08) : 0)        /* mammothtrains */
	                   | (1 << 0x09)  /* trainrefit */
	                   | (1 << 0x14)  /* bridgespeedlimits */
	                   | (1 << 0x16)  /* eternalgame */
	                   | (1 << 0x17)  /* newtrains */
	                   | (1 << 0x18)  /* newrvs */
	                   | (1 << 0x19)  /* newships */
	                   | (1 << 0x1A)  /* newplanes */
	                   | (_patches.signal_side ? (1 << 0x1B) : 0)           /* signalsontrafficside */
	                   | (1 << 0x1C); /* electrifiedrailway */

	_ttdpatch_flags[2] = (_patches.build_on_slopes ? (1 << 0x0D) : 0)       /* buildonslopes */
	                   | (_patches.build_on_slopes ? (1 << 0x15) : 0)       /* buildoncoasts */
	                   | (1 << 0x16)  /* canals */
	                   | (1 << 0x17)  /* newstartyear */
	                   | (1 << 0x1A)  /* newbridges */
	                   | (_patches.wagon_speed_limits ? (1 << 0x1D) : 0);   /* wagonspeedlimits */
	_ttdpatch_flags[3] = (1 << 0x03)  /* pathbasedsignalling */
	                   | (1 << 0x0C)  /* enhancemultiplayer */
	                   | (1 << 0x0E)  /* irregularstations */
	                   | (1 << 0x10); /* autoreplace */
}

/**
 * Unload unused sprite groups from the specified GRF file.
 * Called after loading each GRF file.
 * @param file GRF file
 */
static void ReleaseSpriteGroups(GRFFile *file)
{
	int i;

	// Bail out if no spritegroups were defined.
	if (file->spritegroups == NULL)
		return;

	DEBUG(grf, 6)("ReleaseSpriteGroups: Releasing for `%s'.", file->filename);
	for (i = 0; i < file->spritegroups_count; i++) {
		if (file->spritegroups[i] != NULL)
			UnloadSpriteGroup(&file->spritegroups[i]);
	}
	free(file->spritegroups);
	file->spritegroups = NULL;
	file->spritegroups_count = 0;
}

static void ResetCustomStations(void)
{
	GRFFile *file;
	uint i;
	CargoID c;

	for (file = _first_grffile; file != NULL; file = file->next) {
		for (i = 0; i < lengthof(file->stations); i++) {
			if (file->stations[i].grfid != file->grfid) continue;

			// TODO: Release renderdata, platforms and layouts

			// Release this stations sprite groups.
			for (c = 0; c < NUM_GLOBAL_CID; c++) {
				if (file->stations[i].spritegroup[c] != NULL)
					UnloadSpriteGroup(&file->stations[i].spritegroup[c]);
			}
		}
	}
}

/**
 * Reset all NewGRF loaded data
 * TODO
 */
static void ResetNewGRFData(void)
{
	uint i;

	// Copy/reset original engine info data
	memcpy(&_engine_info, &orig_engine_info, sizeof(orig_engine_info));
	memcpy(&_rail_vehicle_info, &orig_rail_vehicle_info, sizeof(orig_rail_vehicle_info));
	memcpy(&_ship_vehicle_info, &orig_ship_vehicle_info, sizeof(orig_ship_vehicle_info));
	memcpy(&_aircraft_vehicle_info, &orig_aircraft_vehicle_info, sizeof(orig_aircraft_vehicle_info));
	memcpy(&_road_vehicle_info, &orig_road_vehicle_info, sizeof(orig_road_vehicle_info));

	// Copy/reset original bridge info data
	// First, free sprite table data
	for (i = 0; i < MAX_BRIDGES; i++) {
		if (_bridge[i].sprite_table != NULL) {
			uint j;

			for (j = 0; j < 7; j++) free(_bridge[i].sprite_table[j]);
			free(_bridge[i].sprite_table);
		}
	}
	memcpy(&_bridge, &orig_bridge, sizeof(_bridge));

	// Reset refit/cargo class data
	memset(&cargo_allowed, 0, sizeof(cargo_allowed));
	memset(&cargo_disallowed, 0, sizeof(cargo_disallowed));

	// Unload sprite group data
	UnloadWagonOverrides();
	UnloadCustomEngineSprites();
	UnloadCustomEngineNames();
	ResetEngineListOrder();

	// Reset price base data
	ResetPriceBaseMultipliers();

	// Reset station classes
	ResetStationClasses();
	ResetCustomStations();

	// Add engine type to engine data. This is needed for the refit precalculation.
	AddTypeToEngines();
}

static void InitNewGRFFile(const char* filename, int sprite_offset)
{
	GRFFile *newfile;

	newfile = GetFileByFilename(filename);
	if (newfile != NULL) {
		/* We already loaded it once. */
		newfile->sprite_offset = sprite_offset;
		_cur_grffile = newfile;
		return;
	}

	newfile = calloc(1, sizeof(*newfile));

	if (newfile == NULL) error ("Out of memory");

	newfile->filename = strdup(filename);
	newfile->sprite_offset = sprite_offset;

	if (_first_grffile == NULL) {
		_cur_grffile = newfile;
		_first_grffile = newfile;
	} else {
		_cur_grffile->next = newfile;
		_cur_grffile = newfile;
	}
}

/**
 * Precalculate refit masks from cargo classes for all vehicles.
 */
static void CalculateRefitMasks(void)
{
	EngineID engine;

	for (engine = 0; engine < TOTAL_NUM_ENGINES; engine++) {
		uint32 mask = 0;
		uint32 not_mask = 0;
		uint32 xor_mask = _engine_info[engine].refit_mask;
		byte i;

		if (cargo_allowed[engine] != 0) {
			// Build up the list of cargo types from the set cargo classes.
			for (i = 0; i < lengthof(cargo_classes); i++) {
				if (HASBIT(cargo_allowed[engine], i)) mask |= cargo_classes[i];
				if (HASBIT(cargo_disallowed[engine], i)) not_mask |= cargo_classes[i];
			}
		} else {
			// Don't apply default refit mask to wagons or engines with no capacity
			if (xor_mask == 0 && (
						GetEngine(engine)->type != VEH_Train || (
							RailVehInfo(engine)->capacity != 0 &&
							!(RailVehInfo(engine)->flags & RVI_WAGON)
						)
					)) {
				xor_mask = _default_refitmasks[GetEngine(engine)->type - VEH_Train];
			}
		}
		_engine_info[engine].refit_mask = ((mask & ~not_mask) ^ xor_mask) & _landscape_global_cargo_mask[_opt.landscape];
	}
}

/* Here we perform initial decoding of some special sprites (as are they
 * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
 * partial implementation yet). */
/* XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
 * a crafted invalid GRF file. We should tell that to the user somehow, or
 * better make this more robust in the future. */
static void DecodeSpecialSprite(uint num, uint stage)
{
	/* XXX: There is a difference between staged loading in TTDPatch and
	 * here.  In TTDPatch, for some reason actions 1 and 2 are carried out
	 * during stage 0, whilst action 3 is carried out during stage 1 (to
	 * "resolve" cargo IDs... wtf). This is a little problem, because cargo
	 * IDs are valid only within a given set (action 1) block, and may be
	 * overwritten after action 3 associates them. But overwriting happens
	 * in an earlier stage than associating, so...  We just process actions
	 * 1 and 2 in stage 1 now, let's hope that won't get us into problems.
	 * --pasky */
	uint32 action_mask = (stage == 0) ? 0x0001FF40 : 0x0001FFBF;
	static const SpecialSpriteHandler handlers[] = {
		/* 0x00 */ VehicleChangeInfo,
		/* 0x01 */ NewSpriteSet,
		/* 0x02 */ NewSpriteGroup,
		/* 0x03 */ NewVehicle_SpriteGroupMapping,
		/* 0x04 */ VehicleNewName,
		/* 0x05 */ GraphicsNew,
		/* 0x06 */ CfgApply,
		/* 0x07 */ SkipIf,
		/* 0x08 */ GRFInfo,
		/* 0x09 */ SkipIf,
		/* 0x0A */ SpriteReplace,
		/* 0x0B */ GRFError,
		/* 0x0C */ GRFComment,
		/* 0x0D */ ParamSet,
		/* 0x0E */ GRFInhibit,
		/* 0x0F */ NULL, // TODO implement
		/* 0x10 */ NULL  // TODO implement
	};

	byte* buf = malloc(num);
	byte action;

	if (buf == NULL) error("DecodeSpecialSprite: Could not allocate memory");

	FioReadBlock(buf, num);
	action = buf[0];

	if (action >= lengthof(handlers)) {
		DEBUG(grf, 7) ("Skipping unknown action 0x%02X", action);
	} else if (!HASBIT(action_mask, action)) {
		DEBUG(grf, 7) ("Skipping action 0x%02X in stage %d", action, stage);
	} else if (handlers[action] == NULL) {
		DEBUG(grf, 7) ("Skipping unsupported Action 0x%02X", action);
	} else {
		DEBUG(grf, 7) ("Handling action 0x%02X in stage %d", action, stage);
		handlers[action](buf, num);
	}
	free(buf);
}


static void LoadNewGRFFile(const char* filename, uint file_index, uint stage)
{
	uint16 num;

	/* A .grf file is activated only if it was active when the game was
	 * started.  If a game is loaded, only its active .grfs will be
	 * reactivated, unless "loadallgraphics on" is used.  A .grf file is
	 * considered active if its action 8 has been processed, i.e. its
	 * action 8 hasn't been skipped using an action 7.
	 *
	 * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
	 * carried out.  All others are ignored, because they only need to be
	 * processed once at initialization.  */
	if (stage != 0) {
		_cur_grffile = GetFileByFilename(filename);
		if (_cur_grffile == NULL) error("File ``%s'' lost in cache.\n", filename);
		if (!(_cur_grffile->flags & 0x0001)) return;
	}

	FioOpenFile(file_index, filename);
	_file_index = file_index; // XXX

	DEBUG(grf, 7) ("Reading NewGRF-file '%s'", filename);

	/* Skip the first sprite; we don't care about how many sprites this
	 * does contain; newest TTDPatches and George's longvehicles don't
	 * neither, apparently. */
	if (FioReadWord() == 4 && FioReadByte() == 0xFF) {
		FioReadDword();
	} else {
		error("Custom .grf has invalid format.");
	}

	_skip_sprites = 0; // XXX
	nfo_line = 0;

	while ((num = FioReadWord()) != 0) {
		byte type = FioReadByte();
		nfo_line++;

		if (type == 0xFF) {
			if (_skip_sprites == 0) {
				DecodeSpecialSprite(num, stage);
				continue;
			} else {
				FioSkipBytes(num);
			}
		} else {
			if (_skip_sprites == 0) DEBUG(grf, 7) ("Skipping unexpected sprite");

			FioSkipBytes(7);
			num -= 8;

			if (type & 2) {
				FioSkipBytes(num);
			} else {
				while (num > 0) {
					int8 i = FioReadByte();
					if (i >= 0) {
						num -= i;
						FioSkipBytes(i);
					} else {
						i = -(i >> 3);
						num -= i;
						FioReadByte();
					}
				}
			}
		}

		if (_skip_sprites > 0) _skip_sprites--;
	}

	// Release our sprite group references.
	// Any groups that are referenced elsewhere will be cleaned up later.
	// This removes groups that aren't used. (Perhaps skipped?)
	ReleaseSpriteGroups(_cur_grffile);
}


void LoadNewGRF(uint load_index, uint file_index)
{
	uint stage;

	InitializeGRFSpecial();

	ResetNewGRFData();

	/* Load newgrf sprites
	 * in each loading stage, (try to) open each file specified in the config
	 * and load information from it. */
	_custom_sprites_base = load_index;
	for (stage = 0; stage < 2; stage++) {
		uint slot = file_index;
		uint j;

		_cur_stage = stage;
		_cur_spriteid = load_index;
		for (j = 0; j != lengthof(_newgrf_files) && _newgrf_files[j] != NULL; j++) {
			if (!FiosCheckFileExists(_newgrf_files[j])) {
				// TODO: usrerror()
				error("NewGRF file missing: %s", _newgrf_files[j]);
			}
			if (stage == 0) InitNewGRFFile(_newgrf_files[j], _cur_spriteid);
			LoadNewGRFFile(_newgrf_files[j], slot++, stage);
			DEBUG(spritecache, 2) ("Currently %i sprites are loaded", load_index);
		}
	}

	// Pre-calculate all refit masks after loading GRF files
	CalculateRefitMasks();
}