Files @ r5:283cc53559b4
Branch filter:

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

darkvater
(svn r6) -Fix [1006530] BuildRoadOutsideStation fix. Fix bug [994720] road depot - bus/lorry station (Truelight+Darkvater :P )
   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
#include "stdafx.h"
#include "ttd.h"
#include "vehicle.h"
#include "command.h"
#include "pathfind.h"
#include "station.h"
#include "table/train_cmd.h"
#include "gfx.h"
#include "news.h"
#include "engine.h"
#include "player.h"


#define is_firsthead_sprite(spritenum) \
	(is_custom_sprite(spritenum) \
		? is_custom_firsthead_sprite(spritenum) \
		: _engine_sprite_add[spritenum] == 0)


static const byte _vehicle_initial_x_fract[4] = {10,8,4,8};
static const byte _vehicle_initial_y_fract[4] = {8,4,8,10};
static const byte _state_dir_table[4] = { 0x20, 8, 0x10, 4 };

static const byte _signal_onedir[14] = {
	0x80, 0x80, 0x80, 0x20, 0x40, 0x10, 0, 0, 
	0x40, 0x40, 0x40, 0x10, 0x80, 0x20
};

static const byte _signal_otherdir[14] = {
	0x40, 0x40, 0x40, 0x10, 0x80, 0x20, 0, 0,
	0x80, 0x80, 0x80, 0x20, 0x40, 0x10
};

void UpdateTrainAcceleration(Vehicle *v)
{
	uint acc, power=0, max_speed=5000, weight=0;
	Vehicle *u = v;

	assert(v->subtype == 0);

	// compute stuff like max speed, power, and weight.
	do {
		const RailVehicleInfo *rvi = &_rail_vehicle_info[u->engine_type];
		
		// power is sum of the power for all engines
		power += rvi->power;

		// limit the max speed to the speed of the slowest vehicle.
		if (rvi->max_speed && rvi->max_speed <= max_speed) max_speed = rvi->max_speed;

		// weight is the sum of the weight of the wagon and the weight of the cargo.
		weight += rvi->weight;
		weight += (_cargoc.weights[u->cargo_type] * u->cargo_count) >> 4;

	} while ( (u=u->next) != NULL);
	
	// these are shown in the UI
	v->u.rail.cached_weight = weight;
	v->u.rail.cached_power = power;
	v->max_speed = max_speed;

	assert(weight != 0);

	// compute acceleration
	acc = power / weight * 4;

	if (acc >= 255) acc=255;
	if (acc == 0) acc++;

	v->acceleration = (byte)acc;
}

#define F_GRAV 9.82f
#define F_THETA 0.05f

#define F_HP_KW 0.74569f
#define F_KPH_MS 0.27778f
#define F_MU 0.3f

#define F_COEF_FRIC 0.04f
#define F_COEF_ROLL 0.18f

#define F_CURVE_FACTOR (1/96.f)

bool IsTunnelTile(TileIndex tile);

static int GetRealisticAcceleration(Vehicle *v)
{
	uint emass = 0;
	Vehicle *u = v;
	float f = 0.0f, spd;
	int curves = 0;

	assert(v->subtype == 0);

	// compute inclination force and number of curves.
	do {
		const RailVehicleInfo *rvi = &_rail_vehicle_info[u->engine_type];
		uint mass = rvi->weight + ((_cargoc.weights[u->cargo_type] * u->cargo_count) >> 4);
		if (rvi->power) emass += mass;

		if (u->u.rail.flags & VRF_GOINGUP) {
			f += (float)mass * ( -F_GRAV * F_THETA);
		} else if (u->u.rail.flags & VRF_GOINGDOWN) {
			f += (float)mass * ( F_GRAV * F_THETA);
		}

		// compute curve penalty..
		if (u->next != NULL) {
			uint diff = (u->direction - u->next->direction) & 7;
			if (diff) {
				curves += (diff == 1 || diff == 7) ? 1 : 3;
			}
		}
	} while ((u = u->next) != NULL);

	spd = (float)(v->cur_speed ? v->cur_speed : 1);

	// compute tractive effort
	{
		float te = (float)v->u.rail.cached_power * (F_HP_KW/F_KPH_MS) / spd;
		float te2 = (float)emass * (F_MU * F_GRAV);
		if (te > te2) te = te2;
		f += te;
	}
		
	// add air resistance
	{
		float cx = 1.0f; // NOT DONE
		
		// air resistance is doubled in tunnels.
		if (v->vehstatus == 0x40) cx *= 2;

		f -= cx * spd * spd * (F_KPH_MS * F_KPH_MS * 0.001f); 
	}

	// after this f contains the acceleration.
	f /= (float)v->u.rail.cached_weight;

	// add friction to sum of forces (avoid mul by weight). (0.001 because we want kN)
	f -= (F_COEF_FRIC * F_GRAV * 0.001f + (F_COEF_ROLL * F_KPH_MS * F_GRAV * 0.001f) * spd);

	// penalty for curves?
	if (curves)
		 f -= (float)min(curves, 8) * F_CURVE_FACTOR;

	return (int)(f  * (1.0/(F_KPH_MS * 0.015f)) + 0.5f);
}


int GetTrainImage(Vehicle *v, byte direction)
{
	int img = v->spritenum;
	int base;

	if (is_custom_sprite(img)) {
		base = GetCustomVehicleSprite(v, direction + 4 * is_custom_secondhead_sprite(img));
		if (base) return base;
		img = _engine_original_sprites[v->engine_type];
	}
	
	base = _engine_sprite_base[img] + ((direction + _engine_sprite_add[img]) & _engine_sprite_and[img]);

	if (v->cargo_count >= (v->cargo_cap >> 1))
		base += _wagon_full_adder[img];
	return base;
}

void DrawTrainEngine(int x, int y, int engine, uint32 image_ormod)
{
	const RailVehicleInfo *rvi = &_rail_vehicle_info[engine];
	
	int img = rvi->image_index;
	uint32 image = 0;

	if (is_custom_sprite(img)) {
		image = GetCustomEngineSprite(engine, -1, CID_PURCHASE, 0, 0, 6);
		if (!image) img = _engine_original_sprites[engine];
	}
	if (!image) {
		image = (6 & _engine_sprite_and[img]) + _engine_sprite_base[img];
	}

	if (rvi->flags & RVI_MULTIHEAD) {
		DrawSprite(image | image_ormod, x-14, y);
		x += 15;
		image = 0;
		if (is_custom_sprite(img)) {
			image = GetCustomEngineSprite(engine, -1, CID_PURCHASE, 0, 0, 2);
			if (!image) img = _engine_original_sprites[engine];
		}
		if (!image) {
			image = ((6 + _engine_sprite_add[img+1]) & _engine_sprite_and[img+1]) + _engine_sprite_base[img+1];	
		}
	}
	DrawSprite(image | image_ormod, x, y);
}

void DrawTrainEngineInfo(int engine, int x, int y, int maxw)
{
	const RailVehicleInfo *rvi = &_rail_vehicle_info[engine];
	int cap;
	uint multihead = ((rvi->flags & RVI_MULTIHEAD) ? 1 : 0);

	SET_DPARAM32(0, ((_price.build_railvehicle >> 3) * rvi->base_cost) >> 5);
	SET_DPARAM16(2, rvi->max_speed * 10 >> 4);
	SET_DPARAM16(3, rvi->power << multihead);
	SET_DPARAM16(1, rvi->weight << multihead);

	SET_DPARAM32(4, (rvi->running_cost_base * _price.running_rail[rvi->engclass] >> 8) << multihead);
	
	cap = rvi->capacity;
	SET_DPARAM16(5, STR_8838_N_A);
	if (cap != 0) {
		SET_DPARAM16(6, cap << multihead);
		SET_DPARAM16(5, _cargoc.names_long_p[rvi->cargo_type]);
	}
	DrawStringMultiCenter(x, y, STR_885B_COST_WEIGHT_T_SPEED_POWER, maxw);
}


int32 CmdBuildRailWagon(uint engine, uint tile, uint32 flags)
{
	int32 value;
	Vehicle *v;
	const RailVehicleInfo *rvi;
	int dir;
	const Engine *e;
	int x,y;

	rvi = &_rail_vehicle_info[engine];
	value = (rvi->base_cost * _price.build_railwagon) >> 8;

	if (!(flags & DC_QUERY_COST)) {
		_error_message = STR_00E1_TOO_MANY_VEHICLES_IN_GAME;

		v = AllocateVehicle();
		if (v == NULL)
			return CMD_ERROR;

		if (flags & DC_EXEC) {
			byte img = rvi->image_index;
			Vehicle *u;

			v->spritenum = img;

			u = _vehicles;
			for(;;) {
				if (u->type == VEH_Train && u->tile == (TileIndex)tile &&
				    u->subtype == 4 && u->engine_type == engine) {
					u = GetLastVehicleInChain(u);
					break;
				}

				if (++u == endof(_vehicles)) {
					u = NULL;
					break;
				}
			}

			v->engine_type = engine;

			dir = _map5[tile] & 3;

			v->direction = (byte)(dir*2+1);
			v->tile = (TileIndex)tile;
			
			x = GET_TILE_X(tile)*16 | _vehicle_initial_x_fract[dir];
			y = GET_TILE_Y(tile)*16 | _vehicle_initial_y_fract[dir];

			v->x_pos = x;
			v->y_pos = y;
			v->z_pos = GetSlopeZ(x,y);
			v->owner = _current_player;
			v->z_height = 6;
			v->u.rail.track = 0x80;
			v->vehstatus = VS_HIDDEN | VS_DEFPAL;

			v->subtype = 4;
			if (u != NULL) {
				u->next = v;
				v->subtype = 2;
				v->u.rail.first_engine = u->u.rail.first_engine;
				if (v->u.rail.first_engine == 0xffff && u->subtype == 0)
					v->u.rail.first_engine = u->engine_type;
			} else {
				v->u.rail.first_engine = 0xffff;
			}

			v->cargo_type = rvi->cargo_type;
			v->cargo_cap = rvi->capacity;
			v->value = value;
//			v->day_counter = 0;

			e = &_engines[engine];
			v->u.rail.railtype = e->railtype;
			
			v->build_year = _cur_year;
			v->type = VEH_Train;
			v->cur_image = 0xAC2;
	
			_new_wagon_id = v->index;

			VehiclePositionChanged(v);

			InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
		}
	}

	return value;
}

