File: city.c

package info (click to toggle)
freeciv 2.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 212,508 kB
  • sloc: ansic: 443,831; cpp: 29,541; sh: 7,982; makefile: 7,886; python: 1,933; xml: 945
file content (3248 lines) | stat: -rw-r--r-- 115,509 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
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
/***********************************************************************
 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
***********************************************************************/

#ifdef HAVE_CONFIG_H
#include <fc_config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <math.h> /* pow, sqrt, exp */

/* utility */
#include "distribute.h"
#include "fcintl.h"
#include "log.h"
#include "mem.h"
#include "support.h"

/* common */
#include "ai.h"
#include "citizens.h"
#include "effects.h"
#include "game.h"
#include "government.h"
#include "improvement.h"
#include "map.h"
#include "movement.h"
#include "packets.h"
#include "specialist.h"
#include "traderoutes.h"
#include "unit.h"

/* aicore */
#include "cm.h"

#include "city.h"

/* Define this to add in extra (very slow) assertions for the city code. */
#undef CITY_DEBUGGING

static char *citylog_map_line(int y, int city_radius_sq, int *city_map_data);
#ifdef DEBUG
/* only used for debugging */
static void citylog_map_index(enum log_level level);
static void citylog_map_radius_sq(enum log_level level);
#endif

/* Get city tile informations using the city tile index. */
static struct iter_index *city_map_index = NULL;
/* Get city tile informations using the city tile coordinates. This is an
 * [x][y] array of integer values corresponding to city_map_index. The
 * coordinates x and y are in the range [0, CITY_MAP_MAX_SIZE] */
static int city_map_xy[CITY_MAP_MAX_SIZE][CITY_MAP_MAX_SIZE];

/* number of tiles of a city; depends on the squared city radius */
static int city_map_numtiles[CITY_MAP_MAX_RADIUS_SQ + 1];

/* definitions and functions for the tile_cache */
struct tile_cache {
  int output[O_LAST];
};

static inline void city_tile_cache_update(struct city *pcity);
static inline int city_tile_cache_get_output(const struct city *pcity,
                                             int city_tile_index,
                                             enum output_type_id o);

struct citystyle *city_styles = NULL;

/* One day these values may be read in from the ruleset.  In the meantime
 * they're just an easy way to access information about each output type. */
struct output_type output_types[O_LAST] = {
  {O_FOOD, N_("Food"), "food", TRUE, UNHAPPY_PENALTY_SURPLUS},
  {O_SHIELD, N_("Shield"), "shield", TRUE, UNHAPPY_PENALTY_SURPLUS},
  {O_TRADE, N_("Trade"), "trade", TRUE, UNHAPPY_PENALTY_NONE},
  {O_GOLD, N_("Gold"), "gold", FALSE, UNHAPPY_PENALTY_ALL_PRODUCTION},
  {O_LUXURY, N_("Luxury"), "luxury", FALSE, UNHAPPY_PENALTY_NONE},
  {O_SCIENCE, N_("Science"), "science", FALSE, UNHAPPY_PENALTY_ALL_PRODUCTION}
};

/**************************************************************************
  Returns the coordinates for the given city tile index taking into account
  the squared city radius.
**************************************************************************/
bool city_tile_index_to_xy(int *city_map_x, int *city_map_y,
                           int city_tile_index, int city_radius_sq)
{
  fc_assert_ret_val(city_radius_sq >= CITY_MAP_MIN_RADIUS_SQ, FALSE);
  fc_assert_ret_val(city_radius_sq <= CITY_MAP_MAX_RADIUS_SQ, FALSE);

  /* tile indices are sorted from smallest to largest city radius */
  if (city_tile_index < 0
      || city_tile_index >= city_map_tiles(city_radius_sq)) {
    return FALSE;
  }

  *city_map_x = CITY_REL2ABS(city_map_index[city_tile_index].dx);
  *city_map_y = CITY_REL2ABS(city_map_index[city_tile_index].dy);

  return TRUE;
}

/**************************************************************************
  Returns the index for the given city tile coordinates taking into account
  the squared city radius.
**************************************************************************/
int city_tile_xy_to_index(int city_map_x, int city_map_y,
                          int city_radius_sq)
{
  fc_assert_ret_val(city_radius_sq >= CITY_MAP_MIN_RADIUS_SQ, 0);
  fc_assert_ret_val(city_radius_sq <= CITY_MAP_MAX_RADIUS_SQ, 0);
  fc_assert_ret_val(is_valid_city_coords(city_radius_sq, city_map_x,
                                         city_map_y), 0);

  return city_map_xy[city_map_x][city_map_y];
}

/**************************************************************************
  Returns the current squared radius of the city.
**************************************************************************/
int city_map_radius_sq_get(const struct city *pcity)
{
  /* a save return value is only the minimal squared radius */
  fc_assert_ret_val(pcity != NULL, CITY_MAP_MIN_RADIUS_SQ);

  return pcity->city_radius_sq;
}

/**************************************************************************
  Returns the current squared radius of the city.
**************************************************************************/
void city_map_radius_sq_set(struct city *pcity, int radius_sq)
{
  fc_assert_ret(radius_sq >= CITY_MAP_MIN_RADIUS_SQ);
  fc_assert_ret(radius_sq <= CITY_MAP_MAX_RADIUS_SQ);

  pcity->city_radius_sq = radius_sq;
}

/**************************************************************************
  Maximum city radius in this ruleset.
**************************************************************************/
int rs_max_city_radius_sq(void)
{
  int max_rad = game.info.init_city_radius_sq
    + effect_cumulative_max(EFT_CITY_RADIUS_SQ, NULL);

  return MIN(max_rad, CITY_MAP_MAX_RADIUS_SQ);
}

/**************************************************************************
  Return the number of tiles for the given city radius. Special case is
  the value -1 for no city tiles.
**************************************************************************/
int city_map_tiles(int city_radius_sq)
{
  if (city_radius_sq == CITY_MAP_CENTER_RADIUS_SQ) {
    /* special case: city center; first tile of the city map */
    return 0;
  }

  fc_assert_ret_val(city_radius_sq >= CITY_MAP_MIN_RADIUS_SQ, -1);
  fc_assert_ret_val(city_radius_sq <= CITY_MAP_MAX_RADIUS_SQ, -1);

  return city_map_numtiles[city_radius_sq];
}

/**************************************************************************
  Return TRUE if the given city coordinate pair is "valid"; that is, if it
  is a part of the citymap and thus is workable by the city.
**************************************************************************/
bool is_valid_city_coords(const int city_radius_sq, const int city_map_x,
                          const int city_map_y)
{
  /* The city's valid positions are in a circle around the city center.
   * Depending on the value for the squared city radius the circle will be:
   *
   *  - rectangular (max radius = 5; max squared radius = 26)
   *
   *        0    1    2    3    4    5    6    7    8    9   10
   *
   *  0                        26   25   26                       -5
   *  1              25   20   17   16   17   20   25             -4
   *  2         25   18   13   10    9   10   13   18   25        -3
   *  3         20   13    8    5    4    5    8   13   20        -2
   *  4    26   17   10    5    2    1    2    5   10   17   26   -1
   *  5    25   16    9    4    1    0    1    4    9   16   25   +0
   *  6    26   17   10    5    2    1    2    5   10   17   26   +1
   *  7         20   13    8    5    4    5    8   13   20        +2
   *  8         25   18   13   10    9   10   13   18   25        +3
   *  9              25   20   17   16   17   20   25             +4
   * 10                        26   25   26                       +5
   *
   *       -5   -4   -3   -2   -1   +0   +1   +2   +3   +4   +5
   *
   * - hexagonal (max radius = 5; max squared radius = 26)
   *
   *        0    1    2    3    4    5    6    7    8    9   10
   *
   *  0                             25   25   25   25   25   25   -5
   *  1                        25   16   16   16   16   16   25   -4
   *  2                   25   16    9    9    9    9   16   25   -3
   *  3              25   16    9    4    4    4    9   16   25   -2
   *  4         25   16    9    4    1    1    4    9   16   25   -1
   *  5    25   16    9    4    1    0    1    4    9   16   25   +0
   *  6    25   16    9    4    1    1    4    9   16   25        +1
   *  7    25   16    9    4    4    4    9   16   25             +2
   *  8    25   16    9    9    9    9   16   25                  +3
   *  9    25   16   16   16   16   16   25                       +4
   * 10    25   25   25   25   25   25                            +5
   *
   *       -5   -4   -3   -2   -1   +0   +1   +2   +3   +4   +5
   *
   * The following tables show the tiles per city radii / squared city radii.
   * '-' indicates no change compared to the previous value
   *
   * radius            |  0 |  1 |    |    |  2 |    |    |    |    |  3
   * radius_sq         |  1 |  2 |  3 |  4 |  5 |  6 |  7 |  8 |  9 | 10
   * ------------------+----+----+----+----+----+----+----+----+----+----
   * tiles rectangular |  5 |  9 |  - | 13 | 21 |  - |  - | 25 | 29 | 37
   * tiles hexagonal   |  7 |  - |  - | 19 |  - |  - |  - |  - | 37 |  -
   *
   * radius            |    |    |    |    |    |    |  4 |    |    |
   * radius_sq         | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20
   * ------------------+----+----+----+----+----+----+----+----+----+----
   * tiles rectangular |  - |  - | 45 |  - |  - | 49 | 57 | 61 |  - | 69
   * tiles hexagonal   |  - |  - |  - |  - |  - | 61 |  - |  - |  - |  -
   *
   * radius            |    |    |    |    |    |  5
   * radius_sq         | 21 | 22 | 23 | 24 | 25 | 26
   * ------------------+----+----+----+----+----+----
   * tiles rectangular |  - |  - |  - |  - | 81 | 89
   * tiles hexagonal   |  - |  - |  - |  - | 91 |  -
   *
   * So radius_sq == 5 (radius == 2) corresponds to the "traditional"
   * used city map.
   */
  int dist = map_vector_to_sq_distance(CITY_ABS2REL(city_map_x),
                                       CITY_ABS2REL(city_map_y));

  return dist <= city_radius_sq;
}

/**************************************************************************
  Finds the city map coordinate for a given map position and a city
  center. Returns whether the map position is inside of the city map.
**************************************************************************/
bool city_tile_to_city_map(int *city_map_x, int *city_map_y,
                           const int city_radius_sq,
                           const struct tile *city_center,
                           const struct tile *map_tile)
{
  map_distance_vector(city_map_x, city_map_y, city_center, map_tile);

  *city_map_x += CITY_MAP_MAX_RADIUS;
  *city_map_y += CITY_MAP_MAX_RADIUS;

  return is_valid_city_coords(city_radius_sq, *city_map_x, *city_map_y);
}

/**************************************************************************
  Finds the city map coordinate for a given map position and a
  city. Returns whether the map position is inside of the city map.
**************************************************************************/
bool city_base_to_city_map(int *city_map_x, int *city_map_y,
                           const struct city *const pcity,
                           const struct tile *map_tile)
{
  return city_tile_to_city_map(city_map_x, city_map_y,
                               city_map_radius_sq_get(pcity), pcity->tile,
                               map_tile);
}

/**************************************************************************
  Finds the map position for a given city map coordinate of a certain
  city. Returns true if the map position found is real.
**************************************************************************/
struct tile *city_map_to_tile(const struct tile *city_center,
                              int city_radius_sq, int city_map_x,
                              int city_map_y)
{
  int tile_x, tile_y;

  fc_assert_ret_val(is_valid_city_coords(city_radius_sq, city_map_x,
                                         city_map_y), NULL);

  index_to_map_pos(&tile_x, &tile_y, tile_index(city_center));
  tile_x += CITY_ABS2REL(city_map_x);
  tile_y += CITY_ABS2REL(city_map_y);

  return map_pos_to_tile(tile_x, tile_y);
}

/**************************************************************************
  Compare two integer values, as required by qsort.
***************************************************************************/
static int cmp(int v1, int v2)
{
  if (v1 == v2) {
    return 0;
  } else if (v1 > v2) {
    return 1;
  } else {
    return -1;
  }
}

/**************************************************************************
  Compare two iter_index values from the city_map_index.

  This function will be passed to qsort().  It should never return zero,
  or the sort order will be left up to qsort and will be undefined.  This
  would mean that server execution would not be reproducable.
***************************************************************************/
int compare_iter_index(const void *a, const void *b)
{
  const struct iter_index *index1 = a, *index2 = b;
  int value;

  value = cmp(index1->dist, index2->dist);
  if (value != 0) {
    return value;
  }

  value = cmp(index1->dx, index2->dx);
  if (value != 0) {
    return value;
  }

  value = cmp(index1->dy, index2->dy);
  fc_assert(0 != value);
  return value;
}

