File: mplayer.c

package info (click to toggle)
xconq 7.2.2-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 8,296 kB
  • ctags: 9,199
  • sloc: ansic: 107,849; sh: 2,108; perl: 2,057; makefile: 1,177; sed: 161; csh: 50; awk: 49; lisp: 39
file content (3176 lines) | stat: -rw-r--r-- 96,163 bytes parent folder | download | duplicates (2)
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
/* Implementation of the "mplayer" AI in Xconq.
   Copyright (C) 1987-1989, 1991-1998 Stanley T. Shebs.

Xconq 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 2, or (at your option)
any later version.  See the file COPYING.  */

#include "conq.h"
extern int select_by_weight PARAMS ((int *arr, int numvals));
extern int carryable PARAMS ((int u));
extern int accelerable PARAMS ((int u));
extern int accelerator PARAMS ((int u1, int u2));
#include "kpublic.h"
extern void try_to_draw PARAMS ((Side *side, int flag, char *ainame));
extern void give_up PARAMS ((Side *side, char *ainame));

extern int bhw_max;

/* Limit on the number of goals that a side may have. */

#define MAXGOALS 10

/* Limit on the number of theaters a single side may have. */

#define MAXTHEATERS 98

/* what does the game look like? */
typedef enum a_game_class {
    gc_none,
    gc_standard,
    gc_time
} GameClass;

static GameClass game_class = gc_none;

/* Strategy is what a side uses to make decisions. */

typedef struct a_strategy {
    int type;			/* placeholder */
    int trytowin;
    int report_not_understood;
    int creationdate;
    short strengths[MAXSIDES][MAXUTYPES];  /* estimated numbers of units */
    short points[MAXSIDES];	/* estimated point value */
    short alstrengths[MAXSIDES][MAXUTYPES];  /* numbers in alliances */
    short alpoints[MAXSIDES];	/* points in alliances */
    short initial_strengths_computed;
    short strengths0[MAXSIDES][MAXUTYPES];  /* initial estimated numbers of units */
    short points0[MAXSIDES];	/* initial estimated point value */
    short alstrengths0[MAXSIDES][MAXUTYPES];  /* initial numbers in alliances */
    short alpoints0[MAXSIDES];	/* initial points in alliances */
    short contacted[MAXSIDES+1];
    short homefound[MAXSIDES+1];
    int analyzegame;
    struct a_theater *theaters;
    struct a_theater **theatertable;
    short numtheaters;
    char *areatheaters;
    struct a_theater *homefront;
    struct a_theater *perimeters[NUMDIRS];
    struct a_theater *midranges[NUMDIRS];
    struct a_theater *remotes[NUMDIRS];
    int numgoals;
    struct a_goal *goals[MAXGOALS];
    /* Exploration and search slots. */
    int zonewidth, zoneheight;
    int numzonex, numzoney;     /* dimensions of search zone array */
    int numzones;
    struct a_searchzone *searchzones;
    short *explorertypes;
    short explorersneeded;
    short *terrainguess;
    short cx, cy;               /* "centroid" of all our units */
    short *demand;              /* worth of each utype w.r.t. strategy */
    int explore_priority;
    int defend_priority;
    int attack_priority;
    struct a_unit *unitlist[MAXUTYPES];   /* lists to help mplay efficiency */
    short unitlistcount[MAXUTYPES];  /* counts of above lists */
    short *actualmix;
    short *expectedmix;
    short *idealmix;
    short *research_status;  /* specific to the "time" game */
    short *research_on;      /* specific to the "time" game */
    Obj *writable_state;
} Strategy;

/* utype-specific research status codes for the "time" game */
#define RS_RESEARCH_NEEDED 4
#define RS_RESEARCH_ASSIGNED 3
#define RS_UPGRADE_NEEDED 1

#define mplayer(s) ((Strategy *) (s)->ai)

/* A Theater is a sub-area that can be planned for all at once. */

/* To save space in theater layer, no more than 127 theaters may exist at once.
   This should be sufficient, even a Napoleon would have trouble keeping track
   of that much activity. */

typedef struct a_theater {
    short id;
    char *name;			/* an informative name for this theater */
    short x, y;			/* center of the theater */
    short xmin, ymin;		/*  */
    short xmax, ymax;		/*  */
    int size;			/* number of cells in the theater */
    short importance;		/* 0 = shrug, 100 = critical */
    Goal *maingoal;
    short allied_units;		/* How many units on our side here. */
    short makers;		/* Total number of makers */
    short unexplored;		/* number of unseen cells in theater */
    short allied_bases;		/* total number of our bases, includes towns */
    short border;		/* true if this is a border theater. */
    short reinforce;		/* priority on request for units. */
    short numassigned[MAXUTYPES];  /* num of each type assigned to theater */
    short numneeded[MAXUTYPES];  /* units we should move to theater. */
    short numtotransport[MAXUTYPES];  /* types needing transportation. */
    short numenemies[MAXUTYPES];
    short numsuspected[MAXUTYPES];
    short numsuspectedmax[MAXUTYPES];
    int *people;		/* number of populated cells seen */
    int enemystrengthmin;	/* estimate of enemy unit strength */
    int enemystrengthmax;	/* estimate of enemy unit strength */
    short units_lost;		/* How many units have we lost here. */
    struct a_theater *next;
} Theater;

#define for_all_theaters(s,th)  \
  for ((th) = mplayer(s)->theaters; (th) != NULL; (th) = (th)->next)

#define theater_at(s,x,y)  \
  (mplayer(s)->theatertable[mplayer(s)->areatheaters[(x)+area.width*(y)]])

#define set_theater_at(s,x,y,th)  \
  ((mplayer(s)->areatheaters[(x)+area.width*(y)]) = (th)->id)

