Files @ r662:d42c2c6d320b
Branch filter:

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

truelight
(svn r1096) -Fix: [Network] PlayAs is now registered correctly
-Codewise: [Network] Cleaned some code, removed some comment, changed
some wrong comment
   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
#include "stdafx.h"
#include "ttd.h"
#include "table/strings.h"
#include "station.h"
#include "gfx.h"
#include "window.h"
#include "viewport.h"
#include "command.h"
#include "town.h"
#include "vehicle.h"
#include "news.h"
#include "saveload.h"
#include "economy.h"
#include "player.h"
#include "airport.h"
#include "sprite.h"
#include "table/directions.h"

// FIXME -- need to be embedded into Airport variable. Is dynamically
// deducteable from graphics-tile array, so will not be needed
const byte _airport_size_x[5] = {4, 6, 1, 6, 7 };
const byte _airport_size_y[5] = {3, 6, 1, 6, 7 };

void ShowAircraftDepotWindow(uint tile);
extern void UpdateAirplanesOnNewStation(Station *st);

static void MarkStationDirty(Station *st)
{
	if (st->sign.width_1 != 0) {
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, 1);

		MarkAllViewportsDirty(
			st->sign.left - 6,
			st->sign.top,
			st->sign.left + (st->sign.width_1 << 2) + 12,
			st->sign.top + 48);
	}
}

#define CHECK_STATIONS_ERR ((Station*)-1)

static Station *GetStationAround(uint tile, int w, int h, int closest_station)
{
	// check around to see if there's any stations there
	BEGIN_TILE_LOOP(tile_cur, w + 2, h + 2, tile - TILE_XY(1,1))
		if (IS_TILETYPE(tile_cur, MP_STATION)) {
			int t;
			t = _map2[tile_cur];
			{
				Station *st = DEREF_STATION(t);
				// you cannot take control of an oilrig!!
				if (st->airport_type == AT_OILRIG && st->facilities == (FACIL_AIRPORT|FACIL_DOCK))
					continue;
			}

			if (closest_station == -1) {
				closest_station = t;
			} else if (closest_station != t) {
				_error_message = STR_3006_ADJOINS_MORE_THAN_ONE_EXISTING;
				return CHECK_STATIONS_ERR;
			}
		}
	END_TILE_LOOP(tile_cur, w + 2, h + 2, tile - TILE_XY(1,1))
	return (closest_station == -1) ? NULL : DEREF_STATION(closest_station);
}

TileIndex GetStationTileForVehicle(Vehicle *v, Station *st)
{
	switch (v->type) {
		case VEH_Train: 		return st->train_tile;
		case VEH_Aircraft:	return st->airport_tile;
		case VEH_Ship:			return st->dock_tile;
		case VEH_Road:			return (v->cargo_type == CT_PASSENGERS) ? st->bus_tile : st->lorry_tile;
		default:
			assert(false);
			return 0;
	}
}

static bool CheckStationSpreadOut(Station *st, uint tile, int w, int h)
{
	byte station_index = st->index;
	uint i;
	uint x1 = GET_TILE_X(tile);
	uint y1 = GET_TILE_Y(tile);
	uint x2 = x1 + w - 1;
	uint y2 = y1 + h - 1;
	uint t;

	for(i=0; i!=TILES_X*TILES_Y; i++) {
		if (IS_TILETYPE(i, MP_STATION) && _map2[i] == station_index) {
			t = GET_TILE_X(i);
			if (t < x1) x1 = t;
			if (t > x2) x2 = t;

			t = GET_TILE_Y(i);
			if (t < y1) y1 = t;
			if (t > y2) y2 = t;
		}
	}

	if (y2-y1 >= _patches.station_spread || x2-x1 >= _patches.station_spread) {
		_error_message = STR_306C_STATION_TOO_SPREAD_OUT;
		return false;
	}

	return true;
}

static Station *AllocateStation()
{
	Station *st, *a_free = NULL;
	int count;
	int num_free = 0;
	int i;

	for(st = _stations, count = lengthof(_stations); count != 0; count--, st++) {
		if (st->xy == 0) {
			num_free++;
			if (a_free==NULL)
				a_free = st;
		}
	}

	if (a_free == NULL ||
			(num_free < 30 && IS_HUMAN_PLAYER(_current_player))) {
		_error_message = STR_3008_TOO_MANY_STATIONS_LOADING;
		return NULL;
	}

	i = a_free->index;
	memset(a_free, 0, sizeof(Station));
	a_free->index = i;
	return a_free;
}


static int CountMapSquareAround(uint tile, byte type, byte min, byte max) {
	static const TileIndexDiff _count_square_table[7*7+1] = {
		TILE_XY(-3,-3), 1, 1, 1, 1, 1, 1,
		TILE_XY(-6,1),  1, 1, 1, 1, 1, 1,
		TILE_XY(-6,1),  1, 1, 1, 1, 1, 1,
		TILE_XY(-6,1),  1, 1, 1, 1, 1, 1,
		TILE_XY(-6,1),  1, 1, 1, 1, 1, 1,
		TILE_XY(-6,1),  1, 1, 1, 1, 1, 1,
		TILE_XY(-6,1),  1, 1, 1, 1, 1, 1,
		0,
	};
	int j;
	const TileIndexDiff *p = _count_square_table;
	int num = 0;

	while ( (j=*p++) != 0 ) {
		tile = TILE_MASK(tile + j);

		if (IS_TILETYPE(tile, type) && _map5[tile] >= min && _map5[tile] <= max)
			num++;
	}

	return num;
}

#define M(x) ((x) - STR_SV_STNAME)

static bool GenerateStationName(Station *st, uint tile, int flag)
{
	static const uint32 _gen_station_name_bits[] = {
		0,																/* 0 */
		1 << M(STR_SV_STNAME_AIRPORT),		/* 1 */
		1 << M(STR_SV_STNAME_OILFIELD),		/* 2 */
		1 << M(STR_SV_STNAME_DOCKS),			/* 3 */
		0x1FF << M(STR_SV_STNAME_BUOY_1),	/* 4 */
		1 << M(STR_SV_STNAME_HELIPORT),		/* 5 */
	};

	Town *t = st->town;
	uint32 free_names = (uint32)-1;
	int found;
	uint z,z2;
	unsigned long tmp;

	{
		Station *s;

		FOR_ALL_STATIONS(s) {
			if (s != st && s->xy != 0 && s->town==t) {
				uint str = M(s->string_id);
				if (str <= 0x20) {
					if (str == M(STR_SV_STNAME_FOREST))
						str = M(STR_SV_STNAME_WOODS);
					CLRBIT(free_names, str);
				}
			}
		}
	}

	/* check default names */
	tmp = free_names & _gen_station_name_bits[flag];
	if (tmp != 0) {
		found = FindFirstBit(tmp);
		goto done;
	}

	/* check mine? */
	if (HASBIT(free_names, M(STR_SV_STNAME_MINES))) {
		if (CountMapSquareAround(tile, MP_INDUSTRY, 0, 6) >= 2 ||
		    CountMapSquareAround(tile, MP_INDUSTRY, 0x64, 0x73) >= 2 ||
				CountMapSquareAround(tile, MP_INDUSTRY, 0x2F, 0x33) >= 2 ||
				CountMapSquareAround(tile, MP_INDUSTRY, 0x48, 0x58) >= 2 ||
				CountMapSquareAround(tile, MP_INDUSTRY, 0x5B, 0x63) >= 2) {
					found = M(STR_SV_STNAME_MINES);
					goto done;
				}
	}

	/* check close enough to town to get central as name? */
	if (GetTileDist1D(tile,t->xy) < 8) {
		found = M(STR_SV_STNAME);
		if (HASBIT(free_names, M(STR_SV_STNAME))) goto done;

		found = M(STR_SV_STNAME_CENTRAL);
		if (HASBIT(free_names, M(STR_SV_STNAME_CENTRAL))) goto done;
	}

	/* Check lakeside */
	if (HASBIT(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
			!CheckDistanceFromEdge(tile, 20) &&
			CountMapSquareAround(tile, MP_WATER, 0, 0) >= 5) {
				found = M(STR_SV_STNAME_LAKESIDE);
				goto done;
			}

	/* Check woods */
	if (HASBIT(free_names, M(STR_SV_STNAME_WOODS)) && (
			CountMapSquareAround(tile, MP_TREES, 0, 255) >= 8 ||
			CountMapSquareAround(tile, MP_INDUSTRY, 0x10, 0x11) >= 2 )) {
				found = (_opt.landscape==LT_DESERT) ? M(STR_SV_STNAME_FOREST) : M(STR_SV_STNAME_WOODS);
				goto done;
	}

	/* check elevation compared to town */
	z = GetTileZ(tile);
	z2 = GetTileZ(t->xy);
	if (z < z2) {
		found = M(STR_SV_STNAME_VALLEY);
		if (HASBIT(free_names, M(STR_SV_STNAME_VALLEY))) goto done;
	} else if (z > z2) {
		found = M(STR_SV_STNAME_HEIGHTS);
		if (HASBIT(free_names, M(STR_SV_STNAME_HEIGHTS))) goto done;
	}

	/* check direction compared to town */
	{
		static const int8 _direction_and_table[] = {
			~( (1<<M(STR_SV_STNAME_WEST)) | (1<<M(STR_SV_STNAME_EAST)) | (1<<M(STR_SV_STNAME_NORTH)) ),
			~( (1<<M(STR_SV_STNAME_SOUTH)) | (1<<M(STR_SV_STNAME_WEST)) | (1<<M(STR_SV_STNAME_NORTH)) ),
			~( (1<<M(STR_SV_STNAME_SOUTH)) | (1<<M(STR_SV_STNAME_EAST)) | (1<<M(STR_SV_STNAME_NORTH)) ),
			~( (1<<M(STR_SV_STNAME_SOUTH)) | (1<<M(STR_SV_STNAME_WEST)) | (1<<M(STR_SV_STNAME_EAST)) ),
		};

		free_names &= _direction_and_table[
			(GET_TILE_X(tile) < GET_TILE_X(t->xy)) +
			(GET_TILE_Y(tile) < GET_TILE_Y(t->xy))*2];
	}

	tmp = free_names & ((1<<1)|(1<<2)|(1<<3)|(1<<4)|(1<<6)|(1<<7)|(1<<12)|(1<<26)|(1<<27)|(1<<28)|(1<<29)|(1<<30));
	if (tmp == 0) {
		_error_message = STR_3007_TOO_MANY_STATIONS_LOADING;
		return false;
	}
	found = FindFirstBit(tmp);

done:
	st->string_id = found + STR_SV_STNAME;
	return true;
}
#undef M

static Station *GetClosestStationFromTile(uint tile, uint threshold, byte owner)
{
	Station *st, *best_station = NULL;
	uint cur_dist;

	FOR_ALL_STATIONS(st) {
		cur_dist = GetTileDist(tile, st->xy);
		if (cur_dist < threshold && (owner == 0xFF || st->owner == owner) && (st->xy != 0)) {
			threshold = cur_dist;
			best_station = st;
		}
	}

	return best_station;
}

static void StationInitialize(Station *st, TileIndex tile)
{
	int i;
	GoodsEntry *ge;

	st->xy = tile;
	st->bus_tile = st->lorry_tile = st->airport_tile = st->dock_tile = st->train_tile = 0;
	st->had_vehicle_of_type = 0;
	st->time_since_load = 255;
	st->time_since_unload = 255;
	st->delete_ctr = 0;
	st->facilities = 0;

	st->last_vehicle = INVALID_VEHICLE;

	for(i=0,ge=st->goods; i!=NUM_CARGO; i++, ge++) {
		ge->waiting_acceptance = 0;
		ge->days_since_pickup = 0;
		ge->enroute_from = 0xFF;
		ge->rating = 175;
		ge->last_speed = 0;
		ge->last_age = 0xFF;
	}

	_global_station_sort_dirty = true; // build a new station
}

// Update the virtual coords needed to draw the station sign.
// st = Station to update for.
static void UpdateStationVirtCoord(Station *st)
{
	Point pt = RemapCoords2(GET_TILE_X(st->xy) * 16, GET_TILE_Y(st->xy) * 16);
	pt.y -= 32;
	if (st->facilities&FACIL_AIRPORT && st->airport_type==AT_OILRIG) pt.y -= 16;

	SetDParam(0, st->index);
	SetDParam(1, st->facilities);
	UpdateViewportSignPos(&st->sign, pt.x, pt.y, STR_305C_0);
}

// Update the virtual coords needed to draw the station sign for all stations.
void UpdateAllStationVirtCoord()
{
	Station *st;
	FOR_ALL_STATIONS(st) {
		if (st->xy != 0)
			UpdateStationVirtCoord(st);
	}
}

// Update the station virt coords while making the modified parts dirty.
static void UpdateStationVirtCoordDirty(Station *st)
{
	MarkStationDirty(st);
	UpdateStationVirtCoord(st);
	MarkStationDirty(st);
}

// Get a mask of the cargo types that the station accepts.
static uint GetAcceptanceMask(Station *st)
{
	uint mask = 0;
	uint cur_mask = 1;
	int i;
	for(i=0; i!=NUM_CARGO; i++,cur_mask*=2) {
		if (st->goods[i].waiting_acceptance & 0x8000)
			mask |= cur_mask;
	}
	return mask;
}

// Items contains the two cargo names that are to be accepted or rejected.
// msg is the string id of the message to display.
static void ShowRejectOrAcceptNews(Station *st, uint32 items, StringID msg)
{
	if (items) {
		SetDParam(2, items >> 16);
		SetDParam(1, items & 0xFFFF);
		SetDParam(0, st->index);
		AddNewsItem(msg + ((items >> 16)?1:0), NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_TILE, NT_ACCEPTANCE, 0), st->xy, 0);
	}
}

