This file is indexed.

/usr/share/games/micropolis/res/micropolis.tcl is in micropolis-data 0.0.20071228-8.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
#######################################################################
# Micropolis.tcl, by Don Hopkins.
# Copyright (C) 2002 by Electronic Arts.
# This file defines the user interface of Micropolis. 
# Modify at your own risk!
########################################################################
# Micropolis, Unix Version.  This game was released for the Unix platform
# in or about 1990 and has been modified for inclusion in the One Laptop
# Per Child program.  Copyright (C) 1989 - 2007 Electronic Arts Inc.  If
# you need assistance with this program, you may contact:
#   http://wiki.laptop.org/go/Micropolis  or email  micropolis@laptop.org.
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.  You should have received a
# copy of the GNU General Public License along with this program.  If
# not, see <http://www.gnu.org/licenses/>.
# 
#             ADDITIONAL TERMS per GNU GPL Section 7
# 
# No trademark or publicity rights are granted.  This license does NOT
# give you any right, title or interest in the trademark SimCity or any
# other Electronic Arts trademark.  You may not distribute any
# modification of this program using the trademark SimCity or claim any
# affliation or association with Electronic Arts Inc. or its employees.
# 
# Any propagation or conveyance of this program must include this
# copyright notice and these terms.
# 
# If you convey this program (or any modifications of it) and assume
# contractual liability for the program to recipients of it, you agree
# to indemnify Electronic Arts for any liability that those contractual
# assumptions impose on Electronic Arts.
# 
# You may not misrepresent the origins of this program; modified
# versions of the program must be marked as such and not identified as
# the original program.
# 
# This disclaimer supplements the one included in the General Public
# License.  TO THE FULLEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW, THIS
# PROGRAM IS PROVIDED TO YOU "AS IS," WITH ALL FAULTS, WITHOUT WARRANTY
# OF ANY KIND, AND YOUR USE IS AT YOUR SOLE RISK.  THE ENTIRE RISK OF
# SATISFACTORY QUALITY AND PERFORMANCE RESIDES WITH YOU.  ELECTRONIC ARTS
# DISCLAIMS ANY AND ALL EXPRESS, IMPLIED OR STATUTORY WARRANTIES,
# INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, SATISFACTORY QUALITY,
# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT OF THIRD PARTY
# RIGHTS, AND WARRANTIES (IF ANY) ARISING FROM A COURSE OF DEALING,
# USAGE, OR TRADE PRACTICE.  ELECTRONIC ARTS DOES NOT WARRANT AGAINST
# INTERFERENCE WITH YOUR ENJOYMENT OF THE PROGRAM; THAT THE PROGRAM WILL
# MEET YOUR REQUIREMENTS; THAT OPERATION OF THE PROGRAM WILL BE
# UNINTERRUPTED OR ERROR-FREE, OR THAT THE PROGRAM WILL BE COMPATIBLE
# WITH THIRD PARTY SOFTWARE OR THAT ANY ERRORS IN THE PROGRAM WILL BE
# CORRECTED.  NO ORAL OR WRITTEN ADVICE PROVIDED BY ELECTRONIC ARTS OR
# ANY AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY.  SOME
# JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF OR LIMITATIONS ON IMPLIED
# WARRANTIES OR THE LIMITATIONS ON THE APPLICABLE STATUTORY RIGHTS OF A
# CONSUMER, SO SOME OR ALL OF THE ABOVE EXCLUSIONS AND LIMITATIONS MAY
# NOT APPLY TO YOU.


########################################################################
# Libraries
########################################################################


set errorInfo {}
set auto_noexec 1

source $tk_library/wish.tcl


########################################################################
# Globals
########################################################################


set UniqueID 0
set State uninitialized
set CityName "Micropolis"
set GameLevel 0
set SimHome [pwd]
set CityLibDir $SimHome/cities
set CityDir $CityLibDir
set OldBudget 0
set BudgetRoadFund 0
set BudgetFireFund 0
set BudgetPoliceFund 0
set BudgetTaxRate 0
set DemandRes 0
set DemandCom 0
set DemandInd 0
set Priority 2
set Time 3
set Pause 0
set AutoGoto 1
set AutoBudget 1
set Disasters 1
set AutoBulldoze 1
set Sound 1
set DoAnimation 1
set DoMessages 1
set DoNotices 1
set ShapePies 1
set SoundServers {}
set AudioChannels {mode edit fancy warning intercom}
set BudgetTimeout 30
set BudgetTimer 0
set BudgetTimerActive 0
set BudgetsVisible 0
set EvaluationsVisible 0
set SplashScreenDelay 5000
set Scenario -1
set Chatting 0
set ChatServer "localhost"
set ChatSocket 6667
set ChatConnection {}
set NickName "nickname"
set UserName "username"
set ServerName "servername"
set RealName "realname"
set ChannelName "#Micropolis"
set HomeDir ""
set ResourceDir ""
set HostName ""
set LocalHostName "[exec hostname]"
set SaveCityWin ""
set MapHistory {}
set MapHistoryNum -1
set HelpLoaded 0
set QueryX 0
set QueryY 0
set FreeVotes 0
set ShowingPicture 300
set MaxLines 500
set ShrinkLines 250
set ShowingParms {}
set VoteNames {UseThisMap Ask Zone}
set VotesForUseThisMap {}
set VotesForAsk {}
set VotesForZone {}
set VotesForBudget {}
set CurrentDate {}

set HeadWindows {}
set EditorWindows {}
set MapWindows {}
set GraphWindows {}
set BudgetWindows {}
set EvaluationWindows {}
set SplashWindows {}
set ScenarioWindows {}
set FileWindows {}
set AskWindows {}
set PlayerWindows {}
set NoticeWindows {}
set HelpWindows {}
set FrobWindows {}

set HeadPanelWidth 360
set HeadPanelHeight 200

set MapPanelWidth 360
set MapPanelHeight 330

set NoticePanelWidth 360
set NoticePanelHeight 250

set SplashPanelWidth 1200
set SplashPanelHeight 900

set ScenarioPanelWidth 420
set ScenarioPanelHeight 440

set SugarURI ""
set SugarNickName ""
set SugarShared 0
set SugarActivated 0
set SugarBuddies {}

set SubWindows {
  {editor EditorWindows}
  {map MapWindows}
  {graph GraphWindows}
  {budget BudgetWindows}
  {evaluation EvaluationWindows}
  {scenario ScenarioWindows}
  {splash SplashWindows}
  {file FileWindows}
  {ask AskWindows}
  {player PlayerWindows}
  {notice NoticeWindows}
  {help HelpWindows}
  {frob FrobWindows}
  {head HeadWindows}
}


#   0           1               2               3       4         5   6   7   8         9       10   11       12      13
#   type	id		callback	param	var	  x   y   w   h		normal	over disabled checked checkedover
#   ----------- --------------- --------------- ------- ------- --- --- --- ---         ------- ---- -------- ------- -----------
set ScenarioButtons {
  { button	load		DoLoad		""	""	 70 238 157  90		""	@images/button1hilite.xpm "" }
  { button	generate	DoGenerate	""	""	 62 392 157  90		""	@images/button2hilite.xpm "" }
  { button	quit		DoQuit		""	""	 68 544 157  90		""	@images/button3hilite.xpm "" }
  { button	about		DoAbout		""	""	101 705 157  90		""	@images/button4hilite.xpm "" }
  { checkbox	easy		DoLevel		0	""	982 106 190  70		""	@images/checkbox1hilite.xpm "" @images/checkbox1checked.xpm @images/checkbox1hilitechecked.xpm }
  { checkbox	medium		DoLevel		1	""	982 176 190  70		""	@images/checkbox2hilite.xpm "" @images/checkbox2checked.xpm @images/checkbox2hilitechecked.xpm }
  { checkbox	hard		DoLevel		2	""	982 246 190  70		""	@images/checkbox3hilite.xpm "" @images/checkbox3checked.xpm @images/checkbox3hilitechecked.xpm }
  { button	left		DoLeft		""	""	540 375  50  50		""	@images/lefthilite.xpm @images/leftdisabled.xpm }
  { button	right		DoRight		""	""	841 375  50  50		""	@images/righthilite.xpm @images/rightdisabled.xpm }
  { button	play		DoPlay		""	""	625 376 180  50		""	@images/playhilite.xpm "" }
  { button	scenario1	DoPickScenario	"1"	""	310 451 209 188		""	@images/scenario1hilite.xpm "" }
  { button	scenario2	DoPickScenario	"2"	""	519 451 209 188		""	@images/scenario2hilite.xpm "" }
  { button	scenario3	DoPickScenario	"3"	""	727 450 209 188		""	@images/scenario3hilite.xpm "" }
  { button	scenario4	DoPickScenario	"4"	""	936 450 209 188		""	@images/scenario4hilite.xpm "" }
  { button	scenario5	DoPickScenario	"5"	""	310 639 209 188		""	@images/scenario5hilite.xpm "" }
  { button	scenario6	DoPickScenario	"8"	""	519 639 209 188		""	@images/scenario6hilite.xpm "" }
  { button	scenario7	DoPickScenario	"7"	""	728 638 209 188		""	@images/scenario7hilite.xpm "" }
  { button	scenario8	DoPickScenario	"6"	""	937 638 209 188		""	@images/scenario8hilite.xpm "" }
}

# Disabled until we handle mouse events on the map itself.
#   { button	map		DoMap		""	""	516  30 396 338		""	@images/maphilite.xpm }


########################################################################
# Fonts


set FontInfo {
  {Big {
	{-*-dejavu lgc sans-medium-r-normal-*-90-*}
  }}
  {Large {
	{-*-dejavu lgc sans-medium-r-normal-*-80-*}
  }}
  {Medium {
	{-*-dejavu lgc sans-medium-r-normal-*-70-*}
  }}
  {Small {
	{-*-dejavu lgc sans-medium-r-normal-*-60-*}
  }}
  {Narrow {
	{-*-dejavu lgc sans-medium-r-normal-*-60-*}
  }}
  {Tiny {
	{-*-dejavu lgc sans-medium-r-normal-*-60-*}
  }}
  {Text {
	{-*-dejavu lgc sans-medium-r-normal-*-70-*}
  }}
  {Message {
	{-*-dejavu lgc sans-medium-r-normal-*-70-*}
  }}
  {Alert {
	{-*-dejavu lgc sans-medium-r-normal-*-70-*}
  }}
}


########################################################################


set MapTitles {
  {Micropolis Overall Map}
  {Residential Zone Map}
  {Commercial Zone Map}
  {Industrial Zone Map}
  {Power Grid Map}
  {Transportation Map}
  {Population Density Map}
  {Rate of Growth Map}
  {Traffic Density Map}
  {Pollution Desity Map}
  {Crime Rate Map}
  {Land Value Map}
  {Fire Coverage Map}
  {Police Coverage Map}
  {Dynamic Filter Map}
}


set EditorPallets {
  leftframe.tools.palletres
  leftframe.tools.palletcom
  leftframe.tools.palletind
  leftframe.tools.palletfire
  leftframe.tools.palletquery
  leftframe.tools.palletpolice
  leftframe.tools.palletwire
  leftframe.tools.palletbulldozer
  leftframe.tools.palletrail
  leftframe.tools.palletroad
  leftframe.tools.palletchalk
  leftframe.tools.palleteraser
  leftframe.tools.palletstadium
  leftframe.tools.palletpark
  leftframe.tools.palletseaport
  leftframe.tools.palletcoal
  leftframe.tools.palletnuclear
  leftframe.tools.palletairport
}


set EditorPalletImages { 
  res com ind fire qry pol
  wire dozr rail road chlk ersr
  stad park seap coal nuc airp
}


set EditorPalletSounds { 
  Res Com Ind Fire Query Police
  Wire Bulldozer Rail Road Chalk Eraser
  Stadium Park Seaport Coal Nuclear Airport
}


set GraphPallets {
  leftframe.left.res
  leftframe.left.com
  leftframe.left.ind
  leftframe.right.money
  leftframe.right.crime
  leftframe.right.pollution
}


set GraphPalletImages { 
  res com ind mony crim poll
}


set GraphYearPallets {
  leftframe.year.year10
  leftframe.year.year120
}


set GraphYearPalletImages { 10 120 }


set ToolInfo {
  {     {a}	{Residential Zone}	{$100}}
  {     {a}	{Commercial Zone}	{$100}}
  {     {an}	{Industrial Zone}	{$100}}
  {     {a}	{Fire Station}		{$500}}
  {     {a}	{Query}			{free}}
  {     {a}	{Police Station}	{$500}}
  {     {a}	{Wire}			{$5}}
  {     {a}	{Bulldozer}		{$1}}
  {     {a}	{Rail}			{$20}}
  {     {a}	{Road}			{$10}}
  {     {a}	{Chalk}			{free}}
  {     {an}	{Eraser}		{free}}
  {     {a}	{Stadium}		{$5,000}}
  {     {a}	{Park}			{$20}}
  {     {a}	{Seaport}		{$3,000}}
  {     {a}	{Coal Power Plant}	{$3,000}}
  {     {a}	{Nuclear Power Plant}	{$5,000}}
  {     {an}	{Airport}		{$10,000}}
  {     {a}	{Network}		{$1,000}}
}


set DynamicDataNames {
  {Population Density}
  {Rate of Growth}
  {Traffic Density}
  {Pollution Density}
  {Crime Rate}
  {Land Value}
  {Police Coverage}
  {Fire Coverage}
}

########################################################################
# Initialization
########################################################################


wm title . {Micropolis Root}


if {"[sim Platform]" == "msdos"} {
  sim DoAnimation 0
  set DoAnimation 0
  set ShapePies 0
} else {
  sim DoAnimation 1
  set DoAnimation 1
  set ShapePies 1
}

sprite explosion 7
sprite tornado 6
sprite airplane 3
sprite helicopter 2
sprite monster 5
sprite ship 4
sprite bus 8
sprite train 1

sim ResetDynamic

# The next three lines have no effect on the OLPC, where we don't provide
# the font in res (because it's already in the system fonts).  These lines
# are for other systems that lack the font.
set FontPath "[pwd]/res/dejavu-lgc"
system "xset -fp \"$FontPath\" >/dev/null 2>&1"
system "xset +fp \"$FontPath\" >/dev/null 2>&1"

# Ignore SIGCHLD for spawned sound-player childs, this should lead to them
# being reaped by init
signal ignore SIGCHLD


########################################################################
# Messages
########################################################################


proc Message {id color title msg {props {}}} {
  global Messages
  set Messages($id) [list $color $title $msg $props]
}


Message 1 #7f7fff {DULLSVILLE, USA  1900} \
{Things haven't changed much around here in the last hundred years or so and the residents are beginning to get bored.  They think Dullsville could be the next great city with the right leader. 

It is your job to attract new growth and development, turning Dullsville into a Metropolis within 30 years.}

Message 2 #7f7fff {SAN FRANCISCO, CA.  1906} \
{Damage from the earthquake was minor compared to that of the ensuing fires, which took days to control.  1500 people died.

Controlling the fires should be your initial concern.  Then clear the rubble and start rebuilding.  You have 5 years.}
	
Message 3 #7f7fff {HAMBURG, GERMANY  1944} \
{Allied fire-bombing of German cities in WWII caused tremendous damage and loss of life.  People living in the inner cities were at greatest risk.

You must control the firestorms during the bombing and then rebuild the city after the war.  You have 5 years.}

Message 4 #7f7fff {BERN, SWITZERLAND  1965} \
{The roads here are becoming more congested every day, and the residents are upset.  They demand that you do something about it.

Some have suggested a mass transit system as the answer, but this would require major rezoning in the downtown area.  You have 10 years.}

Message 5 #7f7fff {TOKYO, JAPAN  1957} \
{A large reptilian creature has been spotted heading for Tokyo bay.  It seems to be attracted to the heavy levels of industrial pollution there.

Try to control the fires, then rebuild the industrial center.  You have 5 years.}

Message 6 #7f7fff {DETROIT, MI.  1972} \
{By 1970, competition from overseas and other economic factors pushed the once "automobile capital of the world" into recession.  Plummeting land values and unemployment then increased crime in the inner-city to chronic levels.

You have 10 years to reduce crime and rebuild the industrial base of the city.}

Message 7 #7f7fff {BOSTON, MA.  2010} \
{A major meltdown is about to occur at one of the new downtown nuclear reactors.  The area in the vicinity of the reactor will be severly contaminated by radiation, forcing you to restructure the city around it.

You have 5 years to get the situation under control.}

Message 8 #7f7fff {RIO DE JANEIRO, BRAZIL  2047} \
{In the mid-21st century, the greenhouse effect raised global temperatures 6 degrees F.  Polar icecaps melted and raised sea levels worldwide.  Coastal areas were devastated by flood and erosion.

You have 10 years to turn this swamp back into a city again.}