// Move all free vehicles in the depot to the train
static void NormalizeTrainVehInDepot(Vehicle *u)
{
	Vehicle *v;
	FOR_ALL_VEHICLES(v) {
		if (v->type == VEH_Train && v->subtype==4 &&
				v->tile == u->tile &&
				v->u.rail.track == 0x80) {
			if (DoCommandByTile(0,v->index | (u->index<<16), 1, DC_EXEC, CMD_MOVE_RAIL_VEHICLE) == CMD_ERROR)
				break;
		}
	}
}

static const byte _railveh_unk1[] = {
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 1, 1, 0, 0, 0,
	0, 0, 0, 0, 1, 0, 1, 0,
	0, 1, 1, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 1,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0,
};

static const byte _railveh_score[] = {
	1, 4, 7, 19, 20, 30, 31, 19,
	20, 21, 22, 10, 11, 30, 31, 32,
	33, 34, 35, 29, 45, 32, 50, 40,
	41, 51, 52, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 60, 62,
	63, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 70, 71, 72, 73,
	74, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0,
};


static int32 EstimateTrainCost(const RailVehicleInfo *rvi)
{
	return (rvi->base_cost * (_price.build_railvehicle >> 3)) >> 5;
}

/* Build a railroad vehicle
 * p1 = vehicle type id
 */

int32 CmdBuildRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	const RailVehicleInfo *rvi;
	int value,dir;
	Vehicle *v, *u;
	byte unit_num;
	Engine *e;
	uint tile;

	_cmd_build_rail_veh_var1 = 0;
	
	SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES);

	tile = TILE_FROM_XY(x,y);
	rvi = &_rail_vehicle_info[p1];
	
	if (rvi->flags & RVI_WAGON) {
		return CmdBuildRailWagon(p1, tile, flags);
	}

	value = EstimateTrainCost(rvi);

	if (!(flags & DC_QUERY_COST)) {
		v = AllocateVehicle();
		if (v == NULL || _ptr_to_next_order >= endof(_order_array))
			return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);

		unit_num = GetFreeUnitNumber(VEH_Train);
		if (unit_num > _patches.max_trains)
			return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);

		if (flags & DC_EXEC) {
			v->unitnumber = unit_num;

			dir = _map5[tile] & 3;

			v->direction = (byte)(dir*2+1);
			v->tile = (TileIndex)tile;
			v->owner = _current_player;
			v->x_pos = (x |= _vehicle_initial_x_fract[dir]);
			v->y_pos = (y |= _vehicle_initial_y_fract[dir]);
			v->z_pos = GetSlopeZ(x,y);
			v->z_height = 6;
			v->u.rail.track = 0x80;
			v->u.rail.first_engine = 0xffff;
			v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
//			v->subtype = 0;
			v->spritenum = rvi->image_index;
			v->cargo_type = rvi->cargo_type;
			v->cargo_cap = rvi->capacity;
			v->max_speed = rvi->max_speed;
//			v->cargo_count = 0;
			v->value = value;
//			v->day_counter = 0;
//			v->next_order = 0;
//			v->next_station = 0;
//			v->load_unload_time_rem = 0;
//			v->progress = 0;
//			v->targetairport = 0;
//			v->crash_anim_pos = 0;
			v->last_station_visited = 0xff;
			v->dest_tile = 0;
//			v->profit_last_year = 0;
//			v->profit_this_year = 0;
			
			v->engine_type = (byte)p1;
			e = &_engines[p1];

			v->reliability = e->reliability;
			v->reliability_spd_dec = e->reliability_spd_dec;
			v->max_age = e->lifelength * 366;
			
			v->string_id = STR_SV_TRAIN_NAME;
//			v->cur_speed = 0;
//			v->subspeed = 0;
			v->u.rail.railtype = e->railtype;
			_new_train_id = v->index;
//			v->cur_order_index = 0;
//			v->num_orders = 0;
			
			*(v->schedule_ptr = _ptr_to_next_order++) = 0;
//			v->next_in_chain = 0xffff;
//			v->next = NULL;
			
			v->service_interval = _patches.servint_trains;
//			v->breakdown_ctr = 0;
//			v->breakdowns_since_last_service = 0;
//			v->unk4D = 0;
			v->date_of_last_service = _date;
			v->build_year = _cur_year;
			v->type = VEH_Train;
			v->cur_image = 0xAC2;

			VehiclePositionChanged(v);

			if (rvi->flags&RVI_MULTIHEAD && (u=AllocateVehicle()) != NULL) {
				u->direction = v->direction;
				u->owner = v->owner;
				u->tile = v->tile;
				u->x_pos = v->x_pos;
				u->y_pos = v->y_pos;
				u->z_pos = v->z_pos;
				u->z_height = 6;
				u->u.rail.track = 0x80;
				v->u.rail.first_engine = 0xffff;
				u->vehstatus = VS_HIDDEN | VS_DEFPAL;
				u->subtype = 2;
				u->spritenum = v->spritenum + 1;
				u->cargo_type = v->cargo_type;
				u->cargo_cap = v->cargo_cap;
				u->u.rail.railtype = v->u.rail.railtype;
//				u->next_in_chain = 0xffff;
				v->next = u;
				u->engine_type = v->engine_type;
				u->build_year = v->build_year;
				v->value = u->value = v->value >> 1;
//				u->day_counter = 0;
				u->type = VEH_Train;
				u->cur_image = 0xAC2;
				VehiclePositionChanged(u);
			}

			UpdateTrainAcceleration(v);
			NormalizeTrainVehInDepot(v);

			InvalidateWindow(WC_VEHICLE_DEPOT, tile);
			InvalidateWindow(WC_TRAINS_LIST, v->owner);
			InvalidateWindow(WC_COMPANY, v->owner);
		}
	}
	_cmd_build_rail_veh_var1 = _railveh_unk1[p1];
	_cmd_build_rail_veh_score = _railveh_score[p1];
	return value;		
}


bool IsTrainDepotTile(TileIndex tile)
{
	return IS_TILETYPE(tile, MP_RAILWAY) &&
					(_map5[tile] & 0xFC) == 0xC0;
}

bool IsTunnelTile(TileIndex tile)
{
	return IS_TILETYPE(tile, MP_TUNNELBRIDGE) &&
				 (_map5[tile]&0x80) == 0;
}


int CheckStoppedInDepot(Vehicle *v)
{
	int count;
	TileIndex tile = v->tile;
	
	/* check if stopped in a depot */
	if (!IsTrainDepotTile(tile) || v->cur_speed != 0) {
errmsg:
		_error_message = STR_881A_TRAINS_CAN_ONLY_BE_ALTERED;
		return -1;
	}

	count = 0;
	do {
		count++;
		if (v->u.rail.track != 0x80 || v->tile != (TileIndex)tile || 
				(v->subtype==0 && !(v->vehstatus&VS_STOPPED)))
			goto errmsg;
	} while ( (v=v->next) != NULL);

	return count;
}

// unlink a rail wagon from the linked list.
// returns the new value of first
static Vehicle *UnlinkWagon(Vehicle *v, Vehicle *first)
{
	// unlinking the first vehicle of the chain?
	v->u.rail.first_engine = 0xffff;
	if (v == first) {
		Vehicle *u;
		if ((v=v->next) == NULL) return NULL;
		for (u=v; u; u=u->next) u->u.rail.first_engine = v->engine_type;
		v->subtype = 4;
		return v;
	} else {
		Vehicle *u;
		for(u=first; u->next!=v; u=u->next) {}
		u->next = v->next;
		return first;
	}
}

static Vehicle *FindGoodVehiclePos(Vehicle *src)
{
	Vehicle *dst;
	uint16 eng = src->engine_type;
	TileIndex tile = src->tile;

	FOR_ALL_VEHICLES(dst) {
		if (dst->type==VEH_Train && dst->subtype==4 && dst->tile==tile) {
			// check so all vehicles in the line have the same engine.
			Vehicle *v = dst;
			while (v->engine_type == eng) {
				if ((v = v->next) == NULL) return dst;
			}
		}
	}

	return NULL;
}

/* p1 & 0xffff= source vehicle index
   p1 & 0xffff0000 = what wagon to put the wagon AFTER, 0xffff0000 to make a new line
	 p2 & 1 = move all vehicles following the vehicle..
 */

