Files @ r2299:f465fd68e7cc
Branch filter:

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

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

#include "stdafx.h"
#include "openttd.h"
#include "functions.h"
#include "map.h"
#include "tile.h"
#include "player.h"
#include "vehicle.h"
#include "engine.h"
#include "command.h"
#include "town.h"
#include "industry.h"
#include "station.h"
#include "pathfind.h"
#include "economy.h"
#include "airport.h"
#include "depot.h"
#include "variables.h"

// remove some day perhaps?
static Player *_cur_ai_player;
static uint _ai_service_interval;

typedef void AiStateAction(Player *p);

enum {
	AIS_0 = 0,
	AIS_1 = 1,
	AIS_VEH_LOOP = 2,
	AIS_VEH_CHECK_REPLACE_VEHICLE = 3,
	AIS_VEH_DO_REPLACE_VEHICLE = 4,
	AIS_WANT_NEW_ROUTE = 5,
	AIS_BUILD_DEFAULT_RAIL_BLOCKS = 6,
	AIS_BUILD_RAIL = 7,
	AIS_BUILD_RAIL_VEH = 8,
	AIS_DELETE_RAIL_BLOCKS = 9,
	AIS_BUILD_DEFAULT_ROAD_BLOCKS = 10,
	AIS_BUILD_ROAD = 11,
	AIS_BUILD_ROAD_VEHICLES = 12,
	AIS_DELETE_ROAD_BLOCKS = 13,
	AIS_AIRPORT_STUFF = 14,
	AIS_BUILD_DEFAULT_AIRPORT_BLOCKS = 15,
	AIS_BUILD_AIRCRAFT_VEHICLES = 16,
	AIS_CHECK_SHIP_STUFF = 17,
	AIS_BUILD_DEFAULT_SHIP_BLOCKS = 18,
	AIS_DO_SHIP_STUFF = 19,
	AIS_SELL_VEHICLE = 20,
	AIS_REMOVE_STATION = 21,
	AIS_REMOVE_TRACK = 22,
	AIS_REMOVE_SINGLE_RAIL_TILE = 23
};


#include "table/ai_rail.h"

static byte GetRailTrackStatus(TileIndex tile) {
	uint32 r = GetTileTrackStatus(tile, TRANSPORT_RAIL);
	return (byte) (r | r >> 8);
}


static void AiCase0(Player *p)
{
	p->ai.state = AIS_REMOVE_TRACK;
	p->ai.state_counter = 0;
}

static void AiCase1(Player *p)
{
	p->ai.cur_veh = NULL;
	p->ai.state = AIS_VEH_LOOP;
}

static void AiStateVehLoop(Player *p)
{
	Vehicle *v;
	uint index;

	index = (p->ai.cur_veh == NULL) ? 0 : p->ai.cur_veh->index + 1;

	FOR_ALL_VEHICLES_FROM(v, index) {
		if (v->type == 0 || v->owner != _current_player)
			continue;

		if ((v->type == VEH_Train && v->subtype==0) ||
				v->type == VEH_Road ||
				(v->type == VEH_Aircraft && v->subtype <= 2) ||
				v->type == VEH_Ship) {

			/* replace engine? */
			if (v->type == VEH_Train && v->engine_type < 3 &&
					(_price.build_railvehicle >> 3) < p->player_money) {
				p->ai.state = AIS_VEH_CHECK_REPLACE_VEHICLE;
				p->ai.cur_veh = v;
				return;
			}

			/* not profitable? */
			if (v->age >= 730 &&
					v->profit_last_year < _price.station_value*5 &&
					v->profit_this_year < _price.station_value*5) {
				p->ai.state_counter = 0;
				p->ai.state = AIS_SELL_VEHICLE;
				p->ai.cur_veh = v;
				return;
			}

			/* not reliable? */
			if ((v->age != 0 &&
					GetEngine(v->engine_type)->reliability < 35389) ||
					v->age >= v->max_age) {
				p->ai.state = AIS_VEH_CHECK_REPLACE_VEHICLE;
				p->ai.cur_veh = v;
				return;
			}
		}
	}

	p->ai.state = AIS_WANT_NEW_ROUTE;
	p->ai.state_counter = 0;
}

static int AiChooseTrainToBuild(byte railtype, int32 money, byte flag, TileIndex tile)
{
	int best_veh_index = -1;
	byte best_veh_score = 0;
	int32 ret;
	int i;

	for (i = 0; i < NUM_TRAIN_ENGINES; i++) {
		const RailVehicleInfo *rvi = RailVehInfo(i);
		const Engine* e = GetEngine(i);

		if (e->railtype != railtype || rvi->flags & RVI_WAGON
		    || !HASBIT(e->player_avail, _current_player) || e->reliability < 0x8A3D)
			continue;

		ret = DoCommandByTile(tile, i, 0, 0, CMD_BUILD_RAIL_VEHICLE);
		if (!CmdFailed(ret) && (!(_cmd_build_rail_veh_var1&1) || !(flag&1)) && ret <= money &&
				_cmd_build_rail_veh_score >= best_veh_score) {
			best_veh_score = _cmd_build_rail_veh_score;
			best_veh_index = i;
		}
	}

	return best_veh_index;
}

static int AiChooseRoadVehToBuild(byte cargo, int32 money, TileIndex tile)
{
	int best_veh_index = -1;
	int32 best_veh_cost = 0;
	int32 ret;

	int i = _cargoc.ai_roadveh_start[cargo];
	int end = i + _cargoc.ai_roadveh_count[cargo];
	const Engine* e = GetEngine(i);

	do {
		if (!HASBIT(e->player_avail, _current_player) || e->reliability < 0x8A3D)
			continue;

		ret = DoCommandByTile(tile, i, 0, 0, CMD_BUILD_ROAD_VEH);
		if (!CmdFailed(ret) && ret <= money && ret >= best_veh_cost) {
			best_veh_cost = ret;
			best_veh_index = i;
		}
	} while (++e, ++i != end);

	return best_veh_index;
}

static int AiChooseAircraftToBuild(int32 money, byte flag)
{
	int best_veh_index = -1;
	int32 best_veh_cost = 0;
	int32 ret;

	int i = AIRCRAFT_ENGINES_INDEX;
	int end = i + NUM_AIRCRAFT_ENGINES;
	const Engine* e = GetEngine(i);

	do {
		if (!HASBIT(e->player_avail, _current_player) || e->reliability < 0x8A3D)
			continue;

		if (flag&1) {
			if (i<253) continue;
		} else {
			if (i>=253) continue;
		}

		ret = DoCommandByTile(0, i, 0, 0, CMD_BUILD_AIRCRAFT);
		if (!CmdFailed(ret) && ret <= money && ret >= best_veh_cost) {
			best_veh_cost = ret;
			best_veh_index = i;
		}
	} while (++e, ++i != end);

	return best_veh_index;
}

static int32 AiGetBasePrice(Player *p)
{
	int32 base = _price.station_value;

	// adjust base price when more expensive vehicles are available
	if (p->ai.railtype_to_use == 1) base = (base * 3) >> 1;
	else if (p->ai.railtype_to_use == 2) base *= 2;

	return base;
}

#if 0
static int AiChooseShipToBuild(byte cargo, int32 money)
{
	// XXX: not done
	return 0;
}
#endif

static int AiChooseRoadVehToReplaceWith(Player *p, Vehicle *v)
{
	int32 avail_money = p->player_money + v->value;
	return AiChooseRoadVehToBuild(v->cargo_type, avail_money, v->tile);
}

static int AiChooseAircraftToReplaceWith(Player *p, Vehicle *v)
{
	int32 avail_money = p->player_money + v->value;
	return AiChooseAircraftToBuild(avail_money, v->engine_type>=253?1:0);
}

static int AiChooseTrainToReplaceWith(Player *p, Vehicle *v)
{
	int32 avail_money = p->player_money + v->value;
	int num=0;
	Vehicle *u = v;

	while (++num, u->next != NULL) {
		u = u->next;
	}

	// XXX: check if a wagon
	return AiChooseTrainToBuild(v->u.rail.railtype, avail_money, 0, v->tile);
}

static int AiChooseShipToReplaceWith(Player *p, Vehicle *v)
{
	error("!AiChooseShipToReplaceWith");

	/* maybe useless, but avoids compiler warning this way */
	return 0;
}

static void AiHandleGotoDepot(Player *p, int cmd)
{
	if (p->ai.cur_veh->current_order.type != OT_GOTO_DEPOT)
		DoCommandByTile(0, p->ai.cur_veh->index, 0, DC_EXEC, cmd);

	if (++p->ai.state_counter <= 1387) {
		p->ai.state = AIS_VEH_DO_REPLACE_VEHICLE;
		return;
	}

	if (p->ai.cur_veh->current_order.type == OT_GOTO_DEPOT) {
		p->ai.cur_veh->current_order.type = OT_DUMMY;
		p->ai.cur_veh->current_order.flags = 0;
		InvalidateWindow(WC_VEHICLE_VIEW, p->ai.cur_veh->index);
	}
}

static void AiRestoreVehicleOrders(Vehicle *v, BackuppedOrders *bak)
{
	int i;

	for (i = 0; bak->order[i].type != OT_NOTHING; i++)
		if (CmdFailed(DoCommandP(0, v->index + (i << 16), PackOrder(&bak->order[i]), NULL, CMD_INSERT_ORDER | CMD_NO_TEST_IF_IN_NETWORK)))
			break;
}

static void AiHandleReplaceTrain(Player *p)
{
	Vehicle *v = p->ai.cur_veh;
	BackuppedOrders orderbak[1];
	int veh;

	// wait until the vehicle reaches the depot.
	if (!IsTileDepotType(v->tile, TRANSPORT_RAIL) || v->u.rail.track != 0x80 || !(v->vehstatus&VS_STOPPED)) {
		AiHandleGotoDepot(p, CMD_TRAIN_GOTO_DEPOT);
		return;
	}

	veh = AiChooseTrainToReplaceWith(p, v);
	if (veh != -1) {
		TileIndex tile;

		BackupVehicleOrders(v, orderbak);
		tile = v->tile;

		if (!CmdFailed(DoCommandByTile(0, v->index, 2, DC_EXEC, CMD_SELL_RAIL_WAGON)) &&
			  !CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE)) ) {
			veh = _new_train_id;
			AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
			DoCommandByTile(0, veh, 0, DC_EXEC, CMD_START_STOP_TRAIN);

			DoCommandByTile(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
		}
	}
}

static void AiHandleReplaceRoadVeh(Player *p)
{
	Vehicle *v = p->ai.cur_veh;
	BackuppedOrders orderbak[1];
	int veh;

	if (!IsTileDepotType(v->tile, TRANSPORT_ROAD) || v->u.road.state != 254 || !(v->vehstatus&VS_STOPPED)) {
		AiHandleGotoDepot(p, CMD_SEND_ROADVEH_TO_DEPOT);
		return;
	}

	veh = AiChooseRoadVehToReplaceWith(p, v);
	if (veh != -1) {
		TileIndex tile;

		BackupVehicleOrders(v, orderbak);
		tile = v->tile;

		if (!CmdFailed(DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH)) &&
			  !CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_ROAD_VEH)) ) {
			veh = _new_roadveh_id;
			AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
			DoCommandByTile(0, veh, 0, DC_EXEC, CMD_START_STOP_ROADVEH);

			DoCommandByTile(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
		}
	}
}

static void AiHandleReplaceAircraft(Player *p)
{
	Vehicle *v = p->ai.cur_veh;
	int veh;
	BackuppedOrders orderbak[1];

	if (!IsAircraftHangarTile(v->tile) && !(v->vehstatus&VS_STOPPED)) {
		AiHandleGotoDepot(p, CMD_SEND_AIRCRAFT_TO_HANGAR);
		return;
	}

	veh = AiChooseAircraftToReplaceWith(p, v);
	if (veh != -1) {
		TileIndex tile;

		BackupVehicleOrders(v, orderbak);
		tile = v->tile;

		if (!CmdFailed(DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_AIRCRAFT)) &&
			  !CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_AIRCRAFT)) ) {
			veh = _new_aircraft_id;
			AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
			DoCommandByTile(0, veh, 0, DC_EXEC, CMD_START_STOP_AIRCRAFT);

			DoCommandByTile(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);
		}
	}
}

static void AiHandleReplaceShip(Player *p)
{
	error("!AiHandleReplaceShip");
}

typedef int CheckReplaceProc(Player *p, Vehicle *v);

static CheckReplaceProc * const _veh_check_replace_proc[] = {
	AiChooseTrainToReplaceWith,
	AiChooseRoadVehToReplaceWith,
	AiChooseShipToReplaceWith,
	AiChooseAircraftToReplaceWith,
};

typedef void DoReplaceProc(Player *p);
static DoReplaceProc * const _veh_do_replace_proc[] = {
	AiHandleReplaceTrain,
	AiHandleReplaceRoadVeh,
	AiHandleReplaceShip,
	AiHandleReplaceAircraft
};

static void AiStateCheckReplaceVehicle(Player *p)
{
	Vehicle *v = p->ai.cur_veh;

	if (v->type == 0 || v->owner != _current_player || v->type > VEH_Ship || _veh_check_replace_proc[v->type - VEH_Train](p, v) == -1) {
		p->ai.state = AIS_VEH_LOOP;
	} else {
		p->ai.state_counter = 0;
		p->ai.state = AIS_VEH_DO_REPLACE_VEHICLE;
	}
}

static void AiStateDoReplaceVehicle(Player *p)
{
	Vehicle *v = p->ai.cur_veh;
	p->ai.state = AIS_VEH_LOOP;
	// vehicle is not owned by the player anymore, something went very wrong.
	if (v->type == 0 || v->owner != _current_player)
		return;
	_veh_do_replace_proc[v->type - VEH_Train](p);
}

typedef struct FoundRoute {
	int distance;
	byte cargo;
	void *from;
	void *to;
} FoundRoute;

static Town *AiFindRandomTown(void)
{
	Town *t = GetTown(RandomRange(_total_towns));
	return (t->xy != 0) ? t : NULL;
}

static Industry *AiFindRandomIndustry(void)
{
	Industry *i = GetIndustry(RandomRange(_total_industries));
	return (i->xy != 0) ? i : NULL;
}