Message 9 #ffa500 {Query Zone Status} \
{
Zone:	    %s
Density:    %s
Value:	    %s
Crime:	    %s
Pollution:  %s
Growth:	    %s} \
{{view {PanView $v $QueryX $QueryY}}}

Message 10 #ff4f4f {POLLUTION ALERT!} \
{Pollution in your city has exceeded the maximum allowable amounts established by the Micropolis Pollution Agency.  You are running the risk of grave ecological consequences.

Either clean up your act or open a gas mask concession at city hall.} \
{{view {PanView $v [sim PolMaxX] [sim PolMaxY]}}}

Message 11 #ff4f4f {CRIME ALERT!} \
{Crime in your city is out of hand.  Angry mobs are looting and vandalizing the central city.  The president will send in the national guard soon if you cannot control the problem.} \
{{view {PanView $v [sim CrimeMaxX] [sim CrimeMaxY]}}}

Message 12 #ff4f4f {TRAFFIC WARNING!} \
{Traffic in this city is horrible.  The city gridlock is expanding.  The commuters are getting militant.

Either build more roads and rails or get a bulletproof limo.} \
{{view {PanView $v [sim TrafMaxX] [sim TrafMaxY]}}}

Message 20 #ff4f4f {FIRE REPORTED!} \
"A fire has been reported!" \
{{view {PanView $v [sim CrashX] [sim CrashY]}}}

Message 21 #ff4f4f {MONSTER ATTACK!} \
"A large reptilian creature has been spotted in the water.  It seems to be attracted to areas of high pollution.  There is a trail of destruction wherever it goes.  \
All you can do is wait till he leaves, then rebuild from the rubble." \
{{view {FollowView $v monster}}}

# XXX: write more text
Message 22 #ff4f4f {TORNADO ALERT!} \
{A tornado has been reported!  There's nothing you can do to stop it, so you'd better prepare to clean up after the disaster!} \
{{view {FollowView $v tornado}}}

# XXX: write more text
Message 23 #ff4f4f {EARTHQUAKE!} \
{A major earthquake has occurred!  Put out the fires as quickly as possible, before they spread, then reconnect the power grid and rebuild the city.} \
{{view {PanView $v [sim CenterX] [sim CenterY]}}}

# XXX: write more text
Message 24 #ff4f4f {PLANE CRASH!} \
{A plane has crashed!} \
{{view {PanView $v [sim CrashX] [sim CrashY]}}}

# XXX: write more text
Message 25 #ff4f4f {SHIPWRECK!} \
{A ship has wrecked!} \
{{view {PanView $v [sim CrashX] [sim CrashY]}}}

# XXX: write more text
Message 26 #ff4f4f {TRAIN CRASH!} \
{A train has crashed!} \
{{view {PanView $v [sim CrashX] [sim CrashY]}}}

# XXX: write more text
Message 27 #ff4f4f {HELICOPTER CRASH!} \
{A helicopter has crashed!} \
{{view {PanView $v [sim CrashX] [sim CrashY]}}}

Message 30 #ff4f4f {FIREBOMBING REPORTED!} \
{Firebombs are falling!!} \
{{view {PanView $v [sim CrashX] [sim CrashY]}}}

Message 35 #7fff7f {TOWN} \
{Congratulations, your village has grown to town status.  You now have 2,000 citizens.} \
{{view {PanView $v [sim CenterX] [sim CenterY]}}}

Message 36 #7fff7f {CITY} \
{Your town has grown into a full sized city, with a current population of 10,000.  Keep up the good work!} \
{{view {PanView $v [sim CenterX] [sim CenterY]}}}

Message 37 #7fff7f {CAPITAL} \
{Your city has become a capital.  The current population here is 50,000.  Your political future looks bright.} \
{{view {PanView $v [sim CenterX] [sim CenterY]}}}

Message 38 #7fff7f {METROPOLIS} \
{Your capital city has now achieved the status of metropolis.  The current population is 100,000.  With your management skills, you should seriously consider running for governor.} \
{{view {PanView $v [sim CenterX] [sim CenterY]}}}

Message 39 #7fff7f {MEGALOPOLIS} \
{Congratulation, you have reached the highest category of urban development, the megalopolis.

If you manage to reach this level, send us email at micropolis@laptop.org or send us a copy of your city.  We might do something interesting with it.} \
{{view {PanView $v [sim CenterX] [sim CenterY]}}}

Message 40 #7fff7f {MEGALINIUM} \
{Congratulation, you have reached the end of time!

Because of the toroidal nature of the the Micropolis Space/Time Continuum, your city has wrapped back in time to 1900!} \
{{view {PanView $v [sim CenterX] [sim CenterY]}}}

# XXX: write more text
Message 41 #ff4f4f {HEAVY TRAFFIC!} \
{Sky Watch One
reporting heavy traffic!} \
{{view {FollowView $v helicopter}}}