// Get a list of the cargo types being produced around the tile.
void GetProductionAroundTiles(uint *produced, uint tile, int w, int h, int rad)
{
	int x,y;
	int x1,y1,x2,y2;
	int xc,yc;
	byte cargos[2];

	memset(produced, 0, NUM_CARGO * sizeof(uint));

	x = GET_TILE_X(tile);
	y = GET_TILE_Y(tile);

	// expand the region by 4 tiles on each side
	// while making sure that we remain inside the board.
	x2 = min(x + w + rad, TILE_X_MAX+1);
	x1 = max(x-rad, 0);

	y2 = min(y + h + rad, TILE_Y_MAX+1);
	y1 = max(y-rad, 0);

	assert(x1 < x2);
	assert(y1 < y2);
	assert(w > 0);
	assert(h > 0);

	yc = y1;
	do {
		xc = x1;
		do {
			if (!(IS_INSIDE_1D(xc, x, w) && IS_INSIDE_1D(yc, y, h))) {
				GetProducedCargoProc *gpc;
				uint tile = TILE_XY(xc, yc);
				gpc = _tile_type_procs[GET_TILETYPE(tile)]->get_produced_cargo_proc;
				if (gpc != NULL) {
					cargos[0] = cargos[1] = 0xFF;
					gpc(tile, cargos);
					if (cargos[0] != 0xFF) {
						produced[cargos[0]]++;
						if (cargos[1] != 0xFF) {
							produced[cargos[1]]++;
						}
					}
				}
			}
		} while (++xc != x2);
	} while (++yc != y2);
}

// Get a list of the cargo types that are accepted around the tile.
void GetAcceptanceAroundTiles(uint *accepts, uint tile, int w, int h, int rad)
{
	int x,y;
	int x1,y1,x2,y2;
	int xc,yc;

	memset(accepts, 0, sizeof(AcceptedCargo));

	x = GET_TILE_X(tile);
	y = GET_TILE_Y(tile);

	// expand the region by 4 tiles on each side
	// while making sure that we remain inside the board.
	x2 = min(x + w + rad, TILE_X_MAX+1);
	y2 = min(y + h + rad, TILE_Y_MAX+1);
	x1 = max(x-rad, 0);
	y1 = max(y-rad, 0);

	assert(x1 < x2);
	assert(y1 < y2);
	assert(w > 0);
	assert(h > 0);

	yc = y1;
	do {
		xc = x1;
		do {
			uint tile = TILE_XY(xc, yc);
			if (!IS_TILETYPE(tile, MP_STATION)) {
				AcceptedCargo ac;
				int i;

				GetAcceptedCargo(tile, ac);
				for (i = 0; i < NUM_CARGO; ++i)
					accepts[i] += ac[i];
			}
		} while (++xc != x2);
	} while (++yc != y2);
}

// Update the acceptance for a station.
// show_msg controls whether to display a message that acceptance was changed.
static void UpdateStationAcceptance(Station *st, bool show_msg)
{
	uint old_acc, new_acc;
	TileIndex span[1+1+2+2+1];
	int i;
	int min_x, min_y, max_x, max_y;
	int rad = 4;	//Put this to surpress a compiler warning
	uint accepts[NUM_CARGO];

	// Don't update acceptance for a buoy
	if (st->had_vehicle_of_type & HVOT_BUOY)
		return;

	/* old accepted goods types */
	old_acc = GetAcceptanceMask(st);

	// Put all the tiles that span an area in the table.
	span[3] = span[5] = 0;
	span[0] = st->bus_tile;
	span[1] = st->lorry_tile;
	span[2] = st->train_tile;
	if (st->train_tile != 0) {
		span[3] = st->train_tile + TILE_XY(st->trainst_w-1, st->trainst_h-1);
	}
	span[4] = st->airport_tile;
	if (st->airport_tile != 0) {
		span[5] = st->airport_tile + TILE_XY(_airport_size_x[st->airport_type]-1, _airport_size_y[st->airport_type]-1);
	}
	span[6] = st->dock_tile;

	// Construct a rectangle from those points
	min_x = min_y = 0x7FFFFFFF;
	max_x = max_y = 0;

	for(i=0; i!=7; i++) {
		uint tile = span[i];
		if (tile) {
			min_x = min(min_x,GET_TILE_X(tile));
			max_x = max(max_x,GET_TILE_X(tile));
			min_y = min(min_y,GET_TILE_Y(tile));
			max_y = max(max_y,GET_TILE_Y(tile));
		}
	}
	if (_patches.modified_catchment) {
		FIND_CATCHMENT_RADIUS(st,rad)
	} else {
		rad = 4;
	}

	// And retrieve the acceptance.
	if (max_x != 0) {
		GetAcceptanceAroundTiles(accepts, TILE_XY(min_x, min_y), max_x - min_x + 1, max_y-min_y+1,rad);
	} else {
		memset(accepts, 0, sizeof(accepts));
	}

	// Adjust in case our station only accepts fewer kinds of goods
	for(i=0; i!=NUM_CARGO; i++) {
		uint amt = min(accepts[i], 15);

		// Make sure the station can accept the goods type.
		if ((i != CT_PASSENGERS && !(st->facilities & (byte)~FACIL_BUS_STOP)) ||
				(i == CT_PASSENGERS && !(st->facilities & (byte)~FACIL_TRUCK_STOP)))
			amt = 0;

		st->goods[i].waiting_acceptance = (st->goods[i].waiting_acceptance & ~0xF000) + (amt << 12);
	}

	// Only show a message in case the acceptance was actually changed.
	new_acc = GetAcceptanceMask(st);
	if (old_acc == new_acc)
		return;

	// show a message to report that the acceptance was changed?
	if (show_msg && st->owner == _local_player && st->facilities) {
		uint32 accept=0, reject=0; /* these contain two string ids each */
		const StringID *str = _cargoc.names_s;

		do {
			if (new_acc & 1) {
				if (!(old_acc & 1)) accept = (accept << 16) | *str;
			} else {
				if (old_acc & 1) reject = (reject << 16) | *str;
			}
		} while (str++,(new_acc>>=1) != (old_acc>>=1));

		ShowRejectOrAcceptNews(st, accept, STR_3040_NOW_ACCEPTS);
		ShowRejectOrAcceptNews(st, reject, STR_303E_NO_LONGER_ACCEPTS);
	}

	// redraw the station view since acceptance changed
	InvalidateWindowWidget(WC_STATION_VIEW, st->index, 4);
}

// This is called right after a station was deleted.
// It checks if the whole station is free of substations, and if so, the station will be
// deleted after a little while.
static void DeleteStationIfEmpty(Station *st) {
	if (st->facilities == 0) {
		st->delete_ctr = 0;
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}
}

