summaryrefslogtreecommitdiff
path: root/src/station_cmd.cpp
blob: a2bd618d2b0e53462caa6f85ee710b49f3f63948 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
/* $Id$ */

/** @file station_cmd.cpp Handling of station tiles. */

#include "stdafx.h"
#include "openttd.h"
#include "aircraft.h"
#include "bridge_map.h"
#include "cmd_helper.h"
#include "debug.h"
#include "tile_cmd.h"
#include "landscape.h"
#include "station_map.h"
#include "viewport_func.h"
#include "command_func.h"
#include "town.h"
#include "news_func.h"
#include "saveload.h"
#include "airport.h"
#include "sprite.h"
#include "train.h"
#include "roadveh.h"
#include "water_map.h"
#include "industry_map.h"
#include "newgrf_callbacks.h"
#include "newgrf_station.h"
#include "yapf/yapf.h"
#include "road_type.h"
#include "road_internal.h" /* For drawing catenary/checking road removal */
#include "cargotype.h"
#include "variables.h"
#include "autoslope.h"
#include "transparency.h"
#include "water.h"
#include "station_gui.h"
#include "strings_func.h"
#include "functions.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "signal_func.h"
#include "oldpool_func.h"
#include "animated_tile_func.h"

#include "table/sprites.h"
#include "table/strings.h"

DEFINE_OLD_POOL_GENERIC(Station, Station)
DEFINE_OLD_POOL_GENERIC(RoadStop, RoadStop)


/**
 * Check whether the given tile is a hangar.
 * @param t the tile to of whether it is a hangar.
 * @pre IsTileType(t, MP_STATION)
 * @return true if and only if the tile is a hangar.
 */
bool IsHangar(TileIndex t)
{
	assert(IsTileType(t, MP_STATION));

	const Station *st = GetStationByTile(t);
	const AirportFTAClass *apc = st->Airport();

	for (uint i = 0; i < apc->nof_depots; i++) {
		if (st->airport_tile + ToTileIndexDiff(apc->airport_depots[i]) == t) return true;
	}

	return false;
}

RoadStop *GetRoadStopByTile(TileIndex tile, RoadStopType type)
{
	const Station *st = GetStationByTile(tile);

	for (RoadStop *rs = st->GetPrimaryRoadStop(type);; rs = rs->next) {
		if (rs->xy == tile) return rs;
		assert(rs->next != NULL);
	}
}


static uint GetNumRoadStopsInStation(const Station *st, RoadStopType type)
{
	uint num = 0;

	assert(st != NULL);
	for (const RoadStop *rs = st->GetPrimaryRoadStop(type); rs != NULL; rs = rs->next) {
		num++;
	}

	return num;
}


/** Calculate the radius of the station. Basicly it is the biggest
 *  radius that is available within the station
 * @param st Station to query
 * @return the so calculated radius
 */
static uint FindCatchmentRadius(const Station *st)
{
	uint ret = CA_NONE;

	if (st->bus_stops   != NULL) ret = max<uint>(ret, CA_BUS);
	if (st->truck_stops != NULL) ret = max<uint>(ret, CA_TRUCK);
	if (st->train_tile  != 0)    ret = max<uint>(ret, CA_TRAIN);
	if (st->dock_tile   != 0)    ret = max<uint>(ret, CA_DOCK);
	if (st->airport_tile)        ret = max<uint>(ret, st->Airport()->catchment);

	return ret;
}

#define CHECK_STATIONS_ERR ((Station*)-1)

static Station *GetStationAround(TileIndex tile, int w, int h, StationID closest_station)
{
	/* check around to see if there's any stations there */
	BEGIN_TILE_LOOP(tile_cur, w + 2, h + 2, tile - TileDiffXY(1, 1))
		if (IsTileType(tile_cur, MP_STATION)) {
			StationID t = GetStationIndex(tile_cur);

			if (closest_station == INVALID_STATION) {
				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 - TileDiffXY(1, 1))
	return (closest_station == INVALID_STATION) ? NULL : GetStation(closest_station);
}

/**
 * Function to check whether the given tile matches some criterion.
 * @param tile the tile to check
 * @return true if it matches, false otherwise
 */
typedef bool (*CMSAMatcher)(TileIndex tile);

/**
 * Counts the numbers of tiles matching a specific type in the area around
 * @param tile the center tile of the 'count area'
 * @param type the type of tile searched for
 * @param industry when type == MP_INDUSTRY, the type of the industry,
 *                 in all other cases this parameter is ignored
 * @return the result the noumber of matching tiles around
 */
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
{
	int num = 0;

	for (int dx = -3; dx <= 3; dx++) {
		for (int dy = -3; dy <= 3; dy++) {
			if (cmp(TILE_MASK(tile + TileDiffXY(dx, dy)))) num++;
		}
	}

	return num;
}

/**
 * Check whether the tile is a mine.
 * @param tile the tile to investigate.
 * @return true if and only if the tile is a mine
 */
static bool CMSAMine(TileIndex tile)
{
	/* No industry */
	if (!IsTileType(tile, MP_INDUSTRY)) return false;

	const Industry *ind = GetIndustryByTile(tile);

	/* No extractive industry */
	if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;

	for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
		/* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine */
		if (ind->produced_cargo[i] != CT_INVALID && (GetCargo(ind->produced_cargo[i])->classes & CC_LIQUID) == 0) return true;
	}

	return false;
}

/**
 * Check whether the tile is water.
 * @param tile the tile to investigate.
 * @return true if and only if the tile is a mine
 */
static bool CMSAWater(TileIndex tile)
{
	return IsTileType(tile, MP_WATER) && IsWater(tile);
}

/**
 * Check whether the tile is a tree.
 * @param tile the tile to investigate.
 * @return true if and only if the tile is a mine
 */
static bool CMSATree(TileIndex tile)
{
	return IsTileType(tile, MP_TREES);
}

/**
 * Check whether the tile is a forest.
 * @param tile the tile to investigate.
 * @return true if and only if the tile is a mine
 */
static bool CMSAForest(TileIndex tile)
{
	/* No industry */
	if (!IsTileType(tile, MP_INDUSTRY)) return false;

	const Industry *ind = GetIndustryByTile(tile);

	/* No extractive industry */
	if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;

	for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
		/* The industry produces wood. */
		if (ind->produced_cargo[i] != CT_INVALID && GetCargo(ind->produced_cargo[i])->label == 'WOOD') return true;
	}

	return false;
}

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

enum StationNaming {
	STATIONNAMING_RAIL = 0,
	STATIONNAMING_ROAD = 0,
	STATIONNAMING_AIRPORT,
	STATIONNAMING_OILRIG,
	STATIONNAMING_DOCK,
	STATIONNAMING_BUOY,
	STATIONNAMING_HELIPORT,
};

static StringID GenerateStationName(Station *st, TileIndex 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 */
	};

	const Town *t = st->town;
	uint32 free_names = UINT32_MAX;

	const Station *s;
	FOR_ALL_STATIONS(s) {
		if (s != st && 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 */
	uint32 tmp = free_names & _gen_station_name_bits[flag];
	if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);

	/* check mine? */
	if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
		if (CountMapSquareAround(tile, CMSAMine) >= 2) {
			return STR_SV_STNAME_MINES;
		}
	}

	/* check close enough to town to get central as name? */
	if (DistanceMax(tile, t->xy) < 8) {
		if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;

		if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
	}

	/* Check lakeside */
	if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
			DistanceFromEdge(tile) < 20 &&
			CountMapSquareAround(tile, CMSAWater) >= 5) {
		return STR_SV_STNAME_LAKESIDE;
	}

	/* Check woods */
	if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
				CountMapSquareAround(tile, CMSATree) >= 8 ||
				CountMapSquareAround(tile, CMSAForest) >= 2)
			) {
		return _opt.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
	}

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

	/* 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[
		(TileX(tile) < TileX(t->xy)) +
		(TileY(tile) < TileY(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));
	return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
}
#undef M

static Station *GetClosestStationFromTile(TileIndex tile)
{
	uint threshold = 8;
	Station *best_station = NULL;
	Station *st;

	FOR_ALL_STATIONS(st) {
		if (st->facilities == 0 && st->owner == _current_player) {
			uint cur_dist = DistanceManhattan(tile, st->xy);

			if (cur_dist < threshold) {
				threshold = cur_dist;
				best_station = st;
			}
		}
	}

	return best_station;
}

/** Update the virtual coords needed to draw the station sign.
 * @param st Station to update for.
 */
static void UpdateStationVirtCoord(Station *st)
{
	Point pt = RemapCoords2(TileX(st->xy) * TILE_SIZE, TileY(st->xy) * TILE_SIZE);

	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) {
		UpdateStationVirtCoord(st);
	}
}

/**
 * Update the station virt coords while making the modified parts dirty.
 *
 * This function updates the virt coords and mark the modified parts as dirty
 *
 * @param st The station to update the virt coords
 * @ingroup dirty
 */
static void UpdateStationVirtCoordDirty(Station *st)
{
	st->MarkDirty();
	UpdateStationVirtCoord(st);
	st->MarkDirty();
}

/** Get a mask of the cargo types that the station accepts.
 * @param st Station to query
 * @return the expected mask
 */
static uint GetAcceptanceMask(const Station *st)
{
	uint mask = 0;

	for (CargoID i = 0; i < NUM_CARGO; i++) {
		if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) mask |= 1 << i;
	}
	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(const Station *st, uint num_items, CargoID *cargo, StringID msg)
{
	for (uint i = 0; i < num_items; i++) {
		SetDParam(i + 1, GetCargo(cargo[i])->name);
	}

	SetDParam(0, st->index);
	AddNewsItem(msg, NM_SMALL, NF_VIEWPORT | NF_TILE, NT_ACCEPTANCE, DNC_NONE, st->xy, 0);
}

/**
 * Get a list of the cargo types being produced around the tile (in a rectangle).
 * @param produced: Destination array of produced cargo
 * @param tile: Center of the search area
 * @param w: Width of the center
 * @param h: Height of the center
 * @param rad: Radius of the search area
 */
void GetProductionAroundTiles(AcceptedCargo produced, TileIndex tile,
	int w, int h, int rad)
{
	memset(produced, 0, sizeof(AcceptedCargo));

	int x = TileX(tile);
	int y = TileY(tile);

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

	int y2 = min(y + h + rad, MapSizeY());
	int y1 = max(y - rad, 0);

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

	for (int yc = y1; yc != y2; yc++) {
		for (int xc = x1; xc != x2; xc++) {
			TileIndex tile = TileXY(xc, yc);

			if (!IsTileType(tile, MP_STATION)) {
				GetProducedCargoProc *gpc = _tile_type_procs[GetTileType(tile)]->get_produced_cargo_proc;
				if (gpc != NULL) {
					CargoID cargos[256]; // Required for CBID_HOUSE_PRODUCE_CARGO.
					memset(cargos, CT_INVALID, 256);

					gpc(tile, cargos);
					for (uint i = 0; i < lengthof(cargos); ++i) {
						if (cargos[i] != CT_INVALID) produced[cargos[i]]++;
					}
				}
			}
		}
	}
}

/**
 * Get a list of the cargo types that are accepted around the tile.
 * @param accepts: Destination array of accepted cargo
 * @param tile: Center of the search area
 * @param w: Width of the center
 * @param h: Height of the center
 * @param rad: Radius of the rectangular search area
 */