/****************************************************************************
  Return one line (y coordinate) of a city map. *city_map_data is a pointer
  to an array containing the data which should be printed. Its size is
  defined by city_map_tiles(city_radius_sq).
*****************************************************************************/
#define CITYLOG_MAX_VAL 9999 /* maximal value displayed in the citylog */
static char *citylog_map_line(int y, int city_radius_sq, int *city_map_data)
{
  int x, mindex;
  static char citylog[128], tmp[8];

  fc_assert_ret_val(city_map_data != NULL, NULL);

  /* print y coordinates (absolut) */
  fc_snprintf(citylog, sizeof(citylog), "%2d ", y);

  /* print values */
  for (x = 0; x < CITY_MAP_MAX_SIZE; x++) {
    if (is_valid_city_coords(city_radius_sq, x, y)) {
      mindex = city_tile_xy_to_index(x, y, city_radius_sq);
      /* show values between -10000 and +10000 */
      if (city_map_data[mindex] >= -CITYLOG_MAX_VAL
          && city_map_data[mindex] <= CITYLOG_MAX_VAL) {
        fc_snprintf(tmp, sizeof(tmp), "%5d", city_map_data[mindex]);
        sz_strlcat(citylog, tmp);
      } else {
        fc_snprintf(tmp, sizeof(tmp), " ####");
        sz_strlcat(citylog, tmp);
      }
    } else {
      fc_snprintf(tmp, sizeof(tmp), "     ");
      sz_strlcat(citylog, tmp);
    }
  }

  /* print y coordinates (relativ) */
  fc_snprintf(tmp, sizeof(tmp), " %+4d", CITY_ABS2REL(y));
  sz_strlcat(citylog, tmp);

  return citylog;
}
#undef CITYLOG_MAX_VAL

/****************************************************************************
  Display 'map_data' on a city map with the given radius 'radius_sq' for the
  requested log level. The size of 'map_data' is defined by
  city_map_tiles(radius_sq).
*****************************************************************************/
void citylog_map_data(enum log_level level, int radius_sq, int *map_data)
{
  int x, y;
  char line[128], tmp[8];

  if (!log_do_output_for_level(level)) {
    return;
  }

  log_base(level, "(max squared city radius = %d)", CITY_MAP_MAX_RADIUS_SQ);

  /* print x coordinates (absolut) */
  fc_snprintf(line, sizeof(line), "   ");
  for (x = 0; x < CITY_MAP_MAX_SIZE; x++) {
    fc_snprintf(tmp, sizeof(tmp), "%+5d", x);
    sz_strlcat(line, tmp);
  }
  log_base(level, "%s", line);

  for (y = 0; y < CITY_MAP_MAX_SIZE; y++) {
    log_base(level, "%s", citylog_map_line(y, radius_sq, map_data));
  }

  /* print x coordinates (relativ) */
  fc_snprintf(line, sizeof(line), "   ");
  for (x = 0; x < CITY_MAP_MAX_SIZE; x++) {
    fc_snprintf(tmp, sizeof(tmp), "%+5d", CITY_ABS2REL(x));
    sz_strlcat(line, tmp);
  }
  log_base(level, "%s", line);
}

/****************************************************************************
  Display the location of the workers within the city map of pcity.
*****************************************************************************/
void citylog_map_workers(enum log_level level, struct city *pcity)
{
  int *city_map_data = NULL;

  fc_assert_ret(pcity != NULL);

  if (!log_do_output_for_level(level)) {
    return;
  }

  city_map_data = fc_calloc(city_map_tiles(city_map_radius_sq_get(pcity)),
                            sizeof(*city_map_data));

  city_map_iterate(city_map_radius_sq_get(pcity), cindex, x, y) {
    struct tile *ptile = city_map_to_tile(city_tile(pcity),
                                          city_map_radius_sq_get(pcity),
                                          x, y);
    city_map_data[cindex] = (ptile && tile_worked(ptile) == pcity)
                            ? (is_free_worked_index(cindex) ? 2 : 1) : 0;
  } city_map_iterate_end;

  log_base(level, "[%s (%d)] workers map:", city_name_get(pcity), pcity->id);
  citylog_map_data(level, city_map_radius_sq_get(pcity), city_map_data);
  FC_FREE(city_map_data);
}

#ifdef FREECIV_DEBUG
/****************************************************************************
  Log the index of all tiles of the city map.
*****************************************************************************/
static void citylog_map_index(enum log_level level)
{
  int *city_map_data = NULL;

  if (!log_do_output_for_level(level)) {
    return;
  }

  city_map_data = fc_calloc(city_map_tiles(CITY_MAP_MAX_RADIUS_SQ),
                            sizeof(*city_map_data));

  city_map_iterate(CITY_MAP_MAX_RADIUS_SQ, cindex, x, y) {
    city_map_data[cindex] = cindex;
  } city_map_iterate_end;

  log_debug("city map index:");
  citylog_map_data(level, CITY_MAP_MAX_RADIUS_SQ, city_map_data);
  FC_FREE(city_map_data);
}

/****************************************************************************
  Log the radius of all tiles of the city map.
*****************************************************************************/
static void citylog_map_radius_sq(enum log_level level)
{
  int *city_map_data = NULL;

  if (!log_do_output_for_level(level)) {
    return;
  }

  city_map_data = fc_calloc(city_map_tiles(CITY_MAP_MAX_RADIUS_SQ),
                            sizeof(*city_map_data));

  city_map_iterate(CITY_MAP_MAX_RADIUS_SQ, cindex, x, y) {
    city_map_data[cindex] = map_vector_to_sq_distance(CITY_ABS2REL(x),
                                                      CITY_ABS2REL(y));
  } city_map_iterate_end;

  log_debug("city map squared radius:");
  citylog_map_data(level, CITY_MAP_MAX_RADIUS_SQ, city_map_data);
  FC_FREE(city_map_data);
}
#endif /* FREECIV_DEBUG */

/**************************************************************************
  Fill the arrays city_map_index, city_map_xy and city_map_numtiles. This
  may depend on topology and ruleset settings.
***************************************************************************/
void generate_city_map_indices(void)
{
  int i, dx, dy, city_x, city_y, dist, city_count_tiles = 0;
  struct iter_index city_map_index_tmp[CITY_MAP_MAX_SIZE
                                       * CITY_MAP_MAX_SIZE];

  /* initialise map information for each city radii */
  for (i = 0; i <= CITY_MAP_MAX_RADIUS_SQ; i++) {
     city_map_numtiles[i] = 0; /* will be set below */
  }

  /* We don't use city-map iterators in this function because they may
   * rely on the indices that have not yet been generated. Furthermore,
   * we don't know the number of tiles within the city radius, so we need
   * an temporary city_map_index array. Its content will be copied into
   * the real array below. */
  for (dx = -CITY_MAP_MAX_RADIUS; dx <= CITY_MAP_MAX_RADIUS; dx++) {
    for (dy = -CITY_MAP_MAX_RADIUS; dy <= CITY_MAP_MAX_RADIUS; dy++) {
      dist = map_vector_to_sq_distance(dx, dy);

      if (dist <= CITY_MAP_MAX_RADIUS_SQ) {
        city_map_index_tmp[city_count_tiles].dx = dx;
        city_map_index_tmp[city_count_tiles].dy = dy;
        city_map_index_tmp[city_count_tiles].dist = dist;

        for (i = CITY_MAP_MAX_RADIUS_SQ; i >= 0; i--) {
          if (dist <= i) {
            /* increase number of tiles within this squared city radius */
            city_map_numtiles[i]++;
          }
        }

        city_count_tiles++;
      }

      /* Initialise city_map_xy. -1 defines a invalid city map positions. */
      city_map_xy[CITY_REL2ABS(dx)][CITY_REL2ABS(dy)] = -1;
    }
  }

  fc_assert(NULL == city_map_index);
  city_map_index = fc_malloc(city_count_tiles * sizeof(*city_map_index));

  /* copy the index numbers from city_map_index_tmp into city_map_index */
  for (i = 0; i < city_count_tiles; i++) {
    city_map_index[i] = city_map_index_tmp[i];
  }

  qsort(city_map_index, city_count_tiles, sizeof(*city_map_index),
        compare_iter_index);

  /* set the static variable city_map_xy */
  for (i = 0; i < city_count_tiles; i++) {
    city_x = CITY_REL2ABS(city_map_index[i].dx);
    city_y = CITY_REL2ABS(city_map_index[i].dy);
    city_map_xy[city_x][city_y] = i;
  }

#ifdef DEBUG
  citylog_map_radius_sq(LOG_DEBUG);
  citylog_map_index(LOG_DEBUG);

  for (i = CITY_MAP_MIN_RADIUS_SQ; i <= CITY_MAP_MAX_RADIUS_SQ; i++) {
    log_debug("radius_sq = %2d, tiles = %2d", i, city_map_tiles(i));
  }

  for (i = 0; i < city_count_tiles; i++) {
    city_x = CITY_REL2ABS(city_map_index[i].dx);
    city_y = CITY_REL2ABS(city_map_index[i].dy);
    log_debug("[%2d]: (dx,dy) = (%+2d,%+2d), (x,y) = (%2d,%2d), "
              "dist = %2d, check = %2d", i,
              city_map_index[i].dx, city_map_index[i].dy, city_x, city_y,
              city_map_index[i].dist, city_map_xy[city_x][city_y]);
  }
#endif /* DEBUG */

  cm_init_citymap();
}

/****************************************************************************
  Free memory allocated by generate_citymap_index
*****************************************************************************/
void free_city_map_index(void)
{
  FC_FREE(city_map_index);
}

/****************************************************************************
  Return an id string for the output type.  This string can be used
  internally by rulesets and tilesets and should not be changed or
  translated.
*****************************************************************************/
const char *get_output_identifier(Output_type_id output)
{
  fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
  return output_types[output].id;
}

/****************************************************************************
  Return a translated name for the output type.  This name should only be
  used for user display.
*****************************************************************************/
const char *get_output_name(Output_type_id output)
{
  fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
  return _(output_types[output].name);
}

/****************************************************************************
  Return the output type for this index.
****************************************************************************/
struct output_type *get_output_type(Output_type_id output)
{
  fc_assert_ret_val(output >= 0 && output < O_LAST, NULL);
  return &output_types[output];
}

/**************************************************************************
  Find the output type for this output identifier.
**************************************************************************/
Output_type_id output_type_by_identifier(const char *id)
{
  Output_type_id o;

  for (o = 0; o < O_LAST; o++) {
    if (fc_strcasecmp(output_types[o].id, id) == 0) {
      return o;
    }
  }

  return O_LAST;
}

/**************************************************************************
  Return the extended name of the building.
**************************************************************************/
const char *city_improvement_name_translation(const struct city *pcity,
					      struct impr_type *pimprove)
{
  static char buffer[256];
  const char *state = NULL;

  if (is_great_wonder(pimprove)) {
    if (great_wonder_is_available(pimprove)) {
      state = Q_("?wonder:W");
    } else if (great_wonder_is_destroyed(pimprove)) {
      state = Q_("?destroyed:D");
    } else {
      state = Q_("?built:B");
    }
  }
  if (pcity) {
    struct player *pplayer = city_owner(pcity);

    if (improvement_obsolete(pplayer, pimprove, pcity)) {
      state = Q_("?obsolete:O");
    } else if (is_improvement_redundant(pcity, pimprove)) {
      state = Q_("?redundant:*");
    }
  }

  if (state) {
    fc_snprintf(buffer, sizeof(buffer), "%s(%s)",
                improvement_name_translation(pimprove), state); 
    return buffer;
  } else {
    return improvement_name_translation(pimprove);
  }
}

/**************************************************************************
  Return the extended name of the current production.
**************************************************************************/
const char *city_production_name_translation(const struct city *pcity)
{
  static char buffer[256];

  switch (pcity->production.kind) {
  case VUT_IMPROVEMENT:
    return city_improvement_name_translation(pcity, pcity->production.value.building);
  default:
    /* fallthru */
    break;
  };
  return universal_name_translation(&pcity->production, buffer, sizeof(buffer));
}

/**************************************************************************
  Return TRUE when the current production has this flag.
**************************************************************************/
bool city_production_has_flag(const struct city *pcity,
			      enum impr_flag_id flag)
{
  return VUT_IMPROVEMENT == pcity->production.kind
      && improvement_has_flag(pcity->production.value.building, flag);
}

/**************************************************************************
  Return the number of shields it takes to build current city production.
**************************************************************************/
int city_production_build_shield_cost(const struct city *pcity)
{
  return universal_build_shield_cost(&pcity->production);
}