int32 CmdMoveRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *src, *dst, *src_head, *dst_head;
	bool is_loco;

	src = &_vehicles[p1 & 0xffff];
	if (src->type != VEH_Train) return CMD_ERROR;

	is_loco = !(_rail_vehicle_info[src->engine_type].flags & RVI_WAGON)
	          && is_firsthead_sprite(src->spritenum);

	// if nothing is selected as destination, try and find a matching vehicle to drag to.
	if (((int32)p1 >> 16) == -1) {	
		dst = NULL;
		if (!is_loco) dst = FindGoodVehiclePos(src);
	} else {
		dst = &_vehicles[((int32)p1 >> 16)];
	}

	// don't move the same vehicle..
	if (src == dst)
		return 0;
	
	/* the player must be the owner */
	if (!CheckOwnership(src->owner) || (dst!=NULL && !CheckOwnership(dst->owner)))
		return CMD_ERROR;

	/* locate the head of the two chains */
	src_head = GetFirstVehicleInChain(src);
	dst_head = NULL;
	if (dst != NULL) dst_head = GetFirstVehicleInChain(dst);
	
	/* check if all vehicles in the source train are stopped */
	if (CheckStoppedInDepot(src_head) < 0)
		return CMD_ERROR;

	/* check if all the vehicles in the dest train are stopped,
	 * and that the length of the dest train is no longer than XXX vehicles */
	if (dst_head != NULL) {
		int num = CheckStoppedInDepot(dst_head);
		if (num < 0)
			return CMD_ERROR;

		if (num > (_patches.mammoth_trains ? 100 : 9) && dst_head->subtype==0)
			return_cmd_error(STR_8819_TRAIN_TOO_LONG);

		// if it's a multiheaded vehicle we're dragging to, drag to the vehicle before..
		while (is_custom_secondhead_sprite(dst->spritenum)
		       || (!is_custom_sprite(dst->spritenum) && _engine_sprite_add[dst->spritenum] != 0)) {
			Vehicle *v = GetPrevVehicleInChain(dst);
			if (!v || src == v) break;
			dst = v;
		}

		assert(dst_head->tile == src_head->tile);
	}

	// when moving all wagons, we can't have the same src_head and dst_head
	if (p2 & 1 && src_head == dst_head)
		return 0;

	// moving a loco to a new line?, then we need to assign a unitnumber.
	if (dst == NULL && src->subtype != 0 && is_loco) {
		uint unit_num = GetFreeUnitNumber(VEH_Train);
		if (unit_num > _patches.max_trains)
			return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);

		if (flags & DC_EXEC)
			src->unitnumber = unit_num;
	}


	/* do it? */
	if (flags & DC_EXEC) {
		if (p2 & 1) {
			// unlink ALL wagons
			if (src != src_head) {
				Vehicle *v = src_head;
				while (v->next != src) v=v->next;
				v->next = NULL;
			}
		} else {
			// unlink single wagon from linked list
			UnlinkWagon(src, src_head);
			src->next = NULL;
		}

		if (dst == NULL) {
			// move the train to an empty line. for locomotives, we set the type to 0. for wagons, 4.
			if (is_loco) {
				if (src->subtype != 0) {
					// setting the type to 0 also involves setting up the schedule_ptr field.
					src->subtype = 0;
					assert(src->schedule_ptr == NULL);
					*(src->schedule_ptr = _ptr_to_next_order++) = 0;
					src->num_orders = 0;
				}
				dst_head = src;
			} else {
				src->subtype = 4;
			}
			src->u.rail.first_engine = 0xffff;
		} else {
			if (src->subtype == 0) {
				// the vehicle was previously a loco. need to free the schedule list and delete vehicle windows etc.
				DeleteWindowById(WC_VEHICLE_VIEW, src->index);
				DeleteVehicleSchedule(src);
			}
			
			src->subtype = 2;
			src->unitnumber = 0; // doesn't occupy a unitnumber anymore.

			// setup first_engine
			src->u.rail.first_engine = dst->u.rail.first_engine;
			if (src->u.rail.first_engine == 0xffff && dst->subtype == 0)
				src->u.rail.first_engine = dst->engine_type;

			// link in the wagon(s) in the chain.
			{
				Vehicle *v = src;
				while (v->next != NULL) {
					v->next->u.rail.first_engine = v->u.rail.first_engine;
					v = v->next;
				}
				v->next = dst->next;
			}
			dst->next = src;
		}

		if (src_head->subtype == 0)
			UpdateTrainAcceleration(src_head);
		InvalidateWindow(WC_VEHICLE_DETAILS, src_head->index);

		if (dst_head) {
			if (dst_head->subtype == 0)
				UpdateTrainAcceleration(dst_head);
			InvalidateWindow(WC_VEHICLE_DETAILS, dst_head->index);
		}

		InvalidateWindow(WC_VEHICLE_DEPOT, src_head->tile);
		InvalidateWindow(WC_TRAINS_LIST, _current_player);
	}

	return 0;
}

/* p1 = train to start / stop */
int32 CmdStartStopTrain(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *v;

	v = &_vehicles[p1];

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

	if (flags & DC_EXEC) {
		v->u.rail.days_since_order_progr = 0;
		v->vehstatus ^= VS_STOPPED;
		InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
		InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
	}
	return 0;
}

// p1 = wagon/loco index
// p2 = mode
//   0: sell just the vehicle
//   1: sell the vehicle and all vehicles that follow it in the chain
//   2: when selling attached locos, rearrange all vehicles after it to separate lines.
int32 CmdSellRailWagon(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *v, *first,*last;
	int32 cost;

	SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES);

	v = &_vehicles[p1];

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

	// get first vehicle in chain
	first = v;
	if (first->subtype != 0) {
		first = GetFirstVehicleInChain(first);
		last = NULL;
	} else {
		if (p2 != 1) {
			// sell last part of multiheaded?
			last = GetLastVehicleInChain(v);
			if (is_firsthead_sprite(last->spritenum))
				last = NULL;
		} else {
			last = NULL;
		}
	}
	
	// make sure the vehicle is stopped in the depot
	if (CheckStoppedInDepot(first) < 0)
		return CMD_ERROR;


	if (flags & DC_EXEC) {
		// always redraw the depot. maybe redraw train list
		InvalidateWindow(WC_VEHICLE_DEPOT, first->tile);
		if (first->subtype == 0) InvalidateWindow(WC_TRAINS_LIST, first->owner);
		// when selling an attached locomotive. we need to delete its window.
		if (v->subtype == 0) {
			DeleteWindowById(WC_VEHICLE_VIEW, v->index);
			
			// rearrange all vehicles that follow to separate lines.
			if (p2 == 2) {
				Vehicle *u,*tmp;
				u = v->next;
				while (u != last) {
					tmp = u;
					u = u->next;
					DoCommandByTile(tmp->tile, tmp->index | ((-1)<<16), 0, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);		
				}
			}
		}

		// delete the vehicles
		cost = 0;
		for(;;) {
			Vehicle *tmp;

			assert(first);
			first = UnlinkWagon(v, first);
			cost -= v->value;
			tmp = v;
			v = v->next;
			DeleteVehicle(tmp);
			if (v == NULL || p2 != 1) break;
		}

		// delete last vehicle of multiheaded train?
		if (last) {
			first = UnlinkWagon(last, first);
			cost -= last->value;
			DeleteVehicle(last);
		}
		
		// an attached train changed?
		if (first && first->subtype == 0) {
			UpdateTrainAcceleration(first);
			InvalidateWindow(WC_VEHICLE_DETAILS, first->index);
		}
	} else {
		cost = 0;
		for(;;) {
			cost -= v->value;
			if ((v=v->next) == NULL || p2 != 1) break;
		}
		if (last) cost -= last->value;
	}

	return cost;
}

static void UpdateTrainDeltaXY(Vehicle *v, int direction)
{
#define MKIT(a,b,c,d) ((a&0xFF)<<24) | ((b&0xFF)<<16) | ((c&0xFF)<<8) | ((d&0xFF)<<0)
	static const uint32 _delta_xy_table[8] = {
		MKIT(3, 3, -1, -1),
		MKIT(3, 7, -1, -3),
		MKIT(3, 3, -1, -1),
		MKIT(7, 3, -3, -1),
		MKIT(3, 3, -1, -1),
		MKIT(3, 7, -1, -3),
		MKIT(3, 3, -1, -1),
		MKIT(7, 3, -3, -1),
	};
#undef MKIT

	uint32 x = _delta_xy_table[direction];

	v->x_offs = (byte)x;
	v->y_offs = (byte)(x>>=8);
	v->sprite_width = (byte)(x>>=8);
	v->sprite_height = (byte)(x>>=8);
}

static void UpdateVarsAfterSwap(Vehicle *v)
{
	UpdateTrainDeltaXY(v, v->direction);
	v->cur_image = GetTrainImage(v, v->direction);
	BeginVehicleMove(v);
	VehiclePositionChanged(v);
	EndVehicleMove(v);
}

static void SetLastSpeed(Vehicle *v, int spd) {	
	int old = v->u.rail.last_speed;
	if (spd != old) {
		v->u.rail.last_speed = spd;
		if (_patches.vehicle_speed || !old != !spd)
			InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
	}
}

static void ReverseTrainSwapVeh(Vehicle *v, int l, int r)
{
	Vehicle *a, *b;

	/* locate vehicles to swap */
	for(a=v; l!=0; l--) { a = a->next; }
	for(b=v; r!=0; r--) { b = b->next; }

	if (a != b) {
		/* swap the hidden bits */
		{
			uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus&VS_HIDDEN);
			b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus&VS_HIDDEN);
			a->vehstatus = tmp;
		}
		
		/* swap variables */
		swap_byte(&a->u.rail.track, &b->u.rail.track);
		swap_byte(&a->direction, &b->direction);

		/* toggle direction */
		if (!(a->u.rail.track & 0x80)) a->direction ^= 4;
		if (!(b->u.rail.track & 0x80)) b->direction ^= 4;
		
		/* swap more variables */
		swap_int16(&a->x_pos, &b->x_pos);
		swap_int16(&a->y_pos, &b->y_pos);
		swap_tile(&a->tile, &b->tile);
		swap_byte(&a->z_pos, &b->z_pos);

		/* update other vars */
		UpdateVarsAfterSwap(a);
		UpdateVarsAfterSwap(b);
	} else {
		if (!(a->u.rail.track & 0x80)) a->direction ^= 4;
		UpdateVarsAfterSwap(a);		
	}
}

static void ReverseTrainDirection(Vehicle *v)
{
	int l = 0, r = -1;
	Vehicle *u;

	if (IsTrainDepotTile(v->tile))
		InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);

	// count number of vehicles
	u = v;
	do r++; while ( (u = u->next) != NULL );

	/* swap start<>end, start+1<>end-1, ... */
	do {
		ReverseTrainSwapVeh(v, l++, r--);
	} while (l <= r);

	if (IsTrainDepotTile(v->tile))
		InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);

	v->u.rail.flags &= ~VRF_REVERSING;
}

/* p1 = vehicle */
int32 CmdReverseTrainDirection(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *v;

	v = &_vehicles[p1];

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

	_error_message = STR_EMPTY;

//	if (v->u.rail.track & 0x80 || IsTrainDepotTile(v->tile))
//		return CMD_ERROR;

	if (v->u.rail.crash_anim_pos != 0 || v->breakdown_ctr != 0)
		return CMD_ERROR;

	if (flags & DC_EXEC) {
		if (_patches.realistic_acceleration && v->cur_speed != 0) {
			v->u.rail.flags ^= VRF_REVERSING;
		} else {
			v->cur_speed = 0;
			SetLastSpeed(v, 0);
			ReverseTrainDirection(v);
		}
	}
	return 0;
}

int32 CmdForceTrainProceed(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *v;

	v = &_vehicles[p1];

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

	if (flags & DC_EXEC)
		v->u.rail.force_proceed = 0x50;
	
	return 0;
}

// p1 = vehicle to refit
// p2 = new cargo

int32 CmdRefitRailVehicle(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *v;
	int32 cost;
	uint num;

	SET_EXPENSES_TYPE(EXPENSES_NEW_VEHICLES);

	v = &_vehicles[p1];
	if (!CheckOwnership(v->owner) || CheckStoppedInDepot(v) < 0)
		return CMD_ERROR;

	cost = 0;
	num = 0;

	do {
		if (!(_rail_vehicle_info[v->engine_type].flags & RVI_WAGON) && (byte)p2 != v->cargo_type && v->cargo_cap != 0) {
			cost += (_price.ship_base >> 7);
			num += v->cargo_cap;
			if (flags & DC_EXEC) {
				v->cargo_count = 0;
				v->cargo_type = (byte)p2;
				InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
			}
		}	
	} while ( (v=v->next) != NULL);

	_returned_refit_amount = num;

	return cost;
}