void GetAcceptanceAroundTiles(AcceptedCargo accepts, TileIndex tile,
	int w, int h, int rad)
{
	memset(accepts, 0, sizeof(AcceptedCargo));

	int x = TileX(tile);
	int y = TileY(tile);

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

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

	for (int yc = y1; yc != y2; yc++) {
		for (int xc = x1; xc != x2; xc++) {
			TileIndex tile = TileXY(xc, yc);

			if (!IsTileType(tile, MP_STATION)) {
				AcceptedCargo ac;

				GetAcceptedCargo(tile, ac);
				for (uint i = 0; i < lengthof(ac); ++i) accepts[i] += ac[i];
			}
		}
	}
}

static inline void MergePoint(Rect *rect, TileIndex tile)
{
	int x = TileX(tile);
	int y = TileY(tile);

	if (rect->left   > x) rect->left   = x;
	if (rect->bottom > y) rect->bottom = y;
	if (rect->right  < x) rect->right  = x;
	if (rect->top    < y) rect->top    = y;
}

/** Update the acceptance for a station.
 * @param st Station to update
 * @param show_msg controls whether to display a message that acceptance was changed.
 */
static void UpdateStationAcceptance(Station *st, bool show_msg)
{
	/* Don't update acceptance for a buoy */
	if (st->IsBuoy()) return;

	Rect rect;
	rect.left   = MapSizeX();
	rect.bottom = MapSizeY();
	rect.right  = 0;
	rect.top    = 0;

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

	/* Put all the tiles that span an area in the table. */
	if (st->train_tile != 0) {
		MergePoint(&rect, st->train_tile);
		MergePoint(&rect, st->train_tile + TileDiffXY(st->trainst_w - 1, st->trainst_h - 1));
	}

	if (st->airport_tile != 0) {
		const AirportFTAClass *afc = st->Airport();

		MergePoint(&rect, st->airport_tile);
		MergePoint(&rect, st->airport_tile + TileDiffXY(afc->size_x - 1, afc->size_y - 1));
	}

	if (st->dock_tile != 0) MergePoint(&rect, st->dock_tile);

	for (const RoadStop *rs = st->bus_stops; rs != NULL; rs = rs->next) {
		MergePoint(&rect, rs->xy);
	}

	for (const RoadStop *rs = st->truck_stops; rs != NULL; rs = rs->next) {
		MergePoint(&rect, rs->xy);
	}

	/* And retrieve the acceptance. */
	AcceptedCargo accepts;
	if (rect.right >= rect.left) {
		GetAcceptanceAroundTiles(
			accepts,
			TileXY(rect.left, rect.bottom),
			rect.right - rect.left   + 1,
			rect.top   - rect.bottom + 1,
			_patches.modified_catchment ? FindCatchmentRadius(st) : (uint)CA_UNMODIFIED
		);
	} else {
		memset(accepts, 0, sizeof(accepts));
	}

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

		/* Make sure the station can accept the goods type. */
		bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
		if ((!is_passengers && !(st->facilities & (byte)~FACIL_BUS_STOP)) ||
				(is_passengers && !(st->facilities & (byte)~FACIL_TRUCK_STOP))) {
			amt = 0;
		}

		SB(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, amt >= 8);
	}

	/* Only show a message in case the acceptance was actually changed. */
	uint 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) {
		/* List of accept and reject strings for different number of
		 * cargo types */
		static const StringID accept_msg[] = {
			STR_3040_NOW_ACCEPTS,
			STR_3041_NOW_ACCEPTS_AND,
		};
		static const StringID reject_msg[] = {
			STR_303E_NO_LONGER_ACCEPTS,
			STR_303F_NO_LONGER_ACCEPTS_OR,
		};

		/* Array of accepted and rejected cargo types */
		CargoID accepts[2] = { CT_INVALID, CT_INVALID };
		CargoID rejects[2] = { CT_INVALID, CT_INVALID };
		uint num_acc = 0;
		uint num_rej = 0;

		/* Test each cargo type to see if its acceptange has changed */
		for (CargoID i = 0; i < NUM_CARGO; i++) {
			if (HasBit(new_acc, i)) {
				if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
					/* New cargo is accepted */
					accepts[num_acc++] = i;
				}
			} else {
				if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
					/* Old cargo is no longer accepted */
					rejects[num_rej++] = i;
				}
			}
		}

		/* Show news message if there are any changes */
		if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
		if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
	}

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

static void UpdateStationSignCoord(Station *st)
{
	const StationRect *r = &st->rect;

	if (r->IsEmpty()) return; /* no tiles belong to this station */

	/* clamp sign coord to be inside the station rect */
	st->xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
	UpdateStationVirtCoordDirty(st);
}

/** 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.
 * @param st Station
 */
static void DeleteStationIfEmpty(Station *st)
{
	if (st->facilities == 0) {
		st->delete_ctr = 0;
		RebuildStationLists();
		InvalidateWindow(WC_STATION_LIST, st->owner);
	}
	/* station remains but it probably lost some parts - station sign should stay in the station boundaries */
	UpdateStationSignCoord(st);
}

static CommandCost ClearTile_Station(TileIndex tile, byte flags);

/** Tries to clear the given area.
 * @param tile TileIndex to start check
 * @param w width of search area
 * @param h height of search area
 * @param flags operation to perform
 * @param invalid_dirs prohibited directions (set of DiagDirections)
 * @param station StationID to be queried and returned if available
 * @param check_clear if clearing tile should be performed (in wich case, cost will be added)
 * @return the cost in case of success, or an error code if it failed.
 */
CommandCost CheckFlatLandBelow(TileIndex tile, uint w, uint h, uint flags, uint invalid_dirs, StationID *station, bool check_clear = true)
{
	CommandCost cost(EXPENSES_CONSTRUCTION);
	int allowed_z = -1;

	BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
		if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) {
			return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
		}

		if (!EnsureNoVehicleOnGround(tile_cur)) return CMD_ERROR;

		uint z;
		Slope tileh = GetTileSlope(tile_cur, &z);

		/* Prohibit building if
		 *   1) The tile is "steep" (i.e. stretches two height levels)
		 * -OR-
		 *   2) The tile is non-flat if
		 *     a) the player building is an "old-school" AI
		 *   -OR-
		 *     b) the build_on_slopes switch is disabled
		 */
		if (IsSteepSlope(tileh) ||
				((_is_old_ai_player || !_patches.build_on_slopes) && tileh != SLOPE_FLAT)) {
			return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
		}

		int flat_z = z;
		if (tileh != SLOPE_FLAT) {
			/* need to check so the entrance to the station is not pointing at a slope.
			 * This must be valid for all station tiles, as the user can remove single station tiles. */
			if ((HasBit(invalid_dirs, DIAGDIR_NE) && !(tileh & SLOPE_NE)) ||
			    (HasBit(invalid_dirs, DIAGDIR_SE) && !(tileh & SLOPE_SE)) ||
			    (HasBit(invalid_dirs, DIAGDIR_SW) && !(tileh & SLOPE_SW)) ||
			    (HasBit(invalid_dirs, DIAGDIR_NW) && !(tileh & SLOPE_NW))) {
				return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
			}
			cost.AddCost(_price.terraform);
			flat_z += TILE_HEIGHT;
		}

		/* 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) {
			return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
		}

		/* if station is set, then we have special handling to allow building on top of already existing stations.
		 * so station points to INVALID_STATION 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 != NULL && IsTileType(tile_cur, MP_STATION)) {
			if (!IsRailwayStation(tile_cur)) {
				return ClearTile_Station(tile_cur, DC_AUTO); // get error message
			} else {
				StationID st = GetStationIndex(tile_cur);
				if (*station == INVALID_STATION) {
					*station = st;
				} else if (*station != st) {
					return_cmd_error(STR_3006_ADJOINS_MORE_THAN_ONE_EXISTING);
				}
			}
		} else if (check_clear) {
			CommandCost ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
			if (CmdFailed(ret)) return ret;
			cost.AddCost(ret);
		}
	} END_TILE_LOOP(tile_cur, w, h, tile)

	return cost;
}

static bool CanExpandRailroadStation(const Station *st, uint *fin, Axis axis)
{
	uint curw = st->trainst_w;
	uint curh = st->trainst_h;
	TileIndex 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(TileX(st->train_tile), TileX(tile));
		int y = min(TileY(st->train_tile), TileY(tile));
		curw = max(TileX(st->train_tile) + curw, TileX(tile) + w) - x;
		curh = max(TileY(st->train_tile) + curh, TileY(tile) + h) - y;
		tile = TileXY(x, y);
	} else {
		/* do not allow modifying non-uniform stations,
		 * the uniform-stations code wouldn't handle it well */
		BEGIN_TILE_LOOP(t, st->trainst_w, st->trainst_h, st->train_tile)
			if (!st->TileBelongsToRailStation(t)) { // there may be adjoined station
				_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
				return false;
			}
		END_TILE_LOOP(t, st->trainst_w, st->trainst_h, st->train_tile)

		/* check so the orientation is the same */
		if (GetRailStationAxis(st->train_tile) != axis) {
			_error_message = STR_NONUNIFORM_STATIONS_DISALLOWED;
			return false;
		}

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