// Tries to clear the given area. Returns the cost in case of success.
// Or an error code if it failed.
int32 CheckFlatLandBelow(uint tile, uint w, uint h, uint flags, uint invalid_dirs, int *station)
{
	int32 cost = 0, ret;

	uint tileh;
	int z, allowed_z = -1, flat_z;

	BEGIN_TILE_LOOP(tile_cur, w, h, tile)
		if (!EnsureNoVehicle(tile_cur))
			return CMD_ERROR;

		tileh = GetTileSlope(tile_cur, &z);

		// steep slopes are completely prohibited
		if (tileh & 0x10 || (((!_patches.ainew_active && _is_ai_player) || !_patches.build_on_slopes) && tileh != 0)) {
			_error_message = STR_0007_FLAT_LAND_REQUIRED;
			return CMD_ERROR;
		}

		flat_z = z;
		if (tileh) {
			// need to check so the entrance to the station is not pointing at a slope.
			if ((invalid_dirs&1 && !(tileh & 0xC) && (uint)w_cur == w) ||
					(invalid_dirs&2 && !(tileh & 6) &&	h_cur == 1) ||
					(invalid_dirs&4 && !(tileh & 3) && w_cur == 1) ||
					(invalid_dirs&8 && !(tileh & 9) && (uint)h_cur == h)) {
				_error_message = STR_0007_FLAT_LAND_REQUIRED;
				return CMD_ERROR;
			}
			cost += _price.terraform;
			flat_z += 8;
		}

		// get corresponding flat level and make sure that all parts of the station have the same level.
		if (allowed_z == -1) {
			// first tile
			allowed_z = flat_z;
		} else if (allowed_z != flat_z) {
			_error_message = STR_0007_FLAT_LAND_REQUIRED;
			return CMD_ERROR;
		}

		// if station is set, then we have special handling to allow building on top of already existing stations.
		// so station points to -1 if we can build on any station. or it points to a station if we're only allowed to build
		// on exactly that station.
		if (station && IS_TILETYPE(tile_cur, MP_STATION)) {
			if (_map5[tile] >= 8) {
				_error_message = STR_0007_FLAT_LAND_REQUIRED;
				return CMD_ERROR;
			} else {
				int st = _map2[tile_cur];
				if (*station == -1)
					*station = st;
				else if (*station != st) {
					_error_message = STR_3006_ADJOINS_MORE_THAN_ONE_EXISTING;
					return CMD_ERROR;
				}
			}
		} else {
			ret = DoCommandByTile(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
			if (ret == CMD_ERROR) return CMD_ERROR;
			cost += ret;
		}
	END_TILE_LOOP(tile_cur, w, h, tile)

	return cost;
}

static bool CanExpandRailroadStation(Station *st, uint *fin, int direction)
{
	uint curw = st->trainst_w, curh = st->trainst_h;
	uint tile = fin[0];
	uint w = fin[1];
	uint h = fin[2];

	if (_patches.nonuniform_stations) {
		// determine new size of train station region..
		int x = min(GET_TILE_X(st->train_tile), GET_TILE_X(tile));
		int y = min(GET_TILE_Y(st->train_tile), GET_TILE_Y(tile));
		curw = max(GET_TILE_X(st->train_tile) + curw, GET_TILE_X(tile) + w) - x;
		curh = max(GET_TILE_Y(st->train_tile) + curh, GET_TILE_Y(tile) + h) - y;
		tile = TILE_XY(x,y);
	} else {
		// check so the direction is the same
		if ((_map5[st->train_tile] & 1) != direction) return false;

		// check if the new station adjoins the old station in either direction
		if (curw == w && st->train_tile == tile + TILE_XY(0, h)) {
			// above
			curh += h;
		} else if (curw == w && st->train_tile == tile - TILE_XY(0, curh)) {
			// below
			tile -= TILE_XY(0, curh);
			curh += h;
		} else if (curh == h && st->train_tile == tile + TILE_XY(w, 0)) {
			// to the left
			curw += w;
		} else if (curh == h && st->train_tile == tile - TILE_XY(curw, 0)) {
			// to the right
			tile -= TILE_XY(curw, 0);
			curw += w;
		} else
			return false;
	}
	// make sure the final size is not too big.
	if (curw > _patches.station_spread || curh > _patches.station_spread) return false;

	// now tile contains the new value for st->train_tile
	// curw, curh contain the new value for width and height
	fin[0] = tile;
	fin[1] = curw;
	fin[2] = curh;
	return true;
}

static inline byte *CreateSingle(byte *layout, int n)
{
	int i = n;
	do *layout++ = 0; while (--i);
	layout[((n-1) >> 1)-n] = 2;
	return layout;
}

static inline byte *CreateMulti(byte *layout, int n, byte b)
{
	int i = n;
	do *layout++ = b; while (--i);
	if (n > 4) {
		layout[0-n] = 0;
		layout[n-1-n] = 0;
	}
	return layout;
}

// stolen from TTDPatch
static void GetStationLayout(byte *layout, int numtracks, int plat_len, struct StationSpec *spec)
{
	if (spec != NULL && spec->lengths >= plat_len && spec->platforms[plat_len - 1] >= numtracks
	    && spec->layouts[plat_len - 1][numtracks - 1]) {
		/* Custom layout defined, follow it. */
		memcpy(layout, spec->layouts[plat_len - 1][numtracks - 1],
		       plat_len * numtracks);
		return;
	}

	if (plat_len == 1) {
		CreateSingle(layout, numtracks);
	} else {
		if (numtracks & 1)
			layout = CreateSingle(layout, plat_len);
		numtracks>>=1;

		while (--numtracks >= 0) {
			layout = CreateMulti(layout, plat_len, 4);
			layout = CreateMulti(layout, plat_len, 6);
		}
	}
}

/* build railroad station
 * p1 & 1 - orientation
 * (p1 >> 8) & 0xFF - numtracks
 * (p1 >> 16) & 0xFF - platform length
 * p2 & 0xF  - railtype
 * p2 & 0x10 - set for custom station
 * p2 >> 8   - custom station id
 */

int32 CmdBuildRailroadStation(int x_org, int y_org, uint32 flags, uint32 p1, uint32 p2)
{
	/* unpack params */
	int w_org,h_org;
	uint tile_org;
	int32 cost, ret;
	Station *st;
	int est;
	int plat_len, numtracks;
	int direction;
	uint finalvalues[3];

	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);

	tile_org = TILE_FROM_XY(x_org,y_org);

	/* Does the authority allow this? */
	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile_org))
		return CMD_ERROR;

	{
		/* unpack parameters */
		direction = p1 & 1;
		plat_len = (p1 >> 16) & 0xFF;
		numtracks = (p1 >> 8) & 0xFF;
		/* w = length, h = num_tracks */
		if (direction) {
			h_org = plat_len;
			w_org = numtracks;
		} else {
			w_org = plat_len;
			h_org = numtracks;
		}
	}

	// these values are those that will be stored in train_tile and station_platforms
	finalvalues[0] = tile_org;
	finalvalues[1] = w_org;
	finalvalues[2] = h_org;

	// Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station)
	est = -1;
	// If DC_EXEC is in flag, do not want to pass it to CheckFlatLandBelow, because of a nice bug
	//  for detail info, see: https://sourceforge.net/tracker/index.php?func=detail&aid=1029064&group_id=103924&atid=636365
	if ((ret=CheckFlatLandBelow(tile_org, w_org, h_org, flags&~DC_EXEC, 5 << direction, _patches.nonuniform_stations ? &est : NULL)) == CMD_ERROR) return CMD_ERROR;
	cost = ret + (numtracks * _price.train_station_track + _price.train_station_length) * plat_len;

	// Make sure there are no similar stations around us.
	st = GetStationAround(tile_org, w_org, h_org, est);
	if (st == CHECK_STATIONS_ERR) return CMD_ERROR;

	// See if there is a deleted station close to us.
	if (st == NULL) {
		st = GetClosestStationFromTile(tile_org, 8, _current_player);
		if (st != NULL && st->facilities) st = NULL;
	}

	if (st != NULL) {
		// Reuse an existing station.
		if (st->owner != OWNER_NONE && st->owner != _current_player)
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);

		if (st->train_tile != 0) {
			// check if we want to expanding an already existing station?
			if ((!_patches.ainew_active && _is_ai_player) || !_patches.join_stations || !CanExpandRailroadStation(st, finalvalues, direction))
				return_cmd_error(STR_3005_TOO_CLOSE_TO_ANOTHER_RAILROAD);
		}

		if (!CheckStationSpreadOut(st, tile_org, w_org, h_org))
			return CMD_ERROR;

	}	else {
		// Create a new station
		st = AllocateStation();
		if (st == NULL)
			return CMD_ERROR;

		st->town = ClosestTownFromTile(tile_org, (uint)-1);
		if (_current_player < MAX_PLAYERS && flags&DC_EXEC)
			SETBIT(st->town->have_ratings, _current_player);

		if (!GenerateStationName(st, tile_org, 0))
			return CMD_ERROR;

		if (flags & DC_EXEC)
			StationInitialize(st, tile_org);
	}

	if (flags & DC_EXEC) {
		int tile_delta;
		byte *layout_ptr;
		uint station_index = st->index;
		struct StationSpec *statspec;

		// Now really clear the land below the station
		// It should never return CMD_ERROR.. but you never know ;)
		//  (a bit strange function name for it, but it really does clear the land, when DC_EXEC is in flags)
		if (CheckFlatLandBelow(tile_org, w_org, h_org, flags, 5 << direction, _patches.nonuniform_stations ? &est : NULL) == CMD_ERROR) return CMD_ERROR;

		st->train_tile = finalvalues[0];
		if (!st->facilities) st->xy = finalvalues[0];
		st->facilities |= FACIL_TRAIN;
		st->owner = _current_player;

		st->trainst_w = finalvalues[1];
		st->trainst_h = finalvalues[2];

		st->build_date = _date;

		tile_delta = direction ? TILE_XY(0,1) : TILE_XY(1,0);

		statspec = (p2 & 0x10) != 0 ? GetCustomStation(STAT_CLASS_DFLT, p2 >> 8) : NULL;
		layout_ptr = alloca(numtracks * plat_len);
		GetStationLayout(layout_ptr, numtracks, plat_len, statspec);

		do {
			int tile = tile_org;
			int w = plat_len;
			do {

				ModifyTile(tile,
					MP_SETTYPE(MP_STATION) | MP_MAPOWNER_CURRENT |
					MP_MAP2 | MP_MAP5 | MP_MAP3LO | MP_MAP3HI,
					station_index, /* map2 parameter */
					p2 & 0xFF,     /* map3lo parameter */
					p2 >> 8,       /* map3hi parameter */
					(*layout_ptr++) + direction   /* map5 parameter */
				);

				tile += tile_delta;
			} while (--w);
			tile_org += tile_delta ^ TILE_XY(1,1);
		} while (--numtracks);

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}

	return cost;
}

static bool TileBelongsToRailStation(Station *st, uint tile)
{
	return IS_TILETYPE(tile, MP_STATION) && _map2[tile] == st->index && _map5[tile] < 8;
}

static void MakeRailwayStationAreaSmaller(Station *st)
{
	uint w = st->trainst_w;
	uint h = st->trainst_h;
	uint tile = st->train_tile;
	uint i;

restart:

	// too small?
	if (w != 0 && h != 0) {
		// check the left side, x = constant, y changes
		for(i=0; !TileBelongsToRailStation(st, tile + TILE_XY(0,i)) ;)
			// the left side is unused?
			if (++i==h) { tile += TILE_XY(1, 0); w--; goto restart; }

		// check the right side, x = constant, y changes
		for(i=0; !TileBelongsToRailStation(st, tile + TILE_XY(w-1,i)) ;)
			// the right side is unused?
			if (++i==h) { w--; goto restart; }

		// check the upper side, y = constant, x changes
		for(i=0; !TileBelongsToRailStation(st, tile + TILE_XY(i,0)) ;)
			// the left side is unused?
			if (++i==w) { tile += TILE_XY(0, 1); h--; goto restart; }

		// check the lower side, y = constant, x changes
		for(i=0; !TileBelongsToRailStation(st, tile + TILE_XY(i,h-1)) ;)
			// the left side is unused?
			if (++i==w) { h--; goto restart; }
	} else {
		tile = 0;
	}

	st->trainst_w = w;
	st->trainst_h = h;
	st->train_tile = tile;
}

// remove a single tile from a railroad station
int32 CmdRemoveFromRailroadStation(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	uint tile = TILE_FROM_XY(x, y);
	Station *st;

	// make sure the specified tile belongs to the current player, and that it is a railroad station.
	if (!IS_TILETYPE(tile, MP_STATION) || _map5[tile] >= 8 || !_patches.nonuniform_stations) return CMD_ERROR;
	st = DEREF_STATION(_map2[tile]);
	if (_current_player != OWNER_WATER && (!CheckOwnership(st->owner) || !EnsureNoVehicle(tile))) return CMD_ERROR;

	// if we reached here, it means we can actually delete it. do that.
	if (flags & DC_EXEC) {
		DoClearSquare(tile);
		// now we need to make the "spanned" area of the railway station smaller if we deleted something at the edges.
		// we also need to adjust train_tile.
		MakeRailwayStationAreaSmaller(st);

		// if we deleted the whole station, delete the train facility.
		if (st->train_tile == 0) {
			st->facilities &= ~FACIL_TRAIN;
			UpdateStationVirtCoordDirty(st);
			DeleteStationIfEmpty(st);
		}
	}
	return _price.remove_rail_station;
}

// determine the number of platforms for the station
uint GetStationPlatforms(Station *st, uint tile)
{
	uint t;
	int dir,delta;
	int len;
	assert(TileBelongsToRailStation(st, tile));

	len = 0;
	dir = _map5[tile]&1;
	delta = dir ? TILE_XY(0,1) : TILE_XY(1,0);

	// find starting tile..
	t = tile;
	do { t -= delta; len++; } while (TileBelongsToRailStation(st, t) && (_map5[t]&1) == dir);

	// find ending tile
	t = tile;
	do { t += delta; len++; }while (TileBelongsToRailStation(st, t) && (_map5[t]&1) == dir);

	return len - 1;
}