int GetDepotByTile(uint tile)
{
	Depot *d;
	int i=0;
	for(d=_depots; d->xy != (TileIndex)tile; d++) { i++; }
	return i;
}

typedef struct TrainFindDepotData {
	uint best_length;
	uint tile;
	byte owner;
} TrainFindDepotData;

static bool TrainFindDepotEnumProc(uint tile, TrainFindDepotData *tfdd, int track, uint length, byte *state)
{
	if (IS_TILETYPE(tile, MP_RAILWAY) && _map_owner[tile] == tfdd->owner) {
		if ((_map5[tile] & ~0x3) == 0xC0) {
			if (length < tfdd->best_length) {
				tfdd->best_length = length;
				tfdd->tile = tile;
			}
			return true;
		}

		// make sure the train doesn't run against a oneway signal
		if ((_map5[tile] & 0xC0) == 0x40) {
			if (!(_map3_lo[tile] & _signal_onedir[track]) && _map3_lo[tile] & _signal_otherdir[track])
				return true;
		}
	}

	// stop  searching if we've found a destination that is closer already.
	return length >= tfdd->best_length;
}

// returns the tile of a depot to goto to
static uint FindClosestTrainDepot(Vehicle *v)
{
	int i;
	TrainFindDepotData tfdd;
	uint tile = v->tile;

	if (IsTrainDepotTile(tile))
		return tile;

	if (v->u.rail.track == 0x40) { tile = GetVehicleOutOfTunnelTile(v); }
		
	tfdd.owner = v->owner;
	tfdd.best_length = (uint)-1;

	if (!_patches.new_depot_finding) {
		// search in all directions
		for(i=0; i!=4; i++)
			NewTrainPathfind(tile, i, (TPFEnumProc*)TrainFindDepotEnumProc, &tfdd, NULL);
		if (tfdd.best_length != (uint)-1)
			return tfdd.tile;
	} else {
		// search in the forward direction first.
		i = v->direction >> 1;
		if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) { i = (i - 1) & 3; }
		NewTrainPathfind(tile, i, (TPFEnumProc*)TrainFindDepotEnumProc, &tfdd, NULL);
		if (tfdd.best_length != (uint)-1)
			return tfdd.tile;

		// search in backwards direction
		i = (v->direction^4) >> 1;
		if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[i]) { i = (i - 1) & 3; }
		NewTrainPathfind(tile, i, (TPFEnumProc*)TrainFindDepotEnumProc, &tfdd, NULL);
		if (tfdd.best_length != (uint)-1)
			return tfdd.tile;
	}
	
	return (uint)-1;
}

int32 CmdTrainGotoDepot(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *v = &_vehicles[p1];
	uint depot_tile;

	if ((v->next_order & OT_MASK) == OT_GOTO_DEPOT) {
		if (flags & DC_EXEC) {
			if (v->next_order & OF_UNLOAD) {
				v->u.rail.days_since_order_progr = 0;
				v->cur_order_index++;
			}
			
			v->next_order = OT_DUMMY;
			InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
		}
		return 0;
	}

	depot_tile = FindClosestTrainDepot(v);
	if (depot_tile == (uint)-1)
		return_cmd_error(STR_883A_UNABLE_TO_FIND_ROUTE_TO);

	if (flags & DC_EXEC) {
		v->dest_tile = depot_tile;
		v->next_order = OF_NON_STOP | OF_FULL_LOAD | OT_GOTO_DEPOT;
		v->next_order_param = GetDepotByTile(depot_tile);
		InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
	}
	
	return 0;
}

/* p1 = vehicle
 * p2 = new service int
 */
int32 CmdChangeTrainServiceInt(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Vehicle *v = &_vehicles[p1];

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

	if (flags & DC_EXEC) {
		v->service_interval = (uint16)p2;
		InvalidateWindowWidget(WC_VEHICLE_DETAILS, v->index, 8);
	}
	
	return 0;
}

void OnTick_Train()
{
	_age_cargo_skip_counter = (_age_cargo_skip_counter == 0) ? 184 : (_age_cargo_skip_counter - 1);
}

static const int8 _vehicle_smoke_pos[16] = {
	-4, -4, -4, 0, 4, 4, 4, 0,
	-4,  0,  4, 4, 4, 0,-4,-4,
};

static void HandleLocomotiveSmokeCloud(Vehicle *v)
{
	Vehicle *u;

	if (v->vehstatus & VS_TRAIN_SLOWING || v->load_unload_time_rem != 0 || v->cur_speed < 2)
		return;

	u = v;

	do {
		int engtype = v->engine_type;

		// no smoke?
		if (_rail_vehicle_info[engtype].flags & 2
		    || _engines[engtype].railtype > 0
		    || (v->vehstatus&VS_HIDDEN) || (v->u.rail.track & 0xC0) )
			continue;

		switch (_rail_vehicle_info[engtype].engclass) {
		case 0:
			// steam smoke.
			if ( (v->tick_counter&0xF) == 0 && !IsTrainDepotTile(v->tile) && !IsTunnelTile(v->tile)) {
				CreateEffectVehicleRel(v, 
					(_vehicle_smoke_pos[v->direction]),
					(_vehicle_smoke_pos[v->direction+8]),
					10,
					EV_STEAM_SMOKE);
			}
			break;

		case 1:
			// diesel smoke
			if (u->cur_speed <= 40 && !IsTrainDepotTile(v->tile) && !IsTunnelTile(v->tile) && (uint16)Random() <= 0x1E00) {
				CreateEffectVehicleRel(v, 0,0,10, EV_SMOKE_3);
			}
			break;

		case 2:
			// blue spark
			if ( (v->tick_counter&0x3) == 0 && !IsTrainDepotTile(v->tile) && !IsTunnelTile(v->tile) && (uint16)Random() <= 0x5B0) {
				CreateEffectVehicleRel(v, 0,0,10, EV_SMOKE_2);
			}
			break;
		}
	} while ( (v = v->next) != NULL );

}

static void TrainPlayLeaveStationSound(Vehicle *v)
{
	static const byte sfx[3] = { 0x2, 0x8, 0x8 };
	int engtype = v->engine_type;

	switch (_engines[engtype].railtype) {
		case 0: SndPlayVehicleFx(sfx[_rail_vehicle_info[engtype].engclass], v); break;
		case 1: SndPlayVehicleFx(0x41, v); break;
		case 2: SndPlayVehicleFx(0x47, v); break;
	}
}

static bool CheckTrainStayInDepot(Vehicle *v)
{
	Vehicle *u;
	if (v->u.rail.track != 0x80)	// first wagon (eg engine) in depot
		return false;

	// make sure that all vehicles are in the depot
	u = GetLastVehicleInChain(v);
	if (u->u.rail.track != 0x80)
		return false;

	// fix hung train if both ends are in depots (when here first wagon and last wagon is in depot)
	// both first and last should be in the same depot, eg on the same tile
	if (v->tile != u->tile)
		return false;

	if (v->u.rail.force_proceed == 0) {
		if (++v->load_unload_time_rem < 37)
			return true;
		v->load_unload_time_rem = 0;

		if (UpdateSignalsOnSegment(v->tile, v->direction))
			return true;
	}

	TrainPlayLeaveStationSound(v);
	
	v->u.rail.track = 1;
	if (v->direction & 2)
		v->u.rail.track = 2;
	
	v->vehstatus &= ~VS_HIDDEN;
	v->cur_speed = 0;
	
	UpdateTrainDeltaXY(v, v->direction);
	v->cur_image = GetTrainImage(v, v->direction);
	VehiclePositionChanged(v);
	UpdateSignalsOnSegment(v->tile, v->direction);
	UpdateTrainAcceleration(v);
	InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);

	return false;
}

typedef struct TrainTrackFollowerData {
	TileIndex dest_coords;
	int station_index; // station index we're heading for
	uint best_bird_dist;
	uint best_track_dist;
	byte best_track;
} TrainTrackFollowerData;

static bool TrainTrackFollower(uint tile, TrainTrackFollowerData *ttfd, int track, uint length, byte *state){
	if (IS_TILETYPE(tile, MP_RAILWAY) && (_map5[tile]&0xC0) == 0x40) {
		// the tile has a signal
		byte m3 = _map3_lo[tile];
		if (!(m3 & _signal_onedir[track])) {
			// if one way signal not pointing towards us, stop going in this direction.
			if (m3 & _signal_otherdir[track])
				return true;
		} else if (_map2[tile] & _signal_onedir[track]) {
			// green signal in our direction. either one way or two way.
			*state = true;
		} else if (m3 & _signal_otherdir[track]) {
			// two way signal. unless we passed another green signal on the way,
			// stop going in this direction.
			if (!*state) return true;
		}
	}

	// heading for nowhere?
	if (ttfd->dest_coords == 0)
		return false;

	// did we reach the final station?
	if (tile == ttfd->dest_coords ||
			(IS_TILETYPE(tile, MP_STATION) && IS_BYTE_INSIDE(_map5[tile], 0, 8) && _map2[tile] == ttfd->station_index)) {
		// found station
		ttfd->best_bird_dist = 0;
		if (length < ttfd->best_track_dist) {
			ttfd->best_track_dist = length;
			ttfd->best_track = state[1];
		}
		return true;
	} else {
		uint dist;

		// we've actually found the destination already. no point searching in directions longer than this.
		if (ttfd->best_track_dist != (uint)-1)
			return length >= ttfd->best_track_dist;
		
		// didn't find station
		dist = GetTileDist(tile, ttfd->dest_coords);
		if (dist < ttfd->best_bird_dist) {
			ttfd->best_bird_dist = dist;
			ttfd->best_track = state[1];
		}
		return false;
	}
}

static void FillWithStationData(TrainTrackFollowerData *fd, Vehicle *v)
{
	uint tile;

	fd->dest_coords = tile = v->dest_tile;
	fd->station_index = -1;

	if (IS_TILETYPE(tile, MP_STATION) && IS_BYTE_INSIDE(_map5[tile], 0, 8) )
		fd->station_index = _map2[tile];
}