/**************************************************************************
  Return TRUE if the city could use the additional build slots provided by
  the effect City_Build_Slots. Within 'num_units' the total number of units
  the city can build considering the current shield stock is returned.
**************************************************************************/
bool city_production_build_units(const struct city *pcity,
                                 bool add_production, int *num_units)
{
  struct unit_type *utype;
  struct universal target;
  int build_slots = city_build_slots(pcity);
  int shields_left = pcity->shield_stock;
  int unit_shield_cost, i;

  fc_assert_ret_val(num_units != NULL, FALSE);
  (*num_units) = 0;

  if (pcity->production.kind != VUT_UTYPE) {
    /* not a unit as the current production */
    return FALSE;
  }

  utype = pcity->production.value.utype;
  if (utype_pop_value(utype) != 0 || utype_has_flag(utype, UTYF_UNIQUE)) {
    /* unit with population cost or unique unit means that only one unit can
     * be build */
    (*num_units)++;
    return FALSE;
  }

  if (add_production) {
    shields_left += pcity->prod[O_SHIELD];
  }

  unit_shield_cost = utype_build_shield_cost(utype);

  for (i = 0; i < build_slots; i++) {
    if (shields_left < unit_shield_cost) {
      /* not enough shields */
      break;
    }

    (*num_units)++;
    shields_left -= unit_shield_cost;

    if (worklist_length(&pcity->worklist) > i) {
      (void) worklist_peek_ith(&pcity->worklist, &target, i);
      if (target.kind != VUT_UTYPE
          || utype_index(target.value.utype) != utype_index(utype)) {
        /* stop if there is a build target in the worklist not equal to the
         * unit we build */
        break;
      }
    }
  }

  return TRUE;
}

/**************************************************************************
  Return the cost (gold) to buy the current city production.
**************************************************************************/
int city_production_buy_gold_cost(const struct city *pcity)
{
  int build = pcity->shield_stock;

  switch (pcity->production.kind) {
  case VUT_IMPROVEMENT:
    return impr_buy_gold_cost(pcity->production.value.building,
			      build);
  case VUT_UTYPE:
    return utype_buy_gold_cost(pcity->production.value.utype,
			       build);
  default:
    break;
  };
  return FC_INFINITY;
}

/**************************************************************************
 Calculates the turns which are needed to build the requested
 production in the city.  GUI Independent.
**************************************************************************/
int city_production_turns_to_build(const struct city *pcity,
                                   bool include_shield_stock)
{
  return city_turns_to_build(pcity, &pcity->production, include_shield_stock);
}

/**************************************************************************
  Return whether given city can build given building, ignoring whether
  it is obsolete.
**************************************************************************/
bool can_city_build_improvement_direct(const struct city *pcity,
				       struct impr_type *pimprove)
{
  if (!can_player_build_improvement_direct(city_owner(pcity), pimprove)) {
    return FALSE;
  }

  if (city_has_building(pcity, pimprove)) {
    return FALSE;
  }

  return are_reqs_active(city_owner(pcity), NULL, pcity, NULL,
                         pcity->tile, NULL, NULL, NULL, NULL,
			 &(pimprove->reqs), RPT_CERTAIN);
}

/**************************************************************************
  Return whether given city can build given building; returns FALSE if
  the building is obsolete.
**************************************************************************/
bool can_city_build_improvement_now(const struct city *pcity,
				    struct impr_type *pimprove)
{  
  if (!can_city_build_improvement_direct(pcity, pimprove)) {
    return FALSE;
  }
  if (improvement_obsolete(city_owner(pcity), pimprove, pcity)) {
    return FALSE;
  }
  return TRUE;
}

/**************************************************************************
  Return whether player can eventually build given building in the city;
  returns FALSE if improvement can never possibly be built in this city.
**************************************************************************/
bool can_city_build_improvement_later(const struct city *pcity,
				      struct impr_type *pimprove)
{
  /* Can the _player_ ever build this improvement? */
  if (!can_player_build_improvement_later(city_owner(pcity), pimprove)) {
    return FALSE;
  }

  /* Check for requirements that aren't met and that are unchanging (so
   * they can never be met). */
  requirement_vector_iterate(&pimprove->reqs, preq) {
    if (is_req_unchanging(preq)
        && !is_req_active(city_owner(pcity), NULL, pcity, NULL,
                          pcity->tile, NULL, NULL, NULL, NULL,
                          preq, RPT_POSSIBLE)) {
      return FALSE;
    }
  } requirement_vector_iterate_end;
  return TRUE;
}

/**************************************************************************
  Return whether given city can build given unit, ignoring whether unit 
  is obsolete.
**************************************************************************/
bool can_city_build_unit_direct(const struct city *pcity,
				const struct unit_type *punittype)
{
  if (!can_player_build_unit_direct(city_owner(pcity), punittype)) {
    return FALSE;
  }

  /* Check to see if the unit has a building requirement. */
  if (punittype->need_improvement
   && !city_has_building(pcity, punittype->need_improvement)) {
    return FALSE;
  }

  /* You can't build naval units inland. */
  if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
      && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
    return FALSE;
  }
  return TRUE;
}

/**************************************************************************
  Return whether given city can build given unit; returns FALSE if unit is 
  obsolete.
**************************************************************************/
bool can_city_build_unit_now(const struct city *pcity,
			     const struct unit_type *punittype)
{  
  if (!can_city_build_unit_direct(pcity, punittype)) {
    return FALSE;
  }
  while ((punittype = punittype->obsoleted_by) != U_NOT_OBSOLETED) {
    if (can_player_build_unit_direct(city_owner(pcity), punittype)) {
	return FALSE;
    }
  }
  return TRUE;
}

/**************************************************************************
  Returns whether player can eventually build given unit in the city;
  returns FALSE if unit can never possibly be built in this city.
**************************************************************************/
bool can_city_build_unit_later(const struct city *pcity,
			       const struct unit_type *punittype)
{
  /* Can the _player_ ever build this unit? */
  if (!can_player_build_unit_later(city_owner(pcity), punittype)) {
    return FALSE;
  }

  /* Some units can be built only in certain cities -- for instance,
     ships may be built only in cities adjacent to ocean. */
  if (!uclass_has_flag(utype_class(punittype), UCF_BUILD_ANYWHERE)
      && !is_native_near_tile(utype_class(punittype), pcity->tile)) {
    return FALSE;
  }

  return TRUE;
}

/**************************************************************************
  Returns whether city can immediately build given target,
  unit or improvement. This considers obsolete targets still buildable.
**************************************************************************/
bool can_city_build_direct(const struct city *pcity,
                           const struct universal *target)
{
  switch (target->kind) {
  case VUT_UTYPE:
    return can_city_build_unit_direct(pcity, target->value.utype);
  case VUT_IMPROVEMENT:
    return can_city_build_improvement_direct(pcity, target->value.building);
  default:
    break;
  };
  return FALSE;
}

/**************************************************************************
  Returns whether city can immediately build given target,
  unit or improvement. This considers obsolete targets no longer buildable.
**************************************************************************/
bool can_city_build_now(const struct city *pcity,
                        const struct universal *target)
{
  switch (target->kind) {
  case VUT_UTYPE:
    return can_city_build_unit_now(pcity, target->value.utype);
  case VUT_IMPROVEMENT:
    return can_city_build_improvement_now(pcity, target->value.building);
  default:
    break;
  };
  return FALSE;
}

/**************************************************************************
  Returns whether city can ever build given target, unit or improvement. 
**************************************************************************/
bool can_city_build_later(const struct city *pcity,
                          const struct universal *target)
{
  switch (target->kind) {
  case VUT_UTYPE:
    return can_city_build_unit_later(pcity, target->value.utype);
  case VUT_IMPROVEMENT:
    return can_city_build_improvement_later(pcity, target->value.building);
  default:
    break;
  };
  return FALSE;
}

/****************************************************************************
  Returns TRUE iff the given city can use this kind of specialist.
****************************************************************************/
bool city_can_use_specialist(const struct city *pcity,
			     Specialist_type_id type)
{
  return are_reqs_active(city_owner(pcity), NULL, pcity, NULL,
                         NULL, NULL, NULL, NULL, NULL,
			 &specialist_by_number(type)->reqs, RPT_POSSIBLE);
}

/****************************************************************************
  Returns TRUE iff the given city can change what it is building
****************************************************************************/
bool city_can_change_build(const struct city *pcity)
{
  return !pcity->did_buy || pcity->shield_stock <= 0;
}

/**************************************************************************
  Always tile_set_owner(ptile, pplayer) sometime before this!
**************************************************************************/
void city_choose_build_default(struct city *pcity)
{
  if (NULL == city_tile(pcity)) {
    /* When a "dummy" city is created with no tile, then choosing a build 
     * target could fail.  This currently might happen during map editing.
     * FIXME: assumes the first unit is always "valid", so check for
     * obsolete units elsewhere. */
    pcity->production.kind = VUT_UTYPE;
    pcity->production.value.utype = utype_by_number(0);
  } else {
    struct unit_type *u = best_role_unit(pcity, L_FIRSTBUILD);

    if (u) {
      pcity->production.kind = VUT_UTYPE;
      pcity->production.value.utype = u;
    } else {
      bool found = FALSE;

      /* Just pick the first available item. */

      improvement_iterate(pimprove) {
	if (can_city_build_improvement_direct(pcity, pimprove)) {
	  found = TRUE;
	  pcity->production.kind = VUT_IMPROVEMENT;
	  pcity->production.value.building = pimprove;
	  break;
	}
      } improvement_iterate_end;

      if (!found) {
	unit_type_iterate(punittype) {
	  if (can_city_build_unit_direct(pcity, punittype)) {
	    found = TRUE;
	    pcity->production.kind = VUT_UTYPE;
	    pcity->production.value.utype = punittype;
	  }
	} unit_type_iterate_end;
      }

      fc_assert_msg(found, "No production found for city %s!",
                    city_name_get(pcity));
    }
  }
}

#ifndef city_name_get
/**************************************************************************
  Return the name of the city.
**************************************************************************/
const char *city_name_get(const struct city *pcity)
{
  return pcity->name;
}
#endif /* city_name_get */

/**************************************************************************
  Return the owner of the city.
**************************************************************************/
struct player *city_owner(const struct city *pcity)
{
  fc_assert_ret_val(NULL != pcity, NULL);
  fc_assert(NULL != pcity->owner);
  return pcity->owner;
}

#ifndef city_tile
/**************************************************************************
  Return the tile location of the city.
  Not (yet) always used, mostly for debugging.
**************************************************************************/
struct tile *city_tile(const struct city *pcity)
{
  return pcity->tile;
}
#endif


/*****************************************************************************
  Get the city size.
*****************************************************************************/
citizens city_size_get(const struct city *pcity)
{
  fc_assert_ret_val(pcity != NULL, 0);

  return pcity->size;
}

/*****************************************************************************
  Add a (positive or negative) value to the city size. As citizens is an
  unsigned value use int for the parameter 'add'.
*****************************************************************************/
void city_size_add(struct city *pcity, int add)
{
  citizens size = city_size_get(pcity);

  fc_assert_ret(pcity != NULL);
  fc_assert_ret(MAX_CITY_SIZE - size > add);
  fc_assert_ret(size >= -add);

  city_size_set(pcity, city_size_get(pcity) + add);
}

/*****************************************************************************
  Set the city size.
*****************************************************************************/
void city_size_set(struct city *pcity, citizens size)
{
  fc_assert_ret(pcity != NULL);

  /* Set city size. */
  pcity->size = size;
}

/**************************************************************************
 Returns how many thousand citizen live in this city.
**************************************************************************/
int city_population(const struct city *pcity)
{
  /*  Sum_{i=1}^{n} i  ==  n*(n+1)/2  */
  return city_size_get(pcity) * (city_size_get(pcity) + 1) * 5;
}

/**************************************************************************
  Returns the total amount of gold needed to pay for all buildings in the
  city.
**************************************************************************/
int city_total_impr_gold_upkeep(const struct city *pcity)
{
  int gold_needed = 0;

  if (!pcity) {
    return 0;
  }

  city_built_iterate(pcity, pimprove) {
      gold_needed += city_improvement_upkeep(pcity, pimprove);
  } city_built_iterate_end;

  return gold_needed;
}

/***************************************************************************
  Get the total amount of gold needed to pay upkeep costs for all supported
  units of the city. Takes into account EFT_UNIT_UPKEEP_FREE_PER_CITY.
***************************************************************************/
int city_total_unit_gold_upkeep(const struct city *pcity)
{
  int gold_needed = 0;

  if (!pcity || !pcity->units_supported
      || unit_list_size(pcity->units_supported) < 1) {
    return 0;
  }

  unit_list_iterate(pcity->units_supported, punit) {
    gold_needed += punit->upkeep[O_GOLD];
  } unit_list_iterate_end;

  return gold_needed;
}

/**************************************************************************
  Return TRUE iff the city has this building in it.
**************************************************************************/
bool city_has_building(const struct city *pcity,
		       const struct impr_type *pimprove)
{
  if (NULL == pimprove) {
    /* callers should ensure that any external data is tested with 
     * valid_improvement_by_number() */
    return FALSE;
  }
  return (pcity->built[improvement_index(pimprove)].turn > I_NEVER);
}

/**************************************************************************
  Return the upkeep (gold) needed each turn to upkeep the given improvement
  in the given city.
**************************************************************************/
int city_improvement_upkeep(const struct city *pcity,
			    const struct impr_type *b)
{
  int upkeep;

  if (NULL == b)
    return 0;
  if (is_wonder(b))
    return 0;

  upkeep = b->upkeep;
  if (upkeep <= get_building_bonus(pcity, b, EFT_UPKEEP_FREE)) {
    return 0;
  }
  
  return upkeep;
}