# XXX: write more text
Message 42 #ff4f4f {FLOODING REPORTED!} \
{Flooding has been been reported along the water's edge!} \
{{view {PanView $v [sim FloodX] [sim FloodY]}}}

Message 43 #ff4f4f {NUCLEAR MELTDOWN!} \
{A nuclear meltdown has occured at your power plant.  You are advised to avoid the area until the radioactive isotopes decay.

Many generations will confront this problem before it goes away, so don't hold your breath.} \
{{view {PanView $v [sim MeltX] [sim MeltY]}}}


Message 44 #ff4f4f {RIOTS!} \
{The citizens are rioting in the streets, setting cars and houses on fire, and bombing government buildings and businesses!

All media coverage is blacked out, while the fascist pigs beat the poor citizens into submission.}

Message 46 #ff4f4f {NO SOUND SERVER!} \
{There is no sound server running on your X11 display "%s".  You won't hear any noise unless you run a sound server, and turn the sound back on in the "Options" menu.}

Message 48 #7f7fff {Start a New City} \
{Build your very own city from the ground up, starting with this map of uninhabited land.}

Message 49 #7f7fff {Restore a Saved City} \
{This city was saved in the file named: %s}

Message 100 #7fff7f {YOU'RE A WINNER!} \
{Your mayorial skill and city planning expertise have earned you the KEY TO THE CITY.  Local residents will erect monuments to your glory and name their first-born children after you.  Why not run for governor?} \
{{middle {@images/key2city.xpm}}}

Message 200 #ff4f4f {IMPEACHMENT NOTICE!} \
{The entire population of this city has finally had enough of your inept planning and incompetant management.  An angry mob -- led by your mother -- has been spotted in the vicinity of city hall.

You should seriously consider taking an extended vacation -- NOW.  (Or read the manual and try again.)}

Message 300 #ffd700 {About Micropolis} \
"Micropolis Version [sim Version] Copyright (C) 2007
    by Electronic Arts.
Based on the Original Micropolis Concept and Design
    by Will Wright.
TCL/Tk User Interface Designed and Created
    by Don Hopkins, DUX Software.
Ported to Linux, Optimized and Adapted for OLPC
    by Don Hopkins.
Licensed under the GNU General Public License, 
    version 3, with additional conditions." 


########################################################################
# Options
########################################################################


option add *CheckButton.relief		flat
option add *Dialog.cursor		top_left_arrow
option add *Entry.relief		sunken
option add *Frame.borderWidth		0
option add *Listbox.relief		sunken
option add *Scrollbar.relief		sunken
option add *RadioButton.anchor		w
option add *RadioButton.relief		flat

option add *background			#b0b0b0
option add *foreground			#000000
option add *activeBackground		#d0d0d0
option add *activeForeground		#000000
option add *disabledForeground		""
option add *selectBackground		#d0d0d0
option add *selectForeground		#000000
#option add *selector			#ffff80
option add *selector			#bf0000

option add *Scrollbar.Background 	#b0b0b0
option add *Scrollbar.Foreground	#d0d0d0
option add *Interval.Background 	#b0b0b0
option add *Interval.Foreground		#000000
option add *Interval.activeForeground	#d0d0d0
option add *Interval.sliderForeground	#b0b0b0
option add *Scale.activeForeground	#d0d0d0
option add *Scale.sliderForeground	#b0b0b0
option add *PieMenu.activeBackground	#b0b0b0

option add Mwm*Micropolis.clientDecoration -maximize


########################################################################
# Global Bindings
########################################################################


bind all <Help> {HandleHelp %W %x %y %X %Y}
bind all <Shift-ButtonPress> {HandleHelp %W %x %y %X %Y}
bind all <Meta-ButtonPress> {HandleHelp %W %x %y %X %Y}
bind all <Shift-Meta-ButtonPress> {HandleHelp %W %x %y %X %Y}


########################################################################
# Utilities
########################################################################


proc echo {args} {
  puts stdout $args
  flush stdout
} 


proc Unique {} {
  global UniqueID
  set id $UniqueID
  incr UniqueID
  return $id
}


proc tkerror {err} {
    global errorInfo
    puts stderr "$errorInfo"
}


proc ident {i} {
  return "$i"
}

proc NoFunction {args} {}


proc LinkWindow {fromname to} {
  global WindowLinks
  set WindowLinks($fromname) $to
}


proc WindowLink {fromname} {
  global WindowLinks
  set to ""
  catch {set to $WindowLinks($fromname)}
  return $to
}


proc DeleteWindow {sym name win} {
  set head [WindowLink $win.head]
  LinkWindow $head.$sym {}
  global $name
  set wins [eval ident "\$$name"]
  set i [lsearch $wins $win]
  if {$i != -1} {
    set $name [lreplace $wins $i $i]
  }
  destroy $win
}


proc Font {win name} {
  global FontInfo FontCache HeadWindows
  set scr [winfo screen $win]
  set font ""
  catch {
    set font $FontCache($scr,$name)
  }
  if {"$font" == ""} {
    set label ""
    catch {
      set label $FontCache($scr)
    }
    if {"$label" == ""} {
      foreach head $HeadWindows {
	if {"[winfo screen $head]" == "$scr"} {
	  set label $head.fontlabel
	  label $label -text "X11 Sucks" -font fixed
	  set FontCache($scr) $label
	}
      }
    }

    set fonts [keylget FontInfo $name]
    foreach font $fonts {
      #echo "Configuring font $font on $label"
      if {[catch "$label config -font \"$font\""] == 0} {
        #echo "yow!"
	break
      } else {
        #echo "oops!"
	set font ""
      }
    }
    if {"$font" == ""} {
      #set font 8x16
      # OLCP default font
      set font 6x13
    }
    set FontCache($scr,$name) $font
  }
  return $font
}


proc Color {win color mono} {
  if {[winfo screendepth $win] == 1} {
    return $mono
  } else {
    return $color
  }
}


########################################################################
# Window Definition Functions
########################################################################


proc MakeWindow.head {{display ":0"}} {
  global ResourceDir
  source $ResourceDir/whead.tcl
  return $win
}


proc MakeWindow.editor {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/weditor.tcl
  return $win
}


proc MakeWindow.map {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wmap.tcl
  return $win
}


proc MakeWindow.graph {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wgraph.tcl
  return $win
}


proc MakeWindow.budget {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wbudget.tcl
  return $win
}


proc MakeWindow.evaluation {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/weval.tcl
  return $win
}


proc MakeWindow.splash {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wsplash.tcl
  return $win
}


proc MakeWindow.scenario {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wscen.tcl
  return $win
}


proc MakeWindow.file {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wfile.tcl
  return $win
}


proc MakeWindow.ask {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wask.tcl
  return $win
}


proc MakeWindow.player {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wplayer.tcl
  return $win
}


proc MakeWindow.notice {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wnotice.tcl
  return $win
}

proc MakeWindow.help {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/whelp.tcl
  return $win
}

proc MakeWindow.frob {head {display ":0"}} {
  global ResourceDir
  source $ResourceDir/wfrob.tcl
  return $win
}


########################################################################
# Sound Support
########################################################################


proc UIInitializeSound {} {
}


proc UIShutDownSound {} {
}


proc UIDoSoundOn {win cmd} {
  global Sound SoundServers
  if {$Sound} {
    set win [WindowLink [winfo toplevel $win].head]
    if {[lsearch $SoundServers $win] != -1} {
      set cmd "send -quick -server $win Sound sound $cmd"
      if {[catch $cmd]} {
	# XXX: Lost a sound server...
	LostSoundServer $win
      }
    }
  }
}


proc UIDoSound {cmd} {
  global Sound SoundServers
  if {$Sound} {
    foreach win $SoundServers {
      set foo "send -quick -server $win Sound $cmd"
      if {[catch $foo]} {
	# XXX: Lost a sound server...
        LostSoundServer $win
      }
    }
  }
}


proc KillSoundServers {} {
  global SoundServers
  foreach win $SoundServers {
    set foo "send -quick -server $win Sound KillSoundServer"
    catch $foo
  }
  set SoundServers {}
}


proc UISetChannelVolume {win chan vol} {
  UIDoSoundOn $win "channel $chan -volume $vol"
}


proc EchoPlaySound {soundspec} {
}


proc UIMakeSoundOn {win chan sound {opts ""}} {
  playsound $chan $sound $opts
}


proc UIStartSoundOn {win chan sound {opts ""}} {
  # Send message to Python to play sound.
  EchoPlaySound $sound

  #UIDoSoundOn $win "play $sound -replay -channel $chan -repeat 100 $opts"
}


proc UIMakeSound {chan sound {opts ""}} {
  playsound $chan $sound $opts
}


proc UIStartSound {chan sound {opts ""}} {
  # Send message to Python to play sound.
  EchoPlaySound $sound

  #UIDoSound "sound play $sound -channel $chan -repeat 100 $opts"
}


proc SetupSoundServer {win} {
  AddSoundServer $win
}


proc AddSoundServer {win} {
  global SoundServers
  set i [lsearch $SoundServers $win]
  if {$i < 0} {
    set SoundServers [linsert $SoundServers 0 $win]
  }
}


proc LostSoundServer {win} {
  DeleteSoundServer $win
#  UIShowPictureOn [WindowLink $win.head] 46 [winfo screen $win]
}


proc DeleteSoundServer {win} {
  global SoundServers
  set i [lsearch $SoundServers $win]
  if {$i >= 0} {
    set SoundServers [lreplace $SoundServers $i $i]
  }
}


proc UISoundOff {} {
}


proc MonsterSpeed {} {
  return [expr "[sim Rand 40] + 70"]
}


proc ExplosionPitch {} {
  return [expr "[sim Rand 20] + 90"]
}


proc HonkPitch {} {
  return [expr "[sim Rand 20] + 90"]
}


########################################################################
# Global Window Handlers


proc WithdrawAll {} {
  WithdrawHeads
  WithdrawEditors
  WithdrawMaps
  WithdrawGraphs
  WithdrawBudgets
  WithdrawEvaluations
  WithdrawSplashes
  WithdrawScenarios
  WithdrawFiles
  WithdrawAsks
  WithdrawPlayers
  WithdrawNotices
  WithdrawHelps
  WithdrawFrobs
}


proc ShowInitial {} {
  ShowHeads
  ShowEditors
  ShowMaps
  EnableMaps
}


########################################################################
# Head Window Handlers


proc PrepHead {head} {
  global State
  InitHeadMenus $head
  case $State {
    uninitialized {
    }
    splash {
      WithdrawHeadOf $head
      ShowSplashOf $head
    }
    scenario {
      after 1000 "WithdrawSplashOf $head"
      WithdrawHeadOf $head
      ShowScenarioOf $head
      sim UpdateMaps
    }
    play {
      WithdrawSplashOf $head
      WithdrawScenarioOf $head
      ShowHeadOf $head
      ShowEditorOf $head
      ShowMapOf $head
      EnableMaps
      ReShowPictureOn $head
      InitHead $head
      InitHeadMenus $head
    }
  }
}


proc ShowHeadOf {head} {
  wm deiconify $head
}


proc WithdrawHeadOf {head} {
  wm withdraw $head
}


proc ShowHeads {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowHeadOf $win
  }
}


proc WithdrawHeads {} {
  global HeadWindows
  foreach win $HeadWindows {
    wm withdraw $win
  }
}


proc DeleteHeadWindow {head} {
  UIQuit $head
}


proc InitHeads {} {
  global HeadWindows
  foreach win $HeadWindows {
    InitHead $win
  }
}


proc InitHead {win} {
  set w [WindowLink $win.text]
  $w configure -state normal
  $w delete 0.0 end
  $w insert end "\n"
  $w configure -state disabled

  if {[sim MultiPlayerMode]} {
    set w [WindowLink $win.entry]
    $w delete 0 end
    global ${w}.value
    set ${w}.value ""
  }

  sim UpdateHeads
  UIUpdateRunning
}


proc InitAllHeadMenus {} {
  global HeadWindows

  foreach win $HeadWindows {
    InitHeadMenus $win
  }
}


proc InitHeadMenus {win} {
  global State
  set m0 [WindowLink $win.m0]
  set m1 [WindowLink $win.m1]
  set m2 [WindowLink $win.m2]
  set m3 [WindowLink $win.m3]
  set m4 [WindowLink $win.m4]
  set b0 [WindowLink $win.b0]
  set b1 [WindowLink $win.b1]
  set b2 [WindowLink $win.b2]
  set b3 [WindowLink $win.b3]
  set b4 [WindowLink $win.b4]
  case $State {
    uninitialized {
    }
    splash {
    }
    scenario {
      $m0 unpost
      $m1 unpost
      $m2 unpost
      $m3 unpost
      $m4 unpost
      $m0 disable 1
      $m0 disable 2
      # When in multi player mode there is an extra menu
      # item to add another player, before the quit item,
      # so compensate for it here.
      if {[sim MultiPlayerMode]} {
        $m0 disable 4
      } else {
        $m0 disable 3
      }
      $b0 config -state normal
      $b2 config -state disabled
      $b4 config -state disabled
    }
    play {
      $m0 enable 1
      $m0 enable 2
      # When in multi player mode there is an extra menu
      # item to add another player, before the quit item,
      # so compensate for it here.
      if {[sim MultiPlayerMode]} {
        $m0 enable 4
      } else {
        $m0 enable 3
      }
      $b0 config -state normal
      $b2 config -state normal
      $b4 config -state normal
    }
  }
}


proc UIDisaster {win cmd action} {
  AskQuestion [Color $win #ff0000 #ffffff] "Cause a Disaster" \
    "Oh no! Do you really want to $action" \
    "{No way!} Disaster.No {WithdrawAsks}" \
    "" \
    "{I guess so.} Disaster.Yes {WithdrawAsks ; $cmd}"
}


proc CrushHead {head} {
  global SubWindows VoteNames

  foreach foo $VoteNames {
    global VotesFor$foo
    set votes [eval ident \$VotesFor$foo]
    set i [lsearch $votes $head]
    if {$i != -1} {
      set VotesFor$foo [lreplace $votes $i $i]
    }
  }

  foreach foo $SubWindows {
    set sym [lindex $foo 0]
    set name [lindex $foo 1]
    global $name
    set wins [eval ident "\$$name"]
    foreach win $wins {
      if {[WindowLink $win.head] == $head} {
	DeleteWindow $sym $name $win
      }
    }
  }
}


proc ChatDown {win} {
  tk_butDown $win
}


proc ChatUp {win} {
  tk_butUp $win

  global Chatting

  if {$Chatting} {
    CloseChat
  } else {
    OpenChat
  }
}


proc OpenChat {} {
  global Chatting
  global ChatServer
  global ChatSocket
  global ChatConnection

  DoSendMessage "Opening Connection to Chat Server $ChatServer socket $ChatSocket ..." status

  set ChatConnection {}
  catch {
    set ChatConnection [connect $ChatServer $ChatSocket]
  }

  if {$ChatConnection == {}} then {
    DoSendMessage "Sorry, I could not open a connection to chat server $ChatServer socket $ChatSocket." status
    set Chatting 0
  } else {
    filehandler $ChatConnection r "ReceiveChat"
    set Chatting 1
  }

  global NickName
  global UserName
  global HostName
  global ServerName
  global RealName
  global ChannelName
  catch {
    puts $ChatConnection "USER $UserName $HostName $ServerName $RealName\r\n" nonewline
    puts $ChatConnection "NICK $NickName\r\n" nonewline
    puts $ChatConnection "JOIN $ChannelName\r\n" nonewline
    flush $ChatConnection
  }
}


proc ReceiveChat {mode f} {
#    DoSendMessage "ReceiveChat: MODE $mode F $f"
    set msg ""
    gets $f msg

    if {[string first {:} $msg]} {
	set msg ": $msg"
    }

    set from [lindex $msg 0]
    set cmd [string tolower [lindex $msg 1]]

    set handled 0

    if {($cmd == "privmsg") ||
        ($cmd == "notice")} then {
      set handled 1
      set chan [lindex $msg 2]
      set i [expr "[string length $from] + 1 + [string length $cmd] + 1 + [string length $chan] + 2"]
      set j [expr "[string length $msg] - 2"]
      set line [string range $msg $i $j]
      set chan [string range $chan 1 [string length $chan]]
      set from [string range $from 1 [expr "[string length $from] - 1"]]
      set from [split $from {!}]
      set from [lindex $from 0]
      DoSendMessage "$from> $line"
    }

    if {$handled == 0} {
	set msg [string range $msg \
		  [expr "[string length $from] + 1"] \
		  [expr "[string length $msg] - 2"]]
	DoSendMessage $msg
    }
}


proc SendChatMessage {msg win} {
    global ChatConnection ChannelName NickName

    if {"$msg" == ""} {
	return
    }

    if {[string range $msg 0 0] == "/"} {
	set cmd [string range $msg 1 [string length $msg]]
        DoSendMessage "$NickName> \[$cmd\]"
	set cmd "$cmd\r\n"
    } else {
	set cmd "PRIVMSG $ChannelName :$msg\r\n"
        DoSendMessage "$NickName> $msg"
    }
    

    set result 1

    catch {
	puts $ChatConnection $cmd nonewline
	flush $ChatConnection
	set result 0
    }

    if {$result} {
	DoSendMessage "IRC Broke the connection"
	CloseChat
    }
}


proc CloseChat {} {
  global Chatting
  global ChatServer
  global ChatSocket
  global ChatConnection

  DoSendMessage "Closing Connection to Chat Server." status

  catch {
    puts $ChatConnection "QUIT\r\n" nonewline
    flush $ChatConnection
    $ChatConnection close
  }

  set ChatConnection {}
  set Chatting 0
}


proc DoEnterMessage {win var} {
  global Chatting
  global $var
  set msg [eval ident "\$\{$var\}"]

  if {$Chatting} then {
    SendChatMessage $msg $win
  } else {
    DoSendMessage $msg
  }
  $win delete 0 end
}


proc DoEvalMessage {win var} {
  global $var
  set command [eval ident "\$\{$var\}"]
  $win delete 0 end
  DoSendMessage "Evaluating TCL: $command"
  catch {uplevel #0 $command} result
  DoSendMessage "Result: $result"
}


proc DoSendMessage {msg {tag message}} {
  global HeadWindows
  foreach win $HeadWindows {
    appendWithTag [WindowLink $win.text] $tag "$msg"
  }
}


proc UISetMessage {msg {tag status}} {
  global DoMessages EditorWindows HeadWindows

  if {$DoMessages == 0} {
      return
  }

  foreach win $EditorWindows {
    [WindowLink $win.message] configure -text "$msg"
  }

  foreach win $HeadWindows {
    appendWithTag [WindowLink $win.text] $tag "$msg"
  }
}




proc appendWithTag {w tag text} {
    global MaxLines
    global ShrinkLines

    set start [$w index end]
    $w configure -state normal
    if {$start > $MaxLines} then {
	$w delete 0.0 $ShrinkLines.0
	set start [$w index end]
    }
    $w insert end "${text}\n"
    $w tag add $tag $start {end - 1 char}
    $w configure -state disabled
    $w yview -pickplace {end - 1 char}
}


########################################################################
# Budget Window Handlers


proc ShowBudgetOf {head} {
  set win [WindowLink $head.budget]
  if {$win == {}} {
    set win [MakeWindow.budget $head [winfo screen $head]]
  }
  wm deiconify $win
  wm raise $win
  update idletasks
  sim UpdateBudget
}


proc ShowBudgets {} {
  global HeadWindows BudgetsVisible
  set BudgetsVisible 1
  foreach win $HeadWindows {
    ShowBudgetOf $win
  }
}


proc WithdrawBudgets {} {
  global BudgetWindows BudgetsVisible
  foreach win $BudgetWindows {
    wm withdraw $win
  }
  StopBudgetTimer
  set BudgetsVisible 0
}


proc BudgetContinue {{win ""}} {
  global OldBudget BudgetRoadFund BudgetFireFund BudgetPoliceFund BudgetTaxRate
  set OldBudget 0
  if {([sim RoadFund] != $BudgetRoadFund) ||
      ([sim FireFund] != $BudgetFireFund) ||
      ([sim PoliceFund] != $BudgetPoliceFund) ||
      ([sim TaxRate] != $BudgetTaxRate)} {
    UISetMessage "The budget was changed."
  } else {
    UISetMessage "The budget wasn't changed."
  }
  WithdrawBudgets
  sim Resume
  MakeRunningSound
}


proc BudgetReset {{win ""}} {
  global OldBudget BudgetRoadFund BudgetFireFund BudgetPoliceFund BudgetTaxRate
  if {([sim RoadFund] != $BudgetRoadFund) ||
      ([sim FireFund] != $BudgetFireFund) ||
      ([sim PoliceFund] != $BudgetPoliceFund) ||
      ([sim TaxRate] != $BudgetTaxRate)} {
    UISetMessage "The budget was reset."
    if {[sim Players] > 1} {
      UIMakeSound edit Sorry
    }
  } else {
    UISetMessage "The budget was reset."
  }
  sim RoadFund $BudgetRoadFund
  sim FireFund $BudgetFireFund
  sim PoliceFund $BudgetPoliceFund 
  sim TaxRate $BudgetTaxRate
  set OldBudget 0
  ChangeBudget
}


proc BudgetCancel {{win ""}} {
  BudgetReset
  WithdrawBudgets
  sim Resume
  MakeRunningSound
}


proc SetTaxRate {rate} {
  sim TaxRate $rate
}


proc BudgetSetTaxRate {rate} {
  SetTaxRate $rate
  ChangeBudget
}


proc BudgetSetRoadFund {percent} {
  sim RoadFund $percent
  ChangeBudget
}


proc BudgetSetFireFund {percent} {
  sim FireFund $percent
  ChangeBudget
}


proc BudgetSetPoliceFund {percent} {
  sim PoliceFund $percent
  ChangeBudget
}


proc UIShowBudgetAndWait {} {
  global OldBudget BudgetRoadFund BudgetFireFund BudgetPoliceFund BudgetTaxRate
  if {$OldBudget == 0} {
    set BudgetRoadFund [sim RoadFund]
    set BudgetFireFund [sim FireFund]
    set BudgetPoliceFund [sim PoliceFund]
    set BudgetTaxRate [sim TaxRate]
    set OldBudget 1
  }
  ShowBudgets
  UISetMessage "Pausing to set the budget ..."
  sim Pause
  MakeRunningSound
  StartBudgetTimer
  InitVotesForBudget
  sim UpdateBudget
  sim UpdateBudgetWindow
}


proc ToggleBudgetTimer {} {
  global BudgetTimerActive
  if {$BudgetTimerActive} {
    StopBudgetTimer
  } else {
    StartBudgetTimer
  }
}


proc StopBudgetTimer {} {
  global BudgetTimerActive
  set BudgetTimerActive 0
  UpdateBudgetTimer
}


proc StartBudgetTimer {} {
  global BudgetTimerActive BudgetTimer BudgetTimeout
  set me [Unique]
  set BudgetTimerActive $me
  set BudgetTimer $BudgetTimeout
  UpdateBudgetTimer
  after 1000 TickBudgetTimer $me
}


proc RestartBudgetTimer {} {
  global BudgetTimerActive
  if {$BudgetTimerActive} {
    StopBudgetTimer
    StartBudgetTimer
  }
}


proc UpdateBudgetTimer {} {
  global BudgetWindows BudgetTimerActive BudgetTimer
  if {$BudgetTimerActive} {
    set text [format "Auto Cancel In %d Seconds (click to disable)" $BudgetTimer]
  } else {
    set text [format "Enable Auto Cancel (currently disabled)"]
  }
  foreach win $BudgetWindows {
    set t [WindowLink $win.timer]
    $t config -text "$text"
  }
}


proc TickBudgetTimer {me} {
  global BudgetTimerActive BudgetTimer BudgetTimeout
  if {$BudgetTimerActive == $me} {
    incr BudgetTimer -1
    if {$BudgetTimer < 0} {
      StopBudgetTimer
      UpdateBudgetTimer
      FireBudgetTimer
    } else {
      UpdateBudgetTimer
      after 1000 TickBudgetTimer $me
    }
  }
}


proc FireBudgetTimer {} {
  BudgetCancel
}


proc funds {n} {
  sim Funds $n
}


proc ToggleAutoBudget {} {
  global AutoBudget
  if {$AutoBudget} {
      #echo "ToggleAutoBudget found on, clearing"
      sim AutoBudget 0
  } else {
      #echo "ToggleAutoBudget found off, setting"
      sim AutoBudget 1
  }
}


proc UIUpdateBudget {} {
  UpdateAutoBudget
}


proc UpdateAutoBudget {} {
  global BudgetWindows AutoBudget
  if {[sim AutoBudget]} {
    set text "Disable Auto Budget (currently enabled)"
  } else {
    set text "Enable Auto Budget (currently disabled)"
  }
  #echo "UpdateAutoBudget $AutoBudget $text"
  foreach win $BudgetWindows {
    set t [WindowLink $win.autobudget]
    $t config -text "$text"
  }
}


proc UISetBudget {cashflow previous current collected taxrate} {
  global BudgetWindows BudgetsVisible

  #echo "UISetBudgetValues $taxrate $BudgetsVisible"

  if {$BudgetsVisible} {

    foreach win $BudgetWindows {
      set w [WindowLink $win.cashflow]
      set old [lindex [$w configure -text] 4]
      if {$old != $cashflow} {
	$w configure -text $cashflow
      }
      set w [WindowLink $win.previous]
      set old [lindex [$w configure -text] 4]
      if {$old != $previous} {
	$w configure -text $previous
      }
      set w [WindowLink $win.current]
      set old [lindex [$w configure -text] 4]
      if {$old != $current} {
	$w configure -text $current
      }
      set w [WindowLink $win.collected]
      set old [lindex [$w configure -text] 4]
      if {$old != $collected} {
	$w configure -text $collected
      }

      set w [WindowLink $win.taxrate]
      set old [$w get]
      if {$old != $taxrate} {
	$w set $taxrate
      }

      set w [WindowLink $win.taxlabel]
      set old [lindex [$w configure -text] 4]
      set new "$taxrate%"
      if {$old != $new} {
	$w configure -text $new
      }
    }
  }

  global HeadWindows
  foreach win $HeadWindows {

    set w [WindowLink $win.taxrate]
    set old [$w get]
    if {$old != $taxrate} {
      # FIXME: this might not work if the slider is disabled in multi player mode.
      $w set $taxrate
    }

    set w [WindowLink $win.taxlabel]
    set old [lindex [$w configure -text] 4]
    set new "Tax Rate: $taxrate%"
    if {$old != $new} {
      $w configure -text $new
    }
  }
}


proc UISetBudgetValues {roadgot roadwant roadpercent policegot policewant policepercent firegot firewant firepercent} {
  global BudgetWindows BudgetsVisible

  if {$BudgetsVisible == 0} {
      return;
  }

  foreach win $BudgetWindows {
    set w [WindowLink $win.fire].request
    set old [lindex [$w configure -text] 4]
    set new "$firepercent% of $firewant = $firegot"
    if {$old != $new} {
      $w configure -text $new
    }
    set w [WindowLink $win.fire].fund
    set old [$w get]
    if {$old != $firepercent} {
      $w set $firepercent
    }

    set w [WindowLink $win.police].request
    set old [lindex [$w configure -text] 4]
    set new "$policepercent% of $policewant = $policegot"
    if {$old != $new} {
      $w configure -text $new
    }
    set w [WindowLink $win.police].fund
    set old [$w get]
    if {$old != $policepercent} {
      $w set $policepercent
    }

    set w [WindowLink $win.road].request
    set old [lindex [$w configure -text] 4]
    set new "$roadpercent% of $roadwant = $roadgot"
    if {$old != $new} {
      $w configure -text $new
    }
    set w [WindowLink $win.road].fund
    set old [$w get]
    if {$old != $roadpercent} {
      $w set $roadpercent
    }
  }
}


proc ChangeBudget {} {
  global VotesForBudget
  if {"$VotesForBudget" != ""} {
    InitVotesForBudget
  }
  RestartBudgetTimer
}


proc InitVotesForBudget {} {
  global VotesForBudget BudgetWindows
  set VotesForBudget {}
  foreach win $BudgetWindows {
    [WindowLink $win.vote] config -relief raised
  }
  UpdateVotesForBudget
}


proc UpdateVotesForBudget {} {
  global BudgetWindows
  UpdateVotesFor Budget $BudgetWindows
}


proc UpdateTaxRateSliders {} {
  global HeadWindows
  set players [sim Players]
  foreach win $HeadWindows {
    set slider [WindowLink $win.taxrate]
    #echo "UpdateTaxRateSliders players $players win $win slider $slider"
    if {$players == 1} {
      $slider configure -state normal
    } else {
      $slider configure -state disabled
    }
  }
}


########################################################################
# Evaluation Window Handlers


proc ToggleEvaluationOf {head} {
  global State
  if {"$State" != "play"} {
    return
  }

  set mapped 0
  set win [WindowLink $head.evaluation]
  if {$win != ""} {
    set mapped [winfo ismapped $win]
  }

  if {$mapped} {
    WithdrawEvaluationOf $head
  } else {
    ShowEvaluationOf $head
  }

}


proc WithdrawEvaluationOf {head} {
  set win [WindowLink $head.evaluation]
  if {"$win" != ""} {
    pack unpack $win
  }
}


proc ShowEvaluationOf {head} {
  set win [WindowLink $head.evaluation]
  if {$win == {}} {
    set win [MakeWindow.evaluation $head [winfo screen $head]]
  }
  #wm raise $win
  #wm deiconify $win
  set parent [WindowLink $win.parent]
  #pack append [WindowLink $head.col2]\
  #  $parent {top frame nw fill}
  pack append $parent\
    $win {top frame nw fillx}
  update idletasks
  sim UpdateEvaluation
}


proc WithdrawEvaluations {} {
  global EvaluationWindows EvaluationsVisible
  foreach win $EvaluationWindows {
    #wm withdraw $win
    #set parent [WindowLink $win.parent]
    #pack unpack $parent
    pack unpack $win
  }
  set EvaluationsVisible 0
}


proc EvaluationVisible {w v} {
    global EvaluationsVisible
    global [set var $w.visible]
    
    set $var $v

    if ($v) {
	set EvaluationsVisible [expr "$EvaluationsVisible + 1"]
    } else {
	set EvaluationsVisible [expr "$EvaluationsVisible - 1"]
    }
}


proc UISetEvaluation {changed score ps0 ps1 ps2 ps3 pv0 pv1 pv2 pv3 pop delta assessed cityclass citylevel goodyes goodno title} {
  global EvaluationWindows EvaluationsVisible CurrentDate

  set class [string tolower $cityclass]
  UISetMessage "$CurrentDate: Score $score, $class population $pop."

  if {$EvaluationsVisible} {

    foreach win $EvaluationWindows {

      global [set var $win.visible]
      set visible [eval ident "\$\{$var\}"]

      if {$visible} {

	# TODO: set evaluation window and icon title
	#wm title $win "$title"
	#wm iconname $win "$title"

	set w [WindowLink $win.goodjob]
	set old [lindex [$w configure -text] 4]
	set new "$goodyes\n$goodno"
	if {$old != $new} {
	  $w configure -text $new
	}

	set w [WindowLink $win.problemnames]
	set old [lindex [$w configure -text] 4]
	set new "$ps0\n$ps1\n$ps2\n$ps3"
	if {$old != $new} {
	  $w configure -text $new
	}

	set w [WindowLink $win.problempercents]
	set old [lindex [$w configure -text] 4]
	set new "$pv0\n$pv1\n$pv2\n$pv3"
	if {$old != $new} {
	  $w configure -text $new
	}

	set w [WindowLink $win.stats]
	set old [lindex [$w configure -text] 4]
	set new "$pop\n$delta\n\n$assessed\n$cityclass\n$citylevel"
	if {$old != $new} {
	  $w configure -text $new
	}

	set w [WindowLink $win.score]
	set old [lindex [$w configure -text] 4]
	set new "$score\n$changed"
	if {$old != $new} {
	  $w configure -text $new
	}
      }
    }
  }
}


########################################################################
# File Window Handlers


proc ShowFileOf {head} {
  set win [WindowLink $head.file]
  if {$win == {}} {
    set win [MakeWindow.file $head [winfo screen $head]]
  }
  wm deiconify $win
  wm raise $win
  return $win
}


proc ShowFiles {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowFileOf $win
  }
}


proc WithdrawFiles {} {
  global FileWindows
  foreach win $FileWindows {
    wm withdraw $win
  }
}


proc DoFileDialog {win Message Path Pattern FileName ActionOk ActionCancel} {
  ShowFileDialog $win "$Path" "$Pattern"
  $win.message1 configure -text "$Message"
  $win.path.path delete 0 end
  $win.path.path insert 0 $Path
  $win.file.file delete 0 end
  $win.file.file insert 0 "$FileName"
  $win.frame1.ok config -command "
      $ActionOk \[$win.file.file get\] \[$win.path.path get\]
      wm withdraw $win"
  $win.frame1.rescan config -command "
      ShowFileDialog $win \[$win.path.path get\] $Pattern"
  $win.frame1.cancel config -command "
      $ActionCancel
      wm withdraw $win"
  bind $win.files.files "<Double-Button-1>" "\
    FileSelectDouble $win %W %y $Pattern \"
	$ActionOk {\[$win.file.file get\]} {\[$win.path.path get\]}\""
  bind $win.path.path <Return> "
    ShowFileDialog $win \[$win.path.path get\] $Pattern
    $win.file.file cursor 0
    focus $win.file.file"
  bind $win.file.file <Return> "\
    $ActionOk \[$win.file.file get\] \[$win.path.path get\]
    wm withdraw $win"
}


proc BindSelectOne {win Y} {
  set Nearest [$win nearest $Y]
  if {$Nearest >= 0} {
    $win select from $Nearest
    $win select to $Nearest
  }
}


proc FileSelect {win widget Y} {
  BindSelectOne $widget $Y
  set Nearest [$widget nearest $Y]
  if {$Nearest >= 0} {
    set Path [$win.path.path get]
    set TmpEntry [$widget get $Nearest]
    if {[string compare "/" [string index $TmpEntry \
          [expr [string length $TmpEntry]-1]]] == 0 || \
        [string compare "@" [string index $TmpEntry \
          [expr [string length $TmpEntry]-1]]] == 0} {
      # handle directories, and symbolic links to directories
      set FileName [string range $TmpEntry 0 \
            [expr [string length $TmpEntry]-2]]
      # whoops / or @ is part of the name
      if {[MiscIsDir $Path/$FileName] != 1} {
        set FileName $TmpEntry
      }
    } {
      if {[string compare "*" [string index $TmpEntry \
            [expr [string length $TmpEntry]-1]]] == 0} {
        # handle executable filenames
        set FileName [string range $TmpEntry 0 \
              [expr [string length $TmpEntry]-2]]
        # whoops * is part of the name
        if {[file executable $Path/$FileName] != 1} {
          set FileName $TmpEntry
        }
      } {
        # a ordinary filename
        set FileName $TmpEntry
      }
    }
    # enter the selected filename into the filename field
    if {[MiscIsDir $Path/$FileName] != 1} {
      $win.file.file delete 0 end
      $win.file.file insert 0 $FileName
    }
  }
}


proc FileSelectDouble {win widget Y Pattern Action} {
  BindSelectOne $widget $Y
  set Nearest [$widget nearest $Y]
  if {$Nearest >= 0} {
    set Path [$win.path.path get]
    set TmpEntry [$widget get $Nearest]
    if {[string compare $TmpEntry "../"] == 0} {
      # go up one directory
      set TmpEntry \
        [string trimright [string trimright [string trim $Path] /] @]
      if {[string length $TmpEntry] <= 0} {
        return
      }
      set Path [file dirname $TmpEntry]
      $win.path.path delete 0 end
      $win.path.path insert 0 $Path
      ShowFileDialog $win $Path $Pattern
    } {
      if {[string compare "/" [string index $TmpEntry \
            [expr [string length $TmpEntry]-1]]] == 0 || \
          [string compare "@" [string index $TmpEntry \
            [expr [string length $TmpEntry]-1]]] == 0} {
        # handle directorys, and symbolic links to directorys
        set FileName [string range $TmpEntry 0 \
              [expr [string length $TmpEntry]-2]]
        # whoops / or @ is part of the name
        if {[MiscIsDir $Path/$FileName] != 1} {
          set FileName $TmpEntry
        }
      } {
        if {[string compare "*" [string index $TmpEntry \
              [expr [string length $TmpEntry]-1]]] == 0} {
          # handle executable filenames
          set FileName [string range $TmpEntry 0 \
                [expr [string length $TmpEntry]-2]]
          # whoops * is part of the name
          if {[file executable $Path/$FileName] != 1} {
            set FileName $TmpEntry
          }
        } {
          # a ordinary filename
          set FileName $TmpEntry
        }
      }
      # change directory
      if {[MiscIsDir $Path/$FileName] == 1} {
        if {[string compare "/" [string index $Path \
              [expr [string length $Path]-1]]] == 0} {
           append Path $FileName
        } {
          append Path / $FileName
        }
        $win.path.path delete 0 end
        $win.path.path insert 0 $Path
        ShowFileDialog $win $Path $Pattern
      } {
        # enter the selected filename into the filename field
	$win.file.file delete 0 end
	$win.file.file insert 0 "$FileName"
        if {[string length $Action] > 0} {
          eval $Action
        }
        wm withdraw $win
      }
    }
  }
}


proc NameComplete {win Type} {

  set NewFile ""
  set Matched ""

  if {[string compare $Type path] == 0} {
    set DirName [file dirname [$win.path.path get]]
    set FileName [file tail [$win.path.path get]]
  } {
    set DirName [file dirname [$win.path.path get]/]
    set FileName [file tail [$win.file.file get]]
  }

  set FoundCounter 0
  if {[MiscIsDir $DirName] == 1} {
    catch "exec ls $DirName/" Result
    set Counter 0
    set ListLength [llength $Result]
    # go through list
    while {$Counter < $ListLength} {
      if {[string length $FileName] == 0} {
        if {$FoundCounter == 0} {
          set NewFile [lindex $Result $Counter]
        } {
          set Counter1 0
          set TmpFile1 $NewFile
          set TmpFile2 [lindex $Result $Counter]
          set Length1 [string length $TmpFile1]
          set Length2 [string length $TmpFile2]
          set NewFile ""
          if {$Length1 > $Length2} {
            set Length1 $Length2
          }
          while {$Counter1 < $Length1} {
            if {[string compare [string index $TmpFile1 $Counter1] \
                  [string index $TmpFile2 $Counter1]] == 0} {
              append NewFile [string index $TmpFile1 $Counter1]
            } {
              break
            }
            incr Counter1 1
          }
        }
        incr FoundCounter 1
      } {
        if {[regexp "^$FileName" [lindex $Result $Counter] \
              Matched] == 1} {
          if {$FoundCounter == 0} {
            set NewFile [lindex $Result $Counter]
          } {
            set Counter1 0
            set TmpFile1 $NewFile
            set TmpFile2 [lindex $Result $Counter]
            set Length1 [string length $TmpFile1]
            set Length2 [string length $TmpFile2]
            set NewFile ""
            if {$Length1 > $Length2} {
              set Length1 $Length2
            }
            while {$Counter1 < $Length1} {
              if {[string compare [string index $TmpFile1 $Counter1] \
                    [string index $TmpFile2 $Counter1]] == 0} {
                append NewFile [string index $TmpFile1 $Counter1]
              } {
                break
              }
              incr Counter1 1
            }
          }
          incr FoundCounter 1
        }
      }
      incr Counter 1
    }
  }

  if {$FoundCounter == 1} {
    if {[MiscIsDir $DirName/$NewFile] == 1} {
      if {[string compare $DirName "/"] == 0} {
        $win.path.path delete 0 end
        $win.path.path insert 0 "/[string trim [string trim $NewFile /] @]/"
      } {
        $win.path.path delete 0 end
        $win.path.path insert 0 "[string trimright $DirName /]/[string trim [string trim $NewFile /] @]/"
      }
    } {
      $win.path.path delete 0 end
      $win.path.path insert 0 \
        "[string trim [string trimright $DirName /] @]/"
      $win.file.file delete 0 end
      $win.file.file insert 0 "$NewFile"
    }
  } {
    if {[MiscIsDir $DirName/$NewFile] == 1 ||
        [string compare $Type path] == 0} {
      $win.path.path delete 0 end
      $win.path.path insert 0 \
        "[string trimright $DirName /]/[string trim [string trim $NewFile /] @]"
    } {
      $win.path.path delete 0 end
      $win.path.path insert 0 "$DirName"
      if {[string length $NewFile] > 0} {
        $win.file.file delete 0 end
        $win.file.file insert 0 "$NewFile"
      }
    }
  }
}


proc ShowFileDialog {win Path Pattern} {
  busy $win {
    #set Path [lindex [split $Path] 0]
    if {[$win.files.files size] > 0} {
      $win.files.files delete 0 end
    }
    # read directory
    if {[catch "exec ls -F \"$Path\"" Result]} {
      set ElementList {}
    }
    if {[string match $Result "* not found"]} {
      set ElementList {}
    }
    set ElementList [lsort [split $Result "\n"]]

    # insert ..
    if {[string compare $Path "/"]} {
      $win.files.files insert end "../"
    }

    # walk through list
    foreach Counter $ElementList {
      # insert filename
      if {[string match $Pattern $Counter] == 1} {
	if {[string compare $Counter "../"] &&
	    [string compare $Counter "./"]} {
	  $win.files.files insert end $Counter
	}
      } else {
        set fn $Path/[string trim [string trim [string trim $Counter /] @] *]
	if {[MiscIsDir $fn]} {
	  $win.files.files insert end $Counter
	}
      }
    }
  }
}


proc MiscIsDir {PathName} {

  if {[file isdirectory $PathName] == 1} {
    return 1
  } {
    catch "file type $PathName" Type
    if {[string compare $Type link] == 0} {
      set LinkName [file readlink $PathName]
      catch "file type $LinkName" Type
      while {[string compare $Type link] == 0} {
        set LinkName [file readlink $LinkName]
      }
      return [file isdirectory $LinkName]
    }
  }
  return 0
}


proc busy {win cmds} {
    set busy {}
    set list [winfo children $win]
    set busy $list
    while {$list != ""} {
	set next {}
	foreach w $list {
	    set class [winfo class $w]
	    set cursor [lindex [$w config -cursor] 4]
	    if {[winfo toplevel $w] == $w} {
		lappend busy [list $w $cursor]
	    }
	    set next [concat $next [winfo children $w]]
	}
	set list $next
    }

    foreach w $busy {
	catch {[lindex $w 0] config -cursor watch}
    }

    update idletasks

    set error [catch {uplevel eval [list $cmds]} result]

    foreach w $busy {
	catch {[lindex $w 0] config -cursor [lindex $w 1]}
    }

    if $error {
	error $result
    } else {
	return $result
    }
}


########################################################################
# Editor Window Handlers

proc ShowEditorOf {head} {
  global EditorWindows
  set found 0
  foreach win $EditorWindows {
    if {[WindowLink $win.head] == $head} {
      set parent [WindowLink $win.parent]
      #pack append [WindowLink $head.col2]\
      #  $parent {top frame nw expand fill}
      pack append $parent\
	$win {top frame nw expand fill}
      set found 1
    }
  }
  if {$found == 0} {
    NewEditorOf $head
  } else {
    update idletasks
    sim UpdateEditors
    sim UpdateMaps
  }
}


proc NewEditorOf {head} {
  set win [MakeWindow.editor $head [winfo screen $head]]
  #wm deiconify $win
  set parent [WindowLink $win.parent]
  pack append $parent\
    $win {top frame nw expand fill}
  update idletasks
  sim UpdateEditors
  sim UpdateMaps
}


proc ShowEditors {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowEditorOf $win
  }
}


proc WithdrawEditors {} {
  global EditorWindows
  foreach win $EditorWindows {
    #set parent [WindowLink $win.parent]
    #pack unpack $parent
    pack unpack $win
  }
}


proc InitEditors {} {
  global EditorWindows
  foreach win $EditorWindows {
    InitEditor $win
  }
}


proc InitEditor {win} {
  set e [WindowLink $win.view]
  UISetToolState $win 7
  $e ToolState 7
  set size [$e size]
  $e Pan 960 800
  $e AutoGoing 0
  global $e.TrackState
  set $e.TrackState {}
}


proc SetEditorAutoGoto {win val} {
  global AutoGoto.$win
  set AutoGoto.$win $val
  set e [WindowLink $win.view]
  $e AutoGoto $val
}


proc SetEditorControls {win val} {
  global Controls.$win
  set Controls.$win $val
  if {$val} {
    pack append $win $win.leftframe {left frame center filly} 
  } else {
    pack unpack $win.leftframe
  }
}


proc SetEditorOverlay {win val} {
  global Overlay.$win
  set Overlay.$win $val
  set e [WindowLink $win.view]
  $e ShowOverlay $val
}


proc SetEditorDynamicFilter {win val} {
  global DynamicFilter.$win
  set DynamicFilter.$win $val
  set e [WindowLink $win.view]
  $e DynamicFilter $val
  if {$val == 1} then {
    ShowFrobOf [WindowLink $win.head]
  }
}


proc SetEditorSkip {win val} {
  set e [WindowLink $win.view]
  $e Skip $val
}


proc EditorToolDown {mod w x y} {
  global [set var $w.TrackState]

  $w ToolMode 1

  case [$w ToolState] in \
    7 { # bulldozer
      UIMakeSoundOn $w edit Rumble "-repeat 4"
    } \
    10 { # chalk
      StartChalk $w
    }

  case $mod in \
    constrain {
      set $var [list constrain_start $x $y]
      $w ToolConstrain $x $y
    } \
    default {
      set $var none
    }
  EditorTool ToolDown $w $x $y
  sim NeedRest 5
}


proc EditorToolDrag {w x y} {
  EditorTool ToolDrag $w $x $y
  sim NeedRest 5
}


proc EditorToolUp {w x y} {
  global [set var $w.TrackState]
  $w ToolMode 0

  case [$w ToolState] in \
    7 { # bulldozer
      stopdozer
    } \
    10 { # chalk
      StopChalk $w
    }

  EditorTool ToolUp $w $x $y
  set $var {}
  $w ToolConstrain -1 -1
  sim UpdateMaps
  sim UpdateEditors
  sim NeedRest 5
}


proc EditorTool {action w x y} {
  global [set var $w.TrackState]
  set state [eval ident "\$\{$var\}"]
  case [lindex $state 0] in \
    constrain_start {
      set x0 [lindex $state 1]
      set y0 [lindex $state 2]
      set dx [expr "$x - $x0"]
      set dy [expr "$y - $y0"]
      if [expr "($dx > 16) || ($dx < -16)"] then {
        $w ToolConstrain -1 $y0
        set $var none
      } else {
	if [expr "($dy > 16) || ($dy < -16)"] then {
	  $w ToolConstrain $x0 -1
	  set $var none
	}
      }
    }
  $w $action $x $y
}


proc StartChalk {w} {
  sim CollapseMotion 0
}


proc StopChalk {w} {
  sim CollapseMotion 1
}


proc EditorPanDown {mod w x y} {
  global [set var $w.TrackState]
  $w ToolMode -1
  case $mod in \
    constrain {
      set $var [list constrain_start $x $y]
      $w ToolConstrain $x $y
    } \
    default {
      set $var none
    }
  EditorTool PanStart $w $x $y
}


proc EditorPanDrag {w x y} {
  EditorTool PanTo $w $x $y
}


proc EditorPanUp {w x y} {
  $w AutoGoing 0
  $w ToolMode 0
  EditorTool PanTo $w $x $y
  $w ToolConstrain -1 -1
  sim UpdateMaps
  sim UpdateEditors
}


proc EditorKeyDown {w k} {
  $w KeyDown $k
}


proc EditorKeyUp {w k} {
  $w KeyUp $k
}


proc BindEditorButtons {win} {
  set w [WindowLink $win.top]

  bind $win <1> "CancelPie $win ; EditorToolDown none %W %x %y"
  bind $win <B1-Motion> {EditorToolDrag %W %x %y}
  bind $win <ButtonRelease-1> {EditorToolUp %W %x %y}

  bind $win <Control-1> "CancelPie $win ; EditorToolDown constrain %W %x %y"
  bind $win <Control-B1-Motion> {EditorToolDrag %W %x %y}
  bind $win <Control-ButtonRelease-1> {EditorToolUp %W %x %y}

  bind $win <2> "CancelPie $win ; EditorPanDown none %W %x %y"
  bind $win <B2-Motion> {EditorPanDrag %W %x %y}
  bind $win <ButtonRelease-2> {EditorPanUp %W %x %y}

  bind $win <Control-2> "CancelPie $win ; EditorPanDown constrain %W %x %y"
  bind $win <Control-B2-Motion> {EditorPanDrag %W %x %y}
  bind $win <Control-ButtonRelease-2> {EditorPanUp %W %x %y}

  InitPie $win $w.toolpie
}


proc UISetFunds {funds} {
  global HeadWindows
  foreach win $HeadWindows {
    [WindowLink $win.funds] configure -text "$funds"
  }
}


proc UISetDate {date month year} {
  global HeadWindows
  global CurrentDate
  
  set CurrentDate "$date"

  foreach win $HeadWindows {
    [WindowLink $win.date] Set $month $year
  }
}


proc SetPriority {index} {
  case $index { \
    {0} {
      sim Delay 500000
      sim Skips 0
    } \
    {1} {
      sim Delay 100000
      sim Skips 0
    } \
    {2} {
      sim Delay 25000
      sim Skips 0
    } \
    {3} {
      sim Delay 5000
      sim Skips 20
    } \
    {4} {
      sim Delay 5
      sim Skips 500
    }
  }
}


proc UISetDemand {r c i} {
  global HeadWindows DemandRes DemandCom DemandInd

  set DemandRes $r
  set DemandCom $c
  set DemandInd $i

  if {$r <= 0} then {set ry0 32} else {set ry0 24}
  set ry1 [expr "$ry0 - $r"]
  if {$c <= 0} then {set cy0 32} else {set cy0 24}
  set cy1 [expr "$cy0 - $c"]
  if {$i <= 0} then {set iy0 32} else {set iy0 24}
  set iy1 [expr "$iy0 - $i"]

  foreach win $HeadWindows {
    set can [WindowLink $win.demand]
#    $can coords r 8 $ry0 14 $ry1
#    $can coords c 17 $cy0 23 $cy1
#    $can coords i 26 $iy0 32 $iy1
    $can coords r 49 $ry0 55 $ry1
    $can coords c 58 $cy0 64 $cy1
    $can coords i 67 $iy0 73 $iy1
  }
}


proc UISetOptions {autobudget autogoto autobulldoze disasters sound animation messages notices} {
  global AutoBudget AutoGoto AutoBulldoze Disasters Sound
  set AutoBudget $autobudget
  set AutoGoto $autogoto
  set AutoBulldoze $autobulldoze
  set Disasters $disasters
  set Sound $sound
  set DoAnimation $animation
  set DoMessages $messages
  set DoNotices $notices
}


proc UIDidToolRes {win x y} {
  UIMakeSoundOn $win edit O "-speed 140"
}


proc UIDidToolCom {win x y} {
  UIMakeSoundOn $win edit A "-speed 140"
}


proc UIDidToolInd {win x y} {
  UIMakeSoundOn $win edit E "-speed 140"
}


proc UIDidToolFire {win x y} {
  UIMakeSoundOn $win edit O "-speed 130"
}


proc UIDidToolQry {win x y} {
  UIMakeSoundOn $win edit E "-speed 200"
}


proc UIDidToolPol {win x y} {
  UIMakeSoundOn $win edit E "-speed 130"
}


proc UIDidToolWire {win x y} {
  UIMakeSoundOn $win edit O "-speed 120"
}


proc UIDidToolDozr {win x y} {
  UIMakeSoundOn $win edit Rumble
}


proc UIDidToolRail {win x y} {
  UIMakeSoundOn $win edit O "-speed 100"
}


proc UIDidToolRoad {win x y} {
  UIMakeSoundOn $win edit E "-speed 100"
}


proc UIDidToolChlk {win x y} {
}


proc UIDidToolEraser {win x y} {
}


proc UIDidToolStad {win x y} {
  UIMakeSoundOn $win edit O "-speed 90"
}


proc UIDidToolPark {win x y} {
  UIMakeSoundOn $win edit A "-speed 130"
}


proc UIDidToolSeap {win x y} {
  UIMakeSoundOn $win edit E "-speed 90"
}


proc UIDidToolCoal {win x y} {
  UIMakeSoundOn $win edit O "-speed 75"
}


proc UIDidToolNuc {win x y} {
  UIMakeSoundOn $win edit E "-speed 75"
}


proc UIDidToolAirp {win x y} {
  UIMakeSoundOn $win edit A "-speed 50"
}


proc UISetToolState {w state} {
  global EditorPallets EditorPalletImages ToolInfo
  set win [WindowLink $w.top]
  #echo "UISETTOOLSTATE w $w win $win $state"
  ExclusivePallet $state $win $EditorPallets ic $EditorPalletImages \
	raised sunken {NoFunction}
	{NoFunction}
  set c1 [WindowLink $w.cost1]
  if {"$c1" != ""} {
    set info [lindex $ToolInfo $state]
    set cost1 [lindex $info 1]
    set cost2 [lindex $info 2]
    $c1 configure -text "$cost1"
    [WindowLink $w.cost2] configure -text "$cost2"
  }
}


proc UIShowZoneStatus {zone density value crime pollution growth x y} {
  global QueryX QueryY
  set QueryX [expr "8 + 16 * $x"]
  set QueryY [expr "8 + 16 * $y"]
  UIShowPicture 9 [list $zone $density $value $crime $pollution $growth]
}


########################################################################
# Map Window Handlers


proc ShowMapOf {head} {
  global MapWindows
  set found 0
  foreach win $MapWindows {
    if {"[WindowLink $win.head]" == "$head"} {
      global MapPanelWidth MapPanelHeight
      #place configure $win -x 0 -y 0 -width $MapPanelWidth -height $MapPanelHeight
      #[WindowLink $win.parent] configure -width $MapPanelWidth -height $MapPanelHeight
      set parent [WindowLink $win.parent]
      pack append [WindowLink $head.w2] \
	  $win {top frame nw expand fill}
      set found 1
    }
  }
  if {$found == 0} {
    NewMapOf $head
  } else {
    update idletasks
    sim UpdateMaps
  }
}


proc NewMapOf {head} {
  set win [MakeWindow.map $head [winfo screen $head]]
  global MapPanelWidth MapPanelHeight
  #place configure $win -x 0 -y 0 -width $MapPanelWidth -height $MapPanelHeight
  #[WindowLink $win.parent] configure -width $MapPanelWidth -height $MapPanelHeight
  set parent [WindowLink $win.parent]
  #pack append [WindowLink $head.col1]\
  #  $parent {top frame nw fillx}
  pack append [WindowLink $head.w2] \
      $win {top frame nw expand fill}
  sim UpdateMaps
}


proc ShowMaps {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowMapOf $win
  }
}


proc WithdrawMaps {} {
  global MapWindows
  foreach win $MapWindows {
    #place forget $win
    pack unpack $win
  }
}


proc InitMaps {} {
  global MapWindows
  foreach win $MapWindows {
    InitMap $win
  }
}


proc InitMap {win} {
  SetMapState $win 0
}


proc EnableMaps {} {
  global MapWindows
  foreach win $MapWindows {
    EnableMap $win
  }
}


proc EnableMap {win} {
  [WindowLink $win.view] ShowEditors 1
  [WindowLink $win.zones] config -state normal
  [WindowLink $win.overlays] config -state normal
}


proc DisableMaps {} {
  global MapWindows
  foreach win $MapWindows {
    DisableMap $win
  }
}


proc DisableMap {win} {
  [WindowLink $win.view] ShowEditors 0
  [WindowLink $win.zones] config -state disabled
  [WindowLink $win.overlays] config -state disabled
}


proc SetMapState {win state} {
  set m [WindowLink $win.view]
  $m MapState $state
  if {$state == 14} then {
    ShowFrobOf [WindowLink $win.head]
  }
}


proc MapPanDown {w x y} {
  $w PanStart $x $y
}


proc MapPanDrag {w x y} {
  $w PanTo $x $y
}


proc MapPanUp {w x y} {
  $w PanTo $x $y
  sim UpdateMaps
  sim UpdateEditors
}


proc UISetMapState {w state} {
  global MapTitles
  #set win [winfo toplevel $w]
  set win [WindowLink $w.win]
  set m [WindowLink $win.view]
  set title [lindex $MapTitles $state]

  # TODO: set map text field header to title
  #wm title $win "$title"
  #wm iconname $win "$title"

  global [set var MapState.$win]
  set $var $state

  case $state { \
    {6 8 9 10 11 12 13} {
      [WindowLink $win.legend] config -bitmap "@images/legendmm.xpm"
    } \
    {7} {
      [WindowLink $win.legend] config -bitmap "@images/legendpm.xpm"
    } \
    {0 1 2 3 4 5 14} {
      [WindowLink $win.legend] config -bitmap "@images/legendn.xpm"
    }
  }
}


########################################################################
# Graph Window Handlers


proc ToggleGraphOf {head} {
  global State
  if {"$State" != "play"} {
    return
  }

  set mapped 0
  set win [WindowLink $head.graph]
  if {$win != ""} {
    set mapped [winfo ismapped $win]
  }

  if {$mapped} {
    WithdrawGraphOf $head
  } else {
    ShowGraphOf $head
  }

}


proc WithdrawGraphOf {head} {
  set win [WindowLink $head.graph]
  if {"$win" != ""} {
    pack unpack $win
  }
}


proc ShowGraphOf {head} {
  set win [WindowLink $head.graph]
  if {$win == {}} {
    set win [MakeWindow.graph $head [winfo screen $head]]
  }
  #wm deiconify $win
  #wm raise $win
  set parent [WindowLink $win.parent]
  pack append $parent\
    $win {top frame nw fillx}
  update idletasks
  sim UpdateGraphs
}


proc WithdrawGraphs {} {
  global GraphWindows
  foreach win $GraphWindows {
    #wm withdraw $win
    pack unpack $win
  }
}


proc InitGraphs {} {
  global GraphWindows
  foreach win $GraphWindows {
    InitGraph $win
  }
}


proc InitGraph {win} {
  UISetGraphState $win 1 1 1 1 1 1 0
}


proc UISetGraphState {win t0 t1 t2 t3 t4 t5 range} {
  set g [WindowLink $win.graphview]
  GraphPalletMask $win [expr "$t0 + ($t1<<1) + ($t2<<2) + ($t3<<3) + ($t4<<4) + ($t5<<5)"]
  GraphYearPallet $win $range
}


########################################################################
# Splash Window Handlers


proc ShowSplashOf {head} {
  set win [WindowLink $head.splash]
  if {$win == {}} {
    set win [MakeWindow.splash $head [winfo screen $head]]
  }
  set splashscreen [WindowLink $win.splashscreen]
  set success 0
  catch {$splashscreen config -bitmap "@images/splashscreen.xpm"; set success 1}
  if {$success} {
    wm deiconify $win
    global SplashScreenDelay
    after $SplashScreenDelay "UIPickScenarioMode"
  } else {
    UIPickScenarioMode
  }
}


proc WithdrawSplashOf {head} {
  set win [WindowLink $head.splash]
  if {$win != {}} {
    wm withdraw $win
  }
}


proc ShowSplashes {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowSplashOf $win
  }
}