static const byte _initial_tile_subcoord[6][4][3] = {
{{ 15, 8, 1 },{ 0, 0, 0 },{ 0, 8, 5 },{ 0, 0, 0 }},
{{  0, 0, 0 },{ 8, 0, 3 },{ 0, 0, 0 },{ 8,15, 7 }},
{{  0, 0, 0 },{ 7, 0, 2 },{ 0, 7, 6 },{ 0, 0, 0 }},
{{ 15, 8, 2 },{ 0, 0, 0 },{ 0, 0, 0 },{ 8,15, 6 }},
{{ 15, 7, 0 },{ 8, 0, 4 },{ 0, 0, 0 },{ 0, 0, 0 }},
{{  0, 0, 0 },{ 0, 0, 0 },{ 0, 8, 4 },{ 7,15, 0 }},
};

static const uint32 _reachable_tracks[4] = {
	0x10091009,
	0x00160016,
	0x05200520,
	0x2A002A00,
};

static const byte _search_directions[6][4] = {
	{ 0, 9, 2, 9 }, // track 1
	{ 9, 1, 9, 3 }, // track 2
	{ 9, 0, 3, 9 }, // track upper
	{ 1, 9, 9, 2 }, // track lower
	{ 3, 2, 9, 9 }, // track left
	{ 9, 9, 1, 0 }, // track right
};

static const byte _pick_track_table[6] = {1, 3, 2, 2, 0, 0};

/* choose a track */
static byte ChooseTrainTrack(Vehicle *v, uint tile, int direction, byte trackbits)
{	
	TrainTrackFollowerData fd;
	int bits = trackbits;
	uint best_track;
#if 0
	int time = rdtsc();
	static float f;
#endif

	assert( (bits & ~0x3F) == 0);

	/* quick return in case only one possible direction is available */
	if (KILL_FIRST_BIT(bits) == 0)
		return FIND_FIRST_BIT(bits);

	FillWithStationData(&fd, v);

	if (_patches.new_pathfinding) {
		fd.best_bird_dist = (uint)-1;
		fd.best_track_dist = (uint)-1;
		fd.best_track = 0xFF;
		NewTrainPathfind(tile - _tileoffs_by_dir[direction], direction, (TPFEnumProc*)TrainTrackFollower, &fd, NULL);

//		printf("Train %d %s\n", v->unitnumber, fd.best_track_dist == -1 ? "NOTFOUND" : "FOUND");

		if (fd.best_track == 0xff) {
			// blaha
			best_track = FIND_FIRST_BIT(bits);
		} else {
			best_track = fd.best_track & 7;
		}
	} else {
		int i, r;
		uint best_bird_dist  = 0;
		uint best_track_dist = 0;
		byte train_dir = v->direction & 3;


		best_track = -1;

		do {
			i = FIND_FIRST_BIT(bits);
			bits = KILL_FIRST_BIT(bits);

			fd.best_bird_dist = (uint)-1;
			fd.best_track_dist = (uint)-1;
			
			NewTrainPathfind(tile, _search_directions[i][direction], (TPFEnumProc*)TrainTrackFollower, &fd, NULL);
			if (best_track != -1) {
				if (best_track_dist == -1) {
					if (fd.best_track_dist == -1) {
						/* neither reached the destination, pick the one with the smallest bird dist */
						if (fd.best_bird_dist > best_bird_dist) goto bad;
						if (fd.best_bird_dist < best_bird_dist) goto good;
					} else {
						/* we found the destination for the first time */
						goto good;		
					}
				} else {
					if (fd.best_track_dist == -1) {
						/* didn't find destination, but we've found the destination previously */
						goto bad;
					} else {
						/* both old & new reached the destination, compare track length */
						if (fd.best_track_dist > best_track_dist) goto bad;
						if (fd.best_track_dist < best_track_dist) goto good;
					}
				}
				
				/* if we reach this position, there's two paths of equal value so far. 
				 * pick one randomly. */
				r = (byte)Random();
				if (_pick_track_table[i] == train_dir) r += 80;
				if (_pick_track_table[best_track] == train_dir) r -= 80;
		
				if (r <= 127) goto bad;
			}
	good:;
			best_track = i;
			best_bird_dist = fd.best_bird_dist;
			best_track_dist = fd.best_track_dist;
	bad:;
		} while (bits != 0);
//		printf("Train %d %s\n", v->unitnumber, best_track_dist == -1 ? "NOTFOUND" : "FOUND");
		assert(best_track != -1);
	}

#if 0
	time = rdtsc() - time;
	f = f * 0.99 + 0.01 * time;
	printf("PF time = %d %f\n", time, f);
#endif

	return best_track;
}


static bool CheckReverseTrain(Vehicle *v)
{
	TrainTrackFollowerData fd;
	int i, r;
	int best_track;
	uint best_bird_dist  = 0;
	uint best_track_dist = 0;
	uint reverse, reverse_best;

	if (_opt.diff.line_reverse_mode != 0 ||
			v->u.rail.track & 0xC0 ||
			!(v->direction & 1))
		return false;

	FillWithStationData(&fd, v);

	best_track = -1;
	reverse_best = reverse = 0;

	assert(v->u.rail.track);

	i = _search_directions[FIND_FIRST_BIT(v->u.rail.track)][v->direction>>1];

	while(true) {
		fd.best_bird_dist = (uint)-1;
		fd.best_track_dist = (uint)-1;

		NewTrainPathfind(v->tile, reverse ^ i, (TPFEnumProc*)TrainTrackFollower, &fd, NULL);

		if (best_track != -1) {
			if (best_bird_dist != 0) {
				if (fd.best_bird_dist != 0) {
					/* neither reached the destination, pick the one with the smallest bird dist */
					if (fd.best_bird_dist > best_bird_dist) goto bad;
					if (fd.best_bird_dist < best_bird_dist) goto good;
				} else {
					/* we found the destination for the first time */
					goto good;		
				}
			} else {
				if (fd.best_bird_dist != 0) {
					/* didn't find destination, but we've found the destination previously */
					goto bad;
				} else {
					/* both old & new reached the destination, compare track length */
					if (fd.best_track_dist > best_track_dist) goto bad;
					if (fd.best_track_dist < best_track_dist) goto good;
				}
			}
			
			/* if we reach this position, there's two paths of equal value so far. 
			 * pick one randomly. */
			r = (byte)Random();
			if (_pick_track_table[i] == (v->direction & 3)) r += 80;
			if (_pick_track_table[best_track] == (v->direction & 3)) r -= 80;
			if (r <= 127) goto bad;
		}
good:;
		best_track = i;
		best_bird_dist = fd.best_bird_dist;
		best_track_dist = fd.best_track_dist;
		reverse_best = reverse;
bad:;
		if (reverse != 0)
			break;
		reverse = 2;
	}

	return reverse_best != 0;
}

static bool ProcessTrainOrder(Vehicle *v)
{
	uint order;
	bool result;

	// These are un-interruptible
	if ((v->next_order & OT_MASK) >= OT_GOTO_DEPOT && (v->next_order & OT_MASK) <= OT_LEAVESTATION) {
		
		// Let a depot order in the schedule interrupt.
		if ((v->next_order & (OT_MASK|OF_UNLOAD)) != (OT_GOTO_DEPOT|OF_UNLOAD))
			return false;
	}

	if ((v->next_order & (OT_MASK|OF_UNLOAD|OF_FULL_LOAD)) == (OT_GOTO_DEPOT|OF_UNLOAD|OF_FULL_LOAD) &&
		v->date_of_last_service+v->service_interval > _date) {
		v->cur_order_index++;
	}

	// check if we've reached the checkpoint?
	if ((v->next_order & OT_MASK) == OT_GOTO_CHECKPOINT && v->tile == v->dest_tile) {
		v->cur_order_index++;
	}

	// check if we've reached a non-stop station while TTDPatch nonstop is enabled.. 
	if (_patches.new_nonstop && (v->next_order & OF_NON_STOP) && v->next_order_param == _map2[v->tile]) { 
		v->cur_order_index++; 
	}

	// Get the current order
	if (v->cur_order_index >= v->num_orders)
		v->cur_order_index = 0;
	order = v->schedule_ptr[v->cur_order_index];

	// If no order, do nothing.
	if (order == 0) {
		v->next_order = OT_NOTHING;
		v->dest_tile = 0;
		return false;
	}

	// If it is unchanged, keep it.
	if (order == (uint)((v->next_order | (v->next_order_param<<8))))
		return false;

	// Otherwise set it, and determine the destination tile.
	v->next_order = (byte)order;
	v->next_order_param = (byte)(order >> 8);

	v->dest_tile = 0;

	result = false;
	if ((order & OT_MASK) == OT_GOTO_STATION) {
		if ( (byte)(order >> 8) == v->last_station_visited)
			v->last_station_visited = 0xFF;
		v->dest_tile = DEREF_STATION(order >> 8)->xy;
		result = CheckReverseTrain(v);
	} else if ((order & OT_MASK) == OT_GOTO_DEPOT) {
		v->dest_tile = _depots[order >> 8].xy;
		result = CheckReverseTrain(v);
	} else if ((order & OT_MASK) == OT_GOTO_CHECKPOINT) {
		v->dest_tile = _checkpoints[order >> 8].xy;
		result = CheckReverseTrain(v);
	}

	InvalidateVehicleOrderWidget(v);

	return result;
}

static void MarkTrainDirty(Vehicle *v)
{
	do {
		v->cur_image = GetTrainImage(v, v->direction);
		MarkAllViewportsDirty(v->left_coord, v->top_coord, v->right_coord + 1, v->bottom_coord + 1);
	} while ( (v=v->next) != NULL);
}

static void HandleTrainLoading(Vehicle *v, bool mode)
{
	if (v->next_order == OT_NOTHING)
		return;
	
	if (v->next_order != OT_DUMMY) {
		if ((v->next_order&OT_MASK) != OT_LOADING)
			return;

		if (mode)
			return;

		// don't mark the train as lost if we're loading on the final station.
		if (v->next_order & OF_NON_STOP)
			v->u.rail.days_since_order_progr = 0;

		if (--v->load_unload_time_rem)
			return;

		if (v->next_order&OF_FULL_LOAD && CanFillVehicle(v)) {
			SET_EXPENSES_TYPE(EXPENSES_TRAIN_INC);
			if (LoadUnloadVehicle(v)) {
				InvalidateWindow(WC_TRAINS_LIST, v->owner);
				MarkTrainDirty(v);
				
				// need to update acceleration since the goods on the train changed.
				UpdateTrainAcceleration(v);
			}
			return;
		}
		
		TrainPlayLeaveStationSound(v);
		
		{
			byte b = v->next_order;
			v->next_order = OT_LEAVESTATION;
			
			// If this was not the final order, don't remove it from the list.
			if (!(b & OF_NON_STOP))
				return;
		}
	}

	v->u.rail.days_since_order_progr = 0;
	v->cur_order_index++;
	InvalidateVehicleOrderWidget(v);
}