/**************************************************************************
  Calculate the output for the tile.
  pcity may be NULL.
  is_celebrating may be speculative.
  otype is the output type (generally O_FOOD, O_TRADE, or O_SHIELD).

  This can be used to calculate the benefits celebration would give.
**************************************************************************/
int city_tile_output(const struct city *pcity, const struct tile *ptile,
		     bool is_celebrating, Output_type_id otype)
{
  int prod;
  struct terrain *pterrain = tile_terrain(ptile);
  const struct output_type *output = &output_types[otype];
  struct player *pplayer = NULL;

  fc_assert_ret_val(otype >= 0 && otype < O_LAST, 0);

  if (T_UNKNOWN == pterrain) {
    /* Special case for the client.  The server doesn't allow unknown tiles
     * to be worked but we don't necessarily know what player is involved. */
    return 0;
  }

  prod = pterrain->output[otype];
  if (tile_resource_is_valid(ptile)) {
    prod += tile_resource(ptile)->output[otype];
  }

  if (pcity != NULL) {
    pplayer = city_owner(pcity);
  }

  switch (otype) {
  case O_SHIELD:
    if (pterrain->mining_shield_incr != 0) {
      prod += pterrain->mining_shield_incr
        * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
                                   ptile, NULL, NULL, NULL, NULL,
                                   EFT_MINING_PCT)
        / 100;
    }
    break;
  case O_FOOD:
    if (pterrain->irrigation_food_incr != 0) {
      prod += pterrain->irrigation_food_incr
        * get_target_bonus_effects(NULL, pplayer, NULL, pcity, NULL,
                                   ptile, NULL, NULL, NULL, NULL,
                                   EFT_IRRIGATION_PCT)
        / 100;
    }
    break;
  case O_TRADE:
  case O_GOLD:
  case O_SCIENCE:
  case O_LUXURY:
  case O_LAST:
    break;
  }

  prod += tile_roads_output_incr(ptile, otype);
  prod += (prod * tile_roads_output_bonus(ptile, otype) / 100);

  prod += get_tile_output_bonus(pcity, ptile, output, EFT_OUTPUT_ADD_TILE);
  if (prod > 0) {
    int penalty_limit = get_tile_output_bonus(pcity, ptile, output,
                                              EFT_OUTPUT_PENALTY_TILE);

    if (is_celebrating) {
      prod += get_tile_output_bonus(pcity, ptile, output,
                                    EFT_OUTPUT_INC_TILE_CELEBRATE);
      penalty_limit = 0; /* no penalty if celebrating */
    }
    prod += get_tile_output_bonus(pcity, ptile, output,
                                  EFT_OUTPUT_INC_TILE);
    prod += (prod 
             * get_tile_output_bonus(pcity, ptile, output,
                                     EFT_OUTPUT_PER_TILE)) 
            / 100;
    if (!is_celebrating && penalty_limit > 0 && prod > penalty_limit) {
      prod--;
    }
  }

  prod -= (prod
           * get_tile_output_bonus(pcity, ptile, output,
                                   EFT_OUTPUT_TILE_PUNISH_PCT))
           / 100;

  if (NULL != pcity && is_city_center(pcity, ptile)) {
    prod = MAX(prod, game.info.min_city_center_output[otype]);
  }

  return prod;
}

/**************************************************************************
  Calculate the production output the given tile is capable of producing
  for the city.  The output type is given by 'otype' (generally O_FOOD,
  O_SHIELD, or O_TRADE).
**************************************************************************/
int city_tile_output_now(const struct city *pcity, const struct tile *ptile,
			 Output_type_id otype)
{
  return city_tile_output(pcity, ptile, city_celebrating(pcity), otype);
}

/****************************************************************************
  Returns TRUE when a tile is available to be worked, or the city itself is
  currently working the tile (and can continue).

  The paramter 'restriction', which is usually client_player(), allow a
  player to handle with its real knownledge to guess it the work of this
  tile is possible.

  This function shouldn't be called directly, but with city_can_work_tile()
  (common/city.[ch]) or client_city_can_work_tile() (client/climap.[ch]).
****************************************************************************/
bool base_city_can_work_tile(const struct player *restriction,
                             const struct city *pcity,
                             const struct tile *ptile)
{
  struct player *powner = city_owner(pcity);
  int city_map_x, city_map_y;

  if (NULL == ptile) {
    return FALSE;
  }

  if (!city_base_to_city_map(&city_map_x, &city_map_y, pcity, ptile)) {
    return FALSE;
  }

  if (NULL != restriction
      && TILE_UNKNOWN == tile_get_known(ptile, restriction)) {
    return FALSE;
  }

  if (NULL != tile_owner(ptile) && tile_owner(ptile) != powner) {
    return FALSE;
  }
  /* TODO: civ3-like option for borders */

  if (NULL != tile_worked(ptile) && tile_worked(ptile) != pcity) {
    return FALSE;
  }

  if (powner == restriction
      && TILE_KNOWN_SEEN != tile_get_known(ptile, powner)) {
    return FALSE;
  }

  if (!is_free_worked(pcity, ptile)
      && NULL != unit_occupies_tile(ptile, powner)) {
    return FALSE;
  }

  if (get_city_tile_output_bonus(pcity, ptile, NULL, EFT_TILE_WORKABLE) <= 0) {
    return FALSE;
  }

  return TRUE;
}

/**************************************************************************
  Returns TRUE when a tile is available to be worked, or the city itself is
  currently working the tile (and can continue).

  See also client_city_can_work_tile() (client/climap.[ch]).
**************************************************************************/
bool city_can_work_tile(const struct city *pcity, const struct tile *ptile)
{
  return base_city_can_work_tile(city_owner(pcity), pcity, ptile);
}

/****************************************************************************
  Returns TRUE if the given unit can build a city at the given map
  coordinates.

  punit is the founding unit. It may be NULL if a city is built out of the
  blue (e.g., through editing).
****************************************************************************/
bool city_can_be_built_here(const struct tile *ptile,
                            const struct unit *punit)
{
  return (CB_OK == city_build_here_test(ptile, punit));
}

/****************************************************************************
  Returns CB_OK if the given unit can build a city at the given map
  coordinates. Else, returns the reason of the failure.

  punit is the founding unit. It may be NULL if a city is built out of the
  blue (e.g., through editing).
****************************************************************************/
enum city_build_result city_build_here_test(const struct tile *ptile,
                                            const struct unit *punit)
{
  int citymindist;

  if (terrain_has_flag(tile_terrain(ptile), TER_NO_CITIES)) {
    /* No cities on this terrain. */
    return CB_BAD_CITY_TERRAIN;
  }

  if (punit && !can_unit_exist_at_tile(punit, ptile)) {
    /* We allow land units to build land cities and sea units to build
     * ocean cities. Air units can build cities anywhere. */
    return CB_BAD_UNIT_TERRAIN;
  }

  if (punit && tile_owner(ptile) && tile_owner(ptile) != unit_owner(punit)) {
    /* Cannot steal borders by settling. This has to be settled by
     * force of arms. */
    return CB_BAD_BORDERS;
  }

  /* citymindist minimum is 1, meaning adjacent is okay */
  citymindist = game.info.citymindist;
  square_iterate(ptile, citymindist - 1, ptile1) {
    if (tile_city(ptile1)) {
      return CB_NO_MIN_DIST;
    }
  } square_iterate_end;

  return CB_OK;
}

/**************************************************************************
  Return TRUE iff this city is its nation's capital.  The capital city is
  special-cased in a number of ways.
**************************************************************************/
bool is_capital(const struct city *pcity)
{
  return (get_city_bonus(pcity, EFT_CAPITAL_CITY) > 0);
}

/**************************************************************************
  Return TRUE iff this city is governmental center.
**************************************************************************/
bool is_gov_center(const struct city *pcity)
{
  return (get_city_bonus(pcity, EFT_GOV_CENTER) > 0);
}

/**************************************************************************
 This can be City Walls, Coastal defense... depending on attacker type.
 If attacker type is not given, just any defense effect will do.
**************************************************************************/
bool city_got_defense_effect(const struct city *pcity,
                             const struct unit_type *attacker)
{
  if (!attacker) {
    /* Any defense building will do */
    return get_city_bonus(pcity, EFT_DEFEND_BONUS) > 0;
  }

  return get_unittype_bonus(city_owner(pcity), pcity->tile, attacker,
                            EFT_DEFEND_BONUS) > 0;
}

/**************************************************************************
  Return TRUE iff the city is happy.  A happy city will start celebrating
  soon.
  A city can only be happy if half or more of the population is happy,
  none of the population is unhappy or angry, and it has sufficient size.
**************************************************************************/
bool city_happy(const struct city *pcity)
{
  return (city_size_get(pcity) >= game.info.celebratesize
	  && pcity->feel[CITIZEN_ANGRY][FEELING_FINAL] == 0
	  && pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL] == 0
	  && pcity->feel[CITIZEN_HAPPY][FEELING_FINAL] >= (city_size_get(pcity) + 1) / 2);
}

/**************************************************************************
  Return TRUE iff the city is unhappy.  An unhappy city will fall
  into disorder soon.
**************************************************************************/
bool city_unhappy(const struct city *pcity)
{
  return (pcity->feel[CITIZEN_HAPPY][FEELING_FINAL]
	< pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL]
	  + 2 * pcity->feel[CITIZEN_ANGRY][FEELING_FINAL]);
}

/**************************************************************************
  Return TRUE if the city was celebrating at the start of the turn,
  and it still has sufficient size to be in rapture.
**************************************************************************/
bool base_city_celebrating(const struct city *pcity)
{
  return (city_size_get(pcity) >= game.info.celebratesize && pcity->was_happy);
}

/**************************************************************************
cities celebrate only after consecutive happy turns
**************************************************************************/
bool city_celebrating(const struct city *pcity)
{
  return base_city_celebrating(pcity) && city_happy(pcity);
}

/**************************************************************************
  Returns whether city is growing by rapture.
**************************************************************************/
bool city_rapture_grow(const struct city *pcity)
{
  /* .rapture is checked instead of city_celebrating() because this
     function is called after .was_happy was updated. */
  return (pcity->rapture > 0 && pcity->surplus[O_FOOD] > 0
	  && (pcity->rapture % game.info.rapturedelay) == 0
          && get_city_bonus(pcity, EFT_RAPTURE_GROW) > 0);
}

/**************************************************************************
  Find city with given id from list.
**************************************************************************/
struct city *city_list_find_number(struct city_list *This, int id)
{
  if (id != 0) {
    city_list_iterate(This, pcity) {
      if (pcity->id == id) {
	return pcity;
      }
    } city_list_iterate_end;
  }

  return NULL;
}

/**************************************************************************
  Find city with given name from list.
**************************************************************************/
struct city *city_list_find_name(struct city_list *This, const char *name)
{
  city_list_iterate(This, pcity) {
    if (fc_strcasecmp(name, pcity->name) == 0) {
      return pcity;
    }
  } city_list_iterate_end;

  return NULL;
}

/**************************************************************************
  Comparison function for qsort for city _pointers_, sorting by city name.
  Args are really (struct city**), to sort an array of pointers.
  (Compare with old_city_name_compare() in game.c, which use city_id's)
**************************************************************************/
int city_name_compare(const void *p1, const void *p2)
{
  return fc_strcasecmp((*(const struct city **) p1)->name,
                       (*(const struct city **) p2)->name);
}

/****************************************************************************
  Returns the city style that has the given (translated) name.
  Returns -1 if none match.
****************************************************************************/
int city_style_by_translated_name(const char *s)
{
  int i;

  for (i = 0; i < game.control.styles_count; i++) {
    if (0 == strcmp(city_style_name_translation(i), s)) {
      return i;
    }
  }

  return -1;
}

/****************************************************************************
  Returns the city style that has the given (untranslated) rule name.
  Returns -1 if none match.
****************************************************************************/
int city_style_by_rule_name(const char *s)
{
  const char *qs = Qn_(s);
  int i;

  for (i = 0; i < game.control.styles_count; i++) {
    if (0 == fc_strcasecmp(city_style_rule_name(i), qs)) {
      return i;
    }
  }

  return -1;
}

/****************************************************************************
  Return the (translated) name of the given city style. 
  You don't have to free the return pointer.
****************************************************************************/
const char *city_style_name_translation(const int style)
{
  return name_translation_get(&city_styles[style].name);
}

/****************************************************************************
  Return the (untranslated) rule name of the city style.
  You don't have to free the return pointer.
****************************************************************************/
const char *city_style_rule_name(const int style)
{
   return rule_name_get(&city_styles[style].name);
}