static void AiFindSubsidyIndustryRoute(FoundRoute *fr)
{
	uint i;
	byte cargo;
	Subsidy *s;
	Industry *from, *to_ind;
	Town *to_tow;
	TileIndex to_xy;

	// initially error
	fr->distance = -1;

	// Randomize subsidy index..
	i = RandomRange(lengthof(_subsidies) * 3);
	if (i >= lengthof(_subsidies))
		return;

	s = &_subsidies[i];

	// Don't want passengers or mail
	cargo = s->cargo_type;
	if (cargo == 0xFF || cargo == CT_PASSENGERS || cargo == CT_MAIL || s->age > 7)
		return;
	fr->cargo = cargo;

	fr->from = from = GetIndustry(s->from);

	if (cargo == CT_GOODS || cargo == CT_FOOD) {
		to_tow = GetTown(s->to);
		if (to_tow->population < (uint32)(cargo == CT_FOOD ? 200 : 900))
			return; // error
		fr->to = to_tow;
		to_xy = to_tow->xy;
	} else {
		to_ind = GetIndustry(s->to);
		fr->to = to_ind;
		to_xy = to_ind->xy;
	}

	fr->distance = DistanceManhattan(from->xy, to_xy);
}

static void AiFindSubsidyPassengerRoute(FoundRoute *fr)
{
	uint i;
	Subsidy *s;
	Town *from,*to;

	// initially error
	fr->distance = -1;

	// Randomize subsidy index..
	i = RandomRange(lengthof(_subsidies) * 3);
	if (i >= lengthof(_subsidies))
		return;

	s = &_subsidies[i];

	// Only want passengers
	if (s->cargo_type != CT_PASSENGERS || s->age > 7)
		return;
	fr->cargo = s->cargo_type;

	fr->from = from = GetTown(s->from);
	fr->to = to = GetTown(s->to);

	// They must be big enough
	if (from->population < 400 || to->population < 400)
		return;

	fr->distance = DistanceManhattan(from->xy, to->xy);
}

static void AiFindRandomIndustryRoute(FoundRoute *fr)
{
	Industry *i,*i2;
	Town *t;
	uint32 r;
	byte cargo;

	// initially error
	fr->distance = -1;

	r = Random();

	// pick a source
	fr->from = i = AiFindRandomIndustry();
	if (i == NULL)
		return;

	// pick a random produced cargo
	cargo = i->produced_cargo[0];
	if (r&1 && i->produced_cargo[1] != 0xFF)
		cargo = i->produced_cargo[1];

	fr->cargo = cargo;

	// don't allow passengers
	if (cargo == 0xFF || cargo == CT_PASSENGERS)
		return;

	if (cargo != CT_GOODS && cargo != CT_FOOD) {
		// pick a dest, and see if it can receive
		i2 = AiFindRandomIndustry();
		if (i2 == NULL || i == i2 || !(i2->accepts_cargo[0] == cargo || i2->accepts_cargo[1] == cargo || i2->accepts_cargo[2] == cargo))
			return;

		fr->to = i2;
		fr->distance = DistanceManhattan(i->xy, i2->xy);
	} else {
		// pick a dest town, and see if it's big enough
		t = AiFindRandomTown();
		if (t == NULL || t->population < (uint32)(cargo == CT_FOOD ? 200 : 900))
			return;

		fr->to = t;
		fr->distance = DistanceManhattan(i->xy, t->xy);
	}
}

static void AiFindRandomPassengerRoute(FoundRoute *fr)
{
	uint32 r;
	Town *source, *dest;

	// initially error
	fr->distance = -1;

	r = Random();

	fr->from = source = AiFindRandomTown();
	if (source == NULL || source->population < 400)
		return;

	fr->to = dest = AiFindRandomTown();
	if (dest == NULL || source == dest || dest->population < 400)
		return;

	fr->distance = DistanceManhattan(source->xy, dest->xy);
}

// Warn: depends on 'xy' being the first element in both Town and Industry
#define GET_TOWN_OR_INDUSTRY_TILE(p) (((Town*)(p))->xy)

static bool AiCheckIfRouteIsGood(Player *p, FoundRoute *fr, byte bitmask)
{
	TileIndex from_tile, to_tile;
	Station *st;
	int dist, cur;
	uint same_station = 0;

	// Make sure distance to closest station is < 37 pixels.
	from_tile = GET_TOWN_OR_INDUSTRY_TILE(fr->from);
	to_tile = GET_TOWN_OR_INDUSTRY_TILE(fr->to);

	dist = 0xFFFF;
	FOR_ALL_STATIONS(st) if (st->xy != 0 && st->owner == _current_player) {
		cur = DistanceMax(from_tile, st->xy);
		if (cur < dist) dist = cur;
		cur = DistanceMax(to_tile, st->xy);
		if (cur < dist) dist = cur;
		if (to_tile == from_tile && st->xy == to_tile)
		    same_station++;
	}

	// To prevent the AI from building ten busstations in the same town, do some calculations
	//  For each road or airport station, we want 350 of population!
	if ((bitmask == 2 || bitmask == 4) && same_station > 2 && ((Town *)(fr->from))->population < same_station * 350)
	    return false;

	if (dist != 0xFFFF && dist > 37)
		return false;

	if (p->ai.route_type_mask != 0 && !(p->ai.route_type_mask&bitmask) && !CHANCE16(1,5))
		return false;

	if (fr->cargo == CT_PASSENGERS || fr->cargo == CT_MAIL) {
		if (((Town*)fr->from)->pct_pass_transported > 0x99 ||
				((Town*)fr->to)->pct_pass_transported > 0x99)
			return false;

		// Make sure it has a reasonably good rating
		if ( ((Town*)fr->from)->ratings[_current_player] < -100 ||
				((Town*)fr->to)->ratings[_current_player] < -100)
			return false;
	} else {
		Industry *i = (Industry*)fr->from;

		if (i->pct_transported[fr->cargo != i->produced_cargo[0]] > 0x99 ||
				i->total_production[fr->cargo != i->produced_cargo[0]] == 0)
			return false;
	}

	p->ai.route_type_mask |= bitmask;
	return true;
}

static byte AiGetDirectionBetweenTiles(TileIndex a, TileIndex b)
{
	byte i = (TileX(a) < TileX(b)) ? 1 : 0;
	if (TileY(a) >= TileY(b)) i ^= 3;
	return i;
}

static TileIndex AiGetPctTileBetween(TileIndex a, TileIndex b, byte pct)
{
	return TileXY(
		TileX(a) + ((TileX(b) - TileX(a)) * pct >> 8),
		TileY(a) + ((TileY(b) - TileY(a)) * pct >> 8)
	);
}

static void AiWantLongIndustryRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {
		// look for one from the subsidy list
		AiFindSubsidyIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 60, 90+1))
			break;

		// try a random one
		AiFindRandomIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 60, 90+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	if (!AiCheckIfRouteIsGood(p, &fr, 1))
		return;

	// Fill the source field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);

	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 9;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.unk6 = 1;
	p->ai.src.unk7 = 0;
	p->ai.src.buildcmd_a = 0x24;
	p->ai.src.buildcmd_b = 0xFF;
	p->ai.src.direction = AiGetDirectionBetweenTiles(
			p->ai.src.spec_tile,
			p->ai.dst.spec_tile
		);
	p->ai.src.cargo = fr.cargo | 0x80;

	// Fill the dest field

	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 9;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.unk6 = 1;
	p->ai.dst.unk7 = 0;
	p->ai.dst.buildcmd_a = 0x34;
	p->ai.dst.buildcmd_b = 0xFF;
	p->ai.dst.direction = AiGetDirectionBetweenTiles(
			p->ai.dst.spec_tile,
			p->ai.src.spec_tile
		);
	p->ai.dst.cargo = fr.cargo;

	// Fill middle field 1
	p->ai.mid1.spec_tile = AiGetPctTileBetween(
			p->ai.src.spec_tile,
			p->ai.dst.spec_tile,
			0x55
		);
	p->ai.mid1.use_tile = 0;
	p->ai.mid1.rand_rng = 6;
	p->ai.mid1.cur_building_rule = 0xFF;
	p->ai.mid1.unk6 = 2;
	p->ai.mid1.unk7 = 1;
	p->ai.mid1.buildcmd_a = 0x30;
	p->ai.mid1.buildcmd_b = 0xFF;
	p->ai.mid1.direction = p->ai.src.direction;
	p->ai.mid1.cargo = fr.cargo;

	// Fill middle field 2
	p->ai.mid2.spec_tile = AiGetPctTileBetween(
			p->ai.src.spec_tile,
			p->ai.dst.spec_tile,
			0xAA
		);
	p->ai.mid2.use_tile = 0;
	p->ai.mid2.rand_rng = 6;
	p->ai.mid2.cur_building_rule = 0xFF;
	p->ai.mid2.unk6 = 2;
	p->ai.mid2.unk7 = 1;
	p->ai.mid2.buildcmd_a = 0xFF;
	p->ai.mid2.buildcmd_b = 0xFF;
	p->ai.mid2.direction = p->ai.dst.direction;
	p->ai.mid2.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.num_wagons = 3;
	p->ai.build_kind = 2;
	p->ai.num_build_rec = 4;
	p->ai.num_loco_to_build = 2;
	p->ai.num_want_fullload = 2;
	p->ai.wagon_list[0] = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;

	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantMediumIndustryRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 40, 60+1))
			break;

		// try a random one
		AiFindRandomIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 40, 60+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	if (!AiCheckIfRouteIsGood(p, &fr, 1))
		return;

	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 9;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.unk6 = 1;
	p->ai.src.unk7 = 0;
	p->ai.src.buildcmd_a = 0x10;
	p->ai.src.buildcmd_b = 0xFF;
	p->ai.src.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.from),
			GET_TOWN_OR_INDUSTRY_TILE(fr.to)
		);
	p->ai.src.cargo = fr.cargo | 0x80;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 9;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.unk6 = 1;
	p->ai.dst.unk7 = 0;
	p->ai.dst.buildcmd_a = 0xFF;
	p->ai.dst.buildcmd_b = 0xFF;
	p->ai.dst.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.to),
			GET_TOWN_OR_INDUSTRY_TILE(fr.from)
		);
	p->ai.dst.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.num_wagons = 3;
	p->ai.build_kind = 1;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 1;
	p->ai.num_want_fullload = 1;
	p->ai.wagon_list[0] = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;
	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantShortIndustryRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 15, 40+1))
			break;

		// try a random one
		AiFindRandomIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 15, 40+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	if (!AiCheckIfRouteIsGood(p, &fr, 1))
		return;

	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 9;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.unk6 = 1;
	p->ai.src.unk7 = 0;
	p->ai.src.buildcmd_a = 0x10;
	p->ai.src.buildcmd_b = 0xFF;
	p->ai.src.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.from),
			GET_TOWN_OR_INDUSTRY_TILE(fr.to)
		);
	p->ai.src.cargo = fr.cargo | 0x80;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 9;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.unk6 = 1;
	p->ai.dst.unk7 = 0;
	p->ai.dst.buildcmd_a = 0xFF;
	p->ai.dst.buildcmd_b = 0xFF;
	p->ai.dst.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.to),
			GET_TOWN_OR_INDUSTRY_TILE(fr.from)
		);
	p->ai.dst.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.num_wagons = 2;
	p->ai.build_kind = 1;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 1;
	p->ai.num_want_fullload = 1;
	p->ai.wagon_list[0] = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;
	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantMailRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 60, 110+1))
			break;

		// try a random one
		AiFindRandomPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 60, 110+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	fr.cargo = CT_MAIL;
	if (!AiCheckIfRouteIsGood(p, &fr, 1))
		return;

	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 7;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.unk6 = 1;
	p->ai.src.unk7 = 0;
	p->ai.src.buildcmd_a = 0x24;
	p->ai.src.buildcmd_b = 0xFF;
	p->ai.src.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.from),
			GET_TOWN_OR_INDUSTRY_TILE(fr.to)
		);
	p->ai.src.cargo = fr.cargo;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 7;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.unk6 = 1;
	p->ai.dst.unk7 = 0;
	p->ai.dst.buildcmd_a = 0x34;
	p->ai.dst.buildcmd_b = 0xFF;
	p->ai.dst.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.to),
			GET_TOWN_OR_INDUSTRY_TILE(fr.from)
		);
	p->ai.dst.cargo = fr.cargo;

	// Fill middle field 1
	p->ai.mid1.spec_tile = AiGetPctTileBetween(
			GET_TOWN_OR_INDUSTRY_TILE(fr.from),
			GET_TOWN_OR_INDUSTRY_TILE(fr.to),
			0x55
		);
	p->ai.mid1.use_tile = 0;
	p->ai.mid1.rand_rng = 6;
	p->ai.mid1.cur_building_rule = 0xFF;
	p->ai.mid1.unk6 = 2;
	p->ai.mid1.unk7 = 1;
	p->ai.mid1.buildcmd_a = 0x30;
	p->ai.mid1.buildcmd_b = 0xFF;
	p->ai.mid1.direction = p->ai.src.direction;
	p->ai.mid1.cargo = fr.cargo;

	// Fill middle field 2
	p->ai.mid2.spec_tile = AiGetPctTileBetween(
			GET_TOWN_OR_INDUSTRY_TILE(fr.from),
			GET_TOWN_OR_INDUSTRY_TILE(fr.to),
			0xAA
		);
	p->ai.mid2.use_tile = 0;
	p->ai.mid2.rand_rng = 6;
	p->ai.mid2.cur_building_rule = 0xFF;
	p->ai.mid2.unk6 = 2;
	p->ai.mid2.unk7 = 1;
	p->ai.mid2.buildcmd_a = 0xFF;
	p->ai.mid2.buildcmd_b = 0xFF;
	p->ai.mid2.direction = p->ai.dst.direction;
	p->ai.mid2.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.num_wagons = 3;
	p->ai.build_kind = 2;
	p->ai.num_build_rec = 4;
	p->ai.num_loco_to_build = 2;
	p->ai.num_want_fullload = 0;
	p->ai.wagon_list[0] = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;
	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantPassengerRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 0, 55+1))
			break;

		// try a random one
		AiFindRandomPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 0, 55+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	fr.cargo = CT_PASSENGERS;
	if (!AiCheckIfRouteIsGood(p, &fr, 1))
		return;

	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 7;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.unk6 = 1;
	p->ai.src.unk7 = 0;
	p->ai.src.buildcmd_a = 0x10;
	p->ai.src.buildcmd_b = 0xFF;
	p->ai.src.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.from),
			GET_TOWN_OR_INDUSTRY_TILE(fr.to)
		);
	p->ai.src.cargo = fr.cargo;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 7;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.unk6 = 1;
	p->ai.dst.unk7 = 0;
	p->ai.dst.buildcmd_a = 0xFF;
	p->ai.dst.buildcmd_b = 0xFF;
	p->ai.dst.direction = AiGetDirectionBetweenTiles(
			GET_TOWN_OR_INDUSTRY_TILE(fr.to),
			GET_TOWN_OR_INDUSTRY_TILE(fr.from)
		);
	p->ai.dst.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.num_wagons = 2;
	p->ai.build_kind = 1;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 1;
	p->ai.num_want_fullload = 0;
	p->ai.wagon_list[0] = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;
	p->ai.state = AIS_BUILD_DEFAULT_RAIL_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantTrainRoute(Player *p)
{
	uint16 r;
	p->ai.railtype_to_use = GetBestRailtype(p);
	r = (uint16)Random();

	if (r > 0xD000) {
		AiWantLongIndustryRoute(p);
	} else if (r > 0x6000) {
		AiWantMediumIndustryRoute(p);
	} else if (r > 0x1000) {
		AiWantShortIndustryRoute(p);
	} else if (r > 0x800) {
		AiWantPassengerRoute(p);
	} else {
		AiWantMailRoute(p);
	}
}

static void AiWantLongRoadIndustryRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 35, 55+1))
			break;

		// try a random one
		AiFindRandomIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 35, 55+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	if (!AiCheckIfRouteIsGood(p, &fr, 2))
		return;

	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 9;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.buildcmd_a = 1;
	p->ai.src.direction = 0;
	p->ai.src.cargo = fr.cargo | 0x80;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 9;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.buildcmd_a = 0xFF;
	p->ai.dst.direction = 0;
	p->ai.dst.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 5;
	p->ai.num_want_fullload = 5;

//	p->ai.loco_id = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;

	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantMediumRoadIndustryRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 15, 40+1))
			break;

		// try a random one
		AiFindRandomIndustryRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 15, 40+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	if (!AiCheckIfRouteIsGood(p, &fr, 2))
		return;

	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 9;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.buildcmd_a = 1;
	p->ai.src.direction = 0;
	p->ai.src.cargo = fr.cargo | 0x80;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 9;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.buildcmd_a = 0xFF;
	p->ai.dst.direction = 0;
	p->ai.dst.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 3;
	p->ai.num_want_fullload = 3;

//	p->ai.loco_id = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;

	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantLongRoadPassengerRoute(Player *p)
{
	int i;
	FoundRoute fr;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 55, 180+1))
			break;

		// try a random one
		AiFindRandomPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance, 55, 180+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	fr.cargo = CT_PASSENGERS;

	if (!AiCheckIfRouteIsGood(p, &fr, 2))
		return;

	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 10;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.buildcmd_a = 1;
	p->ai.src.direction = 0;
	p->ai.src.cargo = CT_PASSENGERS;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 10;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.buildcmd_a = 0xFF;
	p->ai.dst.direction = 0;
	p->ai.dst.cargo = CT_PASSENGERS;

	// Fill common fields
	p->ai.cargo_type = CT_PASSENGERS;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 4;
	p->ai.num_want_fullload = 0;

//	p->ai.loco_id = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;

	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantPassengerRouteInsideTown(Player *p)
{
	int i;
	FoundRoute fr;
	Town *t;

	i = 60;
	for(;;) {
		// Find a town big enough
		t = AiFindRandomTown();
		if (t != NULL && t->population >= 700)
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	fr.cargo = CT_PASSENGERS;
	fr.from = fr.to = t;

	if (!AiCheckIfRouteIsGood(p, &fr, 2))
		return;

	// Fill the source field
	p->ai.src.spec_tile = t->xy;
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 10;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.buildcmd_a = 1;
	p->ai.src.direction = 0;
	p->ai.src.cargo = CT_PASSENGERS;

	// Fill the dest field
	p->ai.dst.spec_tile = t->xy;
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 10;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.buildcmd_a = 0xFF;
	p->ai.dst.direction = 0;
	p->ai.dst.cargo = CT_PASSENGERS;

	// Fill common fields
	p->ai.cargo_type = CT_PASSENGERS;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 2;
	p->ai.num_want_fullload = 0;

//	p->ai.loco_id = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;

	p->ai.state = AIS_BUILD_DEFAULT_ROAD_BLOCKS;
	p->ai.state_mode = -1;
	p->ai.state_counter = 0;
	p->ai.timeout_counter = 0;
}

static void AiWantRoadRoute(Player *p)
{
	uint16 r = (uint16)Random();

	if (r > 0x4000) {
		AiWantLongRoadIndustryRoute(p);
	} else if (r > 0x2000) {
		AiWantMediumRoadIndustryRoute(p);
	} else if (r > 0x1000) {
		AiWantLongRoadPassengerRoute(p);
	} else {
		AiWantPassengerRouteInsideTown(p);
	}

}

static void AiWantPassengerAircraftRoute(Player *p)
{
	FoundRoute fr;
	int i;

	i = 60;
	for(;;) {

		// look for one from the subsidy list
		AiFindSubsidyPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance,0,95+1))
			break;

		// try a random one
		AiFindRandomPassengerRoute(&fr);
		if (IS_INT_INSIDE(fr.distance,0,95+1))
			break;

		// only test 60 times
		if (--i == 0)
			return;
	}

	fr.cargo = CT_PASSENGERS;
	if (!AiCheckIfRouteIsGood(p, &fr, 4))
		return;


	// Fill the source field
	p->ai.src.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.to);
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 12;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.cargo = fr.cargo;

	// Fill the dest field
	p->ai.dst.spec_tile = GET_TOWN_OR_INDUSTRY_TILE(fr.from);
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 12;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.cargo = fr.cargo;

	// Fill common fields
	p->ai.cargo_type = fr.cargo;
	p->ai.build_kind = 0;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 1;
	p->ai.num_want_fullload = 1;
//	p->ai.loco_id = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;

	p->ai.state = AIS_AIRPORT_STUFF;
	p->ai.timeout_counter = 0;
}

static void AiWantOilRigAircraftRoute(Player *p)
{
	int i;
	FoundRoute fr;
	Town *t;
	Industry *in;

	i = 60;
	for(;;) {
		// Find a town
		t = AiFindRandomTown();
		if (t != NULL) {
			// Find a random oil rig industry
			in = GetIndustry(RandomRange(_total_industries));
			if (in != NULL && in->type == IT_OIL_RIG) {
				if (DistanceManhattan(t->xy, in->xy) < 60)
					break;
			}
		}

		// only test 60 times
		if (--i == 0)
			return;
	}

	fr.cargo = CT_PASSENGERS;
	fr.from = fr.to = t;

	if (!AiCheckIfRouteIsGood(p, &fr, 4))
		return;

	// Fill the source field
	p->ai.src.spec_tile = t->xy;
	p->ai.src.use_tile = 0;
	p->ai.src.rand_rng = 12;
	p->ai.src.cur_building_rule = 0xFF;
	p->ai.src.cargo = CT_PASSENGERS;

	// Fill the dest field
	p->ai.dst.spec_tile = in->xy;
	p->ai.dst.use_tile = 0;
	p->ai.dst.rand_rng = 5;
	p->ai.dst.cur_building_rule = 0xFF;
	p->ai.dst.cargo = CT_PASSENGERS;

	// Fill common fields
	p->ai.cargo_type = CT_PASSENGERS;
	p->ai.build_kind = 1;
	p->ai.num_build_rec = 2;
	p->ai.num_loco_to_build = 1;
	p->ai.num_want_fullload = 0;
//	p->ai.loco_id = INVALID_VEHICLE;
	p->ai.order_list_blocks[0] = 0;
	p->ai.order_list_blocks[1] = 1;
	p->ai.order_list_blocks[2] = 255;

	p->ai.state = AIS_AIRPORT_STUFF;
	p->ai.timeout_counter = 0;
}

static void AiWantAircraftRoute(Player *p)
{
	uint16 r = (uint16)Random();

	if (r >= 0x2AAA || _date < 0x3912) {
		AiWantPassengerAircraftRoute(p);
	} else {
		AiWantOilRigAircraftRoute(p);
	}
}

static void AiWantShipRoute(Player *p)
{
	// XXX
//	error("AiWaitShipRoute");
}



static void AiStateWantNewRoute(Player *p)
{
	uint16 r;
	int i;

	if (p->player_money < AiGetBasePrice(p) * 500) {
		p->ai.state = AIS_0;
		return;
	}

	i = 200;
	for(;;) {
		r = (uint16)Random();

		if (_patches.ai_disable_veh_train && _patches.ai_disable_veh_roadveh &&
			_patches.ai_disable_veh_aircraft && _patches.ai_disable_veh_ship)
			return;

		if (r < 0x7626) {
			if (_patches.ai_disable_veh_train) continue;
			AiWantTrainRoute(p);
		} else if (r < 0xC4EA) {
			if (_patches.ai_disable_veh_roadveh) continue;
			AiWantRoadRoute(p);
		} else if (r < 0xD89B) {
			if (_patches.ai_disable_veh_aircraft) continue;
			AiWantAircraftRoute(p);
		} else {
			if (_patches.ai_disable_veh_ship) continue;
			AiWantShipRoute(p);
		}

		// got a route?
		if (p->ai.state != AIS_WANT_NEW_ROUTE)
			break;

		// time out?
		if (--i == 0) {
			if (++p->ai.state_counter == 556) p->ai.state = AIS_0;
			break;
		}
	}
}

static bool AiCheckTrackResources(TileIndex tile, const AiDefaultBlockData *p, byte cargo)
{
	uint values[NUM_CARGO];
	int rad;

	for(;p->mode != 4;p++) if (p->mode == 1) {
		TileIndex tile2 = TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));
		uint w;
		uint h;

		w = GB(p->attr, 1, 3);
		h = GB(p->attr, 4, 3);
		if (p->attr & 1) uintswap(w, h);


		if (_patches.modified_catchment) {
			rad = CA_TRAIN;
		} else {
			rad = 4;
		}

		if (cargo & 0x80) {
			GetProductionAroundTiles(values, tile2, w, h, rad);
			return values[cargo & 0x7F] != 0;
		} else {
			GetAcceptanceAroundTiles(values, tile2, w, h, rad);
			if (!(values[cargo] & ~7))
				return false;
			if (cargo != CT_MAIL)
				return true;
			return !!((values[cargo]>>1) & ~7);
		}
	}

	return true;
}

static int32 AiDoBuildDefaultRailTrack(TileIndex tile, const AiDefaultBlockData *p, byte flag)
{
	int32 ret;
	int32 total_cost = 0;
	Town *t = NULL;
	int rating = 0;
	int i,j,k;

	for(;;) {
		// This will seldomly overflow for valid reasons. Mask it to be on the safe side.
		uint c = TILE_MASK(tile + ToTileIndexDiff(p->tileoffs));

		_cleared_town = NULL;

		if (p->mode < 2) {
			if (p->mode == 0) {
				// Depot
				ret = DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, p->attr, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_TRAIN_DEPOT);
			} else {
				// Station
				ret = DoCommandByTile(c, (p->attr&1) | (p->attr>>4)<<8 | (p->attr>>1&7)<<16, _cur_ai_player->ai.railtype_to_use, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_RAILROAD_STATION);
			}

			if (CmdFailed(ret)) return CMD_ERROR;
			total_cost += ret;

clear_town_stuff:;
			if (_cleared_town != NULL) {
				if (t != NULL && t != _cleared_town)
					return CMD_ERROR;
				t = _cleared_town;
				rating += _cleared_town_rating;
			}
		} else if (p->mode == 2) {
			// Rail
			if (IsTileType(c, MP_RAILWAY))
				return CMD_ERROR;

			j = p->attr;
			k = 0;

			// Build the rail
			for(i=0; i!=6; i++,j>>=1) {
				if (j&1) {
					k = i;
					ret = DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, i, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_SINGLE_RAIL);
					if (CmdFailed(ret)) return CMD_ERROR;
					total_cost += ret;
				}
			}

			/* signals too? */
			if (j&3) {
				// Can't build signals on a road.
				if (IsTileType(c, MP_STREET)) return CMD_ERROR;

				if (flag & DC_EXEC) {
					j = 4 - j;
					do {
						ret = DoCommandByTile(c, k, 0, flag, CMD_BUILD_SIGNALS);
					} while (--j);
				} else {
					ret = _price.build_signals;
				}
				if (CmdFailed(ret)) return CMD_ERROR;
				total_cost += ret;
			}
		} else if (p->mode == 3) {
			//Clear stuff and then build single rail.
			if (GetTileSlope(c,NULL) != 0)
				return CMD_ERROR;
			ret = DoCommandByTile(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR);
			if (CmdFailed(ret)) return CMD_ERROR;
			total_cost += ret + _price.build_rail;

			if (flag & DC_EXEC) {
				DoCommandByTile(c, _cur_ai_player->ai.railtype_to_use, p->attr&1, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_SINGLE_RAIL);
			}

			goto clear_town_stuff;
		} else {
			// Unk
			break;
		}

		p++;
	}

	if (!(flag & DC_EXEC)) {
		if (t != NULL && rating > t->ratings[_current_player]) {
			return CMD_ERROR;
		}
	}

	return total_cost;
}

// Returns rule and cost
static int AiBuildDefaultRailTrack(TileIndex tile, byte p0, byte p1, byte p2, byte p3, byte dir, byte cargo, int32 *cost)
{
	int i;
	const AiDefaultRailBlock *p;

	for(i=0; (p = _default_rail_track_data[i]) != NULL; i++) {
		if (p->p0 == p0 && p->p1 == p1 && p->p2 == p2 && p->p3 == p3 &&
				(p->dir == 0xFF || p->dir == dir || ((p->dir-1)&3) == dir)) {
			*cost = AiDoBuildDefaultRailTrack(tile, p->data, DC_NO_TOWN_RATING);
			if (*cost != CMD_ERROR && AiCheckTrackResources(tile, p->data, cargo))
				return i;
		}
	}

	return -1;
}

static const byte _terraform_up_flags[] = {
	14, 13, 12, 11,
	10, 9, 8, 7,
	6, 5, 4, 3,
	2, 1, 0, 1,
	2, 1, 4, 1,
	2, 1, 8, 1,
	2, 1, 4, 2,
	2, 1
};

static const byte _terraform_down_flags[] = {
	1, 2, 3, 4,
	5, 6, 1, 8,
	9, 10, 8, 12,
	4, 2, 0, 0,
	1, 2, 3, 4,
	5, 6, 2, 8,
	9, 10, 1, 12,
	8, 4
};