proc WithdrawSplashes {} {
  global SplashWindows
  foreach win $SplashWindows {
    wm withdraw $win
    set splashscreen [WindowLink $win.splashscreen]
    $splashscreen config -bitmap ""
  }
}


proc InitSplashes {} {
}


proc InitSplash {win} {
}


proc DeleteSplashWindow {win} {
  # TODO
}


########################################################################
# Scenario Window Handlers


proc ShowScenarioOf {head} {
  set win [WindowLink $head.scenario]
  if {$win == {}} {
    set win [MakeWindow.scenario $head [winfo screen $head]]
  }
  # TODO: load background bitmap
  wm deiconify $win
}


proc WithdrawScenarioOf {head} {
  set win [WindowLink $head.scenario]
  if {$win != {}} {
    wm withdraw $win
  }
}


proc ShowScenarios {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowScenarioOf $win
  }
}


proc WithdrawScenarios {} {
  global ScenarioWindows
  foreach win $ScenarioWindows {
    wm withdraw $win
    # TODO: flush background bitmap
  }
}


proc InitScenarios {} {
  global MapHistory MapHistoryNum
  if {$MapHistoryNum < 1} {
    set prev disabled
  } else {
    set prev normal
  }
  if {$MapHistoryNum == ([llength $MapHistory] - 1)} {
    set next disabled
  } else {
    set next normal
  }
  global ScenarioWindows
  foreach win $ScenarioWindows {
    # TODO
    #[WindowLink $win.previous] config -state $prev
    #[WindowLink $win.next] config -state $next
  }
}