/**************************************************************************
 Compute and optionally apply the change-production penalty for the given
 production change (to target) in the given city (pcity).
 Always returns the number of shields which would be in the stock if
 the penalty had been applied.

 If we switch the "class" of the target sometime after a city has produced
 (i.e., not on the turn immediately after), then there's a shield loss.
 But only on the first switch that turn.  Also, if ever change back to
 original improvement class of this turn, restore lost production.
**************************************************************************/
int city_change_production_penalty(const struct city *pcity,
                                   const struct universal *target)
{
  int shield_stock_after_adjustment;
  enum production_class_type orig_class;
  enum production_class_type new_class;
  int unpenalized_shields = 0, penalized_shields = 0;

  switch (pcity->changed_from.kind) {
  case VUT_IMPROVEMENT:
    if (is_wonder(pcity->changed_from.value.building)) {
      orig_class = PCT_WONDER;
    } else {
      orig_class = PCT_NORMAL_IMPROVEMENT;
    }
    break;
  case VUT_UTYPE:
    orig_class = PCT_UNIT;
    break;
  default:
    orig_class = PCT_LAST;
    break;
  };

  switch (target->kind) {
  case VUT_IMPROVEMENT:
    if (is_wonder(target->value.building)) {
      new_class = PCT_WONDER;
    } else {
      new_class = PCT_NORMAL_IMPROVEMENT;
    }
    break;
  case VUT_UTYPE:
    new_class = PCT_UNIT;
    break;
  default:
    new_class = PCT_LAST;
    break;
  };

  /* Changing production is penalized under certain circumstances. */
  if (orig_class == new_class
      || orig_class == PCT_LAST) {
    /* There's never a penalty for building something of the same class. */
    unpenalized_shields = pcity->before_change_shields;
  } else if (city_built_last_turn(pcity)) {
    /* Surplus shields from the previous production won't be penalized if
     * you change production on the very next turn.  But you can only use
     * up to the city's surplus amount of shields in this way. */
    unpenalized_shields = MIN(pcity->last_turns_shield_surplus,
                              pcity->before_change_shields);
    penalized_shields = pcity->before_change_shields - unpenalized_shields;
  } else {
    /* Penalize 50% of the production. */
    penalized_shields = pcity->before_change_shields;
  }

  /* Do not put penalty on these. It shouldn't matter whether you disband unit
     before or after changing production...*/
  unpenalized_shields += pcity->disbanded_shields;

  /* Caravan shields are penalized (just as if you disbanded the caravan)
   * if you're not building a wonder. */
  if (new_class == PCT_WONDER) {
    unpenalized_shields += pcity->caravan_shields;
  } else {
    penalized_shields += pcity->caravan_shields;
  }

  shield_stock_after_adjustment =
    unpenalized_shields + penalized_shields / 2;

  return shield_stock_after_adjustment;
}

/**************************************************************************
 Calculates the turns which are needed to build the requested
 improvement in the city. GUI Independent.
**************************************************************************/
int city_turns_to_build(const struct city *pcity,
                        const struct universal *target,
                        bool include_shield_stock)
{
  int city_shield_surplus = pcity->surplus[O_SHIELD];
  int city_shield_stock = include_shield_stock ?
      city_change_production_penalty(pcity, target) : 0;
  int cost = universal_build_shield_cost(target);

  if (target->kind == VUT_IMPROVEMENT
      && is_great_wonder(target->value.building)
      && !great_wonder_is_available(target->value.building)) {
    return FC_INFINITY;
  }

  if (include_shield_stock && (city_shield_stock >= cost)) {
    return 1;
  } else if (city_shield_surplus > 0) {
    return (cost - city_shield_stock - 1) / city_shield_surplus + 1;
  } else {
    return FC_INFINITY;
  }
}

/**************************************************************************
 Calculates the turns which are needed for the city to grow.  A value
 of FC_INFINITY means the city will never grow.  A value of 0 means
 city growth is blocked.  A negative value of -x means the city will
 shrink in x turns.  A positive value of x means the city will grow in
 x turns.
**************************************************************************/
int city_turns_to_grow(const struct city *pcity)
{
  if (pcity->surplus[O_FOOD] > 0) {
    return (city_granary_size(city_size_get(pcity)) - pcity->food_stock +
	    pcity->surplus[O_FOOD] - 1) / pcity->surplus[O_FOOD];
  } else if (pcity->surplus[O_FOOD] < 0) {
    /* turns before famine loss */
    return -1 + (pcity->food_stock / pcity->surplus[O_FOOD]);
  } else {
    return FC_INFINITY;
  }
}

/****************************************************************************
  Return TRUE iff the city can grow to the given size.
****************************************************************************/
bool city_can_grow_to(const struct city *pcity, int pop_size)
{
  return (get_city_bonus(pcity, EFT_SIZE_UNLIMIT) > 0
	  || pop_size <= get_city_bonus(pcity, EFT_SIZE_ADJ));
}

/**************************************************************************
 is there an enemy city on this tile?
**************************************************************************/
struct city *is_enemy_city_tile(const struct tile *ptile,
				const struct player *pplayer)
{
  struct city *pcity = tile_city(ptile);

  if (pcity && pplayers_at_war(pplayer, city_owner(pcity)))
    return pcity;
  else
    return NULL;
}

/**************************************************************************
 is there an friendly city on this tile?
**************************************************************************/
struct city *is_allied_city_tile(const struct tile *ptile,
				 const struct player *pplayer)
{
  struct city *pcity = tile_city(ptile);

  if (pcity && pplayers_allied(pplayer, city_owner(pcity)))
    return pcity;
  else
    return NULL;
}

/**************************************************************************
 is there an enemy city on this tile?
**************************************************************************/
struct city *is_non_attack_city_tile(const struct tile *ptile,
				     const struct player *pplayer)
{
  struct city *pcity = tile_city(ptile);

  if (pcity && pplayers_non_attack(pplayer, city_owner(pcity)))
    return pcity;
  else
    return NULL;
}

/**************************************************************************
 is there an non_allied city on this tile?
**************************************************************************/
struct city *is_non_allied_city_tile(const struct tile *ptile,
				     const struct player *pplayer)
{
  struct city *pcity = tile_city(ptile);

  if (pcity && !pplayers_allied(pplayer, city_owner(pcity)))
    return pcity;
  else
    return NULL;
}

/**************************************************************************
  Return TRUE if there is a friendly city near to this unit (within 3
  steps).
**************************************************************************/
bool is_unit_near_a_friendly_city(const struct unit *punit)
{
  return is_friendly_city_near(unit_owner(punit), unit_tile(punit));
}

/**************************************************************************
  Return TRUE if there is a friendly city near to this tile (within 3
  steps).
**************************************************************************/
bool is_friendly_city_near(const struct player *owner,
                           const struct tile *ptile)
{
  square_iterate(ptile, 3, ptile1) {
    struct city *pcity = tile_city(ptile1);
    if (pcity && pplayers_allied(owner, city_owner(pcity))) {
      return TRUE;
    }
  } square_iterate_end;

  return FALSE;
}

/**************************************************************************
  Return true iff a city exists within a city radius of the given 
  location. may_be_on_center determines if a city at x,y counts.
**************************************************************************/
bool city_exists_within_max_city_map(const struct tile *ptile,
                                     bool may_be_on_center)
{
  city_tile_iterate(CITY_MAP_MAX_RADIUS_SQ, ptile, ptile1) {
    if (may_be_on_center || !same_pos(ptile, ptile1)) {
      if (tile_city(ptile1)) {
        return TRUE;
      }
    }
  } city_tile_iterate_end;

  return FALSE;
}

/****************************************************************************
  Generalized formula used to calculate granary size.

  The AI may not deal well with non-default settings.  See food_weighting().
****************************************************************************/
int city_granary_size(int city_size)
{
  int food_inis = game.info.granary_num_inis;
  int food_inc = game.info.granary_food_inc;
  int base_value;

  /* If the city has no citizens, there is no granary. */
  if (city_size == 0) {
    return 0;
  }

  /* Granary sizes for the first food_inis citizens are given directly.
   * After that we increase the granary size by food_inc per citizen. */
  if (city_size > food_inis) {
    base_value = game.info.granary_food_ini[food_inis - 1];
    base_value += food_inc * (city_size - food_inis);
  } else {
    base_value = game.info.granary_food_ini[city_size - 1];
  }

  return MAX(base_value * game.info.foodbox / 100, 1);
}

/****************************************************************************
  Give base happiness in any city owned by pplayer.
  A positive number is a number of content citizens. A negative number is
  a number of angry citizens (a city never starts with both).
****************************************************************************/
static int player_base_citizen_happiness(const struct player *pplayer)
{
  int cities = city_list_size(pplayer->cities);
  int content = get_player_bonus(pplayer, EFT_CITY_UNHAPPY_SIZE);
  int basis = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_BASE);
  int step = get_player_bonus(pplayer, EFT_EMPIRE_SIZE_STEP);

  if (basis + step <= 0) {
    /* Value of zero means effect is inactive */
    return content;
  }

  if (cities > basis) {
    content--;
    if (step != 0) {
      /* the first penalty is at (basis + 1) cities;
         the next is at (basis + step + 1), _not_ (basis + step) */
      content -= (cities - basis - 1) / step;
    }
  }
  return content;
}

/****************************************************************************
  Give base number of content citizens in any city owned by pplayer.
****************************************************************************/
citizens player_content_citizens(const struct player *pplayer)
{
  int content = player_base_citizen_happiness(pplayer);

  return CLIP(0, content, MAX_CITY_SIZE);
}

/****************************************************************************
  Give base number of angry citizens in any city owned by pplayer.
****************************************************************************/
citizens player_angry_citizens(const struct player *pplayer)
{
  if (!game.info.angrycitizen) {
    return 0;
  } else {
    /* Create angry citizens only if we have a negative number of possible
     * content citizens. This can happen when empires grow really big. */
    int content = player_base_citizen_happiness(pplayer);

    return CLIP(0, -content, MAX_CITY_SIZE);
  }
}

/**************************************************************************
 Return the factor (in %) by which the city's output should be multiplied.
**************************************************************************/
int get_final_city_output_bonus(const struct city *pcity, Output_type_id otype)
{
  struct output_type *output = &output_types[otype];
  int bonus1 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
						EFT_OUTPUT_BONUS);
  int bonus2 = 100 + get_city_tile_output_bonus(pcity, NULL, output,
						EFT_OUTPUT_BONUS_2);

  return MAX(bonus1 * bonus2 / 100, 0);
}

/**************************************************************************
  Return the amount of gold generated by buildings under "tithe" attribute
  governments.
**************************************************************************/
int get_city_tithes_bonus(const struct city *pcity)
{
  int tithes_bonus = 0;

  if (get_city_bonus(pcity, EFT_HAPPINESS_TO_GOLD) <= 0) {
    return 0;
  }

  tithes_bonus += get_city_bonus(pcity, EFT_MAKE_CONTENT);
  tithes_bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);

  return tithes_bonus;
}

/**************************************************************************
  Add the incomes of a city according to the taxrates (ignore # of 
  specialists). trade should be in output[O_TRADE].
**************************************************************************/
void add_tax_income(const struct player *pplayer, int trade, int *output)
{
  const int SCIENCE = 0, TAX = 1, LUXURY = 2;
  int rates[3], result[3];

  if (game.info.changable_tax) {
    rates[SCIENCE] = pplayer->economic.science;
    rates[LUXURY] = pplayer->economic.luxury;
    rates[TAX] = 100 - rates[SCIENCE] - rates[LUXURY];
  } else {
    rates[SCIENCE] = game.info.forced_science;
    rates[LUXURY] = game.info.forced_luxury;
    rates[TAX] = game.info.forced_gold;
  }
  
  /* ANARCHY */
  if (government_of_player(pplayer) == game.government_during_revolution) {
    rates[SCIENCE] = 0;
    rates[LUXURY] = 100;
    rates[TAX] = 0;
  }

  distribute(trade, 3, rates, result);

  output[O_SCIENCE] += result[SCIENCE];
  output[O_GOLD] += result[TAX];
  output[O_LUXURY] += result[LUXURY];
}

/**************************************************************************
  Return TRUE if the city built something last turn (meaning production
  was completed between last turn and this).
**************************************************************************/
bool city_built_last_turn(const struct city *pcity)
{
  return pcity->turn_last_built + 1 >= game.info.turn;
}

/****************************************************************************
  Calculate output (food, trade and shields) generated by the worked tiles
  of a city.  This will completely overwrite the output[] array.

  'workers_map' is an boolean array which defines the placement of the
  workers within the city map. It uses the tile index and its size is
  defined by city_map_tiles_from_city(_pcity). See also cm_state_init().
****************************************************************************/
static inline void get_worked_tile_output(const struct city *pcity,
                                          int *output, bool *workers_map)
{
  bool is_worked;
#ifdef CITY_DEBUGGING
  bool is_celebrating = base_city_celebrating(pcity);
#endif
  struct tile *pcenter = city_tile(pcity);

  memset(output, 0, O_LAST * sizeof(*output));

  city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
                          city_tile_index) {
    if (workers_map == NULL) {
      struct city *pwork = tile_worked(ptile);

      is_worked = (NULL != pwork && pwork == pcity);
    } else {
      is_worked = workers_map[city_tile_index];
    }

    if (is_worked) {
      output_type_iterate(o) {
#ifdef CITY_DEBUGGING
        /* This assertion never fails, but it's so slow that we disable
         * it by default. */
        fc_assert(city_tile_cache_get_output(pcity, city_tile_index, o)
                  == city_tile_output(pcity, ptile, is_celebrating, o));
#endif
        output[o] += city_tile_cache_get_output(pcity, city_tile_index, o);
      } output_type_iterate_end;
    }
  } city_tile_iterate_index_end;
}