static int UpdateTrainSpeed(Vehicle *v)
{
	uint spd;
	uint accel;

	if (v->vehstatus & VS_STOPPED || v->u.rail.flags & VRF_REVERSING) {
		accel = -v->acceleration * 2;
	} else {
		accel = v->acceleration;
		if (_patches.realistic_acceleration) {
			accel = GetRealisticAcceleration(v);
		}
	}

	spd = v->subspeed + accel * 2;
	v->subspeed = (byte)spd;
	v->cur_speed = spd = clamp(v->cur_speed + ((int)spd >> 8), 0, v->max_speed);

	if (!(v->direction & 1)) spd = spd * 3 >> 2;

	spd += v->progress;
	v->progress = (byte)spd;
	return (spd >> 8);
}

static void TrainEnterStation(Vehicle *v, int station)
{
	Station *st;
	uint32 flags;

	v->last_station_visited = station;

	/* check if a train ever visited this station before */
	st = DEREF_STATION(station);
	if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
		st->had_vehicle_of_type |= HVOT_TRAIN;
		SET_DPARAM16(0, st->index);
		flags = (v->owner == _local_player) ? NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_PLAYER, 0) : NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ARRIVAL_OTHER, 0);
		AddNewsItem(
			STR_8801_CITIZENS_CELEBRATE_FIRST,
			flags,
			v->index,
			0);
	}

	// Did we reach the final destination?
	if ((v->next_order&OT_MASK) == OT_GOTO_STATION && v->next_order_param == (byte)station) {
		// Yeah, keep the load/unload flags
		// Non Stop now means if the order should be increased.
		v->next_order = (v->next_order & (OF_FULL_LOAD|OF_UNLOAD)) | OF_NON_STOP | OT_LOADING;
	} else {
		// No, just do a simple load
		v->next_order = OT_LOADING;
	}
	v->next_order_param = 0;

	SET_EXPENSES_TYPE(EXPENSES_TRAIN_INC);
	if (LoadUnloadVehicle(v) != 0) {
		InvalidateWindow(WC_TRAINS_LIST, v->owner);
		MarkTrainDirty(v);
		UpdateTrainAcceleration(v);
	}
	InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
}

static byte AfterSetTrainPos(Vehicle *v)
{
	byte new_z, old_z;
	
	// need this hint so it returns the right z coordinate on bridges.
	_get_z_hint = v->z_pos;
	new_z = GetSlopeZ(v->x_pos, v->y_pos);
	_get_z_hint = 0;

	old_z = v->z_pos;
	v->z_pos = new_z;

	v->u.rail.flags &= ~(VRF_GOINGUP | VRF_GOINGDOWN);

	if (new_z != old_z) {
		v->u.rail.flags |= (new_z > old_z) ? VRF_GOINGUP : VRF_GOINGDOWN;
	}

	VehiclePositionChanged(v);
	EndVehicleMove(v);
	return old_z;
}

static const byte _new_vehicle_direction_table[11] = {
	0, 7, 6, 0,
	1, 0, 5, 0,
	2, 3, 4,
};

static int GetNewVehicleDirectionByTile(uint new_tile, uint old_tile)
{
	uint offs = (GET_TILE_Y(new_tile) - GET_TILE_Y(old_tile) + 1) * 4 + 
							GET_TILE_X(new_tile) - GET_TILE_X(old_tile) + 1;
	assert(offs < 11);
	return _new_vehicle_direction_table[offs];
}

static int GetNewVehicleDirection(Vehicle *v, int x, int y)
{
	uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
	assert(offs < 11);
	return _new_vehicle_direction_table[offs];
}

static int GetDirectionToVehicle(Vehicle *v, int x, int y)
{
	byte offs;

	x -= v->x_pos;
	if (x >= 0) {
		offs = (x > 2) ? 0 : 1;
	} else {
		offs = (x < -2) ? 2 : 1;
	}

	y -= v->y_pos;
	if (y >= 0) {
		offs += ((y > 2) ? 0 : 1) * 4;
	} else {
		offs += ((y < -2) ? 2 : 1) * 4;
	}

	assert(offs < 11);
	return _new_vehicle_direction_table[offs];
}

/* Check if the vehicle is compatible with the specified tile */
static bool CheckCompatibleRail(Vehicle *v, uint tile)
{
	if (IS_TILETYPE(tile, MP_RAILWAY) ||
			IS_TILETYPE(tile, MP_STATION)) {

	} else if (IS_TILETYPE(tile, MP_TUNNELBRIDGE)) {
		if ((_map5[tile] & 0xC0) == 0xC0) {// is bridge middle part?
			TileInfo ti;
			FindLandscapeHeightByTile(&ti, tile);

			// correct Z position of a train going under a bridge on slopes
			if (CORRECT_Z(ti.tileh))
				ti.z += 8;
			
			if(v->z_pos != ti.z) // train is going over bridge
				return true;
		}
	} else
		return true;

	if (_map_owner[tile] != v->owner ||
			(v->subtype == 0 && (_map3_lo[tile] & 0xF) != v->u.rail.railtype))
		return false;
	
	return true;
}

typedef struct {
	byte small_turn, large_turn;
	byte z_up; // fraction to remove when moving up
	byte z_down; // fraction to remove when moving down
} RailtypeSlowdownParams;

static const RailtypeSlowdownParams _railtype_slowdown[3] = {
	// normal accel
	{256/4, 256/2, 256/4, 2}, // normal
	{256/4, 256/2, 256/4, 2}, // monorail
	{0,     256/2, 256/4, 2}, // maglev
};

/* Modify the speed of the vehicle due to a turn */
static void AffectSpeedByDirChange(Vehicle *v, byte new_dir)
{
	byte diff;
	const RailtypeSlowdownParams *rsp;

	if (_patches.realistic_acceleration || (diff = (v->direction - new_dir) & 7) == 0)
		return;

	rsp = &_railtype_slowdown[v->u.rail.railtype];
	v->cur_speed -= ((diff == 1 || diff == 7) ? rsp->small_turn : rsp->large_turn) * v->cur_speed >> 8;
}

/* Modify the speed of the vehicle due to a change in altitude */
static void AffectSpeedByZChange(Vehicle *v, byte old_z)
{
	const RailtypeSlowdownParams *rsp;
	if (old_z == v->z_pos || _patches.realistic_acceleration)
		return;

	rsp = &_railtype_slowdown[v->u.rail.railtype];

	if (old_z < v->z_pos) {
		v->cur_speed -= (v->cur_speed * rsp->z_up >> 8);
	} else {
		uint16 spd = v->cur_speed + rsp->z_down;
		if (spd <= v->max_speed)
			v->cur_speed = spd;
	}
}

static const byte _otherside_signal_directions[14] = {
	1, 3, 1, 3, 5, 3, 0, 0,
	5, 7, 7, 5, 7, 1,
};

static void TrainMovedChangeSignals(uint tile, int dir)
{
	int i;
	if (IS_TILETYPE(tile, MP_RAILWAY) && (_map5[tile]&0xC0)==0x40) {
		i = FindFirstBit2x64((_map5[tile]+(_map5[tile]<<8)) & _reachable_tracks[dir]);
		UpdateSignalsOnSegment(tile, _otherside_signal_directions[i]);
	}
}


typedef struct TrainCollideChecker {
	Vehicle *v, *v_skip;

} TrainCollideChecker;

void *FindTrainCollideEnum(Vehicle *v, TrainCollideChecker *tcc)
{
	if (v == tcc->v || v == tcc->v_skip || v->type != VEH_Train || v->u.rail.track==0x80)
		return 0;

	if ( myabs(v->z_pos - tcc->v->z_pos) > 6 ||
			 myabs(v->x_pos - tcc->v->x_pos) >= 6 ||
			 myabs(v->y_pos - tcc->v->y_pos) >= 6)
				return NULL;
	return v;
}

static void SetVehicleCrashed(Vehicle *v)
{
	Vehicle *u;

	if (v->u.rail.crash_anim_pos != 0)
		return;

	v->u.rail.crash_anim_pos++;
	
	u = v;
	BEGIN_ENUM_WAGONS(v)
		v->vehstatus |= VS_CRASHED;
	END_ENUM_WAGONS(v)

	InvalidateWindowWidget(WC_VEHICLE_VIEW, u->index, 4);
}

static int CountPassengersInTrain(Vehicle *v)
{
	int num = 0;	
	BEGIN_ENUM_WAGONS(v)
		if (v->cargo_type == 0) num += v->cargo_count;
	END_ENUM_WAGONS(v)
	return num;
}

static void CheckTrainCollision(Vehicle *v)
{
	TrainCollideChecker tcc;
	Vehicle *coll;
	int num;

	/* can't collide in depot */
	if (v->u.rail.track == 0x80)
		return;
	
	assert((uint)TILE_FROM_XY(v->x_pos, v->y_pos) == v->tile);

	tcc.v = v;
	tcc.v_skip = v->next;

	/* find colliding vehicle */
	coll = VehicleFromPos(v->tile, &tcc, (VehicleFromPosProc*)FindTrainCollideEnum);
	if (coll == NULL)
		return;
	
	coll = GetFirstVehicleInChain(coll);
	
	/* it can't collide with its own wagons */
	if (v == coll)
		return;

	//two drivers + passangers killed in train v 
	num = 2 + CountPassengersInTrain(v);
	if(!(coll->vehstatus&VS_CRASHED)) 
		//two drivers + passangers killed in train coll (if it was not crashed already)
		num += 2 + CountPassengersInTrain(coll);

	SetVehicleCrashed(v);
	if (coll->subtype == 0)
		SetVehicleCrashed(coll);

	
	SET_DPARAM16(0, num);
	
	AddNewsItem(STR_8868_TRAIN_CRASH_DIE_IN_FIREBALL,
		NEWS_FLAGS(NM_THIN, NF_VIEWPORT|NF_VEHICLE, NT_ACCIDENT, 0),
		v->index,
		0);

	ModifyStationRatingAround(v->tile, v->owner, -160, 30);
	SndPlayVehicleFx(17, v);
}