/* TODO: Custom classes! */
/* Indexed by class, just STAT_CLASS_DFLT and STAT_CLASS_WAYP supported. */
static int _statspec_highest_id[2] = {-1, -1};
static struct StationSpec _station_spec[2][256];

void SetCustomStation(byte local_stid, struct StationSpec *spec)
{
	enum StationClass sclass;
	int stid = -1;

	assert(spec->sclass == STAT_CLASS_DFLT || spec->sclass == STAT_CLASS_WAYP);
	sclass = spec->sclass - 1;

	if (spec->localidx != 0) {
		/* Already allocated, try to resolve to global stid */
		int i;

		for (i = 0; i <= _statspec_highest_id[sclass]; i++) {
			if (_station_spec[sclass][i].grfid == spec->grfid
			    && _station_spec[sclass][i].localidx == local_stid + 1) {
				stid = i;
				/* FIXME: Release original SpriteGroup to
				 * prevent leaks. But first we need to
				 * refcount the SpriteGroup. --pasky */
				break;
			}
		}
	}

	if (stid == -1) {
		/* Allocate new one. */
		if (_statspec_highest_id[sclass] >= 255) {
			error("Too many custom stations allocated.");
			return;
		}
		stid = ++_statspec_highest_id[sclass];
		spec->localidx = local_stid + 1;
	}

	//debug("Registering station #%d of class %d", stid, sclass);
	memcpy(&_station_spec[sclass][stid], spec, sizeof(*spec));
}

struct StationSpec *GetCustomStation(enum StationClass sclass, byte stid)
{
	assert(sclass == STAT_CLASS_DFLT || sclass == STAT_CLASS_WAYP);
	sclass--;
	//debug("Asking for station #%d of class %d", stid, sclass);
	if (stid > _statspec_highest_id[sclass])
		return NULL;
	return &_station_spec[sclass][stid];
}

static struct RealSpriteGroup *
ResolveStationSpriteGroup(struct SpriteGroup *spritegroup, struct Station *stat)
{
	switch (spritegroup->type) {
		case SGT_REAL:
			return &spritegroup->g.real;

		case SGT_DETERMINISTIC: {
			struct DeterministicSpriteGroup *dsg = &spritegroup->g.determ;
			struct SpriteGroup *target;
			int value = -1;

			if ((dsg->variable >> 6) == 0) {
				/* General property */
				value = GetDeterministicSpriteValue(dsg->variable);

			} else {
				if (stat == NULL) {
					/* We are in a build dialog of something,
					 * and we are checking for something undefined.
					 * That means we should get the first target
					 * (NOT the default one). */
					if (dsg->num_ranges > 0) {
						target = &dsg->ranges[0].group;
					} else {
						target = dsg->default_group;
					}
					return ResolveStationSpriteGroup(target, NULL);
				}

				/* Station-specific property. */
				if (dsg->var_scope == VSG_SCOPE_PARENT) {
					/* TODO: Town structure. */

				} else /* VSG_SELF */ {
					if (dsg->variable == 0x40
					    || dsg->variable == 0x41) {
						/* FIXME: This is ad hoc only
						 * for waypoints. */
						value = 0x01010000;
					} else {
						/* TODO: Only small fraction done. */
						// TTDPatch runs on little-endian arch;
						// Variable is 0x70 + offset in the TTD's station structure
						switch (dsg->variable - 0x70) {
							case 0x80:
								value = stat->facilities;
								break;
							case 0x81:
								value = stat->airport_type;
								break;
							case 0x82:
								value = stat->truck_stop_status;
								break;
							case 0x83:
								value = stat->bus_stop_status;
								break;
							case 0x86:
								value = stat->airport_flags & 0xFFFF;
								break;
							case 0x87:
								value = stat->airport_flags & 0xFF;
								break;
							case 0x8A:
								value = stat->build_date;
								break;
						}
					}
				}
			}

			target = value != -1 ? EvalDeterministicSpriteGroup(dsg, value) : dsg->default_group;
			return ResolveStationSpriteGroup(target, stat);
		}

		default:
		case SGT_RANDOMIZED:
			error("I don't know how to handle random spritegroups yet!");
			return NULL;
	}
}

uint32 GetCustomStationRelocation(struct StationSpec *spec, struct Station *stat, byte ctype)
{
	struct RealSpriteGroup *rsg;

	rsg = ResolveStationSpriteGroup(&spec->spritegroup[ctype], stat);

	if (rsg->sprites_per_set != 0) {
		if (rsg->loading_count != 0) {
			return rsg->loading[0];
		} else if (rsg->loading_count != 0) {
			return rsg->loaded[0];
		}
	}

	error("Custom station 0x%08x::0x%02x has no sprites associated.",
	       spec->grfid, spec->localidx);
	/* This is what gets subscribed of dtss->image in newgrf.c,
	 * so it's probably kinda "default offset". Try to use it as
	 * emergency measure. */
	return 0x42D;
}

int GetCustomStationsCount(enum StationClass sclass)
{
	assert(sclass == STAT_CLASS_DFLT || sclass == STAT_CLASS_WAYP);
	sclass--;
	return _statspec_highest_id[sclass] + 1;
}


static int32 RemoveRailroadStation(Station *st, TileIndex tile, uint32 flags)
{
	int w,h;
	int32 cost;

	/* if there is flooding and non-uniform stations are enabled, remove platforms tile by tile */
	if (_current_player == OWNER_WATER && _patches.nonuniform_stations)
		return DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAILROAD_STATION);

	/* Current player owns the station? */
	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner))
		return CMD_ERROR;

	/* determine width and height of platforms */
	tile = st->train_tile;
	w = st->trainst_w;
	h = st->trainst_h;

	assert(w != 0 && h != 0);

	/* cost is area * constant */
	cost = w*h*_price.remove_rail_station;

	/* clear all areas of the station */
	do {
		int w_bak = w;
		do {
			// for nonuniform stations, only remove tiles that are actually train station tiles
			if (TileBelongsToRailStation(st, tile)) {
				if (!EnsureNoVehicle(tile))
					return CMD_ERROR;
				if (flags & DC_EXEC)
					DoClearSquare(tile);
			}
			tile += TILE_XY(1, 0);
		} while (--w);
		w = w_bak;
		tile = tile + TILE_XY(-w, 1);
	} while (--h);

	if (flags & DC_EXEC) {
		st->train_tile = 0;
		st->facilities &= ~FACIL_TRAIN;

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return cost;
}

int32 DoConvertStationRail(uint tile, uint totype, bool exec)
{
	Station *st;

	st = DEREF_STATION(_map2[tile]);
	if (!CheckOwnership(st->owner) || !EnsureNoVehicle(tile)) return CMD_ERROR;

	// tile is not a railroad station?
	if (_map5[tile] >= 8) return CMD_ERROR;

	// tile is already of requested type?
	if ( (uint)(_map3_lo[tile] & 0xF) == totype) return CMD_ERROR;

	if (exec) {
		// change type.
		_map3_lo[tile] = (_map3_lo[tile] & 0xF0) + totype;
		MarkTileDirtyByTile(tile);
	}

	return _price.build_rail >> 1;
}

/* Build a bus station
 * p1 - direction
 * p2 - unused
 */

int32 CmdBuildBusStation(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	uint tile;
	int32 cost;
	Station *st;

	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);

	tile = TILE_FROM_XY(x,y);

	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile))
		return CMD_ERROR;

	if ((cost=CheckFlatLandBelow(tile, 1, 1, flags, 1 << p1, NULL)) == CMD_ERROR)
		return CMD_ERROR;

	st = GetStationAround(tile, 1, 1, -1);
	if (st == CHECK_STATIONS_ERR)
		return CMD_ERROR;

	/* Find a station close to us */
	if (st == NULL) {
		st = GetClosestStationFromTile(tile, 8, _current_player);
		if (st!=NULL && st->facilities) st = NULL;
	}

	if (st != NULL) {
		if (st->owner != OWNER_NONE && st->owner != _current_player)
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);

		if (!CheckStationSpreadOut(st, tile, 1, 1))
			return CMD_ERROR;

		if (st->bus_tile != 0)
			return_cmd_error(STR_3044_TOO_CLOSE_TO_ANOTHER_BUS);
	} else {
		Town *t;

		st = AllocateStation();
		if (st == NULL)
			return CMD_ERROR;

		st->town = t = ClosestTownFromTile(tile, (uint)-1);

		if (_current_player < MAX_PLAYERS && flags&DC_EXEC)
			SETBIT(t->have_ratings, _current_player);

		st->sign.width_1 = 0;

		if (!GenerateStationName(st, tile, 0))
			return CMD_ERROR;

		if (flags & DC_EXEC)
			StationInitialize(st, tile);
	}

	cost += _price.build_bus_station;

	if (flags & DC_EXEC) {
		st->bus_tile = tile;
		if (!st->facilities) st->xy = tile;
		st->facilities |= FACIL_BUS_STOP;
		st->bus_stop_status = 3;
		st->owner = _current_player;

		st->build_date = _date;

		ModifyTile(tile,
			MP_SETTYPE(MP_STATION) | MP_MAPOWNER_CURRENT |
			MP_MAP2 | MP_MAP5 | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR,
			st->index,			/* map2 parameter */
			p1 + 0x47       /* map5 parameter */
		);

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}
	return cost;
}

// Remove a bus station
static int32 RemoveBusStation(Station *st, uint32 flags)
{
	uint tile;

	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner))
		return CMD_ERROR;

	tile = st->bus_tile;

	if (!EnsureNoVehicle(tile))
		return CMD_ERROR;

	if (flags & DC_EXEC) {
		DoClearSquare(tile);

		st->bus_tile = 0;
		st->facilities &= ~FACIL_BUS_STOP;

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return _price.remove_bus_station;
}


/* Build a truck station
 * p1 - direction
 * p2 - unused
 */
int32 CmdBuildTruckStation(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	uint tile;
	int32 cost = 0;
	Station *st;

	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);

	tile = TILE_FROM_XY(x,y);

	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile))
		return CMD_ERROR;

	if ((cost=CheckFlatLandBelow(tile, 1, 1, flags, 1 << p1, NULL)) == CMD_ERROR)
		return CMD_ERROR;

	st = GetStationAround(tile, 1, 1, -1);
	if (st == CHECK_STATIONS_ERR)
		return CMD_ERROR;

	/* Find a station close to us */
	if (st == NULL) {
		st = GetClosestStationFromTile(tile, 8, _current_player);
		if (st!=NULL && st->facilities) st = NULL;
	}

	if (st != NULL) {
		if (st->owner != OWNER_NONE && st->owner != _current_player)
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);

		if (!CheckStationSpreadOut(st, tile, 1, 1))
			return CMD_ERROR;

		if (st->lorry_tile != 0)
			return_cmd_error(STR_3045_TOO_CLOSE_TO_ANOTHER_TRUCK);
	} else {
		Town *t;

		st = AllocateStation();
		if (st == NULL)
			return CMD_ERROR;

		st->town = t = ClosestTownFromTile(tile, (uint)-1);

		if (_current_player < MAX_PLAYERS && flags&DC_EXEC)
			SETBIT(t->have_ratings, _current_player);

		st->sign.width_1 = 0;

		if (!GenerateStationName(st, tile, 0))
			return CMD_ERROR;

		if (flags & DC_EXEC)
			StationInitialize(st, tile);
	}

	cost += _price.build_truck_station;

	if (flags & DC_EXEC) {
		st->lorry_tile = tile;
		if (!st->facilities) st->xy = tile;
		st->facilities |= FACIL_TRUCK_STOP;
		st->truck_stop_status = 3;
		st->owner = _current_player;

		st->build_date = _date;

		ModifyTile(tile,
			MP_SETTYPE(MP_STATION) | MP_MAPOWNER_CURRENT |
			MP_MAP2 | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR | MP_MAP5,
			st->index,			/* map2 parameter */
			p1 + 0x43       /* map5 parameter */
		);

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}
	return cost;
}