/****************************************************************************
  Calculate output (gold, science, and luxury) generated by the specialists
  of a city.  The output[] array is not cleared but is just added to.
****************************************************************************/
void add_specialist_output(const struct city *pcity, int *output)
{
  specialist_type_iterate(sp) {
    int count = pcity->specialists[sp];

    output_type_iterate(stat_index) {
      int amount = get_specialist_output(pcity, sp, stat_index);

      output[stat_index] += count * amount;
    } output_type_iterate_end;
  } specialist_type_iterate_end;
}

/****************************************************************************
  This function sets all the values in the pcity->bonus[] array.
  Called near the beginning of city_refresh_from_main_map().

  It doesn't depend on anything else in the refresh and doesn't change
  as workers are moved around, but does change when buildings are built,
  etc.
****************************************************************************/
static inline void set_city_bonuses(struct city *pcity)
{
  output_type_iterate(o) {
    pcity->bonus[o] = get_final_city_output_bonus(pcity, o);
  } output_type_iterate_end;
}

/****************************************************************************
  This function sets the cache for the tile outputs, the pcity->tile_cache[]
  array. It is called near the beginning of city_refresh_from_main_map().

  It doesn't depend on anything else in the refresh and doesn't change
  as workers are moved around, but does change when buildings are built,
  etc.

  TODO: use the cached values elsewhere in the code!
****************************************************************************/
static inline void city_tile_cache_update(struct city *pcity)
{
  bool is_celebrating = base_city_celebrating(pcity);
  int radius_sq = city_map_radius_sq_get(pcity);

  /* initialize tile_cache if needed */
  if (pcity->tile_cache == NULL || pcity->tile_cache_radius_sq == -1
      || pcity->tile_cache_radius_sq != radius_sq) {
    pcity->tile_cache = fc_realloc(pcity->tile_cache,
                                   city_map_tiles(radius_sq)
                                   * sizeof(*(pcity->tile_cache)));
    pcity->tile_cache_radius_sq = radius_sq;
  }

  /* Any unreal tiles are skipped - these values should have been memset
   * to 0 when the city was created. */
  city_tile_iterate_index(radius_sq, pcity->tile, ptile, city_tile_index) {
    output_type_iterate(o) {
      (pcity->tile_cache[city_tile_index]).output[o]
        = city_tile_output(pcity, ptile, is_celebrating, o);
    } output_type_iterate_end;
  } city_tile_iterate_index_end;
}

/****************************************************************************
  This function returns the output of 'o' for the city tile 'city_tile_index'
  of 'pcity'.
****************************************************************************/
static inline int city_tile_cache_get_output(const struct city *pcity,
                                             int city_tile_index,
                                             enum output_type_id o)
{
  fc_assert_ret_val(pcity->tile_cache_radius_sq
                    == city_map_radius_sq_get(pcity), 0);
  fc_assert_ret_val(city_tile_index < city_map_tiles_from_city(pcity), 0);

  return (pcity->tile_cache[city_tile_index]).output[o];
}

/**************************************************************************
  Set the final surplus[] array from the prod[] and usage[] values.
**************************************************************************/
static void set_surpluses(struct city *pcity)
{
  output_type_iterate(o) {
    pcity->surplus[o] = pcity->prod[o] - pcity->usage[o];
  } output_type_iterate_end;
}

/**************************************************************************
  Copy the happyness array in the city to index i from index i-1.
**************************************************************************/
static void happy_copy(struct city *pcity, enum citizen_feeling i)
{
  int c = 0;

  for (; c < CITIZEN_LAST; c++) {
    pcity->feel[c][i] = pcity->feel[c][i - 1];
  }
}

/**************************************************************************
  Create content, unhappy and angry citizens.
**************************************************************************/
static void citizen_base_mood(struct city *pcity)
{
  struct player *pplayer = city_owner(pcity);
  citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_BASE];
  citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_BASE];
  citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_BASE];
  citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_BASE];
  citizens size = city_size_get(pcity);
  citizens spes = city_specialists(pcity);

  /* This is the number of citizens that may start out content, depending
   * on empire size and game's city unhappysize. This may be bigger than
   * the size of the city, since this is a potential. */
  citizens base_content = player_content_citizens(pplayer);
  /* Similarly, this is the potential number of angry citizens. */
  citizens base_angry = player_angry_citizens(pplayer);

  /* Create content citizens. Take specialists from their ranks. */
  *content = MAX(0, MIN(size, base_content) - spes);

  /* Create angry citizens. Specialists never become angry. */
  fc_assert_action(base_content == 0 || base_angry == 0, *content = 0);
  *angry = MIN(base_angry, size - spes);

  /* Create unhappy citizens. In the beginning, all who are not content,
   * specialists or angry are unhappy. This is changed by luxuries and 
   * buildings later. */
  *unhappy = (size - spes - *content - *angry);

  /* No one is born happy. */
  *happy = 0;
}

/**************************************************************************
  Make people happy: 
   * angry citizen are eliminated first
   * then content are made happy, then unhappy content, etc.
   * each conversions costs 2 or 4 luxuries.
**************************************************************************/
static inline void citizen_luxury_happy(struct city *pcity, int *luxuries)
{
  citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_LUXURY];
  citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_LUXURY];
  citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_LUXURY];
  citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_LUXURY];

  while (*luxuries >= game.info.happy_cost && *angry > 0) {
    /* Upgrade angry to unhappy: costs HAPPY_COST each. */
    (*angry)--;
    (*unhappy)++;
    *luxuries -= game.info.happy_cost;
  }
  while (*luxuries >= game.info.happy_cost && *content > 0) {
    /* Upgrade content to happy: costs HAPPY_COST each. */
    (*content)--;
    (*happy)++;
    *luxuries -= game.info.happy_cost;
  }
  while (*luxuries >= 2 * game.info.happy_cost && *unhappy > 0) {
    /* Upgrade unhappy to happy.  Note this is a 2-level upgrade with
     * double the cost. */
    (*unhappy)--;
    (*happy)++;
    *luxuries -= 2 * game.info.happy_cost;
  }
  if (*luxuries >= game.info.happy_cost && *unhappy > 0) {
    /* Upgrade unhappy to content: costs HAPPY_COST each. */
    (*unhappy)--;
    (*content)++;
    *luxuries -= game.info.happy_cost;
  }
}

/**************************************************************************
  Make citizens happy due to luxury.
**************************************************************************/
static inline void citizen_happy_luxury(struct city *pcity)
{
  int x = pcity->prod[O_LUXURY];

  citizen_luxury_happy(pcity, &x);
}

/**************************************************************************
  Make citizens content due to city improvements.
**************************************************************************/
static inline void citizen_content_buildings(struct city *pcity)
{
  citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_EFFECT];
  citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_EFFECT];
  citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_EFFECT];
  int faces = get_city_bonus(pcity, EFT_MAKE_CONTENT);

  /* make people content (but not happy):
     get rid of angry first, then make unhappy content. */
  while (faces > 0 && *angry > 0) {
    (*angry)--;
    (*unhappy)++;
    faces--;
  }
  while (faces > 0 && *unhappy > 0) {
    (*unhappy)--;
    (*content)++;
    faces--;
  }
}

/**************************************************************************
  Apply effects of citizen nationality to happiness
**************************************************************************/
static inline void citizen_happiness_nationality(struct city *pcity)
{
  citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_NATIONALITY];
  citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_NATIONALITY];
  citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_NATIONALITY];

  if (game.info.citizen_nationality) {
    int pct = get_city_bonus(pcity, EFT_ENEMY_CITIZEN_UNHAPPY_PCT);

    if (pct > 0) {
      int enemies = 0;
      int unhappy_inc;
      struct player *owner = city_owner(pcity);

      citizens_foreign_iterate(pcity, pslot, nationality) {
        if (pplayers_at_war(owner, player_slot_get_player(pslot))) {
          enemies += nationality;
        }
      } citizens_foreign_iterate_end;

      unhappy_inc = enemies * pct / 100;

      /* First make content => unhappy, then happy => unhappy,
       * then happy => content. No-one becomes angry. */
      while (unhappy_inc > 0 && *content > 0) {
        (*content)--;
        (*unhappy)++;
        unhappy_inc--;
      }
      while (unhappy_inc > 1 && *happy > 0) {
        (*happy)--;
        (*unhappy)++;
        unhappy_inc -= 2;
      }
      while (unhappy_inc > 0 && *happy > 0) {
        (*happy)--;
        (*content)++;
        unhappy_inc--;
      }
    }
  }
}

/**************************************************************************
  Make citizens happy/unhappy due to units.

  This function requires that pcity->martial_law and
  pcity->unit_happy_cost have already been set in city_support().
**************************************************************************/
static inline void citizen_happy_units(struct city *pcity)
{
  citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_MARTIAL];
  citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_MARTIAL];
  citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_MARTIAL];
  citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_MARTIAL];
  citizens  amt = pcity->martial_law;

  /* Pacify discontent citizens through martial law.  First convert
   * angry => unhappy, then unhappy => content. */
  while (amt > 0 && *angry > 0) {
    (*angry)--;
    (*unhappy)++;
    amt--;
  }
  while (amt > 0 && *unhappy > 0) {
    (*unhappy)--;
    (*content)++;
    amt--;
  }

  /* Now make citizens unhappier because of military units away from home.
   * First make content => unhappy, then happy => unhappy,
   * then happy => content. */
  amt = pcity->unit_happy_upkeep;
  while (amt > 0 && *content > 0) {
    (*content)--;
    (*unhappy)++;
    amt--;
  }
  while (amt > 1 && *happy > 0) {
    (*happy)--;
    (*unhappy)++;
    amt -= 2;
  }
  while (amt > 0 && *happy > 0) {
    (*happy)--;
    (*content)++;
    amt--;
  }
  /* Any remaining unhappiness is lost since angry citizens aren't created
   * here. */
  /* FIXME: Why not? - Per */
}

/**************************************************************************
  Make citizens happy due to wonders.
**************************************************************************/
static inline void citizen_happy_wonders(struct city *pcity)
{
  citizens *happy = &pcity->feel[CITIZEN_HAPPY][FEELING_FINAL];
  citizens *content = &pcity->feel[CITIZEN_CONTENT][FEELING_FINAL];
  citizens *unhappy = &pcity->feel[CITIZEN_UNHAPPY][FEELING_FINAL];
  citizens *angry = &pcity->feel[CITIZEN_ANGRY][FEELING_FINAL];
  int bonus = get_city_bonus(pcity, EFT_MAKE_HAPPY);

  /* First create happy citizens from content, then from unhappy
   * citizens; we cannot help angry citizens here. */
  while (bonus > 0 && *content > 0) {
    (*content)--;
    (*happy)++;
    bonus--;
  }
  while (bonus > 1 && *unhappy > 0) {
    (*unhappy)--;
    (*happy)++;
    bonus -= 2;
  }
  /* The rest falls through and lets unhappy people become content. */

  if (get_city_bonus(pcity, EFT_NO_UNHAPPY) > 0) {
    *content += *unhappy + *angry;
    *unhappy = 0;
    *angry = 0;
    return;
  }

  bonus += get_city_bonus(pcity, EFT_FORCE_CONTENT);

  /* get rid of angry first, then make unhappy content */
  while (bonus > 0 && *angry > 0) {
    (*angry)--;
    (*unhappy)++;
    bonus--;
  }
  while (bonus > 0 && *unhappy > 0) {
    (*unhappy)--;
    (*content)++;
    bonus--;
  }
}

/**************************************************************************
  Set food, tax, science and shields production to zero if city is in
  disorder.
**************************************************************************/
static inline void unhappy_city_check(struct city *pcity)
{
  if (city_unhappy(pcity)) {
    output_type_iterate(o) {
      switch (output_types[o].unhappy_penalty) {
      case UNHAPPY_PENALTY_NONE:
	pcity->unhappy_penalty[o] = 0;
	break;
      case UNHAPPY_PENALTY_SURPLUS:
	pcity->unhappy_penalty[o] = MAX(pcity->prod[o] - pcity->usage[o], 0);
	break;
      case UNHAPPY_PENALTY_ALL_PRODUCTION:
	pcity->unhappy_penalty[o] = pcity->prod[o];
	break;
      }

      pcity->prod[o] -= pcity->unhappy_penalty[o];
    } output_type_iterate_end;
  } else {
    memset(pcity->unhappy_penalty, 0,
 	   O_LAST * sizeof(*pcity->unhappy_penalty));
  }
}