static void AiDoTerraformLand(TileIndex tile, int dir, int unk, int mode)
{
	byte old_player;
	uint32 r;
	uint slope;
	uint h;

	old_player = _current_player;
	_current_player = OWNER_NONE;

	r = Random();

	unk &= (int)r;

	do {
		tile = TILE_MASK(tile + TileOffsByDir(dir));

		r >>= 2;
		if (r&2) {
			dir++;
			if (r&1)
				dir -= 2;
		}
		dir &= 3;
	} while (--unk >= 0);

	slope = GetTileSlope(tile, &h);

	if (slope != 0) {
		if (mode > 0 || (mode == 0 && !(r&0xC))) {
			// Terraform up
			DoCommandByTile(tile, _terraform_up_flags[slope-1], 1,
				DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
		} else if (h != 0) {
			// Terraform down
			DoCommandByTile(tile, _terraform_down_flags[slope-1], 0,
				DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
		}
	}

	_current_player = old_player;
}

static void AiStateBuildDefaultRailBlocks(Player *p)
{
	int i, j;
	AiBuildRec *aib;
	int rule;
	int32 cost;

	// time out?
	if (++p->ai.timeout_counter == 1388) {
		p->ai.state = AIS_DELETE_RAIL_BLOCKS;
		return;
	}

	// do the following 8 times
	i = 8;
	do {
		// check if we can build the default track
		aib = &p->ai.src;
		j = p->ai.num_build_rec;
		do {
			// this item has already been built?
			if (aib->cur_building_rule != 255)
				continue;

			// adjust the coordinate randomly,
			// to make sure that we find a position.
			aib->use_tile = AdjustTileCoordRandomly(aib->spec_tile, aib->rand_rng);

			// check if the track can be build there.
			rule = AiBuildDefaultRailTrack(aib->use_tile,
				p->ai.build_kind, p->ai.num_wagons,
				aib->unk6, aib->unk7,
				aib->direction, aib->cargo, &cost);

			if (rule == -1) {
				// cannot build, terraform after a while
				if (p->ai.state_counter >= 600) {
					AiDoTerraformLand(aib->use_tile, Random()&3, 3, (int8)p->ai.state_mode);
				}
				// also try the other terraform direction
				if (++p->ai.state_counter >= 1000) {
					p->ai.state_counter = 0;
					p->ai.state_mode = -p->ai.state_mode;
				}
			} else if (CheckPlayerHasMoney(cost)) {
				int32 r;
				// player has money, build it.
				aib->cur_building_rule = rule;

				r = AiDoBuildDefaultRailTrack(
					aib->use_tile,
					_default_rail_track_data[rule]->data,
					DC_EXEC | DC_NO_TOWN_RATING
				);
				assert(r != CMD_ERROR);
			}
		} while (++aib,--j);
	} while (--i);

	// check if we're done with all of them
	aib = &p->ai.src;
	j = p->ai.num_build_rec;
	do {
		if (aib->cur_building_rule == 255)
			return;
	} while (++aib,--j);

	// yep, all are done. switch state to the rail building state.
	p->ai.state = AIS_BUILD_RAIL;
	p->ai.state_mode = 255;
}

static TileIndex AiGetEdgeOfDefaultRailBlock(byte rule, TileIndex tile, byte cmd, int *dir)
{
	const AiDefaultBlockData *p = _default_rail_track_data[rule]->data;

	while (p->mode != 3 || !((--cmd) & 0x80)) p++;

	return tile + ToTileIndexDiff(p->tileoffs) - TileOffsByDir(*dir = p->attr);
}

typedef struct AiRailPathFindData {
	TileIndex tile;
	TileIndex tile2;
	int count;
	bool flag;
} AiRailPathFindData;

static bool AiEnumFollowTrack(TileIndex tile, AiRailPathFindData *a, int track, uint length, byte *state)
{
	if (a->flag)
		return true;

	if (length > 20 || tile == a->tile) {
		a->flag = true;
		return true;
	}

	if (DistanceMax(tile, a->tile2) < 4)
		a->count++;

	return false;
}

static bool AiDoFollowTrack(Player *p)
{
	AiRailPathFindData arpfd;
	arpfd.tile = p->ai.start_tile_a;
	arpfd.tile2 = p->ai.cur_tile_a;
	arpfd.flag = false;
	arpfd.count = 0;
	FollowTrack(p->ai.cur_tile_a + TileOffsByDir(p->ai.cur_dir_a), 0x2000 | TRANSPORT_RAIL, p->ai.cur_dir_a^2,
		(TPFEnumProc*)AiEnumFollowTrack, NULL, &arpfd);
	return arpfd.count > 8;
}

typedef struct AiRailFinder {
	TileIndex final_tile;
	byte final_dir;
	byte depth;
	byte recursive_mode;
	byte cur_best_dir;
	byte best_dir;
	byte cur_best_depth;
	byte best_depth;
	uint cur_best_dist;
	const byte *best_ptr;
	uint best_dist;
	TileIndex cur_best_tile, best_tile;
	TileIndex bridge_end_tile;
	Player *player;
	TileInfo ti;
} AiRailFinder;

static const byte _ai_table_15[4][8] = {
	{0, 0, 4, 3, 3, 1, 128+0, 64},
	{1, 1, 2, 0, 4, 2, 128+1, 65},
	{0, 2, 2, 3, 5, 1, 128+2, 66},
	{1, 3, 5, 0, 3, 2, 128+3, 67}
};

static const byte _dir_table_1[] = {3, 9, 12, 6};
static const byte _dir_table_2[] = {12, 6, 3, 9};


static bool AiIsTileBanned(Player *p, TileIndex tile, byte val) {
	int i;

	for(i=0; i!=p->ai.banned_tile_count; i++)
		if (p->ai.banned_tiles[i] == tile &&
				p->ai.banned_val[i] == val)
					return true;
	return false;
}

static void AiBanTile(Player *p, TileIndex tile, byte val) {
	int i;

	for(i=lengthof(p->ai.banned_tiles)-1; i!=0; i--) {
		p->ai.banned_tiles[i] = p->ai.banned_tiles[i-1];
		p->ai.banned_val[i] = p->ai.banned_val[i-1];
	}

	p->ai.banned_tiles[0] = tile;
	p->ai.banned_val[0] = val;

	if (p->ai.banned_tile_count != lengthof(p->ai.banned_tiles))
		p->ai.banned_tile_count++;
}

static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir);

static bool AiCheckRailPathBetter(AiRailFinder *arf, const byte *p)
{
	bool better = false;

	if (arf->recursive_mode < 1) {
		// Mode is 0. This means destination has not been found yet.
		// If the found path is shorter than the current one, remember it.
		if (arf->cur_best_dist < arf->best_dist) {
			arf->best_dir = arf->cur_best_dir;
			arf->best_dist = arf->cur_best_dist;
			arf->best_ptr = p;
			arf->best_tile = arf->cur_best_tile;
			better = true;
		}
	} else if (arf->recursive_mode > 1) {
		// Mode is 2.
		if (arf->best_dist != 0 || arf->cur_best_depth < arf->best_depth) {
			arf->best_depth = arf->cur_best_depth;
			arf->best_dist = 0;
			arf->best_ptr = p;
			arf->best_tile = 0;
			better = true;
		}
	}
	arf->recursive_mode = 0;
	arf->cur_best_dist = (uint)-1;
	arf->cur_best_depth = 0xff;

	return better;
}

static inline void AiCheckBuildRailBridgeHere(AiRailFinder *arf, TileIndex tile, const byte *p)
{
	TileIndex tile_new;
	bool flag;

	int dir2 = p[0] & 3;

	FindLandscapeHeightByTile(&arf->ti, tile);

	if (arf->ti.tileh == _dir_table_1[dir2] || (arf->ti.tileh==0 && arf->ti.z!=0)) {
		tile_new = tile;
		// Allow bridges directly over bottom tiles
		flag = arf->ti.z == 0;
		for(;;) {
			if ((TileIndexDiff)tile_new < -TileOffsByDir(dir2)) return; // Wraping around map, no bridge possible!
			tile_new = TILE_MASK(tile_new + TileOffsByDir(dir2));
			FindLandscapeHeightByTile(&arf->ti, tile_new);
			if (arf->ti.tileh != 0 || arf->ti.type == MP_CLEAR || arf->ti.type == MP_TREES) {
				if (!flag) return;
				break;
			}
			if (arf->ti.type != MP_WATER && arf->ti.type != MP_RAILWAY && arf->ti.type != MP_STREET)
				return;
			flag = true;
		}

		// Is building a (rail)bridge possible at this place (type doesn't matter)?
		if (CmdFailed(DoCommandByTile(tile_new, tile, 0 | arf->player->ai.railtype_to_use << 8,
			DC_AUTO, CMD_BUILD_BRIDGE)) )
				return;
		AiBuildRailRecursive(arf, tile_new, dir2);

		// At the bottom depth, check if the new path is better than the old one.
		if (arf->depth == 1) {
			if (AiCheckRailPathBetter(arf, p))
				arf->bridge_end_tile = tile_new;
		}
	}
}

static inline void AiCheckBuildRailTunnelHere(AiRailFinder *arf, TileIndex tile, const byte *p)
{
	FindLandscapeHeightByTile(&arf->ti, tile);

	if (arf->ti.tileh == _dir_table_2[p[0]&3] && arf->ti.z!=0) {
		int32 cost = DoCommandByTile(tile, arf->player->ai.railtype_to_use, 0, DC_AUTO, CMD_BUILD_TUNNEL);

		if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
			AiBuildRailRecursive(arf, _build_tunnel_endtile, p[0]&3);
			if (arf->depth == 1) {
				AiCheckRailPathBetter(arf, p);
			}
		}
	}
}


static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir)
{
	const byte *p;

	tile = TILE_MASK(tile + TileOffsByDir(dir));

	// Reached destination?
	if (tile == arf->final_tile) {
		if (arf->final_dir != (dir^2)) {
			if (arf->recursive_mode != 2)
				arf->recursive_mode = 1;
		} else if (arf->recursive_mode != 2) {
			arf->recursive_mode = 2;
			arf->cur_best_depth = arf->depth;
		} else {
			if (arf->depth < arf->cur_best_depth)
				arf->cur_best_depth = arf->depth;
		}
		return;
	}

	// Depth too deep?
	if (arf->depth >= 4) {
		uint dist = DistanceMaxPlusManhattan(tile, arf->final_tile);
		if (dist < arf->cur_best_dist) {
			// Store the tile that is closest to the final position.
			arf->cur_best_depth = arf->depth;
			arf->cur_best_dist = dist;
			arf->cur_best_tile = tile;
			arf->cur_best_dir = dir;
		}
		return;
	}

	// Increase recursion depth
	arf->depth++;

	// Grab pointer to list of stuff that is possible to build
	p = _ai_table_15[dir];

	// Try to build a single rail in all directions.
	FindLandscapeHeightByTile(&arf->ti, tile);
	if (arf->ti.z == 0) {
		p += 6;
	} else {
		do {
			// Make sure the tile is not in the list of banned tiles and that a rail can be built here.
			if (!AiIsTileBanned(arf->player, tile, p[0]) &&
					!CmdFailed(DoCommandByTile(tile, arf->player->ai.railtype_to_use, p[0], DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL))) {
				AiBuildRailRecursive(arf, tile, p[1]);
			}

			// At the bottom depth?
			if (arf->depth == 1) {
				AiCheckRailPathBetter(arf, p);
			}

			p += 2;
		} while (!(p[0]&0x80));
	}

	AiCheckBuildRailBridgeHere(arf, tile, p);
	AiCheckBuildRailTunnelHere(arf, tile, p+1);

	arf->depth--;
}


static const byte _dir_table_3[]= {0x25, 0x2A, 0x19, 0x16};

static void AiBuildRailConstruct(Player *p)
{
	AiRailFinder arf;
	int i;

	// Check too much lookahead?
	if (AiDoFollowTrack(p)) {
		p->ai.state_counter = (Random()&0xE)+6; // Destruct this amount of blocks
		p->ai.state_mode = 1; // Start destruct

		// Ban this tile and don't reach it for a while.
		AiBanTile(p, p->ai.cur_tile_a, FindFirstBit(GetRailTrackStatus(p->ai.cur_tile_a)));
		return;
	}

	// Setup recursive finder and call it.
	arf.player = p;
	arf.final_tile = p->ai.cur_tile_b;
	arf.final_dir = p->ai.cur_dir_b;
	arf.depth = 0;
	arf.recursive_mode = 0;
	arf.best_ptr = NULL;
	arf.cur_best_dist = (uint)-1;
	arf.cur_best_depth = 0xff;
	arf.best_dist = (uint)-1;
	arf.best_depth = 0xff;
	arf.cur_best_tile = 0;
	arf.best_tile = 0;
	AiBuildRailRecursive(&arf, p->ai.cur_tile_a, p->ai.cur_dir_a);

	// Reached destination?
	if (arf.recursive_mode == 2 && arf.cur_best_depth == 0) {
		p->ai.state_mode = 255;
		return;
	}

	// Didn't find anything to build?
	if (arf.best_ptr == NULL) {
		// Terraform some
		for(i=0; i!=5; i++)
			AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);

		if (++p->ai.state_counter == 21) {
			p->ai.state_counter = 40;
			p->ai.state_mode = 1;

			// Ban this tile
			AiBanTile(p, p->ai.cur_tile_a, FindFirstBit(GetRailTrackStatus(p->ai.cur_tile_a)));
		}
		return;
	}

	p->ai.cur_tile_a += TileOffsByDir(p->ai.cur_dir_a);

	if (arf.best_ptr[0]&0x80) {
		int i;
		int32 bridge_len = GetBridgeLength(arf.bridge_end_tile, p->ai.cur_tile_a);

		/*	Figure out what (rail)bridge type to build
				start with best bridge, then go down to worse and worse bridges
				unnecessary to check for worse bridge (i=0), since AI will always build that.
				AI is so fucked up that fixing this small thing will probably not solve a thing
		*/
		for (i = MAX_BRIDGES - 1; i != 0; i--) {
			if (CheckBridge_Stuff(i, bridge_len)) {
				int32 cost = DoCommandByTile(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO, CMD_BUILD_BRIDGE);
				if (!CmdFailed(cost) && cost < (p->player_money >> 5))
					break;
			}
		}

		// Build it
		DoCommandByTile(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);

		p->ai.cur_tile_a = arf.bridge_end_tile;
		p->ai.state_counter = 0;
	} else if (arf.best_ptr[0]&0x40) {
		// tunnel
		DoCommandByTile(p->ai.cur_tile_a, p->ai.railtype_to_use, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
		p->ai.cur_tile_a = _build_tunnel_endtile;
		p->ai.state_counter = 0;
	} else {
		// rail
		p->ai.cur_dir_a = arf.best_ptr[1];
		DoCommandByTile(p->ai.cur_tile_a, p->ai.railtype_to_use, arf.best_ptr[0],
			DC_EXEC | DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL);
		p->ai.state_counter = 0;
	}

	if (arf.best_tile != 0) {
		for(i=0; i!=2; i++)
			AiDoTerraformLand(arf.best_tile, arf.best_dir, 3, 0);
	}
}