static void *CheckVehicleAtSignal(Vehicle *v, void *data)
{
	uint32 d = (uint32)data;

	if (v->type == VEH_Train && v->subtype == 0 && v->tile == (TileIndex)(d >> 8)) {
		byte diff = (v->direction - (byte)d + 2) & 7;
		if (diff == 2 || (v->cur_speed <= 5 && diff <= 4))
			return (void*)1;
	}
	return 0;
}

static void TrainController(Vehicle *v)
{
	Vehicle *prev = NULL;
	GetNewVehiclePosResult gp;
	uint32 r, tracks,ts;
	int dir, i;
	byte chosen_dir;
	byte chosen_track;
	byte old_z;

	for(;;) {
		BeginVehicleMove(v);
		
		if (v->u.rail.track != 0x40) {
			if (GetNewVehiclePos(v, &gp)) {
				/* Statying in the old tile */
				if (v->u.rail.track == 0x80) {
					/* inside depot */
					gp.x = v->x_pos;
					gp.y = v->y_pos;
				} else {
					/* isnot inside depot */
					r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
					if (r & 0x8)
						goto invalid_rail;
					if (r & 0x2) {
						TrainEnterStation(v, r >> 8);
						return;
					}

					if (v->next_order == OT_LEAVESTATION) {
						v->next_order = OT_NOTHING;
						InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
					}
				}
			} else {
				/* A new tile is about to be entered. */

				/* Determine what direction we're entering the new tile from */
				dir = GetNewVehicleDirectionByTile(gp.new_tile, gp.old_tile);
				assert(dir==1 || dir==3 || dir==5 || dir==7);
				
				/* Get the status of the tracks in the new tile and mask
				 * away the bits that aren't reachable. */
				ts = GetTileTrackStatus(gp.new_tile, 0) & _reachable_tracks[dir >> 1];

				/* Combine the from & to directions.
				 * Now, the lower byte contains the track status, and the byte at bit 16 contains
				 * the signal status. */
				tracks = ts|(ts >> 8);
				if ( (byte) tracks == 0)
					goto invalid_rail;

				/* Check if the new tile contrains tracks that are compatible
				 * with the current train, if not, bail out. */
				if (!CheckCompatibleRail(v, gp.new_tile))
					goto invalid_rail;

				if (prev == NULL) {
					/* Currently the locomotive is active. Determine which one of the
					 * available tracks to choose */
					chosen_track = 1 << ChooseTrainTrack(v, gp.new_tile, dir>>1, (byte)tracks);

					/* Check if it's a red signal and that force proceed is not clicked. */
					if ( (tracks>>16)&chosen_track && v->u.rail.force_proceed == 0) goto red_light;
				} else {
					static byte _matching_tracks[8] = {0x30, 1, 0xC, 2, 0x30, 1, 0xC, 2};
					
					/* The wagon is active, simply follow the prev vehicle. */
					chosen_track = (byte)(_matching_tracks[GetDirectionToVehicle(prev, gp.x, gp.y)] & tracks);
				}

				/* make sure chosen track is a valid track */
				assert(chosen_track==1 || chosen_track==2 || chosen_track==4 || chosen_track==8 || chosen_track==16 || chosen_track==32);

				/* Update XY to reflect the entrance to the new tile, and select the direction to use */
				{
					const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][dir>>1];
					gp.x = (gp.x & ~0xF) | b[0];
					gp.y = (gp.y & ~0xF) | b[1];
					chosen_dir = b[2];
				}
				
				/* Call the landscape function and tell it that the vehicle entered the tile */
				r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
				if (r&0x8)
					goto invalid_rail;

				if (v->subtype == 0) v->load_unload_time_rem = 0;

				if (!(r&0x4)) {
					v->tile = gp.new_tile;
					v->u.rail.track = chosen_track;
				}

				if (v->subtype == 0)
					TrainMovedChangeSignals(gp.new_tile, dir>>1);

				if (v->next == NULL)
					TrainMovedChangeSignals(gp.old_tile, (dir>>1) ^ 2);
				
				if (prev == NULL) {
					AffectSpeedByDirChange(v, chosen_dir);
				}

				v->direction = chosen_dir;
			}
		} else {
			/* in tunnel */
			GetNewVehiclePos(v, &gp);
			
			if (IS_TILETYPE(gp.new_tile, MP_TUNNELBRIDGE) &&
					!(_map5[gp.new_tile] & 0xF0)) {
				r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
				if (r & 0x4) goto common;
			}

			v->x_pos = gp.x;
			v->y_pos = gp.y;
			VehiclePositionChanged(v);
			goto next_vehicle;
		}
common:;

		/* update image of train, as well as delta XY */
		dir = GetNewVehicleDirection(v, gp.x, gp.y);
		UpdateTrainDeltaXY(v, dir);
		v->cur_image = GetTrainImage(v, dir);

		v->x_pos = gp.x;
		v->y_pos = gp.y;

		/* update the Z position of the vehicle */
		old_z = AfterSetTrainPos(v);
		
		if (prev == NULL) {
			AffectSpeedByZChange(v, old_z);
			CheckTrainCollision(v);
		}

		/* continue with next vehicle */
next_vehicle:;
		prev = v;
		if ((v=v->next) == NULL)
			return;
	}

invalid_rail:
	if (prev != NULL) {
		error("!Disconnecting train");
	}
	goto reverse_train_direction;

red_light: {
		/* find the first set bit in ts. need to do it in 2 steps, since
		 * FIND_FIRST_BIT only handles 6 bits at a time. */
		i = FindFirstBit2x64(ts);
		
		if (!(_map3_lo[gp.new_tile] & _signal_otherdir[i])) {
			v->cur_speed = 0;
			v->subspeed = 0;
			v->progress = 255-100;
			if (++v->load_unload_time_rem < _patches.wait_oneway_signal * 20)
				return;
		} else if (_map3_lo[gp.new_tile] & _signal_onedir[i]){
			v->cur_speed = 0;
			v->subspeed = 0;
			v->progress = 255-10;
			if (++v->load_unload_time_rem < _patches.wait_twoway_signal * 73) {
				uint o_tile = gp.new_tile + _tileoffs_by_dir[dir>>1];
				/* check if a train is waiting on the other side */
				if (VehicleFromPos(o_tile, (void*)( (o_tile<<8) | (dir^4)), (VehicleFromPosProc*)CheckVehicleAtSignal) == NULL)
					return;
			}
		}
	}
		
reverse_train_direction:
	v->load_unload_time_rem = 0;
	v->cur_speed = 0;
	v->subspeed = 0;
	ReverseTrainDirection(v);

}

static void DeleteLastWagon(Vehicle *v)
{
	Vehicle *u = v;
	int t;

	while (v->next != NULL) {
		u = v;
		v = v->next;
	}
	u->next = NULL;

	InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
	DeleteWindowById(WC_VEHICLE_VIEW, v->index);
	InvalidateWindow(WC_TRAINS_LIST, v->owner);
	InvalidateWindow(WC_COMPANY, v->owner);

	BeginVehicleMove(v);
	EndVehicleMove(v);
	DeleteVehicle(v);

	if (!((t=v->u.rail.track) & 0xC0)) {
		SetSignalsOnBothDir(v->tile, FIND_FIRST_BIT(t));
	}
}

static void ChangeTrainDirRandomly(Vehicle *v)
{
	static int8 _random_dir_change[4] = { -1, 0, 0, 1};
	
	do {
		v->direction = (v->direction + _random_dir_change[Random()&3]) & 7;
		if (!(v->vehstatus & VS_HIDDEN)) {
			BeginVehicleMove(v);
			UpdateTrainDeltaXY(v, v->direction);
			v->cur_image = GetTrainImage(v, v->direction);
			AfterSetTrainPos(v);
		}
	} while ( (v=v->next) != NULL);
}

static void HandleCrashedTrain(Vehicle *v)
{
	int state = ++v->u.rail.crash_anim_pos, index;
	uint32 r;
	Vehicle *u;
	
	if (state == 4) {
		CreateEffectVehicleRel(v, 4, 4, 8, EV_CRASHED_SMOKE);
	}

	if (state <= 200 && (uint16)(r=Random()) <= 0x2492) {
		index = (r * 10 >> 16);

		u = v;
		do {
			if (--index < 0) {
				r = Random();

				CreateEffectVehicleRel(u,
					2 + ((r>>8)&7),
					2 + ((r>>16)&7),
					5 + (r&7),
					EV_DEMOLISH);
				break;
			}
		} while ( (u=u->next) != NULL);
	}

	if (state <= 240 && !(v->tick_counter&3)) {
		ChangeTrainDirRandomly(v);
	}

	if (state >= 4440 && !(v->tick_counter&0x1F))
		DeleteLastWagon(v);
}

static void HandleBrokenTrain(Vehicle *v)
{
	if (v->breakdown_ctr != 1) {
		v->breakdown_ctr = 1;
		v->cur_speed = 0;

		if (v->breakdowns_since_last_service != 255)
			v->breakdowns_since_last_service++;
		
		InvalidateWindow(WC_VEHICLE_VIEW, v->index);
		InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
		
		SndPlayVehicleFx((_opt.landscape != LT_CANDY) ? 0xE : 0x3A, v);

		if (!(v->vehstatus & VS_HIDDEN)) {
			Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
			if (u)
				u->u.special.unk0 = v->breakdown_delay * 2;
		}
	}

	if (!(v->tick_counter & 3)) {
		if (!--v->breakdown_delay) {
			v->breakdown_ctr = 0;
			InvalidateWindow(WC_VEHICLE_VIEW, v->index);
		}
	}
}

static const byte _breakdown_speeds[16] = {
	225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
};