/**************************************************************************
  Calculate the pollution from production and population in the city.
**************************************************************************/
int city_pollution_types(const struct city *pcity, int shield_total,
			 int *pollu_prod, int *pollu_pop, int *pollu_mod)
{
  int prod, pop, mod;

  /* Add one one pollution per shield, multipled by the bonus. */
  prod = 100 + get_city_bonus(pcity, EFT_POLLU_PROD_PCT);
  prod = shield_total * MAX(prod, 0) / 100;

  /* Add one pollution per citizen for baseline combined bonus (100%). */
  pop = (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT))
      * (100 + get_city_bonus(pcity, EFT_POLLU_POP_PCT_2))
      / 100;
  pop = (city_size_get(pcity) * MAX(pop, 0)) / 100;

  /* Then there is base pollution (usually a negative number). */
  mod = game.info.base_pollution;

  if (pollu_prod) {
    *pollu_prod = prod;
  }
  if (pollu_pop) {
    *pollu_pop = pop;
  }
  if (pollu_mod) {
    *pollu_mod = mod;
  }
  return MAX(prod + pop + mod, 0);
}

/**************************************************************************
  Calculate pollution for the city.  The shield_total must be passed in
  (most callers will want to pass pcity->shield_prod).
**************************************************************************/
int city_pollution(const struct city *pcity, int shield_total)
{
  return city_pollution_types(pcity, shield_total, NULL, NULL, NULL);
}

/**************************************************************************
  Gets whether cities that pcity trades with had the plague. If so, it 
  returns the health penalty in tenth of percent which depends on the size
  of both cities. The health penalty is given as the product of the ruleset
  option 'game.info.illness_trade_infection' (in percent) and the square
  root of the product of the size of both cities.
 *************************************************************************/
static int get_trade_illness(const struct city *pcity)
{
  float illness_trade = 0.0;

  trade_routes_iterate(pcity, trade_city) {
    if (trade_city->turn_plague != -1
        && game.info.turn - trade_city->turn_plague < 5) {
      illness_trade += (float)game.info.illness_trade_infection
                       * sqrt(1.0 * city_size_get(pcity)
                              * city_size_get(trade_city)) / 100.0;
    }
  } trade_routes_iterate_end;

  return (int)illness_trade;
}

/**************************************************************************
  Get any effects regarding health from the buildings of the city. The
  effect defines the reduction of the possibility of an illness in percent.
**************************************************************************/
static int get_city_health(const struct city *pcity)
{
  return get_city_bonus(pcity, EFT_HEALTH_PCT);
}

/**************************************************************************
  Calculate city's illness in tenth of percent:

  base illness        (the maximum value for illness in percent is given by
                       'game.info.illness_base_factor')
  + trade illness     (see get_trade_illness())
  + pollution illness (the pollution in the city times
                       'game.info.illness_pollution_factor')

  The illness is reduced by the percentage given by the health effect.
  Illness cannot exceed 999 (= 99.9%), or be less then 0
 *************************************************************************/
int city_illness_calc(const struct city *pcity, int *ill_base,
                      int *ill_size, int *ill_trade, int *ill_pollution)
{
  int illness_size = 0, illness_trade = 0, illness_pollution = 0;
  int illness_base, illness_percent;

  if (game.info.illness_on
      && city_size_get(pcity) > game.info.illness_min_size) {
    /* offset the city size by game.info.illness_min_size */
    int use_size = city_size_get(pcity) - game.info.illness_min_size;

    illness_size = (int)((1.0 - exp(- (float)use_size / 10.0))
                         * 10.0 * game.info.illness_base_factor);
    if (is_server()) {
      /* on the server we recalculate the illness due to trade as we have
       * all informations */
      illness_trade = get_trade_illness(pcity);
    } else {
      /* on the client we have to rely on the value saved within the city
       * struct */
      illness_trade = pcity->illness_trade;
    }

    illness_pollution = pcity->pollution
                        * game.info.illness_pollution_factor / 100;
  }

  illness_base = illness_size + illness_trade + illness_pollution;
  illness_percent = 100 - get_city_health(pcity);

  /* returning other data */
  if (ill_size) {
    *ill_size = illness_size;
  }

  if (ill_trade) {
    *ill_trade = illness_trade;
  }

  if (ill_pollution) {
    *ill_pollution = illness_pollution;
  }

  if (ill_base) {
    *ill_base = illness_base;
  }

  return CLIP(0, illness_base * illness_percent / 100 , 999);
}

/****************************************************************************
  Returns whether city had a plague outbreak this turn.
****************************************************************************/
bool city_had_recent_plague(const struct city *pcity)
{
  /* Correctly handles special case turn_plague == -1 (never) */
  return (pcity->turn_plague == game.info.turn);
}

/****************************************************************************
  The maximum number of units a city can build per turn.
****************************************************************************/
int city_build_slots(const struct city *pcity)
{
  return get_city_bonus(pcity, EFT_CITY_BUILD_SLOTS);
}

/****************************************************************************
  A city's maximum airlift capacity.
  (Note, this still returns a finite number even if airliftingstyle allows
  unlimited airlifts)
****************************************************************************/
int city_airlift_max(const struct city *pcity)
{
  return get_city_bonus(pcity, EFT_AIRLIFT);
}

/**************************************************************************
   Set food, trade and shields production in a city.

   This initializes the prod[] and waste[] arrays.  It assumes that
   the bonus[] and citizen_base[] arrays are alread built.
**************************************************************************/
inline void set_city_production(struct city *pcity)
{
  int i;

  /* Calculate city production!
   *
   * This is a rather complicated process if we allow rules to become
   * more generalized.  We can assume that there are no recursive dependency
   * loops, but there are some dependencies that do not follow strict
   * ordering.  For instance corruption must be calculated before 
   * trade taxes can be counted up, which must occur before the science bonus
   * is added on.  But the calculation of corruption must include the
   * trade bonus.  To do this without excessive special casing means that in
   * this case the bonuses are multiplied on twice (but only saved the second
   * time).
   */

  output_type_iterate(o) {
    pcity->prod[o] = pcity->citizen_base[o];
  } output_type_iterate_end;

  /* Add on special extra incomes: trade routes and tithes. */
  for (i = 0; i < MAX_TRADE_ROUTES; i++) {
    struct city *tcity = game_city_by_number(pcity->trade[i]);

    if (tcity != NULL) {
      bool can_trade = can_cities_trade(pcity, tcity);

      if (!can_trade) {
        enum trade_route_type type = cities_trade_route_type(pcity, tcity);
        struct trade_route_settings *settings = trade_route_settings_by_type(type);

         if (settings->cancelling == TRI_ACTIVE) {
           can_trade = TRUE;
         }
      } 

      if (can_trade) {
        pcity->trade_value[i] =
          trade_between_cities(pcity, game_city_by_number(pcity->trade[i]));
        pcity->prod[O_TRADE] += pcity->trade_value[i]
          * (100 + get_city_bonus(pcity, EFT_TRADEROUTE_PCT)) / 100;
      } else {
        pcity->trade_value[i] = 0;
      }
    }
  }
  pcity->prod[O_GOLD] += get_city_tithes_bonus(pcity);

  /* Account for waste.  Note that waste is calculated before tax income is
   * calculated, so if you had "science waste" it would not include taxed
   * science.  However waste is calculated after the bonuses are multiplied
   * on, so shield waste will include shield bonuses. */
  output_type_iterate(o) {
    pcity->waste[o] = city_waste(pcity, o,
				 pcity->prod[o] * pcity->bonus[o] / 100,
                                 NULL);
  } output_type_iterate_end;

  /* Convert trade into science/luxury/gold, and add this on to whatever
   * science/luxury/gold is already there. */
  add_tax_income(city_owner(pcity),
		 pcity->prod[O_TRADE] * pcity->bonus[O_TRADE] / 100
		 - pcity->waste[O_TRADE] - pcity->usage[O_TRADE],
		 pcity->prod);

  /* Add on effect bonuses and waste.  Note that the waste calculation
   * (above) already includes the bonus multiplier. */
  output_type_iterate(o) {
    pcity->prod[o] = pcity->prod[o] * pcity->bonus[o] / 100;
    pcity->prod[o] -= pcity->waste[o];
  } output_type_iterate_end;
}

/**************************************************************************
  Query unhappiness caused by a given unit.
**************************************************************************/
int city_unit_unhappiness(struct unit *punit, int *free_unhappy)
{
  struct city *pcity;
  struct unit_type *ut;
  struct player *plr;
  int happy_cost;

  if (!punit || !free_unhappy) {
    return 0;
  }

  pcity = game_city_by_number(punit->homecity);
  if (pcity == NULL) {
    return 0;
  }

  ut = unit_type_get(punit);
  plr = unit_owner(punit);
  happy_cost = utype_happy_cost(ut, plr);

  if (happy_cost <= 0) {
    return 0;
  }

  fc_assert_ret_val(0 <= *free_unhappy, 0);

  if (!unit_being_aggressive(punit) && !is_field_unit(punit)) {
    return 0;
  }

  happy_cost -= get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL_PER);
  if (happy_cost <= 0) {
    return 0;
  }

  if (*free_unhappy >= happy_cost) {
    *free_unhappy -= happy_cost;
    return 0;
  } else {
    happy_cost -= *free_unhappy;
    *free_unhappy = 0;
  }

  return happy_cost;
}

/**************************************************************************
  Calculate upkeep costs.  This builds the pcity->usage[] array as well
  as setting some happiness values.
**************************************************************************/
static inline void city_support(struct city *pcity)
{
  int free_unhappy, martial_law_each;

  /* Clear all usage values. */
  memset(pcity->usage, 0, O_LAST * sizeof(*pcity->usage));
  pcity->martial_law = 0;
  pcity->unit_happy_upkeep = 0;

  /* Building and unit gold upkeep depends on the setting
   * 'game.info.gold_upkeep_style':
   * GOLD_UPKEEP_CITY: The upkeep for buildings and units is paid by the
   *                   city.
   * GOLD_UPKEEP_MIXED: The upkeep for buildings is paid by the city.
   *                    The upkeep for units is paid by the nation.
   * GOLD_UPKEEP_NATION: The upkeep for buildings and units is paid by the
   *                     nation. */
  fc_assert_msg(gold_upkeep_style_is_valid(game.info.gold_upkeep_style),
                "Invalid gold_upkeep_style %d", game.info.gold_upkeep_style);
  switch (game.info.gold_upkeep_style) {
  case GOLD_UPKEEP_CITY:
    pcity->usage[O_GOLD] += city_total_unit_gold_upkeep(pcity);
    fc__fallthrough; /* No break */
  case GOLD_UPKEEP_MIXED:
    pcity->usage[O_GOLD] += city_total_impr_gold_upkeep(pcity);
    break;
  case GOLD_UPKEEP_NATION:
    /* nothing */
    break;
  }
  /* Food consumption by citizens. */
  pcity->usage[O_FOOD] += game.info.food_cost * city_size_get(pcity);

  /* military units in this city (need _not_ be home city) can make
   * unhappy citizens content */
  martial_law_each = get_city_bonus(pcity, EFT_MARTIAL_LAW_EACH);
  if (martial_law_each > 0) {
    int count = 0;
    int martial_law_max = get_city_bonus(pcity, EFT_MARTIAL_LAW_MAX);

    unit_list_iterate(pcity->tile->units, punit) {
      if ((count < martial_law_max || martial_law_max == 0)
          && is_military_unit(punit)
          && unit_owner(punit) == city_owner(pcity)) {
        count++;
      }
    } unit_list_iterate_end;

    pcity->martial_law = CLIP(0, count * martial_law_each, MAX_CITY_SIZE);
  }

  free_unhappy = get_city_bonus(pcity, EFT_MAKE_CONTENT_MIL);
  unit_list_iterate(pcity->units_supported, punit) {
    pcity->unit_happy_upkeep += city_unit_unhappiness(punit, &free_unhappy);
    output_type_iterate(o) {
      if (O_GOLD != o) {
        /* O_GOLD is handled with "game.info.gold_upkeep_style", see over. */
        pcity->usage[o] += punit->upkeep[o];
      }
    } output_type_iterate_end;
  } unit_list_iterate_end;
}

/**************************************************************************
  Refreshes the internal cached data in the city structure.

  !full_refresh will not update tile_cache[] or bonus[].  These two
  values do not need to be recalculated for AI CMA testing.

  'workers_map' is an boolean array which defines the placement of the
  workers within the city map. It uses the tile index and its size is
  defined by city_map_tiles_from_city(_pcity). See also cm_state_init().

  If 'workers_map' is set, only basic updates are needed.
**************************************************************************/
void city_refresh_from_main_map(struct city *pcity, bool *workers_map)
{
  if (workers_map == NULL) {
    /* do a full refresh */

    /* Calculate the bonus[] array values. */
    set_city_bonuses(pcity);
    /* Calculate the tile_cache[] values. */
    city_tile_cache_update(pcity);
    /* manage settlers, and units */
    city_support(pcity);
  }

  /* Calculate output from citizens (uses city_tile_cache_get_output()). */
  get_worked_tile_output(pcity, pcity->citizen_base, workers_map);
  add_specialist_output(pcity, pcity->citizen_base);

  set_city_production(pcity);
  citizen_base_mood(pcity);
  /* Note that pollution is calculated before unhappy_city_check() makes
   * deductions for disorder; so a city in disorder still causes pollution */
  pcity->pollution = city_pollution(pcity, pcity->prod[O_SHIELD]);

  happy_copy(pcity, FEELING_LUXURY);
  citizen_happy_luxury(pcity);	/* with our new found luxuries */

  happy_copy(pcity, FEELING_EFFECT);
  citizen_content_buildings(pcity);

  happy_copy(pcity, FEELING_NATIONALITY);
  citizen_happiness_nationality(pcity);

  /* Martial law & unrest from units */
  happy_copy(pcity, FEELING_MARTIAL);
  citizen_happy_units(pcity);

  /* Building (including wonder) happiness effects */
  happy_copy(pcity, FEELING_FINAL);
  citizen_happy_wonders(pcity);

  unhappy_city_check(pcity);
  set_surpluses(pcity);
}