static bool AiRemoveTileAndGoForward(Player *p)
{
	byte b;
	int bit;
	const byte *ptr;
	TileIndex tile = p->ai.cur_tile_a;
	int offs;
	TileIndex tilenew;

	if (IsTileType(tile, MP_TUNNELBRIDGE)) {
		if (!(_m[tile].m5 & 0x80)) {
			// Clear the tunnel and continue at the other side of it.
			if (CmdFailed(DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR)) )
				return false;
			p->ai.cur_tile_a = TILE_MASK(_build_tunnel_endtile - TileOffsByDir(p->ai.cur_dir_a));
			return true;
		}

		if (!(_m[tile].m5 & 0x40)) {

			// Check if the bridge points in the right direction.
			// This is not really needed the first place AiRemoveTileAndGoForward is called.
			if ((_m[tile].m5&1) != (p->ai.cur_dir_a&1))
				return false;

			// Find other side of bridge.
			offs = TileOffsByDir(p->ai.cur_dir_a);
			do {
				tile = TILE_MASK(tile - offs);
			} while (_m[tile].m5 & 0x40);

			tilenew = TILE_MASK(tile - offs);
			// And clear the bridge.
			if (CmdFailed(DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR)) )
				return false;
			p->ai.cur_tile_a = tilenew;
			return true;
		}
	}

	// Find the railtype at the position. Quit if no rail there.
	b = GetRailTrackStatus(tile) & _dir_table_3[p->ai.cur_dir_a];
	if (b == 0)
		return false;

	// Convert into a bit position that CMD_REMOVE_SINGLE_RAIL expects.
	bit = FindFirstBit(b);

	// Then remove and signals if there are any.
	if (IsTileType(tile, MP_RAILWAY) &&
			(_m[tile].m5&0xC0) == 0x40) {
		DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_REMOVE_SIGNALS);
	}

	// And also remove the rail.
	if (CmdFailed(DoCommandByTile(tile, 0, bit, DC_EXEC, CMD_REMOVE_SINGLE_RAIL)) )
		return false;

	// Find the direction at the other edge of the rail.
	ptr = _ai_table_15[p->ai.cur_dir_a^2];
	while (ptr[0] != bit) ptr+=2;
	p->ai.cur_dir_a = ptr[1] ^ 2;

	// And then also switch tile.
	p->ai.cur_tile_a = TILE_MASK(p->ai.cur_tile_a - TileOffsByDir(p->ai.cur_dir_a));

	return true;
}


static void AiBuildRailDestruct(Player *p)
{
	// Decrease timeout.
	if (!--p->ai.state_counter) {
		p->ai.state_mode = 2;
		p->ai.state_counter = 0;
	}

	// Don't do anything if the destination is already reached.
	if (p->ai.cur_tile_a == p->ai.start_tile_a)
		return;

	AiRemoveTileAndGoForward(p);
}


static void AiBuildRail(Player *p)
{
	int i;

	if (p->ai.state_mode < 1) {
		// Construct mode, build new rail.
		AiBuildRailConstruct(p);
	} else if (p->ai.state_mode == 1) {

		// Destruct mode, destroy the rail currently built.
		AiBuildRailDestruct(p);
	} else if (p->ai.state_mode == 2) {

		// Terraform some and then try building again.
		for(i=0; i!=4; i++)
			AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);

		if (++p->ai.state_counter == 4) {
			p->ai.state_counter = 0;
			p->ai.state_mode = 0;
		}
	}
}

static void AiStateBuildRail(Player *p)
{
	int num;
	AiBuildRec *aib;
	byte cmd;
	TileIndex tile;
	int dir;

	// time out?
	if (++p->ai.timeout_counter == 1388) {
		p->ai.state = AIS_DELETE_RAIL_BLOCKS;
		return;
	}

	// Currently building a rail between two points?
	if (p->ai.state_mode != 255) {
		AiBuildRail(p);

		// Alternate between edges
		swap_tile(&p->ai.start_tile_a, &p->ai.start_tile_b);
		swap_tile(&p->ai.cur_tile_a, &p->ai.cur_tile_b);
		swap_byte(&p->ai.start_dir_a, &p->ai.start_dir_b);
		swap_byte(&p->ai.cur_dir_a, &p->ai.cur_dir_b);
		return;
	}

	// Now, find two new points to build between
	num = p->ai.num_build_rec;
	aib = &p->ai.src;

	for(;;) {
		cmd = aib->buildcmd_a;
		aib->buildcmd_a = 255;
		if (cmd != 255) break;

		cmd = aib->buildcmd_b;
		aib->buildcmd_b = 255;
		if (cmd != 255) break;

		aib++;
		if (--num == 0) {
			p->ai.state = AIS_BUILD_RAIL_VEH;
			p->ai.state_counter = 0; // timeout
			return;
		}
	}

	// Find first edge to build from.
	tile = AiGetEdgeOfDefaultRailBlock(aib->cur_building_rule, aib->use_tile, cmd&3, &dir);
	p->ai.start_tile_a = tile;
	p->ai.cur_tile_a = tile;
	p->ai.start_dir_a = dir;
	p->ai.cur_dir_a = dir;
	DoCommandByTile(TILE_MASK(tile + TileOffsByDir(dir)), 0, (dir&1)?1:0, DC_EXEC, CMD_REMOVE_SINGLE_RAIL);

	assert(TILE_MASK(tile) != 0xFF00);

	// Find second edge to build to
	aib = (&p->ai.src) + ((cmd >> 4)&0xF);
	tile = AiGetEdgeOfDefaultRailBlock(aib->cur_building_rule, aib->use_tile, (cmd>>2)&3, &dir);
	p->ai.start_tile_b = tile;
	p->ai.cur_tile_b = tile;
	p->ai.start_dir_b = dir;
	p->ai.cur_dir_b = dir;
	DoCommandByTile(TILE_MASK(tile + TileOffsByDir(dir)), 0, (dir&1)?1:0, DC_EXEC, CMD_REMOVE_SINGLE_RAIL);

	assert(TILE_MASK(tile) != 0xFF00);

	// And setup state.
	p->ai.state_mode = 2;
	p->ai.state_counter = 0;
	p->ai.banned_tile_count = 0;
}

static int AiGetStationIdByDef(TileIndex tile, int id)
{
	const AiDefaultBlockData *p = _default_rail_track_data[id]->data;
	while (p->mode != 1) p++;
	return _m[TILE_ADD(tile, ToTileIndexDiff(p->tileoffs))].m2;
}

static void AiStateBuildRailVeh(Player *p)
{
	const AiDefaultBlockData *ptr;
	TileIndex tile;
	int i, veh;
	int cargo;
	int32 cost;
	Vehicle *v;
	uint loco_id;

	ptr = _default_rail_track_data[p->ai.src.cur_building_rule]->data;
	while (ptr->mode != 0) {	ptr++; }

	tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));

	cargo = p->ai.cargo_type;
	for(i=0;;) {
		if (p->ai.wagon_list[i] == INVALID_VEHICLE) {
			veh = _cargoc.ai_railwagon[p->ai.railtype_to_use][cargo];
			cost = DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE);
			if (CmdFailed(cost)) goto handle_nocash;
			p->ai.wagon_list[i] = _new_wagon_id;
			p->ai.wagon_list[i+1] = INVALID_VEHICLE;
			return;
		}
		if (cargo == CT_MAIL)
			cargo = CT_PASSENGERS;
		if (++i == p->ai.num_wagons * 2 - 1)
			break;
	}

	// Which locomotive to build?
	veh = AiChooseTrainToBuild(p->ai.railtype_to_use, p->player_money, (cargo!=CT_PASSENGERS)?1:0, tile);
	if (veh == -1) {
handle_nocash:
		// after a while, if AI still doesn't have cash, get out of this block by selling the wagons.
		if (++p->ai.state_counter == 1000) {
			for(i=0; p->ai.wagon_list[i] != INVALID_VEHICLE; i++) {
				cost = DoCommandByTile(tile, p->ai.wagon_list[i], 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
				assert(!CmdFailed(cost));
			}
			p->ai.state =	AIS_0;
		}
		return;
	}

	// Try to build the locomotive
	cost = DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE);
	assert(!CmdFailed(cost));
	loco_id = _new_train_id;

	// Sell a vehicle if the train is double headed.
	v = GetVehicle(loco_id);
	if (v->next != NULL) {
		i = p->ai.wagon_list[p->ai.num_wagons*2-2];
		p->ai.wagon_list[p->ai.num_wagons*2-2] = INVALID_VEHICLE;
		DoCommandByTile(tile, i, 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
	}

	// Move the wagons onto the train
	for(i=0; p->ai.wagon_list[i] != INVALID_VEHICLE; i++) {
		DoCommandByTile(tile, p->ai.wagon_list[i] | (loco_id << 16), 0, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
	}

	for(i=0; p->ai.order_list_blocks[i] != 0xFF; i++) {
		AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
		bool is_pass = (p->ai.cargo_type == CT_PASSENGERS ||
							p->ai.cargo_type == CT_MAIL ||
							(_opt.landscape==LT_NORMAL && p->ai.cargo_type == CT_VALUABLES));
		Order order;

		order.type = OT_GOTO_STATION;
		order.flags = 0;
		order.station = AiGetStationIdByDef(aib->use_tile, aib->cur_building_rule);

		if (!is_pass && i == 1) order.flags |= OF_UNLOAD;
		if (p->ai.num_want_fullload != 0 && (is_pass || i == 0))
			order.flags |= OF_FULL_LOAD;

		DoCommandByTile(0, loco_id + (i << 16),	PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
	}

	DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_TRAIN);

	DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);

	if (p->ai.num_want_fullload != 0)
		p->ai.num_want_fullload--;

	if (--p->ai.num_loco_to_build != 0) {
//		p->ai.loco_id = INVALID_VEHICLE;
		p->ai.wagon_list[0] = INVALID_VEHICLE;
	} else {
		p->ai.state =	AIS_0;
	}
}

static void AiStateDeleteRailBlocks(Player *p)
{
	int num;
	AiBuildRec *aib;
	const AiDefaultBlockData *b;

	num = p->ai.num_build_rec;
	aib = &p->ai.src;
	do {
		if (aib->cur_building_rule != 255) {
			b = _default_rail_track_data[aib->cur_building_rule]->data;
			while (b->mode != 4) {
				DoCommandByTile(TILE_ADD(aib->use_tile, ToTileIndexDiff(b->tileoffs)), 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
				b++;
			}
		}
	} while (++aib,--num);

	p->ai.state = AIS_0;
}

static bool AiCheckRoadResources(TileIndex tile, const AiDefaultBlockData *p, byte cargo)
{
	uint values[NUM_CARGO];
	int rad;

	if (_patches.modified_catchment) {
		rad = CA_TRUCK;		//Same as CA_BUS at the moment?
	} else {			//change that at some point?
		rad = 4;
	}

	for(;;p++) {
		if (p->mode == 4) {
			return true;
		} else if (p->mode == 1) {
			TileIndex tile2 = TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));

			if (cargo & 0x80) {
				GetProductionAroundTiles(values, tile2, 1, 1, rad);
				return values[cargo & 0x7F] != 0;
			} else {
				GetAcceptanceAroundTiles(values, tile2, 1, 1, rad);
				return (values[cargo]&~7) != 0;
			}
		}
	}
}

static bool _want_road_truck_station;
static int32 AiDoBuildDefaultRoadBlock(TileIndex tile, const AiDefaultBlockData *p, byte flag);

// Returns rule and cost
static int AiFindBestDefaultRoadBlock(TileIndex tile, byte direction, byte cargo, int32 *cost)
{
	int i;
	const AiDefaultRoadBlock *p;

	_want_road_truck_station = (cargo & 0x7F) != CT_PASSENGERS;

	for(i=0; (p = _road_default_block_data[i]) != NULL; i++) {
		if (p->dir == direction) {
			*cost = AiDoBuildDefaultRoadBlock(tile, p->data, 0);
			if (*cost != CMD_ERROR && AiCheckRoadResources(tile, p->data, cargo))
				return i;
		}
	}

	return -1;
}

static int32 AiDoBuildDefaultRoadBlock(TileIndex tile, const AiDefaultBlockData *p, byte flag)
{
	int32 ret;
	int32 total_cost = 0;
	Town *t = NULL;
	int rating = 0;
	int roadflag = 0;

	for(;p->mode != 4;p++) {
		uint c = TILE_MASK(tile + ToTileIndexDiff(p->tileoffs));

		_cleared_town = NULL;

		if (p->mode == 2) {
			if (IsTileType(c, MP_STREET) &&
					(_m[c].m5&0xF0)==0 &&
					(_m[c].m5&p->attr)!=0) {
				roadflag |= 2;

				// all bits are already built?
				if ((_m[c].m5&p->attr)==p->attr)
					continue;
			}

			ret = DoCommandByTile(c, p->attr, 0, flag | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD);
			if (CmdFailed(ret)) return CMD_ERROR;
			total_cost += ret;

			continue;
		}

		if (p->mode == 0) {
			// Depot
			ret = DoCommandByTile(c, p->attr, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_ROAD_DEPOT);
			goto clear_town_stuff;
		} else if (p->mode == 1) {
			if (_want_road_truck_station) {
				// Truck station
				ret = DoCommandByTile(c, p->attr, RS_TRUCK, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_ROAD_STOP);
			} else {
				// Bus station
				ret = DoCommandByTile(c, p->attr, RS_BUS, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_ROAD_STOP);
			}
clear_town_stuff:;

			if (CmdFailed(ret)) return CMD_ERROR;
			total_cost += ret;

			if (_cleared_town != NULL) {
				if (t != NULL && t != _cleared_town)
					return CMD_ERROR;
				t = _cleared_town;
				rating += _cleared_town_rating;
			}
		} else if (p->mode == 3) {
			if (flag & DC_EXEC)
				continue;

			if (GetTileSlope(c, NULL) != 0)
				return CMD_ERROR;

			if (!(IsTileType(c, MP_STREET) && (_m[c].m5 & 0xF0) == 0)) {
				ret = DoCommandByTile(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR);
				if (CmdFailed(ret)) return CMD_ERROR;
			}

		}
	}

	if (!_want_road_truck_station && !(roadflag&2))
		return CMD_ERROR;

	if (!(flag & DC_EXEC)) {
		if (t != NULL && rating > t->ratings[_current_player]) {
			return CMD_ERROR;
		}
	}
	return total_cost;
}