static void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec)
{
	if (statspec != NULL && statspec->lengths >= plat_len &&
			statspec->platforms[plat_len - 1] >= numtracks &&
			statspec->layouts[plat_len - 1][numtracks - 1]) {
		/* Custom layout defined, follow it. */
		memcpy(layout, statspec->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
 * @param tile_org starting position of station dragging/placement
 * @param flags operation to perform
 * @param p1 various bitstuffed elements
 * - p1 = (bit  0)    - orientation (Axis)
 * - p1 = (bit  8-15) - number of tracks
 * - p1 = (bit 16-23) - platform length
 * - p1 = (bit 24)    - allow stations directly adjacent to other stations.
 * @param p2 various bitstuffed elements
 * - p2 = (bit  0- 3) - railtype (p2 & 0xF)
 * - p2 = (bit  8-15) - custom station class
 * - p2 = (bit 16-23) - custom station id
 */
CommandCost CmdBuildRailroadStation(TileIndex tile_org, uint32 flags, uint32 p1, uint32 p2)
{
	/* Does the authority allow this? */
	if (!(flags & DC_NO_TOWN_RATING) && !CheckIfAuthorityAllows(tile_org)) return CMD_ERROR;
	if (!ValParamRailtype((RailType)(p2 & 0xF))) return CMD_ERROR;

	/* unpack parameters */
	Axis axis = Extract<Axis, 0>(p1);
	uint numtracks = GB(p1,  8, 8);
	uint plat_len  = GB(p1, 16, 8);

	int w_org, h_org;
	if (axis == AXIS_X) {
		w_org = plat_len;
		h_org = numtracks;
	} else {
		h_org = plat_len;
		w_org = numtracks;
	}

	if (h_org > _patches.station_spread || w_org > _patches.station_spread) return CMD_ERROR;

	/* these values are those that will be stored in train_tile and station_platforms */
	uint finalvalues[3];
	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) */
	StationID est = INVALID_STATION;
	/* 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 */
	CommandCost ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags & ~DC_EXEC, 5 << axis, _patches.nonuniform_stations ? &est : NULL);
	if (CmdFailed(ret)) return ret;
	CommandCost cost(EXPENSES_CONSTRUCTION, ret.GetCost() + (numtracks * _price.train_station_track + _price.train_station_length) * plat_len);

	Station *st = NULL;
	bool check_surrounding = true;

	if (_patches.adjacent_stations) {
		if (est != INVALID_STATION) {
			if (HasBit(p1, 24)) {
				/* You can't build an adjacent station over the top of one that
				 * already exists. */
				return_cmd_error(STR_MUST_REMOVE_RAILWAY_STATION_FIRST);
			} else {
				/* Extend the current station, and don't check whether it will
				 * be near any other stations. */
				st = GetStation(est);
				check_surrounding = false;
			}
		} else {
			/* There's no station here. Don't check the tiles surrounding this
			 * one if the player wanted to build an adjacent station. */
			if (HasBit(p1, 24)) check_surrounding = false;
		}
	}

	if (check_surrounding) {
		/* 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);

	if (st != NULL) {
		/* Reuse an existing station. */
		if (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 (_is_old_ai_player || !_patches.join_stations)
				return_cmd_error(STR_3005_TOO_CLOSE_TO_ANOTHER_RAILROAD);
			if (!CanExpandRailroadStation(st, finalvalues, axis))
				return CMD_ERROR;
		}

		/* XXX can't we pack this in the "else" part of the if above? */
		if (!st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TEST)) return CMD_ERROR;
	} else {
		/* allocate and initialize new station */
		if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);

		if (flags & DC_EXEC) {
			st = new Station(tile_org);

			st->town = ClosestTownFromTile(tile_org, UINT_MAX);
			st->string_id = GenerateStationName(st, tile_org, STATIONNAMING_RAIL);

			if (IsValidPlayer(_current_player)) {
				SetBit(st->town->have_ratings, _current_player);
			}
		}
	}

	/* Check if the given station class is valid */
	if (GB(p2, 8, 8) >= GetNumStationClasses()) return CMD_ERROR;

	/* Check if we can allocate a custom stationspec to this station */
	const StationSpec *statspec = GetCustomStationSpec((StationClassID)GB(p2, 8, 8), GB(p2, 16, 8));
	int specindex = AllocateSpecToStation(statspec, st, flags & DC_EXEC);
	if (specindex == -1) return CMD_ERROR;

	if (statspec != NULL) {
		/* Perform NewStation checks */

		/* Check if the station size is permitted */
		if (HasBit(statspec->disallowed_platforms, numtracks - 1) || HasBit(statspec->disallowed_lengths, plat_len - 1)) {
			return CMD_ERROR;
		}

		/* Check if the station is buildable */
		if (HasBit(statspec->callbackmask, CBM_STATION_AVAIL) && GB(GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, NULL, INVALID_TILE), 0, 8) == 0) {
			return CMD_ERROR;
		}
	}

	if (flags & DC_EXEC) {
		TileIndexDiff tile_delta;
		byte *layout_ptr;
		byte numtracks_orig;
		Track track;

		/* 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) */
		ret = CheckFlatLandBelow(tile_org, w_org, h_org, flags, 5 << axis, _patches.nonuniform_stations ? &est : NULL);
		if (CmdFailed(ret)) return ret;

		st->train_tile = finalvalues[0];
		st->AddFacility(FACIL_TRAIN, finalvalues[0]);

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

		st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);

		if (statspec != NULL) {
			/* Include this station spec's animation trigger bitmask
			 * in the station's cached copy. */
			st->cached_anim_triggers |= statspec->anim_triggers;
		}

		tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
		track = AxisToTrack(axis);

		layout_ptr = (byte*)alloca(numtracks * plat_len);
		GetStationLayout(layout_ptr, numtracks, plat_len, statspec);

		numtracks_orig = numtracks;

		do {
			TileIndex tile = tile_org;
			int w = plat_len;
			do {
				byte layout = *layout_ptr++;
				MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, (RailType)GB(p2, 0, 4));
				SetCustomStationSpecIndex(tile, specindex);
				SetStationTileRandomBits(tile, GB(Random(), 0, 4));
				SetStationAnimationFrame(tile, 0);

				if (statspec != NULL) {
					/* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
					uint32 platinfo = GetPlatformInfo(AXIS_X, 0, plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);

					/* As the station is not yet completely finished, the station does not yet exist. */
					uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, NULL, tile);
					if (callback != CALLBACK_FAILED && callback < 8) SetStationGfx(tile, (callback & ~1) + axis);

					/* Trigger station animation -- after building? */
					StationAnimationTrigger(st, tile, STAT_ANIM_BUILT);
				}

				tile += tile_delta;
			} while (--w);
			AddTrackToSignalBuffer(tile_org, track, _current_player);
			YapfNotifyTrackLayoutChange(tile_org, track);
			tile_org += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
		} while (--numtracks);

		st->MarkTilesDirty(false);
		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		RebuildStationLists();
		InvalidateWindow(WC_STATION_LIST, st->owner);
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
	}

	return cost;
}

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

restart:

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

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

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

		/* check the lower side, y = constant, x changes */
		for (uint i = 0; !st->TileBelongsToRailStation(tile + TileDiffXY(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.
 * This allows for custom-built station with holes and weird layouts
 * @param tile tile of station piece to remove
 * @param flags operation to perform
 * @param p1 start_tile
 * @param p2 unused
 */
CommandCost CmdRemoveFromRailroadStation(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{
	TileIndex start = p1 == 0 ? tile : p1;

	/* Count of the number of tiles removed */
	int quantity = 0;

	if (tile >= MapSize() || start >= MapSize()) return CMD_ERROR;

	/* make sure sx,sy are smaller than ex,ey */
	int ex = TileX(tile);
	int ey = TileY(tile);
	int sx = TileX(start);
	int sy = TileY(start);
	if (ex < sx) Swap(ex, sx);
	if (ey < sy) Swap(ey, sy);
	tile = TileXY(sx, sy);

	int size_x = ex - sx + 1;
	int size_y = ey - sy + 1;

	/* Do the action for every tile into the area */
	BEGIN_TILE_LOOP(tile2, size_x, size_y, tile) {
		/* Make sure the specified tile is a railroad station */
		if (!IsTileType(tile2, MP_STATION) || !IsRailwayStation(tile2)) {
			continue;
		}

		/* If there is a vehicle on ground, do not allow to remove (flood) the tile */
		if (!EnsureNoVehicleOnGround(tile2)) {
			continue;
		}

		/* Check ownership of station */
		Station *st = GetStationByTile(tile2);
		if (_current_player != OWNER_WATER && !CheckOwnership(st->owner)) {
			continue;
		}

		/* Do not allow removing from stations if non-uniform stations are not enabled
		 * The check must be here to give correct error message
		 */
		if (!_patches.nonuniform_stations) return_cmd_error(STR_NONUNIFORM_STATIONS_DISALLOWED);

		/* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
		quantity++;

		if (flags & DC_EXEC) {
			/* read variables before the station tile is removed */
			uint specindex = GetCustomStationSpecIndex(tile2);
			Track track = GetRailStationTrack(tile2);
			Owner owner = GetTileOwner(tile2);

			DoClearSquare(tile2);
			st->rect.AfterRemoveTile(st, tile2);
			AddTrackToSignalBuffer(tile2, track, owner);
			YapfNotifyTrackLayoutChange(tile2, track);

			DeallocateSpecFromStation(st, specindex);

			/* 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);
			st->MarkTilesDirty(false);
			UpdateStationSignCoord(st);

			/* if we deleted the whole station, delete the train facility. */
			if (st->train_tile == 0) {
				st->facilities &= ~FACIL_TRAIN;
				InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
				UpdateStationVirtCoordDirty(st);
				DeleteStationIfEmpty(st);
			}
		}
	} END_TILE_LOOP(tile2, size_x, size_y, tile)

	/* If we've not removed any tiles, give an error */
	if (quantity == 0) return CMD_ERROR;

	return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_rail_station * quantity);
}


static CommandCost RemoveRailroadStation(Station *st, TileIndex tile, uint32 flags)
{
	/* if there is flooding and non-uniform stations are enabled, remove platforms tile by tile */
	if (_current_player == OWNER_WATER && _patches.nonuniform_stations) {
		return DoCommand(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;
	int w = st->trainst_w;
	int h = st->trainst_h;

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

	CommandCost cost(EXPENSES_CONSTRUCTION);
	/* 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 (st->TileBelongsToRailStation(tile)) {
				if (!EnsureNoVehicleOnGround(tile))
					return CMD_ERROR;
				cost.AddCost(_price.remove_rail_station);
				if (flags & DC_EXEC) {
					/* read variables before the station tile is removed */
					Track track = GetRailStationTrack(tile);
					Owner owner = GetTileOwner(tile); // _current_player can be OWNER_WATER
					DoClearSquare(tile);
					AddTrackToSignalBuffer(tile, track, owner);
					YapfNotifyTrackLayoutChange(tile, track);
				}
			}
			tile += TileDiffXY(1, 0);
		} while (--w);
		w = w_bak;
		tile += TileDiffXY(-w, 1);
	} while (--h);

	if (flags & DC_EXEC) {
		st->rect.AfterRemoveRect(st, st->train_tile, st->trainst_w, st->trainst_h);

		st->train_tile = 0;
		st->trainst_w = st->trainst_h = 0;
		st->facilities &= ~FACIL_TRAIN;

		free(st->speclist);
		st->num_specs = 0;
		st->speclist  = NULL;
		st->cached_anim_triggers = 0;

		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_TRAINS);
		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return cost;
}

/**
 * @param truck_station Determines whether a stop is ROADSTOP_BUS or ROADSTOP_TRUCK
 * @param st The Station to do the whole procedure for
 * @return a pointer to where to link a new RoadStop*
 */
static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
{
	RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;

	if (*primary_stop == NULL) {
		/* we have no roadstop of the type yet, so write a "primary stop" */
		return primary_stop;
	} else {
		/* there are stops already, so append to the end of the list */
		RoadStop *stop = *primary_stop;
		while (stop->next != NULL) stop = stop->next;
		return &stop->next;
	}
}

/** Build a bus or truck stop
 * @param tile tile to build the stop at
 * @param flags operation to perform
 * @param p1 entrance direction (DiagDirection)
 * @param p2 bit 0: 0 for Bus stops, 1 for truck stops
 *           bit 1: 0 for normal, 1 for drive-through
 *           bit 2..4: the roadtypes
 *           bit 5: allow stations directly adjacent to other stations.
 */