proc InitScenario {win} {
  global MapHistory MapHistoryNum
  if {$MapHistoryNum < 1} {
    set prev disabled
  } else {
    set prev normal
  }

  if {$MapHistoryNum == ([llength $MapHistory] - 1)} {
    set next disabled
  } else {
    set next normal
  }

  # TODO
  #[WindowLink $win.previous] config -state $prev
  #[WindowLink $win.next] config -state $next

  LinkWindow $win.scenarioTarget -1
  LinkWindow $win.scenarioTargetDown -1

  global ScenarioButtons
  set i 0
  set len [llength $ScenarioButtons]
  while {$i < $len} {
    set data [lindex $ScenarioButtons $i]
    set type [lindex $data 0]
    set id [lindex $data 1]
    #echo "DATA $data"
    #echo "ID $id"

    LinkWindow $win.$id.over 0
    LinkWindow $win.$id.enabled 1
    LinkWindow $win.$id.checked 0
    #echo "SETTING WIN $win ID $id"

    set i [expr "$i + 1"]
  }

  UpdateLevelSelection $win
  UpdateLeftRightEnabled $win
}


proc UpdateLevelSelection {win} {
  #echo UpdateLevelSelection
  global GameLevel
  if {$GameLevel == 0} then {
    LinkWindow $win.easy.checked 1
    LinkWindow $win.medium.checked 0
    LinkWindow $win.hard.checked 0
  }
  if {$GameLevel == 1} then {
    LinkWindow $win.easy.checked 0
    LinkWindow $win.medium.checked 1
    LinkWindow $win.hard.checked 0
  }
  if {$GameLevel == 2} then {
    LinkWindow $win.easy.checked 0
    LinkWindow $win.medium.checked 0
    LinkWindow $win.hard.checked 1
  }

  UpdateScenarioButtonID $win easy
  UpdateScenarioButtonID $win medium
  UpdateScenarioButtonID $win hard

}