/**************************************************************************
  Give corruption/waste generated by city.  otype gives the output type
  (O_SHIELD/O_TRADE).  'total' gives the total output of this type in the
  city.  If non-NULL, 'breakdown' should be an OLOSS_LAST-sized array
  which will be filled in with a breakdown of the kinds of waste
  (not cumulative).
**************************************************************************/
int city_waste(const struct city *pcity, Output_type_id otype, int total,
               int *breakdown)
{
  int penalty_waste = 0;
  int penalty_size = 0;  /* separate notradesize/fulltradesize from normal
                          * corruption */
  int total_eft = total; /* normal corruption calculated on total reduced by
                          * possible size penalty */
  int waste_level = get_city_output_bonus(pcity, get_output_type(otype),
                                          EFT_OUTPUT_WASTE);
  bool waste_all = FALSE;

  if (otype == O_TRADE) {
    /* FIXME: special case for trade: it is affected by notradesize and
     * fulltradesize server settings.
     *
     * If notradesize and fulltradesize are equal then the city gets no
     * trade at that size. */
    int notradesize = MIN(game.info.notradesize, game.info.fulltradesize);
    int fulltradesize = MAX(game.info.notradesize, game.info.fulltradesize);

    if (city_size_get(pcity) <= notradesize) {
      penalty_size = total_eft; /* Then no trade income. */
    } else if (city_size_get(pcity) >= fulltradesize) {
      penalty_size = 0;
     } else {
      penalty_size = total_eft * (fulltradesize - city_size_get(pcity))
                     / (fulltradesize - notradesize);
    }
  }

  /* Apply corruption only to anything left after tradesize */
  total_eft -= penalty_size;

  /* Distance-based waste.
   * Don't bother calculating if there's nothing left to lose. */
  if (total_eft > 0) {
    int waste_by_dist = get_city_output_bonus(pcity, get_output_type(otype),
                                              EFT_OUTPUT_WASTE_BY_DISTANCE);
    if (waste_by_dist > 0) {
      const struct city *gov_center = NULL;
      int min_dist = FC_INFINITY;

      /* Check the special case that city itself is gov center
       * before expensive iteration through all cities. */
      if (is_gov_center(pcity)) {
        gov_center = pcity;
        min_dist = 0;
      } else {
        city_list_iterate(city_owner(pcity)->cities, gc) {
          /* Do not recheck current city */
          if (gc != pcity && is_gov_center(gc)) {
            int dist = real_map_distance(gc->tile, pcity->tile);

            if (dist < min_dist) {
              gov_center = gc;
              min_dist = dist;
            }
          }
        } city_list_iterate_end;
      }

      if (gov_center == NULL) {
        waste_all = TRUE; /* no gov center - no income */
      } else {
        waste_level += waste_by_dist * min_dist;
      }
    }
  }

  if (waste_all) {
    penalty_waste = total_eft;
  } else {
    int waste_pct = get_city_output_bonus(pcity, get_output_type(otype),
                                          EFT_OUTPUT_WASTE_PCT);

    /* corruption/waste calculated only for the actually produced amount */
    if (waste_level > 0) {
      penalty_waste = total_eft * waste_level / 100;
    }

    /* bonus calculated only for the actually produced amount */
    penalty_waste -= penalty_waste * waste_pct / 100;

    /* Clip */
    penalty_waste = MIN(MAX(penalty_waste, 0), total_eft);
  }

  if (breakdown) {
    breakdown[OLOSS_WASTE] = penalty_waste;
    breakdown[OLOSS_SIZE]  = penalty_size;
  }

  /* add up total penalty */
  return penalty_waste + penalty_size;
}

/**************************************************************************
  Give the number of specialists in a city.
**************************************************************************/
citizens city_specialists(const struct city *pcity)
{
  citizens count = 0;

  specialist_type_iterate(sp) {
    fc_assert_ret_val(MAX_CITY_SIZE - count > pcity->specialists[sp], 0);
    count += pcity->specialists[sp];
  } specialist_type_iterate_end;

  return count;
}

/****************************************************************************
  Return the "best" specialist available in the game.  This specialist will
  have the most of the given type of output.  If pcity is given then only
  specialists usable by pcity will be considered.
****************************************************************************/
Specialist_type_id best_specialist(Output_type_id otype,
				   const struct city *pcity)
{
  int best = DEFAULT_SPECIALIST;
  int val = get_specialist_output(pcity, best, otype);

  specialist_type_iterate(i) {
    if (!pcity || city_can_use_specialist(pcity, i)) {
      int val2 = get_specialist_output(pcity, i, otype);

      if (val2 > val) {
	best = i;
	val = val2;
      }
    }
  } specialist_type_iterate_end;

  return best;
}

/**************************************************************************
 Adds an improvement (and its effects) to a city.
**************************************************************************/
void city_add_improvement(struct city *pcity,
			  const struct impr_type *pimprove)
{
  pcity->built[improvement_index(pimprove)].turn = game.info.turn; /*I_ACTIVE*/

  if (is_server() && is_wonder(pimprove)) {
    /* Client just read the info from the packets. */
    wonder_built(pcity, pimprove);
  }
}

/**************************************************************************
 Removes an improvement (and its effects) from a city.
**************************************************************************/
void city_remove_improvement(struct city *pcity,
			     const struct impr_type *pimprove)
{
  log_debug("Improvement %s removed from city %s",
            improvement_rule_name(pimprove), pcity->name);
  
  pcity->built[improvement_index(pimprove)].turn = I_DESTROYED;

  if (is_server() && is_wonder(pimprove)) {
    /* Client just read the info from the packets. */
    wonder_destroyed(pcity, pimprove);
  }
}

/**************************************************************************
 Returns TRUE iff the city has set the given option.
**************************************************************************/
bool is_city_option_set(const struct city *pcity, enum city_options option)
{
  return BV_ISSET(pcity->city_options, option);
}

/**************************************************************************
 Allocate memory for this amount of city styles.
**************************************************************************/
void city_styles_alloc(int num)
{
  int i;

  city_styles = fc_calloc(num, sizeof(*city_styles));
  game.control.styles_count = num;

  for (i = 0; i < game.control.styles_count; i++) {
    requirement_vector_init(&city_styles[i].reqs);
  }
}

/**************************************************************************
 De-allocate the memory used by the city styles.
**************************************************************************/
void city_styles_free(void)
{
  int i;

  for (i = 0; i < game.control.styles_count; i++) {
    requirement_vector_free(&city_styles[i].reqs);
  }

  free(city_styles);
  city_styles = NULL;
  game.control.styles_count = 0;
}

/**************************************************************************
  Create virtual skeleton for a city.
  Values are mostly sane defaults.

  Always tile_set_owner(ptile, pplayer) sometime after this!
**************************************************************************/
struct city *create_city_virtual(struct player *pplayer,
                                 struct tile *ptile, const char *name)
{
  int i;

  /* Make sure that contents of city structure are correctly initialized,
   * if you ever allocate it by some other mean than fc_calloc() */
  struct city *pcity = fc_calloc(1, sizeof(*pcity));

  fc_assert_ret_val(NULL != name, NULL);        /* No unnamed cities! */
  sz_strlcpy(pcity->name, name);

  pcity->tile = ptile;
  fc_assert_ret_val(NULL != pplayer, NULL);     /* No unowned cities! */
  pcity->owner = pplayer;
  pcity->original = pplayer;

  /* City structure was allocated with fc_calloc(), so contents are initially
   * zero. There is no need to initialize it a second time. */

  /* Now set some usefull default values. */
  city_size_set(pcity, 1);
  pcity->specialists[DEFAULT_SPECIALIST] = 1;

  output_type_iterate(o) {
    pcity->bonus[o] = 100;
  } output_type_iterate_end;

  pcity->turn_plague = -1; /* -1 = never */
  pcity->did_buy = FALSE;
  pcity->city_radius_sq = game.info.init_city_radius_sq;
  pcity->turn_founded = game.info.turn;
  pcity->turn_last_built = game.info.turn;

  pcity->tile_cache_radius_sq = -1; /* -1 = tile_cache must be initialised */

  /* pcity->ai.act_cache: worker activities on the city map */

  /* Initialise improvements list */
  for (i = 0; i < ARRAY_SIZE(pcity->built); i++) {
    pcity->built[i].turn = I_NEVER;
  }

  /* Set up the worklist */
  worklist_init(&pcity->worklist);

  pcity->units_supported = unit_list_new();
  pcity->task_reqs = worker_task_list_new();

  if (is_server()) {
    pcity->server.mgr_score_calc_turn = -1; /* -1 = never */

    CALL_FUNC_EACH_AI(city_alloc, pcity);
  } else {
    pcity->client.info_units_supported =
        unit_list_new_full(unit_virtual_destroy);
    pcity->client.info_units_present =
        unit_list_new_full(unit_virtual_destroy);
    /* collecting_info_units_supported set by fc_calloc().
     * collecting_info_units_present set by fc_calloc(). */
  }

  return pcity;
}

/**************************************************************************
  Removes the virtual skeleton of a city. You should already have removed
  all buildings and units you have added to the city before this.
**************************************************************************/
void destroy_city_virtual(struct city *pcity)
{
  CALL_FUNC_EACH_AI(city_free, pcity);

  citizens_free(pcity);

  while (worker_task_list_size(pcity->task_reqs) > 0) {
    struct worker_task *ptask = worker_task_list_get(pcity->task_reqs, 0);

    worker_task_list_remove(pcity->task_reqs, ptask);

    free(ptask);
  }
  worker_task_list_destroy(pcity->task_reqs);

  unit_list_destroy(pcity->units_supported);
  if (pcity->tile_cache != NULL) {
    free(pcity->tile_cache);
  }

  if (!is_server()) {
    unit_list_destroy(pcity->client.info_units_supported);
    unit_list_destroy(pcity->client.info_units_present);
    /* Handle a rare case where the game is freed in the middle of a
     * spy/diplomat investigate cycle. */
    if (pcity->client.collecting_info_units_supported != NULL) {
      unit_list_destroy(pcity->client.collecting_info_units_supported);
    }
    if (pcity->client.collecting_info_units_present != NULL) {
      unit_list_destroy(pcity->client.collecting_info_units_present);
    }
  }

  memset(pcity, 0, sizeof(*pcity)); /* ensure no pointers remain */
  free(pcity);
}

/**************************************************************************
  Check if city with given id still exist. Use this before using
  old city pointers when city might have disappeared.
**************************************************************************/
bool city_exist(int id)
{
  /* Check if city exist in game */
  if (game_city_by_number(id)) {
    return TRUE;
  }

  return FALSE;
}

/**************************************************************************
  Return TRUE if the city is a virtual city. That is, it is a valid city
  pointer but does not correspond to a city that exists in the game.

  NB: A return value of FALSE implies that either the pointer is NULL or
  that the city exists in the game.
**************************************************************************/
bool city_is_virtual(const struct city *pcity)
{
  if (!pcity) {
    return FALSE;
  }

  return pcity != game_city_by_number(pcity->id);
}

/**************************************************************************
  Return TRUE if the city is centered at the given tile.

  NB: This doesn't simply check whether pcity->tile == ptile because that
  would miss virtual clones made of city center tiles, which are used by
  autosettler to judge whether improvements are worthwhile.  The upshot is
  that city centers would appear to lose their irrigation/farmland bonuses
  as well as their minimum outputs of one food and one shield, and thus
  autosettler would rarely transform or mine them.
**************************************************************************/
bool is_city_center(const struct city *pcity, const struct tile *ptile)
{
  if (!pcity || !pcity->tile || !ptile) {
    return FALSE;
  }

  return tile_index(city_tile(pcity)) == tile_index(ptile);
}

/**************************************************************************
  Return TRUE if the city is worked without using up a citizen.
**************************************************************************/
bool is_free_worked(const struct city *pcity, const struct tile *ptile)
{
  return is_city_center(pcity, ptile);
}

/**************************************************************************
  Return pointer to ai data of given city and ai type.
**************************************************************************/
void *city_ai_data(const struct city *pcity, const struct ai_type *ai)
{
  return pcity->server.ais[ai_type_number(ai)];
}

/**************************************************************************
  Attach ai data to city
**************************************************************************/
void city_set_ai_data(struct city *pcity, const struct ai_type *ai,
                      void *data)
{
  pcity->server.ais[ai_type_number(ai)] = data;
}