// Remove a truck station
static int32 RemoveTruckStation(Station *st, uint32 flags)
{
	uint tile;

	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner))
		return CMD_ERROR;

	tile = st->lorry_tile;

	if (!EnsureNoVehicle(tile))
		return CMD_ERROR;

	if (flags & DC_EXEC) {
		DoClearSquare(tile);

		st->lorry_tile = 0;
		st->facilities &= ~FACIL_TRUCK_STOP;

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return _price.remove_truck_station;
}

// FIXME -- need to move to its corresponding Airport variable
// Country Airfield (small)
static const byte _airport_map5_tiles_country[] = {
	54, 53, 52, 65,
	58, 57, 56, 55,
	64, 63, 63, 62
};

// City Airport (large)
static const byte _airport_map5_tiles_town[] = {
	31, 9, 33, 9, 9, 32,
	27, 36, 29, 34, 8, 10,
	30, 11, 35, 13, 20, 21,
	51, 12, 14, 17, 19, 28,
	38, 13, 15, 16, 18, 39,
	26, 22, 23, 24, 25, 26
};

// Metropolitain Airport (large) - 2 runways
static const byte _airport_map5_tiles_metropolitan[] = {
	31, 9, 33, 9, 9, 32,
	27, 36, 29, 34, 8, 10,
	30, 11, 35, 13, 20, 21,
 102,  8,  8,  8,  8, 28,
	83, 84, 84, 84, 84, 83,
	26, 23, 23, 23, 23, 26
};

// International Airport (large) - 2 runways
static const byte _airport_map5_tiles_international[] = {
  88, 89, 89, 89, 89, 89, 88,
 	51,  8,  8,  8,  8,  8, 32,
	30,  8, 11, 27, 11,  8, 10,
	32,  8, 11, 27, 11,  8, 114,
	87,  8, 11, 85, 11,  8, 114,
	87,  8,  8,  8,  8,  8, 90,
	26, 23, 23, 23, 23, 23, 26
};

// Heliport
static const byte _airport_map5_tiles_heliport[] = {
	66,
};

static const byte * const _airport_map5_tiles[] = {
	_airport_map5_tiles_country,				// Country Airfield (small)
	_airport_map5_tiles_town,						// City Airport (large)
	_airport_map5_tiles_heliport,				// Heliport
	_airport_map5_tiles_metropolitan,   // Metropolitain Airport (large)
	_airport_map5_tiles_international,	// International Airport (xlarge)
};

/* Place an Airport
 * p1 - airport type
 * p2 - unused
 */
int32 CmdBuildAirport(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	uint tile;
	Town *t;
	Station *st;
	int32 cost;
	int w,h;
	bool airport_upgrade = true;

	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);

	tile = TILE_FROM_XY(x,y);

	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile))
		return CMD_ERROR;

	t = ClosestTownFromTile(tile, (uint)-1);

	/* Check if local auth refuses a new airport */
	{
		uint num = 0;
		FOR_ALL_STATIONS(st) {
			if (st->xy != 0 && st->town == t && st->facilities&FACIL_AIRPORT && st->airport_type != AT_OILRIG)
				num++;
		}
		if (num >= 2) {
			SetDParam(0, t->index);
			return_cmd_error(STR_2035_LOCAL_AUTHORITY_REFUSES);
		}
	}

	w = _airport_size_x[p1];
	h = _airport_size_y[p1];

	cost = CheckFlatLandBelow(tile, w, h, flags, 0, NULL);
	if (cost == CMD_ERROR)
		return CMD_ERROR;

	st = GetStationAround(tile, w, h, -1);
	if (st == CHECK_STATIONS_ERR)
		return CMD_ERROR;

	/* Find a station close to us */
	if (st == NULL) {
		st = GetClosestStationFromTile(tile, 8, _current_player);
		if (st!=NULL && st->facilities) st = NULL;
	}

	if (st != NULL) {
		if (st->owner != OWNER_NONE && st->owner != _current_player)
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);

		if (!CheckStationSpreadOut(st, tile, 1, 1))
			return CMD_ERROR;

		if (st->airport_tile != 0)
			return_cmd_error(STR_300D_TOO_CLOSE_TO_ANOTHER_AIRPORT);
	} else {
		Town *t;

		airport_upgrade = false;

		st = AllocateStation();
		if (st == NULL)
			return CMD_ERROR;

		st->town = t = ClosestTownFromTile(tile, (uint)-1);

		if (_current_player < MAX_PLAYERS && flags&DC_EXEC)
			SETBIT(t->have_ratings, _current_player);

		st->sign.width_1 = 0;

		// if airport type equals Heliport then generate
		// type 5 name, which is heliport, otherwise airport names (1)
		if (!GenerateStationName(st, tile, p1 == AT_HELIPORT ? 5 : 1))
			return CMD_ERROR;

		if (flags & DC_EXEC)
			StationInitialize(st, tile);
	}

	cost += _price.build_airport * w * h;

	if (flags & DC_EXEC) {
		st->owner = _current_player;
		if (_current_player == _local_player && p1 <= AT_INTERNATIONAL) {
      _last_built_aircraft_depot_tile = tile + GetAirport(p1)->airport_depots[0];
    }

		st->airport_tile = tile;
		if (!st->facilities) st->xy = tile;
		st->facilities |= FACIL_AIRPORT;
		st->airport_type = (byte)p1;
		st->airport_flags = 0;

		st->build_date = _date;

		/*	if airport was demolished while planes were en-route to it, the positions can no longer
				be the same (v->u.air.pos), since different airports have different indexes. So update
				all planes en-route to this airport. Only update if
				1. airport is upgraded
				2. airport is added to existing station (unfortunately unavoideable)
		*/
		if (airport_upgrade) {UpdateAirplanesOnNewStation(st);}

		{
			const byte *b = _airport_map5_tiles[p1];
BEGIN_TILE_LOOP(tile_cur,w,h,tile)
				ModifyTile(tile_cur,
					MP_SETTYPE(MP_STATION) | MP_MAPOWNER_CURRENT |
					MP_MAP2 | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR | MP_MAP5,
					st->index, *b++);
END_TILE_LOOP(tile_cur,w,h,tile)
		}

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}

	return cost;
}

static int32 RemoveAirport(Station *st, uint32 flags)
{
	uint tile;
	int w,h;
	int32 cost;

	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner))
		return CMD_ERROR;

	tile = st->airport_tile;

	w = _airport_size_x[st->airport_type];
	h = _airport_size_y[st->airport_type];

	cost = w * h * _price.remove_airport;

	{
BEGIN_TILE_LOOP(tile_cur,w,h,tile)
		if (!EnsureNoVehicle(tile_cur))
			return CMD_ERROR;

		if (flags & DC_EXEC) {
			DeleteAnimatedTile(tile_cur);
			DoClearSquare(tile_cur);
		}
END_TILE_LOOP(tile_cur, w,h,tile)
	}

	if (flags & DC_EXEC) {
		if (st->airport_type <= AT_INTERNATIONAL)
      DeleteWindowById(WC_VEHICLE_DEPOT, tile + GetAirport(st->airport_type)->airport_depots[0]);
		st->airport_tile = 0;
		st->facilities &= ~FACIL_AIRPORT;

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return cost;
}

/* Build a buoy
 * p1,p2 unused
 */

int32 CmdBuildBuoy(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	TileInfo ti;
	Station *st;

	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);

	FindLandscapeHeight(&ti, x, y);

	if (ti.type != MP_WATER || ti.tileh != 0 || ti.map5 != 0 || ti.tile == 0)
		return_cmd_error(STR_304B_SITE_UNSUITABLE);

	st = AllocateStation();
	if (st == NULL)
		return CMD_ERROR;

	st->town = ClosestTownFromTile(ti.tile, (uint)-1);
	st->sign.width_1 = 0;

	if (!GenerateStationName(st, ti.tile, 4))
		return CMD_ERROR;

	if (flags & DC_EXEC) {
		StationInitialize(st, ti.tile);
		st->dock_tile = ti.tile;
		st->facilities |= FACIL_DOCK;
		st->had_vehicle_of_type |= HVOT_BUOY;
		st->owner = OWNER_NONE;

		st->build_date = _date;

		ModifyTile(ti.tile,
			MP_SETTYPE(MP_STATION) |
			MP_MAP2 | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR | MP_MAPOWNER | MP_MAP5,
			st->index,		/* map2 */
			OWNER_NONE,		/* map_owner */
			0x52					/* map5 */
		);

		UpdateStationVirtCoordDirty(st);

		UpdateStationAcceptance(st, false);
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}

	return _price.build_dock;
}