CommandCost CmdBuildRoadStop(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{
	bool type = HasBit(p2, 0);
	bool is_drive_through = HasBit(p2, 1);
	bool build_over_road  = is_drive_through && IsNormalRoadTile(tile);
	bool town_owned_road  = build_over_road && IsTileOwner(tile, OWNER_TOWN);
	RoadTypes rts = (RoadTypes)GB(p2, 2, 3);

	if (!AreValidRoadTypes(rts) || !HasRoadTypesAvail(_current_player, rts)) return CMD_ERROR;

	/* Trams only have drive through stops */
	if (!is_drive_through && HasBit(rts, ROADTYPE_TRAM)) return CMD_ERROR;

	/* Saveguard the parameters */
	if (!IsValidDiagDirection((DiagDirection)p1)) return CMD_ERROR;
	/* If it is a drive-through stop check for valid axis */
	if (is_drive_through && !IsValidAxis((Axis)p1)) return CMD_ERROR;
	/* Road bits in the wrong direction */
	if (build_over_road && (GetAllRoadBits(tile) & ((Axis)p1 == AXIS_X ? ROAD_Y : ROAD_X)) != 0) return_cmd_error(STR_DRIVE_THROUGH_ERROR_DIRECTION);

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

	/* Not allowed to build over this road */
	if (build_over_road) {
		if (IsTileOwner(tile, OWNER_TOWN) && !_patches.road_stop_on_town_road) return_cmd_error(STR_DRIVE_THROUGH_ERROR_ON_TOWN_ROAD);

		RoadTypes cur_rts = GetRoadTypes(tile);

		/* there is a road, check if we can build road+tram stop over it */
		if (HasBit(cur_rts, ROADTYPE_ROAD)) {
			Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
			if (road_owner != OWNER_TOWN && road_owner != OWNER_NONE && !CheckOwnership(road_owner)) return CMD_ERROR;
		}

		/* there is a tram, check if we can build road+tram stop over it */
		if (HasBit(cur_rts, ROADTYPE_TRAM)) {
			Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
			if (tram_owner != OWNER_NONE && !CheckOwnership(tram_owner)) return CMD_ERROR;
		}

		/* Don't allow building the roadstop when vehicles are already driving on it */
		if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;

		/* Do not remove roadtypes! */
		rts |= cur_rts;
	}

	CommandCost cost = CheckFlatLandBelow(tile, 1, 1, flags, is_drive_through ? 5 << p1 : 1 << p1, NULL, !build_over_road);
	if (CmdFailed(cost)) return cost;

	Station *st = NULL;

	if (!_patches.adjacent_stations || !HasBit(p2, 5)) {
		st = GetStationAround(tile, 1, 1, INVALID_STATION);
		if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
	}

	/* Find a station close to us */
	if (st == NULL) st = GetClosestStationFromTile(tile);

	/* give us a road stop in the list, and check if something went wrong */
	if (!RoadStop::CanAllocateItem()) return_cmd_error(type ? STR_TOO_MANY_TRUCK_STOPS : STR_TOO_MANY_BUS_STOPS);

	if (st != NULL &&
			GetNumRoadStopsInStation(st, ROADSTOP_BUS) + GetNumRoadStopsInStation(st, ROADSTOP_TRUCK) >= RoadStop::LIMIT) {
		return_cmd_error(type ? STR_TOO_MANY_TRUCK_STOPS : STR_TOO_MANY_BUS_STOPS);
	}

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

		if (!st->rect.BeforeAddTile(tile, StationRect::ADD_TEST)) return CMD_ERROR;
	} else {
		/* allocate and initialize new station */
		if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);

		if (flags & DC_EXEC) {
			st = new Station(tile);

			st->town = ClosestTownFromTile(tile, UINT_MAX);
			st->string_id = GenerateStationName(st, tile, STATIONNAMING_ROAD);

			if (IsValidPlayer(_current_player)) {
				SetBit(st->town->have_ratings, _current_player);
			}
			st->sign.width_1 = 0;
		}
	}

	cost.AddCost((type) ? _price.build_truck_station : _price.build_bus_station);

	if (flags & DC_EXEC) {
		RoadStop *road_stop = new RoadStop(tile);
		/* Insert into linked list of RoadStops */
		RoadStop **currstop = FindRoadStopSpot(type, st);
		*currstop = road_stop;

		/*initialize an empty station */
		st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, tile);

		st->rect.BeforeAddTile(tile, StationRect::ADD_TRY);

		RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
		if (is_drive_through) {
			MakeDriveThroughRoadStop(tile, st->owner, st->index, rs_type, rts, (Axis)p1, town_owned_road);
		} else {
			MakeRoadStop(tile, st->owner, st->index, rs_type, rts, (DiagDirection)p1);
		}

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		RebuildStationLists();
		InvalidateWindow(WC_STATION_LIST, st->owner);
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
	}
	return cost;
}


static void *ClearRoadStopStatusEnum(Vehicle *v, void *)
{
	if (v->type == VEH_ROAD) ClrBit(v->u.road.state, RVS_IN_DT_ROAD_STOP);

	return NULL;
}


/** Remove a bus station
 * @param st Station to remove
 * @param flags operation to perform
 * @param tile TileIndex been queried
 * @return cost or failure of operation
 */
static CommandCost RemoveRoadStop(Station *st, uint32 flags, TileIndex tile)
{
	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner)) {
		return CMD_ERROR;
	}

	bool is_truck = IsTruckStop(tile);

	RoadStop **primary_stop;
	RoadStop *cur_stop;
	if (is_truck) { // truck stop
		primary_stop = &st->truck_stops;
		cur_stop = GetRoadStopByTile(tile, ROADSTOP_TRUCK);
	} else {
		primary_stop = &st->bus_stops;
		cur_stop = GetRoadStopByTile(tile, ROADSTOP_BUS);
	}

	assert(cur_stop != NULL);

	/* don't do the check for drive-through road stops when company bankrupts */
	if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
		/* remove the 'going through road stop' status from all vehicles on that tile */
		if (flags & DC_EXEC) VehicleFromPos(tile, NULL, &ClearRoadStopStatusEnum);
	} else {
		if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
	}

	if (flags & DC_EXEC) {
		if (*primary_stop == cur_stop) {
			/* removed the first stop in the list */
			*primary_stop = cur_stop->next;
			/* removed the only stop? */
			if (*primary_stop == NULL) {
				st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
			}
		} else {
			/* tell the predecessor in the list to skip this stop */
			RoadStop *pred = *primary_stop;
			while (pred->next != cur_stop) pred = pred->next;
			pred->next = cur_stop->next;
		}

		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
		delete cur_stop;
		DoClearSquare(tile);
		st->rect.AfterRemoveTile(st, tile);

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return CommandCost(EXPENSES_CONSTRUCTION, (is_truck) ? _price.remove_truck_station : _price.remove_bus_station);
}

/** Remove a bus or truck stop
 * @param tile tile to remove the stop from
 * @param flags operation to perform
 * @param p1 not used
 * @param p2 bit 0: 0 for Bus stops, 1 for truck stops
 */
CommandCost CmdRemoveRoadStop(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{
	/* Make sure the specified tile is a road stop of the correct type */
	if (!IsTileType(tile, MP_STATION) || !IsRoadStop(tile) || (uint32)GetRoadStopType(tile) != p2) return CMD_ERROR;
	Station *st = GetStationByTile(tile);
	/* Save the stop info before it is removed */
	bool is_drive_through = IsDriveThroughStopTile(tile);
	RoadTypes rts = GetRoadTypes(tile);
	RoadBits road_bits = IsDriveThroughStopTile(tile) ?
			((GetRoadStopDir(tile) == DIAGDIR_NE) ? ROAD_X : ROAD_Y) :
			DiagDirToRoadBits(GetRoadStopDir(tile));
	bool is_towns_road = is_drive_through && GetStopBuiltOnTownRoad(tile);

	CommandCost ret = RemoveRoadStop(st, flags, tile);

	/* If the stop was a drive-through stop replace the road */
	if ((flags & DC_EXEC) && CmdSucceeded(ret) && is_drive_through) {
		/* Rebuild the drive throuhg road stop. As a road stop can only be
		 * removed by the owner of the roadstop, _current_player is the
		 * owner of the road stop. */
		MakeRoadNormal(tile, road_bits, rts, is_towns_road ? ClosestTownFromTile(tile, UINT_MAX)->index : 0,
				is_towns_road ? OWNER_TOWN : _current_player, _current_player, _current_player);
	}

	return ret;
}

/* FIXME -- need to move to its corresponding Airport variable*/

/* Country Airfield (small) */
static const byte _airport_sections_country[] = {
	54, 53, 52, 65,
	58, 57, 56, 55,
	64, 63, 63, 62
};

/* City Airport (large) */
static const byte _airport_sections_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_sections_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_sections_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
};

/* Intercontinental Airport (vlarge) - 4 runways */
static const byte _airport_sections_intercontinental[] = {
	102, 120,  89,  89,  89,  89,  89,  89, 118,
	120,  23,  23,  23,  23,  23,  23, 119, 117,
	 87,  54,  87,   8,   8,   8,   8,  51, 117,
	 87, 162,  87,  85, 116, 116,   8,   9,  10,
	 87,   8,   8,  11,  31,  11,   8, 160,  32,
	 32, 160,   8,  11,  27,  11,   8,   8,  10,
	 87,   8,   8,  11,  30,  11,   8,   8,  10,
	 87, 142,   8,  11,  29,  11,  10, 163,  10,
	 87, 164,  87,   8,   8,   8,  10,  37, 117,
	 87, 120,  89,  89,  89,  89,  89,  89, 119,
	121,  23,  23,  23,  23,  23,  23, 119,  37
};


/* Commuter Airfield (small) */
static const byte _airport_sections_commuter[] = {
	85, 30, 115, 115, 32,
	87, 8,    8,   8, 10,
	87, 11,  11,  11, 10,
	26, 23,  23,  23, 26
};

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

/* Helidepot */
static const byte _airport_sections_helidepot[] = {
	124, 32,
	122, 123
};

/* Helistation */
static const byte _airport_sections_helistation[] = {
	 32, 134, 159, 158,
	161, 142, 142, 157
};

static const byte * const _airport_sections[] = {
	_airport_sections_country,           // Country Airfield (small)
	_airport_sections_town,              // City Airport (large)
	_airport_sections_heliport,          // Heliport
	_airport_sections_metropolitan,      // Metropolitain Airport (large)
	_airport_sections_international,     // International Airport (xlarge)
	_airport_sections_commuter,          // Commuter Airport (small)
	_airport_sections_helidepot,         // Helidepot
	_airport_sections_intercontinental,  // Intercontinental Airport (xxlarge)
	_airport_sections_helistation        // Helistation
};

/** Place an Airport.
 * @param tile tile where airport will be built
 * @param flags operation to perform
 * @param p1 airport type, @see airport.h
 * @param p2 (bit 0) - allow airports directly adjacent to other airports.
 */
CommandCost CmdBuildAirport(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{
	bool airport_upgrade = true;

	/* Check if a valid, buildable airport was chosen for construction */
	if (p1 > lengthof(_airport_sections) || !HasBit(GetValidAirports(), p1)) return CMD_ERROR;

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

	Town *t = ClosestTownFromTile(tile, UINT_MAX);
	const AirportFTAClass *afc = GetAirport(p1);
	int w = afc->size_x;
	int h = afc->size_y;
	Station *st = NULL;

	if (w > _patches.station_spread || h > _patches.station_spread) {
		_error_message = STR_306C_STATION_TOO_SPREAD_OUT;
		return CMD_ERROR;
	}

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

	/* Check if local auth refuses a new airport */
	uint num = 0;
	FOR_ALL_STATIONS(st) {
		if (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);
	}

	if (!_patches.adjacent_stations || !HasBit(p2, 0)) {
		st = GetStationAround(tile, w, h, INVALID_STATION);
		if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
	} else {
		st = NULL;
	}

	/* Find a station close to us */
	if (st == NULL) st = GetClosestStationFromTile(tile);

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

		if (!st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST)) return CMD_ERROR;

		if (st->airport_tile != 0) {
			return_cmd_error(STR_300D_TOO_CLOSE_TO_ANOTHER_AIRPORT);
		}
	} else {
		airport_upgrade = false;

		/* allocate and initialize new station */
		if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);

		if (flags & DC_EXEC) {
			st = new Station(tile);

			st->town = t;
			st->string_id = GenerateStationName(st, tile, !(afc->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);

			if (IsValidPlayer(_current_player)) {
				SetBit(st->town->have_ratings, _current_player);
			}
			st->sign.width_1 = 0;
		}
	}

	cost.AddCost(_price.build_airport * w * h);

	if (flags & DC_EXEC) {
		st->airport_tile = tile;
		st->AddFacility(FACIL_AIRPORT, tile);
		st->airport_type = (byte)p1;
		st->airport_flags = 0;

		st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);

		/* 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_sections[p1];

			BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
				MakeAirport(tile_cur, st->owner, st->index, *b - ((*b < 67) ? 8 : 24));
				b++;
			} END_TILE_LOOP(tile_cur, w, h, tile)
		}

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		RebuildStationLists();
		InvalidateWindow(WC_STATION_LIST, st->owner);
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_PLANES);
	}

	return cost;
}

static CommandCost RemoveAirport(Station *st, uint32 flags)
{
	if (_current_player != OWNER_WATER && !CheckOwnership(st->owner)) {
		return CMD_ERROR;
	}

	TileIndex tile = st->airport_tile;

	const AirportFTAClass *afc = st->Airport();
	int w = afc->size_x;
	int h = afc->size_y;

	CommandCost cost(EXPENSES_CONSTRUCTION, w * h * _price.remove_airport);

	const Vehicle *v;
	FOR_ALL_VEHICLES(v) {
		if (!(v->type == VEH_AIRCRAFT && IsNormalAircraft(v))) continue;

		if (v->u.air.targetairport == st->index && v->u.air.state != FLYING) return CMD_ERROR;
	}

	BEGIN_TILE_LOOP(tile_cur, w, h, tile) {
		if (!EnsureNoVehicleOnGround(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) {
		for (uint i = 0; i < afc->nof_depots; ++i) {
			DeleteWindowById(
				WC_VEHICLE_DEPOT, tile + ToTileIndexDiff(afc->airport_depots[i])
			);
		}

		st->rect.AfterRemoveRect(st, tile, w, h);

		st->airport_tile = 0;
		st->facilities &= ~FACIL_AIRPORT;

		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_PLANES);
		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return cost;
}

/** Build a buoy.
 * @param tile tile where to place the bouy
 * @param flags operation to perform
 * @param p1 unused
 * @param p2 unused
 */