proc UpdateLeftRightEnabled {win} {
  #echo UpdateLeftRightEnabled

  global MapHistory MapHistoryNum
  if {$MapHistoryNum < 1} {
    LinkWindow $win.left.enabled 0
  } else {
    LinkWindow $win.left.enabled 1
  }

  if {$MapHistoryNum == ([llength $MapHistory] - 1)} {
    LinkWindow $win.right.enabled 0
  } else {
    LinkWindow $win.right.enabled 1
  }

  UpdateScenarioButtonID $win left
  UpdateScenarioButtonID $win right
}


proc UpdateScenarioButtonID {win id} {

  global ScenarioButtons
  set i 0
  set len [llength $ScenarioButtons]
  while {$i < $len} {
    set data [lindex $ScenarioButtons $i]
    set id 
    if {$id == [lindex $data 1]} then {
      UpdateScenarioButton $win $data
      break
    }

    set i [expr "$i + 1"]
  }
}


proc UpdateScenarioButton {win data} {
  global Messages

  set type [lindex $data 0]
  set id [lindex $data 1]
  set over [WindowLink $win.$id.over]
  set enabled [WindowLink $win.$id.enabled]
  set checked [WindowLink $win.$id.checked]
  #echo "WIN $win TYPE $type ID $id OVER $over ENABLED $enabled CHECKED $checked"
  if {$over} {
    if {[lindex ${data} 2] == "DoPickScenario"} {
      catch {text $win.desc \
      	-borderwidth 2 \
      	-relief flat \
      	-wrap word \
      	-state normal \
      	-font [Font $win Large]}
      
      $win.desc configure -state normal
      $win.desc delete 0.0 end
      $win.desc insert end "[lindex $Messages([lindex ${data} 3]) 1]\n\n[lindex $Messages([lindex ${data} 3]) 2]"
      $win.desc configure -state disabled
      
      place $win.desc -x 232 -y 170 -width 280 -height 285
    }
  } else {
    catch {destroy $win.desc}
  }
  if {$enabled} {
    if {$checked} {
      if {$over} {
        set bm [lindex $data 13]
      } else {
        set bm [lindex $data 12]
      }
    } else {
      if {$over} {
        set bm [lindex $data 10]
      } else {
        set bm [lindex $data 9]
      }
    }
  } else {
    set bm [lindex $data 11]
  }

  [WindowLink $win.canvas] itemconfig $id -bitmap $bm
}


proc DoEnterCityName {win} {
}


proc InitVotesForUseThisMap {} {
  # TODO: Disabled for new scenario window.
  return

  global VotesForUseThisMap ScenarioWindows
  set VotesForUseThisMap {}
  foreach win $ScenarioWindows {
    [WindowLink $win.vote] config -relief raised
  }
  UpdateVotesForUseThisMap
}


proc UpdateVotesForUseThisMap {} {
  global ScenarioWindows
  UpdateVotesFor UseThisMap $ScenarioWindows
}


proc UIUseThisMap {} {
  global CityName GameLevel Scenario
  WithdrawAll
  # special handling for scenarios?
  if {$GameLevel != -1} {
    sim GameLevel $GameLevel
  }
  sim CityName $CityName
  UINewGame
  UIPlayGame
  if {$Scenario != -1} {
    UIShowPicture $Scenario
  }
}


proc HandleScenarioDown {win x y} {
  #echo HandleScenarioDown $win $x $y
  HandleScenarioMove $win $x $y
  set w [WindowLink $win.w]
  set target [WindowLink $w.scenarioTarget]
  LinkWindow $w.scenarioTargetDown $target
}


proc HandleScenarioUp {win x y} {
  #echo HandleScenarioUp $win $x $y
  HandleScenarioMove $win $x $y
  global ScenarioButtons
  set w [WindowLink $win.w]
  set target [WindowLink $w.scenarioTarget]
  set targetDown [WindowLink $w.scenarioTargetDown]
  if {($target != -1) &&
      ($target == $targetDown)} {
    set data [lindex $ScenarioButtons $target]
    set type [lindex $data 0]
    set id [lindex $data 1]
    set callback [lindex $data 2]
    set param [lindex $data 3]
    set var [lindex $data 4]
    set xx [lindex $data 5]
    set yy [lindex $data 6]
    set ww [lindex $data 7]
    set hh [lindex $data 8]
    set normal [lindex $data 9]
    set over [lindex $data 10]
    set disabled [lindex $data 11]
    if {$type == "button"} {
      #echo callback $callback w $w param $param
      eval "$callback $w {$param}"
    } else {
      if {$type == "checkbox"} {
        #echo checkbox callback $callback w $w param $param
	eval "$callback $w {$param}"
      }
    }
  }
}


proc HandleScenarioMove {win x y} {
  #echo HandleScenarioMove $win $x $y
  global ScenarioButtons
  set w [WindowLink $win.w]
  set target [WindowLink $w.scenarioTarget]
  set found -1
  set i 0
  set len [llength $ScenarioButtons]
  while {$i < $len} {
    set data [lindex $ScenarioButtons $i]
    set type [lindex $data 0]
    set id [lindex $data 1]
    set callback [lindex $data 2]
    set param [lindex $data 3]
    set var [lindex $data 4]
    set xx [lindex $data 5]
    set yy [lindex $data 6]
    set ww [lindex $data 7]
    set hh [lindex $data 8]

    set enabled [WindowLink $w.$id.enabled]
    set checked [WindowLink $w.$id.checked]

    #echo "ID $id ENABLED $enabled CHECKED $checked w $w id $id"

    if {($enabled != 0) &&
        ($x >= $xx) &&
	($x < ($xx + $ww)) &
	($y >= $yy) &&
	($y < ($yy + $hh))} {
      set found $i
      break
    }

    set i [expr "$i + 1"]
  }

  if {$found != $target} {

    if {$found == -1} {
      if {$target != -1} { 

	#echo OUT $w $found $xx $yy $normal
	LinkWindow $w.scenarioTarget -1

        set targetdata [lindex $ScenarioButtons $target]
	set targetid [lindex $targetdata 1]
	LinkWindow $w.$targetid.over 0
        UpdateScenarioButton $w $targetdata

      }
    } else {

      #echo IN $w $found $xx $yy $over
      LinkWindow $w.scenarioTarget $found
      LinkWindow $w.$id.over 1

      if {$target != -1} {
        set targetdata [lindex $ScenarioButtons $target]
	set targetid [lindex $targetdata 1]
	LinkWindow $w.$targetid.over 0
	UpdateScenarioButton $w $targetdata
      }

      UpdateScenarioButton $w $data

    }
  }
}

proc DoLoad {win param} {
  #echo DOLOAD $win $param
  UILoadCity $win
}


proc DoGenerate {win param} {
  #echo DOGENERATE $win $param
  UIGenerateNewCity
}


proc DoQuit {win param} {
  #echo DOQUIT $win $param
  UIQuit $win
}


proc DoAbout {win param} {
  #echo DOABOUT $win $param
  MakeHistory "DoLoadCity cities/about.cty"
}


proc DoMap {win param} {
  #echo DOMAP $win $param
}


proc DoLevel {win param} {
  #echo DOLEVEL $win $param
  DoSetGameLevel $param
}


proc DoLeft {win param} {
  #echo DOLEFT $win $param
  PrevHistory
}


proc DoRight {win param} {
  #echo DORIGHT $win $param
 NextHistory
}


proc DoPlay {win param} {
  #echo DOPLAY $win $param
  UIUseThisMap
}


proc DoPickScenario {win param} {
  #echo DOPICKSCENARIO $win $param
  UILoadScenario $param
}

proc DeleteScenarioWindow {win} {
  UIQuit $win
}


########################################################################
# Undo/Redo Facility


proc InitHistory {} {
  global MapHistory
  global MapHistoryNum
  set MapHistory {}
  set MapHistoryNum -1
}


proc MakeHistory {cmd} {
  global MapHistory
  set len [llength $MapHistory]
  if {($len == 0) ||
      ($cmd != [lindex $MapHistory [expr $len-1]])} {
    lappend MapHistory $cmd
  } else {
    incr len -1
  }
  GotoHistory $len
}


proc GotoHistory {i} {
  global MapHistory
  global MapHistoryNum
  InitVotesForUseThisMap
  if {$i != $MapHistoryNum} {
    set MapHistoryNum $i
    set cmd [lindex $MapHistory $i]
    eval $cmd
  }
  if {$MapHistoryNum == 0} {
    set prev disabled
  } else {
    set prev normal
  }
  if {$MapHistoryNum == ([llength $MapHistory] - 1)} {
    set next disabled
  } else {
    set next normal
  }

  global ScenarioWindows
  foreach win $ScenarioWindows {
    UpdateLeftRightEnabled $win
  }

}


proc NextHistory {} {
  global MapHistory
  global MapHistoryNum
  set len [llength $MapHistory]
  set i [expr "$MapHistoryNum + 1"]
  if {$i < $len} {
    GotoHistory $i
  }
}


proc PrevHistory {} {
  global MapHistory
  global MapHistoryNum
  set i [expr "$MapHistoryNum - 1"]
  if {$i >= 0} {
    GotoHistory $i
  }
}


########################################################################
# Ask Window Handlers

proc ShowAskOf {head} {
  set win [WindowLink $head.ask]
  if {$win == {}} {
    set win [MakeWindow.ask $head [winfo screen $head]]
  }
  wm deiconify $win
  wm raise $win
  return $win
}


proc ShowAsks {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowAskOf $win
  }
}


proc WithdrawAsks {} {
  global AskWindows
  foreach win $AskWindows {
    wm withdraw $win
  }
}


proc WithdrawAskOf {win} {
  set ask [WindowLink $win.ask]
  if {"$ask" != ""} {
    wm withdraw $ask
  }
}


proc AskQuestion {color title text left middle right} {
  global HeadWindows
  foreach win $HeadWindows {
    AskQuestionOn $win $color $title $text $left $middle $right
  }
}


proc AskQuestionOn {head color title text left middle right} {
  ShowAskOf $head

  set win [WindowLink $head.ask]
  set t [WindowLink $win.title]
  $t configure -text $title
  $t configure -background $color

  set t [WindowLink $win.text]
  $t configure -state normal
  $t delete 0.0 end
  $t insert end "${text}\n"
  $t configure -state disabled

  set bf [WindowLink $win.frame]
  set l [WindowLink $win.left]
  set m [WindowLink $win.middle]
  set r [WindowLink $win.vote]
  set rf [WindowLink $win.voteframe]

  if {$left != ""} {
    $l config \
	-text [lindex $left 0] \
	-command [format [lindex $left 2] $head]
    SetHelp $l [lindex $left 1]
    pack append $bf $l {left frame center}
  } else {
    pack unpack $l
  }

  if {$middle != ""} {
    $m config \
	-text [lindex $middle 0] \
	-command [format [lindex $middle 2] $head]
    SetHelp $m [lindex $middle 1]
    pack append $bf $m {left frame center expand}
  } else {
    pack unpack $m
  }

  if {$right != ""} {
    set notify [format [lindex $right 2] $head]
    set preview [format [lindex $right 3] $head]
    set cmd [list DoVote $win Ask $notify $preview]
    $r config \
	-text [lindex $right 0] \
	-command $cmd
    SetHelp $r [lindex $right 1]
    pack append $bf $rf {right frame center}
  } else {
    pack unpack $rf
  }

  InitVotesForAsk
}


proc BindVotingButton {win but name} {
  set w [WindowLink $win.top]

  bind $but <Any-Enter> "VoteButtonEnter $win $but"
  bind $but <Any-Leave> "VoteButtonLeave $win $but"
  bind $but <1> "VoteButtonDown $win $but $name"
  bind $but <ButtonRelease-1> "VoteButtonUp $win $but $name"
  bind $but <2> "VoteButtonDown $win $but $name"
  bind $but <ButtonRelease-2> "VoteButtonUp $win $but $name"
  bind $but <3> "VoteButtonDown $win $but $name"
  bind $but <ButtonRelease-3> "VoteButtonUp $win $but $name"
}


proc VoteButtonEnter {win but} {
  global tk_priv
  set screen [winfo screen $but]
  if {[lindex [$but config -state] 4] != "disabled"} {
    $but config -state active
    set tk_priv(window@$screen) $but
  } else {
    set tk_priv(window@$screen) ""
  }
}


proc VoteButtonLeave {win but} {
  global tk_priv
  if {[lindex [$but config -state] 4] != "disabled"} {
    $but config -state normal
  }
  set screen [winfo screen $but]
  set tk_priv(window@$screen) ""
}


proc VoteButtonDown {win but name} {
  global tk_priv
  set screen [winfo screen $but]
  set rel [lindex [$but config -relief] 4]
  set tk_priv(relief@$screen) $rel
  if {[lindex [$but config -state] 4] != "disabled"} {
    set head [WindowLink $win.head]
    if {[IsVotingFor $head $name]} {
      $but config -relief raised
    } else {
      $but config -relief sunken
    }
  }
}


proc VoteButtonUp {win but name} {
  global tk_priv
  set screen [winfo screen $but]
  $but config -relief $tk_priv(relief@$screen)
  if {($but == $tk_priv(window@$screen))
	&& ([lindex [$but config -state] 4] != "disabled")} {
    uplevel #0 [list $but invoke]
    set head [WindowLink $win.head]
    if {[IsVotingFor $head $name]} {
      $but config -relief sunken
    } else {
      $but config -relief raised
    }
  }
}


proc PressVoteButton {win but name} {
  global tk_priv
  uplevel #0 [list $but invoke]
  set head [WindowLink $win.head]
  if {[IsVotingFor $head $name]} {
    $but config -relief sunken
  } else {
    $but config -relief raised
  }
}


proc IsVotingFor {win name} {
  global VotesFor$name
  set votes [eval ident "\$\{VotesFor$name\}"]
  if {[lsearch $votes $win] == -1} {
    return 0
  } else {
    return 1
  }
}


proc DoVote {win name notify preview} {
  global VotesFor$name
  set votes [eval ident "\$\{VotesFor$name\}"]

  set win [WindowLink $win.head]
  set i [lsearch $votes $win]
  if {$i == -1} {
    lappend VotesFor$name $win
  } else {
    set VotesFor$name [lreplace $votes $i $i]
  }
  UpdateVotesFor$name
  set votes [eval ident "\$\{VotesFor$name\}"]
  if {[llength $votes] >= [NeededVotes]} {
    eval "$notify"
  } else {
    eval "$preview"
  }
}


proc UpdateVotesFor {name wins} {
  global VotesFor$name
  set votes [eval llength "\$\{VotesFor$name\}"]
  set needed [NeededVotes]

  foreach win $wins {
    set head [WindowLink $win.head]
    if {[IsVotingFor $head $name]} {
      set border [expr "($needed - $votes) * 1"]
      set pad [expr "6 - $border"]
      [WindowLink $win.vote] config -padx $pad -pady $pad
      [WindowLink $win.voteframe] config -borderwidth $border
    } else {
      set border [expr "($needed - $votes - 1) * 1"]
      set pad [expr "6 - $border"]
      [WindowLink $win.vote] config -padx $pad -pady $pad
      [WindowLink $win.voteframe] config -borderwidth $border
    }
  }
}


proc InitVotesForAsk {} {
  global VotesForAsk AskWindows
  set VotesForAsk {}
  foreach win $AskWindows {
    [WindowLink $win.vote] config -relief raised
  }
  sim PendingTool -1
  UpdateVotesForAsk
}


proc UpdateVotesForAsk {} {
  global AskWindows
  UpdateVotesFor Ask $AskWindows
}


########################################################################
# Player Window Handlers

proc ShowPlayerOf {head} {
  set win [WindowLink $head.player]
  if {$win == {}} {
    set win [MakeWindow.player $head [winfo screen $head]]
  }
  wm deiconify $win
  wm raise $win
  return $win
}


proc ShowPlayers {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowPlayerOf $win
  }
}