// Make sure the blocks are not too close to each other
static bool AiCheckBlockDistances(Player *p, TileIndex tile)
{
	AiBuildRec *aib;
	int num;

	num = p->ai.num_build_rec;
	aib = &p->ai.src;

	do {
		if (aib->cur_building_rule != 255) {
			if (DistanceManhattan(aib->use_tile, tile) < 9)
				return false;
		}
	} while (++aib, --num);

	return true;
}


static void AiStateBuildDefaultRoadBlocks(Player *p)
{
	int i, j;
	AiBuildRec *aib;
	int rule;
	int32 cost;

	// time out?
	if (++p->ai.timeout_counter == 1388) {
		p->ai.state = AIS_DELETE_RAIL_BLOCKS;
		return;
	}

	// do the following 8 times
	i = 8;
	do {
		// check if we can build the default track
		aib = &p->ai.src;
		j = p->ai.num_build_rec;
		do {
			// this item has already been built?
			if (aib->cur_building_rule != 255)
				continue;

			// adjust the coordinate randomly,
			// to make sure that we find a position.
			aib->use_tile = AdjustTileCoordRandomly(aib->spec_tile, aib->rand_rng);

			// check if the road can be built there.
			rule = AiFindBestDefaultRoadBlock(aib->use_tile,
				aib->direction, aib->cargo, &cost);

			if (rule == -1) {
				// cannot build, terraform after a while
				if (p->ai.state_counter >= 600) {
					AiDoTerraformLand(aib->use_tile, Random()&3, 3, (int8)p->ai.state_mode);
				}
				// also try the other terraform direction
				if (++p->ai.state_counter >= 1000) {
					p->ai.state_counter = 0;
					p->ai.state_mode = -p->ai.state_mode;
				}
			} else if (CheckPlayerHasMoney(cost) && AiCheckBlockDistances(p,aib->use_tile)) {
				int32 r;

				// player has money, build it.
				aib->cur_building_rule = rule;

				r = AiDoBuildDefaultRoadBlock(
					aib->use_tile,
					_road_default_block_data[rule]->data,
					DC_EXEC | DC_NO_TOWN_RATING
				);
				assert(r != CMD_ERROR);
			}
		} while (++aib,--j);
	} while (--i);

	// check if we're done with all of them
	aib = &p->ai.src;
	j = p->ai.num_build_rec;
	do {
		if (aib->cur_building_rule == 255)
			return;
	} while (++aib,--j);

	// yep, all are done. switch state to the rail building state.
	p->ai.state = AIS_BUILD_ROAD;
	p->ai.state_mode = 255;
}

typedef struct {
	TileIndex final_tile;
	byte final_dir;
	byte depth;
	byte recursive_mode;
	byte cur_best_dir;
	byte best_dir;
	byte cur_best_depth;
	byte best_depth;
	uint cur_best_dist;
	const byte *best_ptr;
	uint best_dist;
	TileIndex cur_best_tile, best_tile;
	TileIndex bridge_end_tile;
	Player *player;
	TileInfo ti;
} AiRoadFinder;

typedef struct AiRoadEnum {
	TileIndex dest;
	TileIndex best_tile;
	int best_track;
	uint best_dist;
} AiRoadEnum;

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

static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, int dir);

static bool AiCheckRoadPathBetter(AiRoadFinder *arf, const byte *p)
{
	bool better = false;

	if (arf->recursive_mode < 1) {
		// Mode is 0. This means destination has not been found yet.
		// If the found path is shorter than the current one, remember it.
		if (arf->cur_best_dist < arf->best_dist ||
			(arf->cur_best_dist == arf->best_dist && arf->cur_best_depth < arf->best_depth)) {
			arf->best_depth = arf->cur_best_depth;
			arf->best_dist = arf->cur_best_dist;
			arf->best_dir = arf->cur_best_dir;
			arf->best_ptr = p;
			arf->best_tile = arf->cur_best_tile;
			better = true;
		}
	} else if (arf->recursive_mode > 1) {
		// Mode is 2.
		if (arf->best_dist != 0 || arf->cur_best_depth < arf->best_depth) {
			arf->best_depth = arf->cur_best_depth;
			arf->best_dist = 0;
			arf->best_ptr = p;
			arf->best_tile = 0;
			better = true;
		}
	}
	arf->recursive_mode = 0;
	arf->cur_best_dist = (uint)-1;
	arf->cur_best_depth = 0xff;

	return better;
}


static bool AiEnumFollowRoad(TileIndex tile, AiRoadEnum *a, int track, uint length, byte *state)
{
	uint dist = DistanceManhattan(tile, a->dest);

	if (dist <= a->best_dist) {
		TileIndex tile2 = TILE_MASK(tile + TileOffsByDir(_dir_by_track[track]));

		if (IsTileType(tile2, MP_STREET) &&
				(_m[tile2].m5&0xF0) == 0) {
			a->best_dist = dist;
			a->best_tile = tile;
			a->best_track = track;
		}
	}

	return false;
}

static const uint16 _ai_road_table_and[4] = {
	0x1009,
	0x16,
	0x520,
	0x2A00,
};

static bool AiCheckRoadFinished(Player *p)
{
	AiRoadEnum are;
	TileIndex tile;
	int dir = p->ai.cur_dir_a;
	uint32 bits;
	int i;

	are.dest = p->ai.cur_tile_b;
	tile = TILE_MASK(p->ai.cur_tile_a + TileOffsByDir(dir));

	bits = GetTileTrackStatus(tile, TRANSPORT_ROAD) & _ai_road_table_and[dir];
	if (bits == 0) {
		return false;
	}

	are.best_dist = (uint)-1;

	for_each_bit(i, bits) {
		FollowTrack(tile, 0x3000 | TRANSPORT_ROAD, _dir_by_track[i], (TPFEnumProc*)AiEnumFollowRoad, NULL, &are);
	}

	if (DistanceManhattan(tile, are.dest) <= are.best_dist)
		return false;

	if (are.best_dist == 0)
		return true;

	p->ai.cur_tile_a = are.best_tile;
	p->ai.cur_dir_a = _dir_by_track[are.best_track];
	return false;
}


static bool AiBuildRoadHelper(TileIndex tile, int flags, int type)
{
	static const byte _road_bits[] = {
		8+2,
		1+4,
		1+8,
		4+2,
		1+2,
		8+4,
	};
	return !CmdFailed(DoCommandByTile(tile, _road_bits[type], 0, flags, CMD_BUILD_ROAD));
}

static inline void AiCheckBuildRoadBridgeHere(AiRoadFinder *arf, TileIndex tile, const byte *p)
{
	TileIndex tile_new;
	bool flag;

	int dir2 = p[0] & 3;

	FindLandscapeHeightByTile(&arf->ti, tile);
	if (arf->ti.tileh == _dir_table_1[dir2] || (arf->ti.tileh==0 && arf->ti.z!=0)) {
		tile_new = tile;
		// Allow bridges directly over bottom tiles
		flag = arf->ti.z == 0;
		for(;;) {
			if ((TileIndexDiff)tile_new < -TileOffsByDir(dir2)) return; // Wraping around map, no bridge possible!
			tile_new = TILE_MASK(tile_new + TileOffsByDir(dir2));
			FindLandscapeHeightByTile(&arf->ti, tile_new);
			if (arf->ti.tileh != 0 || arf->ti.type == MP_CLEAR || arf->ti.type == MP_TREES) {
				// Allow a bridge if either we have a tile that's water, rail or street,
				// or if we found an up tile.
				if (!flag) return;
				break;
			}
			if (arf->ti.type != MP_WATER && arf->ti.type != MP_RAILWAY && arf->ti.type != MP_STREET)
				return;
			flag = true;
		}

		// Is building a (rail)bridge possible at this place (type doesn't matter)?
		if (CmdFailed(DoCommandByTile(tile_new, tile, 0x8000, DC_AUTO, CMD_BUILD_BRIDGE)))
			return;
		AiBuildRoadRecursive(arf, tile_new, dir2);

		// At the bottom depth, check if the new path is better than the old one.
		if (arf->depth == 1) {
			if (AiCheckRoadPathBetter(arf, p))
				arf->bridge_end_tile = tile_new;
		}
	}
}

static inline void AiCheckBuildRoadTunnelHere(AiRoadFinder *arf, TileIndex tile, const byte *p)
{
	FindLandscapeHeightByTile(&arf->ti, tile);

	if (arf->ti.tileh == _dir_table_2[p[0]&3] && arf->ti.z!=0) {
		int32 cost = DoCommandByTile(tile, 0x200, 0, DC_AUTO, CMD_BUILD_TUNNEL);

		if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
			AiBuildRoadRecursive(arf, _build_tunnel_endtile, p[0]&3);
			if (arf->depth == 1) {
				AiCheckRoadPathBetter(arf, p);
			}
		}
	}
}



static void AiBuildRoadRecursive(AiRoadFinder *arf, TileIndex tile, int dir)
{
	const byte *p;

	tile = TILE_MASK(tile + TileOffsByDir(dir));

	// Reached destination?
	if (tile == arf->final_tile) {
		if ((arf->final_dir^2) == dir) {
			arf->recursive_mode = 2;
			arf->cur_best_depth = arf->depth;
		}
		return;
	}

	// Depth too deep?
	if (arf->depth >= 4) {
		uint dist = DistanceMaxPlusManhattan(tile, arf->final_tile);
		if (dist < arf->cur_best_dist) {
			// Store the tile that is closest to the final position.
			arf->cur_best_dist = dist;
			arf->cur_best_tile = tile;
			arf->cur_best_dir = dir;
			arf->cur_best_depth = arf->depth;
		}
		return;
	}

	// Increase recursion depth
	arf->depth++;

	// Grab pointer to list of stuff that is possible to build
	p = _ai_table_15[dir];

	// Try to build a single rail in all directions.
	FindLandscapeHeightByTile(&arf->ti, tile);
	if (arf->ti.z == 0) {
		p += 6;
	} else {
		do {
			// Make sure that a road can be built here.
			if (AiBuildRoadHelper(tile, DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, p[0])) {
				AiBuildRoadRecursive(arf, tile, p[1]);
			}

			// At the bottom depth?
			if (arf->depth == 1) {
				AiCheckRoadPathBetter(arf, p);
			}

			p += 2;
		} while (!(p[0]&0x80));
	}

	AiCheckBuildRoadBridgeHere(arf, tile, p);
	AiCheckBuildRoadTunnelHere(arf, tile, p+1);

	arf->depth--;
}

int sw;


static void AiBuildRoadConstruct(Player *p)
{
	AiRoadFinder arf;
	int i;
	TileIndex tile;

	// Reached destination?
	if (AiCheckRoadFinished(p)) {
		p->ai.state_mode = 255;
		return;
	}

	// Setup recursive finder and call it.
	arf.player = p;
	arf.final_tile = p->ai.cur_tile_b;
	arf.final_dir = p->ai.cur_dir_b;
	arf.depth = 0;
	arf.recursive_mode = 0;
	arf.best_ptr = NULL;
	arf.cur_best_dist = (uint)-1;
	arf.cur_best_depth = 0xff;
	arf.best_dist = (uint)-1;
	arf.best_depth =  0xff;
	arf.cur_best_tile = 0;
	arf.best_tile = 0;
	AiBuildRoadRecursive(&arf, p->ai.cur_tile_a, p->ai.cur_dir_a);

	// Reached destination?
	if (arf.recursive_mode == 2 && arf.cur_best_depth == 0) {
		p->ai.state_mode = 255;
		return;
	}

	// Didn't find anything to build?
	if (arf.best_ptr == NULL) {
		// Terraform some
do_some_terraform:
		for(i=0; i!=5; i++)
			AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);

		if (++p->ai.state_counter == 21) {
			p->ai.state_mode = 1;

			p->ai.cur_tile_a = TILE_MASK(p->ai.cur_tile_a + TileOffsByDir(p->ai.cur_dir_a));
			p->ai.cur_dir_a ^= 2;
			p->ai.state_counter = 0;
		}
		return;
	}

	tile = TILE_MASK(p->ai.cur_tile_a + TileOffsByDir(p->ai.cur_dir_a));

	if (arf.best_ptr[0]&0x80) {
		int i;
		int32 bridge_len;
		p->ai.cur_tile_a = arf.bridge_end_tile;
		bridge_len = GetBridgeLength(tile, p->ai.cur_tile_a); // tile

		/*	Figure out what (road)bridge type to build
				start with best bridge, then go down to worse and worse bridges
				unnecessary to check for worse bridge (i=0), since AI will always build that.
				AI is so fucked up that fixing this small thing will probably not solve a thing
		*/
		for(i = 10; i != 0; i--) {
			if (CheckBridge_Stuff(i, bridge_len)) {
				int32 cost = DoCommandByTile(tile, p->ai.cur_tile_a, i + (0x80 << 8), DC_AUTO, CMD_BUILD_BRIDGE);
				if (!CmdFailed(cost) && cost < (p->player_money >> 5))
					break;
			}
		}

		// Build it
		DoCommandByTile(tile, p->ai.cur_tile_a, i + (0x80 << 8), DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);

		p->ai.state_counter = 0;
	} else if (arf.best_ptr[0]&0x40) {
		// tunnel
		DoCommandByTile(tile, 0x200, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
		p->ai.cur_tile_a = _build_tunnel_endtile;
		p->ai.state_counter = 0;
	} else {

		// road
		if (!AiBuildRoadHelper(tile, DC_EXEC | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, arf.best_ptr[0]))
			goto do_some_terraform;

		p->ai.cur_dir_a = arf.best_ptr[1];
		p->ai.cur_tile_a = tile;
		p->ai.state_counter = 0;
	}

	if (arf.best_tile != 0) {
		for(i=0; i!=2; i++)
			AiDoTerraformLand(arf.best_tile, arf.best_dir, 3, 0);
	}
}


static void AiBuildRoad(Player *p)
{
	int i;

	if (p->ai.state_mode < 1) {
		// Construct mode, build new road.
		AiBuildRoadConstruct(p);
	} else if (p->ai.state_mode == 1) {
		// Destruct mode, not implemented for roads.
		p->ai.state_mode = 2;
		p->ai.state_counter = 0;
	} else if (p->ai.state_mode == 2) {

		// Terraform some and then try building again.
		for(i=0; i!=4; i++)
			AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);

		if (++p->ai.state_counter == 4) {
			p->ai.state_counter = 0;
			p->ai.state_mode = 0;
		}
	}
}