CommandCost CmdBuildBuoy(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{
	if (!IsWaterTile(tile) || tile == 0) return_cmd_error(STR_304B_SITE_UNSUITABLE);
	if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);

	if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_304B_SITE_UNSUITABLE);

	/* allocate and initialize new station */
	if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);

	if (flags & DC_EXEC) {
		Station *st = new Station(tile);

		st->town = ClosestTownFromTile(tile, UINT_MAX);
		st->string_id = GenerateStationName(st, tile, STATIONNAMING_BUOY);

		if (IsValidPlayer(_current_player)) {
			SetBit(st->town->have_ratings, _current_player);
		}
		st->sign.width_1 = 0;
		st->dock_tile = tile;
		st->facilities |= FACIL_DOCK;
		/* Buoys are marked in the Station struct by this flag. Yes, it is this
		 * braindead.. */
		st->had_vehicle_of_type |= HVOT_BUOY;
		st->owner = OWNER_NONE;

		st->build_date = _date;

		MakeBuoy(tile, st->index, GetWaterClass(tile));

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		RebuildStationLists();
		InvalidateWindow(WC_STATION_LIST, st->owner);
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
	}

	return CommandCost(EXPENSES_CONSTRUCTION, _price.build_dock);
}

/**
 * Tests whether the player's vehicles have this station in orders
 * When player == INVALID_PLAYER, then check all vehicles
 * @param station station ID
 * @param player player ID, INVALID_PLAYER to disable the check
 */
bool HasStationInUse(StationID station, PlayerID player)
{
	const Vehicle *v;
	FOR_ALL_VEHICLES(v) {
		if (player == INVALID_PLAYER || v->owner == player) {
			const Order *order;
			FOR_VEHICLE_ORDERS(v, order) {
				if (order->IsType(OT_GOTO_STATION) && order->GetDestination() == station) {
					return true;
				}
			}
		}
	}
	return false;
}

static CommandCost RemoveBuoy(Station *st, uint32 flags)
{
	/* XXX: strange stuff */
	if (!IsValidPlayer(_current_player)) return_cmd_error(INVALID_STRING_ID);

	TileIndex tile = st->dock_tile;

	if (HasStationInUse(st->index, INVALID_PLAYER)) return_cmd_error(STR_BUOY_IS_IN_USE);
	/* remove the buoy if there is a ship on tile when company goes bankrupt... */
	if (!(flags & DC_BANKRUPT) && !EnsureNoVehicleOnGround(tile)) return CMD_ERROR;

	if (flags & DC_EXEC) {
		st->dock_tile = 0;
		/* Buoys are marked in the Station struct by this flag. Yes, it is this
		 * braindead.. */
		st->facilities &= ~FACIL_DOCK;
		st->had_vehicle_of_type &= ~HVOT_BUOY;

		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);

		/* We have to set the water tile's state to the same state as before the
		 * buoy was placed. Otherwise one could plant a buoy on a canal edge,
		 * remove it and flood the land (if the canal edge is at level 0) */
		MakeWaterKeepingClass(tile, GetTileOwner(tile));
		MarkTileDirtyByTile(tile);

		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_truck_station);
}

static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
	{-1,  0},
	{ 0,  0},
	{ 0,  0},
	{ 0, -1}
};
static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };

/** Build a dock/haven.
 * @param tile tile where dock will be built
 * @param flags operation to perform
 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
 * @param p2 unused
 */
CommandCost CmdBuildDock(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{
	DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
	if (direction == INVALID_DIAGDIR) return_cmd_error(STR_304B_SITE_UNSUITABLE);
	direction = ReverseDiagDir(direction);

	/* Docks cannot be placed on rapids */
	if (IsWaterTile(tile)) return_cmd_error(STR_304B_SITE_UNSUITABLE);

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

	if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);

	if (CmdFailed(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) return CMD_ERROR;

	TileIndex tile_cur = tile + TileOffsByDiagDir(direction);

	if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
		return_cmd_error(STR_304B_SITE_UNSUITABLE);
	}

	if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);

	/* Get the water class of the water tile before it is cleared.*/
	WaterClass wc = GetWaterClass(tile_cur);

	if (CmdFailed(DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR))) return CMD_ERROR;

	tile_cur += TileOffsByDiagDir(direction);
	if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
		return_cmd_error(STR_304B_SITE_UNSUITABLE);
	}

	/* middle */
	Station *st = NULL;

	if (!_patches.adjacent_stations || !HasBit(p1, 0)) {
		st = GetStationAround(
				tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
				_dock_w_chk[direction], _dock_h_chk[direction], INVALID_STATION);
		if (st == CHECK_STATIONS_ERR) return CMD_ERROR;
	}

	/* Find a station close to us */
	if (st == NULL) st = GetClosestStationFromTile(tile);

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

		if (!st->rect.BeforeAddRect(tile, _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST)) return CMD_ERROR;

		if (st->dock_tile != 0) return_cmd_error(STR_304C_TOO_CLOSE_TO_ANOTHER_DOCK);
	} else {
		/* allocate and initialize new station */
		/* allocate and initialize new station */
		if (!Station::CanAllocateItem()) return_cmd_error(STR_3008_TOO_MANY_STATIONS_LOADING);

		if (flags & DC_EXEC) {
			st = new Station(tile);

			st->town = ClosestTownFromTile(tile, UINT_MAX);
			st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);

			if (IsValidPlayer(_current_player)) {
				SetBit(st->town->have_ratings, _current_player);
			}
		}
	}

	if (flags & DC_EXEC) {
		st->dock_tile = tile;
		st->AddFacility(FACIL_DOCK, tile);

		st->rect.BeforeAddRect(tile, _dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);

		MakeDock(tile, st->owner, st->index, direction, wc);

		UpdateStationVirtCoordDirty(st);
		UpdateStationAcceptance(st, false);
		RebuildStationLists();
		InvalidateWindow(WC_STATION_LIST, st->owner);
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
	}

	return CommandCost(EXPENSES_CONSTRUCTION, _price.build_dock);
}

static CommandCost RemoveDock(Station *st, uint32 flags)
{
	if (!CheckOwnership(st->owner)) return CMD_ERROR;

	TileIndex tile1 = st->dock_tile;
	TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));

	if (!EnsureNoVehicleOnGround(tile1)) return CMD_ERROR;
	if (!EnsureNoVehicleOnGround(tile2)) return CMD_ERROR;

	if (flags & DC_EXEC) {
		DoClearSquare(tile1);
		MakeWaterKeepingClass(tile2, st->owner);

		st->rect.AfterRemoveTile(st, tile1);
		st->rect.AfterRemoveTile(st, tile2);

		MarkTileDirtyByTile(tile2);

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

		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_SHIPS);
		UpdateStationVirtCoordDirty(st);
		DeleteStationIfEmpty(st);
	}

	return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_dock);
}

#include "table/station_land.h"

const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
{
	return &_station_display_datas[st][gfx];
}

static void DrawTile_Station(TileInfo *ti)
{
	const DrawTileSprites *t = NULL;
	RoadTypes roadtypes;
	int32 total_offset;
	int32 custom_ground_offset;

	if (IsRailwayStation(ti->tile)) {
		const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
		roadtypes = ROADTYPES_NONE;
		total_offset = rti->total_offset;
		custom_ground_offset = rti->custom_ground_offset;
	} else {
		roadtypes = IsRoadStop(ti->tile) ? GetRoadTypes(ti->tile) : ROADTYPES_NONE;
		total_offset = 0;
		custom_ground_offset = 0;
	}
	uint32 relocation = 0;
	const Station *st = NULL;
	const StationSpec *statspec = NULL;
	PlayerID owner = GetTileOwner(ti->tile);

	SpriteID palette;
	if (IsValidPlayer(owner)) {
		palette = PLAYER_SPRITE_COLOR(owner);
	} else {
		/* Some stations are not owner by a player, namely oil rigs */
		palette = PALETTE_TO_GREY;
	}

	/* don't show foundation for docks */
	if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile))
		DrawFoundation(ti, FOUNDATION_LEVELED);

	if (IsCustomStationSpecIndex(ti->tile)) {
		/* look for customization */
		st = GetStationByTile(ti->tile);
		statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;

		if (statspec != NULL) {
			uint tile = GetStationGfx(ti->tile);

			relocation = GetCustomStationRelocation(statspec, st, ti->tile);

			if (HasBit(statspec->callbackmask, CBM_STATION_SPRITE_LAYOUT)) {
				uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
				if (callback != CALLBACK_FAILED) tile = (callback & ~1) + GetRailStationAxis(ti->tile);
			}

			/* Ensure the chosen tile layout is valid for this custom station */
			if (statspec->renderdata != NULL) {
				t = &statspec->renderdata[tile < statspec->tiles ? tile : (uint)GetRailStationAxis(ti->tile)];
			}
		}
	}

	if (t == NULL || t->seq == NULL) t = &_station_display_datas[GetStationType(ti->tile)][GetStationGfx(ti->tile)];


	if (IsBuoy(ti->tile) || IsDock(ti->tile)) {
		if (ti->tileh == SLOPE_FLAT) {
			DrawWaterClassGround(ti);
		} else {
			assert(IsDock(ti->tile));
			TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
			WaterClass wc = GetWaterClass(water_tile);
			if (wc == WATER_CLASS_SEA) {
				DrawShoreTile(ti->tileh);
			} else {
				DrawClearLandTile(ti, 3);
			}
		}
	} else {
		SpriteID image = t->ground.sprite;
		if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
			image += GetCustomStationGroundRelocation(statspec, st, ti->tile);
			image += custom_ground_offset;
		} else {
			image += total_offset;
		}
		DrawGroundSprite(image, HasBit(image, PALETTE_MODIFIER_COLOR) ? palette : PAL_NONE);
	}

	if (IsRailwayStation(ti->tile) && HasCatenary(GetRailType(ti->tile)) && IsStationTileElectrifiable(ti->tile)) DrawCatenary(ti);

	if (HasBit(roadtypes, ROADTYPE_TRAM)) {
		Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
		DrawGroundSprite((HasBit(roadtypes, ROADTYPE_ROAD) ? SPR_TRAMWAY_OVERLAY : SPR_TRAMWAY_TRAM) + (axis ^ 1), PAL_NONE);
		DrawTramCatenary(ti, axis == AXIS_X ? ROAD_X : ROAD_Y);
	}

	/* End now if buildings are invisible */
	if (IsInvisibilitySet(TO_BUILDINGS)) return;

	const DrawTileSeqStruct *dtss;
	foreach_draw_tile_seq(dtss, t->seq) {
		SpriteID image = dtss->image.sprite;
		if (relocation == 0 || HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
			image += total_offset;
		} else {
			image += relocation;
		}

		SpriteID pal;
		if (HasBit(image, PALETTE_MODIFIER_TRANSPARENT) || HasBit(image, PALETTE_MODIFIER_COLOR)) {
			if (dtss->image.pal > 0) {
				pal = dtss->image.pal;
			} else {
				pal = palette;
			}
		} else {
			pal = PAL_NONE;
		}

		if ((byte)dtss->delta_z != 0x80) {
			AddSortableSpriteToDraw(
				image, pal,
				ti->x + dtss->delta_x, ti->y + dtss->delta_y,
				dtss->size_x, dtss->size_y,
				dtss->size_z, ti->z + dtss->delta_z,
				!HasBit(image, SPRITE_MODIFIER_OPAQUE) && IsTransparencySet(TO_BUILDINGS)
			);
		} else {
			AddChildSpriteScreen(image, pal, dtss->delta_x, dtss->delta_y, IsTransparencySet(TO_BUILDINGS));
		}
	}
}