proc WithdrawPlayers {} {
  global PlayerWindows
  foreach win $PlayerWindows {
    wm withdraw $win
  }
}


proc UpdatePlayers {} {
  # TODO: Disabled for new scenario window.
  return

  global HeadWindows PlayerWindows

  set players ""
  foreach win $HeadWindows {
    set server [winfo screen $win]
#    if {[string first : $server] == 0} {
#      set server "[exec hostname]:0"
#    }
    lappend players $server
  }

  sim Players [llength $players]

  foreach win $PlayerWindows {
    set list [WindowLink $win.players]
    $list delete 0 end
    eval "$list insert 0 $players"
  }

  UpdateVotesForUseThisMap
  UpdateVotesForAsk
  UpdateVotesForBudget
  UpdateTaxRateSliders
}


proc UIShowPlayer {win} {
  ShowPlayerOf $win
}


proc DoNewPlayer {win} {
  set field [WindowLink $win.display]
  set dpy [$field get]
  if {"$dpy" != ""} {
    $field delete 0 end
    sim Flush
    update idletasks
    if {[AddPlayer $dpy] != ""} {
      wm withdraw $win
    }
  }
}

########################################################################
# Notice Window Handlers


proc ShowNoticeOf {head} {
  set win [WindowLink $head.notice]
  if {$win == {}} {
    set win [MakeWindow.notice $head [winfo screen $head]]
  }
  global NoticePanelWidth NoticePanelHeight
  #place configure $win -x 0 -y 0 -width $NoticePanelWidth -height $NoticePanelHeight
  pack append [WindowLink $head.w3] \
      $win {bottom frame sw expand fill}
  return $win
}


proc ShowNotices {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowNoticeOf $win
  }
}


proc WithdrawNotices {} {
  global NoticeWindows
  foreach win $NoticeWindows {
    #place forget $win
    pack unpack $win
  }
}


proc ReShowPictureOn {{head ""}} {
  global ShowingPicture ShowingParms
  UIShowPictureOn $head $ShowingPicture $ShowingParms
}


proc UIShowPicture {id {parms ""}} {
  UIShowPictureOn "" $id $parms
}


proc UIShowPictureOn {where id {parms ""}} {
  global DoNotices Messages ShowingPicture ShowingParms
  if {$DoNotices == 0} {
      return
  }

  set ShowingPicture $id
  set ShowingParms $parms
  set msg $Messages($id)
  set color [lindex $msg 0]
  set title [lindex $msg 1]
  set body [lindex $msg 2]
  if {$parms != ""} {
    set cmd "format {$body} $parms"
    set body [uplevel #0 $cmd]
  }
  set props [lindex $msg 3]
  if {"$where" == ""} {
    global HeadWindows
    set where $HeadWindows
  }
  foreach head $where {
    NoticeMessageOn $head "$title" $color "$body" Medium $props
  }
}


proc NoticeMessageOn {head title color text font props} {
  ShowNoticeOf $head
  set win [WindowLink $head.notice]

  set t [WindowLink $win.title]
  $t configure -text $title -background $color

  set t [WindowLink $win.text]
  $t configure -state normal -font [Font $head $font]
  $t delete 0.0 end
  $t insert end "${text}\n"
  $t configure -state disabled

  set left ""
  catch {set left [keylget props left]}
  set l [WindowLink $win.left]
  if {$left != ""} {
    $l config -bitmap $left
    place $l -in $t -anchor sw -relx .05 -rely .95
  } else {
    place forget $l
  }

  set middle ""
  catch {set middle [keylget props middle]}
  set m [WindowLink $win.middle]
  if {$middle != ""} {
    $m config -bitmap $middle
    place $m -in $t -anchor s -relx .5 -rely .95
  } else {
    place forget $m
  }

  set right ""
  catch {set right [keylget props right]}
  set r [WindowLink $win.right]
  if {$right != ""} {
    $r config -bitmap $right
    place $r -in $t -anchor se -relx .95 -rely .95
  } else {
    place forget $r
  }

  set view ""
  catch {set view [keylget props view]}
  set vf [WindowLink $win.viewframe]
  global v
  set v [WindowLink $win.view]
  set bg [WindowLink $win.background]
  if {$view != ""} {
    uplevel #0 "$view"
    pack unpack $t
    pack append $bg $vf {left frame center fill}
    pack append $bg $t {right frame center fill expand}
  } else {
    pack unpack $vf
  }
}


proc UIPopUpMessage {msg} {
  DoSendMessage $msg
}


proc ComeToMe {view} {
  set win [winfo toplevel $view]

  set xy [$view Pan]
  set x [expr "[lindex $xy 0] >>4"]
  set y [expr "[lindex $xy 1] >>4"]

  ComeTo $win $x $y
}


proc ComeTo {win x y} {
  global EditorWindows
  set head [WindowLink $win.head]
  set myeds {}
  set myautoeds {}
  foreach ed $EditorWindows {
    if {"[WindowLink $ed.head]" == "$head"} {
      lappend myeds $ed
      set view [WindowLink $ed.view]
      if {[$view AutoGoto]} {
        lappend myautoeds $ed
      }
    }
  }
  if {[llength $myautoeds]} {
    UIAutoGotoOn $x $y $myautoeds
  } else {
    if {[llength $myeds]} {
      UIAutoGotoOn $x $y $myeds
    }
  }
}


proc FollowView {view id} {
  $view Follow $id

  set skips 999999
  if {[sim DoAnimation]} {
    set head [WindowLink [winfo toplevel $view].head]
    global EditorWindows
    foreach win $EditorWindows {
      if {"[WindowLink $win.head]" == "$head"} {
	set s [[WindowLink $win.view] Skip]
	set skips [min $skips $s]
      }
    }

    if {$skips == 999999} {
      set skips 0
    }
  }

  $view Skip $skips
  $view Update
}


proc PanView {view x y} {
  FollowView $view ""
  $view Pan $x $y
}


########################################################################
# Help Window Handlers


proc ShowHelpOf {head} {
  set win [WindowLink $head.help]
  if {$win == {}} {
    set win [MakeWindow.help $head [winfo screen $head]]
  }
  wm deiconify $win
  wm raise $win
  return $win
}


proc ShowHelps {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowHelpOf $win
  }
}


proc WithdrawHelps {} {
  global HelpWindows
  foreach win $HelpWindows {
    wm withdraw $win
  }
}


########################################################################
# Frob Window Handlers


proc ShowFrobOf {head} {
  set win [WindowLink $head.frob]
  if {$win == {}} {
    set win [MakeWindow.frob $head [winfo screen $head]]
  }
  wm deiconify $win
  wm raise $win

  return $win
}


proc ShowFrobs {} {
  global HeadWindows
  foreach win $HeadWindows {
    ShowFrobOf $win
  }
}


proc WithdrawFrobs {} {
  global FrobWindows
  foreach win $FrobWindows {
    wm withdraw $win
  }
}


proc UISetDynamic {i min max} {
  sim DynamicData [expr "$i*2"] $min
  sim DynamicData [expr "$i*2+1"] $max
}


########################################################################
# Help Handler


proc LoadHelp {} {
  global ResourceDir

  source $ResourceDir/help.tcl
}

proc HandleHelp {win x y rootx rooty} {
  global HelpLoaded HelpWidgets Messages

  if {$HelpLoaded == 0} {
    LoadHelp
    set HelpLoaded 1
  }

  set orig $win
  set head [WindowLink [winfo toplevel $win].head]
  set id ""
  while {1} {
    catch {set id $HelpWidgets($win)}
    if {$id != ""} {
      break
    }
    set list [split $win .]
    set len [expr "[llength $list] - 2"]
    set list [lrange $list 0 $len]
    if {[llength $list] <= 1} {
      set id Window
      break
    }
    set win [join $list .]
  }
  if [info exists Messages($id)] {
    UIShowHelpOn $head $id
  } else {
    UIShowHelpOn $head Window
  }
}