static TileIndex AiGetRoadBlockEdge(byte rule, TileIndex tile, int *dir)
{
	const AiDefaultBlockData *p = _road_default_block_data[rule]->data;
	while (p->mode != 1) p++;
	*dir = p->attr;
	return TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));
}


static void AiStateBuildRoad(Player *p)
{
	int num;
	AiBuildRec *aib;
	byte cmd;
	TileIndex tile;
	int dir;

	// time out?
	if (++p->ai.timeout_counter == 1388) {
		p->ai.state = AIS_DELETE_ROAD_BLOCKS;
		return;
	}

	// Currently building a road between two points?
	if (p->ai.state_mode != 255) {
		AiBuildRoad(p);

		// Alternate between edges
		swap_tile(&p->ai.start_tile_a, &p->ai.start_tile_b);
		swap_tile(&p->ai.cur_tile_a, &p->ai.cur_tile_b);
		swap_byte(&p->ai.start_dir_a, &p->ai.start_dir_b);
		swap_byte(&p->ai.cur_dir_a, &p->ai.cur_dir_b);

		sw ^= 1;
		return;
	}

	// Now, find two new points to build between
	num = p->ai.num_build_rec;
	aib = &p->ai.src;

	for(;;) {
		cmd = aib->buildcmd_a;
		aib->buildcmd_a = 255;
		if (cmd != 255) break;

		aib++;
		if (--num == 0) {
			p->ai.state = AIS_BUILD_ROAD_VEHICLES;
			return;
		}
	}

	// Find first edge to build from.
	tile = AiGetRoadBlockEdge(aib->cur_building_rule, aib->use_tile, &dir);
	p->ai.start_tile_a = tile;
	p->ai.cur_tile_a = tile;
	p->ai.start_dir_a = dir;
	p->ai.cur_dir_a = dir;

	// Find second edge to build to
	aib = (&p->ai.src) + (cmd&0xF);
	tile = AiGetRoadBlockEdge(aib->cur_building_rule, aib->use_tile, &dir);
	p->ai.start_tile_b = tile;
	p->ai.cur_tile_b = tile;
	p->ai.start_dir_b = dir;
	p->ai.cur_dir_b = dir;

	// And setup state.
	p->ai.state_mode = 2;
	p->ai.state_counter = 0;
	p->ai.banned_tile_count = 0;
}

static int AiGetStationIdFromRoadBlock(TileIndex tile, int id)
{
	const AiDefaultBlockData *p = _road_default_block_data[id]->data;
	while (p->mode != 1) p++;
	return _m[TILE_ADD(tile, ToTileIndexDiff(p->tileoffs))].m2;
}

static void AiStateBuildRoadVehicles(Player *p)
{
	const AiDefaultBlockData *ptr;
	TileIndex tile;
	uint loco_id;
	int veh, i;

	ptr = _road_default_block_data[p->ai.src.cur_building_rule]->data;
	for(;ptr->mode != 0;ptr++) {}
	tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));

	veh = AiChooseRoadVehToBuild(p->ai.cargo_type, p->player_money, tile);
	if (veh == -1) {
		p->ai.state = AIS_0;
		return;
	}

	if (CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_ROAD_VEH))) return;

	loco_id = _new_roadveh_id;

	for(i=0; p->ai.order_list_blocks[i] != 0xFF; i++) {
		AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
		bool is_pass = (p->ai.cargo_type == CT_PASSENGERS ||
							p->ai.cargo_type == CT_MAIL ||
							(_opt.landscape==LT_NORMAL && p->ai.cargo_type == CT_VALUABLES));
		Order order;

		order.type = OT_GOTO_STATION;
		order.flags = 0;
		order.station = AiGetStationIdFromRoadBlock(aib->use_tile, aib->cur_building_rule);

		if (!is_pass && i == 1) order.flags |= OF_UNLOAD;
		if (p->ai.num_want_fullload != 0 && (is_pass || i == 0))
			order.flags |= OF_FULL_LOAD;

		DoCommandByTile(0, loco_id + (i << 16),	PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
	}

	DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_ROADVEH);

	DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);

	if (p->ai.num_want_fullload != 0)
		p->ai.num_want_fullload--;

	if (--p->ai.num_loco_to_build == 0) {
		p->ai.state =	AIS_0;
	}
}

static void AiStateDeleteRoadBlocks(Player *p)
{
	int num;
	AiBuildRec *aib;
	const AiDefaultBlockData *b;

	num = p->ai.num_build_rec;
	aib = &p->ai.src;
	do {
		if (aib->cur_building_rule != 255) {
			b = _road_default_block_data[aib->cur_building_rule]->data;
			while (b->mode != 4) {
				if (b->mode <= 1) {
					DoCommandByTile(TILE_ADD(aib->use_tile, ToTileIndexDiff(b->tileoffs)), 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
				}
				b++;
			}
		}
	} while (++aib,--num);

	p->ai.state = AIS_0;
}

static bool AiCheckIfHangar(Station *st)
{
	TileIndex tile = st->airport_tile;

	// HANGAR of airports
	// 0x20 - hangar large airport (32)
	// 0x41 - hangar small airport (65)
	return (_m[tile].m5 == 32 || _m[tile].m5 == 65);
}

static void AiStateAirportStuff(Player *p)
{
	Station *st;
	byte acc_planes;
	int i;
	AiBuildRec *aib;
	byte rule;

	// Here we look for an airport we could use instead of building a new
	// one. If we find such an aiport for any waypoint,
	// AiStateBuildDefaultAirportBlocks() will kindly skip that one when
	// building the waypoints.

	i = 0;
	do {
		// We do this all twice - once for the source (town in the case
		// of oilrig route) and then for the destination (oilrig in the
		// case of oilrig route).
		aib = &p->ai.src + i;

		FOR_ALL_STATIONS(st) {
			// Dismiss ghost stations.
			if (st->xy == 0)
				continue;

			// Is this an airport?
			if (!(st->facilities & FACIL_AIRPORT))
				continue;

			// Do we own the airport? (Oilrigs aren't owned, though.)
			if (st->owner != OWNER_NONE && st->owner != _current_player)
				continue;

			acc_planes = GetAirport(st->airport_type)->acc_planes;

			// Dismiss heliports, unless we are checking an oilrig.
			if (acc_planes == HELICOPTERS_ONLY && !(p->ai.build_kind == 1 && i == 1))
				continue;

			// Dismiss country airports if we are doing the other
			// endpoint of an oilrig route.
			if (acc_planes == AIRCRAFT_ONLY && (p->ai.build_kind == 1 && i == 0))
				continue;

			// Dismiss airports too far away.
			if (DistanceMax(st->airport_tile, aib->spec_tile) > aib->rand_rng)
				continue;

			// It's ideal airport, let's take it!

			/* XXX: This part is utterly broken - rule should
			 * contain number of the rule appropriate for the
			 * airport type (country, town, ...), see
			 * _airport_default_block_data (rule is just an index
			 * in this array). But the only difference between the
			 * currently existing two rules (rule 0 - town and rule
			 * 1 - country) is the attr field which is used only
			 * when building new airports - and that's irrelevant
			 * for us. So using just about any rule will suffice
			 * here for now (some of the new airport types would be
			 * broken because they will probably need different
			 * tileoff values etc), no matter that
			 * AiCheckIfHangar() makes no sense. --pasky */
			if (acc_planes == HELICOPTERS_ONLY) {
				/* Heliports should have maybe own rulesets but
				 * OTOH we don't want AI to pick them up when
				 * looking for a suitable airport type to build.
				 * So any of rules 0 or 1 would do for now. The
				 * original rule number was 2 but that's a bug
				 * because we have no such rule. */
				rule = 1;
			} else {
				rule = AiCheckIfHangar(st);
			}

			aib->cur_building_rule = rule;
			aib->use_tile = st->airport_tile;
			break;
		}
	} while (++i != p->ai.num_build_rec);

	p->ai.state = AIS_BUILD_DEFAULT_AIRPORT_BLOCKS;
	p->ai.state_mode = 255;
	p->ai.state_counter = 0;
}

static int32 AiDoBuildDefaultAirportBlock(TileIndex tile, const AiDefaultBlockData *p, byte flag)
{
	int32 total_cost = 0, ret;

	for(;p->mode == 0;p++) {
		if (!HASBIT(_avail_aircraft, p->attr))
			return CMD_ERROR;
		ret = DoCommandByTile(TILE_MASK(tile + ToTileIndexDiff(p->tileoffs)), p->attr,0,flag | DC_AUTO | DC_NO_WATER,CMD_BUILD_AIRPORT);
		if (CmdFailed(ret)) return CMD_ERROR;
		total_cost += ret;
	}

	return total_cost;
}

static bool AiCheckAirportResources(TileIndex tile, const AiDefaultBlockData *p, byte cargo)
{
	uint values[NUM_CARGO];
	int w,h;
	int rad;

	if (_patches.modified_catchment) {
		rad = CA_AIR_LARGE;		//I Have NFI what airport the
	} else {				//AI is going to build here
		rad = 4;
	}

	for(;p->mode==0;p++) {
		TileIndex tile2 = TILE_ADD(tile, ToTileIndexDiff(p->tileoffs));

		w = _airport_size_x[p->attr];
		h = _airport_size_y[p->attr];
		if (cargo & 0x80) {
			GetProductionAroundTiles(values, tile2, w, h, rad);
			return values[cargo & 0x7F] != 0;
		} else {
			GetAcceptanceAroundTiles(values, tile2, w, h, rad);
			return values[cargo] >= 8;
		}
	}
	return true;
}

static int AiFindBestDefaultAirportBlock(TileIndex tile, byte cargo, byte heli, int32 *cost)
{
	int i;
	const AiDefaultBlockData *p;
	for(i=0; (p = _airport_default_block_data[i]) != NULL; i++) {
		// If we are doing a helicopter service, avoid building
		// airports where they can't land.
		if (heli && GetAirport(p->attr)->acc_planes == AIRCRAFT_ONLY)
			continue;

		*cost = AiDoBuildDefaultAirportBlock(tile, p, 0);
		if (*cost != CMD_ERROR && AiCheckAirportResources(tile, p, cargo))
			return i;
	}
	return -1;
}

static void AiStateBuildDefaultAirportBlocks(Player *p)
{
	int i, j;
	AiBuildRec *aib;
	int rule;
	int32 cost;

	// time out?
	if (++p->ai.timeout_counter == 1388) {
		p->ai.state = AIS_0;
		return;
	}

	// do the following 8 times
	i = 8;
	do {
		// check if we can build the default
		aib = &p->ai.src;
		j = p->ai.num_build_rec;
		do {
			// this item has already been built?
			if (aib->cur_building_rule != 255)
				continue;

			// adjust the coordinate randomly,
			// to make sure that we find a position.
			aib->use_tile = AdjustTileCoordRandomly(aib->spec_tile, aib->rand_rng);

			// check if the aircraft stuff can be built there.
			rule = AiFindBestDefaultAirportBlock(aib->use_tile, aib->cargo, p->ai.build_kind, &cost);

#if 0
			if (!IsTileType(aib->use_tile, MP_STREET) &&
					!IsTileType(aib->use_tile, MP_RAILWAY) &&
					!IsTileType(aib->use_tile, MP_STATION)
					) {

				_m[aib->use_tile].type_height = 0xa1;
				_m[aib->use_tile].m5 = 0x80;
				MarkTileDirtyByTile(aib->use_tile);
			}
#endif
//			SetRedErrorSquare(aib->use_tile);

			if (rule == -1) {
				// cannot build, terraform after a while
				if (p->ai.state_counter >= 600) {
					AiDoTerraformLand(aib->use_tile, Random()&3, 3, (int8)p->ai.state_mode);
				}
				// also try the other terraform direction
				if (++p->ai.state_counter >= 1000) {
					p->ai.state_counter = 0;
					p->ai.state_mode = -p->ai.state_mode;
				}
			} else if (CheckPlayerHasMoney(cost) && AiCheckBlockDistances(p,aib->use_tile)) {
				// player has money, build it.
				int32 r;

				aib->cur_building_rule = rule;

				r = AiDoBuildDefaultAirportBlock(
					aib->use_tile,
					_airport_default_block_data[rule],
					DC_EXEC | DC_NO_TOWN_RATING
				);
				assert(r != CMD_ERROR);
			}
		} while (++aib,--j);
	} while (--i);

	// check if we're done with all of them
	aib = &p->ai.src;
	j = p->ai.num_build_rec;
	do {
		if (aib->cur_building_rule == 255)
			return;
	} while (++aib,--j);

	// yep, all are done. switch state.
	p->ai.state = AIS_BUILD_AIRCRAFT_VEHICLES;
}

static int AiGetStationIdFromAircraftBlock(TileIndex tile, int id)
{
	const AiDefaultBlockData *p = _airport_default_block_data[id];
	while (p->mode != 1) p++;
	return _m[TILE_ADD(tile, ToTileIndexDiff(p->tileoffs))].m2;
}

static void AiStateBuildAircraftVehicles(Player *p)
{
	const AiDefaultBlockData *ptr;
	TileIndex tile;
	int veh;
	int i;
	uint loco_id;

	ptr = _airport_default_block_data[p->ai.src.cur_building_rule];
	for(;ptr->mode!=0;ptr++) {}

	tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));

	veh = AiChooseAircraftToBuild(p->player_money, p->ai.build_kind!=0 ? 1 : 0);
	if (veh == -1) {
		return;
	}

	if (CmdFailed(DoCommandByTile(tile, veh, 0, DC_EXEC, CMD_BUILD_AIRCRAFT))) return;
	loco_id = _new_aircraft_id;

	for(i=0; p->ai.order_list_blocks[i] != 0xFF; i++) {
		AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
		bool is_pass = (p->ai.cargo_type == CT_PASSENGERS || p->ai.cargo_type == CT_MAIL);
		Order order;

		order.type = OT_GOTO_STATION;
		order.flags = 0;
		order.station = AiGetStationIdFromAircraftBlock(aib->use_tile, aib->cur_building_rule);

		if (!is_pass && i == 1) order.flags |= OF_UNLOAD;
		if (p->ai.num_want_fullload != 0 && (is_pass || i == 0))
			order.flags |= OF_FULL_LOAD;

		DoCommandByTile(0, loco_id + (i << 16), PackOrder(&order), DC_EXEC, CMD_INSERT_ORDER);
	}

	DoCommandByTile(0, loco_id, 0, DC_EXEC, CMD_START_STOP_AIRCRAFT);

	DoCommandByTile(0, loco_id, _ai_service_interval, DC_EXEC, CMD_CHANGE_TRAIN_SERVICE_INT);

	if (p->ai.num_want_fullload != 0)
		p->ai.num_want_fullload--;

	if (--p->ai.num_loco_to_build == 0) {
		p->ai.state =	AIS_0;
	}
}