#define for_all_cells_in_theater(s,x,y,th)  \
  for ((x) = theater->xmin; (x) < theater->xmax; ++(x))  \
    for ((y) = theater->ymin; (y) < theater->ymax; ++(y))  \
      if (theater_at((s), (x), (y)) == (th)

#define unit_theater(unit) ((Theater *) (unit)->aihook)

#define set_unit_theater(unit,theater) ((unit)->aihook = (char *) (theater))

#define can_see_actual_units(side, x, y) (all_see_all || cover((side), (x), (y)) > 0)

/* Local function declarations. */

static void mplayer_init PARAMS ((Side *side));
static void mplayer_init_turn PARAMS ((Side *side));
static void create_strategy PARAMS ((Side *side));
static void reset_strategy PARAMS ((Side *side));
static void analyze_the_game PARAMS ((Side *side));
static void determine_subgoals PARAMS ((Side *side));
static void review_theaters PARAMS ((Side *side));
static void create_initial_theaters PARAMS ((Side *side));
static Theater *create_theater PARAMS ((Side *side));
static void remove_theater PARAMS ((Side *side, Theater *theater));
static void remove_small_theaters PARAMS ((Side *side));
static void compute_theater_bounds PARAMS ((Side *side));
static void review_goals PARAMS ((Side *side));
static void review_units PARAMS ((Side *side));
static void update_side_strategy PARAMS ((Side *side));
static void decide_theater_needs PARAMS ((Side *side, Theater *theater));
static void update_unit_plans PARAMS ((Side *side));
static void update_unit_plans_randomly PARAMS ((Side *side));
static void estimate_strengths PARAMS ((Side *side));
static void decide_resignation PARAMS ((Side *side));
static void add_goal PARAMS ((Side *side, Goal *goal));
static Goal *has_goal PARAMS ((Side *side, GoalType goaltype));
static Goal *has_unsatisfied_goal PARAMS ((Side *side, GoalType goaltype));
static void mplayer_decide_plan PARAMS ((Side *side, Unit *unit));
static int need_this_type_to_explore PARAMS ((Side *side, int u));
/* static int compare_weights PARAMS ((struct weightelt *w1, struct weightelt *w2)); */
static void assign_to_exploration PARAMS ((Side *side, Unit *unit));
static void assign_explorer_to_theater PARAMS ((Side *side, Unit *unit, Theater *theater));
static int need_this_type_to_build_explorers PARAMS ((Side *side, int u));
static void assign_to_explorer_construction PARAMS ((Side *side, Unit *unit));
static void assign_to_offense PARAMS ((Side *side, Unit *unit));
static void assign_to_offense_support PARAMS ((Side *side, Unit *unit));
static int mplayer_adjust_plan PARAMS ((Side *side, Unit *unit));
static int type_can_build_attackers PARAMS ((Side *side, int u));
static int preferred_build_type PARAMS ((Side *side, Unit *unit, int plantype));
static int need_more_transportation PARAMS ((Side *side));
static void assign_to_defense PARAMS ((Side *side, Unit *unit));
static void assign_to_defense_support PARAMS ((Side *side, Unit *unit));
static int assign_to_research_on PARAMS ((Side *side, Unit *unit, int u2));
static int can_research_on PARAMS ((int u, int u2));
static int needs_research PARAMS ((Side *side, int u));
static int mplayer_guide_explorer PARAMS ((Side *side, Unit *unit));
static int probably_explorable PARAMS ((Side *side, int x, int y, int u));
static int build_base_for_self PARAMS ((Side *side, Unit *unit));
static int build_base_for_others PARAMS ((Side *side, Unit *unit));
static int build_depot_for_self PARAMS ((Side *side, Unit *unit));
static void mplayer_react_to_action_result PARAMS ((Side *side, Unit *unit, int rslt));
static void mplayer_react_to_task_result PARAMS ((Side *side, Unit *unit, Task *task, TaskOutcome rslt));
static void change_to_adjacent_theater PARAMS ((Side *side, Unit *unit));
static int desired_direction_impassable PARAMS ((Unit *unit, int x, int y));
static int could_be_ferried PARAMS ((Unit *unit, int x, int y));
static int blocked_by_enemy PARAMS ((Unit *unit, int x, int y, int shortest));
static int attack_blockage PARAMS ((Side *side, Unit *unit, int x, int y, int shortest));
static void mplayer_react_to_new_side PARAMS ((Side *side, Side *side2));
static void mplayer_finish_movement PARAMS ((Side *side));
static Unit *search_for_available_transport PARAMS ((Unit *unit, int purpose));
static void rethink_plan PARAMS ((Unit *unit));
static int enemy_close_by PARAMS ((Side *side, Unit *unit, int dist, int *xp, int *yp));
static void mplayer_receive_message PARAMS ((Side *side, Side *sender, char *str));
static char *mplayer_at_desig PARAMS ((Side *side, int x, int y));
static int mplayer_theater_at PARAMS ((Side *side, int x, int y));
static int mplayer_read_strengths PARAMS ((Side *side));
static Obj *mplayer_save_state PARAMS ((Side *side));

static void mplayer_react_to_unit_loss PARAMS ((Side *side, Unit *unit));

static int compare_weights PARAMS ((const void *w1, const void *w2));

/* This is the set of operations that generic code will use. */

AI_ops mplayer_ops = {
    "mplayer",			/* name */
    NULL,			/* to_test_compat */		
    mplayer_init,		/* to_init */
    mplayer_init_turn,		/* to_init_turn */
    mplayer_decide_plan,	/* to_decide_plan */
    mplayer_react_to_action_result,	/* to_react_to_action_result */
    mplayer_react_to_task_result,	/* to_react_to_task_result */
    mplayer_react_to_new_side,	/* to_react_to_new_side */
    mplayer_adjust_plan,	/* to_adjust_plan */
    mplayer_finish_movement,	/* to_finish_movement */
    mplayer_receive_message,	/* to_receive_message */
    mplayer_save_state,		/* to_save_state */
    mplayer_theater_at,		/* region_at */
    mplayer_at_desig,		/* at_desig */
    -1				/* dummy */
};

/* Flag to detect when shared mplayer init has been done. */

static int mplayerinited = FALSE;

static Theater *tmptheater;

static Side *anewside;

/* Determine game type from name of included modules. */

static GameClass
find_game_class()
{
    Module *m;

    for_all_modules(m) {
	if (strcmp(m->name, "time") == 0
	    || (m->origmodulename && strcmp(m->origmodulename, "time") == 0))
	  return gc_time;
    }

    return gc_standard;
}

static void
mplayer_init(side)
Side *side;
{
    Unit *unit;

    if (game_class == gc_none) {
	game_class = find_game_class();
    }

    /* (should do this only when absolutely needed - mplayer might
       never actually be used) */
    if (!mplayerinited) {
	mplayerinited = TRUE;
	Dprintf("One mplayer AI is %d bytes.\n", sizeof(Strategy));
    }
    /* Make sure a strategy object exists. */
    if (mplayer(side) == NULL)
      create_strategy(side);
    /* If the side has no units at the moment, it doesn't really need to
       plan. */
    if (!side_has_units(side))
      return;
    /* Compute an initial estimation of units on each side. */
    /* (Needed for save/restore consistency, otherwise not
       critical to do here.) */
    estimate_strengths(side);
    /* Study the scorekeepers and such, decide how to play the game. */
    analyze_the_game(side);
    /* Reset plans of any units that were not doing anything. */
    for_all_side_units(side, unit) {
    	if (in_play(unit) && unit->plan && unit->plan->aicontrol) {
	    net_force_replan(side, unit, TRUE);
    	}
    }
}

/* At the beginning of each turn, make plans and review the situation. */

static void
mplayer_init_turn(side)
Side *side;
{
    int u, u2;

    /* Cases where we no longer need to run. */
    if (!side->ingame)
      return;
    /* A side without units hasn't got anything to do but wait. */
    /* (should account for possible units on controlled sides) */
    if (!side_has_units(side))
      return;
    /* Mplayers in a hacked game will not play,
       unless they're being debugged. */
    if (compromised && !DebugM)
      return;
    update_all_progress_displays("ai turn init start", side->id);
    DMprintf("%s mplayer init turn\n", side_desig(side));
    /* Make sure a strategy object exists. */
    if (mplayer(side) == NULL)
      create_strategy(side);
    /* Look over the game design we're playing with. */
    analyze_the_game(side);

    if (mplayer(side)->report_not_understood) {
	notify_all("%s AI doesn't understand scoring in this game!", short_side_title(side));
	mplayer(side)->report_not_understood = FALSE;
    }

    /* code specific to the "time" game */
    if (game_class == gc_time) {
	for_all_unit_types(u) {
	    if (mplayer(side)->research_status[u] == RS_RESEARCH_ASSIGNED) {
		u2 = mplayer(side)->research_on[u];
		if (!needs_research (side, u2)) {
		    /* research done, start upgrading */
		    DMprintf("%s has completed research on %s\n",
			     side_desig(side), u_type_name(u2));
		    mplayer(side)->research_status[u] = RS_UPGRADE_NEEDED;
		}
	    }
	}
    }

    /* If this game is one that can be won, as opposed to
       just dinking around, figure how to win it. */
    if (mplayer(side)->trytowin) {
	/* Check out the current goal tree first. */
	review_goals(side);
	/* Goal analysis might have triggered resignation. */
	if (!side->ingame)
	  goto done;
	/* Check out all the theaters. */
	review_theaters(side);
	/* Check out all of our units. */
	review_units(side);
	/* (should be integrated better) */
	mplayer_finish_movement(side);
	/* Decide on the new current plan. */
	update_side_strategy(side);
	/* Propagate this to individual unit plans. */
	update_unit_plans(side);
    } else {
	update_unit_plans_randomly(side);
    }
  done:
    update_all_progress_displays("", side->id);
    DMprintf("%s mplayer init turn done\n", side_desig(side));
}

/* Create and install an entirely new strategy object for the side. */

static void
create_strategy(side)
Side *side;
{
    Strategy *strategy = (Strategy *) xmalloc(sizeof(Strategy));

    /* Put the specific structure into a generic slot. */
    side->ai = (struct a_ai *) strategy;
    strategy->type = mplayertype;
    /* Allocate a table of pointers to theaters, for access via small numbers
       rather than full pointers. */
    strategy->theatertable = (Theater **) xmalloc(127 * sizeof(Theater *));
    /* Allocate a layer of indexes into the theater table. */
    strategy->areatheaters = malloc_area_layer(char);
    /* Allocate random things. */
    /* Arrays for unit types. */
    strategy->actualmix = (short *) xmalloc(numutypes * sizeof(short));
    strategy->expectedmix = (short *) xmalloc(numutypes * sizeof(short));
    strategy->idealmix = (short *) xmalloc(numutypes * sizeof(short));
    strategy->research_status = (short *) xmalloc(numutypes * sizeof(short));
    strategy->research_on     = (short *) xmalloc(numutypes * sizeof(short));
    /* Arrays for terrain types. */
    strategy->terrainguess = (short *) xmalloc(numttypes * sizeof(short));
    strategy->writable_state = lispnil;
    /* Set everything to correct initial values. */
    reset_strategy(side);
}

/* Put all the right initial values into the strategy, but don't allocate anything. */

static void
reset_strategy(side)
Side *side;
{
    int u, u2, t, dir;
    Strategy *strategy = (Strategy *) side->ai;

    /* Remember when we did this. */
    strategy->creationdate = g_turn();
    /* Null out various stuff. */
    strategy->numgoals = 0;
    strategy->theaters = NULL;
    /* Actually we start with no theaters, but it's convenient to leave entry 0
       in the theater table pointing to NULL. */
    strategy->numtheaters = 1;
    /* Clear pointers to special-purpose theaters. */
    strategy->homefront = NULL;
    for_all_directions(dir) {
    	strategy->perimeters[dir] = NULL;
    	strategy->midranges[dir] = NULL;
    	strategy->remotes[dir] = NULL;
    }
    strategy->explorersneeded = 0;
    /* Reset the summation of our exploration needs. */
    for_all_unit_types(u) {
	strategy->actualmix[u] = 0;
	strategy->expectedmix[u] = 0;
	strategy->idealmix[u] = 0;
	strategy->research_status[u] = 0;
	strategy->research_on[u] = 0;

	/* code specific to the "time" game */
	if (game_class == gc_time) {
	    for_all_unit_types(u2) {
		if (needs_research (side, u2) && can_research_on(u, u2)) {
		    strategy->research_status[u] = RS_RESEARCH_NEEDED;
		    strategy->research_on[u] = u2;
		    DMprintf("%s can research on %s (to level %d)\n",
			     u_type_name(u), u_type_name(u2),
			     u_tech_to_build(u2));
		}
	    }
	}
    }
    for_all_terrain_types(t) {
	strategy->terrainguess[t] = 0;
    }
    strategy->analyzegame = TRUE;
    /* Analyze the game and decide our basic goals. */
    analyze_the_game(side);
}

/* Look over the game design and decide what we're supposed to be doing,
   if anything at all.  This just sets up toplevel goals based on the
   game design, does not evaluate goals or any such. */

static void
analyze_the_game(side)
Side *side;
{
    int maybedraw, i;
    Goal *goal;

    if (mplayer(side)->analyzegame) {
	if (should_try_to_win(side)) {
	    mplayer(side)->trytowin = TRUE;
	    /* This is our whole purpose in the game. */
	    goal = create_goal(GOAL_WON_GAME, side, TRUE);
	    add_goal(side, goal);
	    /* Now figure what exactly we have to do in order to win. */
	    determine_subgoals(side);
	    /* Machine will want to keep playing as long as it thinks
	       it has a chance to win. */
	    maybedraw = FALSE;
	} else {
	    mplayer(side)->trytowin = FALSE;
	    /* Since the side is not trying to win anything, it will be
	       pretty laidback about whether to keep the game going. */
	    maybedraw = TRUE;
	}
	/* Be trusting about game saves, at least for now. (The problem
	   is that a human player could escape fate by saving the game
	   and then either editing the saved game or just throwing it
	   away.) */
	if (TRUE != side->willingtosave /* (should) and decision delegated to AI */)
	  net_set_willing_to_save(side, TRUE);
	if (maybedraw != side->willingtodraw /* (should) and decision delegated to AI */)
	  try_to_draw(side, maybedraw, "mplayer");
	mplayer(side)->analyzegame = FALSE;
	/* Summarize our analysis of this game. */
	DMprintf("%s will try to %s this game\n",
		 side_desig(side),
		 mplayer(side)->trytowin ? "win" : "have fun in");
	for (i = 0; i < mplayer(side)->numgoals; ++i) {
	    goal = mplayer(side)->goals[i];
	    DMprintf("%s has %s\n", side_desig(side), goal_desig(goal));
	}
    }
}

static void
determine_subgoals(side)
Side *side;
{
    int numvicgoals, understood;
    Unit *unit;
    Side *side2;
    Scorekeeper *sk;
    Goal *goal;

    understood = TRUE;
    /* Look at each scorekeeper and decide on appropriate goals. */
    for_all_scorekeepers(sk) {
	/* (should test who scorekeeper applies to) */
	if (match_keyword(sk->body, K_LAST_SIDE_WINS)
	    || match_keyword(sk->body, K_LAST_ALLIANCE_WINS)) {
	    /* We want to "kick butt" - *everybody* else's butt. */
	    for_all_sides(side2) {
		if (!trusted_side(side, side2) && side2->ingame) {
		    /* Our goals include preventing other sides from accomplishing
		       theirs. */
		    goal = create_goal(GOAL_WON_GAME, side2, FALSE);
		    add_goal(side, goal);
		    /* (should add "search-and-destroy" as corollaries) */
		}
	    }
	    /* Add goals to protect our own units. */
	    numvicgoals = 0;
	    for_all_side_units(side, unit) {
		if (point_value(unit) > 0  /* (should be "n most valuable") */
		    && in_play(unit)
		    && numvicgoals < 10) {
		    goal = create_goal(GOAL_VICINITY_HELD, side, TRUE);
		    goal->args[0] = unit->x;  goal->args[1] = unit->y;
		    goal->args[2] = goal->args[3] = 2;
		    add_goal(side, goal);
		    ++numvicgoals;
		}
	    }
	} else if (sk->initial != -10001) {
	    /* This is a numerical scorekeeper whose value we want to maximize. */
	    if (consp(sk->body) && match_keyword(car(sk->body), K_SET)) {
		if (consp(cadr(sk->body)) && match_keyword(car(cadr(sk->body)), K_SUM)) {
		    understood = FALSE;
		} else {
		    understood = FALSE;
		}
	    } else {
		understood = FALSE;
	    }
	} else {
	    understood = FALSE;
	}
    }
    
    if (!understood) {
	/* Can't notify anybody yet, no windows up, so record */
	mplayer(side)->report_not_understood = TRUE;
	DMprintf("%s AI doesn't understand scoring in this game!", short_side_title(side));
    }
    /* We might develop a sudden interest in exploration. */
    /* (but should only be if information is really important to winning) */
    if (!all_see_all) {
	if (!g_terrain_seen()) {
	    add_goal(side, create_goal(GOAL_WORLD_KNOWN, side, TRUE));
	}
	/* It will be important to keep track of other sides' units
	   as much as possible. */
	for_all_sides(side2) {
	    if (side != side2) {
		goal = create_goal(GOAL_POSITIONS_KNOWN, side, TRUE);
		goal->args[0] = (long) side2;
		add_goal(side, goal);
	    }
	}
	/* Also add the general goal of knowing where indeps are. */
	goal = create_goal(GOAL_POSITIONS_KNOWN, side, TRUE);
	goal->args[0] = (long) NULL;
	add_goal(side, goal);
    }
}

/* Do a combination of analyzing existing theaters and creating new ones. */

static void
review_theaters(side)
Side *side;
{
    int x, y, u, s, pop, totnumunits;
    int firstcontact = FALSE;
    int homefound = FALSE;
    short view;
    Unit *unit;
    Side *firstcontactside, *homefoundside, *otherside, *side2;
    Theater *theater;

    /* Create some theaters if none exist. */
    if (mplayer(side)->theaters == NULL) {
	create_initial_theaters(side);
    }
    for_all_theaters(side, theater) {
	theater->allied_units = 0;
	theater->makers = 0;
	theater->unexplored = 0;
	theater->border = FALSE;
	theater->allied_bases = 0;
	for_all_unit_types(u) {
	    theater->numassigned[u] = 0;
	    theater->numneeded[u] = 0;
	    theater->numenemies[u] = 0;
	    theater->numsuspected[u] = theater->numsuspectedmax[u] = 0;
	    theater->numtotransport[u] = 0;
	}
	if (people_sides_defined()) {
	    for (s = 0; s <= numsides; ++s)
	      theater->people[s] = 0;
	}
	theater->units_lost /= 2;
    }
    compute_theater_bounds(side);
    /* Now look at all the units that we can. */
    for_all_side_units(side, unit) {
    	if (in_play(unit)) {
	    theater = unit_theater(unit);
	    if (theater != NULL) {
		++(theater->allied_units);
		++(theater->numassigned[unit->type]);
		if (isbase(unit))
		  ++(theater->allied_bases);
		if (unit->plan
		    && unit->plan->waitingfortransport)
		  ++(theater->numtotransport[unit->type]);
	    }
	}
    }
    /* (should also analyze allies etc) */
    /* Now look at the whole world. */
    for_all_interior_cells(x, y) {
	theater = theater_at(side, x, y);
	if (theater != NULL) {
	    if (can_see_actual_units(side, x, y)) {
	    	for_all_stack(x, y, unit) {
	    	    /* what about occupants? */
	    	    if (in_play(unit)
	    	    	&& !trusted_side(side, unit->side)
	    	    	&& (!indep(unit)
	    	    	    || u_point_value(unit->type) > 0)) {
			if (enemy_side(side, unit->side))
			  ++(theater->numenemies[unit->type]);
	    	    	if (mplayer(side)->contacted[side_number(unit->side)] == 0) {
			    mplayer(side)->contacted[side_number(unit->side)] = 1;
			    if (!indep(unit)) {
				firstcontact = TRUE;
				firstcontactside = unit->side;
			    }
	    	    	}
	    	    	if (mplayer(side)->homefound[side_number(unit->side)] == 0
	    	    	    && !mobile(unit->type)) {
			    mplayer(side)->homefound[side_number(unit->side)] = 1;
			    if (!indep(unit)) {
				homefound = TRUE;
				homefoundside = unit->side;
			    }
	    	    	}
	    	    }
	    	}
		if (people_sides_defined()) {
		    pop = people_side_at(x, y);
		    if (pop != NOBODY) {
			++(theater->people[pop]);
	    	    	if (mplayer(side)->homefound[pop] == 0) {
			    mplayer(side)->homefound[pop] = 1;
			    if (pop != 0) {
				homefound = TRUE;
				homefoundside = side_n(pop);
			    }
	    	    	}
		    }
		}
	    } else {
		if (terrain_view(side, x, y) == UNSEEN) {
		    ++(theater->unexplored);
		} else {
		    view = unit_view(side, x, y);
		    if (view != EMPTY) {
			side2 = side_n(vside(view));
			if (side2 == NULL) {
			    u = vtype(view);
			    /* (should rate by value of capture) */
			    if (u_point_value(u) > 0) {
				++(theater->numsuspected[u]);
				++(theater->numsuspectedmax[u]);
			    }
			} else if (enemy_side(side, side2)) {
			    u = vtype(view);
			    if (u_point_value(u) > 0) {
				++(theater->numsuspected[u]);
				++(theater->numsuspectedmax[u]);
			    }
			}
		    }
		    if (people_sides_defined()) {
			pop = people_side_at(x, y);
			if (pop != NOBODY) {
			    ++(theater->people[pop]);
			}
		    }
		}
	    }
	}
    }
    for_all_theaters(side, theater) {
    	theater->x = (theater->xmin + theater->xmax) / 2;
    	theater->y = (theater->ymin + theater->ymax) / 2;
    	theater->enemystrengthmin = theater->enemystrengthmax = 0;
    	for_all_unit_types(u) {
	    theater->enemystrengthmin +=
	      theater->numenemies[u] + theater->numsuspected[u];
	}
	theater->enemystrengthmax = theater->enemystrengthmin;
    }
    if (firstcontact || homefound) {
    	for_all_side_units(side, unit) {
	    if (unit->plan && unit->plan->aicontrol) {
		net_force_replan(side, unit, FALSE);
		set_unit_theater(unit, NULL);
		update_unit_display(side, unit, TRUE);
	    }
	}
    }
    for_all_theaters(side, theater) {
	DMprintf("%s theater \"%s\" at %d,%d from %d,%d to %d,%d (size %d)\n",
		 side_desig(side), theater->name, theater->x, theater->y,
		 theater->xmin, theater->ymin, theater->xmax, theater->ymax,
		 theater->size);
	/* Summarize what we know about the theater. */
	DMprintf("%s theater \"%s\"", side_desig(side), theater->name);
	if (!all_see_all && theater->unexplored > 0) {
	    DMprintf(" unexplored %d", theater->unexplored);
	}
	DMprintf(" enemy %d", theater->enemystrengthmin);
	if (theater->enemystrengthmin != theater->enemystrengthmax) {
	    DMprintf("-%d", theater->enemystrengthmax);
	}
	for_all_unit_types(u) {
	    if (theater->numenemies[u] + theater->numsuspected[u] > 0) {
	    	DMprintf(" %3s %d", u_type_name(u), theater->numenemies[u]);
	    	if (theater->numsuspected[u] > 0) {
		    DMprintf("+%d", theater->numsuspected[u]);
		}
	    }
	}
	if (people_sides_defined()) {
	    DMprintf(" people");
	    for (s = 0; s <= numsides; ++s) {
		if (theater->people[s] > 0) {
		    DMprintf(" s%d %d", s, theater->people[s]);
		}
	    }
	}
	DMprintf("\n");
	totnumunits = 0;
	for_all_unit_types(u) {
	    totnumunits +=
	      (theater->numassigned[u] + theater->numneeded[u] + theater->numtotransport[u]);
	}
	if (totnumunits > 0) {
	    /* Summarize the status of our own units in this theater. */
	    DMprintf("%s theater \"%s\" has ", side_desig(side), theater->name);
	    for_all_unit_types(u) {
		if (theater->numassigned[u] + theater->numneeded[u] + theater->numtotransport[u] > 0) {
		    DMprintf(" %d %3s", theater->numassigned[u], u_type_name(u));
			if (theater->numneeded[u] > 0) {
			    DMprintf(" (of %d needed)", theater->numneeded[u]);
			}
			if (theater->numtotransport[u] > 0) {
			    DMprintf(" (%d awaiting transport)", theater->numtotransport[u]);
			}
		}
	    }
	    DMprintf("\n");
	}
    }
    /* Also summarize contacts. */
    for_all_sides(otherside) {
    	if (otherside != side) {
	    if (mplayer(side)->contacted[otherside->id]) {
		DMprintf("%s contacted s%d", side_desig(side), otherside->id);
		if (mplayer(side)->homefound[otherside->id]) {
		    DMprintf(", home found");
		}
		DMprintf("\n");
	    }
    	}
    }
}

/* Set up the initial set of theaters. */

static void
create_initial_theaters(side)
Side *side;
{
    int x, y, dir, dist, i, j;
    int xmin, ymin, xmax, ymax;
    int homeradius, perimradius, midradius, xxx;
    int numthx, numthy, thwid, thhgt;
    Unit *unit;
    Theater *homefront, *enemyarea, *theater;
    Theater *gridtheaters[8][8];
    Strategy *strategy = mplayer(side);
    
    for (i = 0; i < 8; ++i) {
	for (j = 0; j < 8; ++j) {
	    gridtheaters[i][j] = NULL;
	}
    }
    /* Compute bbox of initial (should also do enemy?) units. */
    xmin = area.width;  ymin = area.height;  xmax = ymax = 0;
    for_all_side_units(side, unit) {
	if (alive(unit) /* and other preconditions? */) {
	    if (unit->x < xmin)
	      xmin = unit->x;
	    if (unit->y < ymin)
	      ymin = unit->y;
	    if (unit->x > xmax)
	      xmax = unit->x;
	    if (unit->y > ymax)
	      ymax = unit->y;
	}
    }
    /* Most games start with each side's units grouped closely together.
       If this is not the case, do something else. */
    if (xmax - xmin > area.width / 4 && ymax - ymin > area.height / 4) {
	/* (should do some sort of clustering of units) */
	if (0 /*people_sides_defined()*/) {
	    homefront = create_theater(side);
	    homefront->name = "Home Front";
	    enemyarea = create_theater(side);
	    enemyarea->name = "Enemy Area";
	    for_all_interior_cells(x, y) {
	        if (people_side_at(x, y) == side->id) {
		    set_theater_at(side, x, y, homefront);
	        } else {
		    set_theater_at(side, x, y, enemyarea);
	        }
	    }
	} else {
	    /* Divide the world up along a grid. */
	    numthx = (area.width  > 60 ? (area.width  > 120 ? 7 : 5) : 3);
	    numthy = (area.height > 60 ? (area.height > 120 ? 7 : 5) : 3);
	    thwid = max(8, area.width / numthx);
	    thhgt = max(8, area.height / numthy);
	    for_all_interior_cells(x, y) {
		i = x / thwid;  j = y / thhgt;
		if (gridtheaters[i][j] == NULL) {
		    theater = create_theater(side);
		    sprintf(spbuf, "Grid %d,%d", i, j);
		    theater->name = copy_string(spbuf);
		    theater->x = x;  theater->y = y;
		    gridtheaters[i][j] = theater;
		} else {
		    theater = gridtheaters[i][j];
		}
		set_theater_at(side, x, y, theater);
	    }
	}
	return;
    } else {
	/* Always create a first theater that covers the starting area. */
	homefront = create_theater(side);
	homefront->name = "Home Front";
	/* Calculate startxy if not already available. */
	if (side->startx < 0 && side->starty < 0)
	  calc_start_xy(side);
	homefront->x = side->startx;  homefront->y = side->starty;
	strategy->homefront = homefront;
	homeradius = max(5, g_radius_min());
	perimradius = max(homeradius + 5, g_separation_min() - homeradius);
	midradius = max(perimradius + 10, g_separation_min() * 2);
	xxx = max((side->startx - perimradius), (area.width - side->startx - perimradius));
	xxx /= 2;
	midradius = min(midradius, perimradius + xxx);
	for_all_interior_cells(x, y) {
	    dist = distance(x, y, side->startx, side->starty);
	    if (people_sides_defined()
		&& people_side_at(x, y) == side->id
		&& dist < (perimradius - 3)) {
		set_theater_at(side, x, y, homefront);
	    } else {
		if (dist < homeradius) {
		    set_theater_at(side, x, y, homefront);
		} else {
		    dir = approx_dir(x - side->startx, y - side->starty);
		    if (dist < perimradius) {
			if (strategy->perimeters[dir] == NULL) {
			    theater = create_theater(side);
			    sprintf(spbuf, "Perimeter %s", dirnames[dir]);
			    theater->name = copy_string(spbuf);
			    theater->x = x;  theater->y = y;
			    strategy->perimeters[dir] = theater;
			} else {
			    theater = strategy->perimeters[dir];
			}
		    } else if (dist < midradius) {
			if (strategy->midranges[dir] == NULL) {
			    theater = create_theater(side);
			    sprintf(spbuf, "Midrange %s", dirnames[dir]);
			    theater->name = copy_string(spbuf);
			    theater->x = x;  theater->y = y;
			    strategy->midranges[dir] = theater;
			} else {
			    theater = strategy->midranges[dir];
			}
		    } else {
			if (strategy->remotes[dir] == NULL) {
			    theater = create_theater(side);
			    sprintf(spbuf, "Remote %s", dirnames[dir]);
			    theater->name = copy_string(spbuf);
			    theater->x = x;  theater->y = y;
			    strategy->remotes[dir] = theater;
			} else {
			    theater = strategy->remotes[dir];
			}
		    }
		    set_theater_at(side, x, y, theater);
	    	}
	    }
	}  
    }
    remove_small_theaters(side);
    /* Assign all units to the theater they're currently in. */
    /* (how do reinforcements get handled? mplayer should get hold of perhaps) */
    for_all_side_units(side, unit) {
	if (in_play(unit) /* and other preconditions? */) {
	    set_unit_theater(unit, theater_at(side, unit->x, unit->y));
	}
    }
}

/* Create a single theater object and link it into the list of
   theaters. */

/* (should be able to re-use theaters in already in theater table) */

static Theater *
create_theater(side)
Side *side;
{
    Theater *theater = (Theater *) xmalloc(sizeof(Theater));
    
    if (mplayer(side)->numtheaters > MAXTHEATERS)
      return NULL;
    theater->id = (mplayer(side)->numtheaters)++;
    theater->name = "?";
    theater->maingoal = NULL;
    theater->people = (int *) xmalloc ((numsides + 1) * sizeof(int));
    /* (should alloc other array slots too) */
    /* Connect theater into a linked list. */
    theater->next = mplayer(side)->theaters;
    mplayer(side)->theaters = theater;
    /* Install it into the theater table also. */
    mplayer(side)->theatertable[theater->id] = theater;
    return theater;
}

/* Clear all references to the theater and remove it from the list.
   Note that the theater size must already be zero. */

static void
remove_theater(side, theater)
Side *side;
Theater *theater;
{
    int dir;
    Theater *prev;

    if (mplayer(side)->homefront == theater)
      mplayer(side)->homefront = NULL;
    for_all_directions(dir) {
	if (mplayer(side)->perimeters[dir] == theater)
	  mplayer(side)->perimeters[dir] = NULL;
	if (mplayer(side)->midranges[dir] == theater)
	  mplayer(side)->midranges[dir] = NULL;
	if (mplayer(side)->remotes[dir] == theater)
	  mplayer(side)->remotes[dir] = NULL;
    }
    if (mplayer(side)->theaters == theater)
      mplayer(side)->theaters = theater->next;
    else {
	prev = NULL;
	for_all_theaters(side, prev) {
	    if (prev->next == theater) {
		prev->next = theater->next;
		break;
	    }
	}
	/* If prev still null, badness */
    }
    --(mplayer(side)->numtheaters);
}

static void
move_theater_cell(x, y)
int x, y;
{
    int dir, x1, y1;
    Theater *theater2;

    if (theater_at(tmpside, x, y) == tmptheater) {
	for_all_directions(dir) {
	    if (interior_point_in_dir(x, y, dir, &x1, &y1)) {
		theater2 = theater_at(tmpside, x1, y1);
		if (theater2 != NULL && theater2 != tmptheater) {
		    set_theater_at(tmpside, x, y, theater2);
		    ++(theater2->size);
		    /* (should recompute bbox too) */
		    --(tmptheater->size);
		}
	    }
	}
    }
}

static void
remove_small_theaters(side)
Side *side;
{
    int domore;
    Theater *theater;

    compute_theater_bounds(side);
    domore = TRUE;
    while (domore) {
	domore = FALSE;
	for_all_theaters(side, theater) {
	    if (between(1, theater->size, 5)) {
		tmpside = side;
		tmptheater = theater;
		apply_to_area(theater->x, theater->y, 6, move_theater_cell);
		if (theater->size == 0) {
		    remove_theater(side, theater);
		    /* Have to start over now. */
		    domore = TRUE;
		    break;
		}
	    }
	}
    }
    /* Redo, many random changes to bounds. */
    compute_theater_bounds(side);
}

/* Compute the size and bounding box of each theater.  This should be run
   each time theaters change in size or shape. */

static void
compute_theater_bounds(side)
Side *side;
{
    int x, y;
    Theater *theater;

    for_all_theaters(side, theater) {
	theater->size = 0;
	theater->xmin = theater->ymin = -1;
	theater->xmax = theater->ymax = -1;
    }
    for_all_interior_cells(x, y) {
	theater = theater_at(side, x, y);
	if (theater != NULL) {
	    ++(theater->size);
	    /* Compute bounding box of theater if not already done. */
	    if (theater->xmin < 0 || x < theater->xmin)
	      theater->xmin = x;
	    if (theater->ymin < 0 || y < theater->ymin)
	      theater->ymin = y;
	    if (theater->xmax < 0 || x > theater->xmax)
	      theater->xmax = x;
	    if (theater->ymax < 0 || y > theater->ymax)
	      theater->ymax = y;
	}
    }
}

/* Examine the goals to see what has been accomplished and what still needs
   to be done. */

static void
review_goals(side)
Side *side;
{
    int i;
    Scorekeeper *sk;
    Goal *goal;
    Side *side2;
    Strategy *strategy = mplayer(side);

    /* First check on our friends and enemies. */
    for_all_sides(side2) {
	/* If they're not trusting us, we don't want to trust them. */
	/* (should be able to update this immediately after other side changes trust) */
	if (!trusted_side(side2, side) && trusted_side(side, side2))
	  net_set_trust(side, side2, FALSE);
    }
    for (i = 0; i < strategy->numgoals; ++i) {
	goal = strategy->goals[i];
	DMprintf("%s has %s\n", side_desig(side), goal_desig(goal));
    }
    /* Should look at certainty of each goal and decide whether to keep or
       drop it, and mention in debug output also. */
    /* Also think about resigning. */
    if (keeping_score()) {
	for_all_scorekeepers(sk) {
	    if (symbolp(sk->body)
		&& (match_keyword(sk->body, K_LAST_SIDE_WINS)
		    || match_keyword(sk->body, K_LAST_ALLIANCE_WINS))) {
		decide_resignation(side);
	    }
	}
    }
}

static void
estimate_strengths(side)
Side *side;
{
    int u, sn1, x, y, uview;
    Side *side1, *side2;
    Strategy *strategy = mplayer(side);
    Unit *unit;
 
    for_all_sides(side1) {
	sn1 = side_number(side1);
	for_all_unit_types(u) {
	    strategy->strengths[sn1][u] = 0;
	}
	/* this lets us count even semi-trusted allies' units accurately... */
	if (side1 == side || allied_side(side, side1)) {
	    for_all_side_units(side1, unit) {
		/* Note that we count off-area units, since they are reinforcements
		   usually. */
		if (alive(unit) && completed(unit)) {
		    ++(strategy->strengths[sn1][unit->type]);
		}
	    }
	}
    }
    if (all_see_all
	|| (!strategy->initial_strengths_computed 
	    && !mplayer_read_strengths(side))) {
	/* If we can see everything, we can add up units accurately.  We also allow
	   initial strengths to be known accurately; this prevents the AI from
	   resigning just because an important unit appears for the first time,
	   even though all players know that it was one of the starting units. */ 
	for_all_cells(x, y) {
	    for_all_stack(x, y, unit) {
		side2 = unit->side;
		if (side2 != NULL && !(side2 == side || allied_side(side, side2))) {
		    if (completed(unit)) {
		        ++(strategy->strengths[side2->id][unit->type]);
		    }
		}
	    }
	}
    } else {
	/* Look at the current view to get enemy strength. */
	/* This is too easily faked, and doesn't know about hiding units... */
	/* Should also discount old data. */
	for_all_cells(x, y) {
	    uview = unit_view(side, x, y);
	    if (uview != UNSEEN && uview != EMPTY) {
		side2 = side_n(vside(uview));
		/* Count only units on other sides. */
		if (side2 != NULL && !(side2 == side || allied_side(side, side2))) {
		    ++(strategy->strengths[side2->id][vtype(uview)]);
		}
	    }
	}
    }
    /* Estimate point values. */
    /* (should try to account for individual units with special point values) */
    for_all_sides(side1) {
	sn1 = side1->id;
	strategy->points[sn1] = 0;
	for_all_unit_types(u) {
	    strategy->points[sn1] +=
	      strategy->strengths[sn1][u] * u_point_value(u);
	}
    }
    /* Estimate how many of each type in allied group. */
    for_all_sides(side1) {
	sn1 = side1->id;
	for_all_unit_types(u) {
	    strategy->alstrengths[sn1][u] = strategy->strengths[sn1][u];
	    for_all_sides(side2) {
		if (side1 != side2 && allied_side(side1, side2)) {
		    strategy->alstrengths[sn1][u] +=
		      strategy->strengths[side2->id][u];
		}
	    }
	}
	strategy->alpoints[sn1] = strategy->points[sn1];
	for_all_sides(side2) {
	    if (side1 != side2 && allied_side(side1, side2)) {
		strategy->alpoints[sn1] += strategy->points[side2->id];
	    }
	}
    }
    /* The first time we estimate strength, record it specially.  Later we will
       use this to compute which sides are getting stronger/weaker as time
       goes on. */
    if (!strategy->initial_strengths_computed) {
	if (!mplayer_read_strengths(side)) {
	    for_all_sides(side1) {
		sn1 = side1->id;
		strategy->points0[sn1] = strategy->points[sn1];
		strategy->alpoints0[sn1] = strategy->alpoints[sn1];
		for_all_unit_types(u) {
		    strategy->strengths0[sn1][u] =
		      strategy->strengths[sn1][u];
		    strategy->alstrengths0[sn1][u] =
		      strategy->alstrengths[sn1][u];
		}
	    }
	}
	ai_save_state(side);
	strategy->initial_strengths_computed = TRUE;
    }
    /* If we're calling strength estimation because a new side has
       come into existence, use the current strengths as the new
       side's initial strengths. */
    if (anewside != NULL) {
	sn1 = anewside->id;
	strategy->points0[sn1] = strategy->points[sn1];
	strategy->alpoints0[sn1] = strategy->alpoints[sn1];
	for_all_unit_types(u) {
	    strategy->strengths0[sn1][u] =
	      strategy->strengths[sn1][u];
	    strategy->alstrengths0[sn1][u] =
	      strategy->alstrengths[sn1][u];
	}
	/* Have to redo the saveable state also; force this by blasting any
	   existing recordable state (it should all be re-creatable from
	   mplayer's internal state). */
	strategy->writable_state = lispnil;
	ai_save_state(side);
    }
    /* Dump out a detailed listing of our estimates. */
    if (DebugM) {
	for_all_sides(side1) {
	    sn1 = side1->id;
	    DMprintf("%s ", side_desig(side));
	    DMprintf("est init streng of %s: ", side_desig(side1));
	    for_all_unit_types(u) {
		DMprintf(" %d", strategy->strengths0[sn1][u]);
	    }
	    DMprintf(" (%d points)\n", strategy->points0[sn1]);
	    DMprintf("%s ", side_desig(side));
	    DMprintf("est curr streng of %s: ", side_desig(side1));
	    for_all_unit_types(u) {
		DMprintf(" %d", strategy->strengths[sn1][u]);
	    }
	    DMprintf(" (%d points)\n", strategy->points[sn1]);
	    DMprintf("%s ", side_desig(side));
	    DMprintf("est init allied of %s: ", side_desig(side1));
	    for_all_unit_types(u) {
		DMprintf(" %d", strategy->alstrengths0[sn1][u]);
	    }
	    DMprintf(" (%d points)\n", strategy->alpoints0[sn1]);
	    DMprintf("%s ", side_desig(side));
	    DMprintf("est curr allied of %s: ", side_desig(side1));
	    for_all_unit_types(u) {
		DMprintf(" %d", strategy->alstrengths[sn1][u]);
	    }
	    DMprintf(" (%d points)\n", strategy->alpoints[sn1]);
	}
    }
}

/* Sometimes there is no point in going on, but be careful not to be too
   pessimistic.  Right now we only give up if no hope at all.  Currently
   this is only used if there is a last-side-wins scorekeeper; it would
   need to be modified considerably to be useful with scorekeepers in
   general. */

static void
decide_resignation(side)
Side *side;
{
    int ratio, ratio0, chance = 0, sn1;
    Side *side1;
    Strategy *strategy = mplayer(side);

    estimate_strengths(side);
    /* If our estimate of our own points is zero, then we're about to lose the
       game anyway, so just return and avoid screwing up ratio calcs below. */
    if (strategy->alpoints[side->id] <= 0)
      return;
    for_all_sides(side1) {
	if (side != side1 && side1->ingame && !allied_side(side, side1)) {
	    sn1 = side1->id;
	    /* Note that ratio calculations always scale up by 100, so that we
	       can do finer comparisons without needing floating point. */
	    ratio = (strategy->alpoints[sn1] * 100) / strategy->alpoints[side->id];
	    /* code specific to the "time" game */
	    /* the mplayer can severely underestimates its own strength */
	    if (game_class == gc_time) {
		ratio /= 3;
	    }

	    if (strategy->alpoints0[side->id] > 0) {
		ratio0 = (strategy->alpoints0[sn1] * 100) / strategy->alpoints0[side->id];
		/* If we estimated 0 points for some side's initial strength,
		   then our estimate is bad; assume parity. */
		if (ratio0 <= 0)
		  ratio0 = 100;
		/* This formula basically calls for no resignation if ratio is no more
		   than twice what it was initially, 50% chance if ratio is four times
		   what it was (if we started out even, then we're outnumbered 4 to 1),
		   and interpolates for ratios in between. */
		chance = (((ratio * 100) / ratio0) - 200) / 5;
		chance = max(chance, 0);
		chance = min(chance, 90);
	    } else {
		/* work by absolute ratios */
		if (ratio > 400) {
		    chance = ratio / 10;
		}
		chance = min(chance, 90);
	    }
	}
    }

    /* Whether or not we actually resign, we may be willing to
       go for a draw if other players want to. */
    /* (Note that toggling this flag is not exactly poker-faced
       behavior, but I doubt human players will be able to derive
       much advantage, since they'll already have a pretty good
       idea if the AI is in trouble or not.) */
    try_to_draw(side, (chance > 0), "mplayer");
    /* Maybe resign. */
    if (chance > 0) {
	if (probability(chance)) {
	    give_up(side, "mplayer");
	}
    }
}

/* Go through all our units (and allied ones?). */

static void
review_units(side)
Side *side;
{
    int u, u2, cp, cpmin, any;
    int numoffensive[MAXUTYPES], numdefensive[MAXUTYPES];
    Unit *unit, *occ, *unit2;
    Plan *plan;
    Theater *oldtheater, *theater;

    /* This code is specific to the "time" game. */
    if (game_class == gc_time) {
	for_all_unit_types(u) {
	    u2 = mplayer(side)->research_on[u];
	    if (mplayer(side)->research_status[u] == RS_RESEARCH_ASSIGNED) {
		/* is anyone researching? */
		unit2 = NULL;
		for_all_side_units(side, unit) {
		    if (unit->type==u && in_play(unit) &&
			unit->plan && unit->plan->aicontrol) {
			if (unit->plan->tasks &&
			    unit->plan->tasks->type == TASK_RESEARCH &&
			    unit->plan->tasks->args[0] == u2) 
			  unit2 = unit;
		    }
		}
		if (unit2 != NULL) {
		    DMprintf("%s is researching for %s on %s (level %d/%d)\n",
			     unit_desig(unit2), side_desig(side),
			     u_type_name(u2),
			     side->tech[u2], u_tech_to_build(u2));
		} else {
		    DMprintf("no %s is researching for %s on %s!\n",
			     u_type_name(u), side_desig(side),
			     u_type_name(u2));
		    mplayer(side)->research_status[u] = RS_RESEARCH_NEEDED;
		}
	    }
	    if (mplayer(side)->research_status[u] == RS_RESEARCH_NEEDED
		&& needs_research (side, u2)) {
		/* pick for research a unit not building; 
		   if all are building, choose the one which started last */
		unit2 = NULL;
		cpmin = 9999;
		any = 0;
		for_all_side_units(side, unit) {
		    if (unit->type == u
			&& in_play(unit)
			&& unit->plan
			&& unit->plan->aicontrol) {
			any = 1;
			cp = 0;
			occ = NULL;
			if ((unit->plan->tasks != NULL
			     && unit->plan->tasks->type == TASK_BUILD))
			  occ = find_unit_to_complete(unit, unit->plan->tasks);
			if (occ != NULL) {
			    cp = occ->cp - uu_creation_cp(u,occ->type);
			    if (uu_cp_per_build(u,u2) > 0)
			      cp /= uu_cp_per_build(u,u2);
			}
			if (cp < cpmin) {
			    unit2 = unit;
			    cpmin = cp;
			}
		    }
		}
		if (unit2 == NULL) {
		    if (any)
		      DMprintf("no %s is available to research for %s on %s!\n",
			       u_type_name(u), side_desig(side),
			       u_type_name(u2));
		} else {
		    if (assign_to_research_on(side, unit2, u2)) {
			mplayer(side)->research_status[u] =
			  RS_RESEARCH_ASSIGNED;
		    }
		}
	    }
	}
    }

    for_all_unit_types(u) {
	numoffensive[u] = numdefensive[u] = 0;
    }
    for_all_side_units(side, unit) {
	if (in_play(unit) && unit->plan && unit->plan->aicontrol) {
	    /* Count plan types. */
	    switch (unit->plan->type) {
	      case PLAN_OFFENSIVE:
	      case PLAN_EXPLORATORY:
		++numoffensive[unit->type];
		break;
	      case PLAN_DEFENSIVE:
		++numdefensive[unit->type];
		break;
	      default:
	        break;
	    }
	}
    }

    for_all_side_units(side, unit) {
	if (in_play(unit) && unit->plan && unit->plan->aicontrol) {
	    /* code specific to the "time" game */
	    if (game_class == gc_time) {
		u = unit->type;
		u2 = mplayer(side)->research_on[u];

		/* should we upgrade? */
		if (mplayer(side)->research_status[u] == RS_UPGRADE_NEEDED) {
		    cp = 0;
		    occ = NULL;
		    if ((unit->plan->tasks != NULL &&
			 unit->plan->tasks->type == TASK_BUILD))
		      occ = find_unit_to_complete(unit, unit->plan->tasks);
		    if (occ != NULL) {
			cp = occ->cp - uu_creation_cp(u,occ->type);
			if (uu_cp_per_build(u,u2)>0)
			  cp /= uu_cp_per_build(u,u2);
		    }
		    if (occ != NULL && occ->type==u2) {
			/* already upgrading */
			DMprintf("%s is upgrading to %s (%d/%d cp)\n",
				 unit_desig(unit), u_type_name(u2),
				 occ->cp, u_cp(occ->type));
		    } else if (cp >= u_cp(u2)/4) { /* rule-of-thumb... */
			/* complete unit under construction */
			DMprintf("%s will complete %s (now %d/%d cp) before upgrading to %s\n",
				 unit_desig(unit), u_type_name(occ->type),
				 occ->cp, u_cp(occ->type), u_type_name(u2));
		    } else {
			/* start upgrading */
			if (occ != NULL && !fullsized(occ)) {
			    DMprintf("%s will drop work on %s (%d/%d cp) and immediately start upgrading to %s\n",
				 unit_desig(unit), u_type_name(occ->type),
				 occ->cp, u_cp(occ->type), u_type_name(u2));
			} else {
			    DMprintf("%s will start upgrading to %s\n",
				     unit_desig(unit), u_type_name(u2));
			}
			net_set_unit_plan_type(side, unit, PLAN_PASSIVE);
			net_clear_task_agenda(side, unit);
			net_set_build_task(unit, u2, 1);
		    }
		}
	    }

	    plan = unit->plan;
	    oldtheater = unit_theater(unit);
	    /* Goal might have become satisfied. */
	    if (plan->maingoal) {
		if (goal_truth(side, plan->maingoal) == 100) {
		    DMprintf("%s %s satisfied, removing\n",
			     unit_desig(unit), goal_desig(plan->maingoal));
		    net_force_replan(side, unit, FALSE);
		    set_unit_theater(unit, NULL);
		}
	    }
	    /* Theater might have become explored enough (90% known). */
	    if (plan->type == PLAN_EXPLORATORY
	        && (theater = unit_theater(unit)) != NULL
	        && theater->unexplored < theater->size / 10) {
		    DMprintf("%s theater %s is mostly known\n",
			     unit_desig(unit), theater->name);
		    net_force_replan(side, unit, FALSE);
		    set_unit_theater(unit, NULL);
	    }
	    /* Don't let defense-only units pile up. */
	    if (plan->type == PLAN_DEFENSIVE
		&& mobile(unit->type)
		&& (numoffensive[unit->type] / 3) < numdefensive[unit->type]
		&& flip_coin()) {
		DMprintf("%s one of too many on defense (%d off, %d def), replanning\n",
			 unit_desig(unit), numoffensive[unit->type], numdefensive[unit->type]);
		net_force_replan(side, unit, FALSE);
	    }
	    theater = unit_theater(unit);
	    DMprintf("%s currently assigned to %s",
	    	     unit_desig(unit),
		     (theater ? theater->name : "no theater"));
	    if (oldtheater != theater) {
	    	DMprintf(" (was %s)",
			 (oldtheater ? oldtheater->name : "no theater"));
	    }
	    DMprintf("\n");
	}
    }
}

/* Look at our current overall strategy and hack it as needed. */

static void
update_side_strategy(side)
Side *side;
{
    Theater *theater;

    DMprintf("%s updating strategy\n", side_desig(side));
    /* Add something to add/update theaters as things open up. (?) */
    for_all_theaters(side, theater) {
	decide_theater_needs(side, theater);
    }
}

/* Figure out how many units to request for each area. */

static void
decide_theater_needs(side, theater)
Side *side;
Theater *theater;
{
    if (theater->unexplored > 0) {
    	/* Exploration is less important when 90% of a theater is known. */
    	if (theater->unexplored > (theater->size / 10)) {
		++(mplayer(side)->explorersneeded);
    	}
	/* Should look for good exploration units. */
	theater->importance = 50;  /* should depend on context */
/*	theater->reinforce = EXPLORE_AREA;  */
#if 0
    } else if (0 /* few enemies? */) {
	if (theater->allied_makers == 0
	    && theater->makers > 0
	    && theater->nearby) {
	    theater->reinforce = GUARD_BORDER_TOWN + 2 * theater->makers;
	} else if (theater->makers > 0) {
	    theater->reinforce = (theater->border ? GUARD_BORDER_TOWN :
				  GUARD_TOWN) + 2 * theater->allied_makers;
	} else if (theater->allied_bases > 0) {
	    theater->reinforce = (theater->border ? GUARD_BORDER: GUARD_BASE);
	} else if (theater->border) {
	    theater->reinforce = NO_UNITS;
	} else {
	    theater->reinforce = NO_UNITS;
	}
    } else {
	if (theater->allied_makers > 0) {
	    theater->reinforce = DEFEND_TOWN + 5 * theater->makers;
	} else if (theater->allied_bases > 0) {
	    theater->reinforce = DEFEND_BASE + theater->allied_bases;
	} else {
	    theater->reinforce = 0 /* DEFEND_AREA */;
	}
#endif
    }
}

/* For each unit, decide what it should be doing (if anything).  This is
   when a side takes the initiative;  a unit can also request info from
   its side when it is working on its individual plan. */

static void
update_unit_plans(side)
Side *side;
{
    Unit *unit;

    for_all_side_units(side, unit) {
	if (is_active(unit) && unit->plan != NULL) {
	    mplayer_decide_plan(side, unit);
	}
    }
}

/* Randomly change a unit's plans.  (This is really more for
   debugging, exercising plan execution code in novel ways.) */

static void
update_unit_plans_randomly(side)
Side *side;
{
    Unit *unit;

    for_all_side_units(side, unit) {
	if (is_active(unit) && unit->plan && unit->plan->aicontrol) {
	    if (probability(10)) {
		DMprintf("Randomly changed %s plan %s",
			 unit_desig(unit), plan_desig(unit->plan));
		net_set_unit_plan_type(side, unit, xrandom((int) NUMPLANTYPES));
		DMprintf("to plan %s\n", plan_desig(unit->plan));
	    }
	    /* (should add/remove goals randomly) */
	    if (probability(10)) {
		net_set_unit_reserve(side, unit, TRUE, FALSE);
	    }
	    if (probability(10)) {
		net_set_unit_asleep(side, unit, TRUE, FALSE);
	    }
	}
    }
}

/* Push a new goal onto the side's list of goals. */

/* (this should only add goals that are not already present) */

static void
add_goal(side, goal)
Side *side;
Goal *goal;
{
    if (mplayer(side)->numgoals < MAXGOALS) {
	mplayer(side)->goals[(mplayer(side)->numgoals)++] = goal;
    }
}

static Goal *
has_goal(side, goaltype)
Side *side;
GoalType goaltype;
{
    int i;
    Goal *goal;

    for (i = 0; i < mplayer(side)->numgoals; ++i) {
	goal = mplayer(side)->goals[i];
	if (goal != NULL && goal->type == goaltype) {
	    return goal;
	}
    }
    return NULL;
}

static Goal *
has_unsatisfied_goal(side, goaltype)
Side *side;
GoalType goaltype;
{
    int i;
    Goal *goal;

    for (i = 0; i < mplayer(side)->numgoals; ++i) {
	goal = mplayer(side)->goals[i];
	if (goal != NULL && goal->type == goaltype && goal_truth(side, goal) < 100) {
	    return goal;
	}
    }
    return NULL;
}

/* This is for when a unit needs a plan and asks its side for one. */

static void
mplayer_decide_plan(side, unit)
Side *side;
Unit *unit;
{
    Plan *plan = unit->plan;
    int u = unit->type;

    if (plan == NULL || !plan->aicontrol)
      return;

    /* code specific to the "time" game */
    /* don't mess up with units researching or upgrading */
    if (game_class == gc_time) {
	if (mplayer(side)->research_status[u] == RS_UPGRADE_NEEDED
	    && plan->tasks != NULL
	    && plan->tasks->type == TASK_BUILD)
	  return;
	if (mplayer(side)->research_status[u] == RS_RESEARCH_ASSIGNED
	    && plan->tasks != NULL
	    && plan->tasks->type == TASK_RESEARCH)
	  return;
    }
    /* If we're not trying to win at this game, then make the unit act randomly. */
    if (!mplayer(side)->trytowin) {
	net_set_unit_plan_type(side, unit, PLAN_RANDOM);
	net_clear_task_agenda(side, unit);
	return;
    }
    switch (plan->type) {
      case PLAN_PASSIVE:
      case PLAN_NONE:
	if (mobile(u)) {
	    /* Maybe assign to exploration. */
	    if (has_goal(side, GOAL_WORLD_KNOWN)) {
		if (need_this_type_to_explore(side, u)) {
		    /* also limit to a total percentage, in case
		       exploration needs are very high */
		    assign_to_exploration(side, unit);
		    return;
		}
	    }
	    if (type_can_attack(u) || type_can_fire(u)) {
		/* (A more precise test would be "can attack types known to be or
		    likely to be in the current game".) */
		/* Assign most units to offense, save some for defense. */
		if (probability(75))
		  assign_to_offense(side, unit);
		else
		  assign_to_defense(side, unit);
	    } else if (type_can_build_attackers(side, u)) {
		assign_to_offense_support(side, unit);
	    } else {
	    }
	} else {
	    if (has_unsatisfied_goal(side, GOAL_VICINITY_HELD)
		&& type_can_build_attackers(side, u)) {
	    	assign_to_offense_support(side, unit);
	    } else if (has_goal(side, GOAL_WORLD_KNOWN)
	        && need_this_type_to_build_explorers(side, u)) {
		assign_to_explorer_construction(side, unit);
	    } else if (type_can_build_attackers(side, u)) {
	    	assign_to_offense_support(side, unit);
	    } else if (type_can_attack(u) || type_can_fire(u)) {
		assign_to_defense(side, unit);
	    } else {
		assign_to_defense_support(side, unit);
	    }
	}
	break;
      case PLAN_OFFENSIVE:
	/* leave plan alone */
	break;
      case PLAN_EXPLORATORY:
	/* leave plan alone */
	break;
      case PLAN_DEFENSIVE:
	/* leave plan alone */
	break;
      default:
	break;
    }
}

static int
need_this_type_to_explore(side, u)
Side *side;
int u;
{
    int s, numcontacted = 0, numfound = 0;

    if (!mobile(u))
      return FALSE;
    for (s = 1; s <= numsides; ++s) {
    	if (s == side->id)
    	  continue;
	if (mplayer(side)->contacted[s])
	  ++numcontacted;
	if (mplayer(side)->homefound[s])
	  ++numfound;
    }
    if (numcontacted == 0) {
	return TRUE;
    } else if (numfound == 0) {
	return probability(50);
    } else if (numfound < numsides - 1) {
	return probability(10);
    } else {
	return FALSE;
    }
}

struct weightelt {
    int weight;
    long data;
};

static int
compare_weights(w1, w2)
CONST void *w1, *w2;
{
    return (((struct weightelt *) w2)->weight - ((struct weightelt *) w1)->weight);
}

/* Set the unit up as an explorer and let it go. */

static void
assign_to_exploration(side, unit)
Side *side;
Unit *unit;
{
    int numweights = 0, weight, i, dist;
    struct weightelt weights[MAXTHEATERS];
    Theater *theater;

    /* Unit's goal in life will be to see that the world is all known. */
    net_set_unit_plan_type(side, unit, PLAN_EXPLORATORY);
    set_unit_theater(unit, NULL);
    /* Find the theater most in need of exploration. */
    for_all_theaters(side, theater) {
    	if (theater->size > 0 && theater->unexplored > 0) {
	    /* Weight by percentage of theater that is unknown. */
	    weight = (100 * theater->unexplored) / theater->size;
	    /* Downrate theaters that are far away. */
	    dist = distance(unit->x, unit->y, theater->x, theater->y)
	      - isqrt(theater->size) / 2;
	    if (dist < 0)
	      dist = 0;
	    weight /= max(1, (4 * dist) / area.maxdim);
	    /* Uprate the home front by a lot. */
	    if (theater == mplayer(side)->homefront)
	      weight *= 4;
	    /* Flatten out 10% variations. */
	    weight = 10 * (weight / 10);
	    weights[numweights].weight = weight;
	    weights[numweights].data = theater->id;
	    ++numweights;
    	}
    }
    if (numweights > 0) {
    	qsort(weights, numweights, sizeof(struct weightelt), compare_weights);
    	/* Choose randomly among theaters of equal weight. */
    	for (i = 0; i < numweights; ++i)
	  if (weights[i].weight < weights[0].weight)
	    break;
    	theater = mplayer(side)->theatertable[weights[xrandom(i)].data];
    } else {
    	theater = NULL;
    }
    assign_explorer_to_theater(side, unit, theater);
}

static int
probably_explorable(side, x, y, u)
Side *side;
int x, y, u;
{
    int dir, x1, y1, tview, t;

    for_all_directions(dir) {
	if (interior_point_in_dir(x, y, dir, &x1, &y1)) {
	    tview = terrain_view(side, x, y);
	    if (tview == UNSEEN)
	      return TRUE;
	    t = vterrain(tview);
	    if (could_be_on(u, t) && could_live_on(u, t))
	      return TRUE;
	}
    }
    return FALSE;
}

static void
assign_explorer_to_theater(side, unit, theater)
Side *side;
Unit *unit;
Theater *theater;
{
    int sq, x, y, tries = 0;
    Goal *goal;

    /* Undo any existing assignment. */
    if (unit_theater(unit) != NULL) {
	--(unit_theater(unit)->numassigned[unit->type]);
	set_unit_theater(unit, NULL);
	/* (should release existing main goal?) */
    }    
    if (theater != NULL) {
	set_unit_theater(unit, theater);
	++(theater->numassigned[unit->type]);
	goal = create_goal(GOAL_VICINITY_KNOWN, side, TRUE);
	sq = isqrt(theater->size);
	while (++tries < 100) {
	    /* Select a random point within the theater. */
	    x = theater->xmin;  y = theater->ymin;
	    x += (xrandom(theater->xmax - theater->xmin)
		  + xrandom(theater->xmax - theater->xmin)) / 2;
	    y += (xrandom(theater->ymax - theater->ymin)
		  + xrandom(theater->ymax - theater->ymin)) / 2;
	    if (theater_at(side, x, y) == theater
		&& terrain_view(side, x, y) == UNSEEN
		&& probably_explorable(side, x, y, unit->type))
	      break;
	}
	goal->args[0] = x;  goal->args[1] = y;
	goal->args[2] = goal->args[3] = sq / 2;
	net_set_unit_main_goal(side, unit, goal);
	DMprintf("%s now assigned to exploration in %s, around %d,%d\n",
		 unit_desig(unit), theater->name, x, y);
    }
}

static int
need_this_type_to_build_explorers(side, u)
Side *side;
int u;
{
    int s, u2;
	
    for (s = 1; s <= numsides; ++s) {
	if (mplayer(side)->contacted[s])
	  return FALSE;
	if (mplayer(side)->homefound[s])
	  return FALSE;
    }
    for_all_unit_types(u2) {
	if (mobile(u2)
	    /* should also check u2 is a useful explorer */
	    && uu_acp_to_create(u, u2) > 0)
	  return TRUE;
    }
    return FALSE;
}

/* Explorer constructors concentrate on building types that are good for
   exploration. */

static void
assign_to_explorer_construction(side, unit)
Side *side;
Unit *unit;
{
    /* Unit's goal in life will be to help see that the world is all known. */
    net_set_unit_plan_type(side, unit, PLAN_EXPLORATORY);
    DMprintf("%s assigned to explorer construction\n", unit_desig(unit));
}

static void
assign_to_offense(side, unit)
Side *side;
Unit *unit;
{
    int numweights = 0, weight;
    struct weightelt weights[MAXTHEATERS];
    Goal *goal;
    Theater *homefront, *theater;

    net_set_unit_plan_type(side, unit, PLAN_OFFENSIVE);
    net_clear_task_agenda(side, unit);
    /* If our home area is being threatened, assign the unit to it. */
    homefront = mplayer(side)->homefront;
    if (homefront != NULL && homefront->enemystrengthmin > 0) {
	set_unit_theater(unit, homefront);
	goal = create_goal(GOAL_VICINITY_HELD, side, TRUE);
	goal->args[0] = homefront->x;  goal->args[1] = homefront->y;
	goal->args[2] = goal->args[3] = isqrt(homefront->size);
	net_set_unit_main_goal(side, unit, goal);
	DMprintf("%s assigned to offensive in the home front\n",
		 unit_desig(unit));
	return;
    }
    /* If the theater the unit is currently in is being threatened,
       assign the unit to it. */
    /* (should just increase it weight in next calculation?) */
    theater = theater_at(side, unit->x, unit->y);
    if (theater != NULL && theater->enemystrengthmin > 0) {
	set_unit_theater(unit, theater);
	goal = create_goal(GOAL_VICINITY_HELD, side, TRUE);
	/* (should randomize?) */
	goal->args[0] = theater->x;  goal->args[1] = theater->y;
	goal->args[2] = (theater->xmax - theater->xmin) / 2;
	goal->args[3] = (theater->ymax - theater->ymin) / 2;
	net_set_unit_main_goal(side, unit, goal);
	DMprintf("%s assigned to offensive in the theater where it's at now\n",
		 unit_desig(unit));
	return;
    }
    for_all_theaters(side, theater) {
    	if (theater->enemystrengthmin > 0 || theater->unexplored > 0) {
	    /* (should weight by strength relative to own units already there) */
	    weight = theater->enemystrengthmax * 20;
	    /* Prefer not to send unit to farther-away theaters. */
	    if (distance(unit->x, unit->y, theater->x, theater->y) > area.maxdim / 2) {
		weight /= 2;
	    }
	    /* Prefer theaters with more unknown territory. */
	    weight += (10 * theater->unexplored) / max(1, theater->size);
	    weights[numweights].weight = weight;
	    weights[numweights].data = theater->id;
	    ++numweights;
    	}
    }
    if (numweights > 0) {
    	qsort(weights, numweights, sizeof(struct weightelt), compare_weights);
    	theater = mplayer(side)->theatertable[weights[0].data];
    } else {
    	theater = theater_at(side, unit->x, unit->y);
    }
    set_unit_theater(unit, theater);
    if (theater != NULL) {
	++(theater->numassigned[unit->type]);
	goal = create_goal(GOAL_VICINITY_HELD, side, TRUE);
	/* (should randomize?) */
	goal->args[0] = theater->x;  goal->args[1] = theater->y;
	goal->args[2] = (theater->xmax - theater->xmin) / 2;
	goal->args[3] = (theater->ymax - theater->ymin) / 2;
	net_set_unit_main_goal(side, unit, goal);
	DMprintf("%s now assigned to offensive in %s",
		 unit_desig(unit), theater->name);
	if (numweights > 1) {
	    DMprintf(" (weight %d; runnerup was %s, weight %d)",
		     weights[0].weight,
		     (mplayer(side)->theatertable[weights[1].data])->name,
		     weights[1].weight);
	}
	DMprintf("\n");
    } else {
	DMprintf("%s now assigned to offensive in no theater\n",
		 unit_desig(unit));
    }
}

static void
assign_to_offense_support(side, unit)
Side *side;
Unit *unit;
{
    net_set_unit_plan_type(side, unit, PLAN_OFFENSIVE);
    net_clear_task_agenda(side, unit);
}

static int
type_can_build_attackers(side, u)
Side *side;
int u;
{
    int u2;
	
    for_all_unit_types(u2) {
	if (mobile(u2)
	    && (type_can_attack(u2) || type_can_fire(u2))
	    && uu_acp_to_create(u, u2) > 0)
	  return TRUE;
    }
    return FALSE;
}

/* For the given side and unit and plan, calculate the right type of
   unit to build. */

static int
preferred_build_type(side, unit, plantype)
Side *side;
Unit *unit;
int plantype;
{
    int u = unit->type, u2, u3, t;
    int x, y, dir, x1, y1, blockedallaround, uview, est, rslt;
    int prefs[MAXUTYPES];
    int fringeterrain[MAXTTYPES], sumfringe, totfringe;
    int enemytypes[MAXUTYPES];
    int numtotransport[MAXUTYPES];
    Unit *unit2, *occ;
    Theater *theater;

    if (plantype == PLAN_EXPLORATORY) {
	/* Calculate the amount of each type of terrain at the edges
	   of the known world. */
	for_all_terrain_types(t)
	  fringeterrain[t] = 0;
	for_all_cells(x, y) {
	    if (terrain_view(side, x, y) != UNSEEN) {
		for_all_directions(dir) {
		    if (point_in_dir(x, y, dir, &x1, &y1)
			&& terrain_view(side, x1, y1) == UNSEEN) {
			++(fringeterrain[(int) terrain_at(x, y)]);
			break;
		    }
		}
	    }
	}
    } else {
	/* should use estimated strengths instead? */
    	for_all_unit_types(u2)
    	  enemytypes[u2] = 0;
    	for_all_interior_cells(x, y) {
	    if (can_see_actual_units(side, x, y)) {
		for_all_stack(x, y, unit2) {
		    if (!trusted_side(side, unit2->side))
		      ++enemytypes[unit2->type];
		    /* (should count occ types recursively also) */
		    for_all_occupants(unit2, occ) {
			++enemytypes[occ->type];
		    }
		}
	    } else {
		uview = unit_view(side, x, y);
		if (uview != EMPTY) {
		    if (!trusted_side(side, side_n(vside(uview))))
		      ++enemytypes[vtype(uview)];
		}
	    }
    	}
    }
    /* Calculate a basic preference for each possible type. */
    for_all_unit_types(u2) {
	prefs[u2] = 0;
	est = est_completion_time(unit, u2);
	if (could_create(u, u2)
	    /* tmp hack until mplayer can do research */
	    && (u_tech_to_build(u2) > 0 ? side->tech[u2] >= u_tech_to_build(u2) : TRUE)
	    && est >= 0
	    && type_allowed_on_side(u2, side)) {
	    if (0 /* any demand in this unit's own theater */) {
	    } else if (need_more_transportation(side)) {
    		for_all_unit_types(u3) {
		    numtotransport[u3] = 0;
    		}
	    	for_all_theaters(side, theater) {
		    for_all_unit_types(u3) {
			numtotransport[u3] += theater->numtotransport[u3];
		    }
	    	}
    		for_all_unit_types(u3) {
		    if (numtotransport[u3] > 0
			&& mobile(u2)
			&& could_carry(u2, u3)) {
			prefs[u2] += numtotransport[u3];
		    }
	    	}
	    } else {
		/* Prefer units by overall suitability for general plan. */
		if (plantype == PLAN_EXPLORATORY) {
		    /* Weight unit types by suitability for exploration around
		       the edges of the known area. */
		    sumfringe = totfringe = 0;
		    for_all_terrain_types(t) {
			totfringe += fringeterrain[t];
			if (!terrain_always_impassable(u2, t))
			  sumfringe += fringeterrain[t];
		    }
		    if (totfringe < 1)
		      sumfringe = totfringe = 1;
		    /* Scale - so 5% diffs in amt of crossable terrain
		       don't affect result. */
		    prefs[u2] = (20 * sumfringe) / totfringe;
		    /* Prefer types that are quicker to build. */
		    prefs[u2] /= max(1, est / 8);
		} else {
		    /* Weight unit type by effectiveness against known enemies. */
		    for_all_unit_types(u3) {
			if (enemytypes[u3] > 0) {
			    if (uu_zz_bhw(u2, u3) > 0) {
				prefs[u2] += ((uu_zz_bhw(u2, u3) * 100) / bhw_max) * enemytypes[u3];
			    }
			    if (uu_zz_bcw(u2, u3) > 0) {
				prefs[u2] += uu_zz_bcw(u2, u3) * enemytypes[u3];
			    }
			}
		    }
		    /* Prefer types that are quicker to build. */
		    prefs[u2] /= max(1, est / 8);
		}
		if (prefs[u2] < 1)
		  prefs[u2] = 1;
	    }
	}
    }
    /* Units that can't even get out of the builder get their preference
       cut.  This helps prevent the construction of large ships in Denver. */
    /* (should allow if units would have some other way to leave) */
    if (1 /* plantype == PLAN_EXPLORATORY */) {
	for_all_unit_types(u2) {
	    if (prefs[u2] > 0) {
		blockedallaround = TRUE;
		for_all_directions(dir) {
		    point_in_dir(unit->x, unit->y, dir, &x1, &y1);
		    if (!terrain_always_impassable(u2, terrain_at(x1, y1))) {
		    	blockedallaround = FALSE;
		    	break;
		    }
#if 0  /* should replace this with a more useful test */
		    if (unit_at(x1, y1) != NULL) {
		    	blockedallaround = FALSE;
		    	break;
		    }
#endif
		}
		if (blockedallaround)
		  prefs[u2] = 0;
	    }
	}
    }
    DMprintf("%s preferred build type is ", unit_desig(unit));
    /* Look for an existing incomplete occupant and prefer to build its type,
       if it is in the choices in the typelist. */
    for_all_occupants(unit, occ) {
	if (in_play(occ) && !completed(occ)) {
	    if (prefs[occ->type] > 0 && flip_coin()) {
		rslt = occ->type;
		DMprintf("%s (incomplete occupant)\n", u_type_name(rslt));
		return rslt;
	    }
	}
    }
    for_all_unit_types(u2)
      if (prefs[u2] < 0)
        prefs[u2] = 0;
    rslt = select_by_weight(prefs, numutypes);
    if (!is_unit_type(rslt))
      rslt = NONUTYPE;
    if (DebugM) {
	if (is_unit_type(rslt)) {
	    DMprintf("%s (choices were", u_type_name(rslt));
	    for_all_unit_types(u2) {
		if (prefs[u2] > 0)
		  DMprintf(" %s,%d", utype_name_n(u2, 1), prefs[u2]);
	    }
	    DMprintf(")");
	} else {
	    DMprintf("nothing (no choices)");
	}
	DMprintf("\n");
    }
    return rslt;
}

static int
need_more_transportation(side)
Side *side;
{
    int u3, u2, anytransport;
    Theater *theater;

    for_all_theaters(side, theater) {
	for_all_unit_types(u3) {
	    if (theater->numtotransport[u3] > 0) {
		anytransport = FALSE;
		for_all_unit_types(u2) {
		    if (theater->numassigned[u2] > 0
			&& mobile(u2)
			&& could_carry(u2, u3))
		      anytransport = TRUE;
		}
		if (!anytransport)
		  return TRUE;
	    }
	}
    }
    return FALSE;
}

static void
assign_to_defense(side, unit)
Side *side;
Unit *unit;
{
    net_set_unit_plan_type(side, unit, PLAN_DEFENSIVE);
    net_clear_task_agenda(side, unit);
}

static void
assign_to_defense_support(side, unit)
Side *side;
Unit *unit;
{
    net_set_unit_plan_type(side, unit, PLAN_DEFENSIVE);
    net_clear_task_agenda(side, unit);
}

static int
can_research_on(u, u2)
int u;
int u2;
{
    int acp_res = uu_acp_to_research(u, u2);

    if (acp_res < 1 || acp_res > u_acp(u))
      return 0;

    return 1;
}

/* code specific to the "time" game */
static int 
needs_research (side, u)
Side *side;
int u;
{
    int u2, i;

    if (game_class != gc_time)
      return 0;

    if (side->tech[u] >= u_tech_to_build(u) ||
	u_tech_max(u)  > u_tech_to_build(u))
      return 0;
    
    i = 0;
    for_all_unit_types(u2) {
	i += uu_acp_to_create(u, u2) > 0;
    }
    if (i < 2)
      return 0;

    return 1;
}

static int
assign_to_research_on(side, unit, u2)
Side *side;
Unit *unit;
int u2;
{
    int lev = u_tech_to_build(u2);

    if (!can_research_on(unit->type, u2)) {
	DMprintf("%s cannot research on %s!\n",
	     unit_desig(unit), u_type_name(u2));
	return 0;
    }

    DMprintf("%s will research for %s on %s (to level %d)\n",
	     unit_desig(unit), side_desig(side), u_type_name(u2), lev);

    net_set_unit_plan_type(side, unit, PLAN_PASSIVE);
    net_push_research_task(unit, u2, lev);
    return 1;
}

static int
mplayer_adjust_plan(side, unit)
Side *side;
Unit *unit;
{
    int curactor, u3;
    Task *task;

    if ((unit->plan->type == PLAN_OFFENSIVE
	 || unit->plan->type == PLAN_EXPLORATORY)
	&& !mobile(unit->type)
	&& unit->plan->aicontrol
	&& !unit->plan->asleep
	&& unit->plan->tasks == NULL
	) {
	    u3 = preferred_build_type(side, unit, unit->plan->type);
	    if (is_unit_type(u3)) {
		task = unit->plan->tasks;
		if (task == NULL || task->type != TASK_BUILD) {
		    DMprintf("%s directed to build %s\n",
			   unit_desig(unit), u_type_name(u3));
		    net_set_build_task(unit, u3, 2);
		} else {
		    DMprintf("%s already building, leaving alone\n",
			   unit_desig(unit));
		}
		/* Only do one at a time, wait for next go-around for next unit. */
		return FALSE;
	    }
    }
    if (unit->plan->waitingfortasks
	&& unit->plan->aicontrol
	) {
	net_force_replan(side, unit, FALSE);
    }
    if (!unit->plan->reserve
	&& unit->plan->execs_this_turn > 10 * max(1, u_acp(unit->type))) {
	net_set_unit_reserve(side, unit, TRUE, FALSE);
    }
    /* Look at more units. */
    return TRUE;
}

/* This is called when an exploring unit gets confused about what to do. */

static int
mplayer_guide_explorer(side, unit)
Side *side;
Unit *unit;
{
    if (probability(10) && build_base_for_self(side, unit))
      return TRUE;
    if (probability(10) && build_base_for_others(side, unit))
      return TRUE;
    return FALSE;
}

/* Decide for the unit whether it should build a base for its own benefit. */

static int
build_base_for_self(side, unit)
Side *side;
Unit *unit;
{
    int u = unit->type, u2, cando = FALSE;

    for_all_unit_types(u2) {
	if (uu_acp_to_create(u, u2) > 0
	    && (uu_creation_cp(u, u2) >= u_cp(u2)
	        || uu_acp_to_build(u, u2) > 0)
	    && u_is_base(u2)
	    /* (should check if any advantage to building) */
	    ) {
	    cando = TRUE;
	    break;
	}
    }
    if (cando) {
	DMprintf("%s building %s as a base for itself\n",
		 unit_desig(unit), u_type_name(u2));
	net_set_build_task(unit, u2, 1);
	return TRUE;
    }
    return FALSE;
}

/* Decide for the unit whether it should build a base to help other units. */

static int
build_base_for_others(side, unit)
Side *side;
Unit *unit;
{
    int u = unit->type, u2, cando = FALSE;

    for_all_unit_types(u2) {
	if (uu_acp_to_create(u, u2) > 0
	    && (uu_creation_cp(u, u2) >= u_cp(u2)
	        || uu_acp_to_build(u, u2) > 0)
	    && u_is_base(u2)
	    /* (should check if any advantage to building) */
	    ) {
	    cando = TRUE;
	    break;
	}
    }
    if (cando) {
	DMprintf("%s building %s as a base for others\n",
		 unit_desig(unit), u_type_name(u2));
	net_set_build_task(unit, u2, 1);
	return TRUE;
    }
    return FALSE;
}

static int
build_depot_for_self(side, unit)
Side *side;
Unit *unit;
{
    int u = unit->type, u2, cando = FALSE;

    for_all_unit_types(u2) {
	if (uu_acp_to_create(u, u2) > 0
	    && (uu_creation_cp(u, u2) >= u_cp(u2)
	        || uu_acp_to_build(u, u2) > 0)
	    /* (should check if any advantage to building) */
	   ) {
	   cando = TRUE;
	   break;
	}
    }
    if (cando) {
	DMprintf("%s building %s as a depot for itself\n",
		     unit_desig(unit), u_type_name(u2));
	net_set_build_task(unit, u2, 1);
	return TRUE;
    }
    return FALSE;
}

static void
mplayer_react_to_action_result(side, unit, rslt)
Side *side;
Unit *unit;
int rslt;
{
}

/* This is a hook that runs after each task is executed. */

static void
mplayer_react_to_task_result(side, unit, task, rslt)
Side *side;
Unit *unit;
Task *task;
TaskOutcome rslt;
{
    int dx, dy, x1, y1, fact;
    Unit *occ;
    Theater *theater;

    /* React to an apparent blockage. */
    if (rslt == TASK_FAILED
	&& task != NULL
	&& task->type == TASK_MOVE_TO
	&& task->retrynum > 2) {
	if (desired_direction_impassable(unit, task->args[0], task->args[1])) {
	    if (could_be_ferried(unit, task->args[0], task->args[1])) {
		if (unit->plan->type == PLAN_EXPLORATORY && flip_coin()) {
		    DMprintf("%s blocked while exploring, \n", unit_desig(unit));
	      	    if (flip_coin()) {
			DMprintf("changing theaters\n");
			change_to_adjacent_theater(side, unit);
		    } else {
			DMprintf("changing goal within theater\n");
			assign_explorer_to_theater(side, unit, unit_theater(unit));
		    }
		    return;
		} else if (flip_coin()) {
		    DMprintf("%s blocked, will wait for transport\n",
			     unit_desig(unit));
		    theater = theater_at(side, unit->x, unit->y);
		    if (theater != NULL) {
			++(theater->numtotransport[unit->type]);
		    }
		    net_set_unit_reserve(side, unit, TRUE, FALSE);
		    net_set_unit_waiting_for_transport(side, unit, TRUE);
		    return;
		}
	    } else {
	    	if (unit->occupant) {
		    DMprintf("%s blocked while transporting, will sit briefly\n",
			     unit_desig(unit));
		    net_set_unit_reserve(side, unit, TRUE, FALSE);
		    for_all_occupants(unit, occ) {
		    	net_wake_unit(side, occ, FALSE);
		    }
		    return;
	    	}
		/* Another option is to transfer to another theater.
		   This is especially useful when exploring. */
		if (unit->plan->type == PLAN_EXPLORATORY && flip_coin()) {
		    DMprintf("%s blocked while exploring, changing theaters\n",
			     unit_desig(unit));
		    change_to_adjacent_theater(side, unit);
		    return;
		}
	    }
	    /* Try moving sideways. */
	    if (probability(80)) {
		dx = task->args[0] - unit->x;  dy = task->args[1] - unit->y;
		fact = (flip_coin() ? 50 : -50);
		x1 = unit->x - ((fact * dy) / 100);  y1 = unit->y + ((fact * dx) / 100);
		if (inside_area(x1, y1))
		  net_push_move_near_task(unit, x1, y1, 1);
	    }
	    return;
	} else if (blocked_by_enemy(unit, task->args[0], task->args[1], TRUE)) {
	    /* (should decide if allowable risk to passengers) */
	    DMprintf("%s blocked by enemy\n", unit_desig(unit));
	    if (!attack_blockage(side, unit, task->args[0], task->args[1], TRUE)) {
		if (blocked_by_enemy(unit, task->args[0], task->args[1], FALSE)) {
		    attack_blockage(side, unit, task->args[0], task->args[1], FALSE);
		} else {
		    /* (should move sideways?) */
		}
	    }
	} else {
	    /* what to do about other failures? */
	}
	return;
    }
    /* React to inability to resupply by trying to build a base. */
    if (rslt == TASK_FAILED
	&& task != NULL
	&& task->type == TASK_RESUPPLY
	&& task->retrynum > 2) {
    	net_set_unit_reserve(side, unit, FALSE, FALSE);
    	build_depot_for_self(side, unit);
    }
}

static void
change_to_adjacent_theater(side, unit)
Side *side;
Unit *unit;
{
    int dir;
    Theater *theater, *newtheater = NULL;

    theater = unit_theater(unit);
    if (theater != NULL) {
   	for_all_directions(dir) {
   	    if (theater == mplayer(side)->perimeters[dir]) {
		if (probability(20) && mplayer(side)->midranges[dir] != NULL)
		  newtheater = mplayer(side)->midranges[dir];
		else
   	    	  newtheater = mplayer(side)->perimeters[flip_coin() ? left_dir(dir) : right_dir(dir)];
   	    	break;
   	    }
   	    if (theater == mplayer(side)->midranges[dir]) {
		if (probability(20) && mplayer(side)->perimeters[dir] != NULL)
		  newtheater = mplayer(side)->perimeters[dir];
		else if (probability(20) && mplayer(side)->remotes[dir] != NULL)
		  newtheater = mplayer(side)->remotes[dir];
		else
   	    	  newtheater = mplayer(side)->midranges[flip_coin() ? left_dir(dir) : right_dir(dir)];
   	    	break;
   	    }
   	    if (theater == mplayer(side)->remotes[dir]) {
 		if (probability(20) && mplayer(side)->midranges[dir] != NULL)
		  newtheater = mplayer(side)->midranges[dir];
		else
   	    	  newtheater = mplayer(side)->remotes[flip_coin() ? left_dir(dir) : right_dir(dir)];
   	    	break;
   	    }
   	}
   	/* (should add grid case also?) */
   	if (newtheater != NULL) {
	    assign_explorer_to_theater(side, unit, newtheater);
   	}
    }
}

/* (should account for impassability because of borders, etc) */

static int
desired_direction_impassable(unit, x, y)
Unit *unit;
int x, y;
{
    int dirs[NUMDIRS], numdirs, i, x1, y1, t, numbaddirs = 0;

    numdirs = choose_move_dirs(unit, x, y, TRUE, NULL, NULL, dirs);
    for (i = 0; i < numdirs; ++i) {
	point_in_dir(unit->x, unit->y, dirs[i], &x1, &y1);
	t = terrain_at(x1, y1);
	if (terrain_always_impassable(unit->type, t))
	  ++numbaddirs;
    }
    return (numbaddirs == numdirs);
}

static int
could_be_ferried(unit, x, y)
Unit *unit;
int x, y;
{
    int dirs[NUMDIRS], numdirs, i, x1, y1, t, u2;

    if (!carryable(unit->type))
      return FALSE;
    numdirs = choose_move_dirs(unit, x, y, FALSE, NULL, NULL, dirs);
    for (i = 0; i < numdirs; ++i) {
	point_in_dir(unit->x, unit->y, dirs[i], &x1, &y1);
	t = terrain_at(x1, y1);
	/* See if there is a type that can carry us through via this direction. */
	for_all_unit_types(u2) {
	    if (could_carry(u2, unit->type)
	        && mobile(u2)
	        && !terrain_always_impassable(u2, t)
	        /* should also have "and this type is avail to us" */
	        ) {
	        return TRUE;
	    }
	}
    }
    return FALSE;
}

static int
blocked_by_enemy(unit, x, y, shortest)
Unit *unit;
int x, y, shortest;
{
    int dirs[NUMDIRS], numdirs, i, x1, y1, t, numbaddirs = 0;
    Unit *unit2;

    numdirs = choose_move_dirs(unit, x, y, shortest, plausible_move_dir, NULL, dirs);
    /* No plausible dirs anyhow, so presence of enemy irrelevant. */
    if (numdirs == 0)
      return FALSE;
    for (i = 0; i < numdirs; ++i) {
	point_in_dir(unit->x, unit->y, dirs[i], &x1, &y1);
	unit2 = unit_at(x1, y1);
	if (in_play(unit2) && !trusted_side(unit->side, unit2->side))
	  ++numbaddirs;
    }
    return (numbaddirs == numdirs);
}

static int
attack_blockage(side, unit, x, y, shortest)
Side *side;
Unit *unit;
int x, y, shortest;
{
    int dirs[NUMDIRS], numdirs, i, x1, y1, t;
    Unit *unit2;

    numdirs = choose_move_dirs(unit, x, y, shortest, plausible_move_dir, NULL, dirs);
    for (i = 0; i < numdirs; ++i) {
	point_in_dir(unit->x, unit->y, dirs[i], &x1, &y1);
	unit2 = unit_at(x1, y1);
	if (in_play(unit2)
	    && !trusted_side(unit->side, unit2->side)
	    && uu_zz_bhw(unit->type, unit2->type) > 0
	    ) {
	    net_push_specific_hit_task(unit, x1, y1, unit2->type, side_number(unit2->side));
	    return TRUE;
	}
    }
    return FALSE;
}

static void
mplayer_react_to_new_side(side, side2)
Side *side, *side2;
{
    /* (Assumes we call this right after adding each new side) */
    int oldnumsides = numsides - 1;
    int *newpeople, s;
    Theater *theater;

    for_all_theaters(side, theater) {
	/* Grow any people count arrays if present. */
	if (theater->people != NULL) {
	    newpeople = (int *) xmalloc ((numsides + 1) * sizeof(int));
	    for (s = 0; s <= oldnumsides; ++s)
	      newpeople[s] = theater->people[s];
	    free(theater->people);
	    theater->people = newpeople;
	}
    }
    anewside = side2;
    estimate_strengths(side);
    anewside = NULL;
}

/* At the end of a turn, re-evaluate the plans of some units in case
   the situation changed. */

static void
mplayer_finish_movement(side)
Side *side;
{
    int u, scan;
    Unit *unit;
    Theater *theater;

    scan = FALSE;
    for_all_theaters(side, theater) {
	for_all_unit_types(u) {
	    if (theater->numtotransport[u] > 0) {
		scan = TRUE;
		break;
	    }
	}
	if (scan)
	  break;
    }
    if (scan) {
	/* Find a unit needing transport. */
	for_all_side_units(side, unit) {
	    if (is_active(unit)
		&& unit->plan
		&& unit->plan->aicontrol
		&& unit->plan->waitingfortransport) {
		search_for_available_transport(unit, 0);
		net_set_unit_waiting_for_transport(side, unit, FALSE);
	    }
	}
    }
    for_all_side_units(side, unit) {
	if (is_active(unit)
	    && unit->plan
	    && unit->plan->aicontrol) {
	    rethink_plan(unit);
	}
    }
}

static Unit *
search_for_available_transport(unit, purpose)
Unit *unit;
int purpose;
{
    int dist, closestdist = area.maxdim;
    Unit *transport, *closesttransport = NULL;
    Theater *theater = unit_theater(unit);

    /* (more efficient to search adjacent cells first?) */
    for_all_side_units(unit->side, transport) {
	if (is_active(transport)
	    && mobile(transport->type)
	    && could_carry(transport->type, unit->type)
	    && transport->occupant == NULL /* (should be "has room") */
	    && transport->act != NULL /* not quite correct, but to fix bug */
	    && (purpose == 1 ? accelerator(transport->type, unit->type) : TRUE)
	    ) {
	    /* Don't grab at units being moved manually. */
	    if (transport->plan
		&& !transport->plan->aicontrol)
	      continue;
	    /* Maybe this one is already coming to get somebody. */
	    if (transport->plan
		&& transport->plan->tasks != NULL
		&& transport->plan->tasks->type == TASK_PICKUP) {
		if (transport->plan->tasks->args[0] == unit->id)
		  return transport;
		/* Picking up somebody else - don't hijack. */
		continue;
	    }
	    if (transport->plan
		&& transport->plan->tasks != NULL
		&& transport->plan->tasks->type == TASK_MOVE_TO
		&& transport->plan->tasks->next != NULL
		&& transport->plan->tasks->next->type == TASK_PICKUP) {
		if (transport->plan->tasks->next->args[0] == unit->id)
		  return transport;
		/* Picking up somebody else - don't hijack. */
		continue;
	    }
	    dist = distance(unit->x, unit->y, transport->x, transport->y);
	    if (dist < closestdist || (dist == closestdist && flip_coin())) {
		closesttransport = transport;
		closestdist = dist;
	    }
	    /* If transport already adjacent, no need to keep looking. */
	    if (closestdist <= 1)
	      break;
	}
    }
    if (closesttransport != NULL && closesttransport->plan != NULL) {
	net_clear_task_agenda(unit->side, unit);
	/* (could inherit unit's goal, but not needed) */
	net_set_unit_main_goal(unit->side, closesttransport, NULL);
	net_push_pickup_task(closesttransport, unit);
	net_push_move_near_task(closesttransport, unit->x, unit->y, 1);
	net_push_occupy_task(unit, closesttransport);
	/* No longer count this unit as needing transport. */
	if (theater != NULL) {
	    --(theater->numtotransport[unit->type]);
	    set_unit_theater(closesttransport, theater);
	}
	DMprintf("%s will be picked up by closest transport %s\n",
	         unit_desig(unit), unit_desig(closesttransport));
	return closesttransport;
    }
    return NULL;
}

/* For units with plans and that are under AI control, consider changing the
   current plan/tasks. */

static void
rethink_plan(unit)
Unit *unit;
{
    int dist, x1, y1;
    Task *toptask = unit->plan->tasks, *nexttask = NULL;
    Plan *plan = unit->plan;
    Unit *transport;

    if (toptask)
      nexttask = toptask->next;
    /* If we have a long ways to go, see if there is a transport available that
       can get us there faster.  */
    if (toptask != NULL
	&& (toptask->type == TASK_HIT_UNIT
	    || (toptask->type == TASK_MOVE_TO
		&& nexttask != NULL
		&& nexttask->type == TASK_HIT_UNIT))
        && !plan->reserve
        && !plan->asleep
        && !plan->waitingfortransport
        && (unit->transport == NULL || !mobile(unit->transport->type))
        && ((dist = distance(unit->x, unit->y,
			     toptask->args[0], toptask->args[1]))
            >= 4 * u_acp(unit->type))
        && accelerable(unit->type)
        ) {
        DMprintf("%s looking for transport to accelerate with;\n", unit_desig(unit));
        transport = search_for_available_transport(unit, 1);
        if (transport != NULL) {
	    /* net_push_sentry_task(unit, max(1, dist / max(1, u_acp(transport->type)))); */
	    net_set_unit_reserve(unit->side, unit, TRUE, FALSE);
	    net_set_unit_waiting_for_transport(unit->side, unit, FALSE);
        } else {
	    DMprintf("  found nothing\n");
        }
    }
    if (unit->plan->type == PLAN_OFFENSIVE
        && toptask != NULL
        && toptask->type == TASK_MOVE_TO
        && distance(unit->x, unit->y, toptask->args[0], toptask->args[1])
		>= min(2, u_acp(unit->type))
        && enemy_close_by(unit->side, unit, 1 /* 2 would be better? */, &x1, &y1)
        ) {
	net_push_hit_task(unit, x1, y1);
	DMprintf("%s sees enemy close by, will attack it\n", unit_desig(unit));
    }
    /* (should also notice fire opportunities) */
    /* If we see somebody that could be captured and help us explore, set up
       to produce capturers. */
    if (!mobile(unit->type)
	&& (unit->plan->type == PLAN_EXPLORATORY || unit->plan->type == PLAN_OFFENSIVE)
	) {
	int range = 4, rslt, x, y;

	DMprintf("%s searching for useful capture within %d in order to choose build; found ",
	     	 unit_desig(unit), range);
	tmpunit = unit;
	rslt = search_around(unit->x, unit->y, range, useful_captureable_here,
			     &x, &y, 1);
	if (rslt && is_unit_type(tmputype)) {
	    DMprintf("%s at %d,%d", u_type_name(tmputype), x, y);
	    if (toptask != NULL
		&& toptask->type == TASK_BUILD
		&& uu_capture(toptask->args[0], tmputype)
		) {
		/* Already doing the right thing. */
		DMprintf(" - already building %s", u_type_name(toptask->args[0]));
	    } else {
		/* (should find best type that can capture quickly,
		    schedule to build it) */
		DMprintf(" - duhhh, what now?");
	    }
	} else {
	    DMprintf("nothing");
	}
	DMprintf("\n");
    }
}

/* Detect an enemy unit in our own or an adjacent cell. */

static int victimx, victimy, victimrating;

static int
enemy_close_by(side, unit, dist, xp, yp)
Side *side;
Unit *unit;
int dist, *xp, *yp;
{
    int x = unit->x, y = unit->y, dir, x1, y1;

    victimrating = -9999;
    tmpunit = unit;
    victim_here(x, y);
    for_all_directions(dir) {
	if (point_in_dir(x, y, dir, &x1, &y1)) {
	    victim_here(x, y);
	}
    }
    if (victimrating > -9999) {
	*xp = victimx;  *yp = victimy;
	return TRUE;
    } else {
	return FALSE;
    }
}

static void
mplayer_react_to_unit_loss(side, unit)
Side *side;
Unit *unit;
{
    int x = unit->x, y = unit->y;
    Theater *th;

    if (!inside_area(x, y)) {
	x = unit->prevx;  y = unit->prevy;
    }
    if (!inside_area(x, y))
      return;
    /* Count the unit as having been lost in a particular theater. */
    if (mplayer(side) && (th = theater_at(side, x, y)) != NULL) {
    	++(th->units_lost);
    }
}

static void
mplayer_receive_message(side, sender, str)
Side *side, *sender;
char *str;
{
    /* First detect standard messages. */
    if (strcmp(str, "Eh?") == 0) {
	/* Don't respond, otherwise we might infinitely recurse. */
    } else if (allied_side(side, sender)) {
	/* (should say something) */
    } else {
	/* Detect insults and respond appropriately. */
	if (strstr(str, "idiot")) {
	    net_send_message(side, add_side_to_set(sender, NOSIDES), "Loser!");
	} else if (strstr(str, "loser")) {
	    net_send_message(side, add_side_to_set(sender, NOSIDES), "Idiot!");
	} else {
	    /* No idea what the message was, be puzzled. */
	    net_send_message(side, add_side_to_set(sender, NOSIDES), "Eh?");
	}
    }
}

/* This is used by interfaces to display the theater in use at a given point. */

static char *
mplayer_at_desig(side, x, y)
Side *side;
int x, y;
{
    Theater *theater;

    if (mplayer(side) == NULL)
      return "";
    theater = theater_at(side, x, y);
    return (theater ? theater->name : "<no theater>");
}

static int
mplayer_theater_at(side, x, y)
Side *side;
int x, y;
{
    Theater *theater;

    if (mplayer(side) == NULL)
      return 0;
    theater = theater_at(side, x, y);
    return (theater ? theater->id : 0);
}

/* Collect initial strength information stored in the mplayer's private saved
   data. */

static int
mplayer_read_strengths(side)
Side *side;
{
    int sn1, u, found = FALSE;
    char *propname;
    Obj *props, *bdg, *rest, *sidebdg, *urest;
    Side *side1;
    Strategy *strategy = mplayer(side);

    props = find_at_key(side->aidata, "mplayer");
    for (; props != lispnil; props = cdr(props)) {
	bdg = car(props);
	propname = c_string(car(bdg));
	if (strcmp(propname, "strengths0") == 0) {
	    found = TRUE;
	    rest = cdr(bdg);
	    for_all_sides(side1) {
		sn1 = side1->id;
		sidebdg = car(rest);
		urest = cadr(sidebdg);
		for_all_unit_types(u) {
		    strategy->strengths0[sn1][u] = c_number(car(urest));
		    urest = cdr(urest);
		}
		rest = cdr(rest);
	    }
	} else if (strcmp(propname, "alstrengths0") == 0) {
	    found = TRUE;
	    rest = cdr(bdg);
	    for_all_sides(side1) {
		sn1 = side1->id;
		sidebdg = car(rest);
		urest = cadr(sidebdg);
		for_all_unit_types(u) {
		    strategy->alstrengths0[sn1][u] = c_number(car(urest));
		    urest = cdr(urest);
		}
		rest = cdr(rest);
	    }
	} else if (strcmp(propname, "points0") == 0) {
	    found = TRUE;
	    rest = cdr(bdg);
	    for_all_sides(side1) {
		sn1 = side1->id;
		strategy->points0[sn1] = c_number(car(rest));
		rest = cdr(rest);
	    }
	} else if (strcmp(propname, "alpoints0") == 0) {
	    found = TRUE;
	    rest = cdr(bdg);
	    for_all_sides(side1) {
		sn1 = side1->id;
		strategy->alpoints0[sn1] = c_number(car(rest));
		rest = cdr(rest);
	    }
	} else {
	}
    }
    return found;
}

/* Write out any state that the mplayer must preserve.  We don't actually write;
   instead we build a Lisp object and pass that back to the writing routines. */

static Obj *
mplayer_save_state(side)
Side *side;
{
    int sn1, u;
    Obj *rslt, *vallist, *uvallist;
    Side *side1;
    Strategy *strategy = mplayer(side);

    rslt = lispnil;
    /* Just return last result if it's already been computed. */
    if (strategy->writable_state != lispnil || xmalloc_warnings)
      return strategy->writable_state;
    /* We're pushing bindings onto a list, so do in reverse of desired order. */
    vallist = lispnil;
    for_all_sides(side1) {
	sn1 = side1->id;
	uvallist = lispnil;
	for_all_unit_types(u) {
	    uvallist = cons(new_number(strategy->alstrengths0[sn1][u]), uvallist);
	}
	uvallist = reverse(uvallist);
	push_binding(&vallist, new_number(sn1), uvallist);
    }
    vallist = reverse(vallist);
    push_cdr_binding(&rslt, intern_symbol("alstrengths0"), vallist);
    vallist = lispnil;
    for_all_sides(side1) {
	sn1 = side1->id;
	uvallist = lispnil;
	for_all_unit_types(u) {
	    uvallist = cons(new_number(strategy->strengths0[sn1][u]), uvallist);
	}
	uvallist = reverse(uvallist);
	push_binding(&vallist, new_number(sn1), uvallist);
    }
    vallist = reverse(vallist);
    push_cdr_binding(&rslt, intern_symbol("strengths0"), vallist);
    vallist = lispnil;
    for_all_sides(side1) {
	sn1 = side1->id;
	vallist = cons(new_number(strategy->alpoints0[sn1]), vallist);
    }
    vallist = reverse(vallist);
    push_cdr_binding(&rslt, intern_symbol("alpoints0"), vallist);
    vallist = lispnil;
    for_all_sides(side1) {
	sn1 = side1->id;
	vallist = cons(new_number(strategy->points0[sn1]), vallist);
    }
    vallist = reverse(vallist);
    push_cdr_binding(&rslt, intern_symbol("points0"), vallist);
    strategy->writable_state = rslt;
    return rslt;
}