void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
{
	int32 total_offset = 0;
	SpriteID pal = PLAYER_SPRITE_COLOR(_local_player);
	const DrawTileSprites *t = &_station_display_datas[st][image];

	if (railtype != INVALID_RAILTYPE) {
		const RailtypeInfo *rti = GetRailTypeInfo(railtype);
		total_offset = rti->total_offset;
	}

	SpriteID img = t->ground.sprite;
	DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOR) ? pal : PAL_NONE, x, y);

	if (roadtype == ROADTYPE_TRAM) {
		DrawSprite(SPR_TRAMWAY_TRAM + (t->ground.sprite == SPR_ROAD_PAVED_STRAIGHT_X ? 1 : 0), PAL_NONE, x, y);
	}

	const DrawTileSeqStruct *dtss;
	foreach_draw_tile_seq(dtss, t->seq) {
		Point pt = RemapCoords(dtss->delta_x, dtss->delta_y, dtss->delta_z);
		DrawSprite(dtss->image.sprite + total_offset, pal, x + pt.x, y + pt.y);
	}
}

static uint GetSlopeZ_Station(TileIndex tile, uint x, uint y)
{
	return GetTileMaxZ(tile);
}

static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
{
	return FlatteningFoundation(tileh);
}

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

static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
{
	td->owner = GetTileOwner(tile);
	td->build_date = GetStationByTile(tile)->build_date;

	StringID str;
	switch (GetStationType(tile)) {
		default: NOT_REACHED();
		case STATION_RAIL:    str = STR_305E_RAILROAD_STATION; break;
		case STATION_AIRPORT:
			str = (IsHangar(tile) ? STR_305F_AIRCRAFT_HANGAR : STR_3060_AIRPORT);
			break;
		case STATION_TRUCK:   str = STR_3061_TRUCK_LOADING_AREA; break;
		case STATION_BUS:     str = STR_3062_BUS_STATION; break;
		case STATION_OILRIG:  str = STR_4807_OIL_RIG; break;
		case STATION_DOCK:    str = STR_3063_SHIP_DOCK; break;
		case STATION_BUOY:    str = STR_3069_BUOY; break;
	}
	td->str = str;
}


static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
	TrackBits trackbits = TRACK_BIT_NONE;

	switch (mode) {
		case TRANSPORT_RAIL:
			if (IsRailwayStation(tile) && !IsStationTileBlocked(tile)) {
				trackbits = TrackToTrackBits(GetRailStationTrack(tile));
			}
			break;

		case TRANSPORT_WATER:
			/* buoy is coded as a station, it is always on open water */
			if (IsBuoy(tile)) {
				trackbits = TRACK_BIT_ALL;
				/* remove tracks that connect NE map edge */
				if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
				/* remove tracks that connect NW map edge */
				if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
			}
			break;

		case TRANSPORT_ROAD:
			if ((GetRoadTypes(tile) & sub_mode) != 0 && IsRoadStop(tile)) {
				DiagDirection dir = GetRoadStopDir(tile);
				Axis axis = DiagDirToAxis(dir);

				if (side != INVALID_DIAGDIR) {
					if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
				}

				trackbits = AxisToTrackBits(axis);
			}
			break;

		default:
			break;
	}

	return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
}


static void TileLoop_Station(TileIndex tile)
{
	/* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
	 * hardcoded.....not good */
	switch (GetStationType(tile)) {
		case STATION_AIRPORT:
			switch (GetStationGfx(tile)) {
				case GFX_RADAR_LARGE_FIRST:
				case GFX_WINDSACK_FIRST : // for small airport
				case GFX_RADAR_INTERNATIONAL_FIRST:
				case GFX_RADAR_METROPOLITAN_FIRST:
				case GFX_RADAR_DISTRICTWE_FIRST: // radar district W-E airport
				case GFX_WINDSACK_INTERCON_FIRST : // for intercontinental airport
					AddAnimatedTile(tile);
					break;
			}
			break;

		case STATION_DOCK:
			if (GetTileSlope(tile, NULL) != SLOPE_FLAT) break; // only handle water part
		/* FALL THROUGH */
		case STATION_OILRIG: //(station part)
		case STATION_BUOY:
			TileLoop_Water(tile);
			break;

		default: break;
	}
}


static void AnimateTile_Station(TileIndex tile)
{
	struct AnimData {
		StationGfx from; // first sprite
		StationGfx to;   // last sprite
		byte delay;
	};

	static const AnimData data[] = {
		{ GFX_RADAR_LARGE_FIRST,         GFX_RADAR_LARGE_LAST,         3 },
		{ GFX_WINDSACK_FIRST,            GFX_WINDSACK_LAST,            1 },
		{ GFX_RADAR_INTERNATIONAL_FIRST, GFX_RADAR_INTERNATIONAL_LAST, 3 },
		{ GFX_RADAR_METROPOLITAN_FIRST,  GFX_RADAR_METROPOLITAN_LAST,  3 },
		{ GFX_RADAR_DISTRICTWE_FIRST,    GFX_RADAR_DISTRICTWE_LAST,    3 },
		{ GFX_WINDSACK_INTERCON_FIRST,   GFX_WINDSACK_INTERCON_LAST,   1 }
	};

	if (IsRailwayStation(tile)) {
		AnimateStationTile(tile);
		return;
	}

	StationGfx gfx = GetStationGfx(tile);

	for (const AnimData *i = data; i != endof(data); i++) {
		if (i->from <= gfx && gfx <= i->to) {
			if ((_tick_counter & i->delay) == 0) {
				SetStationGfx(tile, gfx < i->to ? gfx + 1 : i->from);
				MarkTileDirtyByTile(tile);
			}
			break;
		}
	}
}


static void ClickTile_Station(TileIndex tile)
{
	if (IsHangar(tile)) {
		ShowDepotWindow(tile, VEH_AIRCRAFT);
	} else {
		ShowStationViewWindow(GetStationIndex(tile));
	}
}

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

static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
{
	StationID station_id = GetStationIndex(tile);

	if (v->type == VEH_TRAIN) {
		if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
		if (IsRailwayStation(tile) && IsFrontEngine(v) &&
				!IsCompatibleTrainStationTile(tile + TileOffsByDiagDir(DirToDiagDir(v->direction)), tile)) {
			DiagDirection dir = DirToDiagDir(v->direction);

			x &= 0xF;
			y &= 0xF;

			if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
			if (y == TILE_SIZE / 2) {
				if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
				if (x == 12) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); /* enter station */
				if (x < 12) {
					uint16 spd;

					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 < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)v->u.road.state) && v->u.road.frame == 0) {
			if (IsRoadStop(tile) && IsRoadVehFront(v)) {
				/* Attempt to allocate a parking bay in a road stop */
				RoadStop *rs = GetRoadStopByTile(tile, GetRoadStopType(tile));

				if (IsDriveThroughStopTile(tile)) {
					if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;

					/* Vehicles entering a drive-through stop from the 'normal' side use first bay (bay 0). */
					byte side = ((DirToDiagDir(v->direction) == ReverseDiagDir(GetRoadStopDir(tile))) == (v->u.road.overtaking == 0)) ? 0 : 1;

					if (!rs->IsFreeBay(side)) return VETSB_CANNOT_ENTER;

					/* Check if the vehicle is stopping at this road stop */
					if (GetRoadStopType(tile) == (IsCargoInClass(v->cargo_type, CC_PASSENGERS) ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
							v->current_order.GetDestination() == GetStationIndex(tile)) {
						SetBit(v->u.road.state, RVS_IS_STOPPING);
						rs->AllocateDriveThroughBay(side);
					}

					/* Indicate if vehicle is using second bay. */
					if (side == 1) SetBit(v->u.road.state, RVS_USING_SECOND_BAY);
					/* Indicate a drive-through stop */
					SetBit(v->u.road.state, RVS_IN_DT_ROAD_STOP);
					return VETSB_CONTINUE;
				}

				/* For normal (non drive-through) road stops */
				/* Check if station is busy or if there are no free bays or whether it is a articulated vehicle. */
				if (rs->IsEntranceBusy() || !rs->HasFreeBay() || RoadVehHasArticPart(v)) return VETSB_CANNOT_ENTER;

				SetBit(v->u.road.state, RVS_IN_ROAD_STOP);

				/* Allocate a bay and update the road state */
				uint bay_nr = rs->AllocateBay();
				SB(v->u.road.state, RVS_USING_SECOND_BAY, 1, bay_nr);

				/* Mark the station entrace as busy */
				rs->SetEntranceBusy(true);
			}
		}
	}

	return VETSB_CONTINUE;
}

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

	if (st->facilities == 0 && ++st->delete_ctr >= 8) delete st;

}

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

static void UpdateStationRating(Station *st)
{
	bool waiting_changed = false;

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

	GoodsEntry *ge = st->goods;
	do {
		/* Slowly increase the rating back to his original level in the case we
		 *  didn't deliver cargo yet to this station. This happens when a bribe
		 *  failed while you didn't moved that cargo yet to a station. */
		if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP) && ge->rating < INITIAL_STATION_RATING) {
			ge->rating++;
		}

		/* Only change the rating if we are moving this cargo */
		if (HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) {
			byte_inc_sat(&ge->days_since_pickup);

			int rating = 0;

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

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

			if (IsValidPlayer(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;

			{
				byte days = ge->days_since_pickup;
				if (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);
			}

			uint waiting = ge->cargo.Count();
			(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 (rating <= (int)GB(r, 0, 7)) {
						/* Need to have int, otherwise it will just overflow etc. */
						waiting = max((int)waiting - (int)GB(r, 8, 2) - 1, 0);
						waiting_changed = true;
					}
				}

				/* At some point we really must cap the cargo. Previously this
				 * was a strict 4095, but now we'll have a less strict, but
				 * increasingly agressive truncation of the amount of cargo. */
				static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
				static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
				static const uint MAX_WAITING_CARGO        = 1 << 15;

				if (waiting > WAITING_CARGO_THRESHOLD) {
					uint difference = waiting - WAITING_CARGO_THRESHOLD;
					waiting -= (difference / WAITING_CARGO_CUT_FACTOR);

					waiting = min(waiting, MAX_WAITING_CARGO);
					waiting_changed = true;
				}

				if (waiting_changed) ge->cargo.Truncate(waiting);
			}
		}
	} while (++ge != endof(st->goods));

	StationID index = st->index;
	if (waiting_changed) {
		InvalidateWindow(WC_STATION_VIEW, index); // update whole window
	} else {
		InvalidateWindowWidget(WC_STATION_VIEW, index, SVW_RATINGLIST); // update only ratings list
	}
}