static void AiStateCheckShipStuff(Player *p)
{
	// XXX
	error("!AiStateCheckShipStuff");
}

static void AiStateBuildDefaultShipBlocks(Player *p)
{
	// XXX
	error("!AiStateBuildDefaultShipBlocks");
}

static void AiStateDoShipStuff(Player *p)
{
	// XXX
	error("!AiStateDoShipStuff");
}

static void AiStateSellVeh(Player *p)
{
	Vehicle *v = p->ai.cur_veh;

	if (v->owner == _current_player) {
		if (v->type == VEH_Train) {

			if (!IsTileDepotType(v->tile, TRANSPORT_RAIL) || v->u.rail.track != 0x80 || !(v->vehstatus&VS_STOPPED)) {
				if (v->current_order.type != OT_GOTO_DEPOT)
					DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_TRAIN_GOTO_DEPOT);
				goto going_to_depot;
			}

			// Sell whole train
			DoCommandByTile(v->tile, v->index, 1, DC_EXEC, CMD_SELL_RAIL_WAGON);

		} else if (v->type == VEH_Road) {
			if (!IsTileDepotType(v->tile, TRANSPORT_ROAD) || v->u.road.state != 254 || !(v->vehstatus&VS_STOPPED)) {
				if (v->current_order.type != OT_GOTO_DEPOT)
					DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SEND_ROADVEH_TO_DEPOT);
				goto going_to_depot;
			}

			DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH);
		} else if (v->type == VEH_Aircraft) {
			if (!IsAircraftHangarTile(v->tile) && !(v->vehstatus&VS_STOPPED)) {
				if (v->current_order.type != OT_GOTO_DEPOT)
					DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SEND_AIRCRAFT_TO_HANGAR);
				goto going_to_depot;
			}

			DoCommandByTile(0, v->index, 0, DC_EXEC, CMD_SELL_AIRCRAFT);
			} else if (v->type == VEH_Ship) {
			// XXX: not implemented
			error("!v->type == VEH_Ship");
		}
	}

	goto return_to_loop;
going_to_depot:;
	if (++p->ai.state_counter <= 832)
		return;

	if (v->current_order.type == OT_GOTO_DEPOT) {
		v->current_order.type = OT_DUMMY;
		v->current_order.flags = 0;
		InvalidateWindow(WC_VEHICLE_VIEW, v->index);
	}
return_to_loop:;
	p->ai.state = AIS_VEH_LOOP;
}

static void AiStateRemoveStation(Player *p)
{
	// Remove stations that aren't in use by any vehicle
	byte *in_use;
	const byte *used;
	const Order *ord;
	const Station *st;
	TileIndex tile;

	// Go to this state when we're done.
	p->ai.state = AIS_1;

	// Get a list of all stations that are in use by a vehicle
	in_use = malloc(GetStationPoolSize());
	memset(in_use, 0, GetStationPoolSize());
	FOR_ALL_ORDERS(ord) {
		if (ord->type == OT_GOTO_STATION)
			in_use[ord->station] = 1;
	}

	// Go through all stations and delete those that aren't in use
	used = in_use;
	FOR_ALL_STATIONS(st) {
		if (st->xy != 0 && st->owner == _current_player && !*used &&
				( (st->bus_stops != NULL && (tile = st->bus_stops->xy) != 0) ||
					(st->truck_stops != NULL && (tile = st->truck_stops->xy)) != 0 ||
					(tile = st->train_tile) != 0 ||
					(tile = st->dock_tile) != 0 ||
					(tile = st->airport_tile) != 0)) {
			DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
		}
		used++;
	}

	free(in_use);
}

static void AiRemovePlayerRailOrRoad(Player *p, TileIndex tile)
{
	byte m5;

	if (IsTileType(tile, MP_RAILWAY)) {
		if (!IsTileOwner(tile, _current_player)) return;

		m5 = _m[tile].m5;
		if ((m5&~0x3) != 0xC0) {
is_rail_crossing:;
			m5 = GetRailTrackStatus(tile);

			if (m5 == 0xC || m5 == 0x30)
				return;

			if (m5&0x25) {
pos_0:
				if (!(GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(1, 0))) & 0x19)) {
					p->ai.cur_dir_a = 0;
					p->ai.cur_tile_a = tile;
					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
					return;
				}
			}

			if (m5&0x2A) {
pos_1:
				if (!(GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(0, 1))) & 0x16)) {
					p->ai.cur_dir_a = 1;
					p->ai.cur_tile_a = tile;
					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
					return;
				}
			}

			if (m5&0x19) {
pos_2:
				if (!(GetRailTrackStatus(TILE_MASK(tile + TileDiffXY(1, 0))) & 0x25)) {
					p->ai.cur_dir_a = 2;
					p->ai.cur_tile_a = tile;
					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
					return;
				}
			}

			if (m5&0x16) {
pos_3:
				if (!(GetRailTrackStatus(TILE_MASK(tile - TileDiffXY(0, 1))) & 0x2A)) {
					p->ai.cur_dir_a = 3;
					p->ai.cur_tile_a = tile;
					p->ai.state = AIS_REMOVE_SINGLE_RAIL_TILE;
					return;
				}
			}
		} else {
			static const byte _depot_bits[] = {0x19,0x16,0x25,0x2A};

			m5 &= 3;
			if (GetRailTrackStatus(tile + TileOffsByDir(m5)) & _depot_bits[m5])
				return;

			DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
		}
	} else if (IsTileType(tile, MP_STREET)) {
		if (!IsTileOwner(tile, _current_player)) return;

		if (IsLevelCrossing(tile))
			goto is_rail_crossing;

		if ( (_m[tile].m5&0xF0) == 0x20) {
			int dir;

			// Check if there are any stations around.
			if (IsTileType(tile + TileDiffXY(-1, 0), MP_STATION) &&
					IsTileOwner(tile + TileDiffXY(-1, 0), _current_player))
						return;

			if (IsTileType(tile + TileDiffXY(1, 0), MP_STATION) &&
					IsTileOwner(tile + TileDiffXY(1, 0), _current_player))
						return;

			if (IsTileType(tile + TileDiffXY(0, -1), MP_STATION) &&
					IsTileOwner(tile + TileDiffXY(0, -1), _current_player))
						return;

			if (IsTileType(tile + TileDiffXY(0, 1), MP_STATION) &&
					IsTileOwner(tile + TileDiffXY(0, 1), _current_player))
						return;

			dir = _m[tile].m5 & 3;

			DoCommandByTile(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
			DoCommandByTile(
				TILE_MASK(tile + TileOffsByDir(dir)),
				8 >> (dir ^ 2),
				0,
				DC_EXEC,
				CMD_REMOVE_ROAD);
		}
	} else if (IsTileType(tile, MP_TUNNELBRIDGE)) {
		byte b;

		if (!IsTileOwner(tile, _current_player) || (_m[tile].m5 & 0xC6) != 0x80)
			return;

		m5 = 0;

		b = _m[tile].m5 & 0x21;
		if (b == 0) goto pos_0;
		if (b == 1) goto pos_3;
		if (b == 0x20) goto pos_2;
		goto pos_1;
	}
}

static void AiStateRemoveTrack(Player *p)
{
	/* Was 1000 for standard 8x8 maps. */
	int num = MapSizeX() * 4;

	do {
		TileIndex tile = ++p->ai.state_counter;

		// Iterated all tiles?
		if (tile >= MapSize()) {
			p->ai.state = AIS_REMOVE_STATION;
			return;
		}

		// Remove player stuff in that tile
		AiRemovePlayerRailOrRoad(p, tile);
		if (p->ai.state != AIS_REMOVE_TRACK)
			return;
	} while (--num);
}

static void AiStateRemoveSingleRailTile(Player *p)
{
	// Remove until we can't remove more.
	if (!AiRemoveTileAndGoForward(p)) {
		p->ai.state = AIS_REMOVE_TRACK;
	}
}

static AiStateAction * const _ai_actions[] = {
	AiCase0,
	AiCase1,
	AiStateVehLoop,
	AiStateCheckReplaceVehicle,
	AiStateDoReplaceVehicle,
	AiStateWantNewRoute,

	AiStateBuildDefaultRailBlocks,
	AiStateBuildRail,
	AiStateBuildRailVeh,
	AiStateDeleteRailBlocks,

	AiStateBuildDefaultRoadBlocks,
	AiStateBuildRoad,
	AiStateBuildRoadVehicles,
	AiStateDeleteRoadBlocks,

	AiStateAirportStuff,
	AiStateBuildDefaultAirportBlocks,
	AiStateBuildAircraftVehicles,

	AiStateCheckShipStuff,
	AiStateBuildDefaultShipBlocks,
	AiStateDoShipStuff,

	AiStateSellVeh,
	AiStateRemoveStation,
	AiStateRemoveTrack,

	AiStateRemoveSingleRailTile
};

extern void ShowBuyCompanyDialog(uint player);

static void AiHandleTakeover(Player *p)
{
	if (p->bankrupt_timeout != 0) {
		if ((p->bankrupt_timeout-=8) > 0)
			return;
		p->bankrupt_timeout = 0;
		DeleteWindowById(WC_BUY_COMPANY, _current_player);
		if (_current_player == _local_player) {
			AskExitToGameMenu();
			return;
		}
		if (IS_HUMAN_PLAYER(_current_player))
			return;
	}

	if (p->bankrupt_asked == 255)
		return;

	{
		uint asked = p->bankrupt_asked;
		Player *pp, *best_pl = NULL;
		int32 best_val = -1;
		uint old_p;

		// Ask the guy with the highest performance hist.
		FOR_ALL_PLAYERS(pp) {
			if (pp->is_active &&
					!(asked&1) &&
					pp->bankrupt_asked == 0 &&
					best_val < pp->old_economy[1].performance_history) {
				best_val = pp->old_economy[1].performance_history;
				best_pl = pp;
			}
			asked>>=1;
		}

		// Asked all players?
		if (best_val == -1) {
			p->bankrupt_asked = 255;
			return;
		}

		SETBIT(p->bankrupt_asked, best_pl->index);

		if (best_pl->index == _local_player) {
			p->bankrupt_timeout = 4440;
			ShowBuyCompanyDialog(_current_player);
			return;
		}
		if (IS_HUMAN_PLAYER(best_pl->index))
			return;

		// Too little money for computer to buy it?
		if (best_pl->player_money >> 1 >= p->bankrupt_value) {
			// Computer wants to buy it.
			old_p = _current_player;
			_current_player = p->index;
			DoCommandByTile(0, old_p, 0, DC_EXEC, CMD_BUY_COMPANY);
			_current_player = old_p;
		}
	}
}

static void AiAdjustLoan(Player *p)
{
	int32 base = AiGetBasePrice(p);

	if (p->player_money > base * 1400) {
		// Decrease loan
		if (p->current_loan != 0) {
			DoCommandByTile(0, 0, 0, DC_EXEC, CMD_DECREASE_LOAN);
		}
	} else if (p->player_money < base * 500) {
		// Increase loan
		if (p->current_loan < _economy.max_loan &&
				p->num_valid_stat_ent >= 2 &&
				-(p->old_economy[0].expenses+p->old_economy[1].expenses) < base * 60) {
			DoCommandByTile(0, 0, 0, DC_EXEC, CMD_INCREASE_LOAN);
		}
	}
}

static void AiBuildCompanyHQ(Player *p)
{
	TileIndex tile;

	if (p->location_of_house == 0 &&
			p->last_build_coordinate != 0) {
		tile = AdjustTileCoordRandomly(p->last_build_coordinate, 8);
		DoCommandByTile(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_COMPANY_HQ);
	}
}


void AiDoGameLoop(Player *p)
{
	_cur_ai_player = p;

	if (p->bankrupt_asked != 0) {
		AiHandleTakeover(p);
		return;
	}

	// Ugly hack to make sure the service interval of the AI is good, not looking
	//  to the patch-setting
	// Also, it takes into account the setting if the service-interval is in days
	//  or in %
	_ai_service_interval = _patches.servint_ispercent?80:180;

	if (IS_HUMAN_PLAYER(_current_player))
		return;

	AiAdjustLoan(p);
	AiBuildCompanyHQ(p);

	if (_opt.diff.competitor_speed == 4) {
		/* ultraspeed */
		_ai_actions[p->ai.state](p);
		if (p->bankrupt_asked != 0)
			return;
	} else if (_opt.diff.competitor_speed != 3) {
		p->ai.tick++;
		if (!(p->ai.tick&1))
			return;
		if (_opt.diff.competitor_speed != 2) {
			if (!(p->ai.tick&2))
				return;
			if (_opt.diff.competitor_speed == 0) {
				if (!(p->ai.tick&4))
					return;
			}
		}
	}
#if 0
	{
		static byte old_state = 99;
		static bool hasdots = false;
		char *_ai_state_names[]={
			"AiCase0",
			"AiCase1",
			"AiStateVehLoop",
			"AiStateCheckReplaceVehicle",
			"AiStateDoReplaceVehicle",
			"AiStateWantNewRoute",
			"AiStateBuildDefaultRailBlocks",
			"AiStateBuildRail",
			"AiStateBuildRailVeh",
			"AiStateDeleteRailBlocks",
			"AiStateBuildDefaultRoadBlocks",
			"AiStateBuildRoad",
			"AiStateBuildRoadVehicles",
			"AiStateDeleteRoadBlocks",
			"AiStateAirportStuff",
			"AiStateBuildDefaultAirportBlocks",
			"AiStateBuildAircraftVehicles",
			"AiStateCheckShipStuff",
			"AiStateBuildDefaultShipBlocks",
			"AiStateDoShipStuff",
			"AiStateSellVeh",
			"AiStateRemoveStation",
			"AiStateRemoveTrack",
			"AiStateRemoveSingleRailTile"
		};

		if (p->ai.state != old_state) {
			if (hasdots)
				printf("\n");
			hasdots=false;
			printf("AiState: %s\n", _ai_state_names[old_state=p->ai.state]);
		} else {
			printf(".");
			hasdots=true;
		}
	}
#endif

	_ai_actions[p->ai.state](p);
}