proc UIShowHelpOn {win id {parms ""}} {
  global Messages ShowingPicture ShowingParms ResourceDir
  set head [WindowLink $win.head]
  set msg $Messages($id)
  set color [lindex $msg 0]
  set title [lindex $msg 1]
  set body [lindex $msg 2]
  if {$parms != ""} {
    set cmd "format {$body} $parms"
    set body [uplevel #0 $cmd]
  }
  set props [lindex $msg 3]

  ShowHelpOf $head
  set win [WindowLink $head.help]

  set t [WindowLink $win.title]
  $t configure -text $title -background $color

  set t [WindowLink $win.text]
  $t configure -state normal -font [Font $head Large]
  $t delete 0.0 end
  $t insert end "${body}\n"
  FormatHTML $ResourceDir/doc/$id.html $t
  $t configure -state disabled
}


proc FormatHTML {filename text} {
  set f ""
  catch {
    set f [open $filename]
    set line ""
    set header ""
    set title ""
    gets $f header
    gets $f title

    while {[gets $f line] >= 0} {
      if {"$line" == "</body>"} {
	break
      }
      if {([string index $line 0] == "#") || ([string length $line] == 0)} {
	continue
      }
      $text insert end "$line\n"
    }
  }
  if {$f != ""} {
    close $f
  }
}


proc SetHelp {win id} {
  global HelpWidgets
  set HelpWidgets($win) $id
}


proc Help {id title {msg {}} {props {}}} {
  Message $id #7f7fff $title $msg $props
}

########################################################################
# Pie Menu Handlers


# Set up the bindings to pop up $pie when the right button is clicked in $win
proc InitPie {win pie} {
  bind $win <Motion> {}
  bind $win <3> "PieMenuDown $win $pie $pie Initial %X %Y"
  bind $win <B3-Motion> {}
  bind $win <B3-ButtonRelease> {}
}


# Set up the bindings to continue tracking $pie
# Get this: we keep the tracking machine state in the bindings!
proc ActivatePie {win root pie state} {
  bind $win <Motion> "PieMenuMotion $win $root $pie $state %X %Y"
  bind $win <3> "PieMenuDown $win $root $pie $state %X %Y"
  bind $win <B3-Motion> "PieMenuMotion $win $root $pie $state %X %Y"
  bind $win <B3-ButtonRelease> "PieMenuUp $win $root $pie $state %X %Y"
}


# Cancel and reset a pie menu
proc CancelPie {win} {
  set binding [bind $win <3>]
  set root [lindex $binding 2]
  set pie [lindex $binding 3]
  set state [lindex $binding 4]
  if {"$state" != "Initial"} {
    catch {$root ungrab $win}
    $pie unpost
    $pie activate none
    UIMakeSoundOn $win fancy Oop
  }
  InitPie $win $root
}


# Handle pie menu button down
proc PieMenuDown {win root pie state x y} {
  case $state {
    Initial {
      ActivatePie $win $root $pie FirstDown
      update idletasks
      catch {$root grab $win}
      $pie activate none
      $pie post $x $y
      PreviewPieMenu $win $pie $x $y
      update idletasks
    }
    ClickedUp {
      TrackPieMenu $pie $x $y
      ActivatePie $win $root $pie SecondDown
    }
    SelectedUp {
      $pie activate none
      #$pie post $x $y
      $pie defer
      PreviewPieMenu $win $pie $x $y
      ActivatePie $win $root $pie SecondDown
    }
    FirstDown { # error
      CancelPie $win
    }
    SecondDown { # error
      CancelPie $win
    }
  }
}


# Handle pie menu button motion
proc PieMenuMotion {win root pie state x y} {
  case $state {
    FirstDown {
      TrackPieMenu $pie $x $y
      $pie defer
    }
    ClickedUp {
      $pie activate none
      #$pie post $x $y
    }
    SecondDown {
      TrackPieMenu $pie $x $y
      $pie defer
    }
    SelectedUp {
      $pie activate none
      #$pie post $x $y
    }
    Initial { # error
      CancelPie $win
    }
  }
}


# Handle pie menu button up
proc PieMenuUp {win root pie state x y} {
  case $state {
    FirstDown {
      TrackPieMenu $pie $x $y
      set active [$pie index active]
      if {$active == "none"} {
	$pie show
        catch {$root grab $win}
        ActivatePie $win $root $pie ClickedUp
      } else {
        set label [lindex [$pie entryconfig $active -label] 4]
        set submenu [lindex [$pie entryconfig $active -piemenu] 4]
	UIMakeSoundOn $win mode $label
	if {$submenu == {}} {
	  set reward [$pie pending]
	  catch {$root ungrab $win}
	  $pie unpost
          $pie activate none
          if {$reward} {
	    sim Funds [expr "[sim Funds] + 5"]
	    UIMakeSoundOn $win fancy Aaah
	  }
	  eval [lindex [$pie entryconfig $active -command] 4]
          InitPie $win $root	
	} else {
	  $pie unpost
          $pie activate none
          $submenu activate none
          $submenu post $x $y
	  PreviewPieMenu $win $submenu $x $y
          catch {$root grab $win}
	  ActivatePie $win $root $submenu SelectedUp
	}
      }
    }
    SecondDown {
      TrackPieMenu $pie $x $y
      set active [$pie index active]
      if {$active == "none"} {
	CancelPie $win
      } else {
        set label [lindex [$pie entryconfig $active -label] 4]
        set submenu [lindex [$pie entryconfig $active -piemenu] 4]
	UIMakeSoundOn $win mode $label
	if {$submenu == {}} {
	  set reward [$pie pending]
	  catch {$root ungrab $win}
	  $pie unpost
          $pie activate none
          if {$reward} {
	    sim Funds [expr "[sim Funds] + 5"]
	    UIMakeSoundOn $win fancy Aaah
	  }
	  eval [lindex [$pie entryconfig $active -command] 4]
	  InitPie $win $root
	} else {
	  $pie unpost
          $pie activate none
          $submenu activate none
          $submenu post $x $y
	  PreviewPieMenu $win $submenu $x $y
          catch {$root grab $win}
	  ActivatePie $win $root $submenu SelectedUp
	}
      }
    }
    Initial { # error
      CancelPie $win
    }
    ClickedUp { # error
      CancelPie $win
    }
    SelectedUp { # error
      CancelPie $win
    }
  }
}


# Track the selected item
proc TrackPieMenu {pie x y} {
  $pie activate @$x,$y
}


proc PreviewPieMenu {win pie x y} {
  set preview [lindex [$pie config -preview] 4]
  if {"$preview" != ""} {
    set rx [winfo rootx $win]
    set ry [winfo rooty $win]
    set x [expr "$x - $rx"]
    set y [expr "$y - $ry"]
    eval [format $preview $x $y]
  }
}


########################################################################
# Pallet Handlers


proc ExclusivePallet {state parent children prefix images inactive active cmd} {
  #echo "ExclusivePallet state $state parent $parent children $children prefix $prefix images $images inactive $inactive active $active cmd $cmd"
  set i 0
  foreach child $children {
    set name [lindex $images $i]
    if {$i == $state} then {
      $parent.$child config \
	  -bitmap "@images/${prefix}${name}hi.xpm" \
	  -relief $active
    } else {
      $parent.$child config \
	  -bitmap "@images/${prefix}${name}.xpm" \
	  -relief $inactive
    }
    incr i
  }
  eval [concat $cmd $state]
}


proc NonExclusivePallet {mask parent children prefix images
			 inactive active cmd} {
  set i 0
  foreach child $children {
    set name [lindex $images $i]
    if {$mask & (1<<$i)} then {
      $parent.$child config \
	  -bitmap "@images/${prefix}${name}hi.xpm" \
	  -relief $active
    } else {
      $parent.$child config \
	  -bitmap "@images/${prefix}${name}.xpm" \
	  -relief $inactive
    }
    incr i
  }
  eval [concat $cmd $mask]
}


proc EditorPallet {win state} {
  global EditorPalletSounds
  UIMakeSoundOn $win mode [lindex $EditorPalletSounds $state]
  EditorSetTool $win $state
}


proc EditorSetTool {win state} {
  global EditorPallets
  global EditorPalletImages
  ExclusivePallet $state $win $EditorPallets ic $EditorPalletImages \
	flat raised "$win.centerframe.view ToolState"
}


proc GraphPallet {win state} {
  set mask [[WindowLink $win.graphview] Mask]
  set mask [expr "$mask ^ (1<<$state)"]
  GraphPalletMask $win $mask
}


proc GraphPalletMask {win mask} {
  global GraphPallets
  global GraphPalletImages
  NonExclusivePallet $mask $win $GraphPallets gr $GraphPalletImages \
	flat flat "SetGraphState $win"
}


proc GraphYearPallet {win state} {
  global GraphYearPallets
  global GraphYearPalletImages
  ExclusivePallet $state $win $GraphYearPallets gr $GraphYearPalletImages \
	flat flat "SetGraphYearState $win"
}


proc SetGraphYearState {win state} {
  set graph [WindowLink $win.graphview]
  if {$state == 0} {
    $graph Range 10
  } else {
    $graph Range 120
  }
}


proc SetGraphState {win mask} {
  global GraphPallets
  set graph [WindowLink $win.graphview]
  $graph Mask $mask
}


########################################################################
# Button Handlers

proc sim_butEnter {w} {
  global tk_priv
  set screen [winfo screen $w]
  set tk_priv(window@$screen) $w
}


proc sim_butLeave {w} {
  global tk_priv
  set screen [winfo screen $w]
  set tk_priv(window@$screen) ""
}


proc sim_butDown {w} {
  global tk_priv
  set screen [winfo screen $w]
  set pict [lindex [$w config -bitmap] 4]
  set tk_priv(relief@$screen) $pict
  $w config -bitmap [lindex [split $pict .] 0]hi.xpm
  update idletasks
}


proc sim_butUp {w} {
  global tk_priv
  set screen [winfo screen $w]
  $w config -bitmap $tk_priv(relief@$screen)
  update idletasks
  if {$w == $tk_priv(window@$screen)} {
    uplevel #0 [list $w invoke]
  }
}


proc BindSimButton {w} {
  bind $w <Any-Enter> {sim_butEnter %W}
  bind $w <Any-Leave> {sim_butLeave %W}
  bind $w <1> {sim_butDown %W}
  bind $w <ButtonRelease-1> {sim_butUp %W}
  bind $w <2> {sim_butDown %W}
  bind $w <ButtonRelease-2> {sim_butUp %W}
  bind $w <3> {sim_butDown %W}
  bind $w <ButtonRelease-3> {sim_butUp %W}
}


########################################################################
# Internal Callbacks


proc UIStartMicropolis {homedir resourcedir hostname} {
  global HomeDir ResourceDir HostName HeadWindows
  set HomeDir $homedir
  set ResourceDir $resourcedir
  set HostName $hostname
  sim InitGame
  sim GameStarted
  update

  foreach display [sim Displays] {
    if {"[AddPlayer $display]" == ""} {
      echo Couldn't add a player on $display ...
    }
  }

  if {"$HeadWindows" == ""} {
    echo Micropolis is exiting because it couldn't connect to any players.
    sim ReallyQuit
  }
}


proc UISelectCity {win} {
  AskQuestion [Color $win #ff0000 #ffffff] "Choose Another City" \
    "Do you want to abandon this city and choose another one?" \
    "{Keep playing.} SelectCity.No {RejectPlan}" \
    "" \
    "{Another city!} SelectCity.Yes {UIPickScenarioMode}"
}


proc UIQuit {head} {
  if {[sim Players] == 1} {
    set l "{Keep playing.} Quit.No {RejectPlan}"
    set m ""
    set r "{I quit!} Quit.IQuit {DoReallyQuit %s}"
  } else {
    set l "{Keep playing.} Quit.No {RejectPlan}"
    set m "{I quit!} Quit.IResign {DoIResign %s}"
    set r "{Everyone quit!} Quit.AllQuit {DoReallyQuit %s}"
  }
  AskQuestion [Color $head #ff0000 #ffffff] "Quit Playing Micropolis" \
    "Do you want to quit playing Micropolis?" \
    $l $m $r
}


proc DoIResign {head} {
  global VotesForAsk
  set display [winfo screen $head]
  CrushHead $head
  DecRefDisplay $display
  UISetMessage "The player on X11 Display $display has resigned."
  UpdatePlayers
  if {([sim Players] == 0) ||
      ([llength $VotesForAsk] >= [sim Players])} {
    sim ReallyQuit
  }
}


proc DoReallyQuit {head} {
  echo QuitMicropolis
  sim ReallyQuit
}


proc UISplashMode {} {
  global State
  set State splash
  sim Pause
  WithdrawAll
  InitSplashes
  ShowSplashes
}


proc UIPickScenarioMode {} {
  global State
  global CityLibDir
  set State scenario
  sim Pause
  WithdrawAll
  InitHistory
  UIGenerateCityNow
  InitScenarios
  InitVotesForUseThisMap
  ShowScenarios
}


proc ForcePickScenarioMode {} {
  global State
  if {"$State" != "scenario"} {
    UIPickScenarioMode
  }
}


proc UIGenerateCityNow {} {
  global CityName GameLevel
  sim CityName NowHere
  sim GameLevel 0
  UIGenerateNewCity
}


proc UIGenerateNewCity {} {
  global CityName GameLevel
  if {$GameLevel == -1} {
    set GameLevel 0
  }
  MakeHistory "DoNewCity NowHere $GameLevel [sim Rand] [sim TreeLevel] [sim LakeLevel] [sim CurveLevel] [sim CreateIsland]"
}


proc DoNewCity {name level {r ""} {tl -1} {ll -1} {cl -1} {ci -1}} {
  global Scenario
  set Scenario -1
  sim TreeLevel $tl
  sim LakeLevel $ll
  sim CurveLevel $cl
  sim CreateIsland $ci
  if {"$r" == ""} {
    sim GenerateNewCity
  } else {
    sim GenerateSomeCity $r
  }
  sim CityName $name
  sim GameLevel $level
  UIShowPicture 48
}


proc UIDidGenerateNewCity {} {
  sim Update
}


proc IncRefDisplay {display} {
  global DisplayRegistry
  if ![info exists DisplayRegistry($display)] {
    set DisplayRegistry($display) 0
  }
  incr DisplayRegistry($display)
}


proc DecRefDisplay {display} {
  global DisplayRegistry
  incr DisplayRegistry($display) -1
  if {$DisplayRegistry($display) <= 0} {
    CloseDisplay $display
  }
}


proc CloseDisplay {display} {
}


proc DoStopMicropolis {} {
  KillSoundServers
  destroy .
}


proc AddPlayer {display} {
  set i [string first : $display]
  if {$i == 0} {
  } else {
    if {$i == -1} {
      set display "$display:0"
    }
  }

  echo Adding a player on $display ...

  set head [MakeWindow.head $display]

  if {"$head" != ""} {
    set display [winfo screen $head]
    IncRefDisplay $display
    PrepHead $head
    UISetMessage "Added a player on X11 Display \"$display\"."
    UpdatePlayers
  } else {
    UISetMessage "Couldn't add a player on X11 Display \"$display\"!"
  }
  return $head
}


proc FireBomb {} {
  sim FireBomb
}

proc DropFireBombs {} {
  FireBomb
  after 300 FireBomb
  after 600 FireBomb
  after 900 FireBomb
}


proc UIMakeMonster {} {
  sim MakeMonster [sim Rand 120] [sim Rand 100]
}


proc melt {} {
  sim HeatSteps 1
  sim HeatFlow -7
  sim HeatRule 0
}


proc eco {} {
  sim HeatSteps 1
  sim HeatFlow 19
  sim HeatRule 1
}


proc oops {} {
  sim HeatSteps 0
}


proc TogglePause {} {
  global State Pause

  if {"$State" != "play" || [sim Speed]} {
    sim Speed 0
    set Pause 1
  } else {
    sim Speed 3
    set Pause 0
  }
  MakeRunningSound
}


proc SetSpeedTime {time} {
  sim Speed $time
  MakeRunningSound
}


proc MakeRunningSound {} {
  global State

  if {"$State" == "play" && [sim Speed]} {
    UIMakeSound edit Boing "-speed 1[sim Speed]0"
  } else {
    UIMakeSound edit Boing "-speed 90"
  }
}


proc SayDemands {} {
  global DemandRes DemandCom DemandInd
  set slope 3
  set r [expr "100 + ($DemandRes * $slope)"]
  set c [expr "100 + ($DemandCom * $slope)"]
  set i [expr "100 + ($DemandInd * $slope)"]
  after 020 "UIMakeSound edit O \"-speed $r\""
  after 220 "UIMakeSound edit A \"-speed $c\""
  after 440 "UIMakeSound edit E \"-speed $i\""
}


proc UISaveCity {win} {
  global SaveCityWin
  set SaveCityWin $win
  sim SaveCity
}


proc UISaveCityAs {{win ""}} {
  global SaveCityWin
  if {"$win" == ""} {set win $SaveCityWin}
  set SaveCityWin $win

  global CityDir
  set file [ShowFileOf $win]
  DoFileDialog $file "Choose a File to Save the City" $CityDir "*.cty" "" \
	"UIDoReallySaveCity" ""
}


proc UIDoReallySaveCity {name path} {
  global CityDir
  if {![string match *.cty $name]} {
    set name $name.cty
  }
  set CityDir $path
  sim SaveCityAs $path/$name
}


proc UIDidSaveCity {} {
  DoSendMessage "Saved the city in \"[sim CityFileName]\"." status
}


proc UIDidntSaveCity {msg} {
  DoSendMessage $msg alert
  UIMakeSound warning Sorry "-speed 85"
}


proc UILoadScenario {scen} {
  MakeHistory "DoScenario $scen"
}


proc DoScenario {scen} {
  global Scenario
  set Scenario $scen
  sim LoadScenario $scen
  UIShowPicture $scen
}


proc UIDidLoadScenario {} {
}


proc UIStartScenario {id} {
  global Scenario
  set Scenario $id
  UILoadScenario $id
  UIPlayGame
  UIShowPicture $id
}


proc UIPlayNewCity {} {
  UIGenerateNewCity
  UIPlayGame
}


proc UIStartLoad {} {
  UIPlayGame
}


proc UIReallyStartGame {} {
  #UIPickScenarioMode
  UISplashMode
}


proc UIPlayGame {} {
  global State
  global Priority
  set State play
  sim Resume
  sim Speed 3
  sim AutoGoto 1
  SetPriority $Priority
  InitHeads
  InitAllHeadMenus
  ShowInitial
  sim NeedRest 10
}


proc UISetSpeed {speed} {
  global Time State
  set Time $speed
  if {"$State" == "play"} {
    UISetMessage [lindex {
      {Time pauses.}
      {Time flows slow.}
      {Time flows medium.}
      {Time flows fast.}
    } $speed]
  }
  UIUpdateRunning
}


proc UIUpdateRunning {} {
  global HeadWindows Time State

	if {($State == "play") && $Time} {
    set pict "@images/micropolisg.xpm"
  } else {
    set pict "@images/micropoliss.xpm"
  }

  foreach win $HeadWindows {
    set can [WindowLink $win.demand]
    $can itemconfig micropolis -bitmap $pict
  }
}


proc DoSetGameLevel {level} {
  sim GameLevel $level
}


proc UISetGameLevel {level} {
  global GameLevel
  set GameLevel $level
  global ScenarioWindows
  foreach win $ScenarioWindows {
    UpdateLevelSelection $win
  }
}


proc UISetCityName {name} {
  global EditorWindows
  global CityName
  set CityName $name
  set title "Micropolis Editor on $name"
  foreach win $EditorWindows {
    # TODO: set editor window and icon title
    #wm title $win "$title"
    #wm iconname $win "$title"
  }
}


proc UILoadCity {win} {
  # if changed, r-u-sure?
  global CityDir
  set file [ShowFileOf $win]
  DoFileDialog $file "Choose a City to Load" $CityDir "*.cty" "" \
	"UIDoLoadCity" ""
}


proc UIDoLoadCity {name path} {
  global CityDir
  set CityDir $path
  if {![string match *.cty $name]} {
    set name $name.cty
  }
  MakeHistory "DoLoadCity {$path/$name}"
}


proc DoLoadCity {filename} {
  sim LoadCity $filename
}

proc UIDidLoadCity {} {
  global State GameLevel Scenario
  set Scenario -1
  set GameLevel -1
  if {$State == "play"} {
    UIPlayGame
  } else {
    UIShowPicture 49 [sim CityFileName]
  }
}


proc UIDidntLoadCity {msg} {
  DoSendMessage $msg alert
  UIMakeSound warning Sorry "-speed 85"
  UIShowPicture 49 [sim CityFileName]
  sim Fill 0
  sim UpdateMaps
}


proc UINewGame {} {
  global OldBudget
  set OldBudget 0
  sim InitGame
  sim EraseOverlay
  InitEditors
  InitMaps
  InitGraphs
  update
  sim UpdateMaps
}


proc UIDidPan {w x y} {
  if {[$w ToolMode] == 1} {
    EditorToolDrag $w $x $y
  }
  update idletasks
}


proc UIDidStopPan {win} {
  UIMakeSoundOn $win fancy Skid "-volume 25"
  $win TweakCursor
}


proc UIEarthQuake {} {
}


proc UIAutoGoto {x y {except {}}} {
  global EditorWindows
  set didOne 0
  set x [expr "$x * 16 + 8"]
  set y [expr "$y * 16 + 8"]
  foreach win $EditorWindows {
    if {"$win" != "$except"} {
      set view [WindowLink $win.view]
      if {[$view AutoGoto]} {
        set didOne 1
        $view AutoGoal $x $y
      }
    }
  }
  if {$didOne} {
    sim UpdateMaps
  }
}


proc UIAutoGotoOn {x y eds} {
  set x [expr "$x * 16 + 8"]
  set y [expr "$y * 16 + 8"]
  foreach win $eds {
    [WindowLink $win.view] AutoGoal $x $y
  }
  sim UpdateMaps
}


proc DoLeaveGame {head} {
}


proc UILoseGame {} {
  global Messages
  UIShowPicture 200
  sim Pause
  AskQuestion [Color . #ff0000 #ffffff] [lindex $Messages(200) 1] \
    [lindex $Messages(200) 2] \
    ""\
    ""\
    "{Ok} SelectCity.Yes {UIPickScenarioMode}"
}


proc UIWinGame {} {
  UIShowPicture 100
}


proc DoPendTool {view tool x y} {
  global HeadWindows ToolInfo VotesForAsk

  set win [WindowLink $view.top]
  set head [WindowLink $win.head]

  if {($tool == [sim PendingTool]) &&
      ($x == [sim PendingX]) &&
      ($y == [sim PendingY])} {
    if {[lsearch $VotesForAsk $head] != -1} {
      # you can only vote once
      UIMakeSound edit Oop
    } else {
      UIMakeSound edit Boing
      set ask [WindowLink $head.ask]
      PressVoteButton $ask [WindowLink $ask.vote] Ask
    }
  } else {
    UIAutoGoto $x $y $win

    UIMakeSound edit Boing
    set info [lindex $ToolInfo $tool]
    set a [lindex $info 0]
    set name [lindex $info 1]
    set cost [lindex $info 2]
    set title "Build $a $name"
    set question "Do you support the plan to build $a $name for $cost?"
    AskQuestion [Color $win #00ff00 #ffffff] "$title" \
	"$question" \
	"{Veto plan.} Plan.Veto
	   {RejectPlan}" \
	"{Goto plan.} Plan.Goto
	   {ComeTo %s $x $y}" \
	"{Support plan!} Plan.Support
	   {SupportPlan $view %s $tool $x $y}
	   {PreviewSupportPlan $view %s $tool $x $y}"
    set VotesForAsk $head
    set ask [WindowLink $head.ask]
    [WindowLink $ask.vote] config -relief sunken

    UpdateVotesForAsk

    sim PendingTool $tool
    sim PendingX $x
    sim PendingY $y
    sim Votes [llength $VotesForAsk]
  }
}


proc RejectPlan {} {
  sim PendingTool -1
  if {[sim Players] > 1} {
    UIMakeSound edit Sorry
  }
  WithdrawAsks
}


proc NeededVotes {} {
  global FreeVotes
  set players [sim Players]
  set needed [expr "$players - $FreeVotes"]
  return [max 0 $needed]
}


proc SupportPlan {view h tool x y} {
  global VotesForAsk
  sim Votes [llength $VotesForAsk]
  sim PendingTool -1
  sim OverRide 1
  $view DoTool $tool $x $y
  sim OverRide 0
  WithdrawAsks
  UIMakeSound edit Aaah
}


proc PreviewSupportPlan {view h tool x y} {
  global VotesForAsk
  sim Votes [llength $VotesForAsk]
}


proc SugarStartUp {uri} {
  global SugarURI
  set SugarURI $uri

  # TODO: Load the city file at the given URI, or configure according to URI parameters. 
}


proc SugarNickName {nick} {
  global SugarNickName
  set SugarNickName $nick
}


proc SugarActivate {} {
  global SugarActivated
  set SugarActivated 1
}


proc SugarDeactivate {} {
  global SugarActivated
  set SugarActivated 0
}


proc SugarShare {} {
  global SugarShared
  set SugarShared 1
}


proc SugarBuddyAdd {key nick color address} {
  global SugarBuddies
  set buddy [list $key $nick $color $address]
  lappend SugarBuddies $buddy
}


proc SugarBuddyDel {key nick color address} {
  global SugarBuddies
  set buddy [list $key $nick $color $address]
  set i [lsearch $wins $win]
  if {$i != -1} {
    set SugarBuddies [lreplace $wins $i $i]
  }
}


proc SugarQuit {} {
  sim ReallyQuit
}


########################################################################