static int32 RemoveBuoy(Station *st, uint32 flags)
{
	uint tile;

	if (_current_player >= MAX_PLAYERS) {
		/* XXX: strange stuff */
		return_cmd_error(INVALID_STRING_ID);
	}

	tile = st->dock_tile;

	if (!EnsureNoVehicle(tile))
		return CMD_ERROR;

	if (flags & DC_EXEC) {
		st->dock_tile = 0;
		st->facilities &= ~FACIL_DOCK;
		st->had_vehicle_of_type &= ~HVOT_BUOY;

		ModifyTile(tile,
			MP_SETTYPE(MP_WATER) |
			MP_MAP2_CLEAR | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR | MP_MAPOWNER | MP_MAP5 | MP_MAP2_CLEAR,
			OWNER_WATER, /* map_owner */
			0			/* map5 */
		);

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return _price.remove_truck_station;
}

static const TileIndexDiff _dock_tileoffs_chkaround[4] = {
	TILE_XY(-1,0),
	0,0,
	TILE_XY(0,-1),
};
static const byte _dock_w_chk[4] = { 2,1,2,1 };
static const byte _dock_h_chk[4] = { 1,2,1,2 };

int32 CmdBuildDock(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	TileInfo ti;
	int direction;
	int32 cost;
	uint tile, tile_cur;
	Station *st;

	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);

	FindLandscapeHeight(&ti, x, y);

	if ((direction=0,ti.tileh) != 3 &&
			(direction++,ti.tileh) != 9 &&
			(direction++,ti.tileh) != 12 &&
			(direction++,ti.tileh) != 6)
		return_cmd_error(STR_304B_SITE_UNSUITABLE);

	if (!EnsureNoVehicle(ti.tile))
		return CMD_ERROR;

	cost = DoCommandByTile(ti.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
	if (cost == CMD_ERROR)
		return CMD_ERROR;

	tile_cur = (tile=ti.tile) + _tileoffs_by_dir[direction];

	if (!EnsureNoVehicle(tile_cur))
		return CMD_ERROR;

	FindLandscapeHeightByTile(&ti, tile_cur);
	if (ti.tileh != 0 || ti.type != MP_WATER)
		return_cmd_error(STR_304B_SITE_UNSUITABLE);

	cost = DoCommandByTile(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
	if (cost == CMD_ERROR)
		return CMD_ERROR;

	tile_cur = tile_cur + _tileoffs_by_dir[direction];
	FindLandscapeHeightByTile(&ti, tile_cur);
	if (ti.tileh != 0 || ti.type != MP_WATER)
		return_cmd_error(STR_304B_SITE_UNSUITABLE);

	/* middle */
	st = GetStationAround(tile + _dock_tileoffs_chkaround[direction],
		_dock_w_chk[direction], _dock_h_chk[direction], -1);
	if (st == CHECK_STATIONS_ERR)
		return CMD_ERROR;

	/* Find a station close to us */
	if (st == NULL) {
		st = GetClosestStationFromTile(tile, 8, _current_player);
		if (st!=NULL && st->facilities) st = NULL;
	}

	if (st != NULL) {
		if (st->owner != OWNER_NONE && st->owner != _current_player)
			return_cmd_error(STR_3009_TOO_CLOSE_TO_ANOTHER_STATION);

		if (!CheckStationSpreadOut(st, tile, 1, 1))
			return CMD_ERROR;

		if (st->dock_tile != 0)
			return_cmd_error(STR_304C_TOO_CLOSE_TO_ANOTHER_DOCK);
	} else {
		Town *t;

		st = AllocateStation();
		if (st == NULL)
			return CMD_ERROR;

		st->town = t = ClosestTownFromTile(tile, (uint)-1);

		if (_current_player < MAX_PLAYERS && flags&DC_EXEC)
			SETBIT(t->have_ratings, _current_player);

		st->sign.width_1 = 0;

		if (!GenerateStationName(st, tile, 3))
			return CMD_ERROR;

		if (flags & DC_EXEC)
			StationInitialize(st, tile);
	}

	if (flags & DC_EXEC) {
		st->dock_tile = tile;
		if (!st->facilities) st->xy = tile;
		st->facilities |= FACIL_DOCK;
		st->owner = _current_player;

		st->build_date = _date;

		ModifyTile(tile,
			MP_SETTYPE(MP_STATION) | MP_MAPOWNER_CURRENT |
			MP_MAP2 | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR |
			MP_MAP5,
			st->index,
			direction + 0x4C);

		ModifyTile(tile + _tileoffs_by_dir[direction],
			MP_SETTYPE(MP_STATION) | MP_MAPOWNER_CURRENT |
			MP_MAP2 | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR |
			MP_MAP5,
			st->index,
			(direction&1) + 0x50);

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}
	return _price.build_dock;
}

static int32 RemoveDock(Station *st, uint32 flags)
{
	uint tile1, tile2;

	if (!CheckOwnership(st->owner))
		return CMD_ERROR;

	tile1 = st->dock_tile;
	tile2 = tile1 + _tileoffs_by_dir[_map5[tile1] - 0x4C];

	if (!EnsureNoVehicle(tile1))
		return CMD_ERROR;

	if (!EnsureNoVehicle(tile2))
		return CMD_ERROR;

	if (flags & DC_EXEC) {
		DoClearSquare(tile1);

		// convert the water tile to water.
		ModifyTile(tile2, MP_SETTYPE(MP_WATER) | MP_MAPOWNER | MP_MAP5 | MP_MAP2_CLEAR | MP_MAP3LO_CLEAR | MP_MAP3HI_CLEAR, OWNER_WATER, 0);

		st->dock_tile = 0;
		st->facilities &= ~FACIL_DOCK;

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return _price.remove_dock;
}

#include "table/station_land.h"


extern uint16 _custom_sprites_base;

static void DrawTile_Station(TileInfo *ti)
{
	uint32 image_or_modificator;
	uint32 image;
	const DrawTileSeqStruct *dtss;
	const DrawTileSprites *t = NULL;
	byte railtype = _map3_lo[ti->tile] & 0xF;
	uint32 relocation = 0;

	{
		uint owner = _map_owner[ti->tile];
		image_or_modificator = 0x315 << 16; /* NOTE: possible bug in ttd here? */
		if (owner < MAX_PLAYERS)
			image_or_modificator = PLAYER_SPRITE_COLOR(owner);
	}

	// don't show foundation for docks (docks are between 76 (0x4C) and 81 (0x51))
	if (ti->tileh != 0 && (ti->map5 < 0x4C || ti->map5 > 0x51))
		DrawFoundation(ti, ti->tileh);

	if (_map3_lo[ti->tile] & 0x10) {
		// look for customization
		struct StationSpec *statspec = GetCustomStation(STAT_CLASS_DFLT, _map3_hi[ti->tile]);

		//debug("Cust-o-mized %p", statspec);

		if (statspec != NULL) {
			Station *st = DEREF_STATION(_map2[ti->tile]);

			relocation = GetCustomStationRelocation(statspec, st, 0);
			//debug("Relocation %d", relocation);
			t = &statspec->renderdata[ti->map5];
		}
	}

	if (t == NULL) t = &_station_display_datas[ti->map5];

	image = t->ground_sprite;
	if (image & 0x8000)
		image |= image_or_modificator;

	// station_land array has been increased from 82 elements to 114
	// but this is something else. If AI builds station with 114 it looks all weird
	image += railtype * ((image & 0x3FFF) < _custom_sprites_base ? TRACKTYPE_SPRITE_PITCH : 1);
	DrawGroundSprite(image);

	foreach_draw_tile_seq(dtss, t->seq) {
		image =	dtss->image + relocation;
		// For custom sprites, there's no railtype-based pitching.
		image += railtype * ((image & 0x3FFF) < _custom_sprites_base ? TRACKTYPE_SPRITE_PITCH : 0);
		if (_display_opt & DO_TRANS_BUILDINGS) {
			image = (image & 0x3FFF) | 0x03224000;
		} else {
			if (image&0x8000) image |= image_or_modificator;	
		}

		if ((byte)dtss->delta_z != 0x80) {
			AddSortableSpriteToDraw(image, ti->x + dtss->delta_x, ti->y + dtss->delta_y, dtss->width, dtss->height, dtss->unk, ti->z + dtss->delta_z);
		} else {
			AddChildSpriteScreen(image, dtss->delta_x, dtss->delta_y);
		}
	}
}

void StationPickerDrawSprite(int x, int y, int railtype, int image)
{
	uint32 ormod, img;
	const DrawTileSeqStruct *dtss;
	const DrawTileSprites *t;

	/* baseimage */
	railtype *= TRACKTYPE_SPRITE_PITCH;

	ormod = PLAYER_SPRITE_COLOR(_local_player);

	t = &_station_display_datas[image];

	img = t->ground_sprite;
	if (img & 0x8000)
		img |= ormod;
	DrawSprite(img + railtype, x, y);

	foreach_draw_tile_seq(dtss, t->seq) {
		Point pt = RemapCoords(dtss->delta_x, dtss->delta_y, dtss->delta_z);
		DrawSprite((dtss->image | ormod) + railtype, x + pt.x, y + pt.y);
	}
}

static uint GetSlopeZ_Station(TileInfo *ti)
{
	uint z = ti->z;
	if (ti->tileh != 0)
		z += 8;
	return z;
}

static uint GetSlopeTileh_Station(TileInfo *ti)
{
	return 0;
}

static void GetAcceptedCargo_Station(uint tile, AcceptedCargo ac)
{
	/* not used */
}

static void GetTileDesc_Station(uint tile, TileDesc *td)
{
	byte m5;
	StringID str;

	td->owner = _map_owner[tile];
	td->build_date = DEREF_STATION(_map2[tile])->build_date;

	m5 = _map5[tile];
	(str=STR_305E_RAILROAD_STATION, m5 < 8) ||
	(str=STR_305F_AIRCRAFT_HANGAR, m5==32 || m5==45) || // hangars
	(str=STR_3060_AIRPORT, m5 < 0x43 || (m5 >= 83 && m5 <= 114)) ||
	(str=STR_3061_TRUCK_LOADING_AREA, m5 < 0x47) ||
	(str=STR_3062_BUS_STATION, m5 < 0x4B) ||
	(str=STR_4807_OIL_RIG, m5 == 0x4B) ||
	(str=STR_3063_SHIP_DOCK, m5 != 0x52) ||
	(str=STR_3069_BUOY, true);
	td->str = str;
}


static const byte _tile_track_status_rail[8] = { 1,2,1,2,1,2,1,2 };

static uint32 GetTileTrackStatus_Station(uint tile, TransportType mode) {
	uint i = _map5[tile];
	uint j = 0;

	if (mode == TRANSPORT_RAIL) {
		if (i < 8)
			j = _tile_track_status_rail[i];
		j += (j << 8);
	} else if (mode == TRANSPORT_WATER) {
		// buoy is coded as a station, it is always on open water
		// (0x3F, all tracks available)
		if (i == 0x52) j = 0x3F;
		j += (j << 8);
	}
	return j;
}

static void TileLoop_Station(uint tile)
{
  //FIXME -- GetTileTrackStatus_Station -> animated stationtiles
  // hardcoded.....not good
  // 0x27 - large big airport (39)
  // 0x66 - radar metropolitan airport (102)
  // 0x5A - radar international airport (90)
  // 0x3A - flag small airport (58)
	if (_map5[tile] == 39 || _map5[tile] == 58 || _map5[tile] == 90 || _map5[tile] == 102)
		AddAnimatedTile(tile);

	// treat a bouy tile as water.
	else if (_map5[tile] == 0x52)
		TileLoop_Water(tile);

	// treat a oilrig (the station part) as water
	else if (_map5[tile] == 0x4B)
		TileLoop_Water(tile);

}


static void AnimateTile_Station(uint tile)
{
	byte m5 = _map5[tile];
	//FIXME -- AnimateTile_Station -> not nice code, lots of things double
  // again hardcoded...was a quick hack

  // turning radar / windsack on airport
	if (m5 >= 39 && m5 <= 50) { // turning radar (39 - 50)
		if (_tick_counter & 3)
			return;

		if (++m5 == 50+1)
			m5 = 39;

		_map5[tile] = m5;
		MarkTileDirtyByTile(tile);
  //added - begin
	} else if (m5 >= 90 && m5 <= 113) { // turning radar with ground under it (different fences) (90 - 101 | 102 - 113)
		if (_tick_counter & 3)
			return;

		m5++;

		if (m5 == 101+1) {m5 = 90;}  // radar with fences in south
		else if (m5 == 113+1) {m5 = 102;} // radar with fences in north

		_map5[tile] = m5;
		MarkTileDirtyByTile(tile);
	//added - end
	} else if (m5 >= 0x3A && m5 <= 0x3D) {  // windsack (58 - 61)
		if (_tick_counter & 1)
			return;

		if (++m5 == 0x3D+1)
			m5 = 0x3A;

		_map5[tile] = m5;
		MarkTileDirtyByTile(tile);
	}
}

static void ClickTile_Station(uint tile)
{
  // 0x20 - hangar large airport (32)
  // 0x41 - hangar small airport (65)
	if (_map5[tile] == 32 || _map5[tile] == 65) {
		ShowAircraftDepotWindow(tile);
	} else {
		ShowStationViewWindow(_map2[tile]);
	}
}

static inline bool IsTrainStationTile(uint tile) {
	return IS_TILETYPE(tile, MP_STATION) && IS_BYTE_INSIDE(_map5[tile], 0, 8);
}

static const byte _enter_station_speedtable[12] = {
	215, 195, 175, 155, 135, 115, 95, 75, 55, 35, 15, 0
};

static uint32 VehicleEnter_Station(Vehicle *v, uint tile, int x, int y)
{
	byte station_id;
	byte dir;
	uint16 spd;

	if (v->type == VEH_Train) {
		if (IS_BYTE_INSIDE(_map5[tile], 0, 8) && v->subtype == 0 &&
			!IsTrainStationTile(tile + _tileoffs_by_dir[v->direction >> 1])) {

			station_id = _map2[tile];
			if ((!(v->current_order.flags & OF_NON_STOP) && !_patches.new_nonstop) ||
					(v->current_order.type == OT_GOTO_STATION && v->current_order.station == station_id)) {

				if (!(_patches.new_nonstop && v->current_order.flags & OF_NON_STOP) &&
						v->current_order.type != OT_LEAVESTATION &&
						v->last_station_visited != station_id) {
					x &= 0xF;
					y &= 0xF;

					dir = v->direction & 6;
					if (dir & 2) intswap(x,y);
					if (y == 8) {
						if (dir != 2 && dir != 4) {
							x = (~x)&0xF;
						}
						if (x == 12) return 2 | (station_id << 8); /* enter station */
						if (x < 12) {
							v->vehstatus |= VS_TRAIN_SLOWING;
							spd = _enter_station_speedtable[x];
							if (spd < v->cur_speed)
								v->cur_speed = spd;
						}
					}
				}
			}
		}
	} else if (v->type == VEH_Road) {
		if (v->u.road.state < 16 && (v->u.road.state&4)==0 && v->u.road.frame==0) {
			Station *st = DEREF_STATION(_map2[tile]);
			byte m5 = _map5[tile];
			byte *b, bb,state;

			if (IS_BYTE_INSIDE(m5, 0x43, 0x4B)) {
				b = (m5 >= 0x47) ? &st->bus_stop_status : &st->truck_stop_status;

				bb = *b;

				/* bb bits 1..0 describe current the two parking spots.
				0 means occupied, 1 means free. */

				// Station busy?
				if (bb & 0x80 || (bb&3) == 0)
					return 8;

				state = v->u.road.state + 32;
				if (bb & 1) {
					bb &= ~1;
				} else {
					bb &= ~2;
					state += 2;
				}
				*b = bb;
				v->u.road.state = state;
			}
		}
	}

	return 0;
}

static void DeleteStation(Station *st)
{
	Order order;
	int index;
	st->xy = 0;

	DeleteName(st->string_id);
	MarkStationDirty(st);
	_global_station_sort_dirty = true; // delete station, remove sign
	InvalidateWindowClasses(WC_STATION_LIST);

	index = st->index;
	DeleteWindowById(WC_STATION_VIEW, index);
	order.type = OT_GOTO_STATION;
	order.flags = 0;
	order.station = index;
	DeleteCommandFromVehicleSchedule(order);
	DeleteSubsidyWithStation(index);
}

void DeleteAllPlayerStations()
{
	Station *st;

	FOR_ALL_STATIONS(st) {
		if (st->xy && st->owner < MAX_PLAYERS)
			DeleteStation(st);
	}
}

/* this function is called for one station each tick */
static void StationHandleBigTick(Station *st)
{
	UpdateStationAcceptance(st, true);

	if (st->facilities == 0) {
		if (++st->delete_ctr >= 8)
			DeleteStation(st);
	}
}

static inline void byte_inc_sat(byte *p) { byte b = *p + 1; if (b != 0) *p = b; }

static byte _rating_boost[3] = { 0, 31, 63};

static void UpdateStationRating(Station *st)
{
	GoodsEntry *ge;
	int rating, index;
	int waiting;
	bool waiting_changed = false;

	byte_inc_sat(&st->time_since_load);
	byte_inc_sat(&st->time_since_unload);

	ge = st->goods;
	do {
		if (ge->enroute_from != 0xFF) {
			byte_inc_sat(&ge->enroute_time);
			byte_inc_sat(&ge->days_since_pickup);

			rating = 0;

			{
				int b = ge->last_speed;
				if ((b-=85) >= 0)
					rating += b >> 2;
			}

			{
				byte age = ge->last_age;
				(age >= 3) ||
				(rating += 10, age >= 2) ||
				(rating += 10, age >= 1) ||
				(rating += 13, true);
			}

			{
				if (!IS_HUMAN_PLAYER(st->owner) && st->owner != OWNER_NONE)
							rating += _rating_boost[_opt.diff.competitor_intelligence];
			}

			if (st->owner < 8 && HASBIT(st->town->statues, st->owner))
				rating += 26;

			{
				byte days = ge->days_since_pickup;
				if (st->last_vehicle != INVALID_VEHICLE &&
						(&_vehicles[st->last_vehicle])->type == VEH_Ship)
							days >>= 2;
				(days > 21) ||
				(rating += 25, days > 12) ||
				(rating += 25, days > 6) ||
				(rating += 45, days > 3) ||
				(rating += 35, true);
			}

			{
				waiting = ge->waiting_acceptance & 0xFFF;
				(rating -= 90, waiting > 1500) ||
				(rating += 55, waiting > 1000) ||
				(rating += 35, waiting > 600) ||
				(rating += 10, waiting > 300) ||
				(rating += 20, waiting > 100) ||
				(rating += 10, true);
			}

			{
				int or = ge->rating; // old rating

				// only modify rating in steps of -2, -1, 0, 1 or 2
				ge->rating = rating = or + clamp(clamp(rating, 0, 255) - or, -2, 2);

				// if rating is <= 64 and more than 200 items waiting, remove some random amount of goods from the station
				if (rating <= 64 && waiting >= 200) {
					int dec = Random() & 0x1F;
					if (waiting < 400) dec &= 7;
					waiting -= dec + 1;
					waiting_changed = true;
				}

				// if rating is <= 127 and there are any items waiting, maybe remove some goods.
				if (rating <= 127 && waiting != 0) {
					uint32 r = Random();
					if ( (uint)rating <= (r & 0x7F) ) {
						waiting = max(waiting - ((r >> 8)&3) - 1, 0);
						waiting_changed = true;
					}
				}

				if (waiting_changed)
					ge->waiting_acceptance = (ge->waiting_acceptance & ~0xFFF) + waiting;
			}
		}
	} while (++ge != endof(st->goods));

	index = st->index;

	if (waiting_changed)
		InvalidateWindow(WC_STATION_VIEW, index);
	else
		InvalidateWindowWidget(WC_STATION_VIEW, index, 5);
}

/* called for every station each tick */
static void StationHandleSmallTick(Station *st)
{
	byte b;

	if (st->facilities == 0)
		return;

	b = st->delete_ctr + 1;
	if (b >= 185) b = 0;
	st->delete_ctr = b;

	if (b == 0)
		UpdateStationRating(st);
}

void OnTick_Station()
{
	int i;
	Station *st;

	if (_game_mode == GM_EDITOR)
		return;

	i = _station_tick_ctr;
	if (++_station_tick_ctr == lengthof(_stations))
		_station_tick_ctr = 0;

	st = DEREF_STATION(i);
	if (st->xy != 0)
		StationHandleBigTick(st);

	FOR_ALL_STATIONS(st) {
		if (st->xy != 0)
			StationHandleSmallTick(st);
	}

}

void StationMonthlyLoop()
{
}


void ModifyStationRatingAround(TileIndex tile, byte owner, int amount, uint radius)
{
	Station *st;
	GoodsEntry *ge;
	int i;

	FOR_ALL_STATIONS(st) {
		if (st->xy != 0 && st->owner == owner && GetTileDist(tile, st->xy) <= radius) {
			ge = st->goods;
			for(i=0; i!=NUM_CARGO; i++,ge++) {
				if (ge->enroute_from != 0xFF) {
					ge->rating = clamp(ge->rating + amount, 0, 255);
				}
			}
		}
	}
}

static void UpdateStationWaiting(Station *st, int type, uint amount)
{
	st->goods[type].waiting_acceptance =
		(st->goods[type].waiting_acceptance & ~0xFFF) +
			min(0xFFF, (st->goods[type].waiting_acceptance & 0xFFF) + amount);

	st->goods[type].enroute_time = 0;
	st->goods[type].enroute_from = st->index;
	InvalidateWindow(WC_STATION_VIEW, st->index);
}

int32 CmdRenameStation(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	StringID str,old_str;
	Station *st;

	str = AllocateNameUnique((byte*)_decode_parameters, 6);
	if (str == 0)
		return CMD_ERROR;

	if (flags & DC_EXEC) {
		st = DEREF_STATION(p1);
		old_str = st->string_id;
		st->string_id = str;
		UpdateStationVirtCoord(st);
		DeleteName(old_str);
		_station_sort_dirty[st->owner] = true; // rename a station
		MarkWholeScreenDirty();
	} else {
		DeleteName(str);
	}

	return 0;
}


uint MoveGoodsToStation(uint tile, int w, int h, int type, uint amount)
{
	Station *around_ptr[8];
	byte around[8], st_index;
	int i;
	Station *st;
	uint moved;
	uint best_rating, best_rating2;
	Station *st1, *st2;
	int t;
	int rad=0;
	int w_prod=0, h_prod=0; //width and height of the "producer" of the cargo
	int x_min_prod, x_max_prod;     //min and max coordinates of the producer
	int y_min_prod, y_max_prod;     //relative
	int x_dist, y_dist;
	int max_rad;


	memset(around, 0xff, sizeof(around));

	if (_patches.modified_catchment) {
		w_prod = w;
		h_prod = h;
		w += 16;
		h += 16;
		max_rad = 8;
	} else {
 		w += 8;
 		h += 8;
		max_rad = 4;
	}

	BEGIN_TILE_LOOP(cur_tile, w, h, tile - TILE_XY(max_rad,max_rad))
		cur_tile = TILE_MASK(cur_tile);
		if (IS_TILETYPE(cur_tile, MP_STATION)) {
			st_index = _map2[cur_tile];
			for(i=0; i!=8; i++)	{
				if (around[i] == 0xFF) {
					st = DEREF_STATION(st_index);
					if ((st->had_vehicle_of_type & HVOT_BUOY) == 0 &&
							( !st->town->exclusive_counter || (st->town->exclusivity == st->owner) ) && // check exclusive transport rights
							st->goods[type].rating != 0 &&
							(!_patches.selectgoods || st->goods[type].last_speed) && // if last_speed is 0, no vehicle has been there.
							((st->facilities & (byte)~FACIL_BUS_STOP)!=0 || type==CT_PASSENGERS) && // if we have other fac. than a bus stop, or the cargo is passengers
							((st->facilities & (byte)~FACIL_TRUCK_STOP)!=0 || type!=CT_PASSENGERS)) { // if we have other fac. than a cargo bay or the cargo is not passengers
								if (_patches.modified_catchment) {
									FIND_CATCHMENT_RADIUS(st,rad)
									x_min_prod = y_min_prod = 9;
									x_max_prod = 8 + w_prod;
									y_max_prod = 8 + h_prod;
		
									x_dist = min(w_cur - x_min_prod, x_max_prod - w_cur);
		
									if (w_cur < x_min_prod) {
										x_dist = x_min_prod - w_cur;
									} else {        //save cycles
										if (w_cur > x_max_prod) x_dist = w_cur - x_max_prod;
									}
		
									y_dist = min(h_cur - y_min_prod, y_max_prod - h_cur);
									if (h_cur < y_min_prod) {
										y_dist = y_min_prod - h_cur;
									} else {
										if (h_cur > y_max_prod) y_dist = h_cur - y_max_prod;
									}
		
								} else {
									x_dist = y_dist = 0;
								}
		
								if ( !(x_dist > rad) && !(y_dist > rad) ) {

									around[i] = st_index;
									around_ptr[i] = st;
								}
							}
					break;
				} else if (around[i] == st_index)
					break;
			}
		}
	END_TILE_LOOP(cur_tile, w, h, tile - TILE_XY(max_rad, max_rad))

	/* no stations around at all? */
	if (around[0] == 0xFF)
		return 0;

	if (around[1] == 0xFF) {
		/* only one station around */
		moved = (amount * around_ptr[0]->goods[type].rating >> 8) + 1;
		UpdateStationWaiting(around_ptr[0], type, moved);
		return moved;
	}

	/* several stations around, find the two with the highest rating */
	st2 = st1 = NULL;
	best_rating = best_rating2 = 0;
	for(i=0; i!=8 && around[i] != 0xFF; i++) {
		if (around_ptr[i]->goods[type].rating >= best_rating) {
			best_rating2 = best_rating;
			st2 = st1;

			best_rating = around_ptr[i]->goods[type].rating;
			st1 = around_ptr[i];
		} else if (around_ptr[i]->goods[type].rating >= best_rating2) {
			best_rating2 = around_ptr[i]->goods[type].rating;
			st2 = around_ptr[i];
		}
	}

	assert(st1 != NULL);
	assert(st2 != NULL);
	assert(best_rating != 0 || best_rating2 != 0);

	/* the 2nd highest one gets a penalty */
	best_rating2 >>= 1;

	/* amount given to station 1 */
	t = (best_rating * (amount + 1)) / (best_rating + best_rating2);

	moved = 0;
	if (t != 0) {
		moved = (t * best_rating >> 8) + 1;
		amount -= t;
		UpdateStationWaiting(st1, type, moved);
	}

	assert(amount >= 0);

	if (amount != 0) {
		moved += (amount = (amount * best_rating2 >> 8) + 1);
		UpdateStationWaiting(st2, type, amount);
	}

	return moved;
}

void BuildOilRig(uint tile)
{
	Station *st;
	int j;

	FOR_ALL_STATIONS(st) {
		if (st->xy == 0) {
			st->town = ClosestTownFromTile(tile, (uint)-1);
			st->sign.width_1 = 0;
			if (!GenerateStationName(st, tile, 2))
				return;

			_map_type_and_height[tile] &= 0xF;
			_map_type_and_height[tile] |= MP_STATION << 4;
			_map5[tile] = 0x4B;
			_map_owner[tile] = OWNER_NONE;
			_map3_lo[tile] = 0;
			_map3_hi[tile] = 0;
			_map2[tile] = st->index;

			st->owner = OWNER_NONE;
      st->airport_flags = 0;
			st->airport_type = AT_OILRIG;
			st->xy = tile;
			st->bus_tile = 0;
			st->lorry_tile = 0;
			st->airport_tile = tile;
			st->dock_tile = tile;
			st->train_tile = 0;
			st->had_vehicle_of_type = 0;
			st->time_since_load = 255;
			st->time_since_unload = 255;
			st->delete_ctr = 0;
			st->last_vehicle = INVALID_VEHICLE;
			st->facilities = FACIL_AIRPORT | FACIL_DOCK;
			st->build_date = _date;
			for(j=0; j!=NUM_CARGO; j++) {
				st->goods[j].waiting_acceptance = 0;
				st->goods[j].days_since_pickup = 0;
				st->goods[j].enroute_from = 0xFF;
				st->goods[j].rating = 175;
				st->goods[j].last_speed = 0;
				st->goods[j].last_age = 255;
			}

			UpdateStationVirtCoordDirty(st);
			UpdateStationAcceptance(st, false);
			return;
		}
	}
}

void DeleteOilRig(uint tile)
{
	Station *st = DEREF_STATION(_map2[tile]);

	DoClearSquare(tile);

	st->dock_tile = 0;
	st->airport_tile = 0;
	st->facilities &= ~(FACIL_AIRPORT | FACIL_DOCK);
	st->airport_flags = 0;
	UpdateStationVirtCoordDirty(st);
	DeleteStation(st);
}

static void ChangeTileOwner_Station(uint tile, byte old_player, byte new_player)
{
	if (_map_owner[tile] != old_player)
		return;

	if (new_player != 255) {
		Station *st = DEREF_STATION(_map2[tile]);
		_map_owner[tile] = new_player;
		st->owner = new_player;
		_global_station_sort_dirty = true; // transfer ownership of station to another player
		InvalidateWindowClasses(WC_STATION_LIST);
	} else {
		DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
	}
}

static int32 ClearTile_Station(uint tile, byte flags) {
	byte m5 = _map5[tile];
	Station *st;

	if (flags & DC_AUTO) {
		if (m5 < 8) return_cmd_error(STR_300B_MUST_DEMOLISH_RAILROAD);
		if (m5 < 0x43 || (m5 >= 83 && m5 <= 114)) return_cmd_error(STR_300E_MUST_DEMOLISH_AIRPORT_FIRST);
		if (m5 < 0x47) return_cmd_error(STR_3047_MUST_DEMOLISH_TRUCK_STATION);
		if (m5 < 0x4B) return_cmd_error(STR_3046_MUST_DEMOLISH_BUS_STATION);
		if (m5 == 0x52) return_cmd_error(STR_306A_BUOY_IN_THE_WAY);
		if (m5 != 0x4B && m5 < 0x53) return_cmd_error(STR_304D_MUST_DEMOLISH_DOCK_FIRST);
		SetDParam(0, STR_4807_OIL_RIG);
		return_cmd_error(STR_4800_IN_THE_WAY);
	}

	st = DEREF_STATION(_map2[tile]);

	if (m5 < 8)
		return RemoveRailroadStation(st, tile, flags);

	// original airports < 67, new airports between 83 - 114
	if (m5 < 0x43 || ( m5 >= 83 && m5 <= 114) )
		return RemoveAirport(st, flags);

	if (m5 < 0x47)
		return RemoveTruckStation(st, flags);

	if (m5 < 0x4B)
		return RemoveBusStation(st, flags);

	if (m5 == 0x52)
		return RemoveBuoy(st, flags);

	if (m5 != 0x4B && m5 < 0x53)
		return RemoveDock(st, flags);

	return CMD_ERROR;

}

void InitializeStations()
{
	int i;

	memset(_stations, 0, sizeof(_stations));
	for(i = 0; i != lengthof(_stations); i++)
		_stations[i].index=i;

	_station_tick_ctr = 0;

	// set stations to be sorted on load of savegame
	memset(_station_sort_dirty, true, sizeof(_station_sort_dirty));
	_global_station_sort_dirty = true; // load of savegame
}


const TileTypeProcs _tile_type_station_procs = {
	DrawTile_Station,						/* draw_tile_proc */
	GetSlopeZ_Station,					/* get_slope_z_proc */
	ClearTile_Station,					/* clear_tile_proc */
	GetAcceptedCargo_Station,		/* get_accepted_cargo_proc */
	GetTileDesc_Station,				/* get_tile_desc_proc */
	GetTileTrackStatus_Station,	/* get_tile_track_status_proc */
	ClickTile_Station,					/* click_tile_proc */
	AnimateTile_Station,				/* animate_tile_proc */
	TileLoop_Station,						/* tile_loop_clear */
	ChangeTileOwner_Station,		/* change_tile_owner_clear */
	NULL,												/* get_produced_cargo_proc */
	VehicleEnter_Station,				/* vehicle_enter_tile_proc */
	NULL,												/* vehicle_leave_tile_proc */
	GetSlopeTileh_Station,			/* get_slope_tileh_proc */
};


static const byte _station_desc[] = {
	SLE_VAR(Station,xy,							SLE_UINT16),
	SLE_VAR(Station,bus_tile,				SLE_UINT16),
	SLE_VAR(Station,lorry_tile,			SLE_UINT16),
	SLE_VAR(Station,train_tile,			SLE_UINT16),
	SLE_VAR(Station,airport_tile,		SLE_UINT16),
	SLE_VAR(Station,dock_tile,			SLE_UINT16),
	SLE_REF(Station,town,						REF_TOWN),
	SLE_VAR(Station,trainst_w,			SLE_UINT8),
	SLE_CONDVAR(Station,trainst_h,	SLE_UINT8, 2, 255),

	// alpha_order was stored here in savegame format 0 - 3
	SLE_CONDARR(NullStruct,null,SLE_FILE_U8 | SLE_VAR_NULL, 1, 0, 3),

	SLE_VAR(Station,string_id,			SLE_STRINGID),
	SLE_VAR(Station,had_vehicle_of_type,SLE_UINT16),

	SLE_VAR(Station,time_since_load,		SLE_UINT8),
	SLE_VAR(Station,time_since_unload,	SLE_UINT8),
	SLE_VAR(Station,delete_ctr,					SLE_UINT8),
	SLE_VAR(Station,owner,							SLE_UINT8),
	SLE_VAR(Station,facilities,					SLE_UINT8),
	SLE_VAR(Station,airport_type,				SLE_UINT8),
	SLE_VAR(Station,truck_stop_status,	SLE_UINT8),
	SLE_VAR(Station,bus_stop_status,		SLE_UINT8),

	// blocked_months was stored here in savegame format 0 - 4.0
	SLE_CONDVAR(Station,blocked_months_obsolete,	SLE_UINT8, 0, 4),

	SLE_CONDVAR(Station,airport_flags,			SLE_VAR_U32 | SLE_FILE_U16, 0, 2),
	SLE_CONDVAR(Station,airport_flags,			SLE_UINT32, 3, 255),

	SLE_VAR(Station,last_vehicle,				SLE_UINT16),

	SLE_CONDVAR(Station,class_id,				SLE_UINT8, 3, 255),
	SLE_CONDVAR(Station,stat_id,				SLE_UINT8, 3, 255),
	SLE_CONDVAR(Station,build_date,			SLE_UINT16, 3, 255),

	// reserve extra space in savegame here. (currently 32 bytes)
	SLE_CONDARR(NullStruct,null,SLE_FILE_U8 | SLE_VAR_NULL, 32, 2, 255),

	SLE_END()
};

static const byte _goods_desc[] = {
	SLE_VAR(GoodsEntry,waiting_acceptance,SLE_UINT16),
	SLE_VAR(GoodsEntry,days_since_pickup,	SLE_UINT8),
	SLE_VAR(GoodsEntry,rating,						SLE_UINT8),
	SLE_VAR(GoodsEntry,enroute_from,			SLE_UINT8),
	SLE_VAR(GoodsEntry,enroute_time,			SLE_UINT8),
	SLE_VAR(GoodsEntry,last_speed,				SLE_UINT8),
	SLE_VAR(GoodsEntry,last_age,					SLE_UINT8),

	SLE_END()
};


static void SaveLoad_STNS(Station *st)
{
	int i;
	SlObject(st, _station_desc);
	for(i=0; i!=NUM_CARGO; i++)
		SlObject(&st->goods[i], _goods_desc);
}

static void Save_STNS()
{
	Station *st;
	// Write the vehicles
	FOR_ALL_STATIONS(st) {
		if (st->xy != 0) {
			SlSetArrayIndex(st->index);
			SlAutolength((AutolengthProc*)SaveLoad_STNS, st);
		}
	}
}

static void Load_STNS()
{
	int index;
	while ((index = SlIterateArray()) != -1) {
		Station *st = &_stations[index];
		SaveLoad_STNS(st);

		// this means it's an oldstyle savegame without support for nonuniform stations
		if (st->train_tile && st->trainst_h == 0) {
			int w = st->trainst_w >> 4;
			int h = st->trainst_w & 0xF;
			if (_map5[st->train_tile]&1) intswap(w,h);
			st->trainst_w = w;
			st->trainst_h = h;
		}
	}
}

const ChunkHandler _station_chunk_handlers[] = {
	{ 'STNS', Save_STNS, Load_STNS, CH_ARRAY | CH_LAST},
};