/* called for every station each tick */
static void StationHandleSmallTick(Station *st)
{
	if (st->facilities == 0) return;

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

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

void OnTick_Station()
{
	if (_game_mode == GM_EDITOR) return;

	uint i = _station_tick_ctr;
	if (++_station_tick_ctr > GetMaxStationIndex()) _station_tick_ctr = 0;

	if (IsValidStationID(i)) StationHandleBigTick(GetStation(i));

	Station *st;
	FOR_ALL_STATIONS(st) {
		StationHandleSmallTick(st);

		/* Run 250 tick interval trigger for station animation.
		 * Station index is included so that triggers are not all done
		 * at the same time. */
		if ((_tick_counter + st->index) % 250 == 0) {
			StationAnimationTrigger(st, st->xy, STAT_ANIM_250_TICKS);
		}
	}
}

void StationMonthlyLoop()
{
	/* not used */
}


void ModifyStationRatingAround(TileIndex tile, PlayerID owner, int amount, uint radius)
{
	Station *st;

	FOR_ALL_STATIONS(st) {
		if (st->owner == owner &&
				DistanceManhattan(tile, st->xy) <= radius) {
			for (CargoID i = 0; i < NUM_CARGO; i++) {
				GoodsEntry *ge = &st->goods[i];

				if (ge->acceptance_pickup != 0) {
					ge->rating = Clamp(ge->rating + amount, 0, 255);
				}
			}
		}
	}
}

static void UpdateStationWaiting(Station *st, CargoID type, uint amount)
{
	st->goods[type].cargo.Append(new CargoPacket(st->index, amount));
	SetBit(st->goods[type].acceptance_pickup, GoodsEntry::PICKUP);

	StationAnimationTrigger(st, st->xy, STAT_ANIM_NEW_CARGO, type);

	InvalidateWindow(WC_STATION_VIEW, st->index);
	st->MarkTilesDirty(true);
}

static bool IsUniqueStationName(const char *name)
{
	const Station *st;
	char buf[512];

	FOR_ALL_STATIONS(st) {
		SetDParam(0, st->index);
		GetString(buf, STR_STATION, lastof(buf));
		if (strcmp(buf, name) == 0) return false;
	}

	return true;
}

/** Rename a station
 * @param tile unused
 * @param flags operation to perform
 * @param p1 station ID that is to be renamed
 * @param p2 unused
 */
CommandCost CmdRenameStation(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
{
	if (!IsValidStationID(p1) || StrEmpty(_cmd_text)) return CMD_ERROR;
	Station *st = GetStation(p1);

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

	if (!IsUniqueStationName(_cmd_text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);

	if (flags & DC_EXEC) {
		free(st->name);
		st->name = strdup(_cmd_text);

		UpdateStationVirtCoord(st);
		ResortStationLists();
		MarkWholeScreenDirty();
	}

	return CommandCost();
}

/**
 * Find all (non-buoy) stations around an industry tile
 *
 * @param tile: Center tile to search from
 * @param w: Width of the center
 * @param h: Height of the center
 *
 * @return: Set of found stations
 */
StationSet FindStationsAroundIndustryTile(TileIndex tile, int w, int h)
{
	StationSet station_set;

	int w_prod; // width and height of the "producer" of the cargo
	int h_prod;
	int max_rad;
	if (_patches.modified_catchment) {
		w_prod = w;
		h_prod = h;
		w += 2 * MAX_CATCHMENT;
		h += 2 * MAX_CATCHMENT;
		max_rad = MAX_CATCHMENT;
	} else {
		w_prod = 0;
		h_prod = 0;
		w += 8;
		h += 8;
		max_rad = CA_UNMODIFIED;
	}

	BEGIN_TILE_LOOP(cur_tile, w, h, tile - TileDiffXY(max_rad, max_rad))
		cur_tile = TILE_MASK(cur_tile);
		if (!IsTileType(cur_tile, MP_STATION)) continue;

		Station *st = GetStationByTile(cur_tile);

		if (st->IsBuoy()) continue; // bouys don't accept cargo


		if (_patches.modified_catchment) {
			/* min and max coordinates of the producer relative */
			const int x_min_prod = max_rad + 1;
			const int x_max_prod = max_rad + w_prod;
			const int y_min_prod = max_rad + 1;
			const int y_max_prod = max_rad + h_prod;

			int rad = FindCatchmentRadius(st);

			int 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 if (w_cur > x_max_prod) {
				x_dist = w_cur - x_max_prod;
			}

			if (x_dist > rad) continue;

			int 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;
			}

			if (y_dist > rad) continue;
		}

		/* Insert the station in the set. This will fail if it has
		 * already been added.
		 */
		station_set.insert(st);

	END_TILE_LOOP(cur_tile, w, h, tile - TileDiffXY(max_rad, max_rad))

	return station_set;
}

uint MoveGoodsToStation(TileIndex tile, int w, int h, CargoID type, uint amount)
{
	Station *st1 = NULL;   // Station with best rating
	Station *st2 = NULL;   // Second best station
	uint best_rating1 = 0; // rating of st1
	uint best_rating2 = 0; // rating of st2

	StationSet all_stations = FindStationsAroundIndustryTile(tile, w, h);
	for (StationSet::iterator st_iter = all_stations.begin(); st_iter != all_stations.end(); ++st_iter) {
		Station *st = *st_iter;

		/* Is the station reserved exclusively for somebody else? */
		if (st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) continue;

		if (st->goods[type].rating == 0) continue; // Lowest possible rating, better not to give cargo anymore

		if (_patches.selectgoods && st->goods[type].last_speed == 0) continue; // Selectively servicing stations, and not this one

		if (IsCargoInClass(type, CC_PASSENGERS)) {
			if (st->facilities == FACIL_TRUCK_STOP) continue; // passengers are never served by just a truck stop
		} else {
			if (st->facilities == FACIL_BUS_STOP) continue; // non-passengers are never served by just a bus stop
		}

		/* This station can be used, add it to st1/st2 */
		if (st1 == NULL || st->goods[type].rating >= best_rating1) {
			st2 = st1; best_rating2 = best_rating1; st1 = st; best_rating1 = st->goods[type].rating;
		} else if (st2 == NULL || st->goods[type].rating >= best_rating2) {
			st2 = st; best_rating2 = st->goods[type].rating;
		}
	}

	/* no stations around at all? */
	if (st1 == NULL) return 0;

	if (st2 == NULL) {
		/* only one station around */
		uint moved = amount * best_rating1 / 256 + 1;
		UpdateStationWaiting(st1, type, moved);
		return moved;
	}

	/* several stations around, the best two (highest rating) are in st1 and st2 */
	assert(st1 != NULL);
	assert(st2 != NULL);
	assert(best_rating1 != 0 || best_rating2 != 0);

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

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

	uint moved = 0;
	if (t != 0) {
		moved = t * best_rating1 / 256 + 1;
		amount -= t;
		UpdateStationWaiting(st1, type, moved);
	}

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

	return moved;
}

void BuildOilRig(TileIndex tile)
{
	Station *st = new Station(tile);

	if (st == NULL) {
		DEBUG(misc, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile);
		return;
	}

	st->town = ClosestTownFromTile(tile, UINT_MAX);
	st->sign.width_1 = 0;

	st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);

	MakeOilrig(tile, st->index);

	st->owner = OWNER_NONE;
	st->airport_flags = 0;
	st->airport_type = AT_OILRIG;
	st->xy = tile;
	st->bus_stops = NULL;
	st->truck_stops = NULL;
	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_type = VEH_INVALID;
	st->facilities = FACIL_AIRPORT | FACIL_DOCK;
	st->build_date = _date;

	for (CargoID j = 0; j < NUM_CARGO; j++) {
		st->goods[j].acceptance_pickup = 0;
		st->goods[j].days_since_pickup = 255;
		st->goods[j].rating = INITIAL_STATION_RATING;
		st->goods[j].last_speed = 0;
		st->goods[j].last_age = 255;
	}

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

void DeleteOilRig(TileIndex tile)
{
	Station *st = GetStationByTile(tile);

	MakeWater(tile);

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

static void ChangeTileOwner_Station(TileIndex tile, PlayerID old_player, PlayerID new_player)
{
	if (!IsTileOwner(tile, old_player)) return;

	if (new_player != PLAYER_SPECTATOR) {
		Station *st = GetStationByTile(tile);

		SetTileOwner(tile, new_player);
		if (!IsBuoy(tile)) st->owner = new_player; // do not set st->owner for buoys
		RebuildStationLists();
		InvalidateWindowClasses(WC_STATION_LIST);
	} else {
		if (IsDriveThroughStopTile(tile)) {
			/* Remove the drive-through road stop */
			DoCommand(tile, 0, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
			assert(IsTileType(tile, MP_ROAD));
			/* Change owner of tile and all roadtypes */
			ChangeTileOwner(tile, old_player, new_player);
		} else {
			DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
			/* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
			 * Update owner of buoy if it was not removed (was in orders).
			 * Do not update when owned by OWNER_WATER (sea and rivers). */
			if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_player)) SetTileOwner(tile, OWNER_NONE);
		}
	}
}

/**
 * Check if a drive-through road stop tile can be cleared.
 * Road stops built on town-owned roads check the conditions
 * that would allow clearing of the original road.
 * @param tile road stop tile to check
 * @return true if the road can be cleared
 */
static bool CanRemoveRoadWithStop(TileIndex tile)
{
	/* The road can always be cleared if it was not a town-owned road */
	if (!GetStopBuiltOnTownRoad(tile)) return true;

	bool edge_road;
	return CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_ROAD), OWNER_TOWN, &edge_road, ROADTYPE_ROAD) &&
				CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, ROADTYPE_TRAM), OWNER_TOWN, &edge_road, ROADTYPE_TRAM);
}

static CommandCost ClearTile_Station(TileIndex tile, byte flags)
{
	if (flags & DC_AUTO) {
		switch (GetStationType(tile)) {
			case STATION_RAIL:    return_cmd_error(STR_300B_MUST_DEMOLISH_RAILROAD);
			case STATION_AIRPORT: return_cmd_error(STR_300E_MUST_DEMOLISH_AIRPORT_FIRST);
			case STATION_TRUCK:   return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_MUST_DEMOLISH_CARGO_TRAM_STATION : STR_3047_MUST_DEMOLISH_TRUCK_STATION);
			case STATION_BUS:     return_cmd_error(HasTileRoadType(tile, ROADTYPE_TRAM) ? STR_MUST_DEMOLISH_PASSENGER_TRAM_STATION : STR_3046_MUST_DEMOLISH_BUS_STATION);
			case STATION_BUOY:    return_cmd_error(STR_306A_BUOY_IN_THE_WAY);
			case STATION_DOCK:    return_cmd_error(STR_304D_MUST_DEMOLISH_DOCK_FIRST);
			case STATION_OILRIG:
				SetDParam(0, STR_4807_OIL_RIG);
				return_cmd_error(STR_4800_IN_THE_WAY);
		}
	}

	Station *st = GetStationByTile(tile);

	switch (GetStationType(tile)) {
		case STATION_RAIL:    return RemoveRailroadStation(st, tile, flags);
		case STATION_AIRPORT: return RemoveAirport(st, flags);
		case STATION_TRUCK:
			if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile))
				return_cmd_error(STR_3047_MUST_DEMOLISH_TRUCK_STATION);
			return RemoveRoadStop(st, flags, tile);
		case STATION_BUS:
			if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile))
				return_cmd_error(STR_3046_MUST_DEMOLISH_BUS_STATION);
			return RemoveRoadStop(st, flags, tile);
		case STATION_BUOY:    return RemoveBuoy(st, flags);
		case STATION_DOCK:    return RemoveDock(st, flags);
		default: break;
	}

	return CMD_ERROR;
}