static void TrainCheckIfLineEnds(Vehicle *v)
{
	uint tile;
	uint x,y;
	int t;
	uint32 ts;

	if ((uint)(t=v->breakdown_ctr) > 1) {
		v->vehstatus |= VS_TRAIN_SLOWING;
		
		t = _breakdown_speeds[ ((~t) >> 4) & 0xF];
		if ((uint16)t <= v->cur_speed)
			v->cur_speed = t;
	} else {
		v->vehstatus &= ~VS_TRAIN_SLOWING;
	}

	// exit if inside a tunnel
	if (v->u.rail.track & 0x40)
		return;

	tile = v->tile;

	// tunnel entrance?
	if (IS_TILETYPE(tile, MP_TUNNELBRIDGE) &&
			(_map5[tile] & 0xF0) == 0 && (byte)((_map5[tile] & 3)*2+1) == v->direction)
				return;
	
	// depot?
	if (IS_TILETYPE(tile, MP_RAILWAY) && (_map5[tile] & 0xFC) == 0xC0)
		return;

	// determine the tracks on the next tile.
	t = v->direction >> 1;
	if (!(v->direction & 1) && v->u.rail.track != _state_dir_table[t]) {
		t = (t - 1) & 3;
	}
	tile += _tileoffs_by_dir[t];
	ts = GetTileTrackStatus(tile, 0) & _reachable_tracks[t];
	
	x = v->x_pos & 0xF;
	y = v->y_pos & 0xF;
	
	switch(v->direction) {
	case 0:
		x = (~x) + (~y) + 24;
		break;
	case 7:
		x = y;
		/* fall through */
	case 1:
		x = (~x) + 16;
		break;
	case 2:
		x = (~x) + y + 8;
		break;
	case 3:
		x = y;
		break;
	case 4:
		x = x + y - 8;
		break;
	case 6:
		x = (~y) + x + 8;
		break;
	}

	if ( (uint16)ts != 0) {
		if ((ts &= (ts >> 16)) == 0) {
			// make a rail/road crossing red
			if (IS_TILETYPE(tile, MP_STREET) && (_map5[tile] & 0xF0)==0x10) {
				if (!(_map5[tile] & 4)) {
					_map5[tile] |= 4;
					SndPlayVehicleFx(12, v);
					MarkTileDirtyByTile(tile);
				}
			}
			return;
		}
	} else if (x + 4 > 15) {
		v->cur_speed = 0;
		ReverseTrainDirection(v);
		return;
	}

	// slow down
	v->vehstatus |= VS_TRAIN_SLOWING;
	t = _breakdown_speeds[x & 0xF];
	if (!(v->direction&1)) t>>=1;
	if ((uint16)t < v->cur_speed)
		v->cur_speed = t;
}

static void TrainLocoHandler(Vehicle *v, bool mode)
{
	int j;

	/* train has crashed? */
	if (v->u.rail.crash_anim_pos != 0) {
		if (!mode) HandleCrashedTrain(v);
		return;
	}

	if (v->u.rail.force_proceed != 0)
		v->u.rail.force_proceed--;

	/* train is broken down? */
	if (v->breakdown_ctr != 0) {
		if (v->breakdown_ctr <= 2) {
			HandleBrokenTrain(v);
			return;
		}
		v->breakdown_ctr--;
	}

	if (v->u.rail.flags & VRF_REVERSING && v->cur_speed == 0) {
		ReverseTrainDirection(v);
	}

	/* exit if train is stopped */
	if (v->vehstatus & VS_STOPPED && v->cur_speed == 0)
		return;


	if (ProcessTrainOrder(v)) {
		v->load_unload_time_rem = 0;
		v->cur_speed = 0;
		v->subspeed = 0;
		ReverseTrainDirection(v);
		return;
	}

	HandleTrainLoading(v, mode);

	if ((v->next_order & OT_MASK) == OT_LOADING)
		return;

	if (CheckTrainStayInDepot(v))
		return;

	if (!mode) HandleLocomotiveSmokeCloud(v);

	j = UpdateTrainSpeed(v);
	if (j == 0) {
		// if the vehicle has speed 0, update the last_speed field.
		if (v->cur_speed != 0)
			return;
	} else {
		TrainCheckIfLineEnds(v);

		do {
			TrainController(v);
			if (v->cur_speed <= 0x100)
				break;
		} while (--j != 0);
	}

	SetLastSpeed(v, v->cur_speed);
}


void Train_Tick(Vehicle *v)
{
	if (_age_cargo_skip_counter == 0 && v->cargo_days != 0xff)
		v->cargo_days++;

	v->tick_counter++;

	if (v->subtype == 0) {
		TrainLocoHandler(v, false);
		
		// make sure vehicle wasn't deleted.
		if (v->type == VEH_Train && v->subtype == 0)
			TrainLocoHandler(v, true);
	}
}


static const byte _depot_track_ind[4] = {0,1,0,1};

void TrainEnterDepot(Vehicle *v, uint tile)
{
	byte t;

	SetSignalsOnBothDir(tile, _depot_track_ind[_map5[tile]&3]);

	if (v->subtype != 0)
		v = GetFirstVehicleInChain(v);

	v->date_of_last_service = _date;
	v->breakdowns_since_last_service = 0;
	v->reliability = _engines[v->engine_type].reliability;
	InvalidateWindow(WC_VEHICLE_DETAILS, v->index);

	v->load_unload_time_rem = 0;
	v->cur_speed = 0;

	MaybeRenewVehicle(v, EstimateTrainCost(&_rail_vehicle_info[v->engine_type]));

	if ((v->next_order&OT_MASK) == OT_GOTO_DEPOT) {
		InvalidateWindow(WC_VEHICLE_VIEW, v->index);
	
		t = v->next_order;
		v->next_order = OT_DUMMY;

		// Part of the schedule?
		if (t & OF_UNLOAD) { v->u.rail.days_since_order_progr = 0; v->cur_order_index++; }

		// User initiated?
		else if (t & OF_FULL_LOAD) {
			v->vehstatus |= VS_STOPPED;
			if (v->owner == _local_player) {
				SET_DPARAM16(0, v->unitnumber);
				AddNewsItem(
					STR_8814_TRAIN_IS_WAITING_IN_DEPOT,
					NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0),
					v->index,
					0);
			}
		}
	}
}

static void CheckIfTrainNeedsService(Vehicle *v)
{
	uint tile;
	byte depot;

	if (_patches.no_train_service && IS_HUMAN_PLAYER(v->owner))
		return;

	if (v->date_of_last_service + v->service_interval > _date)
		return;

	if (v->vehstatus & VS_STOPPED)
		return;

	if (_patches.gotodepot && IS_HUMAN_PLAYER(v->owner) && ScheduleHasDepotOrders(v->schedule_ptr))
		return;
	
	// Don't interfere with a depot visit scheduled by the user, or a
	// depot visit by the order list.
	if ((v->next_order & OT_MASK) == OT_GOTO_DEPOT &&
			(v->next_order & (OF_FULL_LOAD|OF_UNLOAD)) != 0)
		return;

	tile = FindClosestTrainDepot(v);
	if (tile == (uint)-1 || GetTileDist(v->tile, tile) > 12) {
		if ((v->next_order & OT_MASK) == OT_GOTO_DEPOT) {
			v->next_order = OT_DUMMY;
			InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
		}
		return;
	}

	depot = GetDepotByTile(tile);

	if ((v->next_order & OT_MASK) == OT_GOTO_DEPOT && v->next_order_param != depot && !CHANCE16(3,16))
		return;

	v->next_order = OT_GOTO_DEPOT | OF_NON_STOP;
	v->next_order_param = depot;
	v->dest_tile = tile;
	InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, 4);
}

int32 GetTrainRunningCost(Vehicle *v)
{
	int32 cost = 0;

	do {
		const RailVehicleInfo *rvi = &_rail_vehicle_info[v->engine_type];
		if (rvi->running_cost_base)
			cost += rvi->running_cost_base * _price.running_rail[rvi->engclass];
	} while ( (v=v->next) != NULL );

	return cost;
}

void OnNewDay_Train(Vehicle *v)
{
	TileIndex tile;

	if ((++v->day_counter & 7) == 0)
		DecreaseVehicleValue(v);

	if (v->subtype == 0) {
		CheckVehicleBreakdown(v);
		AgeVehicle(v);
		
		CheckIfTrainNeedsService(v);
		
		// check if train hasn't advanced in its order list for a set number of days
		if (_patches.lost_train_days && v->num_orders && !(v->vehstatus & VS_STOPPED) && ++v->u.rail.days_since_order_progr >= _patches.lost_train_days && v->owner == _local_player) {
			v->u.rail.days_since_order_progr = 0;
			SET_DPARAM16(0, v->unitnumber);
			AddNewsItem(
				STR_TRAIN_IS_LOST,
				NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0),
				v->index,
				0);
		}

		/* update destination */
		if ((v->next_order & OT_MASK) == OT_GOTO_STATION &&
				(tile=DEREF_STATION(v->next_order_param)->train_tile) != 0)
					v->dest_tile = tile;

		if ((v->vehstatus & VS_STOPPED) == 0) {
			/* running costs */
			int32 cost = GetTrainRunningCost(v) / 364;

			v->profit_this_year -= cost >> 8;

			SET_EXPENSES_TYPE(EXPENSES_TRAIN_RUN);
			SubtractMoneyFromPlayerFract(v->owner, cost);

			InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
			InvalidateWindow(WC_TRAINS_LIST, v->owner);
		}
	}
}

void TrainsYearlyLoop()
{
	Vehicle *v;

	FOR_ALL_VEHICLES(v) {
		if (v->type == VEH_Train && v->subtype == 0) {
			
			// show warning if train is not generating enough income last 2 years (corresponds to a red icon in the vehicle list)
			if (_patches.train_income_warn && v->owner == _local_player && v->age >= 730 && v->profit_this_year < 0) {
				SET_DPARAM32(1, v->profit_this_year);
				SET_DPARAM16(0, v->unitnumber);
				AddNewsItem(
					STR_TRAIN_IS_UNPROFITABLE,
					NEWS_FLAGS(NM_SMALL, NF_VIEWPORT|NF_VEHICLE, NT_ADVICE, 0),
					v->index,
					0);
			}

			v->profit_last_year = v->profit_this_year;
			v->profit_this_year = 0;
			InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
		}
	}
}

extern void ShowTrainViewWindow(Vehicle *v);

void HandleClickOnTrain(Vehicle *v)
{
	if (v->subtype != 0) v = GetFirstVehicleInChain(v);
	ShowTrainViewWindow(v);
}

void InitializeTrains()
{
	_age_cargo_skip_counter = 1;
}

int ScheduleHasDepotOrders(uint16 *schedule)
{
	for (;*schedule!=0;schedule++)
		if ((*schedule&OT_MASK) == OT_GOTO_DEPOT)
			return true;
	return false;
}