void InitializeStations()
{
	/* Clean the station pool and create 1 block in it */
	_Station_pool.CleanPool();
	_Station_pool.AddBlockToPool();

	/* Clean the roadstop pool and create 1 block in it */
	_RoadStop_pool.CleanPool();
	_RoadStop_pool.AddBlockToPool();

	_station_tick_ctr = 0;
}


void AfterLoadStations()
{
	/* Update the speclists of all stations to point to the currently loaded custom stations. */
	Station *st;
	FOR_ALL_STATIONS(st) {
		for (uint i = 0; i < st->num_specs; i++) {
			if (st->speclist[i].grfid == 0) continue;

			st->speclist[i].spec = GetCustomStationSpecByGrf(st->speclist[i].grfid, st->speclist[i].localidx);
		}

		for (CargoID c = 0; c < NUM_CARGO; c++) st->goods[c].cargo.InvalidateCache();

		StationUpdateAnimTriggers(st);
	}
}

static CommandCost TerraformTile_Station(TileIndex tile, uint32 flags, uint z_new, Slope tileh_new)
{
	if (_patches.build_on_slopes && AutoslopeEnabled()) {
		/* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
		 *       TTDP does not call it.
		 */
		if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
			switch (GetStationType(tile)) {
				case STATION_RAIL: {
					DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
					return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
				}

				case STATION_AIRPORT:
					return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);

				case STATION_TRUCK:
				case STATION_BUS: {
					DiagDirection direction = GetRoadStopDir(tile);
					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
					if (IsDriveThroughStopTile(tile)) {
						if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
					}
					return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
				}

				default: break;
			}
		}
	}
	return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
}


extern 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 */
	GetFoundation_Station,      /* get_foundation_proc */
	TerraformTile_Station,      /* terraform_tile_proc */
};

static const SaveLoad _roadstop_desc[] = {
	SLE_VAR(RoadStop, xy,           SLE_UINT32),
	SLE_CONDNULL(1, 0, 44),
	SLE_VAR(RoadStop, status,       SLE_UINT8),
	/* Index was saved in some versions, but this is not needed */
	SLE_CONDNULL(4, 0, 8),
	SLE_CONDNULL(2, 0, 44),
	SLE_CONDNULL(1, 0, 25),

	SLE_REF(RoadStop, next,         REF_ROADSTOPS),
	SLE_CONDNULL(2, 0, 44),

	SLE_CONDNULL(4, 0, 24),
	SLE_CONDNULL(1, 25, 25),

	SLE_END()
};

static const SaveLoad _station_desc[] = {
	SLE_CONDVAR(Station, xy,                         SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
	SLE_CONDVAR(Station, xy,                         SLE_UINT32,                  6, SL_MAX_VERSION),
	SLE_CONDNULL(4, 0, 5),  ///< bus/lorry tile
	SLE_CONDVAR(Station, train_tile,                 SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
	SLE_CONDVAR(Station, train_tile,                 SLE_UINT32,                  6, SL_MAX_VERSION),
	SLE_CONDVAR(Station, airport_tile,               SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
	SLE_CONDVAR(Station, airport_tile,               SLE_UINT32,                  6, SL_MAX_VERSION),
	SLE_CONDVAR(Station, dock_tile,                  SLE_FILE_U16 | SLE_VAR_U32,  0, 5),
	SLE_CONDVAR(Station, dock_tile,                  SLE_UINT32,                  6, SL_MAX_VERSION),
	    SLE_REF(Station, town,                       REF_TOWN),
	    SLE_VAR(Station, trainst_w,                  SLE_UINT8),
	SLE_CONDVAR(Station, trainst_h,                  SLE_UINT8,                   2, SL_MAX_VERSION),

	SLE_CONDNULL(1, 0, 3),  ///< alpha_order

	    SLE_VAR(Station, string_id,                  SLE_STRINGID),
	SLE_CONDSTR(Station, name,                       SLE_STR, 0,                 84, SL_MAX_VERSION),
	    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_CONDNULL(2, 0, 5),  ///< Truck/bus stop status
	SLE_CONDNULL(1, 0, 4),  ///< Blocked months

	SLE_CONDVAR(Station, airport_flags,              SLE_VAR_U64 | SLE_FILE_U16,  0,  2),
	SLE_CONDVAR(Station, airport_flags,              SLE_VAR_U64 | SLE_FILE_U32,  3, 45),
	SLE_CONDVAR(Station, airport_flags,              SLE_UINT64,                 46, SL_MAX_VERSION),

	SLE_CONDNULL(2, 0, 25), ///< last-vehicle
	SLE_CONDVAR(Station, last_vehicle_type,          SLE_UINT8,                  26, SL_MAX_VERSION),

	SLE_CONDNULL(2, 3, 25), ///< custom station class and id
	SLE_CONDVAR(Station, build_date,                 SLE_FILE_U16 | SLE_VAR_I32,  3, 30),
	SLE_CONDVAR(Station, build_date,                 SLE_INT32,                  31, SL_MAX_VERSION),

	SLE_CONDREF(Station, bus_stops,                  REF_ROADSTOPS,               6, SL_MAX_VERSION),
	SLE_CONDREF(Station, truck_stops,                REF_ROADSTOPS,               6, SL_MAX_VERSION),

	/* Used by newstations for graphic variations */
	SLE_CONDVAR(Station, random_bits,                SLE_UINT16,                 27, SL_MAX_VERSION),
	SLE_CONDVAR(Station, waiting_triggers,           SLE_UINT8,                  27, SL_MAX_VERSION),
	SLE_CONDVAR(Station, num_specs,                  SLE_UINT8,                  27, SL_MAX_VERSION),

	SLE_CONDLST(Station, loading_vehicles,           REF_VEHICLE,                57, SL_MAX_VERSION),

	/* reserve extra space in savegame here. (currently 32 bytes) */
	SLE_CONDNULL(32, 2, SL_MAX_VERSION),

	SLE_END()
};

static uint16 _waiting_acceptance;
static uint16 _cargo_source;
static uint32 _cargo_source_xy;
static uint16 _cargo_days;
static Money  _cargo_feeder_share;

static const SaveLoad _station_speclist_desc[] = {
	SLE_CONDVAR(StationSpecList, grfid,    SLE_UINT32, 27, SL_MAX_VERSION),
	SLE_CONDVAR(StationSpecList, localidx, SLE_UINT8,  27, SL_MAX_VERSION),

	SLE_END()
};


void SaveLoad_STNS(Station *st)
{
	static const SaveLoad _goods_desc[] = {
		SLEG_CONDVAR(            _waiting_acceptance, SLE_UINT16,                  0, 67),
		 SLE_CONDVAR(GoodsEntry, acceptance_pickup,   SLE_UINT8,                  68, SL_MAX_VERSION),
		SLE_CONDNULL(2,                                                           51, 67),
		     SLE_VAR(GoodsEntry, days_since_pickup,   SLE_UINT8),
		     SLE_VAR(GoodsEntry, rating,              SLE_UINT8),
		SLEG_CONDVAR(            _cargo_source,       SLE_FILE_U8 | SLE_VAR_U16,   0, 6),
		SLEG_CONDVAR(            _cargo_source,       SLE_UINT16,                  7, 67),
		SLEG_CONDVAR(            _cargo_source_xy,    SLE_UINT32,                 44, 67),
		SLEG_CONDVAR(            _cargo_days,         SLE_UINT8,                   0, 67),
		     SLE_VAR(GoodsEntry, last_speed,          SLE_UINT8),
		     SLE_VAR(GoodsEntry, last_age,            SLE_UINT8),
		SLEG_CONDVAR(            _cargo_feeder_share, SLE_FILE_U32 | SLE_VAR_I64, 14, 64),
		SLEG_CONDVAR(            _cargo_feeder_share, SLE_INT64,                  65, 67),
		 SLE_CONDLST(GoodsEntry, cargo.packets,       REF_CARGO_PACKET,           68, SL_MAX_VERSION),

		SLE_END()
};


	SlObject(st, _station_desc);

	_waiting_acceptance = 0;

	uint num_cargo = CheckSavegameVersion(55) ? 12 : NUM_CARGO;
	for (CargoID i = 0; i < num_cargo; i++) {
		GoodsEntry *ge = &st->goods[i];
		SlObject(ge, _goods_desc);
		if (CheckSavegameVersion(68)) {
			SB(ge->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, HasBit(_waiting_acceptance, 15));
			if (GB(_waiting_acceptance, 0, 12) != 0) {
				/* Don't construct the packet with station here, because that'll fail with old savegames */
				CargoPacket *cp = new CargoPacket();
				/* In old versions, enroute_from used 0xFF as INVALID_STATION */
				cp->source          = (CheckSavegameVersion(7) && _cargo_source == 0xFF) ? INVALID_STATION : _cargo_source;
				cp->count           = GB(_waiting_acceptance, 0, 12);
				cp->days_in_transit = _cargo_days;
				cp->feeder_share    = _cargo_feeder_share;
				cp->source_xy       = _cargo_source_xy;
				cp->days_in_transit = _cargo_days;
				cp->feeder_share    = _cargo_feeder_share;
				SB(ge->acceptance_pickup, GoodsEntry::PICKUP, 1, 1);
				ge->cargo.Append(cp);
			}
		}
	}

	if (st->num_specs != 0) {
		/* Allocate speclist memory when loading a game */
		if (st->speclist == NULL) st->speclist = CallocT<StationSpecList>(st->num_specs);
		for (uint i = 0; i < st->num_specs; i++) {
			SlObject(&st->speclist[i], _station_speclist_desc);
		}
	}
}

static void Save_STNS()
{
	Station *st;
	/* Write the stations */
	FOR_ALL_STATIONS(st) {
		SlSetArrayIndex(st->index);
		SlAutolength((AutolengthProc*)SaveLoad_STNS, st);
	}
}

static void Load_STNS()
{
	int index;
	while ((index = SlIterateArray()) != -1) {
		Station *st = new (index) Station();

		SaveLoad_STNS(st);

		/* this means it's an oldstyle savegame without support for nonuniform stations */
		if (st->train_tile != 0 && st->trainst_h == 0) {
			uint w = GB(st->trainst_w, 4, 4);
			uint h = GB(st->trainst_w, 0, 4);

			if (GetRailStationAxis(st->train_tile) != AXIS_X) Swap(w, h);
			st->trainst_w = w;
			st->trainst_h = h;
		}
	}

	/* This is to ensure all pointers are within the limits of _stations_size */
	if (_station_tick_ctr > GetMaxStationIndex()) _station_tick_ctr = 0;
}

static void Save_ROADSTOP()
{
	RoadStop *rs;

	FOR_ALL_ROADSTOPS(rs) {
		SlSetArrayIndex(rs->index);
		SlObject(rs, _roadstop_desc);
	}
}

static void Load_ROADSTOP()
{
	int index;

	while ((index = SlIterateArray()) != -1) {
		RoadStop *rs = new (index) RoadStop(INVALID_TILE);

		SlObject(rs, _roadstop_desc);
	}
}

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